[clang] [Clang] Only compare template params of potential overload after checking their decl context (PR #78139)

2024-01-16 Thread via cfe-commits


@@ -0,0 +1,28 @@
+// From https://github.com/llvm/llvm-project/issues/77953
+// RUN: rm -rf %t
+// RUN: mkdir -p %t
+// RUN: split-file %s %t
+
+// RUN: %clang_cc1 -std=c++20 -emit-module-interface %t/a.cppm -o %t/a.pcm
+// RUN: %clang_cc1 -std=c++20 -fmodule-file=a=%t/a.pcm %t/b.cppm

cor3ntin wrote:

Good catch, thanks!

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


[clang] [llvm] AMDGPU/GFX12: Add new dot4 fp8/bf8 instructions (PR #77892)

2024-01-16 Thread Mariusz Sikora via cfe-commits

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

>From 628a3d2b42cdcbd903e0830ab7d631ea7dc422b9 Mon Sep 17 00:00:00 2001
From: Petar Avramovic 
Date: Wed, 10 Jan 2024 12:17:58 +0100
Subject: [PATCH 1/2] AMDGPU/GFX12: Add new dot4 fp8/bf8 instructions

Endoding is VOP3P. Tagged as deep/machine learning instructions.
i32 type (v4fp8 or v4bf8 packed in i32) is used for src0 and src1.
src0 and src1 have no src_modifiers. src2 is f32 and has src_modifiers:
f32 fneg(neg_lo[2]) and f32 fabs(neg_hi[2]).
---
 clang/include/clang/Basic/BuiltinsAMDGPU.def  |   4 +
 .../builtins-amdgcn-dl-insts-err.cl   |   5 +
 .../builtins-amdgcn-dl-insts-gfx12.cl |  20 ++
 llvm/include/llvm/IR/IntrinsicsAMDGPU.td  |  19 ++
 .../Target/AMDGPU/AMDGPURegisterBankInfo.cpp  |   4 +
 .../AMDGPU/AsmParser/AMDGPUAsmParser.cpp  |  46 
 .../AMDGPU/MCTargetDesc/AMDGPUInstPrinter.cpp |  17 +-
 llvm/lib/Target/AMDGPU/VOP3PInstructions.td   |  47 
 llvm/lib/Target/AMDGPU/VOPInstructions.td |  13 +-
 .../CodeGen/AMDGPU/llvm.amdgcn.fdot4.f32.ll   | 255 ++
 llvm/test/MC/AMDGPU/gfx12_asm_vop3p.s | 120 +
 llvm/test/MC/AMDGPU/gfx12_asm_vop3p_dpp16.s   |  24 ++
 .../MC/AMDGPU/gfx12_asm_vop3p_dpp16_err.s |  24 ++
 llvm/test/MC/AMDGPU/gfx12_asm_vop3p_dpp8.s|  24 ++
 .../test/MC/AMDGPU/gfx12_asm_vop3p_dpp8_err.s |  27 ++
 llvm/test/MC/AMDGPU/gfx12_asm_vop3p_err.s | 133 +
 .../Disassembler/AMDGPU/gfx12_dasm_vop3p.txt  | 120 +
 .../AMDGPU/gfx12_dasm_vop3p_dpp16.txt |  24 ++
 .../AMDGPU/gfx12_dasm_vop3p_dpp8.txt  |  24 ++
 19 files changed, 938 insertions(+), 12 deletions(-)
 create mode 100644 clang/test/CodeGenOpenCL/builtins-amdgcn-dl-insts-gfx12.cl
 create mode 100644 llvm/test/CodeGen/AMDGPU/llvm.amdgcn.fdot4.f32.ll
 create mode 100644 llvm/test/MC/AMDGPU/gfx12_asm_vop3p_dpp16_err.s
 create mode 100644 llvm/test/MC/AMDGPU/gfx12_asm_vop3p_dpp8_err.s
 create mode 100644 llvm/test/MC/AMDGPU/gfx12_asm_vop3p_err.s

diff --git a/clang/include/clang/Basic/BuiltinsAMDGPU.def 
b/clang/include/clang/Basic/BuiltinsAMDGPU.def
index e562ef04a30194..1c1b9b2c9e9e8c 100644
--- a/clang/include/clang/Basic/BuiltinsAMDGPU.def
+++ b/clang/include/clang/Basic/BuiltinsAMDGPU.def
@@ -255,6 +255,10 @@ TARGET_BUILTIN(__builtin_amdgcn_sudot4, "iIbiIbiiIb", 
"nc", "dot8-insts")
 TARGET_BUILTIN(__builtin_amdgcn_sdot8, "SiSiSiSiIb", "nc", "dot1-insts")
 TARGET_BUILTIN(__builtin_amdgcn_udot8, "UiUiUiUiIb", "nc", "dot7-insts")
 TARGET_BUILTIN(__builtin_amdgcn_sudot8, "iIbiIbiiIb", "nc", "dot8-insts")
+TARGET_BUILTIN(__builtin_amdgcn_fdot4_f32_fp8_bf8, "fUiUif", "nc", 
"gfx12-insts")
+TARGET_BUILTIN(__builtin_amdgcn_fdot4_f32_bf8_fp8, "fUiUif", "nc", 
"gfx12-insts")
+TARGET_BUILTIN(__builtin_amdgcn_fdot4_f32_fp8_fp8, "fUiUif", "nc", 
"gfx12-insts")
+TARGET_BUILTIN(__builtin_amdgcn_fdot4_f32_bf8_bf8, "fUiUif", "nc", 
"gfx12-insts")
 
 
//===--===//
 // GFX10+ only builtins.
diff --git a/clang/test/CodeGenOpenCL/builtins-amdgcn-dl-insts-err.cl 
b/clang/test/CodeGenOpenCL/builtins-amdgcn-dl-insts-err.cl
index 6573325150d958..1be47f71276208 100644
--- a/clang/test/CodeGenOpenCL/builtins-amdgcn-dl-insts-err.cl
+++ b/clang/test/CodeGenOpenCL/builtins-amdgcn-dl-insts-err.cl
@@ -49,4 +49,9 @@ kernel void builtins_amdgcn_dl_insts_err(
 
   iOut[3] = __builtin_amdgcn_sudot8(false, A, true, B, C, false);// 
expected-error {{'__builtin_amdgcn_sudot8' needs target feature dot8-insts}}
   iOut[4] = __builtin_amdgcn_sudot8(true, A, false, B, C, true); // 
expected-error {{'__builtin_amdgcn_sudot8' needs target feature dot8-insts}}
+
+  fOut[5] = __builtin_amdgcn_fdot4_f32_fp8_bf8(uiA, uiB, fC);// 
expected-error {{'__builtin_amdgcn_fdot4_f32_fp8_bf8' needs target feature 
gfx12-insts}}
+  fOut[6] = __builtin_amdgcn_fdot4_f32_bf8_fp8(uiA, uiB, fC);// 
expected-error {{'__builtin_amdgcn_fdot4_f32_bf8_fp8' needs target feature 
gfx12-insts}}
+  fOut[7] = __builtin_amdgcn_fdot4_f32_fp8_fp8(uiA, uiB, fC);// 
expected-error {{'__builtin_amdgcn_fdot4_f32_fp8_fp8' needs target feature 
gfx12-insts}}
+  fOut[8] = __builtin_amdgcn_fdot4_f32_bf8_bf8(uiA, uiB, fC);// 
expected-error {{'__builtin_amdgcn_fdot4_f32_bf8_bf8' needs target feature 
gfx12-insts}}
 }
diff --git a/clang/test/CodeGenOpenCL/builtins-amdgcn-dl-insts-gfx12.cl 
b/clang/test/CodeGenOpenCL/builtins-amdgcn-dl-insts-gfx12.cl
new file mode 100644
index 00..31e10c0a5dc18c
--- /dev/null
+++ b/clang/test/CodeGenOpenCL/builtins-amdgcn-dl-insts-gfx12.cl
@@ -0,0 +1,20 @@
+// REQUIRES: amdgpu-registered-target
+
+// RUN: %clang_cc1 -triple amdgcn-unknown-unknown -target-cpu gfx1200 -S 
-emit-llvm -o - %s | FileCheck %s
+
+typedef unsigned int uint;
+
+// CHECK-LABEL: @builtins_amdgcn_dl_insts
+// CHECK: call float @llvm.amdgcn.fdot4.f32.fp8.bf8(i32 %uiA, i32 %uiB, float 
%fC)

[clang] [llvm] AMDGPU/GFX12: Add new dot4 fp8/bf8 instructions (PR #77892)

2024-01-16 Thread Mariusz Sikora via cfe-commits


@@ -2696,6 +2696,25 @@ def int_amdgcn_udot8 :
  ImmArg>,  ImmArg>, ImmArg>]
   >;
 
+// f32 %r = llvm.amdgcn.dot4.f32.type_a.type_b (v4type_a (as i32) %a, v4type_b 
(as i32) %b, f32 %c)
+//   %r = %a[0] * %b[0] + %a[1] * %b[1] + %a[2] * %b[2] + %a[3] * %b[3] + %c
+class AMDGPU8bitFloatDot4Intrinsic :
+  ClangBuiltin,
+  DefaultAttrsIntrinsic<
+[llvm_float_ty], // %r
+[
+  llvm_i32_ty,   // %a
+  llvm_i32_ty,   // %b
+  llvm_float_ty, // %c
+],
+[IntrNoMem, IntrSpeculatable]
+  >;
+
+def int_amdgcn_fdot4_f32_fp8_bf8 : AMDGPU8bitFloatDot4Intrinsic;
+def int_amdgcn_fdot4_f32_bf8_fp8 : AMDGPU8bitFloatDot4Intrinsic;

mariusz-sikora-at-amd wrote:

Done, renamed fdot4 to dot4

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


[clang] [clang][Interp] Add inline descriptor to global variables (PR #72892)

2024-01-16 Thread Timm Baeder via cfe-commits
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= 
Message-ID:
In-Reply-To: 


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

>From 7551ede34ec97db3a3ef2284ca93c8279ae66524 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Mon, 20 Nov 2023 11:53:40 +0100
Subject: [PATCH 1/4] [clang][Interp] Add inline descriptor to global variables

---
 clang/lib/AST/Interp/ByteCodeExprGen.cpp | 15 ++-
 clang/lib/AST/Interp/Descriptor.cpp  | 25 +--
 clang/lib/AST/Interp/Descriptor.h|  7 +--
 clang/lib/AST/Interp/Interp.cpp  | 16 +++
 clang/lib/AST/Interp/Interp.h| 26 +---
 clang/lib/AST/Interp/Pointer.cpp |  4 +-
 clang/lib/AST/Interp/Pointer.h   | 30 +
 clang/lib/AST/Interp/Program.cpp | 54 ++--
 clang/test/AST/Interp/cxx17.cpp  | 23 --
 clang/test/AST/Interp/cxx23.cpp  | 24 ---
 clang/test/AST/Interp/literals.cpp   | 17 
 11 files changed, 184 insertions(+), 57 deletions(-)

diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 5839123a5b95f2..057c992c2806c5 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -830,13 +830,26 @@ bool ByteCodeExprGen::VisitInitListExpr(const 
InitListExpr *E) {
 return this->visitInitList(E->inits(), E);
 
   if (T->isArrayType()) {
-// FIXME: Array fillers.
 unsigned ElementIndex = 0;
 for (const Expr *Init : E->inits()) {
   if (!this->visitArrayElemInit(ElementIndex, Init))
 return false;
   ++ElementIndex;
 }
+
+// Expand the filler expression.
+// FIXME: This should go away.
+if (const Expr *Filler = E->getArrayFiller()) {
+  const ConstantArrayType *CAT =
+  Ctx.getASTContext().getAsConstantArrayType(E->getType());
+  uint64_t NumElems = CAT->getSize().getZExtValue();
+
+  for (; ElementIndex != NumElems; ++ElementIndex) {
+if (!this->visitArrayElemInit(ElementIndex, Filler))
+  return false;
+  }
+}
+
 return true;
   }
 
diff --git a/clang/lib/AST/Interp/Descriptor.cpp 
b/clang/lib/AST/Interp/Descriptor.cpp
index b330e54baf335a..5701cf0acf915d 100644
--- a/clang/lib/AST/Interp/Descriptor.cpp
+++ b/clang/lib/AST/Interp/Descriptor.cpp
@@ -243,18 +243,19 @@ Descriptor::Descriptor(const DeclTy &D, PrimType Type, 
MetadataSize MD,
bool IsMutable)
 : Source(D), ElemSize(primSize(Type)), Size(ElemSize * NumElems),
   MDSize(MD.value_or(0)),
-  AllocSize(align(Size) + sizeof(InitMapPtr) + MDSize), IsConst(IsConst),
-  IsMutable(IsMutable), IsTemporary(IsTemporary), IsArray(true),
-  CtorFn(getCtorArrayPrim(Type)), DtorFn(getDtorArrayPrim(Type)),
-  MoveFn(getMoveArrayPrim(Type)) {
+  AllocSize(align(MDSize) + align(Size) + sizeof(InitMapPtr)),
+  IsConst(IsConst), IsMutable(IsMutable), IsTemporary(IsTemporary),
+  IsArray(true), CtorFn(getCtorArrayPrim(Type)),
+  DtorFn(getDtorArrayPrim(Type)), MoveFn(getMoveArrayPrim(Type)) {
   assert(Source && "Missing source");
 }
 
 /// Primitive unknown-size arrays.
-Descriptor::Descriptor(const DeclTy &D, PrimType Type, bool IsTemporary,
-   UnknownSize)
-: Source(D), ElemSize(primSize(Type)), Size(UnknownSizeMark), MDSize(0),
-  AllocSize(alignof(void *) + sizeof(InitMapPtr)), IsConst(true),
+Descriptor::Descriptor(const DeclTy &D, PrimType Type, MetadataSize MD,
+   bool IsTemporary, UnknownSize)
+: Source(D), ElemSize(primSize(Type)), Size(UnknownSizeMark),
+  MDSize(MD.value_or(0)),
+  AllocSize(MDSize + sizeof(InitMapPtr) + alignof(void *)), IsConst(true),
   IsMutable(false), IsTemporary(IsTemporary), IsArray(true),
   CtorFn(getCtorArrayPrim(Type)), DtorFn(getDtorArrayPrim(Type)),
   MoveFn(getMoveArrayPrim(Type)) {
@@ -275,12 +276,12 @@ Descriptor::Descriptor(const DeclTy &D, const Descriptor 
*Elem, MetadataSize MD,
 }
 
 /// Unknown-size arrays of composite elements.
-Descriptor::Descriptor(const DeclTy &D, const Descriptor *Elem,
+Descriptor::Descriptor(const DeclTy &D, const Descriptor *Elem, MetadataSize 
MD,
bool IsTemporary, UnknownSize)
 : Source(D), ElemSize(Elem->getAllocSize() + sizeof(InlineDescriptor)),
-  Size(UnknownSizeMark), MDSize(0),
-  AllocSize(alignof(void *) + sizeof(InitMapPtr)), ElemDesc(Elem),
-  IsConst(true), IsMutable(false), IsTemporary(IsTemporary), IsArray(true),
+  Size(UnknownSizeMark), MDSize(MD.value_or(0)),
+  AllocSize(MDSize + alignof(void *)), ElemDesc(Elem), IsConst(true),
+  IsMutable(false), IsTemporary(IsTemporary), IsArray(true),
   CtorFn(ctorArrayDesc), DtorFn(dtorArrayDesc), MoveFn(moveArrayDesc) {
   assert(Source && "Missing source");
 }
diff --git a/clang/lib/AST/Interp/Descri

[clang] [clang-format] adds a space after not inside macros (PR #78176)

2024-01-16 Thread via cfe-commits

mydeveloperday wrote:

> > I think this is kind of too specific.
> 
> +1.
> 
> > Also I agree with [#78166 
> > (comment)](https://github.com/llvm/llvm-project/issues/78166#issuecomment-1892311219)
> >  that `WhitespaceSensitiveMacros` should be used.
> 
> I don't think we should require that the option be used.

+1 to that too! (even though it works)

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


[clang] [clang-format] adds a space after not inside macros (PR #78176)

2024-01-16 Thread Owen Pan via cfe-commits

owenca wrote:

This should work:
```
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -4402,9 +4402,17 @@ bool TokenAnnotator::spaceRequiredBefore(const 
AnnotatedLine &Line,
   if (Left.Finalized)
 return Right.hasWhitespaceBefore();
 
-  // Never ever merge two words.
-  if (Keywords.isWordLike(Right) && Keywords.isWordLike(Left))
-return true;
+  if (Style.isVerilog()) {
+if (Keywords.isWordLike(Left) && Keywords.isWordLike(Right))
+  return true;
+  } else {
+auto IsWordOrNumber = [](const auto &Tok) {
+  return Tok.Tok.getIdentifierInfo() || Tok.is(tok::numeric_constant);
+};
+// Never ever merge two words/numbers.
+if (IsWordOrNumber(Left) && IsWordOrNumber(Right))
+  return true;
+  }
 
   // Leave a space between * and /* to avoid C4138 `comment end` found outside
   // of comment.
@@ -4842,21 +4850,11 @@ bool TokenAnnotator::spaceRequiredBefore(const 
AnnotatedLine &Line,
 return true;
   }
   if (Left.is(TT_UnaryOperator)) {
-if (Right.isNot(tok::l_paren)) {
-  // The alternative operators for ~ and ! are "compl" and "not".
-  // If they are used instead, we do not want to combine them with
-  // the token to the right, unless that is a left paren.
-  if (Left.is(tok::exclaim) && Left.TokenText == "not")
-return true;
-  if (Left.is(tok::tilde) && Left.TokenText == "compl")
-return true;
-  // Lambda captures allow for a lone &, so "&]" needs to be properly
-  // handled.
-  if (Left.is(tok::amp) && Right.is(tok::r_square))
-return Style.SpacesInSquareBrackets;
-}
-return (Style.SpaceAfterLogicalNot && Left.is(tok::exclaim)) ||
-   Right.is(TT_BinaryOperator);
+// Lambda captures allow for a lone &, so "&]" needs to be properly
+// handled.
+if (Left.is(tok::amp) && Right.is(tok::r_square))
+  return Style.SpacesInSquareBrackets;
+return Style.SpaceAfterLogicalNot && Left.is(tok::exclaim);
   }
 
   // If the next token is a binary operator or a selector name, we have
```

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


[clang] [clang][analyzer] Improve modeling of 'fseeko' and 'ftello' in StdLibraryFunctionsChecker (PR #77902)

2024-01-16 Thread Balázs Kéri via cfe-commits

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


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


[clang-tools-extra] [llvm] [clang] [AMDGPU][GFX12] Add Atomic cond_sub_u32 (PR #76224)

2024-01-16 Thread Matt Arsenault via cfe-commits


@@ -2502,10 +2500,9 @@ def int_amdgcn_flat_atomic_fmax_num   : 
AMDGPUAtomicRtn;
 def int_amdgcn_global_atomic_fmin_num : AMDGPUAtomicRtn;
 def int_amdgcn_global_atomic_fmax_num : AMDGPUAtomicRtn;
 
-def int_amdgcn_flat_atomic_cond_sub_u32 : AMDGPUAtomicRtn;
-def int_amdgcn_global_atomic_cond_sub_u32 : AMDGPUAtomicRtn;
-
-def int_amdgcn_ds_cond_sub_u32 : AMDGPUAtomicRtn;
+def int_amdgcn_flat_atomic_cond_sub_u32   : AMDGPUAtomicRtn;
+def int_amdgcn_global_atomic_cond_sub_u32 : AMDGPUAtomicRtn;
+def int_amdgcn_ds_cond_sub_u32: AMDGPUAtomicRtn;

arsenm wrote:

No, I meant one intrinsic, not 3. When we had atomicrmw inc/dec intrinsics, we 
had one intrinsic per operation overloaded per address space 

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


[flang] [llvm] [clang] [lld] [AMDGPU] Introduce Code Object V6 (PR #76954)

2024-01-16 Thread Pierre van Houtryve via cfe-commits

Pierre-vh wrote:

ping

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


[clang] [clang][Interp] Add an EvaluationResult class (PR #71315)

2024-01-16 Thread Timm Baeder via cfe-commits


@@ -183,11 +178,7 @@ int32_t ByteCodeEmitter::getOffset(LabelTy Label) {
   return 0ull;
 }
 
-bool ByteCodeEmitter::bail(const SourceLocation &Loc) {
-  if (!BailLocation)
-BailLocation = Loc;
-  return false;
-}
+bool ByteCodeEmitter::bail(const SourceLocation &Loc) { return false; }

tbaederr wrote:

Hm, probably. There is _some_ utility to it, i.e. I can set a debugger 
breakpoint on it, but if it just returns false, that doesn't work anyway.

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


[clang] [clang-format] adds a space after not inside macros (PR #78176)

2024-01-16 Thread via cfe-commits

https://github.com/mydeveloperday updated 
https://github.com/llvm/llvm-project/pull/78176

>From 9d29ad06ff71b855a43f57b339990e41f206ac8d Mon Sep 17 00:00:00 2001
From: mydeveloperday 
Date: Mon, 15 Jan 2024 15:42:59 +
Subject: [PATCH 1/2] [clang-format] adds a space after not inside macros

No need to add an extract space if merging the characters
doesn't cause a problem, hence ) and ! as well as ( do not
require the extraneous space.
---
 clang/lib/Format/TokenAnnotator.cpp   | 2 +-
 clang/unittests/Format/FormatTest.cpp | 2 ++
 2 files changed, 3 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 227aa0b97af6ba4..e45271809e80854 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -4842,7 +4842,7 @@ bool TokenAnnotator::spaceRequiredBefore(const 
AnnotatedLine &Line,
 return true;
   }
   if (Left.is(TT_UnaryOperator)) {
-if (Right.isNot(tok::l_paren)) {
+if (!Right.isOneOf(tok::r_paren, tok::l_paren, tok::exclaim)) {
   // The alternative operators for ~ and ! are "compl" and "not".
   // If they are used instead, we do not want to combine them with
   // the token to the right, unless that is a left paren.
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 8f115fb8cbf0fbe..54b8593fb98d424 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -24159,6 +24159,8 @@ TEST_F(FormatTest, AlternativeOperators) {
 
   verifyFormat("int a compl(5);");
   verifyFormat("int a not(5);");
+  verifyFormat("v(not)");
+  verifyFormat("v(not!)");
 
   /* FIXME handle alternate tokens
* https://en.cppreference.com/w/cpp/language/operator_alternative

>From ccea956d6a3ebf619520f1b5097d78bc71f8c065 Mon Sep 17 00:00:00 2001
From: mydeveloperday 
Date: Tue, 16 Jan 2024 08:30:14 +
Subject: [PATCH 2/2] [clang-format] adds a space after not inside macros

No need to add an extract space if merging the characters
doesn't cause a problem, hence ) and ! as well as ( do not
require the extraneous space.
---
 clang/lib/Format/TokenAnnotator.cpp   | 10 +-
 clang/unittests/Format/FormatTest.cpp |  6 ++
 2 files changed, 11 insertions(+), 5 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index e45271809e80854..0eec0195b1c63a9 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -4842,7 +4842,7 @@ bool TokenAnnotator::spaceRequiredBefore(const 
AnnotatedLine &Line,
 return true;
   }
   if (Left.is(TT_UnaryOperator)) {
-if (!Right.isOneOf(tok::r_paren, tok::l_paren, tok::exclaim)) {
+if (Right.isOneOf(tok::identifier, tok::numeric_constant)) {
   // The alternative operators for ~ and ! are "compl" and "not".
   // If they are used instead, we do not want to combine them with
   // the token to the right, unless that is a left paren.
@@ -4850,11 +4850,11 @@ bool TokenAnnotator::spaceRequiredBefore(const 
AnnotatedLine &Line,
 return true;
   if (Left.is(tok::tilde) && Left.TokenText == "compl")
 return true;
-  // Lambda captures allow for a lone &, so "&]" needs to be properly
-  // handled.
-  if (Left.is(tok::amp) && Right.is(tok::r_square))
-return Style.SpacesInSquareBrackets;
 }
+// Lambda captures allow for a lone &, so "&]" needs to be properly
+// handled.
+if (Left.is(tok::amp) && Right.is(tok::r_square))
+  return Style.SpacesInSquareBrackets;
 return (Style.SpaceAfterLogicalNot && Left.is(tok::exclaim)) ||
Right.is(TT_BinaryOperator);
   }
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 54b8593fb98d424..5a540672eca2a39 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -24159,8 +24159,14 @@ TEST_F(FormatTest, AlternativeOperators) {
 
   verifyFormat("int a compl(5);");
   verifyFormat("int a not(5);");
+
   verifyFormat("v(not)");
   verifyFormat("v(not!)");
+  verifyFormat("Symbol(not, None)");
+  verifyFormat("Symbol(not!, None)");
+
+  verifyFormat("assert(!\"fail\")");
+  verifyFormat("assert(not\"fail\")");
 
   /* FIXME handle alternate tokens
* https://en.cppreference.com/w/cpp/language/operator_alternative

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


[clang] Improve modeling of two functions in StdLibraryFunctionsChecker (PR #78079)

2024-01-16 Thread Balázs Kéri via cfe-commits


@@ -248,3 +248,25 @@ void check_fflush_all(void) {
 if (errno) {}// no-warning
   }
 }
+
+void check_opendir(const char *Path) {
+  DIR *Dir = opendir(Path);
+  if (Dir == NULL) {
+clang_analyzer_eval(errno != 0); // expected-warning{{TRUE}}
+if (errno) {}// no-warning
+  } else {
+if (errno) {}// expected-warning{{An undefined value 
may be read from 'errno'}}
+closedir(Dir);
+  }
+}
+
+void check_fdopendir(int Fd) {
+  DIR *Dir = fdopendir(Fd);
+  if (Dir == NULL) {
+clang_analyzer_eval(errno != 0); // expected-warning{{TRUE}}
+if (errno) {}// no-warning
+  } else {
+if (errno) {}// expected-warning{{An undefined value 
may be read from 'errno'}}
+closedir(Dir);
+  }
+}

balazske wrote:

I think for now it is not necessary to add tests for these functions. These 
functions are the same type as all other functions in 
`StdLibraryFunctionsChecker` that have currently no test. And it is 
questionable if these functions belong to stream handling functions or to 
`StreamChecker`.

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


[clang-tools-extra] [NFC][clang-tidy]improve performance for misc-unused-using-decls check (PR #78231)

2024-01-16 Thread Haojian Wu via cfe-commits

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

Thanks, the code looks good. Do you have any performance data after this change?

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


[clang] [clang] Fix CTAD not work for function-type and array-type arguments. (PR #78159)

2024-01-16 Thread Haojian Wu via cfe-commits

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


[clang] [clang] Fix CTAD not work for function-type and array-type arguments. (PR #78159)

2024-01-16 Thread Haojian Wu via cfe-commits

hokein wrote:

> Can you please provide a more detailed summary, since these are usually what 
> goes in the git log. It should describe the cause and the approach of the 
> fix. It is also helpful for reviewers as well.

Done, added details in the description.

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


[clang] f725bb9 - [clang] Fix CTAD not work for function-type and array-type arguments. (#78159)

2024-01-16 Thread via cfe-commits

Author: Haojian Wu
Date: 2024-01-16T09:54:36+01:00
New Revision: f725bb960d45ada3cc4667dd7aa22792d389c7e7

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

LOG: [clang] Fix CTAD not work for function-type and array-type arguments. 
(#78159)

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

When transforming a constructor into a corresponding deduction guide,
the decayed types (function/array type) were not handled properly which
made clang fail to compile valid code. The patch teaches clang handle
these decayed type in the transformation.

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaTemplate.cpp
clang/test/SemaCXX/cxx1z-class-template-argument-deduction.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 174392da17551e..ea57769a4a5795 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -748,6 +748,8 @@ Bug Fixes in This Version
 - Fix an issue where clang cannot find conversion function with template
   parameter when instantiation of template class.
   Fixes (`#77583 `_)
+- Fix an issue where CTAD fails for function-type/array-type arguments.
+  Fixes (`#51710 `_)
 
 Bug Fixes to Compiler Builtins
 ^^

diff  --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 5fcc39ec700522..80a48c268a648b 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -2587,15 +2587,15 @@ struct ConvertConstructorToDeductionGuideTransform {
   : ParamTy->isRValueReferenceType() ? VK_XValue
  : VK_PRValue);
 }
-
-ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
-OldParam->getInnerLocStart(),
-OldParam->getLocation(),
-OldParam->getIdentifier(),
-NewDI->getType(),
-NewDI,
-OldParam->getStorageClass(),
-NewDefArg.get());
+// Handle arrays and functions decay.
+auto NewType = NewDI->getType();
+if (NewType->isArrayType() || NewType->isFunctionType())
+  NewType = SemaRef.Context.getDecayedType(NewType);
+
+ParmVarDecl *NewParam = ParmVarDecl::Create(
+SemaRef.Context, DC, OldParam->getInnerLocStart(),
+OldParam->getLocation(), OldParam->getIdentifier(), NewType, NewDI,
+OldParam->getStorageClass(), NewDefArg.get());
 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
OldParam->getFunctionScopeIndex());
 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam);

diff  --git a/clang/test/SemaCXX/cxx1z-class-template-argument-deduction.cpp 
b/clang/test/SemaCXX/cxx1z-class-template-argument-deduction.cpp
index a490d318f54b58..33ed4295c2e48c 100644
--- a/clang/test/SemaCXX/cxx1z-class-template-argument-deduction.cpp
+++ b/clang/test/SemaCXX/cxx1z-class-template-argument-deduction.cpp
@@ -645,4 +645,37 @@ namespace undefined_warnings {
 auto test2 = TemplDObj(.0f);
   }
 }
+
+namespace GH51710 {
+template
+struct A {
+  A(T f()) {}
+  A(int f(), T) {}
+
+  A(T array[10]) {}
+  A(int array[10], T) {}
+};
+
+template
+struct B {
+   B(T array[]) {}
+   B(int array[], T) {}
+};
+
+
+int foo();
+
+void bar() {
+  A test1(foo);
+  A test2(foo, 1);
+
+  int array[10];
+  A test3(array);
+  A test4(array, 1);
+
+  B test5(array);
+  B test6(array, 1);
+}
+} // namespace GH51710
+
 #endif



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


[clang] [clang] Fix CTAD not work for function-type and array-type arguments. (PR #78159)

2024-01-16 Thread Haojian Wu via cfe-commits

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


[clang] 27d963a - [clang][analyzer] Improve modeling of 'fseeko' and 'ftello' in StdLibraryFunctionsChecker (#77902)

2024-01-16 Thread via cfe-commits

Author: Ben Shi
Date: 2024-01-16T16:58:07+08:00
New Revision: 27d963a7089b050d402dbc1ae210d505f7a6

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

LOG: [clang][analyzer] Improve modeling of 'fseeko' and 'ftello' in 
StdLibraryFunctionsChecker (#77902)

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
clang/test/Analysis/std-c-library-functions-POSIX.c
clang/test/Analysis/stream-errno.c

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
index 3b36565681a7f33..641ebe90f88e2eb 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
@@ -2220,6 +2220,9 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
 0, WithinRange, {{EOFv, EOFv}, {0, UCharRangeMax}}))
 .ArgConstraint(NotNull(ArgNo(1;
 
+std::optional Off_tTy = lookupTy("off_t");
+std::optional Off_tMax = getMaxValue(Off_tTy);
+
 // int fseek(FILE *stream, long offset, int whence);
 // FIXME: It can be possible to get the 'SEEK_' values (like EOFv) and use
 // these for condition of arg 2.
@@ -2232,6 +2235,16 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
 .ArgConstraint(NotNull(ArgNo(0)))
 .ArgConstraint(ArgumentCondition(2, WithinRange, {{0, 2}})));
 
+// int fseeko(FILE *stream, off_t offset, int whence);
+addToFunctionSummaryMap(
+"fseeko",
+Signature(ArgTypes{FilePtrTy, Off_tTy, IntTy}, RetType{IntTy}),
+Summary(NoEvalCall)
+.Case(ReturnsZero, ErrnoMustNotBeChecked, GenericSuccessMsg)
+.Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg)
+.ArgConstraint(NotNull(ArgNo(0)))
+.ArgConstraint(ArgumentCondition(2, WithinRange, {{0, 2}})));
+
 // int fgetpos(FILE *restrict stream, fpos_t *restrict pos);
 // From 'The Open Group Base Specifications Issue 7, 2018 edition':
 // "The fgetpos() function shall not change the setting of errno if
@@ -2279,6 +2292,15 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
 .Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg)
 .ArgConstraint(NotNull(ArgNo(0;
 
+// off_t ftello(FILE *stream);
+addToFunctionSummaryMap(
+"ftello", Signature(ArgTypes{FilePtrTy}, RetType{Off_tTy}),
+Summary(NoEvalCall)
+.Case({ReturnValueCondition(WithinRange, Range(0, Off_tMax))},
+  ErrnoMustNotBeChecked, GenericSuccessMsg)
+.Case(ReturnsMinusOne, ErrnoNEZeroIrrelevant, GenericFailureMsg)
+.ArgConstraint(NotNull(ArgNo(0;
+
 // int fileno(FILE *stream);
 addToFunctionSummaryMap(
 "fileno", Signature(ArgTypes{FilePtrTy}, RetType{IntTy}),
@@ -2410,8 +2432,6 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
 .ArgConstraint(
 ArgumentCondition(0, WithinRange, Range(0, IntMax;
 
-std::optional Off_tTy = lookupTy("off_t");
-
 // int truncate(const char *path, off_t length);
 addToFunctionSummaryMap(
 "truncate",
@@ -2854,19 +2874,6 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
 "rand_r", Signature(ArgTypes{UnsignedIntPtrTy}, RetType{IntTy}),
 Summary(NoEvalCall).ArgConstraint(NotNull(ArgNo(0;
 
-// int fseeko(FILE *stream, off_t offset, int whence);
-addToFunctionSummaryMap(
-"fseeko",
-Signature(ArgTypes{FilePtrTy, Off_tTy, IntTy}, RetType{IntTy}),
-Summary(NoEvalCall)
-.Case(ReturnsZeroOrMinusOne, ErrnoIrrelevant)
-.ArgConstraint(NotNull(ArgNo(0;
-
-// off_t ftello(FILE *stream);
-addToFunctionSummaryMap(
-"ftello", Signature(ArgTypes{FilePtrTy}, RetType{Off_tTy}),
-Summary(NoEvalCall).ArgConstraint(NotNull(ArgNo(0;
-
 // void *mmap(void *addr, size_t length, int prot, int flags, int fd,
 // off_t offset);
 // FIXME: Improve for errno modeling.

diff  --git a/clang/test/Analysis/std-c-library-functions-POSIX.c 
b/clang/test/Analysis/std-c-library-functions-POSIX.c
index daa4d904c3ac5ed..8a26e0b0f27286f 100644
--- a/clang/test/Analysis/std-c-library-functions-POSIX.c
+++ b/clang/test/Analysis/std-c-library-functions-POSIX.c
@@ -21,6 +21,8 @@
 // CHECK: Loaded summary for: FILE *freopen(const char *restrict pathname, 
const char *restrict mode, FILE *restrict stream)
 // CHECK: Loaded summary for: int fclose(FILE *stream)
 // CHECK: Loaded summary for: int fseek(FILE *stream, long offset, int whence)
+// CHECK: Loaded summary for: int fseeko(FIL

[clang] [clang][analyzer] Improve modeling of 'fseeko' and 'ftello' in StdLibraryFunctionsChecker (PR #77902)

2024-01-16 Thread Ben Shi via cfe-commits

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


[clang] Improve modeling of two functions in StdLibraryFunctionsChecker (PR #78079)

2024-01-16 Thread Ben Shi via cfe-commits

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

>From fd350eea466db33324f07e59469775e81479b33d Mon Sep 17 00:00:00 2001
From: Ben Shi 
Date: Sun, 14 Jan 2024 12:44:45 +0800
Subject: [PATCH 1/2] [clang][analyzer] Improve modeling of two functions in
 StdLibraryFunctionsChecker

Improve 'errno' modeling of 'opendir' and 'fdopendir'.
---
 .../Checkers/StdLibraryFunctionsChecker.cpp   | 19 +---
 .../Analysis/Inputs/system-header-simulator.h |  7 +-
 clang/test/Analysis/stream-errno.c| 22 +++
 3 files changed, 39 insertions(+), 9 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
index 3b36565681a7f33..2f05dd6997cfad8 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
@@ -2772,18 +2772,21 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
 .ArgConstraint(NotNull(ArgNo(2;
 
 // DIR *opendir(const char *name);
-// FIXME: Improve for errno modeling.
 addToFunctionSummaryMap(
 "opendir", Signature(ArgTypes{ConstCharPtrTy}, RetType{DirPtrTy}),
-Summary(NoEvalCall).ArgConstraint(NotNull(ArgNo(0;
+Summary(NoEvalCall)
+.Case({NotNull(Ret)}, ErrnoMustNotBeChecked, GenericSuccessMsg)
+.Case({IsNull(Ret)}, ErrnoNEZeroIrrelevant, GenericFailureMsg)
+.ArgConstraint(NotNull(ArgNo(0;
 
 // DIR *fdopendir(int fd);
-// FIXME: Improve for errno modeling.
-addToFunctionSummaryMap("fdopendir",
-Signature(ArgTypes{IntTy}, RetType{DirPtrTy}),
-Summary(NoEvalCall)
-.ArgConstraint(ArgumentCondition(
-0, WithinRange, Range(0, IntMax;
+addToFunctionSummaryMap(
+"fdopendir", Signature(ArgTypes{IntTy}, RetType{DirPtrTy}),
+Summary(NoEvalCall)
+.Case({NotNull(Ret)}, ErrnoMustNotBeChecked, GenericSuccessMsg)
+.Case({IsNull(Ret)}, ErrnoNEZeroIrrelevant, GenericFailureMsg)
+.ArgConstraint(
+ArgumentCondition(0, WithinRange, Range(0, IntMax;
 
 // int isatty(int fildes);
 addToFunctionSummaryMap(
diff --git a/clang/test/Analysis/Inputs/system-header-simulator.h 
b/clang/test/Analysis/Inputs/system-header-simulator.h
index cd7ac616bcc67fa..ba0e09ca77bc2af 100644
--- a/clang/test/Analysis/Inputs/system-header-simulator.h
+++ b/clang/test/Analysis/Inputs/system-header-simulator.h
@@ -14,8 +14,9 @@ typedef long long __int64_t;
 typedef __int64_t __darwin_off_t;
 typedef __darwin_off_t fpos_t;
 typedef int off_t;
-
 typedef struct _FILE FILE;
+typedef struct _DIR DIR;
+
 #define SEEK_SET 0 /* Seek from beginning of file. */
 #define SEEK_CUR 1 /* Seek from current position. */
 #define SEEK_END 2 /* Seek from end of file. */
@@ -68,6 +69,10 @@ int ferror(FILE *stream);
 int fileno(FILE *stream);
 int fflush(FILE *stream);
 
+DIR *opendir(const char *name);
+DIR *fdopendir(int fd);
+int closedir(DIR *dir);
+
 size_t strlen(const char *);
 
 char *strcpy(char *restrict, const char *restrict);
diff --git a/clang/test/Analysis/stream-errno.c 
b/clang/test/Analysis/stream-errno.c
index f44ee6070708b26..f19109a3c0b481f 100644
--- a/clang/test/Analysis/stream-errno.c
+++ b/clang/test/Analysis/stream-errno.c
@@ -248,3 +248,25 @@ void check_fflush_all(void) {
 if (errno) {}// no-warning
   }
 }
+
+void check_opendir(const char *Path) {
+  DIR *Dir = opendir(Path);
+  if (Dir == NULL) {
+clang_analyzer_eval(errno != 0); // expected-warning{{TRUE}}
+if (errno) {}// no-warning
+  } else {
+if (errno) {}// expected-warning{{An undefined value 
may be read from 'errno'}}
+closedir(Dir);
+  }
+}
+
+void check_fdopendir(int Fd) {
+  DIR *Dir = fdopendir(Fd);
+  if (Dir == NULL) {
+clang_analyzer_eval(errno != 0); // expected-warning{{TRUE}}
+if (errno) {}// no-warning
+  } else {
+if (errno) {}// expected-warning{{An undefined value 
may be read from 'errno'}}
+closedir(Dir);
+  }
+}

>From cf410b1d56747d5e292c3bf02c12df19f9aa03c5 Mon Sep 17 00:00:00 2001
From: Ben Shi 
Date: Tue, 16 Jan 2024 17:01:04 +0800
Subject: [PATCH 2/2] [clang][analyzer] Improve modeling of two functions in
 StdLibraryFunctionsChecker

---
 .../Analysis/Inputs/system-header-simulator.h |  7 +-
 clang/test/Analysis/stream-errno.c| 22 ---
 2 files changed, 1 insertion(+), 28 deletions(-)

diff --git a/clang/test/Analysis/Inputs/system-header-simulator.h 
b/clang/test/Analysis/Inputs/system-header-simulator.h
index ba0e09ca77bc2af..cd7ac616bcc67fa 100644
--- a/clang/test/Analysis/Inputs/system-header-simulator.h
+++ b/cl

[clang-tools-extra] [clang] [clang-tidy] Handle C++ structured bindings in `performance-for-range-copy` (PR #77105)

2024-01-16 Thread Clement Courbet via cfe-commits

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


[clang-tools-extra] 8fd32b9 - [clang-tidy] Handle C++ structured bindings in `performance-for-range-copy` (#77105)

2024-01-16 Thread via cfe-commits

Author: Clement Courbet
Date: 2024-01-16T10:03:19+01:00
New Revision: 8fd32b96caf37113dd425cd9d0ff8c839c6a048a

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

LOG: [clang-tidy] Handle C++ structured bindings in 
`performance-for-range-copy` (#77105)

Right now we are not triggering on:

```
for (auto [x, y] : container) {
  // const-only access
}
```

Added: 


Modified: 
clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.cpp
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/test/clang-tidy/checkers/performance/for-range-copy.cpp
clang/lib/Analysis/ExprMutationAnalyzer.cpp
clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.cpp 
b/clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.cpp
index 5bfa6fb0d02d5c..655e480ffa62cb 100644
--- a/clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.cpp
+++ b/clang-tools-extra/clang-tidy/performance/ForRangeCopyCheck.cpp
@@ -97,6 +97,15 @@ bool ForRangeCopyCheck::handleConstValueCopy(const VarDecl 
&LoopVar,
   return true;
 }
 
+static bool isReferenced(const VarDecl &LoopVar, const Stmt &Stmt,
+ ASTContext &Context) {
+  const auto IsLoopVar = varDecl(equalsNode(&LoopVar));
+  return !match(stmt(hasDescendant(declRefExpr(to(valueDecl(anyOf(
+IsLoopVar, bindingDecl(forDecomposition(IsLoopVar,
+Stmt, Context)
+  .empty();
+}
+
 bool ForRangeCopyCheck::handleCopyIsOnlyConstReferenced(
 const VarDecl &LoopVar, const CXXForRangeStmt &ForRange,
 ASTContext &Context) {
@@ -113,9 +122,7 @@ bool ForRangeCopyCheck::handleCopyIsOnlyConstReferenced(
   // compiler warning which can't be suppressed.
   // Since this case is very rare, it is safe to ignore it.
   if (!ExprMutationAnalyzer(*ForRange.getBody(), Context).isMutated(&LoopVar) 
&&
-  !utils::decl_ref_expr::allDeclRefExprs(LoopVar, *ForRange.getBody(),
- Context)
-   .empty()) {
+  isReferenced(LoopVar, *ForRange.getBody(), Context)) {
 auto Diag = diag(
 LoopVar.getLocation(),
 "loop variable is copied but only used as const reference; consider "

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index a235a7d02592e8..84c1e906985737 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -447,6 +447,10 @@ Changes in existing checks
   ` check to properly escape
   single quotes.
 
+- Improved :doc:`performance-for-range-copy
+  ` check to handle cases where
+  the loop variable is a structured binding.
+
 - Improved :doc:`performance-noexcept-move-constructor
   ` to better handle
   conditional ``noexcept`` expressions, eliminating false-positives.

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/performance/for-range-copy.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/performance/for-range-copy.cpp
index 1a2eedc9e65c53..f9d06898ca03de 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/performance/for-range-copy.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/performance/for-range-copy.cpp
@@ -47,6 +47,11 @@ struct S {
   S &operator=(const S &);
 };
 
+struct Point {
+  ~Point() {}
+  int x, y;
+};
+
 struct Convertible {
   operator S() const {
 return S();
@@ -87,6 +92,10 @@ void instantiated() {
   // CHECK-MESSAGES: [[@LINE-1]]:16: warning: the loop variable's type is 
{{.*}}
   // CHECK-FIXES: {{^}}  for (const S& S2 : View>()) {}
 
+  for (const auto [X, Y] : View>()) {}
+  // CHECK-MESSAGES: [[@LINE-1]]:19: warning: the loop variable's type is
+  // CHECK-FIXES: {{^}}  for (const auto& [X, Y] : View>()) {}
+
   for (const T T2 : View>()) {}
   // CHECK-MESSAGES: [[@LINE-1]]:16: warning: the loop variable's type is 
{{.*}}
   // CHECK-FIXES: {{^}}  for (const T& T2 : View>()) {}
@@ -123,11 +132,6 @@ struct Mutable {
   ~Mutable() {}
 };
 
-struct Point {
-  ~Point() {}
-  int x, y;
-};
-
 Mutable& operator<<(Mutable &Out, bool B) {
   Out.setBool(B);
   return Out;
@@ -144,6 +148,7 @@ void useByValue(Mutable M);
 void useByConstValue(const Mutable M);
 void mutate(Mutable *M);
 void mutate(Mutable &M);
+void mutate(int &);
 void onceConstOnceMutated(const Mutable &M1, Mutable &M2);
 
 void negativeVariableIsMutated() {
@@ -234,6 +239,22 @@ void positiveOnlyAccessedFieldAsConst() {
   }
 }
 
+void positiveOnlyUsedAsConstBinding() {
+  for (auto [X, Y] : View>()) {
+// CHECK-MESSAGES: [[@LINE-1]]:13: warning: loop variable is copied but
+// CHECK-FIXES: for (const auto& [X, Y] : View>()) {
+use(X);
+use(Y);
+  }
+}
+
+void negativeMutatedBinding() {
+  

[clang] Improve modeling of two functions in StdLibraryFunctionsChecker (PR #78079)

2024-01-16 Thread Ben Shi via cfe-commits


@@ -248,3 +248,25 @@ void check_fflush_all(void) {
 if (errno) {}// no-warning
   }
 }
+
+void check_opendir(const char *Path) {
+  DIR *Dir = opendir(Path);
+  if (Dir == NULL) {
+clang_analyzer_eval(errno != 0); // expected-warning{{TRUE}}
+if (errno) {}// no-warning
+  } else {
+if (errno) {}// expected-warning{{An undefined value 
may be read from 'errno'}}
+closedir(Dir);
+  }
+}
+
+void check_fdopendir(int Fd) {
+  DIR *Dir = fdopendir(Fd);
+  if (Dir == NULL) {
+clang_analyzer_eval(errno != 0); // expected-warning{{TRUE}}
+if (errno) {}// no-warning
+  } else {
+if (errno) {}// expected-warning{{An undefined value 
may be read from 'errno'}}
+closedir(Dir);
+  }
+}

benshi001 wrote:

I have removed those tests. Do you mean all type `DIR` related functions are 
controversial now, so they need tests? Or there are some more functions are so?

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


[clang] Improve modeling of two functions in StdLibraryFunctionsChecker (PR #78079)

2024-01-16 Thread Ben Shi via cfe-commits

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


[clang] Improve modeling of two functions in StdLibraryFunctionsChecker (PR #78079)

2024-01-16 Thread Ben Shi via cfe-commits

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


[clang] [clang] emit an error when the same identifier appears with both internal and external linkage in a translation unit (PR #78064)

2024-01-16 Thread Mariya Podchishchaeva via cfe-commits

Fznamznon wrote:

> @Fznamznon So should I update the test files manually?

Yes, AFAIK there is no script to update the tests. Make sure the new errors 
seen in the tests are expected outcome of the patch though.

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


[llvm] [clang] [AMDGPU] Add global_load_tr for GFX12 (PR #77772)

2024-01-16 Thread Matt Arsenault via cfe-commits


@@ -18178,6 +18178,51 @@ Value *CodeGenFunction::EmitAMDGPUBuiltinExpr(unsigned 
BuiltinID,
 llvm::Function *F = CGM.getIntrinsic(IID, {ArgTy});
 return Builder.CreateCall(F, {Addr, Val, ZeroI32, ZeroI32, ZeroI1});
   }
+  case AMDGPU::BI__builtin_amdgcn_global_load_tr_b64_v2i32:
+  case AMDGPU::BI__builtin_amdgcn_global_load_tr_b64_i32:
+  case AMDGPU::BI__builtin_amdgcn_global_load_tr_b128_v8i16:
+  case AMDGPU::BI__builtin_amdgcn_global_load_tr_b128_v8f16:
+  case AMDGPU::BI__builtin_amdgcn_global_load_tr_b128_v4i16:
+  case AMDGPU::BI__builtin_amdgcn_global_load_tr_b128_v4f16: {
+
+Intrinsic::ID IID;
+llvm::Type *ArgTy;
+switch (BuiltinID) {
+case AMDGPU::BI__builtin_amdgcn_global_load_tr_b64_v2i32:
+  ArgTy = llvm::FixedVectorType::get(
+  llvm::Type::getInt32Ty(getLLVMContext()), 2);
+  IID = Intrinsic::amdgcn_global_load_tr_b64;

arsenm wrote:

I also meant to remove the _global part and have an address space mangled 
pointer operand 

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


[clang] [clang] Fix direct-initialization with new expressions for arrays (PR #78201)

2024-01-16 Thread Mital Ashok via cfe-commits

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


[clang-tools-extra] Add clang-tidy check to suggest replacement of conditional statement with std::min/std::max (PR #77816)

2024-01-16 Thread Bhuminjay Soni via cfe-commits


@@ -0,0 +1,121 @@
+// RUN: %check_clang_tidy %s readability-use-std-min-max %t
+
+constexpr int myConstexprMin(int a, int b) {
+  return a < b ? a : b;
+}
+
+constexpr int myConstexprMax(int a, int b) {
+  return a > b ? a : b;
+}
+
+int bar(int x, int y) {
+  return x < y ? x : y;
+}
+
+class MyClass {
+public:
+  int member1;
+  int member2;
+};
+
+void foo() {
+  int value1,value2,value3;
+  short value4;
+  MyClass obj;
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::max` instead of `<` 
[readability-use-std-min-max]
+  if (value1 < value2)
+value1 = value2; // CHECK-FIXES: value1 = std::max(value1, value2);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::min` instead of `<` 
[readability-use-std-min-max]
+  if (value1 < value2)
+value2 = value1; // CHECK-FIXES: value2 = std::min(value1, value2);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::min` instead of `>` 
[readability-use-std-min-max]
+  if (value2 > value1)
+value2 = value1; // CHECK-FIXES: value2 = std::min(value2, value1);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::max` instead of `>` 
[readability-use-std-min-max
+  if (value2 > value1)
+value1 = value2; // CHECK-FIXES: value1 = std::max(value2, value1);
+
+  // No suggestion needed here
+  if (value1 == value2)
+value1 = value2;
+  
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::max` instead of `<` 
[readability-use-std-min-max]
+  if(value1` 
[readability-use-std-min-max]
+  if (value1 > myConstexprMax(value2, value3))
+value1 = myConstexprMax(value2, value3); // CHECK-FIXES: value1 = 
std::min(value1, myConstexprMax(value2, value3));
+  
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::max` instead of `<` 
[readability-use-std-min-max]
+  if (value1 < bar(value2, value3))
+value1 = bar(value2, value3); // CHECK-FIXES: value1 = std::max(value1, 
bar(value2, value3));
+  
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::min` instead of `<=` 
[readability-use-std-min-max]
+  if (value1 <= value2)
+value2 = value1; // CHECK-FIXES: value2 = std::min(value1, value2);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::max` instead of `<=` 
[readability-use-std-min-max]
+  if (value1 <= value2)
+value1 = value2; // CHECK-FIXES: value1 = std::max(value1, value2);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::max` instead of `>=` 
[readability-use-std-min-max]
+  if (value2 >= value1)
+value1 = value2; // CHECK-FIXES: value1 = std::max(value2, value1);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::min` instead of `>=` 
[readability-use-std-min-max]
+  if (value2 >= value1)
+value2 = value1; // CHECK-FIXES: value2 = std::min(value2, value1);
+  
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::max` instead of `<` 
[readability-use-std-min-max]
+  if (obj.member1 < obj.member2)
+obj.member1 = obj.member2; // CHECK-FIXES: obj.member1 = 
std::max(obj.member1, obj.member2);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::min` instead of `<` 
[readability-use-std-min-max]
+  if (obj.member1 < obj.member2)
+obj.member2 = obj.member1; // CHECK-FIXES: obj.member2 = 
std::min(obj.member1, obj.member2);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::min` instead of `>` 
[readability-use-std-min-max]
+  if (obj.member2 > obj.member1)
+obj.member2 = obj.member1; // CHECK-FIXES: obj.member2 = 
std::min(obj.member2, obj.member1);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::max` instead of `>` 
[readability-use-std-min-max]
+  if (obj.member2 > obj.member1)
+obj.member1 = obj.member2; // CHECK-FIXES: obj.member1 = 
std::max(obj.member2, obj.member1);
+  
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::max` instead of `<` 
[readability-use-std-min-max]
+  if (obj.member1 < value4)
+obj.member1 = value4; // CHECK-FIXES: obj.member1 = std::max(obj.member1, 
value4);
+  
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::min` instead of `<` 
[readability-use-std-min-max]
+  if (obj.member1 + value2 < value3)
+value3 = obj.member1 + value2; // CHECK-FIXES: value3 = 
std::min(obj.member1 + value2, value3);
+  
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::min` instead of `<=` 
[readability-use-std-min-max]
+  if (value1 <= obj.member2)
+obj.member2 = value1; // CHECK-FIXES: obj.member2 = std::min(value1, 
obj.member2);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::max` instead of `<=` 
[readability-use-std-min-max]
+  if (value1 <= obj.member2)
+value1 = obj.member2; // CHECK-FIXES: value1 = std::max(value1, 
obj.member2);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::max` instead of `>=` 
[readability-use-std-min-max]
+  if (obj.member2 >= value1)
+value1 = obj.member2; // CHECK-FIXES: value1 = std::max(obj.member2, 
value1);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::min` instead of `>=` 
[readability

[clang] [clang] Fix direct-initialization with new expressions for arrays (PR #78201)

2024-01-16 Thread Mital Ashok via cfe-commits

MitalAshok wrote:

Yeah #76976 supersedes this.

I would still recommend removing `diag::err_new_array_init_args` if only so:

```c++
int x[2](1, 2);
int* y = new int[2](1, 2);
```

have similar error messages.

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


[clang] [clang] Fix direct-initialization with new expressions for arrays (PR #78201)

2024-01-16 Thread Mital Ashok via cfe-commits

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


[libunwind] [libunwind][WebAssembly] Omit unused parts of libunwind.cpp for Wasm (PR #73196)

2024-01-16 Thread Kazushi Marukawa via cfe-commits


@@ -26,7 +26,7 @@
 #include 
 #endif
 
-#if !defined(__USING_SJLJ_EXCEPTIONS__)
+#if !defined(__USING_SJLJ_EXCEPTIONS__) || !defined(__USING_WASM_EXCEPTIONS__)

kaz7 wrote:

Thanks a lot!!

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


[clang-tools-extra] Add clang-tidy check to suggest replacement of conditional statement with std::min/std::max (PR #77816)

2024-01-16 Thread Bhuminjay Soni via cfe-commits

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


[clang-tools-extra] [llvm] [clang] [AMDGPU][GFX12] Add 16 bit atomic fadd instructions (PR #75917)

2024-01-16 Thread Mariusz Sikora via cfe-commits


@@ -27,34 +27,23 @@ main_body:
   ret float %out0
 }
 
-define amdgpu_ps float @atomic_pk_add_bf16_1d_v2(<8 x i32> inreg %rsrc, <2 x 
i16> %data, i32 %s) {
+define amdgpu_ps float @atomic_pk_add_bf16_1d_v2(<8 x i32> inreg %rsrc, <2 x 
bfloat> %data, i32 %s) {
 ; GFX12-LABEL: atomic_pk_add_bf16_1d_v2:
 ; GFX12:   ; %bb.0: ; %main_body
 ; GFX12-NEXT:image_atomic_pk_add_bf16 v0, v1, s[0:7] dmask:0x1 
dim:SQ_RSRC_IMG_1D th:TH_ATOMIC_RETURN
+; GFX12-NEXT:v_mov_b32_e32 v1, 0
+; GFX12-NEXT:v_mov_b32_e32 v2, 0
 ; GFX12-NEXT:s_waitcnt vmcnt(0)
+; GFX12-NEXT:flat_store_b32 v[1:2], v0
+; GFX12-NEXT:v_mov_b32_e32 v0, 1.0
+; GFX12-NEXT:s_waitcnt lgkmcnt(0)
 ; GFX12-NEXT:; return to shader part epilog
 main_body:
-  %out = call <2 x i16> 
@llvm.amdgcn.image.atomic.pk.add.bf16.1d.v2i16.v2i16(<2 x i16> %data, i32 %s, 
<8 x i32> %rsrc, i32 0, i32 0)
-  %out_i32 = bitcast <2 x i16> %out to i32
-  %out_float = bitcast i32 %out_i32 to float
-  ret float %out_float
-}
-
-define amdgpu_ps float @atomic_pk_add_bf16_1d_v4(<8 x i32> inreg %rsrc, <4 x 
i16> %data, i32 %s) {
-; GFX12-LABEL: atomic_pk_add_bf16_1d_v4:
-; GFX12:   ; %bb.0: ; %main_body
-; GFX12-NEXT:image_atomic_pk_add_bf16 v[0:1], v2, s[0:7] dmask:0x3 
dim:SQ_RSRC_IMG_1D th:TH_ATOMIC_RETURN
-; GFX12-NEXT:s_waitcnt vmcnt(0)
-; GFX12-NEXT:; return to shader part epilog
-main_body:
-  %out = call <4 x i16> 
@llvm.amdgcn.image.atomic.pk.add.bf16.1d.v4i16.v4i16(<4 x i16> %data, i32 %s, 
<8 x i32> %rsrc, i32 0, i32 0)

mariusz-sikora-at-amd wrote:

Yes, #77448 will fix these issue.

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


[compiler-rt] [lld] [mlir] [libcxx] [libcxxabi] [openmp] [llvm] [clang] [runtimes] Use LLVM libunwind from libc++abi by default (PR #77687)

2024-01-16 Thread Petr Hosek via cfe-commits

petrhosek wrote:

> @petrhosek @ldionne would it be better detect libunwind in 
> LLVM_ENABLE_RUNTIMES?
> 
> Asking because we have similar thing in compiler-rt, e.g. for lld, and I am 
> not sure which approach is better: There are trade offs:
> 
> 1. checking LLVM_ENABLE_RUNTIMES simplify end user experience
> 2. forcing default  ON simplifies cmake files and avoids unexpected use of 
> system lib

That would be my preference, specifically I'd set the default for 
`LIBCXXABI_USE_LLVM_UNWINDER` based on whether `libunwind` is present in 
`LLVM_ENABLE_RUNTIMES` (but still let user override it).

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


[clang-tools-extra] [llvm] [clang] [AMDGPU][GFX12] Add 16 bit atomic fadd instructions (PR #75917)

2024-01-16 Thread Mariusz Sikora via cfe-commits


@@ -1368,6 +1391,28 @@ def int_amdgcn_struct_ptr_buffer_atomic_cmpswap : 
Intrinsic<
 // gfx908 intrinsic
 def int_amdgcn_struct_buffer_atomic_fadd : 
AMDGPUStructBufferAtomic;
 def int_amdgcn_struct_ptr_buffer_atomic_fadd : 
AMDGPUStructPtrBufferAtomic;
+// gfx12 intrinsic
+def int_amdgcn_struct_buffer_atomic_fadd_v2bf16 : Intrinsic <
+  [llvm_v2i16_ty],

mariusz-sikora-at-amd wrote:

Done

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


[llvm] [clang] [CloneFunction][DebugInfo] Avoid cloning DILocalVariables of inlined functions (PR #75385)

2024-01-16 Thread Jeremy Morse via cfe-commits

jmorse wrote:

Hi,

We're seeing a crash with this reproducer 
https://gist.github.com/jmorse/b0248c3c9f9195487ffd7c7431a8d15e

llc: llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp:2338: virtual void 
llvm::DwarfDebug::endFunctionImpl(const llvm::MachineFunction *): Assertion 
`LScopes.getAbstractScopesList().size() == NumAbstractSubprograms && 
"getOrCreateAbstractScope() inserted an abstract subprogram scope"' failed.

I'd previously posted the reproducer on 
https://reviews.llvm.org/D144006#4656728 , however I'd anonymised the IR too 
much to the point where it was broken in unrelated ways. Revision 2 of the 
gist, as linked, should produce the crash. I suspect the extra lexical scopes 
reachable through the retained-nodes list also need to be explored when the 
LexicalScopes object gets constructed, to avoid scopes being added late and 
causing containers to invalidate iterators. (Which is what that assertion is 
there to detect).

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


[clang] [Clang][Parse] Diagnose member template declarations with multiple declarators (PR #78243)

2024-01-16 Thread Krystian Stasiowski via cfe-commits

https://github.com/sdkrystian created 
https://github.com/llvm/llvm-project/pull/78243

According to [[temp.pre] p5](http://eel.is/c++draft/temp.pre#5):
> In a 
> [template-declaration](http://eel.is/c++draft/temp.pre#nt:template-declaration),
>  explicit specialization, or explicit instantiation the 
> [init-declarator-list](http://eel.is/c++draft/dcl.decl.general#nt:init-declarator-list)
>  in the declaration shall contain at most one declarator. 

A 
[member-declaration](http://eel.is/c++draft/class.mem.general#nt:member-declaration)
 that is a 
[template-declaration](http://eel.is/c++draft/temp.pre#nt:template-declaration) 
or 
[explicit-specialization](http://eel.is/c++draft/temp.expl.spec#nt:explicit-specialization)
 contains a [declaration](http://eel.is/c++draft/dcl.pre#nt:declaration), even 
though it declares a member. This means it _will_ contain an 
[init-declarator-list](http://eel.is/c++draft/dcl.decl.general#nt:init-declarator-list)
 (not a 
[member-declarator-list](http://eel.is/c++draft/class.mem.general#nt:member-declarator-list)),
 so [[temp.pre] p5](http://eel.is/c++draft/temp.pre#5) applies.

This diagnoses declarations such as:
```cpp
struct A
{
template
static const int x = 0, f(); // error: a template declaration can only 
declare a single entity

template
static const int g(), y = 0; // error: a template declaration can only 
declare a single entity
};
```
The diagnostic messages are the same as those of the equivalent namespace scope 
declarations.

Note: since we currently do not diagnose declarations with multiple abbreviated 
function template declarators at namespace scope e.g., `void f(auto), 
g(auto);`, I did not add diagnostics for the equivalent member declarations.

>From 44c582f0e23725b28b46c07bdb0d2991ebb7d204 Mon Sep 17 00:00:00 2001
From: Krystian Stasiowski 
Date: Fri, 12 Jan 2024 13:45:15 -0500
Subject: [PATCH] [Clang][Parse] Diagnose member template declarations with
 multiple declarators

---
 clang/docs/ReleaseNotes.rst | 1 +
 clang/lib/Parse/ParseDeclCXX.cpp| 9 +
 clang/test/CXX/temp/p3.cpp  | 6 ++
 clang/test/OpenMP/declare_simd_messages.cpp | 3 +--
 4 files changed, 17 insertions(+), 2 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index ea57769a4a5795..54debc4d40e945 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -555,6 +555,7 @@ Improvements to Clang's diagnostics
 - Clang now diagnoses unexpanded packs within the template argument lists of 
function template specializations.
 - Clang now diagnoses attempts to bind a bitfield to an NTTP of a reference 
type as erroneous
   converted constant expression and not as a reference to subobject.
+- Clang now diagnoses member template declarations with multiple declarators.
 
 
 Improvements to Clang's time-trace
diff --git a/clang/lib/Parse/ParseDeclCXX.cpp b/clang/lib/Parse/ParseDeclCXX.cpp
index 5576be9e717a9b..36a9ef199a9588 100644
--- a/clang/lib/Parse/ParseDeclCXX.cpp
+++ b/clang/lib/Parse/ParseDeclCXX.cpp
@@ -3167,6 +3167,15 @@ Parser::ParseCXXClassMemberDeclaration(AccessSpecifier 
AS,
 
 DeclaratorInfo.complete(ThisDecl);
 
+if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
+  if (Tok.is(tok::comma)) {
+Diag(Tok, diag::err_multiple_template_declarators)
+  << (int)TemplateInfo.Kind;
+SkipUntil(tok::semi, StopBeforeMatch);
+  }
+  break;
+}
+
 // If we don't have a comma, it is either the end of the list (a ';')
 // or an error, bail out.
 SourceLocation CommaLoc;
diff --git a/clang/test/CXX/temp/p3.cpp b/clang/test/CXX/temp/p3.cpp
index b708c613d352d2..9e561d0b9a83b2 100644
--- a/clang/test/CXX/temp/p3.cpp
+++ b/clang/test/CXX/temp/p3.cpp
@@ -15,3 +15,9 @@ template struct B { } f(); // expected-error 
{{expected ';' after st
 template struct C { } // expected-error {{expected ';' after 
struct}}
 
 A c;
+
+struct D {
+  template static const int x = 0, f(); // expected-error {{can 
only declare a single entity}}
+
+  template static const int g(), y = 0; // expected-error {{can 
only declare a single entity}}
+};
diff --git a/clang/test/OpenMP/declare_simd_messages.cpp 
b/clang/test/OpenMP/declare_simd_messages.cpp
index dd24322694b69f..fea045400e1faf 100644
--- a/clang/test/OpenMP/declare_simd_messages.cpp
+++ b/clang/test/OpenMP/declare_simd_messages.cpp
@@ -33,10 +33,9 @@ int main();
 int main();
 
 struct A {
-// expected-error@+1 {{function declaration is expected after 'declare simd' 
directive}}
   #pragma omp declare simd
   template
-  T infunc1(T a), infunc2(T a);
+  T infunc1(T a);
 };
 
 // expected-error@+1 {{single declaration is expected after 'declare simd' 
directive}}

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


[clang] [Clang][Parse] Diagnose member template declarations with multiple declarators (PR #78243)

2024-01-16 Thread Krystian Stasiowski via cfe-commits

sdkrystian wrote:

Ping @erichkeane 

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


[clang] [Clang][Parse] Diagnose member template declarations with multiple declarators (PR #78243)

2024-01-16 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Krystian Stasiowski (sdkrystian)


Changes

According to [[temp.pre] p5](http://eel.is/c++draft/temp.pre#5):
> In a 
[template-declaration](http://eel.is/c++draft/temp.pre#nt:template-declaration),
 explicit specialization, or explicit instantiation the 
[init-declarator-list](http://eel.is/c++draft/dcl.decl.general#nt:init-declarator-list)
 in the declaration shall contain at most one declarator. 

A 
[member-declaration](http://eel.is/c++draft/class.mem.general#nt:member-declaration)
 that is a 
[template-declaration](http://eel.is/c++draft/temp.pre#nt:template-declaration) 
or 
[explicit-specialization](http://eel.is/c++draft/temp.expl.spec#nt:explicit-specialization)
 contains a [declaration](http://eel.is/c++draft/dcl.pre#nt:declaration), even 
though it declares a member. This means it _will_ contain an 
[init-declarator-list](http://eel.is/c++draft/dcl.decl.general#nt:init-declarator-list)
 (not a 
[member-declarator-list](http://eel.is/c++draft/class.mem.general#nt:member-declarator-list)),
 so [[temp.pre] p5](http://eel.is/c++draft/temp.pre#5) applies.

This diagnoses declarations such as:
```cpp
struct A
{
template
static const int x = 0, f(); // error: a template declaration can only 
declare a single entity

template
static const int g(), y = 0; // error: a template declaration can only 
declare a single entity
};
```
The diagnostic messages are the same as those of the equivalent namespace scope 
declarations.

Note: since we currently do not diagnose declarations with multiple abbreviated 
function template declarators at namespace scope e.g., `void f(auto), 
g(auto);`, I did not add diagnostics for the equivalent member declarations.

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


4 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+1) 
- (modified) clang/lib/Parse/ParseDeclCXX.cpp (+9) 
- (modified) clang/test/CXX/temp/p3.cpp (+6) 
- (modified) clang/test/OpenMP/declare_simd_messages.cpp (+1-2) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index ea57769a4a5795..54debc4d40e945 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -555,6 +555,7 @@ Improvements to Clang's diagnostics
 - Clang now diagnoses unexpanded packs within the template argument lists of 
function template specializations.
 - Clang now diagnoses attempts to bind a bitfield to an NTTP of a reference 
type as erroneous
   converted constant expression and not as a reference to subobject.
+- Clang now diagnoses member template declarations with multiple declarators.
 
 
 Improvements to Clang's time-trace
diff --git a/clang/lib/Parse/ParseDeclCXX.cpp b/clang/lib/Parse/ParseDeclCXX.cpp
index 5576be9e717a9b..36a9ef199a9588 100644
--- a/clang/lib/Parse/ParseDeclCXX.cpp
+++ b/clang/lib/Parse/ParseDeclCXX.cpp
@@ -3167,6 +3167,15 @@ Parser::ParseCXXClassMemberDeclaration(AccessSpecifier 
AS,
 
 DeclaratorInfo.complete(ThisDecl);
 
+if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
+  if (Tok.is(tok::comma)) {
+Diag(Tok, diag::err_multiple_template_declarators)
+  << (int)TemplateInfo.Kind;
+SkipUntil(tok::semi, StopBeforeMatch);
+  }
+  break;
+}
+
 // If we don't have a comma, it is either the end of the list (a ';')
 // or an error, bail out.
 SourceLocation CommaLoc;
diff --git a/clang/test/CXX/temp/p3.cpp b/clang/test/CXX/temp/p3.cpp
index b708c613d352d2..9e561d0b9a83b2 100644
--- a/clang/test/CXX/temp/p3.cpp
+++ b/clang/test/CXX/temp/p3.cpp
@@ -15,3 +15,9 @@ template struct B { } f(); // expected-error 
{{expected ';' after st
 template struct C { } // expected-error {{expected ';' after 
struct}}
 
 A c;
+
+struct D {
+  template static const int x = 0, f(); // expected-error {{can 
only declare a single entity}}
+
+  template static const int g(), y = 0; // expected-error {{can 
only declare a single entity}}
+};
diff --git a/clang/test/OpenMP/declare_simd_messages.cpp 
b/clang/test/OpenMP/declare_simd_messages.cpp
index dd24322694b69f..fea045400e1faf 100644
--- a/clang/test/OpenMP/declare_simd_messages.cpp
+++ b/clang/test/OpenMP/declare_simd_messages.cpp
@@ -33,10 +33,9 @@ int main();
 int main();
 
 struct A {
-// expected-error@+1 {{function declaration is expected after 'declare simd' 
directive}}
   #pragma omp declare simd
   template
-  T infunc1(T a), infunc2(T a);
+  T infunc1(T a);
 };
 
 // expected-error@+1 {{single declaration is expected after 'declare simd' 
directive}}

``




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


[clang-tools-extra] Add clang-tidy check to suggest replacement of conditional statement with std::min/std::max (PR #77816)

2024-01-16 Thread Piotr Zegar via cfe-commits


@@ -0,0 +1,121 @@
+// RUN: %check_clang_tidy %s readability-use-std-min-max %t
+
+constexpr int myConstexprMin(int a, int b) {
+  return a < b ? a : b;
+}
+
+constexpr int myConstexprMax(int a, int b) {
+  return a > b ? a : b;
+}
+
+int bar(int x, int y) {
+  return x < y ? x : y;
+}
+
+class MyClass {
+public:
+  int member1;
+  int member2;
+};
+
+void foo() {
+  int value1,value2,value3;
+  short value4;
+  MyClass obj;
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::max` instead of `<` 
[readability-use-std-min-max]
+  if (value1 < value2)
+value1 = value2; // CHECK-FIXES: value1 = std::max(value1, value2);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::min` instead of `<` 
[readability-use-std-min-max]
+  if (value1 < value2)
+value2 = value1; // CHECK-FIXES: value2 = std::min(value1, value2);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::min` instead of `>` 
[readability-use-std-min-max]
+  if (value2 > value1)
+value2 = value1; // CHECK-FIXES: value2 = std::min(value2, value1);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::max` instead of `>` 
[readability-use-std-min-max
+  if (value2 > value1)
+value1 = value2; // CHECK-FIXES: value1 = std::max(value2, value1);
+
+  // No suggestion needed here
+  if (value1 == value2)
+value1 = value2;
+  
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::max` instead of `<` 
[readability-use-std-min-max]
+  if(value1` 
[readability-use-std-min-max]
+  if (value1 > myConstexprMax(value2, value3))
+value1 = myConstexprMax(value2, value3); // CHECK-FIXES: value1 = 
std::min(value1, myConstexprMax(value2, value3));
+  
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::max` instead of `<` 
[readability-use-std-min-max]
+  if (value1 < bar(value2, value3))
+value1 = bar(value2, value3); // CHECK-FIXES: value1 = std::max(value1, 
bar(value2, value3));
+  
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::min` instead of `<=` 
[readability-use-std-min-max]
+  if (value1 <= value2)
+value2 = value1; // CHECK-FIXES: value2 = std::min(value1, value2);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::max` instead of `<=` 
[readability-use-std-min-max]
+  if (value1 <= value2)
+value1 = value2; // CHECK-FIXES: value1 = std::max(value1, value2);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::max` instead of `>=` 
[readability-use-std-min-max]
+  if (value2 >= value1)
+value1 = value2; // CHECK-FIXES: value1 = std::max(value2, value1);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::min` instead of `>=` 
[readability-use-std-min-max]
+  if (value2 >= value1)
+value2 = value1; // CHECK-FIXES: value2 = std::min(value2, value1);
+  
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::max` instead of `<` 
[readability-use-std-min-max]
+  if (obj.member1 < obj.member2)
+obj.member1 = obj.member2; // CHECK-FIXES: obj.member1 = 
std::max(obj.member1, obj.member2);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::min` instead of `<` 
[readability-use-std-min-max]
+  if (obj.member1 < obj.member2)
+obj.member2 = obj.member1; // CHECK-FIXES: obj.member2 = 
std::min(obj.member1, obj.member2);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::min` instead of `>` 
[readability-use-std-min-max]
+  if (obj.member2 > obj.member1)
+obj.member2 = obj.member1; // CHECK-FIXES: obj.member2 = 
std::min(obj.member2, obj.member1);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::max` instead of `>` 
[readability-use-std-min-max]
+  if (obj.member2 > obj.member1)
+obj.member1 = obj.member2; // CHECK-FIXES: obj.member1 = 
std::max(obj.member2, obj.member1);
+  
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::max` instead of `<` 
[readability-use-std-min-max]
+  if (obj.member1 < value4)
+obj.member1 = value4; // CHECK-FIXES: obj.member1 = std::max(obj.member1, 
value4);
+  
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::min` instead of `<` 
[readability-use-std-min-max]
+  if (obj.member1 + value2 < value3)
+value3 = obj.member1 + value2; // CHECK-FIXES: value3 = 
std::min(obj.member1 + value2, value3);
+  
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::min` instead of `<=` 
[readability-use-std-min-max]
+  if (value1 <= obj.member2)
+obj.member2 = value1; // CHECK-FIXES: obj.member2 = std::min(value1, 
obj.member2);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::max` instead of `<=` 
[readability-use-std-min-max]
+  if (value1 <= obj.member2)
+value1 = obj.member2; // CHECK-FIXES: value1 = std::max(value1, 
obj.member2);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::max` instead of `>=` 
[readability-use-std-min-max]
+  if (obj.member2 >= value1)
+value1 = obj.member2; // CHECK-FIXES: value1 = std::max(obj.member2, 
value1);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::min` instead of `>=` 
[readability

[clang] [Clang][Parse] Diagnose member template declarations with multiple declarators (PR #78243)

2024-01-16 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 f725bb960d45ada3cc4667dd7aa22792d389c7e7 
44c582f0e23725b28b46c07bdb0d2991ebb7d204 -- clang/lib/Parse/ParseDeclCXX.cpp 
clang/test/CXX/temp/p3.cpp clang/test/OpenMP/declare_simd_messages.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Parse/ParseDeclCXX.cpp b/clang/lib/Parse/ParseDeclCXX.cpp
index 36a9ef199a..03a7ac3205 100644
--- a/clang/lib/Parse/ParseDeclCXX.cpp
+++ b/clang/lib/Parse/ParseDeclCXX.cpp
@@ -3170,7 +3170,7 @@ Parser::ParseCXXClassMemberDeclaration(AccessSpecifier AS,
 if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
   if (Tok.is(tok::comma)) {
 Diag(Tok, diag::err_multiple_template_declarators)
-  << (int)TemplateInfo.Kind;
+<< (int)TemplateInfo.Kind;
 SkipUntil(tok::semi, StopBeforeMatch);
   }
   break;

``




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


[clang] [Clang][Parse] Diagnose member template declarations with multiple declarators (PR #78243)

2024-01-16 Thread Krystian Stasiowski via cfe-commits

https://github.com/sdkrystian updated 
https://github.com/llvm/llvm-project/pull/78243

>From b5d814abf6241d3e9cdfcc64109c33c56a896172 Mon Sep 17 00:00:00 2001
From: Krystian Stasiowski 
Date: Fri, 12 Jan 2024 13:45:15 -0500
Subject: [PATCH] [Clang][Parse] Diagnose member template declarations with
 multiple declarators

---
 clang/docs/ReleaseNotes.rst | 1 +
 clang/lib/Parse/ParseDeclCXX.cpp| 9 +
 clang/test/CXX/temp/p3.cpp  | 6 ++
 clang/test/OpenMP/declare_simd_messages.cpp | 3 +--
 4 files changed, 17 insertions(+), 2 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index ea57769a4a5795..54debc4d40e945 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -555,6 +555,7 @@ Improvements to Clang's diagnostics
 - Clang now diagnoses unexpanded packs within the template argument lists of 
function template specializations.
 - Clang now diagnoses attempts to bind a bitfield to an NTTP of a reference 
type as erroneous
   converted constant expression and not as a reference to subobject.
+- Clang now diagnoses member template declarations with multiple declarators.
 
 
 Improvements to Clang's time-trace
diff --git a/clang/lib/Parse/ParseDeclCXX.cpp b/clang/lib/Parse/ParseDeclCXX.cpp
index 5576be9e717a9b..03a7ac3205d296 100644
--- a/clang/lib/Parse/ParseDeclCXX.cpp
+++ b/clang/lib/Parse/ParseDeclCXX.cpp
@@ -3167,6 +3167,15 @@ Parser::ParseCXXClassMemberDeclaration(AccessSpecifier 
AS,
 
 DeclaratorInfo.complete(ThisDecl);
 
+if (TemplateInfo.Kind != ParsedTemplateInfo::NonTemplate) {
+  if (Tok.is(tok::comma)) {
+Diag(Tok, diag::err_multiple_template_declarators)
+<< (int)TemplateInfo.Kind;
+SkipUntil(tok::semi, StopBeforeMatch);
+  }
+  break;
+}
+
 // If we don't have a comma, it is either the end of the list (a ';')
 // or an error, bail out.
 SourceLocation CommaLoc;
diff --git a/clang/test/CXX/temp/p3.cpp b/clang/test/CXX/temp/p3.cpp
index b708c613d352d2..9e561d0b9a83b2 100644
--- a/clang/test/CXX/temp/p3.cpp
+++ b/clang/test/CXX/temp/p3.cpp
@@ -15,3 +15,9 @@ template struct B { } f(); // expected-error 
{{expected ';' after st
 template struct C { } // expected-error {{expected ';' after 
struct}}
 
 A c;
+
+struct D {
+  template static const int x = 0, f(); // expected-error {{can 
only declare a single entity}}
+
+  template static const int g(), y = 0; // expected-error {{can 
only declare a single entity}}
+};
diff --git a/clang/test/OpenMP/declare_simd_messages.cpp 
b/clang/test/OpenMP/declare_simd_messages.cpp
index dd24322694b69f..fea045400e1faf 100644
--- a/clang/test/OpenMP/declare_simd_messages.cpp
+++ b/clang/test/OpenMP/declare_simd_messages.cpp
@@ -33,10 +33,9 @@ int main();
 int main();
 
 struct A {
-// expected-error@+1 {{function declaration is expected after 'declare simd' 
directive}}
   #pragma omp declare simd
   template
-  T infunc1(T a), infunc2(T a);
+  T infunc1(T a);
 };
 
 // expected-error@+1 {{single declaration is expected after 'declare simd' 
directive}}

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


[clang] [llvm] [AMDGPU] Add global_load_tr for GFX12 (PR #77772)

2024-01-16 Thread Piotr Sobczak via cfe-commits


@@ -18178,6 +18178,51 @@ Value *CodeGenFunction::EmitAMDGPUBuiltinExpr(unsigned 
BuiltinID,
 llvm::Function *F = CGM.getIntrinsic(IID, {ArgTy});
 return Builder.CreateCall(F, {Addr, Val, ZeroI32, ZeroI32, ZeroI1});
   }
+  case AMDGPU::BI__builtin_amdgcn_global_load_tr_b64_v2i32:
+  case AMDGPU::BI__builtin_amdgcn_global_load_tr_b64_i32:
+  case AMDGPU::BI__builtin_amdgcn_global_load_tr_b128_v8i16:
+  case AMDGPU::BI__builtin_amdgcn_global_load_tr_b128_v8f16:
+  case AMDGPU::BI__builtin_amdgcn_global_load_tr_b128_v4i16:
+  case AMDGPU::BI__builtin_amdgcn_global_load_tr_b128_v4f16: {
+
+Intrinsic::ID IID;
+llvm::Type *ArgTy;
+switch (BuiltinID) {
+case AMDGPU::BI__builtin_amdgcn_global_load_tr_b64_v2i32:
+  ArgTy = llvm::FixedVectorType::get(
+  llvm::Type::getInt32Ty(getLLVMContext()), 2);
+  IID = Intrinsic::amdgcn_global_load_tr_b64;

piotrAMD wrote:

Are you suggesting to just drop _global from the intrinsic name since it 
explicitly works on `global_ptr_ty` anyway?

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


[clang] [clang][dataflow] Use `ignoreCFGOmittedNodes()` in `setValue()`. (PR #78245)

2024-01-16 Thread via cfe-commits

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

This is to be consistent with `getValue()`, which also uses
`ignoreCFGOmittedNodes()`.

Before this fix, it was not possible to retrieve a `Value` from a "CFG omitted"
node that had previously been set using `setValue()`; see the accompanying test,
which fails without the fix.

I discovered this issue while running internal integration tests on
https://github.com/llvm/llvm-project/pull/78127.


>From 7a3afa03e030563d9377a163778d4eb6b6b3e253 Mon Sep 17 00:00:00 2001
From: Martin Braenne 
Date: Tue, 16 Jan 2024 09:40:51 +
Subject: [PATCH] [clang][dataflow] Use `ignoreCFGOmittedNodes()` in
 `setValue()`.

This is to be consistent with `getValue()`, which also uses
`ignoreCFGOmittedNodes()`.

Before this fix, it was not possible to retrieve a `Value` from a "CFG omitted"
node that had previously been set using `setValue()`; see the accompanying test,
which fails without the fix.

I discovered this issue while running internal integration tests on
https://github.com/llvm/llvm-project/pull/78127.
---
 .../FlowSensitive/DataflowEnvironment.cpp | 10 ++--
 .../FlowSensitive/DataflowEnvironmentTest.cpp | 46 +++
 2 files changed, 52 insertions(+), 4 deletions(-)

diff --git a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp 
b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
index 96fe6df88dbb9f..05f8101b0068a3 100644
--- a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -803,13 +803,15 @@ void Environment::setValue(const StorageLocation &Loc, 
Value &Val) {
 }
 
 void Environment::setValue(const Expr &E, Value &Val) {
+  const Expr &CanonE = ignoreCFGOmittedNodes(E);
+
   if (auto *RecordVal = dyn_cast(&Val)) {
-assert(isOriginalRecordConstructor(E) ||
-   &RecordVal->getLoc() == &getResultObjectLocation(E));
+assert(isOriginalRecordConstructor(CanonE) ||
+   &RecordVal->getLoc() == &getResultObjectLocation(CanonE));
   }
 
-  assert(E.isPRValue());
-  ExprToVal[&E] = &Val;
+  assert(CanonE.isPRValue());
+  ExprToVal[&CanonE] = &Val;
 }
 
 Value *Environment::getValue(const StorageLocation &Loc) const {
diff --git a/clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp 
b/clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
index 003434a58b1075..8799d03dfd3c58 100644
--- a/clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
@@ -58,6 +58,52 @@ TEST_F(EnvironmentTest, FlowCondition) {
   EXPECT_FALSE(Env.allows(NotX));
 }
 
+TEST_F(EnvironmentTest, SetAndGetValueOnCfgOmittedNodes) {
+  // Check that we can set a value on an expression that is omitted from the 
CFG
+  // (see `ignoreCFGOmittedNodes()`), then retrieve that same value from the
+  // expression. This is a regression test; `setValue()` and `getValue()`
+  // previously did not use `ignoreCFGOmittedNodes()` consistently.
+
+  using namespace ast_matchers;
+
+  std::string Code = R"cc(
+struct S {
+  int f();
+};
+void target() {
+  // Method call on a temporary produces an `ExprWithCleanups`.
+  S().f();
+  (1);
+}
+  )cc";
+
+  auto Unit =
+  tooling::buildASTFromCodeWithArgs(Code, {"-fsyntax-only", "-std=c++17"});
+  auto &Context = Unit->getASTContext();
+
+  ASSERT_EQ(Context.getDiagnostics().getClient()->getNumErrors(), 0U);
+
+  const ExprWithCleanups *WithCleanups = selectFirst(
+  "cleanups",
+  match(exprWithCleanups(hasType(isInteger())).bind("cleanups"), Context));
+  ASSERT_NE(WithCleanups, nullptr);
+
+  const ParenExpr *Paren = selectFirst(
+  "paren", match(parenExpr(hasType(isInteger())).bind("paren"), Context));
+  ASSERT_NE(Paren, nullptr);
+
+  Environment Env(DAContext);
+  IntegerValue *Val1 =
+  cast(Env.createValue(Unit->getASTContext().IntTy));
+  Env.setValue(*WithCleanups, *Val1);
+  EXPECT_EQ(Env.getValue(*WithCleanups), Val1);
+
+  IntegerValue *Val2 =
+  cast(Env.createValue(Unit->getASTContext().IntTy));
+  Env.setValue(*Paren, *Val2);
+  EXPECT_EQ(Env.getValue(*Paren), Val2);
+}
+
 TEST_F(EnvironmentTest, CreateValueRecursiveType) {
   using namespace ast_matchers;
 

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


[clang] [clang][dataflow] Use `ignoreCFGOmittedNodes()` in `setValue()`. (PR #78245)

2024-01-16 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang

@llvm/pr-subscribers-clang-analysis

Author: None (martinboehme)


Changes

This is to be consistent with `getValue()`, which also uses
`ignoreCFGOmittedNodes()`.

Before this fix, it was not possible to retrieve a `Value` from a "CFG omitted"
node that had previously been set using `setValue()`; see the accompanying test,
which fails without the fix.

I discovered this issue while running internal integration tests on
https://github.com/llvm/llvm-project/pull/78127.


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


2 Files Affected:

- (modified) clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp (+6-4) 
- (modified) clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp 
(+46) 


``diff
diff --git a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp 
b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
index 96fe6df88dbb9f7..05f8101b0068a31 100644
--- a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -803,13 +803,15 @@ void Environment::setValue(const StorageLocation &Loc, 
Value &Val) {
 }
 
 void Environment::setValue(const Expr &E, Value &Val) {
+  const Expr &CanonE = ignoreCFGOmittedNodes(E);
+
   if (auto *RecordVal = dyn_cast(&Val)) {
-assert(isOriginalRecordConstructor(E) ||
-   &RecordVal->getLoc() == &getResultObjectLocation(E));
+assert(isOriginalRecordConstructor(CanonE) ||
+   &RecordVal->getLoc() == &getResultObjectLocation(CanonE));
   }
 
-  assert(E.isPRValue());
-  ExprToVal[&E] = &Val;
+  assert(CanonE.isPRValue());
+  ExprToVal[&CanonE] = &Val;
 }
 
 Value *Environment::getValue(const StorageLocation &Loc) const {
diff --git a/clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp 
b/clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
index 003434a58b1075f..8799d03dfd3c588 100644
--- a/clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
@@ -58,6 +58,52 @@ TEST_F(EnvironmentTest, FlowCondition) {
   EXPECT_FALSE(Env.allows(NotX));
 }
 
+TEST_F(EnvironmentTest, SetAndGetValueOnCfgOmittedNodes) {
+  // Check that we can set a value on an expression that is omitted from the 
CFG
+  // (see `ignoreCFGOmittedNodes()`), then retrieve that same value from the
+  // expression. This is a regression test; `setValue()` and `getValue()`
+  // previously did not use `ignoreCFGOmittedNodes()` consistently.
+
+  using namespace ast_matchers;
+
+  std::string Code = R"cc(
+struct S {
+  int f();
+};
+void target() {
+  // Method call on a temporary produces an `ExprWithCleanups`.
+  S().f();
+  (1);
+}
+  )cc";
+
+  auto Unit =
+  tooling::buildASTFromCodeWithArgs(Code, {"-fsyntax-only", "-std=c++17"});
+  auto &Context = Unit->getASTContext();
+
+  ASSERT_EQ(Context.getDiagnostics().getClient()->getNumErrors(), 0U);
+
+  const ExprWithCleanups *WithCleanups = selectFirst(
+  "cleanups",
+  match(exprWithCleanups(hasType(isInteger())).bind("cleanups"), Context));
+  ASSERT_NE(WithCleanups, nullptr);
+
+  const ParenExpr *Paren = selectFirst(
+  "paren", match(parenExpr(hasType(isInteger())).bind("paren"), Context));
+  ASSERT_NE(Paren, nullptr);
+
+  Environment Env(DAContext);
+  IntegerValue *Val1 =
+  cast(Env.createValue(Unit->getASTContext().IntTy));
+  Env.setValue(*WithCleanups, *Val1);
+  EXPECT_EQ(Env.getValue(*WithCleanups), Val1);
+
+  IntegerValue *Val2 =
+  cast(Env.createValue(Unit->getASTContext().IntTy));
+  Env.setValue(*Paren, *Val2);
+  EXPECT_EQ(Env.getValue(*Paren), Val2);
+}
+
 TEST_F(EnvironmentTest, CreateValueRecursiveType) {
   using namespace ast_matchers;
 

``




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


[clang-tools-extra] [clang] [llvm] [mlir] [ASan][AMDGPU] Fix Assertion Failure. (PR #78242)

2024-01-16 Thread via cfe-commits

https://github.com/ampandey-1995 updated 
https://github.com/llvm/llvm-project/pull/78242

>From fe6d4abebb12e063e10b2266f76ff1a604783c0c Mon Sep 17 00:00:00 2001
From: Amit Pandey 
Date: Mon, 11 Dec 2023 14:23:44 +0530
Subject: [PATCH] [ASan][AMDGPU] Fix Assertion Failure.

Assertion failure `(i >= FTy->getNumParams() || FTy->getParamType(i) ==
Args[i]->getType()) && "Calling a function with a bad signature!"'.  The
'llvm.memcpy' intercepted by ASan instrumentation pass is implemented by it's
own __asan_memcpy implementation. The second argument of llvm.memcpy accepts ptr
to addrspace(4), __asan_memcpy also has to follow ptr to addrspace(4)
convention.
---
 .../Instrumentation/AddressSanitizer.cpp  |  8 ++--
 .../AMDGPU/asan_instrument_mem_intrinsics.ll  | 48 +++
 2 files changed, 53 insertions(+), 3 deletions(-)
 create mode 100644 
llvm/test/Instrumentation/AddressSanitizer/AMDGPU/asan_instrument_mem_intrinsics.ll

diff --git a/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp 
b/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
index fb5838bb7941ad..32e7f1b6fc3374 100644
--- a/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ b/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -1254,9 +1254,11 @@ Value *AddressSanitizer::memToShadow(Value *Shadow, 
IRBuilder<> &IRB) {
 void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
   InstrumentationIRBuilder IRB(MI);
   if (isa(MI)) {
-IRB.CreateCall(isa(MI) ? AsanMemmove : AsanMemcpy,
-   {MI->getOperand(0), MI->getOperand(1),
-IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
+IRB.CreateCall(
+isa(MI) ? AsanMemmove : AsanMemcpy,
+{MI->getOperand(0),
+ IRB.CreatePointerBitCastOrAddrSpaceCast(MI->getOperand(1), PtrTy),
+ IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
   } else if (isa(MI)) {
 IRB.CreateCall(
 AsanMemset,
diff --git 
a/llvm/test/Instrumentation/AddressSanitizer/AMDGPU/asan_instrument_mem_intrinsics.ll
 
b/llvm/test/Instrumentation/AddressSanitizer/AMDGPU/asan_instrument_mem_intrinsics.ll
new file mode 100644
index 00..26258ef384795d
--- /dev/null
+++ 
b/llvm/test/Instrumentation/AddressSanitizer/AMDGPU/asan_instrument_mem_intrinsics.ll
@@ -0,0 +1,48 @@
+;RUN: opt < %s -passes=asan -S | FileCheck %s
+
+target datalayout = 
"e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32-p7:160:256:256:32-p8:128:128-p9:192:256:256:32-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5-G1-ni:7:8:9"
+target triple = "amdgcn-amd-amdhsa"
+
+@__const.__assert_fail.fmt = private unnamed_addr addrspace(4) constant [47 x 
i8] c"%s:%u: %s: Device-side assertion `%s' failed.\0A\00", align 16
+
+; Function Attrs: nocallback nofree nounwind willreturn memory(argmem: 
readwrite)
+declare void @llvm.memcpy.p0.p4.i64(ptr noalias nocapture writeonly, ptr 
addrspace(4) noalias nocapture readonly, i64, i1 immarg) #1
+
+; Function Attrs: convergent mustprogress noinline nounwind optnone
+define weak hidden void @test_mem_intrinsic() sanitize_address #0 {
+; CHECK: define weak hidden void @test_mem_intrinsic() #1 {
+; CHECK-NEXT: entry:
+; CHECK-NEXT: [[FMT:%.*]] = alloca [47 x i8], align 16, addrspace(5)
+; CHECK-NEXT: [[FADDRC:%.*]] = addrspacecast ptr addrspace(5) [[FMT]] to ptr
+; CHECK-NEXT: [[ITMP:%.*]] = call ptr @__asan_memcpy(ptr [[FADDRC]], ptr 
addrspacecast (ptr addrspace(4) @__const.__assert_fail.fmt to ptr), i64 47)
+; CHECK-NEXT: ret
+entry:
+%fmt = alloca [47 x i8], align 16, addrspace(5)
+%fmt.ascast = addrspacecast ptr addrspace(5) %fmt to ptr
+call void @llvm.memcpy.p0.p4.i64(ptr align 16 %fmt.ascast, ptr addrspace(4) 
align 16 @__const.__assert_fail.fmt, i64 47, i1 false)
+ret void
+}
+
+
+
+attributes #0 = { convergent mustprogress noinline nounwind optnone 
"frame-pointer"="all" "no-trapping-math"="true" 
"stack-protector-buffer-size"="8" "target-cpu"="gfx906" 
"target-features"="+16-bit-insts,+ci-insts,+dl-insts,+dot1-insts,+dot10-insts,+dot2-insts,+dot7-insts,+dpp,+gfx8-insts,+gfx9-insts,+s-memrealtime,+s-memtime-inst,+wavefrontsize64,+xnack"
 }
+attributes #1 = { nocallback nofree nounwind willreturn memory(argmem: 
readwrite) }
+attributes #2 = { convergent nounwind "frame-pointer"="all" 
"no-trapping-math"="true" "stack-protector-buffer-size"="8" 
"target-cpu"="gfx906" 
"target-features"="+16-bit-insts,+ci-insts,+dl-insts,+dot1-insts,+dot10-insts,+dot2-insts,+dot7-insts,+dpp,+gfx8-insts,+gfx9-insts,+s-memrealtime,+s-memtime-inst,+wavefrontsize64,+xnack"
 }
+attributes #3 = { cold noreturn nounwind memory(inaccessiblemem: write) }
+attributes #4 = { convergent mustprogress noinline norecurse nounwind optnone 
"amdgpu-flat-work-group-size"="1,1024" "frame-pointer"="all" 
"no-trapping-math"="true" "stack-protector-buffer-size"="8" 
"target-cpu"="gfx906" 
"target-features"="+16-bit-insts,+ci-insts,+dl-insts,+d

[clang-tools-extra] [NFC][clang-tidy]improve performance for misc-unused-using-decls check (PR #78231)

2024-01-16 Thread Congcong Cai via cfe-commits

HerrCai0907 wrote:

> Thanks, the code looks good. Do you have any performance data after this 
> change?

I don't run clang-tidy bench for some large project. But I do some test for 
some auto-generated cpp file which has lots of using, and the execution time 
reduce from 0.2s to 0.18s in my MAC M1 Pro.

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


[clang-tools-extra] dca6f60 - [NFC][clang-tidy]improve performance for misc-unused-using-decls check (#78231)

2024-01-16 Thread via cfe-commits

Author: Congcong Cai
Date: 2024-01-16T17:45:03+08:00
New Revision: dca6f60bcdd4a8e6c5defad454d9c470a27701fe

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

LOG: [NFC][clang-tidy]improve performance for misc-unused-using-decls check 
(#78231)

`UnusedUsingDeclsCheck::removeFromFoundDecls` will be called with high
frequency. At current time it will check every `Context`.
This patch adds a cache to reduce algorithm complexity.

Added: 


Modified: 
clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.cpp
clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.h

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.cpp 
b/clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.cpp
index 051375263e53c3..59e487bab31195 100644
--- a/clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.cpp
+++ b/clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.cpp
@@ -117,8 +117,10 @@ void UnusedUsingDeclsCheck::check(const 
MatchFinder::MatchResult &Result) {
 /*SkipTrailingWhitespaceAndNewLine=*/true));
 for (const auto *UsingShadow : Using->shadows()) {
   const auto *TargetDecl = 
UsingShadow->getTargetDecl()->getCanonicalDecl();
-  if (shouldCheckDecl(TargetDecl))
+  if (shouldCheckDecl(TargetDecl)) {
 Context.UsingTargetDecls.insert(TargetDecl);
+UsingTargetDeclsCache.insert(TargetDecl);
+  }
 }
 if (!Context.UsingTargetDecls.empty())
   Contexts.push_back(Context);
@@ -201,13 +203,16 @@ void UnusedUsingDeclsCheck::check(const 
MatchFinder::MatchResult &Result) {
 void UnusedUsingDeclsCheck::removeFromFoundDecls(const Decl *D) {
   if (!D)
 return;
+  const Decl *CanonicalDecl = D->getCanonicalDecl();
+  if (!UsingTargetDeclsCache.contains(CanonicalDecl))
+return;
   // FIXME: Currently, we don't handle the using-decls being used in 
diff erent
   // scopes (such as 
diff erent namespaces, 
diff erent functions). Instead of
   // giving an incorrect message, we mark all of them as used.
-  //
-  // FIXME: Use a more efficient way to find a matching context.
   for (auto &Context : Contexts) {
-if (Context.UsingTargetDecls.contains(D->getCanonicalDecl()))
+if (Context.IsUsed)
+  continue;
+if (Context.UsingTargetDecls.contains(CanonicalDecl))
   Context.IsUsed = true;
   }
 }
@@ -224,6 +229,7 @@ void UnusedUsingDeclsCheck::onEndOfTranslationUnit() {
 }
   }
   Contexts.clear();
+  UsingTargetDeclsCache.clear();
 }
 
 } // namespace clang::tidy::misc

diff  --git a/clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.h 
b/clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.h
index 498b3ffd2678c3..7bdaf12e8aecee 100644
--- a/clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.h
+++ b/clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.h
@@ -49,6 +49,7 @@ class UnusedUsingDeclsCheck : public ClangTidyCheck {
   };
 
   std::vector Contexts;
+  llvm::SmallPtrSet UsingTargetDeclsCache;
 
   StringRef RawStringHeaderFileExtensions;
   FileExtensionsSet HeaderFileExtensions;



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


[clang-tools-extra] [NFC][clang-tidy]improve performance for misc-unused-using-decls check (PR #78231)

2024-01-16 Thread Congcong Cai via cfe-commits

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


[llvm] [clang] [RISCV] CodeGen of RVE and ilp32e/lp64e ABIs (PR #76777)

2024-01-16 Thread Alex Bradbury via cfe-commits

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

LGTM. Thanks for your persistence on this!

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


[mlir] [clang-tools-extra] [llvm] [clang] [ASan][AMDGPU] Fix Assertion Failure. (PR #78242)

2024-01-16 Thread via cfe-commits

https://github.com/ampandey-1995 updated 
https://github.com/llvm/llvm-project/pull/78242

>From fe6d4abebb12e063e10b2266f76ff1a604783c0c Mon Sep 17 00:00:00 2001
From: Amit Pandey 
Date: Mon, 11 Dec 2023 14:23:44 +0530
Subject: [PATCH] [ASan][AMDGPU] Fix Assertion Failure.

Assertion failure `(i >= FTy->getNumParams() || FTy->getParamType(i) ==
Args[i]->getType()) && "Calling a function with a bad signature!"'.  The
'llvm.memcpy' intercepted by ASan instrumentation pass is implemented by it's
own __asan_memcpy implementation. The second argument of llvm.memcpy accepts ptr
to addrspace(4), __asan_memcpy also has to follow ptr to addrspace(4)
convention.
---
 .../Instrumentation/AddressSanitizer.cpp  |  8 ++--
 .../AMDGPU/asan_instrument_mem_intrinsics.ll  | 48 +++
 2 files changed, 53 insertions(+), 3 deletions(-)
 create mode 100644 
llvm/test/Instrumentation/AddressSanitizer/AMDGPU/asan_instrument_mem_intrinsics.ll

diff --git a/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp 
b/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
index fb5838bb7941ad..32e7f1b6fc3374 100644
--- a/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
+++ b/llvm/lib/Transforms/Instrumentation/AddressSanitizer.cpp
@@ -1254,9 +1254,11 @@ Value *AddressSanitizer::memToShadow(Value *Shadow, 
IRBuilder<> &IRB) {
 void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
   InstrumentationIRBuilder IRB(MI);
   if (isa(MI)) {
-IRB.CreateCall(isa(MI) ? AsanMemmove : AsanMemcpy,
-   {MI->getOperand(0), MI->getOperand(1),
-IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
+IRB.CreateCall(
+isa(MI) ? AsanMemmove : AsanMemcpy,
+{MI->getOperand(0),
+ IRB.CreatePointerBitCastOrAddrSpaceCast(MI->getOperand(1), PtrTy),
+ IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
   } else if (isa(MI)) {
 IRB.CreateCall(
 AsanMemset,
diff --git 
a/llvm/test/Instrumentation/AddressSanitizer/AMDGPU/asan_instrument_mem_intrinsics.ll
 
b/llvm/test/Instrumentation/AddressSanitizer/AMDGPU/asan_instrument_mem_intrinsics.ll
new file mode 100644
index 00..26258ef384795d
--- /dev/null
+++ 
b/llvm/test/Instrumentation/AddressSanitizer/AMDGPU/asan_instrument_mem_intrinsics.ll
@@ -0,0 +1,48 @@
+;RUN: opt < %s -passes=asan -S | FileCheck %s
+
+target datalayout = 
"e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32-p7:160:256:256:32-p8:128:128-p9:192:256:256:32-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5-G1-ni:7:8:9"
+target triple = "amdgcn-amd-amdhsa"
+
+@__const.__assert_fail.fmt = private unnamed_addr addrspace(4) constant [47 x 
i8] c"%s:%u: %s: Device-side assertion `%s' failed.\0A\00", align 16
+
+; Function Attrs: nocallback nofree nounwind willreturn memory(argmem: 
readwrite)
+declare void @llvm.memcpy.p0.p4.i64(ptr noalias nocapture writeonly, ptr 
addrspace(4) noalias nocapture readonly, i64, i1 immarg) #1
+
+; Function Attrs: convergent mustprogress noinline nounwind optnone
+define weak hidden void @test_mem_intrinsic() sanitize_address #0 {
+; CHECK: define weak hidden void @test_mem_intrinsic() #1 {
+; CHECK-NEXT: entry:
+; CHECK-NEXT: [[FMT:%.*]] = alloca [47 x i8], align 16, addrspace(5)
+; CHECK-NEXT: [[FADDRC:%.*]] = addrspacecast ptr addrspace(5) [[FMT]] to ptr
+; CHECK-NEXT: [[ITMP:%.*]] = call ptr @__asan_memcpy(ptr [[FADDRC]], ptr 
addrspacecast (ptr addrspace(4) @__const.__assert_fail.fmt to ptr), i64 47)
+; CHECK-NEXT: ret
+entry:
+%fmt = alloca [47 x i8], align 16, addrspace(5)
+%fmt.ascast = addrspacecast ptr addrspace(5) %fmt to ptr
+call void @llvm.memcpy.p0.p4.i64(ptr align 16 %fmt.ascast, ptr addrspace(4) 
align 16 @__const.__assert_fail.fmt, i64 47, i1 false)
+ret void
+}
+
+
+
+attributes #0 = { convergent mustprogress noinline nounwind optnone 
"frame-pointer"="all" "no-trapping-math"="true" 
"stack-protector-buffer-size"="8" "target-cpu"="gfx906" 
"target-features"="+16-bit-insts,+ci-insts,+dl-insts,+dot1-insts,+dot10-insts,+dot2-insts,+dot7-insts,+dpp,+gfx8-insts,+gfx9-insts,+s-memrealtime,+s-memtime-inst,+wavefrontsize64,+xnack"
 }
+attributes #1 = { nocallback nofree nounwind willreturn memory(argmem: 
readwrite) }
+attributes #2 = { convergent nounwind "frame-pointer"="all" 
"no-trapping-math"="true" "stack-protector-buffer-size"="8" 
"target-cpu"="gfx906" 
"target-features"="+16-bit-insts,+ci-insts,+dl-insts,+dot1-insts,+dot10-insts,+dot2-insts,+dot7-insts,+dpp,+gfx8-insts,+gfx9-insts,+s-memrealtime,+s-memtime-inst,+wavefrontsize64,+xnack"
 }
+attributes #3 = { cold noreturn nounwind memory(inaccessiblemem: write) }
+attributes #4 = { convergent mustprogress noinline norecurse nounwind optnone 
"amdgpu-flat-work-group-size"="1,1024" "frame-pointer"="all" 
"no-trapping-math"="true" "stack-protector-buffer-size"="8" 
"target-cpu"="gfx906" 
"target-features"="+16-bit-insts,+ci-insts,+dl-insts,+d

[clang] [llvm] [CMake][PGO] Build Sema.cpp to generate profdata for PGO builds (PR #77347)

2024-01-16 Thread Petr Hosek via cfe-commits


@@ -26,9 +30,23 @@ if(LLVM_BUILD_INSTRUMENTED)
 message(STATUS "To enable merging PGO data LLVM_PROFDATA has to point to 
llvm-profdata")
   else()
 add_custom_target(generate-profdata
-  COMMAND "${Python3_EXECUTABLE}" 
${CMAKE_CURRENT_SOURCE_DIR}/perf-helper.py merge ${LLVM_PROFDATA} 
${CMAKE_CURRENT_BINARY_DIR}/clang.profdata ${CMAKE_CURRENT_BINARY_DIR}
+  COMMAND "${Python3_EXECUTABLE}" 
${CMAKE_CURRENT_SOURCE_DIR}/perf-helper.py merge ${LLVM_PROFDATA} 
${CMAKE_CURRENT_BINARY_DIR}/clang.profdata ${CMAKE_CURRENT_BINARY_DIR} 
${CMAKE_BINARY_DIR}/profiles/
   COMMENT "Merging profdata"
   DEPENDS generate-profraw)
+if (CLANG_PGO_TRAINING_DATA_SOURCE_DIR)
+  llvm_ExternalProject_Add(generate-profraw-external 
${CLANG_PGO_TRAINING_DATA_SOURCE_DIR}
+  USE_TOOLCHAIN EXLUDE_FROM_ALL NO_INSTALL DEPENDS 
generate-profraw)
+  add_dependencies(generate-profdata generate-profraw-external)
+else()
+  # Default to compiling a file from clang. This also builds all the
+  # dependencies needed to build this file, like TableGen.
+  set(generate_profraw_clang_sema 
tools/clang/lib/Sema/CMakeFiles/obj.clangSema.dir/Sema.cpp.o)
+  llvm_ExternalProject_Add(generate-profraw-clang 
${CMAKE_CURRENT_SOURCE_DIR}/../../../llvm
+  USE_TOOLCHAIN EXLUDE_FROM_ALL NO_INSTALL DEPENDS generate-profraw
+  EXTRA_TARGETS generate_profraw_clang_sema

petrhosek wrote:

The idea I'd like explore is using libc++ (and perhaps also libc) test suite 
for training. It consists of self-contained test programs which should 
sufficiently exercise various aspects of C/C++ frontend.

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


[clang] [clang][dataflow] Process terminator condition within `transferCFGBlock()`. (PR #78127)

2024-01-16 Thread via cfe-commits

martinboehme wrote:

Heads up: I'm holding off on merging this PR for the time being because I've 
discovered that it breaks some of our internal integration tests. The reason is 
a pre-existing bug, for which I have a fix in review at #78245.

The effect of the bug is that the following code in this PR does not guarantee 
that `State.Env.getValue(*TerminatorCond)` will return a non-null value after 
the code is run:

```cxx
if (State.Env.getValue(*TerminatorCond) == nullptr)
  State.Env.setValue(*TerminatorCond, State.Env.makeAtomicBoolValue());
```

As a result, the assertion `assert(Val != nullptr);` in `extendFlowCondition()` 
fails.

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


[clang-tools-extra] [NFC][clang-tidy]improve performance for misc-unused-using-decls check (PR #78231)

2024-01-16 Thread Congcong Cai via cfe-commits

HerrCai0907 wrote:

> LGTM. There is open issue for performance of this check. Consider mentioning 
> this in release notes as some generic performance improvement.

I have also seen this issue. But after optimization, this check is still slow. 
I guess registering too many pattern causes performance issue but I cannot find 
a good solution to optimize it.

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


[clang-tools-extra] fd0e06d - [clang-tidy] Fix missing parentheses in readability-implicit-bool-conversion fixes (#74891)

2024-01-16 Thread via cfe-commits

Author: Piotr Zegar
Date: 2024-01-16T10:51:18+01:00
New Revision: fd0e06d1118f14e5a90d5f30b1c9d4b69b0a72eb

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

LOG: [clang-tidy] Fix missing parentheses in 
readability-implicit-bool-conversion fixes (#74891)

Check now more properly add missing parentheses to code like this: 'bool
bar = true ? 1 : 0 != 0;'.

Closes #71867

Added: 


Modified: 
clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
clang-tools-extra/clang-tidy/utils/FixItHintUtils.cpp
clang-tools-extra/clang-tidy/utils/FixItHintUtils.h
clang-tools-extra/docs/ReleaseNotes.rst

clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion-allow-in-conditions.cpp

clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion-cxx98.cpp

clang-tools-extra/test/clang-tidy/checkers/readability/implicit-bool-conversion.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
index 672f28721114c9..11706ffb5b7d4f 100644
--- a/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/ImplicitBoolConversionCheck.cpp
@@ -7,6 +7,7 @@
 
//===--===//
 
 #include "ImplicitBoolConversionCheck.h"
+#include "../utils/FixItHintUtils.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/Lex/Lexer.h"
@@ -61,31 +62,6 @@ bool isUnaryLogicalNotOperator(const Stmt *Statement) {
   return UnaryOperatorExpr && UnaryOperatorExpr->getOpcode() == UO_LNot;
 }
 
-bool areParensNeededForOverloadedOperator(OverloadedOperatorKind OperatorKind) 
{
-  switch (OperatorKind) {
-  case OO_New:
-  case OO_Delete: // Fall-through on purpose.
-  case OO_Array_New:
-  case OO_Array_Delete:
-  case OO_ArrowStar:
-  case OO_Arrow:
-  case OO_Call:
-  case OO_Subscript:
-return false;
-
-  default:
-return true;
-  }
-}
-
-bool areParensNeededForStatement(const Stmt *Statement) {
-  if (const auto *OperatorCall = dyn_cast(Statement)) {
-return areParensNeededForOverloadedOperator(OperatorCall->getOperator());
-  }
-
-  return isa(Statement) || isa(Statement);
-}
-
 void fixGenericExprCastToBool(DiagnosticBuilder &Diag,
   const ImplicitCastExpr *Cast, const Stmt *Parent,
   ASTContext &Context) {
@@ -105,9 +81,10 @@ void fixGenericExprCastToBool(DiagnosticBuilder &Diag,
 
   const Expr *SubExpr = Cast->getSubExpr();
 
-  bool NeedInnerParens = areParensNeededForStatement(SubExpr);
+  bool NeedInnerParens =
+  SubExpr != nullptr && 
utils::fixit::areParensNeededForStatement(*SubExpr);
   bool NeedOuterParens =
-  Parent != nullptr && areParensNeededForStatement(Parent);
+  Parent != nullptr && utils::fixit::areParensNeededForStatement(*Parent);
 
   std::string StartLocInsertion;
 
@@ -364,7 +341,7 @@ void ImplicitBoolConversionCheck::handleCastToBool(const 
ImplicitCastExpr *Cast,
 return;
   }
 
-  auto Diag = diag(Cast->getBeginLoc(), "implicit conversion %0 -> bool")
+  auto Diag = diag(Cast->getBeginLoc(), "implicit conversion %0 -> 'bool'")
   << Cast->getSubExpr()->getType();
 
   StringRef EquivalentLiteral =
@@ -381,7 +358,7 @@ void ImplicitBoolConversionCheck::handleCastFromBool(
 ASTContext &Context) {
   QualType DestType =
   NextImplicitCast ? NextImplicitCast->getType() : Cast->getType();
-  auto Diag = diag(Cast->getBeginLoc(), "implicit conversion bool -> %0")
+  auto Diag = diag(Cast->getBeginLoc(), "implicit conversion 'bool' -> %0")
   << DestType;
 
   if (const auto *BoolLiteral =

diff  --git a/clang-tools-extra/clang-tidy/utils/FixItHintUtils.cpp 
b/clang-tools-extra/clang-tidy/utils/FixItHintUtils.cpp
index 226dd60b5bf5f5..bbdd4326b0bac2 100644
--- a/clang-tools-extra/clang-tidy/utils/FixItHintUtils.cpp
+++ b/clang-tools-extra/clang-tidy/utils/FixItHintUtils.cpp
@@ -224,6 +224,40 @@ std::optional addQualifierToVarDecl(const 
VarDecl &Var,
   return std::nullopt;
 }
 
+bool areParensNeededForStatement(const Stmt &Node) {
+  if (isa(&Node))
+return false;
+
+  if (isa(&Node) || isa(&Node))
+return true;
+
+  if (isa(&Node) ||
+  isa(&Node))
+return true;
+
+  if (const auto *Op = dyn_cast(&Node)) {
+switch (Op->getOperator()) {
+case OO_PlusPlus:
+  [[fallthrough]];
+case OO_MinusMinus:
+  return Op->getNumArgs() != 2;
+case OO_Call:
+  [[fallthrough]];
+case OO_Subscript:
+  [[fallthrough]];
+case OO_Arrow:
+  return false;
+default:
+ 

[llvm] [clang-tools-extra] [clang-tidy] Fix missing parentheses in readability-implicit-bool-conversion fixes (PR #74891)

2024-01-16 Thread Piotr Zegar via cfe-commits

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


[llvm] [clang] [AMDGPU] Add global_load_tr for GFX12 (PR #77772)

2024-01-16 Thread Matt Arsenault via cfe-commits


@@ -18178,6 +18178,51 @@ Value *CodeGenFunction::EmitAMDGPUBuiltinExpr(unsigned 
BuiltinID,
 llvm::Function *F = CGM.getIntrinsic(IID, {ArgTy});
 return Builder.CreateCall(F, {Addr, Val, ZeroI32, ZeroI32, ZeroI1});
   }
+  case AMDGPU::BI__builtin_amdgcn_global_load_tr_b64_v2i32:
+  case AMDGPU::BI__builtin_amdgcn_global_load_tr_b64_i32:
+  case AMDGPU::BI__builtin_amdgcn_global_load_tr_b128_v8i16:
+  case AMDGPU::BI__builtin_amdgcn_global_load_tr_b128_v8f16:
+  case AMDGPU::BI__builtin_amdgcn_global_load_tr_b128_v4i16:
+  case AMDGPU::BI__builtin_amdgcn_global_load_tr_b128_v4f16: {
+
+Intrinsic::ID IID;
+llvm::Type *ArgTy;
+switch (BuiltinID) {
+case AMDGPU::BI__builtin_amdgcn_global_load_tr_b64_v2i32:
+  ArgTy = llvm::FixedVectorType::get(
+  llvm::Type::getInt32Ty(getLLVMContext()), 2);
+  IID = Intrinsic::amdgcn_global_load_tr_b64;

arsenm wrote:

No. Drop the global and use llvm_anyptr_ty 

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


[clang] [libcxx] [lld] [libc] [compiler-rt] [clang-tools-extra] [llvm] [flang] [lldb] [libcxxabi] [llvm-exegesis] Add support for validation counters (PR #76653)

2024-01-16 Thread Aiden Grossman via cfe-commits

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


[llvm] [clang] [AMDGPU] Add global_load_tr for GFX12 (PR #77772)

2024-01-16 Thread Piotr Sobczak via cfe-commits


@@ -18178,6 +18178,51 @@ Value *CodeGenFunction::EmitAMDGPUBuiltinExpr(unsigned 
BuiltinID,
 llvm::Function *F = CGM.getIntrinsic(IID, {ArgTy});
 return Builder.CreateCall(F, {Addr, Val, ZeroI32, ZeroI32, ZeroI1});
   }
+  case AMDGPU::BI__builtin_amdgcn_global_load_tr_b64_v2i32:
+  case AMDGPU::BI__builtin_amdgcn_global_load_tr_b64_i32:
+  case AMDGPU::BI__builtin_amdgcn_global_load_tr_b128_v8i16:
+  case AMDGPU::BI__builtin_amdgcn_global_load_tr_b128_v8f16:
+  case AMDGPU::BI__builtin_amdgcn_global_load_tr_b128_v4i16:
+  case AMDGPU::BI__builtin_amdgcn_global_load_tr_b128_v4f16: {
+
+Intrinsic::ID IID;
+llvm::Type *ArgTy;
+switch (BuiltinID) {
+case AMDGPU::BI__builtin_amdgcn_global_load_tr_b64_v2i32:
+  ArgTy = llvm::FixedVectorType::get(
+  llvm::Type::getInt32Ty(getLLVMContext()), 2);
+  IID = Intrinsic::amdgcn_global_load_tr_b64;

piotrAMD wrote:

Oh, I can see why doing this would be beneficial.

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


[clang] [llvm] [RISCV] CodeGen of RVE and ilp32e/lp64e ABIs (PR #76777)

2024-01-16 Thread Wang Pengcheng via cfe-commits

wangpc-pp wrote:

It's not easy to push this forward and thanks a lot!
I'll merge this soon. If there are some issues (hope not 😄), follow-up patches 
will fix them.

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


[clang-tools-extra] Add clang-tidy check to suggest replacement of conditional statement with std::min/std::max (PR #77816)

2024-01-16 Thread Bhuminjay Soni via cfe-commits


@@ -0,0 +1,121 @@
+// RUN: %check_clang_tidy %s readability-use-std-min-max %t
+
+constexpr int myConstexprMin(int a, int b) {
+  return a < b ? a : b;
+}
+
+constexpr int myConstexprMax(int a, int b) {
+  return a > b ? a : b;
+}
+
+int bar(int x, int y) {
+  return x < y ? x : y;
+}
+
+class MyClass {
+public:
+  int member1;
+  int member2;
+};
+
+void foo() {
+  int value1,value2,value3;
+  short value4;
+  MyClass obj;
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::max` instead of `<` 
[readability-use-std-min-max]
+  if (value1 < value2)
+value1 = value2; // CHECK-FIXES: value1 = std::max(value1, value2);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::min` instead of `<` 
[readability-use-std-min-max]
+  if (value1 < value2)
+value2 = value1; // CHECK-FIXES: value2 = std::min(value1, value2);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::min` instead of `>` 
[readability-use-std-min-max]
+  if (value2 > value1)
+value2 = value1; // CHECK-FIXES: value2 = std::min(value2, value1);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::max` instead of `>` 
[readability-use-std-min-max
+  if (value2 > value1)
+value1 = value2; // CHECK-FIXES: value1 = std::max(value2, value1);
+
+  // No suggestion needed here
+  if (value1 == value2)
+value1 = value2;
+  
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::max` instead of `<` 
[readability-use-std-min-max]
+  if(value1` 
[readability-use-std-min-max]
+  if (value1 > myConstexprMax(value2, value3))
+value1 = myConstexprMax(value2, value3); // CHECK-FIXES: value1 = 
std::min(value1, myConstexprMax(value2, value3));
+  
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::max` instead of `<` 
[readability-use-std-min-max]
+  if (value1 < bar(value2, value3))
+value1 = bar(value2, value3); // CHECK-FIXES: value1 = std::max(value1, 
bar(value2, value3));
+  
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::min` instead of `<=` 
[readability-use-std-min-max]
+  if (value1 <= value2)
+value2 = value1; // CHECK-FIXES: value2 = std::min(value1, value2);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::max` instead of `<=` 
[readability-use-std-min-max]
+  if (value1 <= value2)
+value1 = value2; // CHECK-FIXES: value1 = std::max(value1, value2);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::max` instead of `>=` 
[readability-use-std-min-max]
+  if (value2 >= value1)
+value1 = value2; // CHECK-FIXES: value1 = std::max(value2, value1);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::min` instead of `>=` 
[readability-use-std-min-max]
+  if (value2 >= value1)
+value2 = value1; // CHECK-FIXES: value2 = std::min(value2, value1);
+  
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::max` instead of `<` 
[readability-use-std-min-max]
+  if (obj.member1 < obj.member2)
+obj.member1 = obj.member2; // CHECK-FIXES: obj.member1 = 
std::max(obj.member1, obj.member2);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::min` instead of `<` 
[readability-use-std-min-max]
+  if (obj.member1 < obj.member2)
+obj.member2 = obj.member1; // CHECK-FIXES: obj.member2 = 
std::min(obj.member1, obj.member2);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::min` instead of `>` 
[readability-use-std-min-max]
+  if (obj.member2 > obj.member1)
+obj.member2 = obj.member1; // CHECK-FIXES: obj.member2 = 
std::min(obj.member2, obj.member1);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::max` instead of `>` 
[readability-use-std-min-max]
+  if (obj.member2 > obj.member1)
+obj.member1 = obj.member2; // CHECK-FIXES: obj.member1 = 
std::max(obj.member2, obj.member1);
+  
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::max` instead of `<` 
[readability-use-std-min-max]
+  if (obj.member1 < value4)
+obj.member1 = value4; // CHECK-FIXES: obj.member1 = std::max(obj.member1, 
value4);
+  
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::min` instead of `<` 
[readability-use-std-min-max]
+  if (obj.member1 + value2 < value3)
+value3 = obj.member1 + value2; // CHECK-FIXES: value3 = 
std::min(obj.member1 + value2, value3);
+  
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::min` instead of `<=` 
[readability-use-std-min-max]
+  if (value1 <= obj.member2)
+obj.member2 = value1; // CHECK-FIXES: obj.member2 = std::min(value1, 
obj.member2);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::max` instead of `<=` 
[readability-use-std-min-max]
+  if (value1 <= obj.member2)
+value1 = obj.member2; // CHECK-FIXES: value1 = std::max(value1, 
obj.member2);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::max` instead of `>=` 
[readability-use-std-min-max]
+  if (obj.member2 >= value1)
+value1 = obj.member2; // CHECK-FIXES: value1 = std::max(obj.member2, 
value1);
+
+  // CHECK-MESSAGES: :[[@LINE+1]]:3: warning: use `std::min` instead of `>=` 
[readability

[clang] Improve modeling of two functions in StdLibraryFunctionsChecker (PR #78079)

2024-01-16 Thread Balázs Kéri via cfe-commits


@@ -248,3 +248,25 @@ void check_fflush_all(void) {
 if (errno) {}// no-warning
   }
 }
+
+void check_opendir(const char *Path) {
+  DIR *Dir = opendir(Path);
+  if (Dir == NULL) {
+clang_analyzer_eval(errno != 0); // expected-warning{{TRUE}}
+if (errno) {}// no-warning
+  } else {
+if (errno) {}// expected-warning{{An undefined value 
may be read from 'errno'}}
+closedir(Dir);
+  }
+}
+
+void check_fdopendir(int Fd) {
+  DIR *Dir = fdopendir(Fd);
+  if (Dir == NULL) {
+clang_analyzer_eval(errno != 0); // expected-warning{{TRUE}}
+if (errno) {}// no-warning
+  } else {
+if (errno) {}// expected-warning{{An undefined value 
may be read from 'errno'}}
+closedir(Dir);
+  }
+}

balazske wrote:

They need no tests like there is no test for `chdir`, `chown`, `close`, `open`, 
and all other functions in the checker. These `DIR` type functions are not more 
special than the others. It can be possible to add these `errno` tests for all 
of the functions in a separate file and in a generated way. The tests in 
**stream_*** files are related to `StreamChecker`, but not the `DIR` functions. 
(Goal of `StreamChecker` is now only to work with the functions with `FILE*` 
argument.)

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


[llvm] [clang] [clang-tools-extra] [PowerPC] Peephole address calculation in TOC memops (PR #76488)

2024-01-16 Thread Qiu Chaofan via cfe-commits

https://github.com/ecnelises updated 
https://github.com/llvm/llvm-project/pull/76488

>From 7eb909423d49ea19d9978b097ceb8c4a95fc7bac Mon Sep 17 00:00:00 2001
From: Qiu Chaofan 
Date: Thu, 28 Dec 2023 11:09:07 +0800
Subject: [PATCH 1/3] [PowerPC] Peephole address calculation in TOC memops

---
 llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp   | 391 +-
 llvm/test/CodeGen/PowerPC/toc-data-const.ll   |  45 +-
 .../PowerPC/toc-data-peephole-aligment.ll |  16 +
 llvm/test/CodeGen/PowerPC/toc-data.ll |  22 +-
 4 files changed, 253 insertions(+), 221 deletions(-)
 create mode 100644 llvm/test/CodeGen/PowerPC/toc-data-peephole-aligment.ll

diff --git a/llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp 
b/llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp
index b57d185bb638b8c..c96bf3204a32edf 100644
--- a/llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp
+++ b/llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp
@@ -7567,224 +7567,233 @@ static void reduceVSXSwap(SDNode *N, SelectionDAG 
*DAG) {
   DAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), N->getOperand(0));
 }
 
-void PPCDAGToDAGISel::PeepholePPC64() {
-  SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end();
-
-  while (Position != CurDAG->allnodes_begin()) {
-SDNode *N = &*--Position;
-// Skip dead nodes and any non-machine opcodes.
-if (N->use_empty() || !N->isMachineOpcode())
-  continue;
-
-if (isVSXSwap(SDValue(N, 0)))
-  reduceVSXSwap(N, CurDAG);
-
-unsigned FirstOp;
-unsigned StorageOpcode = N->getMachineOpcode();
-bool RequiresMod4Offset = false;
+static void peepholeMemOffset(SDNode *N, SelectionDAG *DAG,
+  const PPCSubtarget *Subtarget) {
+  unsigned StorageOpcode = N->getMachineOpcode();
+  bool IsLoad = false;
+  SDValue MemOffset, MemBase;
+  bool IsToc = false;
+
+  // TODO: Enable for AIX 32-bit
+  if (!Subtarget->isPPC64())
+return;
 
-switch (StorageOpcode) {
-default: continue;
+  // Global must be word-aligned for LD, STD, LWA.
+  unsigned ExtraAlign = 0;
+  switch (StorageOpcode) {
+  default:
+return;
+  case PPC::LWA:
+  case PPC::LD:
+  case PPC::DFLOADf64:
+  case PPC::DFLOADf32:
+ExtraAlign = 4;
+[[fallthrough]];
+  case PPC::LBZ:
+  case PPC::LBZ8:
+  case PPC::LFD:
+  case PPC::LFS:
+  case PPC::LHA:
+  case PPC::LHA8:
+  case PPC::LHZ:
+  case PPC::LHZ8:
+  case PPC::LWZ:
+  case PPC::LWZ8:
+IsLoad = true;
+MemOffset = N->getOperand(0);
+MemBase = N->getOperand(1);
+break;
+  case PPC::STD:
+  case PPC::DFSTOREf64:
+  case PPC::DFSTOREf32:
+ExtraAlign = 4;
+[[fallthrough]];
+  case PPC::STB:
+  case PPC::STB8:
+  case PPC::STFD:
+  case PPC::STFS:
+  case PPC::STH:
+  case PPC::STH8:
+  case PPC::STW:
+  case PPC::STW8:
+MemOffset = N->getOperand(1);
+MemBase = N->getOperand(2);
+break;
+  }
 
-case PPC::LWA:
-case PPC::LD:
-case PPC::DFLOADf64:
-case PPC::DFLOADf32:
-  RequiresMod4Offset = true;
-  [[fallthrough]];
-case PPC::LBZ:
-case PPC::LBZ8:
-case PPC::LFD:
-case PPC::LFS:
-case PPC::LHA:
-case PPC::LHA8:
-case PPC::LHZ:
-case PPC::LHZ8:
-case PPC::LWZ:
-case PPC::LWZ8:
-  FirstOp = 0;
-  break;
+  // Only constant offsets can be folded.
+  if (!isa(MemOffset) || !MemBase.isMachineOpcode())
+return;
 
-case PPC::STD:
-case PPC::DFSTOREf64:
-case PPC::DFSTOREf32:
-  RequiresMod4Offset = true;
-  [[fallthrough]];
-case PPC::STB:
-case PPC::STB8:
-case PPC::STFD:
-case PPC::STFS:
-case PPC::STH:
-case PPC::STH8:
-case PPC::STW:
-case PPC::STW8:
-  FirstOp = 1;
-  break;
+  auto CheckAlign = [DAG](const SDValue &Val, unsigned TargetAlign) {
+if (TargetAlign == 0)
+  return true;
+if (GlobalAddressSDNode *GA = dyn_cast(Val)) {
+  const GlobalValue *GV = GA->getGlobal();
+  Align Alignment = GV->getPointerAlignment(DAG->getDataLayout());
+  if (Alignment < TargetAlign)
+return false;
 }
+return true;
+  };
 
-// If this is a load or store with a zero offset, or within the alignment,
-// we may be able to fold an add-immediate into the memory operation.
-// The check against alignment is below, as it can't occur until we check
-// the arguments to N
-if (!isa(N->getOperand(FirstOp)))
-  continue;
-
-SDValue Base = N->getOperand(FirstOp + 1);
-if (!Base.isMachineOpcode())
-  continue;
+  // We may need to carry relocation information in ADDI to load.
+  std::optional NewOpFlags;
+  switch (MemBase.getMachineOpcode()) {
+  default:
+return;
+  case PPC::ADDI8:
+  case PPC::ADDI:
+// In some cases (such as TLS) the relocation information
+// is already in place on the operand, so copying the operand
+// is sufficient.
+break;
+  case PPC::ADDIdtprelL:
+NewOpFlags = PPCII::MO_DTPREL_LO;
+break;
+  case PPC::ADDItlsldL:
+NewOpFlags = PPCII::MO_TLSLD_LO;
+break

[clang] Improve modeling of two functions in StdLibraryFunctionsChecker (PR #78079)

2024-01-16 Thread Balázs Kéri via cfe-commits

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


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


[clang] [llvm] [clang-tools-extra] [PowerPC] Peephole address calculation in TOC memops (PR #76488)

2024-01-16 Thread Qiu Chaofan via cfe-commits

https://github.com/ecnelises updated 
https://github.com/llvm/llvm-project/pull/76488

>From 7eb909423d49ea19d9978b097ceb8c4a95fc7bac Mon Sep 17 00:00:00 2001
From: Qiu Chaofan 
Date: Thu, 28 Dec 2023 11:09:07 +0800
Subject: [PATCH 1/4] [PowerPC] Peephole address calculation in TOC memops

---
 llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp   | 391 +-
 llvm/test/CodeGen/PowerPC/toc-data-const.ll   |  45 +-
 .../PowerPC/toc-data-peephole-aligment.ll |  16 +
 llvm/test/CodeGen/PowerPC/toc-data.ll |  22 +-
 4 files changed, 253 insertions(+), 221 deletions(-)
 create mode 100644 llvm/test/CodeGen/PowerPC/toc-data-peephole-aligment.ll

diff --git a/llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp 
b/llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp
index b57d185bb638b8..c96bf3204a32ed 100644
--- a/llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp
+++ b/llvm/lib/Target/PowerPC/PPCISelDAGToDAG.cpp
@@ -7567,224 +7567,233 @@ static void reduceVSXSwap(SDNode *N, SelectionDAG 
*DAG) {
   DAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), N->getOperand(0));
 }
 
-void PPCDAGToDAGISel::PeepholePPC64() {
-  SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end();
-
-  while (Position != CurDAG->allnodes_begin()) {
-SDNode *N = &*--Position;
-// Skip dead nodes and any non-machine opcodes.
-if (N->use_empty() || !N->isMachineOpcode())
-  continue;
-
-if (isVSXSwap(SDValue(N, 0)))
-  reduceVSXSwap(N, CurDAG);
-
-unsigned FirstOp;
-unsigned StorageOpcode = N->getMachineOpcode();
-bool RequiresMod4Offset = false;
+static void peepholeMemOffset(SDNode *N, SelectionDAG *DAG,
+  const PPCSubtarget *Subtarget) {
+  unsigned StorageOpcode = N->getMachineOpcode();
+  bool IsLoad = false;
+  SDValue MemOffset, MemBase;
+  bool IsToc = false;
+
+  // TODO: Enable for AIX 32-bit
+  if (!Subtarget->isPPC64())
+return;
 
-switch (StorageOpcode) {
-default: continue;
+  // Global must be word-aligned for LD, STD, LWA.
+  unsigned ExtraAlign = 0;
+  switch (StorageOpcode) {
+  default:
+return;
+  case PPC::LWA:
+  case PPC::LD:
+  case PPC::DFLOADf64:
+  case PPC::DFLOADf32:
+ExtraAlign = 4;
+[[fallthrough]];
+  case PPC::LBZ:
+  case PPC::LBZ8:
+  case PPC::LFD:
+  case PPC::LFS:
+  case PPC::LHA:
+  case PPC::LHA8:
+  case PPC::LHZ:
+  case PPC::LHZ8:
+  case PPC::LWZ:
+  case PPC::LWZ8:
+IsLoad = true;
+MemOffset = N->getOperand(0);
+MemBase = N->getOperand(1);
+break;
+  case PPC::STD:
+  case PPC::DFSTOREf64:
+  case PPC::DFSTOREf32:
+ExtraAlign = 4;
+[[fallthrough]];
+  case PPC::STB:
+  case PPC::STB8:
+  case PPC::STFD:
+  case PPC::STFS:
+  case PPC::STH:
+  case PPC::STH8:
+  case PPC::STW:
+  case PPC::STW8:
+MemOffset = N->getOperand(1);
+MemBase = N->getOperand(2);
+break;
+  }
 
-case PPC::LWA:
-case PPC::LD:
-case PPC::DFLOADf64:
-case PPC::DFLOADf32:
-  RequiresMod4Offset = true;
-  [[fallthrough]];
-case PPC::LBZ:
-case PPC::LBZ8:
-case PPC::LFD:
-case PPC::LFS:
-case PPC::LHA:
-case PPC::LHA8:
-case PPC::LHZ:
-case PPC::LHZ8:
-case PPC::LWZ:
-case PPC::LWZ8:
-  FirstOp = 0;
-  break;
+  // Only constant offsets can be folded.
+  if (!isa(MemOffset) || !MemBase.isMachineOpcode())
+return;
 
-case PPC::STD:
-case PPC::DFSTOREf64:
-case PPC::DFSTOREf32:
-  RequiresMod4Offset = true;
-  [[fallthrough]];
-case PPC::STB:
-case PPC::STB8:
-case PPC::STFD:
-case PPC::STFS:
-case PPC::STH:
-case PPC::STH8:
-case PPC::STW:
-case PPC::STW8:
-  FirstOp = 1;
-  break;
+  auto CheckAlign = [DAG](const SDValue &Val, unsigned TargetAlign) {
+if (TargetAlign == 0)
+  return true;
+if (GlobalAddressSDNode *GA = dyn_cast(Val)) {
+  const GlobalValue *GV = GA->getGlobal();
+  Align Alignment = GV->getPointerAlignment(DAG->getDataLayout());
+  if (Alignment < TargetAlign)
+return false;
 }
+return true;
+  };
 
-// If this is a load or store with a zero offset, or within the alignment,
-// we may be able to fold an add-immediate into the memory operation.
-// The check against alignment is below, as it can't occur until we check
-// the arguments to N
-if (!isa(N->getOperand(FirstOp)))
-  continue;
-
-SDValue Base = N->getOperand(FirstOp + 1);
-if (!Base.isMachineOpcode())
-  continue;
+  // We may need to carry relocation information in ADDI to load.
+  std::optional NewOpFlags;
+  switch (MemBase.getMachineOpcode()) {
+  default:
+return;
+  case PPC::ADDI8:
+  case PPC::ADDI:
+// In some cases (such as TLS) the relocation information
+// is already in place on the operand, so copying the operand
+// is sufficient.
+break;
+  case PPC::ADDIdtprelL:
+NewOpFlags = PPCII::MO_DTPREL_LO;
+break;
+  case PPC::ADDItlsldL:
+NewOpFlags = PPCII::MO_TLSLD_LO;
+break;

[llvm] [clang] [mlir] [clang-tools-extra] [ASan][AMDGPU] Fix Assertion Failure. (PR #78242)

2024-01-16 Thread Matt Arsenault via cfe-commits


@@ -1254,9 +1254,11 @@ Value *AddressSanitizer::memToShadow(Value *Shadow, 
IRBuilder<> &IRB) {
 void AddressSanitizer::instrumentMemIntrinsic(MemIntrinsic *MI) {
   InstrumentationIRBuilder IRB(MI);
   if (isa(MI)) {
-IRB.CreateCall(isa(MI) ? AsanMemmove : AsanMemcpy,
-   {MI->getOperand(0), MI->getOperand(1),
-IRB.CreateIntCast(MI->getOperand(2), IntptrTy, false)});
+IRB.CreateCall(
+isa(MI) ? AsanMemmove : AsanMemcpy,
+{MI->getOperand(0),
+ IRB.CreatePointerBitCastOrAddrSpaceCast(MI->getOperand(1), PtrTy),

arsenm wrote:

No reason to create pointer bit casts anymore. Just CreateAddrSpaceCast? 

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


[clang] [clang][analyzer] Add function 'fscanf' to StreamChecker. (PR #78180)

2024-01-16 Thread Balázs Kéri via cfe-commits

https://github.com/balazske updated 
https://github.com/llvm/llvm-project/pull/78180

From aacfc3f06ee51ede08464cb23ec32b210e703b6b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Bal=C3=A1zs=20K=C3=A9ri?= 
Date: Mon, 15 Jan 2024 16:41:34 +0100
Subject: [PATCH 1/2] [clang][analyzer] Add function 'fscanf' to StreamChecker.

---
 .../StaticAnalyzer/Checkers/StreamChecker.cpp | 61 +++
 clang/test/Analysis/stream-error.c| 25 
 clang/test/Analysis/stream.c  |  6 ++
 3 files changed, 92 insertions(+)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index 95c7503e49e0d3..ab23a428e9397f 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -266,6 +266,9 @@ class StreamChecker : public Checker(Call.getOriginExpr());
+  if (!CE)
+return;
+
+  const StreamState *OldSS = State->get(StreamSym);
+  if (!OldSS)
+return;
+
+  assertStreamStateOpened(OldSS);
+
+  SValBuilder &SVB = C.getSValBuilder();
+  ASTContext &ACtx = C.getASTContext();
+
+  if (OldSS->ErrorState != ErrorFEof) {
+NonLoc RetVal = makeRetVal(C, CE).castAs();
+ProgramStateRef StateNotFailed =
+State->BindExpr(CE, C.getLocationContext(), RetVal);
+auto RetGeZero =
+SVB.evalBinOp(StateNotFailed, BO_GE, RetVal,
+  SVB.makeZeroVal(ACtx.IntTy), SVB.getConditionType())
+.getAs();
+if (!RetGeZero)
+  return;
+StateNotFailed = StateNotFailed->assume(*RetGeZero, true);
+
+C.addTransition(StateNotFailed);
+  }
+
+  // Add transition for the failed state.
+  // Error occurs if nothing is matched yet and reading the input fails.
+  // Error can be EOF, or other error. At "other error" FERROR or 'errno' can
+  // be set but it is not further specified if all are required to be set.
+  // Documentation does not mention, but file position will be set to
+  // indeterminate similarly as at 'fread'.
+  ProgramStateRef StateFailed = bindInt(*EofVal, State, C, CE);
+  StreamErrorState NewES = (OldSS->ErrorState == ErrorFEof)
+   ? ErrorFEof
+   : ErrorNone | ErrorFEof | ErrorFError;
+  StreamState NewSS = StreamState::getOpened(Desc, NewES, !NewES.isFEof());
+  StateFailed = StateFailed->set(StreamSym, NewSS);
+  if (OldSS->ErrorState != ErrorFEof)
+C.addTransition(StateFailed, constructSetEofNoteTag(C, StreamSym));
+  else
+C.addTransition(StateFailed);
+}
+
 void StreamChecker::evalUngetc(const FnDescription *Desc, const CallEvent 
&Call,
CheckerContext &C) const {
   ProgramStateRef State = C.getState();
diff --git a/clang/test/Analysis/stream-error.c 
b/clang/test/Analysis/stream-error.c
index 0f7fdddc0dd4cd..2cf46e1d4ad51f 100644
--- a/clang/test/Analysis/stream-error.c
+++ b/clang/test/Analysis/stream-error.c
@@ -208,6 +208,31 @@ void error_fprintf(void) {
   fprintf(F, "ccc"); // expected-warning {{Stream might be already closed}}
 }
 
+void error_fscanf(int *A) {
+  FILE *F = tmpfile();
+  if (!F)
+return;
+  int Ret = fscanf(F, "a%ib", A);
+  if (Ret >= 0) {
+clang_analyzer_eval(feof(F) || ferror(F)); // expected-warning {{FALSE}}
+fscanf(F, "bbb");  // no-warning
+  } else {
+if (ferror(F)) {
+  clang_analyzer_warnIfReached(); // expected-warning {{REACHABLE}}
+  fscanf(F, "bbb");   // expected-warning {{might be 
'indeterminate'}}
+} else if (feof(F)) {
+  clang_analyzer_warnIfReached(); // expected-warning {{REACHABLE}}
+  fscanf(F, "bbb");   // expected-warning {{is in EOF state}}
+  clang_analyzer_eval(feof(F));   // expected-warning {{TRUE}}
+} else {
+  clang_analyzer_warnIfReached(); // expected-warning {{REACHABLE}}
+  fscanf(F, "bbb");   // expected-warning {{might be 
'indeterminate'}}
+}
+  }
+  fclose(F);
+  fscanf(F, "ccc"); // expected-warning {{Stream might be already closed}}
+}
+
 void error_ungetc() {
   FILE *F = tmpfile();
   if (!F)
diff --git a/clang/test/Analysis/stream.c b/clang/test/Analysis/stream.c
index e8f06922bdb2f3..36a9b4e26b07a2 100644
--- a/clang/test/Analysis/stream.c
+++ b/clang/test/Analysis/stream.c
@@ -45,6 +45,12 @@ void check_fprintf(void) {
   fclose(fp);
 }
 
+void check_fscanf(void) {
+  FILE *fp = tmpfile();
+  fscanf(fp, "ABC"); // expected-warning {{Stream pointer might be NULL}}
+  fclose(fp);
+}
+
 void check_ungetc(void) {
   FILE *fp = tmpfile();
   ungetc('A', fp); // expected-warning {{Stream pointer might be NULL}}

From 128b59ebe046994f38f2e488ce44e891c0b1b0d4 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Bal=C3=A1zs=20K=C3=A9ri?= 
Date: Tue, 16 Jan 2024 11:27:44 +0100
Subject: [PATCH 2/2] added clarifying comment

---
 clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp | 8 
 1 file changed, 8 insertions(+)

diff --git a/clang/l

[clang] 289999b - [Clang] Make sdot builtins available to SME (#77792)

2024-01-16 Thread via cfe-commits

Author: Sander de Smalen
Date: 2024-01-16T10:32:30Z
New Revision: 28bad76e34441a3a43f4bf32e028b43fad93

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

LOG: [Clang] Make sdot builtins available to SME (#77792)

See the specification for more details:
*
https://github.com/ARM-software/acle/blob/main/main/acle.md#udot-sdot-fdot-vectors
*
https://github.com/ARM-software/acle/blob/main/main/acle.md#udot-sdot-fdot-indexed

Added: 


Modified: 
clang/include/clang/Basic/arm_sve.td
clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_dot.c
llvm/test/CodeGen/AArch64/sve2p1-intrinsics-dots.ll

Removed: 




diff  --git a/clang/include/clang/Basic/arm_sve.td 
b/clang/include/clang/Basic/arm_sve.td
index 838a1e042100db..02039524c41dc5 100644
--- a/clang/include/clang/Basic/arm_sve.td
+++ b/clang/include/clang/Basic/arm_sve.td
@@ -2045,13 +2045,13 @@ let TargetGuard = "sve2p1|sme2" in {
   defm STNT1 : MultiVecStore<"stnt1">;
 }
 
-let TargetGuard = "sve2p1" in {
-def SVDOT_X2_S : SInst<"svdot[_{d}_{2}]", "ddhh", "i",  MergeNone, 
"aarch64_sve_sdot_x2", [], []>;
-def SVDOT_X2_U : SInst<"svdot[_{d}_{2}]", "ddhh", "Ui", MergeNone, 
"aarch64_sve_udot_x2", [], []>;
-def SVDOT_X2_F : SInst<"svdot[_{d}_{2}]", "ddhh", "f",  MergeNone, 
"aarch64_sve_fdot_x2", [], []>;
-def SVDOT_LANE_X2_S : SInst<"svdot_lane[_{d}_{2}]", "ddhhi", "i",  MergeNone, 
"aarch64_sve_sdot_lane_x2", [], [ImmCheck<3, ImmCheck0_3>]>;
-def SVDOT_LANE_X2_U : SInst<"svdot_lane[_{d}_{2}]", "ddhhi", "Ui", MergeNone, 
"aarch64_sve_udot_lane_x2", [], [ImmCheck<3, ImmCheck0_3>]>;
-def SVDOT_LANE_X2_F : SInst<"svdot_lane[_{d}_{2}]", "ddhhi", "f",  MergeNone, 
"aarch64_sve_fdot_lane_x2", [], [ImmCheck<3, ImmCheck0_3>]>;
+let TargetGuard = "sve2p1|sme2" in {
+def SVDOT_X2_S : SInst<"svdot[_{d}_{2}]", "ddhh", "i",  MergeNone, 
"aarch64_sve_sdot_x2", [IsStreamingOrSVE2p1], []>;
+def SVDOT_X2_U : SInst<"svdot[_{d}_{2}]", "ddhh", "Ui", MergeNone, 
"aarch64_sve_udot_x2", [IsStreamingOrSVE2p1], []>;
+def SVDOT_X2_F : SInst<"svdot[_{d}_{2}]", "ddhh", "f",  MergeNone, 
"aarch64_sve_fdot_x2", [IsStreamingOrSVE2p1], []>;
+def SVDOT_LANE_X2_S : SInst<"svdot_lane[_{d}_{2}]", "ddhhi", "i",  MergeNone, 
"aarch64_sve_sdot_lane_x2", [IsStreamingOrSVE2p1], [ImmCheck<3, ImmCheck0_3>]>;
+def SVDOT_LANE_X2_U : SInst<"svdot_lane[_{d}_{2}]", "ddhhi", "Ui", MergeNone, 
"aarch64_sve_udot_lane_x2", [IsStreamingOrSVE2p1], [ImmCheck<3, ImmCheck0_3>]>;
+def SVDOT_LANE_X2_F : SInst<"svdot_lane[_{d}_{2}]", "ddhhi", "f",  MergeNone, 
"aarch64_sve_fdot_lane_x2", [IsStreamingOrSVE2p1], [ImmCheck<3, ImmCheck0_3>]>;
 }
 
 let TargetGuard = "sve2p1|sme2" in {

diff  --git a/clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_dot.c 
b/clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_dot.c
index 035ba244f9441e..97099c1f1061c7 100644
--- a/clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_dot.c
+++ b/clang/test/CodeGen/aarch64-sve2p1-intrinsics/acle_sve2p1_dot.c
@@ -2,11 +2,20 @@
 // REQUIRES: aarch64-registered-target
 // RUN: %clang_cc1 -fclang-abi-compat=latest -triple aarch64-none-linux-gnu 
-target-feature +sve2p1 -S -disable-O0-optnone -Werror -Wall -emit-llvm -o - %s 
| opt -S -p mem2reg,instcombine,tailcallelim | FileCheck %s
 // RUN: %clang_cc1 -fclang-abi-compat=latest -triple aarch64-none-linux-gnu 
-target-feature +sve2p1 -S -disable-O0-optnone -Werror -Wall -emit-llvm -o - -x 
c++ %s | opt -S -p mem2reg,instcombine,tailcallelim | FileCheck %s 
-check-prefix=CPP-CHECK
+// RUN: %clang_cc1 -fclang-abi-compat=latest -triple aarch64-none-linux-gnu 
-target-feature +sme2 -DTEST_SME2 -S -disable-O0-optnone -Werror -Wall 
-emit-llvm -o - %s | opt -S -p mem2reg,instcombine,tailcallelim | FileCheck %s
+// RUN: %clang_cc1 -fclang-abi-compat=latest -triple aarch64-none-linux-gnu 
-target-feature +sme2 -DTEST_SME2 -S -disable-O0-optnone -Werror -Wall 
-emit-llvm -o - -x c++ %s | opt -S -p mem2reg,instcombine,tailcallelim | 
FileCheck %s -check-prefix=CPP-CHECK
 // RUN: %clang_cc1 -fclang-abi-compat=latest -DSVE_OVERLOADED_FORMS -triple 
aarch64-none-linux-gnu -target-feature +sve2p1 -S -disable-O0-optnone -Werror 
-Wall -emit-llvm -o - %s | opt -S -p mem2reg,instcombine,tailcallelim | 
FileCheck %s
 // RUN: %clang_cc1 -fclang-abi-compat=latest -DSVE_OVERLOADED_FORMS -triple 
aarch64-none-linux-gnu -target-feature +sve2p1 -S -disable-O0-optnone -Werror 
-Wall -emit-llvm -o - -x c++ %s | opt -S -p mem2reg,instcombine,tailcallelim | 
FileCheck %s -check-prefix=CPP-CHECK
 // RUN: %clang_cc1 -fclang-abi-compat=latest -triple aarch64-none-linux-gnu 
-target-feature +sve2p1 -S -disable-O0-optnone -Werror -Wall -o /dev/null %s
+// RUN: %clang_cc1 -fclang-abi-compat=latest -triple aarch64-none-linux-gnu 
-target-feature +sme2 -DTEST_SME2 -S -disa

[clang] [llvm] [Clang] Make sdot builtins available to SME (PR #77792)

2024-01-16 Thread Sander de Smalen via cfe-commits

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


[clang] [cfi][CodeGen] Call SetLLVMFunctionAttributes{, ForDefinition} on __cf… (PR #78253)

2024-01-16 Thread Pavel Kosov via cfe-commits

https://github.com/kpdev created https://github.com/llvm/llvm-project/pull/78253

…i_check

This causes __cfi_check, just as __cfi_check_fail, to get the proper 
target-specific attributes, in particular uwtable for unwind table generation. 
Previously, nounwind attribute could be inferred for __cfi_check, which caused 
it to lose its unwind table even with -funwind-table option.

~~

Huawei RRI, OS Lab

>From 52857187c20b4bfb8c2ef0b5c235f95d8577ac1c Mon Sep 17 00:00:00 2001
From: Nikolai Kholiavin 
Date: Wed, 20 Dec 2023 16:19:03 +
Subject: [PATCH] [cfi][CodeGen] Call SetLLVMFunctionAttributes{,ForDefinition}
 on __cfi_check

This causes __cfi_check, just as __cfi_check_fail, to get the proper
target-specific attributes, in particular uwtable for unwind table
generation. Previously, nounwind attribute could be inferred for
__cfi_check, which caused it to lose its unwind table even with
-funwind-table option.

Change-Id: I0e081996f673761f8fcdf1c61a08f7b59d70917b
---
 clang/lib/CodeGen/CGExpr.cpp | 19 ++-
 clang/test/CodeGen/cfi-check-attrs.c |  5 +
 clang/test/CodeGen/cfi-check-fail.c  |  2 +-
 3 files changed, 24 insertions(+), 2 deletions(-)
 create mode 100644 clang/test/CodeGen/cfi-check-attrs.c

diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index 3f277725d9e7fc..c430acc3a3c960 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -3443,11 +3443,28 @@ void CodeGenFunction::EmitCfiSlowPathCheck(
 void CodeGenFunction::EmitCfiCheckStub() {
   llvm::Module *M = &CGM.getModule();
   auto &Ctx = M->getContext();
+  auto &C = getContext();
+  QualType QInt64Ty = C.getIntTypeForBitwidth(64, false);
+
+  FunctionArgList FnArgs;
+  ImplicitParamDecl ArgCallsiteTypeId(C, QInt64Ty, ImplicitParamKind::Other);
+  ImplicitParamDecl ArgAddr(C, C.VoidPtrTy, ImplicitParamKind::Other);
+  ImplicitParamDecl ArgCFICheckFailData(C, C.VoidPtrTy,
+ImplicitParamKind::Other);
+  FnArgs.push_back(&ArgCallsiteTypeId);
+  FnArgs.push_back(&ArgAddr);
+  FnArgs.push_back(&ArgCFICheckFailData);
+  const CGFunctionInfo &FI =
+  CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, FnArgs);
+
   llvm::Function *F = llvm::Function::Create(
-  llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false),
+  llvm::FunctionType::get(VoidTy, {Int64Ty, VoidPtrTy, VoidPtrTy}, false),
   llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
+  CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, F, /*IsThunk=*/false);
+  CGM.SetLLVMFunctionAttributesForDefinition(nullptr, F);
   F->setAlignment(llvm::Align(4096));
   CGM.setDSOLocal(F);
+
   llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
   // CrossDSOCFI pass is not executed if there is no executable code.
   SmallVector Args{F->getArg(2), F->getArg(1)};
diff --git a/clang/test/CodeGen/cfi-check-attrs.c 
b/clang/test/CodeGen/cfi-check-attrs.c
new file mode 100644
index 00..375aa30074d887
--- /dev/null
+++ b/clang/test/CodeGen/cfi-check-attrs.c
@@ -0,0 +1,5 @@
+// RUN: %clang_cc1 -triple arm-unknown-linux -funwind-tables=1 
-fsanitize-cfi-cross-dso -emit-llvm -o - %s | FileCheck %s
+
+// CHECK: define weak {{.*}}void @__cfi_check({{.*}} [[ATTR:#[0-9]*]]
+
+// CHECK: attributes [[ATTR]] = {{.*}} uwtable(sync)
diff --git a/clang/test/CodeGen/cfi-check-fail.c 
b/clang/test/CodeGen/cfi-check-fail.c
index 2f12cee9dec602..15f6c77abf2b20 100644
--- a/clang/test/CodeGen/cfi-check-fail.c
+++ b/clang/test/CodeGen/cfi-check-fail.c
@@ -72,7 +72,7 @@ void caller(void (*f)(void)) {
 // CHECK: [[CONT5]]:
 // CHECK:   ret void
 
-// CHECK: define weak void @__cfi_check(i64 %[[TYPE:.*]], ptr %[[ADDR:.*]], 
ptr %[[DATA:.*]]) align 4096
+// CHECK: define weak void @__cfi_check(i64 noundef %[[TYPE:.*]], ptr noundef 
%[[ADDR:.*]], ptr noundef %[[DATA:.*]]){{.*}} align 4096
 // CHECK-NOT: }
 // CHECK: call void @__cfi_check_fail(ptr %[[DATA]], ptr %[[ADDR]])
 // CHECK-NEXT: ret void

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


[clang] [cfi][CodeGen] Call SetLLVMFunctionAttributes{, ForDefinition} on __cf… (PR #78253)

2024-01-16 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-codegen

Author: Pavel Kosov (kpdev)


Changes

…i_check

This causes __cfi_check, just as __cfi_check_fail, to get the proper 
target-specific attributes, in particular uwtable for unwind table generation. 
Previously, nounwind attribute could be inferred for __cfi_check, which caused 
it to lose its unwind table even with -funwind-table option.

~~

Huawei RRI, OS Lab

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


3 Files Affected:

- (modified) clang/lib/CodeGen/CGExpr.cpp (+18-1) 
- (added) clang/test/CodeGen/cfi-check-attrs.c (+5) 
- (modified) clang/test/CodeGen/cfi-check-fail.c (+1-1) 


``diff
diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index 3f277725d9e7fc2..c430acc3a3c9603 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -3443,11 +3443,28 @@ void CodeGenFunction::EmitCfiSlowPathCheck(
 void CodeGenFunction::EmitCfiCheckStub() {
   llvm::Module *M = &CGM.getModule();
   auto &Ctx = M->getContext();
+  auto &C = getContext();
+  QualType QInt64Ty = C.getIntTypeForBitwidth(64, false);
+
+  FunctionArgList FnArgs;
+  ImplicitParamDecl ArgCallsiteTypeId(C, QInt64Ty, ImplicitParamKind::Other);
+  ImplicitParamDecl ArgAddr(C, C.VoidPtrTy, ImplicitParamKind::Other);
+  ImplicitParamDecl ArgCFICheckFailData(C, C.VoidPtrTy,
+ImplicitParamKind::Other);
+  FnArgs.push_back(&ArgCallsiteTypeId);
+  FnArgs.push_back(&ArgAddr);
+  FnArgs.push_back(&ArgCFICheckFailData);
+  const CGFunctionInfo &FI =
+  CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, FnArgs);
+
   llvm::Function *F = llvm::Function::Create(
-  llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false),
+  llvm::FunctionType::get(VoidTy, {Int64Ty, VoidPtrTy, VoidPtrTy}, false),
   llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
+  CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, F, /*IsThunk=*/false);
+  CGM.SetLLVMFunctionAttributesForDefinition(nullptr, F);
   F->setAlignment(llvm::Align(4096));
   CGM.setDSOLocal(F);
+
   llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
   // CrossDSOCFI pass is not executed if there is no executable code.
   SmallVector Args{F->getArg(2), F->getArg(1)};
diff --git a/clang/test/CodeGen/cfi-check-attrs.c 
b/clang/test/CodeGen/cfi-check-attrs.c
new file mode 100644
index 000..375aa30074d8874
--- /dev/null
+++ b/clang/test/CodeGen/cfi-check-attrs.c
@@ -0,0 +1,5 @@
+// RUN: %clang_cc1 -triple arm-unknown-linux -funwind-tables=1 
-fsanitize-cfi-cross-dso -emit-llvm -o - %s | FileCheck %s
+
+// CHECK: define weak {{.*}}void @__cfi_check({{.*}} [[ATTR:#[0-9]*]]
+
+// CHECK: attributes [[ATTR]] = {{.*}} uwtable(sync)
diff --git a/clang/test/CodeGen/cfi-check-fail.c 
b/clang/test/CodeGen/cfi-check-fail.c
index 2f12cee9dec6026..15f6c77abf2b20a 100644
--- a/clang/test/CodeGen/cfi-check-fail.c
+++ b/clang/test/CodeGen/cfi-check-fail.c
@@ -72,7 +72,7 @@ void caller(void (*f)(void)) {
 // CHECK: [[CONT5]]:
 // CHECK:   ret void
 
-// CHECK: define weak void @__cfi_check(i64 %[[TYPE:.*]], ptr %[[ADDR:.*]], 
ptr %[[DATA:.*]]) align 4096
+// CHECK: define weak void @__cfi_check(i64 noundef %[[TYPE:.*]], ptr noundef 
%[[ADDR:.*]], ptr noundef %[[DATA:.*]]){{.*}} align 4096
 // CHECK-NOT: }
 // CHECK: call void @__cfi_check_fail(ptr %[[DATA]], ptr %[[ADDR]])
 // CHECK-NEXT: ret void

``




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


[clang] [cfi][CodeGen] Call SetLLVMFunctionAttributes{, ForDefinition} on __cf… (PR #78253)

2024-01-16 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Pavel Kosov (kpdev)


Changes

…i_check

This causes __cfi_check, just as __cfi_check_fail, to get the proper 
target-specific attributes, in particular uwtable for unwind table generation. 
Previously, nounwind attribute could be inferred for __cfi_check, which caused 
it to lose its unwind table even with -funwind-table option.

~~

Huawei RRI, OS Lab

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


3 Files Affected:

- (modified) clang/lib/CodeGen/CGExpr.cpp (+18-1) 
- (added) clang/test/CodeGen/cfi-check-attrs.c (+5) 
- (modified) clang/test/CodeGen/cfi-check-fail.c (+1-1) 


``diff
diff --git a/clang/lib/CodeGen/CGExpr.cpp b/clang/lib/CodeGen/CGExpr.cpp
index 3f277725d9e7fc..c430acc3a3c960 100644
--- a/clang/lib/CodeGen/CGExpr.cpp
+++ b/clang/lib/CodeGen/CGExpr.cpp
@@ -3443,11 +3443,28 @@ void CodeGenFunction::EmitCfiSlowPathCheck(
 void CodeGenFunction::EmitCfiCheckStub() {
   llvm::Module *M = &CGM.getModule();
   auto &Ctx = M->getContext();
+  auto &C = getContext();
+  QualType QInt64Ty = C.getIntTypeForBitwidth(64, false);
+
+  FunctionArgList FnArgs;
+  ImplicitParamDecl ArgCallsiteTypeId(C, QInt64Ty, ImplicitParamKind::Other);
+  ImplicitParamDecl ArgAddr(C, C.VoidPtrTy, ImplicitParamKind::Other);
+  ImplicitParamDecl ArgCFICheckFailData(C, C.VoidPtrTy,
+ImplicitParamKind::Other);
+  FnArgs.push_back(&ArgCallsiteTypeId);
+  FnArgs.push_back(&ArgAddr);
+  FnArgs.push_back(&ArgCFICheckFailData);
+  const CGFunctionInfo &FI =
+  CGM.getTypes().arrangeBuiltinFunctionDeclaration(C.VoidTy, FnArgs);
+
   llvm::Function *F = llvm::Function::Create(
-  llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false),
+  llvm::FunctionType::get(VoidTy, {Int64Ty, VoidPtrTy, VoidPtrTy}, false),
   llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
+  CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, F, /*IsThunk=*/false);
+  CGM.SetLLVMFunctionAttributesForDefinition(nullptr, F);
   F->setAlignment(llvm::Align(4096));
   CGM.setDSOLocal(F);
+
   llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
   // CrossDSOCFI pass is not executed if there is no executable code.
   SmallVector Args{F->getArg(2), F->getArg(1)};
diff --git a/clang/test/CodeGen/cfi-check-attrs.c 
b/clang/test/CodeGen/cfi-check-attrs.c
new file mode 100644
index 00..375aa30074d887
--- /dev/null
+++ b/clang/test/CodeGen/cfi-check-attrs.c
@@ -0,0 +1,5 @@
+// RUN: %clang_cc1 -triple arm-unknown-linux -funwind-tables=1 
-fsanitize-cfi-cross-dso -emit-llvm -o - %s | FileCheck %s
+
+// CHECK: define weak {{.*}}void @__cfi_check({{.*}} [[ATTR:#[0-9]*]]
+
+// CHECK: attributes [[ATTR]] = {{.*}} uwtable(sync)
diff --git a/clang/test/CodeGen/cfi-check-fail.c 
b/clang/test/CodeGen/cfi-check-fail.c
index 2f12cee9dec602..15f6c77abf2b20 100644
--- a/clang/test/CodeGen/cfi-check-fail.c
+++ b/clang/test/CodeGen/cfi-check-fail.c
@@ -72,7 +72,7 @@ void caller(void (*f)(void)) {
 // CHECK: [[CONT5]]:
 // CHECK:   ret void
 
-// CHECK: define weak void @__cfi_check(i64 %[[TYPE:.*]], ptr %[[ADDR:.*]], 
ptr %[[DATA:.*]]) align 4096
+// CHECK: define weak void @__cfi_check(i64 noundef %[[TYPE:.*]], ptr noundef 
%[[ADDR:.*]], ptr noundef %[[DATA:.*]]){{.*}} align 4096
 // CHECK-NOT: }
 // CHECK: call void @__cfi_check_fail(ptr %[[DATA]], ptr %[[ADDR]])
 // CHECK-NEXT: ret void

``




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


[clang] Warning for incorrect useof 'pure' attribute (PR #78200)

2024-01-16 Thread via cfe-commits

https://github.com/kelbon updated 
https://github.com/llvm/llvm-project/pull/78200

>From b080d04eb30254502ccd5d59d76b5197db1fa88d Mon Sep 17 00:00:00 2001
From: Kelbon Nik 
Date: Mon, 15 Jan 2024 22:24:34 +0400
Subject: [PATCH 1/5] add warning and test

---
 clang/include/clang/Basic/DiagnosticGroups.td| 1 +
 clang/include/clang/Basic/DiagnosticSemaKinds.td | 7 +++
 clang/lib/Sema/SemaDecl.cpp  | 7 +++
 clang/test/Sema/incorrect_pure.cpp   | 7 +++
 4 files changed, 22 insertions(+)
 create mode 100644 clang/test/Sema/incorrect_pure.cpp

diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index 6765721ae7002c..9fcf2be2e45458 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -414,6 +414,7 @@ def : DiagGroup<"c++2a-compat", [CXX20Compat]>;
 def : DiagGroup<"c++2a-compat-pedantic", [CXX20CompatPedantic]>;
 
 def ExitTimeDestructors : DiagGroup<"exit-time-destructors">;
+def IncorrectAttributeUsage : DiagGroup<"incorrect-attribute-usage">;
 def FlexibleArrayExtensions : DiagGroup<"flexible-array-extensions">;
 def FourByteMultiChar : DiagGroup<"four-char-constants">;
 def GlobalConstructors : DiagGroup<"global-constructors"> {
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 414779a7970ab8..0ad3ea64503d81 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -692,6 +692,13 @@ def warn_maybe_falloff_nonvoid_function : Warning<
 def warn_falloff_nonvoid_function : Warning<
   "non-void function does not return a value">,
   InGroup;
+def warn_pure_attr_on_cxx_constructor : Warning<
+  "constructor cannot be 'pure' (undefined behavior)">,
+  InGroup;
+def warn_pure_function_returns_void : Warning<
+  "'pure' attribute on function returning 'void'">,
+  InGroup;
+
 def err_maybe_falloff_nonvoid_block : Error<
   "non-void block does not return a value in all control paths">;
 def err_falloff_nonvoid_block : Error<
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 4e7049571eeb7a..e340028703b3b3 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -11889,6 +11889,13 @@ bool Sema::CheckFunctionDeclaration(Scope *S, 
FunctionDecl *NewFD,
 NewFD->setInvalidDecl();
   }
 
+  if (NewFD->hasAttr() || NewFD->hasAttr()) {
+if (isa_and_nonnull(NewFD))
+  Diag(NewFD->getLocation(), diag::warn_pure_attr_on_cxx_constructor);
+else if (NewFD->getReturnType()->isVoidType())
+  Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void);
+  }
+
   // C++11 [dcl.constexpr]p8:
   //   A constexpr specifier for a non-static member function that is not
   //   a constructor declares that member function to be const.
diff --git a/clang/test/Sema/incorrect_pure.cpp 
b/clang/test/Sema/incorrect_pure.cpp
new file mode 100644
index 00..ce02309f086386
--- /dev/null
+++ b/clang/test/Sema/incorrect_pure.cpp
@@ -0,0 +1,7 @@
+// RUN: %clang_cc1 -fsyntax-only -verify %s
+
+[[gnu::pure]] void foo(); // expected-warning{{'pure' attribute on function 
returning 'void'}}
+
+struct A {
+[[gnu::pure]] A(); // expected-warning{{constructor cannot be 'pure' 
(undefined behavior)}}
+};

>From d43afccb027ea0e02c97ab9fbe55a1ad6c9d71dd Mon Sep 17 00:00:00 2001
From: Kelbon Nik 
Date: Mon, 15 Jan 2024 22:52:23 +0400
Subject: [PATCH 2/5] use precondition: NewFD is not null

---
 clang/lib/Sema/SemaDecl.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index e340028703b3b3..dcbc5c3c842cca 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -11890,7 +11890,7 @@ bool Sema::CheckFunctionDeclaration(Scope *S, 
FunctionDecl *NewFD,
   }
 
   if (NewFD->hasAttr() || NewFD->hasAttr()) {
-if (isa_and_nonnull(NewFD))
+if (isa(NewFD))
   Diag(NewFD->getLocation(), diag::warn_pure_attr_on_cxx_constructor);
 else if (NewFD->getReturnType()->isVoidType())
   Diag(NewFD->getLocation(), diag::warn_pure_function_returns_void);

>From 950ca9de1c05d561a1123c088455a3e21bd9795b Mon Sep 17 00:00:00 2001
From: Kelbon Nik 
Date: Tue, 16 Jan 2024 00:03:47 +0400
Subject: [PATCH 3/5] fix old incorrect test

---
 clang/test/SemaCXX/cxx0x-cursory-default-delete.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/test/SemaCXX/cxx0x-cursory-default-delete.cpp 
b/clang/test/SemaCXX/cxx0x-cursory-default-delete.cpp
index 9d68a0e5d358f6..6ae146f0d08c7d 100644
--- a/clang/test/SemaCXX/cxx0x-cursory-default-delete.cpp
+++ b/clang/test/SemaCXX/cxx0x-cursory-default-delete.cpp
@@ -194,7 +194,7 @@ struct except_spec_d_match : except_spec_a, except_spec_b {
 // gcc-compatibility: allow attributes on default definitions
 // (but not normal definitions)
 stru

[clang] [clang-format] Add parse tests for SeparateDefinitionBlocks option (PR #78256)

2024-01-16 Thread via cfe-commits

https://github.com/seranu created 
https://github.com/llvm/llvm-project/pull/78256

Add config parse tests for SeparateDefinitionBlocks option.

>From 5399fad41b3898abe0833e283101aa34e76389b9 Mon Sep 17 00:00:00 2001
From: Serban Ungureanu 
Date: Tue, 16 Jan 2024 12:56:10 +0200
Subject: [PATCH] [clang-format] Add parse tests for SeparateDefinitionBlocks
 option

---
 clang/unittests/Format/ConfigParseTest.cpp | 9 +
 1 file changed, 9 insertions(+)

diff --git a/clang/unittests/Format/ConfigParseTest.cpp 
b/clang/unittests/Format/ConfigParseTest.cpp
index 6c0f9ddac5ac8f..f409a6a946f3d9 100644
--- a/clang/unittests/Format/ConfigParseTest.cpp
+++ b/clang/unittests/Format/ConfigParseTest.cpp
@@ -996,6 +996,15 @@ TEST(ConfigParseTest, ParsesConfiguration) {
   FormatStyle::BBNSS_OnlyWithParen);
   CHECK_PARSE("AllowBreakBeforeNoexceptSpecifier: Never",
   AllowBreakBeforeNoexceptSpecifier, FormatStyle::BBNSS_Never);
+
+
+  Style.SeparateDefinitionBlocks = FormatStyle::SDS_Never;
+  CHECK_PARSE("SeparateDefinitionBlocks: Always", SeparateDefinitionBlocks,
+  FormatStyle::SDS_Always);
+  CHECK_PARSE("SeparateDefinitionBlocks: Leave", SeparateDefinitionBlocks,
+  FormatStyle::SDS_Leave);
+  CHECK_PARSE("SeparateDefinitionBlocks: Never", SeparateDefinitionBlocks,
+  FormatStyle::SDS_Never);
 }
 
 TEST(ConfigParseTest, ParsesConfigurationWithLanguages) {

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


[clang] [clang-format] Add parse tests for SeparateDefinitionBlocks option (PR #78256)

2024-01-16 Thread via cfe-commits

github-actions[bot] wrote:

Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be
notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this 
page.

If this is not working for you, it is probably because you do not have write
permissions for the repository. In which case you can instead tag reviewers by
name in a comment by using `@` followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review
by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate
is once a week. Please remember that you are asking for valuable time from 
other developers.

If you have further questions, they may be answered by the [LLVM GitHub User 
Guide](https://llvm.org/docs/GitHub.html).

You can also ask questions in a comment on this PR, on the [LLVM 
Discord](https://discord.com/invite/xS7Z362) or on the 
[forums](https://discourse.llvm.org/).

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


[llvm] [clang] [RISCV] Bump Zfbfmin, Zvfbfmin, and Zvfbfwma to 1.0. (PR #78021)

2024-01-16 Thread Alex Bradbury via cfe-commits

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

LGTM.

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


[clang] [clang-format] Add parse tests for SeparateDefinitionBlocks option (PR #78256)

2024-01-16 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-format

Author: serbanu (seranu)


Changes

Add config parse tests for SeparateDefinitionBlocks option.

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


1 Files Affected:

- (modified) clang/unittests/Format/ConfigParseTest.cpp (+9) 


``diff
diff --git a/clang/unittests/Format/ConfigParseTest.cpp 
b/clang/unittests/Format/ConfigParseTest.cpp
index 6c0f9ddac5ac8f..f409a6a946f3d9 100644
--- a/clang/unittests/Format/ConfigParseTest.cpp
+++ b/clang/unittests/Format/ConfigParseTest.cpp
@@ -996,6 +996,15 @@ TEST(ConfigParseTest, ParsesConfiguration) {
   FormatStyle::BBNSS_OnlyWithParen);
   CHECK_PARSE("AllowBreakBeforeNoexceptSpecifier: Never",
   AllowBreakBeforeNoexceptSpecifier, FormatStyle::BBNSS_Never);
+
+
+  Style.SeparateDefinitionBlocks = FormatStyle::SDS_Never;
+  CHECK_PARSE("SeparateDefinitionBlocks: Always", SeparateDefinitionBlocks,
+  FormatStyle::SDS_Always);
+  CHECK_PARSE("SeparateDefinitionBlocks: Leave", SeparateDefinitionBlocks,
+  FormatStyle::SDS_Leave);
+  CHECK_PARSE("SeparateDefinitionBlocks: Never", SeparateDefinitionBlocks,
+  FormatStyle::SDS_Never);
 }
 
 TEST(ConfigParseTest, ParsesConfigurationWithLanguages) {

``




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


[clang] [clang-format] Extract utility functions outside of test fixture (PR #78108)

2024-01-16 Thread via cfe-commits

seranu wrote:

Closing this PR as rework has been requested on 
https://github.com/llvm/llvm-project/pull/77918

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


[clang] [clang-format] Extract utility functions outside of test fixture (PR #78108)

2024-01-16 Thread via cfe-commits

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


[clang] [clang-format] Add parse tests for SeparateDefinitionBlocks option (PR #78256)

2024-01-16 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 1074b94f5df6e164997cdb494f47657fd49d7cb5 
5399fad41b3898abe0833e283101aa34e76389b9 -- 
clang/unittests/Format/ConfigParseTest.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/unittests/Format/ConfigParseTest.cpp 
b/clang/unittests/Format/ConfigParseTest.cpp
index f409a6a946..172aaab598 100644
--- a/clang/unittests/Format/ConfigParseTest.cpp
+++ b/clang/unittests/Format/ConfigParseTest.cpp
@@ -997,7 +997,6 @@ TEST(ConfigParseTest, ParsesConfiguration) {
   CHECK_PARSE("AllowBreakBeforeNoexceptSpecifier: Never",
   AllowBreakBeforeNoexceptSpecifier, FormatStyle::BBNSS_Never);
 
-
   Style.SeparateDefinitionBlocks = FormatStyle::SDS_Never;
   CHECK_PARSE("SeparateDefinitionBlocks: Always", SeparateDefinitionBlocks,
   FormatStyle::SDS_Always);

``




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


[clang] [clang-format] Separate License text and include blocks (PR #77918)

2024-01-16 Thread via cfe-commits

seranu wrote:

I am going to rework the change as per the review comments.  I created another 
PR to add the missing SeparateDefinitionBlocks config parse tests at 
https://github.com/llvm/llvm-project/pull/78256.
For the rework, shall I create a new PR or can I still use this one?

https://github.com/llvm/llvm-project/pull/77918
___
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 bugprone-eval-order (PR #78028)

2024-01-16 Thread via cfe-commits

maflcko wrote:

Closing for now, but happy to reopen.

I don't see a way to implement this without a user-provided list of class names 
to match, in which case the check will likely not be used/discovered.

https://github.com/llvm/llvm-project/pull/78028
___
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 bugprone-eval-order (PR #78028)

2024-01-16 Thread via cfe-commits

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


[clang] [llvm] [RISCV] Relax march string order constraint (PR #78120)

2024-01-16 Thread Alex Bradbury via cfe-commits

asb wrote:

Just to check, can someone confirm if gcc is now handling ISA strings in this 
way too? I do think this is the right direction to go but haven't done a 
detailed code review of this approach yet.

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


[clang] [llvm] [PowerPC] Make "ca" aliased to "xer" (PR #77557)

2024-01-16 Thread Kai Luo via cfe-commits


@@ -288,9 +288,9 @@ def SPEFSCR: SPR<512, "spefscr">, DwarfRegNum<[612, 112]>;
 
 def XER: SPR<1, "xer">, DwarfRegNum<[76]>;
 
-// Carry bit.  In the architecture this is really bit 0 of the XER register
-// (which really is SPR register 1);  this is the only bit interesting to a
-// compiler.
+// Carry bit. In the architecture this is really bit 2 of the 32-bit XER

bzEq wrote:

> Is there a history of the compiler assuming that all SPR are 32 bits?

The code was written more than a decade ago. I guess authors referenced *The 
PowerPC Compiler Writer’s Guide*. Figure 2-1 of the book shows XER, FPER, FPSCR 
are 32-bit width even under 64-bit environment.

In appendix, there is

> Carry bit Bit 2 in the Fixed-Point Exception Register (XER).

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


[llvm] [clang] [PowerPC] Make "ca" aliased to "xer" (PR #77557)

2024-01-16 Thread Kai Luo via cfe-commits


@@ -782,6 +782,8 @@ ArrayRef PPCTargetInfo::getGCCRegNames() 
const {
 const TargetInfo::GCCRegAlias PPCTargetInfo::GCCRegAliases[] = {
 // While some of these aliases do map to different registers
 // they still share the same register name.
+// Strictly speaking, "ca" is a subregister of "xer". However currently we

bzEq wrote:

> If that happens, would we have to add those other fields and then specify 
> them as proper subregs of XER?

I think so. However, existing instructions look not using other fields like OV 
and OV32.

> does GCC support on PowerPC?

Currently, GCC looks only support `xer` and `ca`. See 
https://godbolt.org/z/6qWqc3Pdd. I have tried using `ov`, hit CE.

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


[llvm] [clang] [PowerPC] Make "ca" aliased to "xer" (PR #77557)

2024-01-16 Thread Kai Luo via cfe-commits


@@ -288,9 +288,9 @@ def SPEFSCR: SPR<512, "spefscr">, DwarfRegNum<[612, 112]>;
 
 def XER: SPR<1, "xer">, DwarfRegNum<[76]>;
 
-// Carry bit.  In the architecture this is really bit 0 of the XER register
-// (which really is SPR register 1);  this is the only bit interesting to a
-// compiler.
+// Carry bit. In the architecture this is really bit 2 of the 32-bit XER

bzEq wrote:

I'll update it according to OpenPower's ISA, since it's more generally 
available.

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


[clang] [cfi][CodeGen] Call SetLLVMFunctionAttributes{, ForDefinition} on __cf… (PR #78253)

2024-01-16 Thread Pavel Kosov via cfe-commits

kpdev wrote:

The same thing was done for `__cfi_check_fail` in the following patch: 
https://reviews.llvm.org/D70692

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


[clang] 032c832 - [Clang][AArch64] Remove unnecessary and incorrect attributes from arm_sme.h.

2024-01-16 Thread Sander de Smalen via cfe-commits

Author: Sander de Smalen
Date: 2024-01-16T11:20:59Z
New Revision: 032c832719b5b2c44b78359ed54b91964ef15b79

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

LOG: [Clang][AArch64] Remove unnecessary and incorrect attributes from 
arm_sme.h.

These attributes were using the GNU attribute syntax, rather than the new
keyword attribute syntax, and they are no longer required as we have code
in SemaChecking to verify whether a builtin is compatible with its caller.

Added: 


Modified: 
clang/utils/TableGen/SveEmitter.cpp

Removed: 




diff  --git a/clang/utils/TableGen/SveEmitter.cpp 
b/clang/utils/TableGen/SveEmitter.cpp
index 060d79a06af88d..99b7148c174963 100644
--- a/clang/utils/TableGen/SveEmitter.cpp
+++ b/clang/utils/TableGen/SveEmitter.cpp
@@ -1066,17 +1066,6 @@ void Intrinsic::emitIntrinsic(raw_ostream &OS, 
SVEEmitter &Emitter,
 
   std::string FullName = mangleName(ClassS);
   std::string ProtoName = mangleName(getClassKind());
-  std::string SMEAttrs = "";
-
-  if (Flags & Emitter.getEnumValueForFlag("IsStreaming"))
-SMEAttrs += ", arm_streaming";
-  if (Flags & Emitter.getEnumValueForFlag("IsStreamingCompatible"))
-SMEAttrs += ", arm_streaming_compatible";
-  if (Flags & Emitter.getEnumValueForFlag("IsSharedZA"))
-SMEAttrs += ", arm_shared_za";
-  if (Flags & Emitter.getEnumValueForFlag("IsPreservesZA"))
-SMEAttrs += ", arm_preserves_za";
-
   OS << (IsOverloaded ? "__aio " : "__ai ")
  << "__attribute__((__clang_arm_builtin_alias(";
 
@@ -1089,8 +1078,6 @@ void Intrinsic::emitIntrinsic(raw_ostream &OS, SVEEmitter 
&Emitter,
 break;
   }
 
-  if (!SMEAttrs.empty())
-OS << SMEAttrs;
   OS << "))\n";
 
   OS << getTypes()[0].str() << " " << ProtoName << "(";



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


[clang] [flang] [flang][driver] Allow explicit specification of -lFortran_main (PR #78152)

2024-01-16 Thread Tom Eccles via cfe-commits

tblah wrote:

> I'd agree to that! The way gfortran does it, seems the best approach. When 
> there's a program unit in the code, gfortran also add a `main` definition to 
> that translation unit. 
+2
 
> I could opt-in to make this a learning project for me, but I'd need some hand 
> holding to get it done. Volunteers? :-)
I'm happy to help, but I think we should discuss this in a community call first

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


[clang] [Clang] Refactor diagnostics for SME builtins. (PR #78258)

2024-01-16 Thread Sander de Smalen via cfe-commits

https://github.com/sdesmalen-arm created 
https://github.com/llvm/llvm-project/pull/78258

The arm_sme.td file was still using `IsSharedZA` and `IsPreservesZA`, which 
should be changed to match the new state attributes added in #76971.

This patch adds `IsInZA`, `IsOutZA` and `IsInOutZA` as the state for the Clang 
builtins and fixes up the code in SemaChecking and SveEmitter to match.

Note that the code is written in such a way that it can be easily extended with 
ZT0 state (to follow in a future patch).

>From 545866d530ebeab04384ce85e61a7eb29d343167 Mon Sep 17 00:00:00 2001
From: Sander de Smalen 
Date: Mon, 15 Jan 2024 16:06:36 +
Subject: [PATCH] [Clang] Refactor diagnostics for SME builtins.

The arm_sme.td file was still using `IsSharedZA` and `IsPreservesZA`,
which should be changed to match the new state attributes added in #76971.

This patch adds `IsInZA`, `IsOutZA` and `IsInOutZA` as the state for the
Clang builtins and fixes up the code in SemaChecking and SveEmitter to match.

Note that the code is written in such a way that it can be easily extended
with ZT0 state (to follow in a future patch).
---
 clang/include/clang/Basic/arm_sme.td  | 572 +-
 clang/include/clang/Basic/arm_sve_sme_incl.td |  13 +-
 clang/lib/Sema/SemaChecking.cpp   |  35 +-
 .../Sema/aarch64-incompat-sm-builtin-calls.c  |   5 +
 clang/utils/TableGen/SveEmitter.cpp   |  30 +-
 5 files changed, 336 insertions(+), 319 deletions(-)

diff --git a/clang/include/clang/Basic/arm_sme.td 
b/clang/include/clang/Basic/arm_sme.td
index aac3bd486de922..4fb50b8e4e4e56 100644
--- a/clang/include/clang/Basic/arm_sme.td
+++ b/clang/include/clang/Basic/arm_sme.td
@@ -21,19 +21,19 @@ include "arm_sve_sme_incl.td"
 multiclass ZALoad 
ch> {
   let TargetGuard = "sme" in {
 def NAME # _H : MInst<"svld1_hor_" # n_suffix, "vimPQ", t,
-  [IsLoad, IsOverloadNone, IsStreaming, IsSharedZA],
+  [IsLoad, IsOverloadNone, IsStreaming, IsInOutZA],
   MemEltTyDefault, i_prefix # "_horiz", ch>;
 
 def NAME # _H_VNUM : MInst<"svld1_hor_vnum_" # n_suffix, "vimPQl", t,
-   [IsLoad, IsOverloadNone, IsStreaming, 
IsSharedZA],
+   [IsLoad, IsOverloadNone, IsStreaming, 
IsInOutZA],
MemEltTyDefault, i_prefix # "_horiz", ch>;
 
 def NAME # _V : MInst<"svld1_ver_" # n_suffix, "vimPQ", t,
-  [IsLoad, IsOverloadNone, IsStreaming, IsSharedZA],
+  [IsLoad, IsOverloadNone, IsStreaming, IsInOutZA],
   MemEltTyDefault, i_prefix # "_vert", ch>;
 
 def NAME # _V_VNUM : MInst<"svld1_ver_vnum_" # n_suffix, "vimPQl", t,
-   [IsLoad, IsOverloadNone, IsStreaming, 
IsSharedZA],
+   [IsLoad, IsOverloadNone, IsStreaming, 
IsInOutZA],
MemEltTyDefault, i_prefix # "_vert", ch>;
   }
 }
@@ -45,11 +45,11 @@ defm SVLD1_ZA64 : ZALoad<"za64", "l", "aarch64_sme_ld1d", 
[ImmCheck<0, ImmCheck0
 defm SVLD1_ZA128 : ZALoad<"za128", "q", "aarch64_sme_ld1q", [ImmCheck<0, 
ImmCheck0_15>]>;
 
 def SVLDR_VNUM_ZA : MInst<"svldr_vnum_za", "vmQl", "",
-  [IsOverloadNone, IsStreamingCompatible, IsSharedZA],
+  [IsOverloadNone, IsStreamingCompatible, IsInOutZA],
   MemEltTyDefault, "aarch64_sme_ldr">;
 
 def SVLDR_ZA : MInst<"svldr_za", "vmQ", "",
-  [IsOverloadNone, IsStreamingCompatible, IsSharedZA],
+  [IsOverloadNone, IsStreamingCompatible, IsInOutZA],
   MemEltTyDefault, "aarch64_sme_ldr", []>;
 
 

@@ -58,19 +58,19 @@ def SVLDR_ZA : MInst<"svldr_za", "vmQ", "",
 multiclass ZAStore 
ch> {
   let TargetGuard = "sme" in {
 def NAME # _H : MInst<"svst1_hor_" # n_suffix, "vimP%", t,
-  [IsStore, IsOverloadNone, IsStreaming, IsSharedZA, 
IsPreservesZA],
+  [IsStore, IsOverloadNone, IsStreaming, IsInZA],
   MemEltTyDefault, i_prefix # "_horiz", ch>;
 
 def NAME # _H_VNUM : MInst<"svst1_hor_vnum_" # n_suffix, "vimP%l", t,
-   [IsStore, IsOverloadNone, IsStreaming, 
IsSharedZA, IsPreservesZA],
+   [IsStore, IsOverloadNone, IsStreaming, IsInZA],
MemEltTyDefault, i_prefix # "_horiz", ch>;
 
 def NAME # _V : MInst<"svst1_ver_" # n_suffix, "vimP%", t,
-  [IsStore, IsOverloadNone, IsStreaming, IsSharedZA, 
IsPreservesZA],
+  [IsStore, IsOverloadNone, IsStreaming, IsInZA],
   MemEltTyDefault, i_prefix # "_vert", ch>;
 
 def NAME # _V_VNUM : MInst<"svst1_ver_vnum_" # n_suffix

[clang] [Clang] Refactor diagnostics for SME builtins. (PR #78258)

2024-01-16 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Sander de Smalen (sdesmalen-arm)


Changes

The arm_sme.td file was still using `IsSharedZA` and `IsPreservesZA`, which 
should be changed to match the new state attributes added in #76971.

This patch adds `IsInZA`, `IsOutZA` and `IsInOutZA` as the state for the Clang 
builtins and fixes up the code in SemaChecking and SveEmitter to match.

Note that the code is written in such a way that it can be easily extended with 
ZT0 state (to follow in a future patch).

---

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


5 Files Affected:

- (modified) clang/include/clang/Basic/arm_sme.td (+286-286) 
- (modified) clang/include/clang/Basic/arm_sve_sme_incl.td (+7-6) 
- (modified) clang/lib/Sema/SemaChecking.cpp (+19-16) 
- (modified) clang/test/Sema/aarch64-incompat-sm-builtin-calls.c (+5) 
- (modified) clang/utils/TableGen/SveEmitter.cpp (+19-11) 


``diff
diff --git a/clang/include/clang/Basic/arm_sme.td 
b/clang/include/clang/Basic/arm_sme.td
index aac3bd486de9223..4fb50b8e4e4e565 100644
--- a/clang/include/clang/Basic/arm_sme.td
+++ b/clang/include/clang/Basic/arm_sme.td
@@ -21,19 +21,19 @@ include "arm_sve_sme_incl.td"
 multiclass ZALoad 
ch> {
   let TargetGuard = "sme" in {
 def NAME # _H : MInst<"svld1_hor_" # n_suffix, "vimPQ", t,
-  [IsLoad, IsOverloadNone, IsStreaming, IsSharedZA],
+  [IsLoad, IsOverloadNone, IsStreaming, IsInOutZA],
   MemEltTyDefault, i_prefix # "_horiz", ch>;
 
 def NAME # _H_VNUM : MInst<"svld1_hor_vnum_" # n_suffix, "vimPQl", t,
-   [IsLoad, IsOverloadNone, IsStreaming, 
IsSharedZA],
+   [IsLoad, IsOverloadNone, IsStreaming, 
IsInOutZA],
MemEltTyDefault, i_prefix # "_horiz", ch>;
 
 def NAME # _V : MInst<"svld1_ver_" # n_suffix, "vimPQ", t,
-  [IsLoad, IsOverloadNone, IsStreaming, IsSharedZA],
+  [IsLoad, IsOverloadNone, IsStreaming, IsInOutZA],
   MemEltTyDefault, i_prefix # "_vert", ch>;
 
 def NAME # _V_VNUM : MInst<"svld1_ver_vnum_" # n_suffix, "vimPQl", t,
-   [IsLoad, IsOverloadNone, IsStreaming, 
IsSharedZA],
+   [IsLoad, IsOverloadNone, IsStreaming, 
IsInOutZA],
MemEltTyDefault, i_prefix # "_vert", ch>;
   }
 }
@@ -45,11 +45,11 @@ defm SVLD1_ZA64 : ZALoad<"za64", "l", "aarch64_sme_ld1d", 
[ImmCheck<0, ImmCheck0
 defm SVLD1_ZA128 : ZALoad<"za128", "q", "aarch64_sme_ld1q", [ImmCheck<0, 
ImmCheck0_15>]>;
 
 def SVLDR_VNUM_ZA : MInst<"svldr_vnum_za", "vmQl", "",
-  [IsOverloadNone, IsStreamingCompatible, IsSharedZA],
+  [IsOverloadNone, IsStreamingCompatible, IsInOutZA],
   MemEltTyDefault, "aarch64_sme_ldr">;
 
 def SVLDR_ZA : MInst<"svldr_za", "vmQ", "",
-  [IsOverloadNone, IsStreamingCompatible, IsSharedZA],
+  [IsOverloadNone, IsStreamingCompatible, IsInOutZA],
   MemEltTyDefault, "aarch64_sme_ldr", []>;
 
 

@@ -58,19 +58,19 @@ def SVLDR_ZA : MInst<"svldr_za", "vmQ", "",
 multiclass ZAStore 
ch> {
   let TargetGuard = "sme" in {
 def NAME # _H : MInst<"svst1_hor_" # n_suffix, "vimP%", t,
-  [IsStore, IsOverloadNone, IsStreaming, IsSharedZA, 
IsPreservesZA],
+  [IsStore, IsOverloadNone, IsStreaming, IsInZA],
   MemEltTyDefault, i_prefix # "_horiz", ch>;
 
 def NAME # _H_VNUM : MInst<"svst1_hor_vnum_" # n_suffix, "vimP%l", t,
-   [IsStore, IsOverloadNone, IsStreaming, 
IsSharedZA, IsPreservesZA],
+   [IsStore, IsOverloadNone, IsStreaming, IsInZA],
MemEltTyDefault, i_prefix # "_horiz", ch>;
 
 def NAME # _V : MInst<"svst1_ver_" # n_suffix, "vimP%", t,
-  [IsStore, IsOverloadNone, IsStreaming, IsSharedZA, 
IsPreservesZA],
+  [IsStore, IsOverloadNone, IsStreaming, IsInZA],
   MemEltTyDefault, i_prefix # "_vert", ch>;
 
 def NAME # _V_VNUM : MInst<"svst1_ver_vnum_" # n_suffix, "vimP%l", t,
-   [IsStore, IsOverloadNone, IsStreaming, 
IsSharedZA, IsPreservesZA],
+   [IsStore, IsOverloadNone, IsStreaming, IsInZA],
MemEltTyDefault, i_prefix # "_vert", ch>;
   }
 }
@@ -82,11 +82,11 @@ defm SVST1_ZA64 : ZAStore<"za64", "l", "aarch64_sme_st1d", 
[ImmCheck<0, ImmCheck
 defm SVST1_ZA128 : ZAStore<"za128", "q", "aarch64_sme_st1q", [ImmCheck<0, 
ImmCheck0_15>]>;
 
 def SVSTR_V

[llvm] [clang] [AMDGPU] Add global_load_tr for GFX12 (PR #77772)

2024-01-16 Thread Piotr Sobczak via cfe-commits

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

>From 1b2085465dd0988459a4c71dab6cd65b1de065be Mon Sep 17 00:00:00 2001
From: Piotr Sobczak 
Date: Thu, 11 Jan 2024 14:52:59 +0100
Subject: [PATCH 1/5] [AMDGPU] Add global_load_tr for GFX12

Support new amdgcn_global_load_tr instructions for load with transpose.

* MC layer support for GLOBAL_LOAD_TR_B64/GLOBAL_LOAD_TR_B128
* Intrinsics int_amdgcn_global_load_tr_b64/int_amdgcn_global_load_tr_b128
* Clang builtins amdgcn_global_load_tr_b64/amdgcn_global_load_tr_b128
---
 clang/include/clang/Basic/BuiltinsAMDGPU.def  |   7 ++
 clang/lib/CodeGen/CGBuiltin.cpp   |  45 
 ...uiltins-amdgcn-global-load-tr-gfx11-err.cl |  26 +
 ...ins-amdgcn-global-load-tr-gfx12-w32-err.cl |  15 +++
 ...ins-amdgcn-global-load-tr-gfx12-w64-err.cl |  16 +++
 .../builtins-amdgcn-global-load-tr-w32.cl |  48 
 .../builtins-amdgcn-global-load-tr-w64.cl |  47 
 llvm/include/llvm/IR/IntrinsicsAMDGPU.td  |  21 
 .../Target/AMDGPU/AMDGPURegisterBankInfo.cpp  |   2 +
 .../Disassembler/AMDGPUDisassembler.cpp   |   4 +
 llvm/lib/Target/AMDGPU/FLATInstructions.td|  33 ++
 .../AMDGPU/llvm.amdgcn.global.load.tr-w32.ll  | 106 ++
 .../AMDGPU/llvm.amdgcn.global.load.tr-w64.ll  | 106 ++
 llvm/test/MC/AMDGPU/gfx11_unsupported.s   |   6 +
 .../test/MC/AMDGPU/gfx12_asm_global_load_tr.s | 103 +
 .../AMDGPU/gfx12_dasm_global_load_tr.txt  |  34 ++
 16 files changed, 619 insertions(+)
 create mode 100644 
clang/test/CodeGenOpenCL/builtins-amdgcn-global-load-tr-gfx11-err.cl
 create mode 100644 
clang/test/CodeGenOpenCL/builtins-amdgcn-global-load-tr-gfx12-w32-err.cl
 create mode 100644 
clang/test/CodeGenOpenCL/builtins-amdgcn-global-load-tr-gfx12-w64-err.cl
 create mode 100644 
clang/test/CodeGenOpenCL/builtins-amdgcn-global-load-tr-w32.cl
 create mode 100644 
clang/test/CodeGenOpenCL/builtins-amdgcn-global-load-tr-w64.cl
 create mode 100644 llvm/test/CodeGen/AMDGPU/llvm.amdgcn.global.load.tr-w32.ll
 create mode 100644 llvm/test/CodeGen/AMDGPU/llvm.amdgcn.global.load.tr-w64.ll
 create mode 100644 llvm/test/MC/AMDGPU/gfx12_asm_global_load_tr.s
 create mode 100644 
llvm/test/MC/Disassembler/AMDGPU/gfx12_dasm_global_load_tr.txt

diff --git a/clang/include/clang/Basic/BuiltinsAMDGPU.def 
b/clang/include/clang/Basic/BuiltinsAMDGPU.def
index e562ef04a30194e..098c309f8085375 100644
--- a/clang/include/clang/Basic/BuiltinsAMDGPU.def
+++ b/clang/include/clang/Basic/BuiltinsAMDGPU.def
@@ -423,6 +423,13 @@ TARGET_BUILTIN(__builtin_amdgcn_s_wakeup_barrier, "vi", 
"n", "gfx12-insts")
 TARGET_BUILTIN(__builtin_amdgcn_s_barrier_leave, "b", "n", "gfx12-insts")
 TARGET_BUILTIN(__builtin_amdgcn_s_get_barrier_state, "Uii", "n", "gfx12-insts")
 
+TARGET_BUILTIN(__builtin_amdgcn_global_load_tr_b64_v2i32, "V2iV2i*1", "nc", 
"gfx12-insts,wavefrontsize32")
+TARGET_BUILTIN(__builtin_amdgcn_global_load_tr_b128_v8i16, "V8sV8s*1", "nc", 
"gfx12-insts,wavefrontsize32")
+TARGET_BUILTIN(__builtin_amdgcn_global_load_tr_b128_v8f16, "V8hV8h*1", "nc", 
"gfx12-insts,wavefrontsize32")
+
+TARGET_BUILTIN(__builtin_amdgcn_global_load_tr_b64_i32, "ii*1", "nc", 
"gfx12-insts,wavefrontsize64")
+TARGET_BUILTIN(__builtin_amdgcn_global_load_tr_b128_v4i16, "V4sV4s*1", "nc", 
"gfx12-insts,wavefrontsize64")
+TARGET_BUILTIN(__builtin_amdgcn_global_load_tr_b128_v4f16, "V4hV4h*1", "nc", 
"gfx12-insts,wavefrontsize64")
 
 #undef BUILTIN
 #undef TARGET_BUILTIN
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 998fcc3af581753..dc634b1c388f46f 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -18178,6 +18178,51 @@ Value *CodeGenFunction::EmitAMDGPUBuiltinExpr(unsigned 
BuiltinID,
 llvm::Function *F = CGM.getIntrinsic(IID, {ArgTy});
 return Builder.CreateCall(F, {Addr, Val, ZeroI32, ZeroI32, ZeroI1});
   }
+  case AMDGPU::BI__builtin_amdgcn_global_load_tr_b64_v2i32:
+  case AMDGPU::BI__builtin_amdgcn_global_load_tr_b64_i32:
+  case AMDGPU::BI__builtin_amdgcn_global_load_tr_b128_v8i16:
+  case AMDGPU::BI__builtin_amdgcn_global_load_tr_b128_v8f16:
+  case AMDGPU::BI__builtin_amdgcn_global_load_tr_b128_v4i16:
+  case AMDGPU::BI__builtin_amdgcn_global_load_tr_b128_v4f16: {
+
+Intrinsic::ID IID;
+llvm::Type *ArgTy;
+switch (BuiltinID) {
+case AMDGPU::BI__builtin_amdgcn_global_load_tr_b64_v2i32:
+  ArgTy = llvm::FixedVectorType::get(
+  llvm::Type::getInt32Ty(getLLVMContext()), 2);
+  IID = Intrinsic::amdgcn_global_load_tr_b64;
+  break;
+case AMDGPU::BI__builtin_amdgcn_global_load_tr_b64_i32:
+  ArgTy = llvm::Type::getInt32Ty(getLLVMContext());
+  IID = Intrinsic::amdgcn_global_load_tr_b64;
+  break;
+case AMDGPU::BI__builtin_amdgcn_global_load_tr_b128_v8i16:
+  ArgTy = llvm::FixedVectorType::get(
+  llvm::Type::getInt16Ty(getLLVMContext()), 8);
+  IID = Intr

[clang] [coroutines][coro_lifetimebound] Detect lifetime issues with lambda captures (PR #77066)

2024-01-16 Thread Utkarsh Saxena via cfe-commits


@@ -15845,8 +15845,10 @@ void Sema::CheckCoroutineWrapper(FunctionDecl *FD) {
   RecordDecl *RD = FD->getReturnType()->getAsRecordDecl();
   if (!RD || !RD->getUnderlyingDecl()->hasAttr())
 return;
-  // Allow `get_return_object()`.
-  if (FD->getDeclName().isIdentifier() &&
+  // Allow some_promise_type::get_return_object().
+  // Since we are still in the promise definition, we can only do this
+  // heuristically as the promise may not be yet associated to a coroutine.
+  if (isa(FD) && FD->getDeclName().isIdentifier() &&
   FD->getName().equals("get_return_object") && FD->param_empty())
 return;

usx95 wrote:

I do not think that would work either. For example, consider TUs with only 
promise definitions and no coroutine definitions. These attr would not be 
available even in the end of TU.

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


[clang] [clang-format] Add parse tests for SeparateDefinitionBlocks option (PR #78256)

2024-01-16 Thread via cfe-commits

https://github.com/seranu updated 
https://github.com/llvm/llvm-project/pull/78256

>From 05de7ff4ba8e90cab10ff42abad5c68e84780e70 Mon Sep 17 00:00:00 2001
From: Serban Ungureanu 
Date: Tue, 16 Jan 2024 12:56:10 +0200
Subject: [PATCH] [clang-format] Add parse tests for SeparateDefinitionBlocks
 option

---
 clang/unittests/Format/ConfigParseTest.cpp | 8 
 1 file changed, 8 insertions(+)

diff --git a/clang/unittests/Format/ConfigParseTest.cpp 
b/clang/unittests/Format/ConfigParseTest.cpp
index 6c0f9ddac5ac8f..172aaab5988ce5 100644
--- a/clang/unittests/Format/ConfigParseTest.cpp
+++ b/clang/unittests/Format/ConfigParseTest.cpp
@@ -996,6 +996,14 @@ TEST(ConfigParseTest, ParsesConfiguration) {
   FormatStyle::BBNSS_OnlyWithParen);
   CHECK_PARSE("AllowBreakBeforeNoexceptSpecifier: Never",
   AllowBreakBeforeNoexceptSpecifier, FormatStyle::BBNSS_Never);
+
+  Style.SeparateDefinitionBlocks = FormatStyle::SDS_Never;
+  CHECK_PARSE("SeparateDefinitionBlocks: Always", SeparateDefinitionBlocks,
+  FormatStyle::SDS_Always);
+  CHECK_PARSE("SeparateDefinitionBlocks: Leave", SeparateDefinitionBlocks,
+  FormatStyle::SDS_Leave);
+  CHECK_PARSE("SeparateDefinitionBlocks: Never", SeparateDefinitionBlocks,
+  FormatStyle::SDS_Never);
 }
 
 TEST(ConfigParseTest, ParsesConfigurationWithLanguages) {

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


[clang] c19cacf - [clang][dataflow] Tighten checking for existence of a function body. (#78163)

2024-01-16 Thread via cfe-commits

Author: martinboehme
Date: 2024-01-16T12:52:55+01:00
New Revision: c19cacfa34f52b65addeb7239d564b20e3cf2c61

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

LOG: [clang][dataflow] Tighten checking for existence of a function body. 
(#78163)

In various places, we would previously call `FunctionDecl::hasBody()`
(which
checks whether any redeclaration of the function has a body, not
necessarily the
one on which `hasBody()` is being called).

This is bug-prone, as a recent bug in Crubit's nullability checker has
shown

([fix](https://github.com/google/crubit/commit/4b01ed0f14d953cda20f92d62256e7365d206b2e),
[fix for the
fix](https://github.com/google/crubit/commit/e0c5d8ddd7d647da483c2ae198ff91d131c12055)).

Instead, we now use `FunctionDecl::doesThisDeclarationHaveABody()`
which, as the
name implies, checks whether the specific redeclaration it is being
called on
has a body.

Alternatively, I considered being more lenient and "canonicalizing" to
the
`FunctionDecl` that has the body if the `FunctionDecl` being passed is a
different redeclaration. However, this also risks hiding bugs: A caller
might
inadverently perform the analysis for all redeclarations of a function
and end
up duplicating work without realizing it. By accepting only the
redeclaration
that contains the body, we prevent this.

I've checked, and all clients that I'm aware of do currently pass in the
redeclaration that contains the function body. Typically this is because
they
use the `ast_matchers::hasBody()` matcher which, unlike
`FunctionDecl::hasBody()`, only matches for the redeclaration containing
the
body.

Added: 


Modified: 
clang/include/clang/Analysis/FlowSensitive/ControlFlowContext.h
clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
clang/lib/Analysis/FlowSensitive/ControlFlowContext.cpp
clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp

Removed: 




diff  --git a/clang/include/clang/Analysis/FlowSensitive/ControlFlowContext.h 
b/clang/include/clang/Analysis/FlowSensitive/ControlFlowContext.h
index 768387a121b920a..405e93287a05d38 100644
--- a/clang/include/clang/Analysis/FlowSensitive/ControlFlowContext.h
+++ b/clang/include/clang/Analysis/FlowSensitive/ControlFlowContext.h
@@ -32,7 +32,8 @@ namespace dataflow {
 class ControlFlowContext {
 public:
   /// Builds a ControlFlowContext from a `FunctionDecl`.
-  /// `Func.hasBody()` must be true, and `Func.isTemplated()` must be false.
+  /// `Func.doesThisDeclarationHaveABody()` must be true, and
+  /// `Func.isTemplated()` must be false.
   static llvm::Expected build(const FunctionDecl &Func);
 
   /// Builds a ControlFlowContext from an AST node. `D` is the function in 
which

diff  --git a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h 
b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
index e8c27d6c12038b2..1543f900e401d6d 100644
--- a/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
+++ b/clang/include/clang/Analysis/FlowSensitive/DataflowEnvironment.h
@@ -172,7 +172,8 @@ class Environment {
   ///
   /// Requirements:
   ///
-  ///  The function must have a body.
+  ///  The function must have a body, i.e.
+  ///  `FunctionDecl::doesThisDecalarationHaveABody()` must be true.
   void initialize();
 
   /// Returns a new environment that is a copy of this one.

diff  --git a/clang/lib/Analysis/FlowSensitive/ControlFlowContext.cpp 
b/clang/lib/Analysis/FlowSensitive/ControlFlowContext.cpp
index 56246066e4aa13a..c9ebffe6f378019 100644
--- a/clang/lib/Analysis/FlowSensitive/ControlFlowContext.cpp
+++ b/clang/lib/Analysis/FlowSensitive/ControlFlowContext.cpp
@@ -69,7 +69,7 @@ static llvm::BitVector findReachableBlocks(const CFG &Cfg) {
 
 llvm::Expected
 ControlFlowContext::build(const FunctionDecl &Func) {
-  if (!Func.hasBody())
+  if (!Func.doesThisDeclarationHaveABody())
 return llvm::createStringError(
 std::make_error_code(std::errc::invalid_argument),
 "Cannot analyze function without a body");

diff  --git a/clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp 
b/clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
index d95b3324ef6b2ae..f4c4af022f51f6b 100644
--- a/clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
+++ b/clang/lib/Analysis/FlowSensitive/DataflowAnalysisContext.cpp
@@ -298,7 +298,7 @@ DataflowAnalysisContext::getControlFlowContext(const 
FunctionDecl *F) {
   if (It != FunctionContexts.end())
 return &It->second;
 
-  if (F->hasBody()) {
+  if (F->doesThisDeclarationHaveABody()) {
 auto CFCtx = ControlFlowContext::build(*F);
 // FIXME: Handle errors.
 assert(CFCtx);

diff  --git a/clang/lib/Analysis/FlowSensitive/Dataf

[clang] [clang][dataflow] Tighten checking for existence of a function body. (PR #78163)

2024-01-16 Thread via cfe-commits

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


[clang] [clang-format] TableGen multi line string support. (PR #78032)

2024-01-16 Thread Hirofumi Nakamura via cfe-commits

https://github.com/hnakamura5 updated 
https://github.com/llvm/llvm-project/pull/78032

>From d0767350f26215e86dee039427183630b3f02668 Mon Sep 17 00:00:00 2001
From: hnakamura5 
Date: Sat, 13 Jan 2024 21:44:34 +0900
Subject: [PATCH 1/4] [clang-format] TableGen multi line string support.

---
 clang/lib/Format/ContinuationIndenter.cpp |  3 +
 clang/lib/Format/FormatToken.h|  1 +
 clang/lib/Format/FormatTokenLexer.cpp | 57 +++
 clang/lib/Format/FormatTokenLexer.h   |  3 +
 clang/lib/Format/TokenAnnotator.cpp   |  2 +-
 clang/unittests/Format/TokenAnnotatorTest.cpp |  5 ++
 6 files changed, 70 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index 102504182c4505..e6eaaa9ab45706 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -1591,6 +1591,9 @@ unsigned 
ContinuationIndenter::moveStateToNextToken(LineState &State,
 State.StartOfStringLiteral = State.Column + 1;
   if (Current.is(TT_CSharpStringLiteral) && State.StartOfStringLiteral == 0) {
 State.StartOfStringLiteral = State.Column + 1;
+  } else if (Current.is(TT_TableGenMultiLineString) &&
+ State.StartOfStringLiteral == 0) {
+State.StartOfStringLiteral = State.Column + 1;
   } else if (Current.isStringLiteral() && State.StartOfStringLiteral == 0) {
 State.StartOfStringLiteral = State.Column;
   } else if (!Current.isOneOf(tok::comment, tok::identifier, tok::hash) &&
diff --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index d5ef627f1348d3..dede89f2600150 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -148,6 +148,7 @@ namespace format {
   TYPE(StructLBrace)   
\
   TYPE(StructRBrace)   
\
   TYPE(StructuredBindingLSquare)   
\
+  TYPE(TableGenMultiLineString)
\
   TYPE(TemplateCloser) 
\
   TYPE(TemplateOpener) 
\
   TYPE(TemplateString) 
\
diff --git a/clang/lib/Format/FormatTokenLexer.cpp 
b/clang/lib/Format/FormatTokenLexer.cpp
index a1fd6dd6effe6c..1060009bdcf131 100644
--- a/clang/lib/Format/FormatTokenLexer.cpp
+++ b/clang/lib/Format/FormatTokenLexer.cpp
@@ -93,6 +93,8 @@ ArrayRef FormatTokenLexer::lex() {
   // string literals are correctly identified.
   handleCSharpVerbatimAndInterpolatedStrings();
 }
+if (Style.isTableGen())
+  handleTableGenMultilineString();
 if (Tokens.back()->NewlinesBefore > 0 || Tokens.back()->IsMultiline)
   FirstInLineIndex = Tokens.size() - 1;
   } while (Tokens.back()->isNot(tok::eof));
@@ -272,6 +274,14 @@ void FormatTokenLexer::tryMergePreviousTokens() {
   return;
 }
   }
+  if (Style.isTableGen()) {
+if (tryMergeTokens({tok::l_square, tok::l_brace},
+   TT_TableGenMultiLineString)) {
+  // Multi line string starts with [{
+  Tokens.back()->Tok.setKind(tok::string_literal);
+  return;
+}
+  }
 }
 
 bool FormatTokenLexer::tryMergeNSStringLiteral() {
@@ -763,6 +773,53 @@ void 
FormatTokenLexer::handleCSharpVerbatimAndInterpolatedStrings() {
   resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset + 1)));
 }
 
+void FormatTokenLexer::handleTableGenMultilineString() {
+  FormatToken *MultiLineString = Tokens.back();
+  if (MultiLineString->isNot(TT_TableGenMultiLineString))
+return;
+
+  bool PrevIsRBrace = false;
+  const char *FirstBreak = nullptr;
+  const char *LastBreak = nullptr;
+  const char *Begin = MultiLineString->TokenText.begin();
+  // Skip until }], the closer of multi line string found.
+  for (const char *Current = Begin, *End = Lex->getBuffer().end();
+   Current != End; ++Current) {
+if (PrevIsRBrace && *Current == ']') {
+  // }] is the end of multi line string.
+  if (!FirstBreak)
+FirstBreak = Current;
+  MultiLineString->TokenText = StringRef(Begin, Current - Begin + 1);
+  // ColumnWidth is only the width of the first line.
+  MultiLineString->ColumnWidth = encoding::columnWidthWithTabs(
+  StringRef(Begin, FirstBreak - Begin + 1),
+  MultiLineString->OriginalColumn, Style.TabWidth, Encoding);
+  if (LastBreak) {
+// Set LastLineColumnWidth if multi line string has multiple lines.
+MultiLineString->LastLineColumnWidth = encoding::columnWidthWithTabs(
+StringRef(LastBreak + 1, Current - LastBreak),
+MultiLineString->OriginalColumn, Style.TabWidth, Encoding);
+  }
+  resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Current + 1)));
+  return;
+}

[llvm] [clang-tools-extra] [flang] [clang] [flang] add SYSTEM runtime and lowering intrinsics support (PR #74309)

2024-01-16 Thread Yi Wu via cfe-commits

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

>From 14f8c3e38791cc6b06455b8beffe37a6f7105e03 Mon Sep 17 00:00:00 2001
From: Yi Wu 
Date: Mon, 4 Dec 2023 10:32:03 +
Subject: [PATCH 01/11] Add SYSTEM runtime and lowering intrinsic support

Calls std::system() function and pass the command,
cmd on Windows or shell on Linux.
Command parameter is required, exitstatus is optional.
call system(command)
call system(command, exitstatus)
---
 flang/docs/Intrinsics.md  |  2 +-
 .../flang/Optimizer/Builder/IntrinsicCall.h   |  1 +
 .../flang/Optimizer/Builder/Runtime/Command.h |  5 +++
 flang/include/flang/Runtime/command.h |  5 +++
 flang/lib/Evaluate/intrinsics.cpp | 16 +---
 flang/lib/Optimizer/Builder/IntrinsicCall.cpp | 22 ++
 .../lib/Optimizer/Builder/Runtime/Command.cpp | 13 ++
 flang/runtime/command.cpp | 19 +
 flang/test/Lower/Intrinsics/system.f90| 39 ++
 flang/unittests/Runtime/CommandTest.cpp   | 41 +++
 10 files changed, 157 insertions(+), 6 deletions(-)
 create mode 100644 flang/test/Lower/Intrinsics/system.f90

diff --git a/flang/docs/Intrinsics.md b/flang/docs/Intrinsics.md
index fef2b4ea4dd8c85..871332399628e92 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, GETPID, 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, MOVE_ALLOC, RANDOM_INIT, RANDOM_NUMBER, RANDOM_SEED, 
SYSTEM, SYSTEM_CLOCK |
 | Atomic intrinsic subroutines | ATOMIC_ADD |
 | Collective intrinsic subroutines | CO_REDUCE |
 
diff --git a/flang/include/flang/Optimizer/Builder/IntrinsicCall.h 
b/flang/include/flang/Optimizer/Builder/IntrinsicCall.h
index 5065f11ae9e7264..669d076c3e0e7d8 100644
--- a/flang/include/flang/Optimizer/Builder/IntrinsicCall.h
+++ b/flang/include/flang/Optimizer/Builder/IntrinsicCall.h
@@ -321,6 +321,7 @@ struct IntrinsicLibrary {
   fir::ExtendedValue genStorageSize(mlir::Type,
 llvm::ArrayRef);
   fir::ExtendedValue genSum(mlir::Type, llvm::ArrayRef);
+  void genSystem(mlir::ArrayRef args);
   void genSystemClock(llvm::ArrayRef);
   mlir::Value genTand(mlir::Type, llvm::ArrayRef);
   mlir::Value genTrailz(mlir::Type, llvm::ArrayRef);
diff --git a/flang/include/flang/Optimizer/Builder/Runtime/Command.h 
b/flang/include/flang/Optimizer/Builder/Runtime/Command.h
index 976fb3aa0b6fbb7..9d6a39639844fc7 100644
--- a/flang/include/flang/Optimizer/Builder/Runtime/Command.h
+++ b/flang/include/flang/Optimizer/Builder/Runtime/Command.h
@@ -53,5 +53,10 @@ mlir::Value genGetEnvVariable(fir::FirOpBuilder &, 
mlir::Location,
   mlir::Value length, mlir::Value trimName,
   mlir::Value errmsg);
 
+/// Generate a call to System runtime function which implements
+/// the non-standard System GNU extension.
+void genSystem(fir::FirOpBuilder &, mlir::Location, mlir::Value command,
+   mlir::Value exitstat);
+
 } // namespace fir::runtime
 #endif // FORTRAN_OPTIMIZER_BUILDER_RUNTIME_COMMAND_H
diff --git a/flang/include/flang/Runtime/command.h 
b/flang/include/flang/Runtime/command.h
index c67d171c8e2f1b8..f325faa7bd09fa1 100644
--- a/flang/include/flang/Runtime/command.h
+++ b/flang/include/flang/Runtime/command.h
@@ -55,6 +55,11 @@ std::int32_t RTNAME(GetEnvVariable)(const Descriptor &name,
 const Descriptor *value = nullptr, const Descriptor *length = nullptr,
 bool trim_name = true, const Descriptor *errmsg = nullptr,
 const char *sourceFile = nullptr, int line = 0);
+
+// Calls std::system()
+void RTNAME(System)(const Descriptor *command = nullptr,
+const Descriptor *exitstat = nullptr, const char *sourceFile = nullptr,
+int line = 0);
 }
 } // namespace Fortran::runt

  1   2   3   4   5   6   >