[clang-tools-extra] Enforce SL.con.3: Add check to replace operator[] with at() [Cont.] (PR #95220)

2025-04-06 Thread Paul Heidekrüger via cfe-commits

paulhdk wrote:

Gentle bump. Thank you for taking a look!

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


[clang] [Clang][Sema] Handle invalid variable template specialization whose type depends on itself (PR #134522)

2025-04-06 Thread Younan Zhang via cfe-commits

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

LGTM

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


[clang] [clang-format] Add 'cl' to enable OpenCL kernel file formatting (PR #134529)

2025-04-06 Thread Wenju He via cfe-commits

https://github.com/wenju-he created 
https://github.com/llvm/llvm-project/pull/134529

None

>From ac389b8b92fbb77c8884515d8f7293b4af17dfa5 Mon Sep 17 00:00:00 2001
From: Wenju He 
Date: Sun, 6 Apr 2025 18:30:42 +0800
Subject: [PATCH] [clang-format] Add 'cl' to enable OpenCL kernel file
 formatting

---
 clang/tools/clang-format/git-clang-format | 1 +
 1 file changed, 1 insertion(+)

diff --git a/clang/tools/clang-format/git-clang-format 
b/clang/tools/clang-format/git-clang-format
index 85eff4761e289..ba324b14ab80d 100755
--- a/clang/tools/clang-format/git-clang-format
+++ b/clang/tools/clang-format/git-clang-format
@@ -126,6 +126,7 @@ def main():
 "pb.txt",
 "textproto",
 "asciipb",  # TextProto
+"cl", # OpenCL
 ]
 )
 

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


[clang] [clang-format] Add 'cl' to enable OpenCL kernel file formatting (PR #134529)

2025-04-06 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-format

Author: Wenju He (wenju-he)


Changes



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


1 Files Affected:

- (modified) clang/tools/clang-format/git-clang-format (+1) 


``diff
diff --git a/clang/tools/clang-format/git-clang-format 
b/clang/tools/clang-format/git-clang-format
index 85eff4761e289..ba324b14ab80d 100755
--- a/clang/tools/clang-format/git-clang-format
+++ b/clang/tools/clang-format/git-clang-format
@@ -126,6 +126,7 @@ def main():
 "pb.txt",
 "textproto",
 "asciipb",  # TextProto
+"cl", # OpenCL
 ]
 )
 

``




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


[clang] [clang] Add `__bf16` Type Support Macros With Literal Suffix Support (PR #134214)

2025-04-06 Thread via cfe-commits

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


[clang] [Clang][AMDGPU] Enable `avail-extern-to-local` for ThinLTO in HIP (PR #134476)

2025-04-06 Thread Shilei Tian via cfe-commits

shiltian wrote:

https://github.com/llvm/llvm-project/pull/134541 resolves the missing 
`__assert_fail` issue.

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


[clang] [Clang][Sema] Handle invalid variable template specialization whose type depends on itself (PR #134522)

2025-04-06 Thread Yanzuo Liu via cfe-commits

https://github.com/zwuis created 
https://github.com/llvm/llvm-project/pull/134522

Fixes #51347 

>From ccab3dc1f18ffeda9acb07c0bd5f80f65cc788b9 Mon Sep 17 00:00:00 2001
From: Yanzuo Liu 
Date: Sun, 6 Apr 2025 15:06:56 +0800
Subject: [PATCH] Handle invalid variable template specialization whose type
 depends on itself

---
 clang/docs/ReleaseNotes.rst|  2 ++
 .../include/clang/Basic/DiagnosticSemaKinds.td |  3 +++
 clang/lib/Sema/SemaTemplate.cpp|  7 +++
 .../SemaTemplate/instantiate-var-template.cpp  | 18 ++
 4 files changed, 30 insertions(+)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 5217e04b5e83f..9e0fe8a94729b 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -414,6 +414,8 @@ Bug Fixes to C++ Support
 - Clang now issues an error when placement new is used to modify a 
const-qualified variable
   in a ``constexpr`` function. (#GH131432)
 - Clang now emits a warning when class template argument deduction for alias 
templates is used in C++17. (#GH133806)
+- No longer crashes when instantiating invalid variable template specialization
+  whose type depends on itself. (#GH51347)
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 393bfecf9a36b..0c1da40dba388 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -5259,6 +5259,9 @@ def err_template_member_noparams : Error<
   "extraneous 'template<>' in declaration of member %0">;
 def err_template_tag_noparams : Error<
   "extraneous 'template<>' in declaration of %0 %1">;
+def err_var_template_spec_type_depends_on_self : Error<
+  "the type of variable template specialization %0 declared with deduced type "
+  "%1 depends on itself">;
 
 def warn_unqualified_call_to_std_cast_function : Warning<
   "unqualified call to '%0'">, InGroup>;
diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 153f44f8ec67a..ce54dbbb3b9fe 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -4377,6 +4377,13 @@ Sema::CheckVarTemplateId(VarTemplateDecl *Template, 
SourceLocation TemplateLoc,
   if (VarTemplateSpecializationDecl *Spec =
   Template->findSpecialization(CTAI.CanonicalConverted, InsertPos)) {
 checkSpecializationReachability(TemplateNameLoc, Spec);
+if (Spec->getType()->isUndeducedType()) {
+  // We are substituting the initializer of this variable template
+  // specialization.
+  Diag(TemplateNameLoc, diag::err_var_template_spec_type_depends_on_self)
+  << Spec << Spec->getType();
+  return true;
+}
 // If we already have a variable template specialization, return it.
 return Spec;
   }
diff --git a/clang/test/SemaTemplate/instantiate-var-template.cpp 
b/clang/test/SemaTemplate/instantiate-var-template.cpp
index 60d3bd3b59f53..34a1b9710814b 100644
--- a/clang/test/SemaTemplate/instantiate-var-template.cpp
+++ b/clang/test/SemaTemplate/instantiate-var-template.cpp
@@ -47,3 +47,21 @@ namespace InvalidInsertPos {
   template<> int v;
   int k = v;
 }
+
+namespace GH51347 {
+  template 
+  auto p = p; // expected-error {{the type of variable template 
specialization 'p'}}
+
+  auto x = p; // expected-note {{in instantiation of variable template 
specialization 'GH51347::p'}}
+}
+
+namespace GH97881_comment {
+  template 
+  auto g = sizeof(g);
+  // expected-error@-1 {{the type of variable template specialization 
'g'}}
+  // expected-note@-2 {{in instantiation of variable template specialization 
'GH97881_comment::g'}}
+
+  void test() {
+(void)sizeof(g); // expected-note {{in instantiation of variable 
template specialization 'GH97881_comment::g'}}
+  }
+}

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


[clang-tools-extra] [clangd] Implement simple folding of preprocessor branches (rebased) (PR #121449)

2025-04-06 Thread Shan Pen via cfe-commits

bricle wrote:

hope you guys are doing well, really need this feature, thank you for your 
contribution!

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


[clang] [X86][AVX10] Make warning message more informative, NFCI (PR #134528)

2025-04-06 Thread Phoebe Wang via cfe-commits

https://github.com/phoebewang created 
https://github.com/llvm/llvm-project/pull/134528

None

>From 04852072c016e6df3c9b6d834ba34c443593aa04 Mon Sep 17 00:00:00 2001
From: "Wang, Phoebe" 
Date: Sun, 6 Apr 2025 18:22:22 +0800
Subject: [PATCH] [X86][AVX10] Make warning message more informative, NFCI

---
 clang/lib/Driver/ToolChains/Arch/X86.cpp | 8 ++--
 clang/test/Driver/x86-target-features.c  | 4 ++--
 2 files changed, 8 insertions(+), 4 deletions(-)

diff --git a/clang/lib/Driver/ToolChains/Arch/X86.cpp 
b/clang/lib/Driver/ToolChains/Arch/X86.cpp
index 429b041c9c513..e6ac3a9e4b350 100644
--- a/clang/lib/Driver/ToolChains/Arch/X86.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/X86.cpp
@@ -252,7 +252,9 @@ void x86::getX86TargetFeatures(const Driver &D, const 
llvm::Triple &Triple,
 D.Diag(diag::warn_drv_deprecated_arg) << Name << 1 << 
Name.drop_back(4);
   else if (Width == "256")
 D.Diag(diag::warn_drv_deprecated_custom)
-<< Name << "because AVX10/256 is not supported and will be 
removed";
+<< Name
+<< "no alternative argument provided because "
+   "AVX10/256 is not supported and will be removed";
   else
 assert((Width == "256" || Width == "512") && "Invalid vector length.");
   Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
@@ -286,7 +288,9 @@ void x86::getX86TargetFeatures(const Driver &D, const 
llvm::Triple &Triple,
 if (A->getOption().matches(options::OPT_mevex512) ||
 A->getOption().matches(options::OPT_mno_evex512))
   D.Diag(diag::warn_drv_deprecated_custom)
-  << Name << "because AVX10/256 is not supported and will be removed";
+  << Name
+  << "no alternative argument provided because "
+ "AVX10/256 is not supported and will be removed";
 
 if (A->getOption().matches(options::OPT_mapx_features_EQ) ||
 A->getOption().matches(options::OPT_mno_apx_features_EQ)) {
diff --git a/clang/test/Driver/x86-target-features.c 
b/clang/test/Driver/x86-target-features.c
index 6416a34898e78..9c18098c87026 100644
--- a/clang/test/Driver/x86-target-features.c
+++ b/clang/test/Driver/x86-target-features.c
@@ -411,8 +411,8 @@
 // RUN: %clang --target=i386 -mavx10.2-512 %s -### -o %t.o 2>&1 | FileCheck 
-check-prefixes=AVX10_2_512,WARN-AVX10-512 %s
 // RUN: %clang --target=i386 -mavx10.2-256 -mavx10.1-512 %s -### -o %t.o 2>&1 
| FileCheck -check-prefixes=AVX10_2_256,AVX10_1_512 %s
 // RUN: %clang --target=i386 -mavx10.2-512 -mavx10.1-256 %s -### -o %t.o 2>&1 
| FileCheck -check-prefixes=AVX10_2_512,AVX10_1_256 %s
-// WARN-EVEX512: warning: argument '{{.*}}evex512' is deprecated, because 
AVX10/256 is not supported and will be removed [-Wdeprecated]
-// WARN-AVX10-256: warning: argument 'avx10.{{.*}}-256' is deprecated, because 
AVX10/256 is not supported and will be removed [-Wdeprecated]
+// WARN-EVEX512: warning: argument '{{.*}}evex512' is deprecated, no 
alternative argument provided because AVX10/256 is not supported and will be 
removed [-Wdeprecated]
+// WARN-AVX10-256: warning: argument 'avx10.{{.*}}-256' is deprecated, no 
alternative argument provided because AVX10/256 is not supported and will be 
removed [-Wdeprecated]
 // WARN-AVX10-512: warning: argument 'avx10.{{.*}}-512' is deprecated, use 
'avx10.{{.*}}' instead [-Wdeprecated]
 // EVEX512: "-target-feature" "+evex512"
 // NO-EVEX512: "-target-feature" "-evex512"

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


[clang] [X86][AVX10] Make warning message more informative, NFCI (PR #134528)

2025-04-06 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-driver

Author: Phoebe Wang (phoebewang)


Changes



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


2 Files Affected:

- (modified) clang/lib/Driver/ToolChains/Arch/X86.cpp (+6-2) 
- (modified) clang/test/Driver/x86-target-features.c (+2-2) 


``diff
diff --git a/clang/lib/Driver/ToolChains/Arch/X86.cpp 
b/clang/lib/Driver/ToolChains/Arch/X86.cpp
index 429b041c9c513..e6ac3a9e4b350 100644
--- a/clang/lib/Driver/ToolChains/Arch/X86.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/X86.cpp
@@ -252,7 +252,9 @@ void x86::getX86TargetFeatures(const Driver &D, const 
llvm::Triple &Triple,
 D.Diag(diag::warn_drv_deprecated_arg) << Name << 1 << 
Name.drop_back(4);
   else if (Width == "256")
 D.Diag(diag::warn_drv_deprecated_custom)
-<< Name << "because AVX10/256 is not supported and will be 
removed";
+<< Name
+<< "no alternative argument provided because "
+   "AVX10/256 is not supported and will be removed";
   else
 assert((Width == "256" || Width == "512") && "Invalid vector length.");
   Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
@@ -286,7 +288,9 @@ void x86::getX86TargetFeatures(const Driver &D, const 
llvm::Triple &Triple,
 if (A->getOption().matches(options::OPT_mevex512) ||
 A->getOption().matches(options::OPT_mno_evex512))
   D.Diag(diag::warn_drv_deprecated_custom)
-  << Name << "because AVX10/256 is not supported and will be removed";
+  << Name
+  << "no alternative argument provided because "
+ "AVX10/256 is not supported and will be removed";
 
 if (A->getOption().matches(options::OPT_mapx_features_EQ) ||
 A->getOption().matches(options::OPT_mno_apx_features_EQ)) {
diff --git a/clang/test/Driver/x86-target-features.c 
b/clang/test/Driver/x86-target-features.c
index 6416a34898e78..9c18098c87026 100644
--- a/clang/test/Driver/x86-target-features.c
+++ b/clang/test/Driver/x86-target-features.c
@@ -411,8 +411,8 @@
 // RUN: %clang --target=i386 -mavx10.2-512 %s -### -o %t.o 2>&1 | FileCheck 
-check-prefixes=AVX10_2_512,WARN-AVX10-512 %s
 // RUN: %clang --target=i386 -mavx10.2-256 -mavx10.1-512 %s -### -o %t.o 2>&1 
| FileCheck -check-prefixes=AVX10_2_256,AVX10_1_512 %s
 // RUN: %clang --target=i386 -mavx10.2-512 -mavx10.1-256 %s -### -o %t.o 2>&1 
| FileCheck -check-prefixes=AVX10_2_512,AVX10_1_256 %s
-// WARN-EVEX512: warning: argument '{{.*}}evex512' is deprecated, because 
AVX10/256 is not supported and will be removed [-Wdeprecated]
-// WARN-AVX10-256: warning: argument 'avx10.{{.*}}-256' is deprecated, because 
AVX10/256 is not supported and will be removed [-Wdeprecated]
+// WARN-EVEX512: warning: argument '{{.*}}evex512' is deprecated, no 
alternative argument provided because AVX10/256 is not supported and will be 
removed [-Wdeprecated]
+// WARN-AVX10-256: warning: argument 'avx10.{{.*}}-256' is deprecated, no 
alternative argument provided because AVX10/256 is not supported and will be 
removed [-Wdeprecated]
 // WARN-AVX10-512: warning: argument 'avx10.{{.*}}-512' is deprecated, use 
'avx10.{{.*}}' instead [-Wdeprecated]
 // EVEX512: "-target-feature" "+evex512"
 // NO-EVEX512: "-target-feature" "-evex512"

``




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


[clang] [CIR] Upstream ArraySubscriptExpr for fixed size array (PR #134536)

2025-04-06 Thread Amr Hesham via cfe-commits

https://github.com/AmrDeveloper created 
https://github.com/llvm/llvm-project/pull/134536

This change adds ArraySubscriptExpr for fixed size ArrayType

Issue #130197

>From 81e1cd76594d3eaeda67d5888e5e5daa63fb0e12 Mon Sep 17 00:00:00 2001
From: AmrDeveloper 
Date: Sun, 6 Apr 2025 14:31:35 +0200
Subject: [PATCH] [CIR] Upstream ArraySubscriptExpr for fixed size array

---
 clang/include/clang/CIR/MissingFeatures.h  |   1 +
 clang/lib/CIR/CodeGen/CIRGenBuilder.cpp|  40 ++
 clang/lib/CIR/CodeGen/CIRGenBuilder.h  |  13 ++
 clang/lib/CIR/CodeGen/CIRGenExpr.cpp   | 156 +
 clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp |   9 ++
 clang/lib/CIR/CodeGen/CIRGenFunction.cpp   |   2 +
 clang/lib/CIR/CodeGen/CIRGenFunction.h |   2 +
 clang/lib/CIR/CodeGen/CMakeLists.txt   |   1 +
 clang/test/CIR/CodeGen/array.cpp   |  21 ++-
 clang/test/CIR/Lowering/array.cpp  |  34 +++--
 10 files changed, 268 insertions(+), 11 deletions(-)
 create mode 100644 clang/lib/CIR/CodeGen/CIRGenBuilder.cpp

diff --git a/clang/include/clang/CIR/MissingFeatures.h 
b/clang/include/clang/CIR/MissingFeatures.h
index 86fdaf1ddaf51..6872f50565721 100644
--- a/clang/include/clang/CIR/MissingFeatures.h
+++ b/clang/include/clang/CIR/MissingFeatures.h
@@ -108,6 +108,7 @@ struct MissingFeatures {
   static bool cgFPOptionsRAII() { return false; }
   static bool metaDataNode() { return false; }
   static bool fastMathFlags() { return false; }
+  static bool emitCheckedInBoundsGEP() { return false; }
 
   // Missing types
   static bool dataMemberType() { return false; }
diff --git a/clang/lib/CIR/CodeGen/CIRGenBuilder.cpp 
b/clang/lib/CIR/CodeGen/CIRGenBuilder.cpp
new file mode 100644
index 0..2f1940e656172
--- /dev/null
+++ b/clang/lib/CIR/CodeGen/CIRGenBuilder.cpp
@@ -0,0 +1,40 @@
+//===--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "CIRGenBuilder.h"
+
+using namespace clang::CIRGen;
+
+mlir::Value CIRGenBuilderTy::maybeBuildArrayDecay(mlir::Location loc,
+  mlir::Value arrayPtr,
+  mlir::Type eltTy) {
+  const auto arrayPtrTy = mlir::cast(arrayPtr.getType());
+  const auto arrayTy = mlir::dyn_cast(arrayPtrTy.getPointee());
+
+  if (arrayTy) {
+const cir::PointerType flatPtrTy = getPointerTo(arrayTy.getEltType());
+return create(loc, flatPtrTy, 
cir::CastKind::array_to_ptrdecay,
+   arrayPtr);
+  }
+
+  assert(arrayPtrTy.getPointee() == eltTy &&
+ "flat pointee type must match original array element type");
+  return arrayPtr;
+}
+
+mlir::Value CIRGenBuilderTy::getArrayElement(mlir::Location arrayLocBegin,
+ mlir::Location arrayLocEnd,
+ mlir::Value arrayPtr,
+ mlir::Type eltTy, mlir::Value idx,
+ bool shouldDecay) {
+  mlir::Value basePtr = arrayPtr;
+  if (shouldDecay)
+basePtr = maybeBuildArrayDecay(arrayLocBegin, arrayPtr, eltTy);
+  const mlir::Type flatPtrTy = basePtr.getType();
+  return create(arrayLocEnd, flatPtrTy, basePtr, idx);
+}
diff --git a/clang/lib/CIR/CodeGen/CIRGenBuilder.h 
b/clang/lib/CIR/CodeGen/CIRGenBuilder.h
index 61a747254b3d0..e659a8fbf4eff 100644
--- a/clang/lib/CIR/CodeGen/CIRGenBuilder.h
+++ b/clang/lib/CIR/CodeGen/CIRGenBuilder.h
@@ -198,6 +198,19 @@ class CIRGenBuilderTy : public cir::CIRBaseBuilderTy {
 
 return create(loc, cir::BinOpKind::Div, lhs, rhs);
   }
+
+  /// Create a cir.ptr_stride operation to get access to an array element.
+  /// idx is the index of the element to access, shouldDecay is true if the
+  /// result should decay to a pointer to the element type.
+  mlir::Value getArrayElement(mlir::Location arrayLocBegin,
+  mlir::Location arrayLocEnd, mlir::Value arrayPtr,
+  mlir::Type eltTy, mlir::Value idx,
+  bool shouldDecay);
+
+  /// Returns a decayed pointer to the first element of the array
+  /// pointed to by arrayPtr.
+  mlir::Value maybeBuildArrayDecay(mlir::Location loc, mlir::Value arrayPtr,
+   mlir::Type eltTy);
 };
 
 } // namespace clang::CIRGen
diff --git a/clang/lib/CIR/CodeGen/CIRGenExpr.cpp 
b/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
index f01e03a89981d..f1a15e46265b5 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
@@ -12,6 +12,7 @@
 
 #include "Address.h"
 #include "CIRGenFunction.h"
+#include "CIRGenModule.h"
 #inclu

[clang] [CIR] Upstream ArraySubscriptExpr for fixed size array (PR #134536)

2025-04-06 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clangir

Author: Amr Hesham (AmrDeveloper)


Changes

This change adds ArraySubscriptExpr for fixed size ArrayType

Issue #130197

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


10 Files Affected:

- (modified) clang/include/clang/CIR/MissingFeatures.h (+1) 
- (added) clang/lib/CIR/CodeGen/CIRGenBuilder.cpp (+40) 
- (modified) clang/lib/CIR/CodeGen/CIRGenBuilder.h (+13) 
- (modified) clang/lib/CIR/CodeGen/CIRGenExpr.cpp (+156) 
- (modified) clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp (+9) 
- (modified) clang/lib/CIR/CodeGen/CIRGenFunction.cpp (+2) 
- (modified) clang/lib/CIR/CodeGen/CIRGenFunction.h (+2) 
- (modified) clang/lib/CIR/CodeGen/CMakeLists.txt (+1) 
- (modified) clang/test/CIR/CodeGen/array.cpp (+20-1) 
- (modified) clang/test/CIR/Lowering/array.cpp (+24-10) 


``diff
diff --git a/clang/include/clang/CIR/MissingFeatures.h 
b/clang/include/clang/CIR/MissingFeatures.h
index 86fdaf1ddaf51..6872f50565721 100644
--- a/clang/include/clang/CIR/MissingFeatures.h
+++ b/clang/include/clang/CIR/MissingFeatures.h
@@ -108,6 +108,7 @@ struct MissingFeatures {
   static bool cgFPOptionsRAII() { return false; }
   static bool metaDataNode() { return false; }
   static bool fastMathFlags() { return false; }
+  static bool emitCheckedInBoundsGEP() { return false; }
 
   // Missing types
   static bool dataMemberType() { return false; }
diff --git a/clang/lib/CIR/CodeGen/CIRGenBuilder.cpp 
b/clang/lib/CIR/CodeGen/CIRGenBuilder.cpp
new file mode 100644
index 0..2f1940e656172
--- /dev/null
+++ b/clang/lib/CIR/CodeGen/CIRGenBuilder.cpp
@@ -0,0 +1,40 @@
+//===--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "CIRGenBuilder.h"
+
+using namespace clang::CIRGen;
+
+mlir::Value CIRGenBuilderTy::maybeBuildArrayDecay(mlir::Location loc,
+  mlir::Value arrayPtr,
+  mlir::Type eltTy) {
+  const auto arrayPtrTy = mlir::cast(arrayPtr.getType());
+  const auto arrayTy = mlir::dyn_cast(arrayPtrTy.getPointee());
+
+  if (arrayTy) {
+const cir::PointerType flatPtrTy = getPointerTo(arrayTy.getEltType());
+return create(loc, flatPtrTy, 
cir::CastKind::array_to_ptrdecay,
+   arrayPtr);
+  }
+
+  assert(arrayPtrTy.getPointee() == eltTy &&
+ "flat pointee type must match original array element type");
+  return arrayPtr;
+}
+
+mlir::Value CIRGenBuilderTy::getArrayElement(mlir::Location arrayLocBegin,
+ mlir::Location arrayLocEnd,
+ mlir::Value arrayPtr,
+ mlir::Type eltTy, mlir::Value idx,
+ bool shouldDecay) {
+  mlir::Value basePtr = arrayPtr;
+  if (shouldDecay)
+basePtr = maybeBuildArrayDecay(arrayLocBegin, arrayPtr, eltTy);
+  const mlir::Type flatPtrTy = basePtr.getType();
+  return create(arrayLocEnd, flatPtrTy, basePtr, idx);
+}
diff --git a/clang/lib/CIR/CodeGen/CIRGenBuilder.h 
b/clang/lib/CIR/CodeGen/CIRGenBuilder.h
index 61a747254b3d0..e659a8fbf4eff 100644
--- a/clang/lib/CIR/CodeGen/CIRGenBuilder.h
+++ b/clang/lib/CIR/CodeGen/CIRGenBuilder.h
@@ -198,6 +198,19 @@ class CIRGenBuilderTy : public cir::CIRBaseBuilderTy {
 
 return create(loc, cir::BinOpKind::Div, lhs, rhs);
   }
+
+  /// Create a cir.ptr_stride operation to get access to an array element.
+  /// idx is the index of the element to access, shouldDecay is true if the
+  /// result should decay to a pointer to the element type.
+  mlir::Value getArrayElement(mlir::Location arrayLocBegin,
+  mlir::Location arrayLocEnd, mlir::Value arrayPtr,
+  mlir::Type eltTy, mlir::Value idx,
+  bool shouldDecay);
+
+  /// Returns a decayed pointer to the first element of the array
+  /// pointed to by arrayPtr.
+  mlir::Value maybeBuildArrayDecay(mlir::Location loc, mlir::Value arrayPtr,
+   mlir::Type eltTy);
 };
 
 } // namespace clang::CIRGen
diff --git a/clang/lib/CIR/CodeGen/CIRGenExpr.cpp 
b/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
index f01e03a89981d..f1a15e46265b5 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
@@ -12,6 +12,7 @@
 
 #include "Address.h"
 #include "CIRGenFunction.h"
+#include "CIRGenModule.h"
 #include "CIRGenValue.h"
 #include "mlir/IR/BuiltinAttributes.h"
 #include "clang/AST/Attr.h"
@@ -232,6 +233,161 @@ LValue CIRGenFunction::emitUnaryOpLValue(const 
UnaryOperator *e) {
   

[clang] [Clang][Sema] Handle invalid variable template specialization whose type depends on itself (PR #134522)

2025-04-06 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Yanzuo Liu (zwuis)


Changes

Fixes #51347 

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


4 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+2) 
- (modified) clang/include/clang/Basic/DiagnosticSemaKinds.td (+3) 
- (modified) clang/lib/Sema/SemaTemplate.cpp (+7) 
- (modified) clang/test/SemaTemplate/instantiate-var-template.cpp (+18) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 5217e04b5e83f..9e0fe8a94729b 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -414,6 +414,8 @@ Bug Fixes to C++ Support
 - Clang now issues an error when placement new is used to modify a 
const-qualified variable
   in a ``constexpr`` function. (#GH131432)
 - Clang now emits a warning when class template argument deduction for alias 
templates is used in C++17. (#GH133806)
+- No longer crashes when instantiating invalid variable template specialization
+  whose type depends on itself. (#GH51347)
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 393bfecf9a36b..0c1da40dba388 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -5259,6 +5259,9 @@ def err_template_member_noparams : Error<
   "extraneous 'template<>' in declaration of member %0">;
 def err_template_tag_noparams : Error<
   "extraneous 'template<>' in declaration of %0 %1">;
+def err_var_template_spec_type_depends_on_self : Error<
+  "the type of variable template specialization %0 declared with deduced type "
+  "%1 depends on itself">;
 
 def warn_unqualified_call_to_std_cast_function : Warning<
   "unqualified call to '%0'">, InGroup>;
diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 153f44f8ec67a..ce54dbbb3b9fe 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -4377,6 +4377,13 @@ Sema::CheckVarTemplateId(VarTemplateDecl *Template, 
SourceLocation TemplateLoc,
   if (VarTemplateSpecializationDecl *Spec =
   Template->findSpecialization(CTAI.CanonicalConverted, InsertPos)) {
 checkSpecializationReachability(TemplateNameLoc, Spec);
+if (Spec->getType()->isUndeducedType()) {
+  // We are substituting the initializer of this variable template
+  // specialization.
+  Diag(TemplateNameLoc, diag::err_var_template_spec_type_depends_on_self)
+  << Spec << Spec->getType();
+  return true;
+}
 // If we already have a variable template specialization, return it.
 return Spec;
   }
diff --git a/clang/test/SemaTemplate/instantiate-var-template.cpp 
b/clang/test/SemaTemplate/instantiate-var-template.cpp
index 60d3bd3b59f53..34a1b9710814b 100644
--- a/clang/test/SemaTemplate/instantiate-var-template.cpp
+++ b/clang/test/SemaTemplate/instantiate-var-template.cpp
@@ -47,3 +47,21 @@ namespace InvalidInsertPos {
   template<> int v;
   int k = v;
 }
+
+namespace GH51347 {
+  template 
+  auto p = p; // expected-error {{the type of variable template 
specialization 'p'}}
+
+  auto x = p; // expected-note {{in instantiation of variable template 
specialization 'GH51347::p'}}
+}
+
+namespace GH97881_comment {
+  template 
+  auto g = sizeof(g);
+  // expected-error@-1 {{the type of variable template specialization 
'g'}}
+  // expected-note@-2 {{in instantiation of variable template specialization 
'GH97881_comment::g'}}
+
+  void test() {
+(void)sizeof(g); // expected-note {{in instantiation of variable 
template specialization 'GH97881_comment::g'}}
+  }
+}

``




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


[clang] [Driver][XCore][NFC] Remove redundant setting of IsIntegratedAssemblerDefault (PR #130397)

2025-04-06 Thread Brad Smith via cfe-commits

https://github.com/brad0 updated 
https://github.com/llvm/llvm-project/pull/130397

>From e3ac24a490948d52b280a4afbc0fa557244932a1 Mon Sep 17 00:00:00 2001
From: Brad Smith 
Date: Fri, 7 Mar 2025 21:50:15 -0500
Subject: [PATCH] [Driver][XCore][NFC] Remove redundant setting of
 IsIntegratedAssemblerDefault

IsIntegratedAssemblerDefault is already set in
Generic_GCC::IsIntegratedAssemblerDefault
---
 clang/lib/Driver/ToolChains/XCore.h | 1 -
 1 file changed, 1 deletion(-)

diff --git a/clang/lib/Driver/ToolChains/XCore.h 
b/clang/lib/Driver/ToolChains/XCore.h
index 95359a6e2542f..d7d1065e66e74 100644
--- a/clang/lib/Driver/ToolChains/XCore.h
+++ b/clang/lib/Driver/ToolChains/XCore.h
@@ -57,7 +57,6 @@ class LLVM_LIBRARY_VISIBILITY XCoreToolChain : public 
ToolChain {
   Tool *buildLinker() const override;
 
 public:
-  bool IsIntegratedAssemblerDefault() const override { return false; }
   bool isPICDefault() const override;
   bool isPIEDefault(const llvm::opt::ArgList &Args) const override;
   bool isPICDefaultForced() const override;

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


[clang] [clang-format] Add 'cl' to enable OpenCL kernel file formatting (PR #134529)

2025-04-06 Thread Wenju He via cfe-commits

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


[clang] [Clang][AMDGPU] Enable `avail-extern-to-local` for ThinLTO in HIP (PR #134476)

2025-04-06 Thread Shilei Tian via cfe-commits

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

>From b537a910f5869c9267ba20793d1531d63a205fdb Mon Sep 17 00:00:00 2001
From: Shilei Tian 
Date: Sun, 6 Apr 2025 11:24:24 -0400
Subject: [PATCH] [Clang][AMDGPU] Enable `avail-extern-to-local` for ThinLTO in
 HIP

In HIP, the Clang driver already sets `force-import-all` when ThinLTO is
enabled. As a result, all imported functions get the `available_externally`
linkage. However, these functions are later removed by the
`EliminateAvailableExternallyPass`, effectively undoing the forced import and
eventually leading to link errors.

The `EliminateAvailableExternallyPass` provides an option to convert
`available_externally` functions into local functions, renaming them to avoid
conflicts. This behavior is exactly what we need for HIP. This PR enables that
option (`avail-extern-to-local`) alongside `force-import-all` when ThinLTO is
used.

With this change, ThinLTO almost works correctly on AMDGPU. The only remaining
issue is an undefined reference to `__assert_fail`, but that falls outside the
scope of this PR.
---
 clang/lib/Driver/ToolChains/HIPAMD.cpp | 4 +++-
 clang/test/Driver/hip-thinlto.hip  | 8 
 2 files changed, 11 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/Driver/hip-thinlto.hip

diff --git a/clang/lib/Driver/ToolChains/HIPAMD.cpp 
b/clang/lib/Driver/ToolChains/HIPAMD.cpp
index abb83701759ce..0c25a40d94a10 100644
--- a/clang/lib/Driver/ToolChains/HIPAMD.cpp
+++ b/clang/lib/Driver/ToolChains/HIPAMD.cpp
@@ -103,8 +103,10 @@ void AMDGCN::Linker::constructLldCommand(Compilation &C, 
const JobAction &JA,
   // ToDo: Remove this option after AMDGPU backend supports ISA-level linking.
   // Since AMDGPU backend currently does not support ISA-level linking, all
   // called functions need to be imported.
-  if (IsThinLTO)
+  if (IsThinLTO) {
 LldArgs.push_back(Args.MakeArgString("-plugin-opt=-force-import-all"));
+
LldArgs.push_back(Args.MakeArgString("-plugin-opt=-avail-extern-to-local"));
+  }
 
   for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
 LldArgs.push_back(
diff --git a/clang/test/Driver/hip-thinlto.hip 
b/clang/test/Driver/hip-thinlto.hip
new file mode 100644
index 0..3db513873ebb7
--- /dev/null
+++ b/clang/test/Driver/hip-thinlto.hip
@@ -0,0 +1,8 @@
+// RUN: %clang -foffload-lto=thin %s -### 2>&1 | FileCheck %s
+
+// CHECK: -plugin-opt=thinlto
+// CHECK-SAME: -plugin-opt=-force-import-all
+// CHECK-SAME: -plugin-opt=-avail-extern-to-local
+int main(int, char *[]) {
+  return 0;
+}

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


[clang] [Clang][AMDGPU] Enable `avail-extern-to-local` for ThinLTO in HIP (PR #134476)

2025-04-06 Thread Shilei Tian via cfe-commits

shiltian wrote:

Hmm, the failure is weird. I can't reproduce it locally. Change it to something 
else and hopefully this can "resolve" the issue.

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


[clang] [alpha.webkit.ForwardDeclChecker] Recognize a forward declared template specialization (PR #134545)

2025-04-06 Thread via cfe-commits

llvmbot wrote:




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

Author: Ryosuke Niwa (rniwa)


Changes

This PR fixes a bug that when a template specialization is declared with a 
forward declaration of a template, the checker fails to find its definition in 
the same translation unit and erroneously emit an unsafe forward declaration 
warning.

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


2 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Checkers/WebKit/ForwardDeclChecker.cpp 
(+12-2) 
- (modified) clang/test/Analysis/Checkers/WebKit/forward-decl-checker.mm (+17) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/ForwardDeclChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/ForwardDeclChecker.cpp
index 2c63224df129a..4f63e5ed866ed 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/ForwardDeclChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/ForwardDeclChecker.cpp
@@ -125,8 +125,18 @@ class ForwardDeclChecker : public 
Checker> {
 if (!R) // Forward declaration of a Objective-C interface is safe.
   return false;
 auto Name = R->getName();
-return !R->hasDefinition() && !RTC.isUnretained(QT) &&
-   !SystemTypes.contains(CanonicalType) &&
+if (R->hasDefinition())
+  return false;
+// Find a definition amongst template declarations.
+if (auto *Specialization = dyn_cast(R)) {
+  if (auto* S = Specialization->getSpecializedTemplate()) {
+for (S = S->getMostRecentDecl(); S; S = S->getPreviousDecl()) {
+  if (S->isThisDeclarationADefinition())
+return false;
+}
+  }
+}
+return !RTC.isUnretained(QT) && !SystemTypes.contains(CanonicalType) &&
!SystemTypes.contains(PointeeType) && !Name.starts_with("Opaque") &&
Name != "_NSZone";
   }
diff --git a/clang/test/Analysis/Checkers/WebKit/forward-decl-checker.mm 
b/clang/test/Analysis/Checkers/WebKit/forward-decl-checker.mm
index 64100d60c4867..084b47322d7f9 100644
--- a/clang/test/Analysis/Checkers/WebKit/forward-decl-checker.mm
+++ b/clang/test/Analysis/Checkers/WebKit/forward-decl-checker.mm
@@ -138,3 +138,20 @@ - (void)doMoreWork:(ObjCObj *)obj {
 }
 
 @end
+
+namespace template_forward_declare {
+
+template class HashSet;
+
+template
+using SingleThreadHashSet = HashSet;
+
+template class HashSet { };
+
+struct Font { };
+
+struct ComplexTextController {
+SingleThreadHashSet* fallbackFonts { nullptr };
+};
+
+}

``




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


[clang] [alpha.webkit.ForwardDeclChecker] Recognize a forward declared template specialization (PR #134545)

2025-04-06 Thread Ryosuke Niwa via cfe-commits

https://github.com/rniwa created 
https://github.com/llvm/llvm-project/pull/134545

This PR fixes a bug that when a template specialization is declared with a 
forward declaration of a template, the checker fails to find its definition in 
the same translation unit and erroneously emit an unsafe forward declaration 
warning.

>From a6c4a36a0c7a9b24e0f44748f3d92eee013ab645 Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Sun, 6 Apr 2025 09:26:33 -0700
Subject: [PATCH] [alpha.webkit.ForwardDeclChecker] Recognize a forward
 declared template specialization

This PR fixes a bug that when a template specialization is declared with a 
forward declaration
of a template, the checker fails to find its definition in the same translation 
unit and
erroneously emit an unsafe forward declaration warning.
---
 .../Checkers/WebKit/ForwardDeclChecker.cpp  | 14 --
 .../Checkers/WebKit/forward-decl-checker.mm | 17 +
 2 files changed, 29 insertions(+), 2 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/ForwardDeclChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/ForwardDeclChecker.cpp
index 2c63224df129a..4f63e5ed866ed 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/ForwardDeclChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/ForwardDeclChecker.cpp
@@ -125,8 +125,18 @@ class ForwardDeclChecker : public 
Checker> {
 if (!R) // Forward declaration of a Objective-C interface is safe.
   return false;
 auto Name = R->getName();
-return !R->hasDefinition() && !RTC.isUnretained(QT) &&
-   !SystemTypes.contains(CanonicalType) &&
+if (R->hasDefinition())
+  return false;
+// Find a definition amongst template declarations.
+if (auto *Specialization = dyn_cast(R)) {
+  if (auto* S = Specialization->getSpecializedTemplate()) {
+for (S = S->getMostRecentDecl(); S; S = S->getPreviousDecl()) {
+  if (S->isThisDeclarationADefinition())
+return false;
+}
+  }
+}
+return !RTC.isUnretained(QT) && !SystemTypes.contains(CanonicalType) &&
!SystemTypes.contains(PointeeType) && !Name.starts_with("Opaque") &&
Name != "_NSZone";
   }
diff --git a/clang/test/Analysis/Checkers/WebKit/forward-decl-checker.mm 
b/clang/test/Analysis/Checkers/WebKit/forward-decl-checker.mm
index 64100d60c4867..084b47322d7f9 100644
--- a/clang/test/Analysis/Checkers/WebKit/forward-decl-checker.mm
+++ b/clang/test/Analysis/Checkers/WebKit/forward-decl-checker.mm
@@ -138,3 +138,20 @@ - (void)doMoreWork:(ObjCObj *)obj {
 }
 
 @end
+
+namespace template_forward_declare {
+
+template class HashSet;
+
+template
+using SingleThreadHashSet = HashSet;
+
+template class HashSet { };
+
+struct Font { };
+
+struct ComplexTextController {
+SingleThreadHashSet* fallbackFonts { nullptr };
+};
+
+}

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


[clang] [alpha.webkit.ForwardDeclChecker] Recognize a forward declared template specialization (PR #134545)

2025-04-06 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 HEAD~1 HEAD --extensions cpp -- 
clang/lib/StaticAnalyzer/Checkers/WebKit/ForwardDeclChecker.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/ForwardDeclChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/ForwardDeclChecker.cpp
index 4f63e5ed8..73a0e9eda 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/ForwardDeclChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/ForwardDeclChecker.cpp
@@ -129,7 +129,7 @@ public:
   return false;
 // Find a definition amongst template declarations.
 if (auto *Specialization = dyn_cast(R)) {
-  if (auto* S = Specialization->getSpecializedTemplate()) {
+  if (auto *S = Specialization->getSpecializedTemplate()) {
 for (S = S->getMostRecentDecl(); S; S = S->getPreviousDecl()) {
   if (S->isThisDeclarationADefinition())
 return false;

``




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


[clang] [alpha.webkit.ForwardDeclChecker] Recognize a forward declared template specialization (PR #134545)

2025-04-06 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Ryosuke Niwa (rniwa)


Changes

This PR fixes a bug that when a template specialization is declared with a 
forward declaration of a template, the checker fails to find its definition in 
the same translation unit and erroneously emit an unsafe forward declaration 
warning.

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


2 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Checkers/WebKit/ForwardDeclChecker.cpp 
(+12-2) 
- (modified) clang/test/Analysis/Checkers/WebKit/forward-decl-checker.mm (+17) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/ForwardDeclChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/ForwardDeclChecker.cpp
index 2c63224df129a..4f63e5ed866ed 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/ForwardDeclChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/ForwardDeclChecker.cpp
@@ -125,8 +125,18 @@ class ForwardDeclChecker : public 
Checker> {
 if (!R) // Forward declaration of a Objective-C interface is safe.
   return false;
 auto Name = R->getName();
-return !R->hasDefinition() && !RTC.isUnretained(QT) &&
-   !SystemTypes.contains(CanonicalType) &&
+if (R->hasDefinition())
+  return false;
+// Find a definition amongst template declarations.
+if (auto *Specialization = dyn_cast(R)) {
+  if (auto* S = Specialization->getSpecializedTemplate()) {
+for (S = S->getMostRecentDecl(); S; S = S->getPreviousDecl()) {
+  if (S->isThisDeclarationADefinition())
+return false;
+}
+  }
+}
+return !RTC.isUnretained(QT) && !SystemTypes.contains(CanonicalType) &&
!SystemTypes.contains(PointeeType) && !Name.starts_with("Opaque") &&
Name != "_NSZone";
   }
diff --git a/clang/test/Analysis/Checkers/WebKit/forward-decl-checker.mm 
b/clang/test/Analysis/Checkers/WebKit/forward-decl-checker.mm
index 64100d60c4867..084b47322d7f9 100644
--- a/clang/test/Analysis/Checkers/WebKit/forward-decl-checker.mm
+++ b/clang/test/Analysis/Checkers/WebKit/forward-decl-checker.mm
@@ -138,3 +138,20 @@ - (void)doMoreWork:(ObjCObj *)obj {
 }
 
 @end
+
+namespace template_forward_declare {
+
+template class HashSet;
+
+template
+using SingleThreadHashSet = HashSet;
+
+template class HashSet { };
+
+struct Font { };
+
+struct ComplexTextController {
+SingleThreadHashSet* fallbackFonts { nullptr };
+};
+
+}

``




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


[clang] [alpha.webkit.ForwardDeclChecker] Recognize a forward declared template specialization (PR #134545)

2025-04-06 Thread Ryosuke Niwa via cfe-commits

https://github.com/rniwa updated 
https://github.com/llvm/llvm-project/pull/134545

>From a6c4a36a0c7a9b24e0f44748f3d92eee013ab645 Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Sun, 6 Apr 2025 09:26:33 -0700
Subject: [PATCH 1/2] [alpha.webkit.ForwardDeclChecker] Recognize a forward
 declared template specialization

This PR fixes a bug that when a template specialization is declared with a 
forward declaration
of a template, the checker fails to find its definition in the same translation 
unit and
erroneously emit an unsafe forward declaration warning.
---
 .../Checkers/WebKit/ForwardDeclChecker.cpp  | 14 --
 .../Checkers/WebKit/forward-decl-checker.mm | 17 +
 2 files changed, 29 insertions(+), 2 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/ForwardDeclChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/ForwardDeclChecker.cpp
index 2c63224df129a..4f63e5ed866ed 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/ForwardDeclChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/ForwardDeclChecker.cpp
@@ -125,8 +125,18 @@ class ForwardDeclChecker : public 
Checker> {
 if (!R) // Forward declaration of a Objective-C interface is safe.
   return false;
 auto Name = R->getName();
-return !R->hasDefinition() && !RTC.isUnretained(QT) &&
-   !SystemTypes.contains(CanonicalType) &&
+if (R->hasDefinition())
+  return false;
+// Find a definition amongst template declarations.
+if (auto *Specialization = dyn_cast(R)) {
+  if (auto* S = Specialization->getSpecializedTemplate()) {
+for (S = S->getMostRecentDecl(); S; S = S->getPreviousDecl()) {
+  if (S->isThisDeclarationADefinition())
+return false;
+}
+  }
+}
+return !RTC.isUnretained(QT) && !SystemTypes.contains(CanonicalType) &&
!SystemTypes.contains(PointeeType) && !Name.starts_with("Opaque") &&
Name != "_NSZone";
   }
diff --git a/clang/test/Analysis/Checkers/WebKit/forward-decl-checker.mm 
b/clang/test/Analysis/Checkers/WebKit/forward-decl-checker.mm
index 64100d60c4867..084b47322d7f9 100644
--- a/clang/test/Analysis/Checkers/WebKit/forward-decl-checker.mm
+++ b/clang/test/Analysis/Checkers/WebKit/forward-decl-checker.mm
@@ -138,3 +138,20 @@ - (void)doMoreWork:(ObjCObj *)obj {
 }
 
 @end
+
+namespace template_forward_declare {
+
+template class HashSet;
+
+template
+using SingleThreadHashSet = HashSet;
+
+template class HashSet { };
+
+struct Font { };
+
+struct ComplexTextController {
+SingleThreadHashSet* fallbackFonts { nullptr };
+};
+
+}

>From 0d26969946b153ff08cdfcabf07bff3e993f47b9 Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Sun, 6 Apr 2025 09:39:24 -0700
Subject: [PATCH 2/2] Fix formatting.

---
 clang/lib/StaticAnalyzer/Checkers/WebKit/ForwardDeclChecker.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/ForwardDeclChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/ForwardDeclChecker.cpp
index 4f63e5ed866ed..73a0e9eda5b20 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/ForwardDeclChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/ForwardDeclChecker.cpp
@@ -129,7 +129,7 @@ class ForwardDeclChecker : public 
Checker> {
   return false;
 // Find a definition amongst template declarations.
 if (auto *Specialization = dyn_cast(R)) {
-  if (auto* S = Specialization->getSpecializedTemplate()) {
+  if (auto *S = Specialization->getSpecializedTemplate()) {
 for (S = S->getMostRecentDecl(); S; S = S->getPreviousDecl()) {
   if (S->isThisDeclarationADefinition())
 return false;

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


[clang] [llvm] [LLVM][Clang][Cygwin] Fix Cygwin builds (PR #134458)

2025-04-06 Thread via cfe-commits
Mateusz =?utf-8?q?Mikuła?= ,
Mateusz =?utf-8?q?Mikuła?= ,
Mateusz =?utf-8?q?Mikuła?= 
Message-ID:
In-Reply-To: 



@@ -236,8 +236,7 @@ class ItaniumCXXABI : public CXXABI {
 
   CallingConv getDefaultMethodCallConv(bool isVariadic) const override {
 const llvm::Triple &T = Context.getTargetInfo().getTriple();
-if (!isVariadic && T.isWindowsGNUEnvironment() &&
-T.getArch() == llvm::Triple::x86)
+if (!isVariadic && T.isOSCygMing() && T.getArch() == llvm::Triple::x86)

jeremyd2019 wrote:

I know this PR is closed, but for the record: this particular change appears to 
be wrong: on i686 cygwin with this change calls to libstdc++ 
basic_string::_M_assign crashed, but with this change backed out it's much 
happier.

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


[clang] clang_EvalResult_getAsCXString impl (PR #134551)

2025-04-06 Thread Damian Andrei via cfe-commits

xTachyon wrote:

@AaronBallman :smile: 

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


[clang] [CIR] Add if statement support (PR #134333)

2025-04-06 Thread via cfe-commits


@@ -316,6 +316,106 @@ void CIRGenFunction::emitIgnoredExpr(const Expr *e) {
   emitLValue(e);
 }
 
+/// Emit an `if` on a boolean condition, filling `then` and `else` into
+/// appropriated regions.
+mlir::LogicalResult CIRGenFunction::emitIfOnBoolExpr(const Expr *cond,
+ const Stmt *thenS,
+ const Stmt *elseS) {
+  // Attempt to be more accurate as possible with IfOp location, generate
+  // one fused location that has either 2 or 4 total locations, depending
+  // on else's availability.
+  auto getStmtLoc = [this](const Stmt &s) {
+return mlir::FusedLoc::get(&getMLIRContext(),
+   {getLoc(s.getSourceRange().getBegin()),
+getLoc(s.getSourceRange().getEnd())});
+  };
+  mlir::Location thenLoc = getStmtLoc(*thenS);
+  std::optional elseLoc;
+  if (elseS)
+elseLoc = getStmtLoc(*elseS);
+
+  mlir::LogicalResult resThen = mlir::success(), resElse = mlir::success();
+  emitIfOnBoolExpr(
+  cond, /*thenBuilder=*/
+  [&](mlir::OpBuilder &, mlir::Location) {
+LexicalScope lexScope{*this, thenLoc, builder.getInsertionBlock()};
+resThen = emitStmt(thenS, /*useCurrentScope=*/true);
+  },
+  thenLoc,
+  /*elseBuilder=*/
+  [&](mlir::OpBuilder &, mlir::Location) {
+assert(elseLoc && "Invalid location for elseS.");
+LexicalScope lexScope{*this, *elseLoc, builder.getInsertionBlock()};
+resElse = emitStmt(elseS, /*useCurrentScope=*/true);
+  },
+  elseLoc);
+
+  return mlir::LogicalResult::success(resThen.succeeded() &&
+  resElse.succeeded());
+}
+
+/// Emit an `if` on a boolean condition, filling `then` and `else` into
+/// appropriated regions.
+cir::IfOp CIRGenFunction::emitIfOnBoolExpr(
+const clang::Expr *cond, BuilderCallbackRef thenBuilder,
+mlir::Location thenLoc, BuilderCallbackRef elseBuilder,
+std::optional elseLoc) {
+
+  SmallVector ifLocs{thenLoc};
+  if (elseLoc)
+ifLocs.push_back(*elseLoc);
+  mlir::Location loc = mlir::FusedLoc::get(&getMLIRContext(), ifLocs);
+
+  // Emit the code with the fully general case.
+  mlir::Value condV = emitOpOnBoolExpr(loc, cond);
+  return builder.create(loc, condV, elseLoc.has_value(),
+   /*thenBuilder=*/thenBuilder,
+   /*elseBuilder=*/elseBuilder);
+}
+
+/// TODO(cir): PGO data

Andres-Salamanca wrote:

Changes applied Let me know if it looks good now

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


[clang] [CIR] Add if statement support (PR #134333)

2025-04-06 Thread via cfe-commits


@@ -316,6 +316,106 @@ void CIRGenFunction::emitIgnoredExpr(const Expr *e) {
   emitLValue(e);
 }
 
+/// Emit an `if` on a boolean condition, filling `then` and `else` into
+/// appropriated regions.
+mlir::LogicalResult CIRGenFunction::emitIfOnBoolExpr(const Expr *cond,
+ const Stmt *thenS,
+ const Stmt *elseS) {
+  // Attempt to be more accurate as possible with IfOp location, generate
+  // one fused location that has either 2 or 4 total locations, depending
+  // on else's availability.
+  auto getStmtLoc = [this](const Stmt &s) {
+return mlir::FusedLoc::get(&getMLIRContext(),
+   {getLoc(s.getSourceRange().getBegin()),
+getLoc(s.getSourceRange().getEnd())});
+  };
+  mlir::Location thenLoc = getStmtLoc(*thenS);
+  std::optional elseLoc;
+  if (elseS)
+elseLoc = getStmtLoc(*elseS);
+
+  mlir::LogicalResult resThen = mlir::success(), resElse = mlir::success();
+  emitIfOnBoolExpr(
+  cond, /*thenBuilder=*/
+  [&](mlir::OpBuilder &, mlir::Location) {
+LexicalScope lexScope{*this, thenLoc, builder.getInsertionBlock()};
+resThen = emitStmt(thenS, /*useCurrentScope=*/true);
+  },
+  thenLoc,
+  /*elseBuilder=*/
+  [&](mlir::OpBuilder &, mlir::Location) {
+assert(elseLoc && "Invalid location for elseS.");
+LexicalScope lexScope{*this, *elseLoc, builder.getInsertionBlock()};
+resElse = emitStmt(elseS, /*useCurrentScope=*/true);
+  },
+  elseLoc);
+
+  return mlir::LogicalResult::success(resThen.succeeded() &&
+  resElse.succeeded());
+}
+
+/// Emit an `if` on a boolean condition, filling `then` and `else` into
+/// appropriated regions.
+cir::IfOp CIRGenFunction::emitIfOnBoolExpr(
+const clang::Expr *cond, BuilderCallbackRef thenBuilder,
+mlir::Location thenLoc, BuilderCallbackRef elseBuilder,
+std::optional elseLoc) {
+
+  SmallVector ifLocs{thenLoc};
+  if (elseLoc)
+ifLocs.push_back(*elseLoc);
+  mlir::Location loc = mlir::FusedLoc::get(&getMLIRContext(), ifLocs);
+
+  // Emit the code with the fully general case.
+  mlir::Value condV = emitOpOnBoolExpr(loc, cond);
+  return builder.create(loc, condV, elseLoc.has_value(),
+   /*thenBuilder=*/thenBuilder,
+   /*elseBuilder=*/elseBuilder);
+}
+
+/// TODO(cir): PGO data
+/// TODO(cir): see EmitBranchOnBoolExpr for extra ideas).
+mlir::Value CIRGenFunction::emitOpOnBoolExpr(mlir::Location loc,
+ const Expr *cond) {
+  // TODO(CIR): scoped ApplyDebugLocation DL(*this, Cond);
+  // TODO(CIR): __builtin_unpredictable and profile counts?

Andres-Salamanca wrote:

Changes applied Let me know if it looks good now

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


[clang] [CIR] Add if statement support (PR #134333)

2025-04-06 Thread via cfe-commits


@@ -316,6 +316,106 @@ void CIRGenFunction::emitIgnoredExpr(const Expr *e) {
   emitLValue(e);
 }
 
+/// Emit an `if` on a boolean condition, filling `then` and `else` into
+/// appropriated regions.
+mlir::LogicalResult CIRGenFunction::emitIfOnBoolExpr(const Expr *cond,
+ const Stmt *thenS,
+ const Stmt *elseS) {
+  // Attempt to be more accurate as possible with IfOp location, generate
+  // one fused location that has either 2 or 4 total locations, depending
+  // on else's availability.
+  auto getStmtLoc = [this](const Stmt &s) {
+return mlir::FusedLoc::get(&getMLIRContext(),
+   {getLoc(s.getSourceRange().getBegin()),
+getLoc(s.getSourceRange().getEnd())});
+  };
+  mlir::Location thenLoc = getStmtLoc(*thenS);
+  std::optional elseLoc;
+  if (elseS)
+elseLoc = getStmtLoc(*elseS);
+
+  mlir::LogicalResult resThen = mlir::success(), resElse = mlir::success();
+  emitIfOnBoolExpr(
+  cond, /*thenBuilder=*/
+  [&](mlir::OpBuilder &, mlir::Location) {
+LexicalScope lexScope{*this, thenLoc, builder.getInsertionBlock()};
+resThen = emitStmt(thenS, /*useCurrentScope=*/true);
+  },
+  thenLoc,
+  /*elseBuilder=*/
+  [&](mlir::OpBuilder &, mlir::Location) {
+assert(elseLoc && "Invalid location for elseS.");
+LexicalScope lexScope{*this, *elseLoc, builder.getInsertionBlock()};
+resElse = emitStmt(elseS, /*useCurrentScope=*/true);
+  },
+  elseLoc);
+
+  return mlir::LogicalResult::success(resThen.succeeded() &&
+  resElse.succeeded());
+}
+
+/// Emit an `if` on a boolean condition, filling `then` and `else` into
+/// appropriated regions.
+cir::IfOp CIRGenFunction::emitIfOnBoolExpr(
+const clang::Expr *cond, BuilderCallbackRef thenBuilder,
+mlir::Location thenLoc, BuilderCallbackRef elseBuilder,
+std::optional elseLoc) {
+
+  SmallVector ifLocs{thenLoc};
+  if (elseLoc)
+ifLocs.push_back(*elseLoc);
+  mlir::Location loc = mlir::FusedLoc::get(&getMLIRContext(), ifLocs);
+
+  // Emit the code with the fully general case.
+  mlir::Value condV = emitOpOnBoolExpr(loc, cond);
+  return builder.create(loc, condV, elseLoc.has_value(),
+   /*thenBuilder=*/thenBuilder,
+   /*elseBuilder=*/elseBuilder);
+}
+
+/// TODO(cir): PGO data
+/// TODO(cir): see EmitBranchOnBoolExpr for extra ideas).
+mlir::Value CIRGenFunction::emitOpOnBoolExpr(mlir::Location loc,
+ const Expr *cond) {
+  // TODO(CIR): scoped ApplyDebugLocation DL(*this, Cond);
+  // TODO(CIR): __builtin_unpredictable and profile counts?
+  cond = cond->IgnoreParens();
+
+  // if (const BinaryOperator *CondBOp = dyn_cast(cond)) {
+  //   llvm_unreachable("binaryoperator ifstmt NYI");
+  // }
+
+  if (const UnaryOperator *CondUOp = dyn_cast(cond)) {

Andres-Salamanca wrote:

Changes applied Let me know if it looks good now

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


[clang] [CIR] Add if statement support (PR #134333)

2025-04-06 Thread via cfe-commits


@@ -316,6 +316,106 @@ void CIRGenFunction::emitIgnoredExpr(const Expr *e) {
   emitLValue(e);
 }
 
+/// Emit an `if` on a boolean condition, filling `then` and `else` into
+/// appropriated regions.
+mlir::LogicalResult CIRGenFunction::emitIfOnBoolExpr(const Expr *cond,
+ const Stmt *thenS,
+ const Stmt *elseS) {
+  // Attempt to be more accurate as possible with IfOp location, generate
+  // one fused location that has either 2 or 4 total locations, depending
+  // on else's availability.
+  auto getStmtLoc = [this](const Stmt &s) {
+return mlir::FusedLoc::get(&getMLIRContext(),
+   {getLoc(s.getSourceRange().getBegin()),
+getLoc(s.getSourceRange().getEnd())});
+  };
+  mlir::Location thenLoc = getStmtLoc(*thenS);
+  std::optional elseLoc;
+  if (elseS)
+elseLoc = getStmtLoc(*elseS);
+
+  mlir::LogicalResult resThen = mlir::success(), resElse = mlir::success();
+  emitIfOnBoolExpr(
+  cond, /*thenBuilder=*/
+  [&](mlir::OpBuilder &, mlir::Location) {
+LexicalScope lexScope{*this, thenLoc, builder.getInsertionBlock()};
+resThen = emitStmt(thenS, /*useCurrentScope=*/true);
+  },
+  thenLoc,
+  /*elseBuilder=*/
+  [&](mlir::OpBuilder &, mlir::Location) {
+assert(elseLoc && "Invalid location for elseS.");
+LexicalScope lexScope{*this, *elseLoc, builder.getInsertionBlock()};
+resElse = emitStmt(elseS, /*useCurrentScope=*/true);
+  },
+  elseLoc);
+
+  return mlir::LogicalResult::success(resThen.succeeded() &&
+  resElse.succeeded());
+}
+
+/// Emit an `if` on a boolean condition, filling `then` and `else` into
+/// appropriated regions.
+cir::IfOp CIRGenFunction::emitIfOnBoolExpr(
+const clang::Expr *cond, BuilderCallbackRef thenBuilder,
+mlir::Location thenLoc, BuilderCallbackRef elseBuilder,
+std::optional elseLoc) {
+
+  SmallVector ifLocs{thenLoc};
+  if (elseLoc)
+ifLocs.push_back(*elseLoc);
+  mlir::Location loc = mlir::FusedLoc::get(&getMLIRContext(), ifLocs);
+
+  // Emit the code with the fully general case.
+  mlir::Value condV = emitOpOnBoolExpr(loc, cond);
+  return builder.create(loc, condV, elseLoc.has_value(),
+   /*thenBuilder=*/thenBuilder,
+   /*elseBuilder=*/elseBuilder);
+}
+
+/// TODO(cir): PGO data
+/// TODO(cir): see EmitBranchOnBoolExpr for extra ideas).
+mlir::Value CIRGenFunction::emitOpOnBoolExpr(mlir::Location loc,
+ const Expr *cond) {
+  // TODO(CIR): scoped ApplyDebugLocation DL(*this, Cond);

Andres-Salamanca wrote:

Changes applied Let me know if it looks good now

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


[clang] [CIR] Add if statement support (PR #134333)

2025-04-06 Thread via cfe-commits


@@ -316,6 +316,106 @@ void CIRGenFunction::emitIgnoredExpr(const Expr *e) {
   emitLValue(e);
 }
 
+/// Emit an `if` on a boolean condition, filling `then` and `else` into
+/// appropriated regions.
+mlir::LogicalResult CIRGenFunction::emitIfOnBoolExpr(const Expr *cond,
+ const Stmt *thenS,
+ const Stmt *elseS) {
+  // Attempt to be more accurate as possible with IfOp location, generate
+  // one fused location that has either 2 or 4 total locations, depending
+  // on else's availability.
+  auto getStmtLoc = [this](const Stmt &s) {
+return mlir::FusedLoc::get(&getMLIRContext(),
+   {getLoc(s.getSourceRange().getBegin()),
+getLoc(s.getSourceRange().getEnd())});
+  };
+  mlir::Location thenLoc = getStmtLoc(*thenS);
+  std::optional elseLoc;
+  if (elseS)
+elseLoc = getStmtLoc(*elseS);

Andres-Salamanca wrote:

Changes applied Let me know if it looks good now

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


[clang] [CIR] Add if statement support (PR #134333)

2025-04-06 Thread via cfe-commits


@@ -316,6 +316,106 @@ void CIRGenFunction::emitIgnoredExpr(const Expr *e) {
   emitLValue(e);
 }
 
+/// Emit an `if` on a boolean condition, filling `then` and `else` into
+/// appropriated regions.
+mlir::LogicalResult CIRGenFunction::emitIfOnBoolExpr(const Expr *cond,
+ const Stmt *thenS,
+ const Stmt *elseS) {
+  // Attempt to be more accurate as possible with IfOp location, generate
+  // one fused location that has either 2 or 4 total locations, depending
+  // on else's availability.
+  auto getStmtLoc = [this](const Stmt &s) {
+return mlir::FusedLoc::get(&getMLIRContext(),
+   {getLoc(s.getSourceRange().getBegin()),
+getLoc(s.getSourceRange().getEnd())});
+  };
+  mlir::Location thenLoc = getStmtLoc(*thenS);

Andres-Salamanca wrote:

Changes applied Let me know if it looks good now

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


[clang] [CIR] Add if statement support (PR #134333)

2025-04-06 Thread via cfe-commits


@@ -316,6 +316,106 @@ void CIRGenFunction::emitIgnoredExpr(const Expr *e) {
   emitLValue(e);
 }
 
+/// Emit an `if` on a boolean condition, filling `then` and `else` into
+/// appropriated regions.
+mlir::LogicalResult CIRGenFunction::emitIfOnBoolExpr(const Expr *cond,
+ const Stmt *thenS,
+ const Stmt *elseS) {
+  // Attempt to be more accurate as possible with IfOp location, generate
+  // one fused location that has either 2 or 4 total locations, depending
+  // on else's availability.
+  auto getStmtLoc = [this](const Stmt &s) {
+return mlir::FusedLoc::get(&getMLIRContext(),
+   {getLoc(s.getSourceRange().getBegin()),
+getLoc(s.getSourceRange().getEnd())});
+  };
+  mlir::Location thenLoc = getStmtLoc(*thenS);
+  std::optional elseLoc;
+  if (elseS)
+elseLoc = getStmtLoc(*elseS);
+
+  mlir::LogicalResult resThen = mlir::success(), resElse = mlir::success();
+  emitIfOnBoolExpr(
+  cond, /*thenBuilder=*/
+  [&](mlir::OpBuilder &, mlir::Location) {
+LexicalScope lexScope{*this, thenLoc, builder.getInsertionBlock()};
+resThen = emitStmt(thenS, /*useCurrentScope=*/true);
+  },
+  thenLoc,
+  /*elseBuilder=*/
+  [&](mlir::OpBuilder &, mlir::Location) {
+assert(elseLoc && "Invalid location for elseS.");
+LexicalScope lexScope{*this, *elseLoc, builder.getInsertionBlock()};
+resElse = emitStmt(elseS, /*useCurrentScope=*/true);
+  },
+  elseLoc);
+
+  return mlir::LogicalResult::success(resThen.succeeded() &&
+  resElse.succeeded());
+}
+
+/// Emit an `if` on a boolean condition, filling `then` and `else` into
+/// appropriated regions.
+cir::IfOp CIRGenFunction::emitIfOnBoolExpr(
+const clang::Expr *cond, BuilderCallbackRef thenBuilder,
+mlir::Location thenLoc, BuilderCallbackRef elseBuilder,
+std::optional elseLoc) {
+
+  SmallVector ifLocs{thenLoc};
+  if (elseLoc)
+ifLocs.push_back(*elseLoc);
+  mlir::Location loc = mlir::FusedLoc::get(&getMLIRContext(), ifLocs);
+
+  // Emit the code with the fully general case.
+  mlir::Value condV = emitOpOnBoolExpr(loc, cond);
+  return builder.create(loc, condV, elseLoc.has_value(),
+   /*thenBuilder=*/thenBuilder,
+   /*elseBuilder=*/elseBuilder);
+}
+
+/// TODO(cir): PGO data
+/// TODO(cir): see EmitBranchOnBoolExpr for extra ideas).
+mlir::Value CIRGenFunction::emitOpOnBoolExpr(mlir::Location loc,
+ const Expr *cond) {
+  // TODO(CIR): scoped ApplyDebugLocation DL(*this, Cond);
+  // TODO(CIR): __builtin_unpredictable and profile counts?
+  cond = cond->IgnoreParens();
+
+  // if (const BinaryOperator *CondBOp = dyn_cast(cond)) {

Andres-Salamanca wrote:

Changes applied Let me know if it looks good now

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


[clang] [CIR] Add if statement support (PR #134333)

2025-04-06 Thread via cfe-commits


@@ -316,6 +316,106 @@ void CIRGenFunction::emitIgnoredExpr(const Expr *e) {
   emitLValue(e);
 }
 
+/// Emit an `if` on a boolean condition, filling `then` and `else` into
+/// appropriated regions.
+mlir::LogicalResult CIRGenFunction::emitIfOnBoolExpr(const Expr *cond,
+ const Stmt *thenS,
+ const Stmt *elseS) {
+  // Attempt to be more accurate as possible with IfOp location, generate
+  // one fused location that has either 2 or 4 total locations, depending
+  // on else's availability.
+  auto getStmtLoc = [this](const Stmt &s) {
+return mlir::FusedLoc::get(&getMLIRContext(),
+   {getLoc(s.getSourceRange().getBegin()),
+getLoc(s.getSourceRange().getEnd())});
+  };
+  mlir::Location thenLoc = getStmtLoc(*thenS);
+  std::optional elseLoc;
+  if (elseS)
+elseLoc = getStmtLoc(*elseS);
+
+  mlir::LogicalResult resThen = mlir::success(), resElse = mlir::success();
+  emitIfOnBoolExpr(
+  cond, /*thenBuilder=*/
+  [&](mlir::OpBuilder &, mlir::Location) {
+LexicalScope lexScope{*this, thenLoc, builder.getInsertionBlock()};
+resThen = emitStmt(thenS, /*useCurrentScope=*/true);
+  },
+  thenLoc,
+  /*elseBuilder=*/
+  [&](mlir::OpBuilder &, mlir::Location) {
+assert(elseLoc && "Invalid location for elseS.");
+LexicalScope lexScope{*this, *elseLoc, builder.getInsertionBlock()};
+resElse = emitStmt(elseS, /*useCurrentScope=*/true);
+  },
+  elseLoc);
+
+  return mlir::LogicalResult::success(resThen.succeeded() &&
+  resElse.succeeded());
+}
+
+/// Emit an `if` on a boolean condition, filling `then` and `else` into
+/// appropriated regions.
+cir::IfOp CIRGenFunction::emitIfOnBoolExpr(
+const clang::Expr *cond, BuilderCallbackRef thenBuilder,
+mlir::Location thenLoc, BuilderCallbackRef elseBuilder,
+std::optional elseLoc) {
+
+  SmallVector ifLocs{thenLoc};
+  if (elseLoc)
+ifLocs.push_back(*elseLoc);
+  mlir::Location loc = mlir::FusedLoc::get(&getMLIRContext(), ifLocs);
+
+  // Emit the code with the fully general case.
+  mlir::Value condV = emitOpOnBoolExpr(loc, cond);
+  return builder.create(loc, condV, elseLoc.has_value(),
+   /*thenBuilder=*/thenBuilder,
+   /*elseBuilder=*/elseBuilder);
+}
+
+/// TODO(cir): PGO data
+/// TODO(cir): see EmitBranchOnBoolExpr for extra ideas).
+mlir::Value CIRGenFunction::emitOpOnBoolExpr(mlir::Location loc,
+ const Expr *cond) {
+  // TODO(CIR): scoped ApplyDebugLocation DL(*this, Cond);
+  // TODO(CIR): __builtin_unpredictable and profile counts?
+  cond = cond->IgnoreParens();
+
+  // if (const BinaryOperator *CondBOp = dyn_cast(cond)) {
+  //   llvm_unreachable("binaryoperator ifstmt NYI");
+  // }
+
+  if (const UnaryOperator *CondUOp = dyn_cast(cond)) {
+// In LLVM the condition is reversed here for efficient codegen.
+// This should be done in CIR prior to LLVM lowering, if we do now
+// we can make CIR based diagnostics misleading.
+//  cir.ternary(!x, t, f) -> cir.ternary(x, f, t)
+assert(!cir::MissingFeatures::shouldReverseUnaryCondOnBoolExpr());
+  }
+
+  if (const ConditionalOperator *CondOp = dyn_cast(cond)) 
{

Andres-Salamanca wrote:

Changes applied Let me know if it looks good now

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


[clang] [CIR] Add if statement support (PR #134333)

2025-04-06 Thread via cfe-commits


@@ -316,6 +316,106 @@ void CIRGenFunction::emitIgnoredExpr(const Expr *e) {
   emitLValue(e);
 }
 
+/// Emit an `if` on a boolean condition, filling `then` and `else` into
+/// appropriated regions.
+mlir::LogicalResult CIRGenFunction::emitIfOnBoolExpr(const Expr *cond,
+ const Stmt *thenS,
+ const Stmt *elseS) {
+  // Attempt to be more accurate as possible with IfOp location, generate
+  // one fused location that has either 2 or 4 total locations, depending
+  // on else's availability.
+  auto getStmtLoc = [this](const Stmt &s) {
+return mlir::FusedLoc::get(&getMLIRContext(),
+   {getLoc(s.getSourceRange().getBegin()),
+getLoc(s.getSourceRange().getEnd())});
+  };
+  mlir::Location thenLoc = getStmtLoc(*thenS);
+  std::optional elseLoc;
+  if (elseS)
+elseLoc = getStmtLoc(*elseS);
+
+  mlir::LogicalResult resThen = mlir::success(), resElse = mlir::success();
+  emitIfOnBoolExpr(
+  cond, /*thenBuilder=*/
+  [&](mlir::OpBuilder &, mlir::Location) {
+LexicalScope lexScope{*this, thenLoc, builder.getInsertionBlock()};
+resThen = emitStmt(thenS, /*useCurrentScope=*/true);
+  },
+  thenLoc,
+  /*elseBuilder=*/
+  [&](mlir::OpBuilder &, mlir::Location) {
+assert(elseLoc && "Invalid location for elseS.");
+LexicalScope lexScope{*this, *elseLoc, builder.getInsertionBlock()};
+resElse = emitStmt(elseS, /*useCurrentScope=*/true);
+  },
+  elseLoc);
+
+  return mlir::LogicalResult::success(resThen.succeeded() &&
+  resElse.succeeded());
+}
+
+/// Emit an `if` on a boolean condition, filling `then` and `else` into
+/// appropriated regions.
+cir::IfOp CIRGenFunction::emitIfOnBoolExpr(
+const clang::Expr *cond, BuilderCallbackRef thenBuilder,
+mlir::Location thenLoc, BuilderCallbackRef elseBuilder,
+std::optional elseLoc) {
+
+  SmallVector ifLocs{thenLoc};
+  if (elseLoc)
+ifLocs.push_back(*elseLoc);
+  mlir::Location loc = mlir::FusedLoc::get(&getMLIRContext(), ifLocs);
+
+  // Emit the code with the fully general case.
+  mlir::Value condV = emitOpOnBoolExpr(loc, cond);
+  return builder.create(loc, condV, elseLoc.has_value(),
+   /*thenBuilder=*/thenBuilder,
+   /*elseBuilder=*/elseBuilder);
+}
+
+/// TODO(cir): PGO data
+/// TODO(cir): see EmitBranchOnBoolExpr for extra ideas).
+mlir::Value CIRGenFunction::emitOpOnBoolExpr(mlir::Location loc,
+ const Expr *cond) {
+  // TODO(CIR): scoped ApplyDebugLocation DL(*this, Cond);
+  // TODO(CIR): __builtin_unpredictable and profile counts?
+  cond = cond->IgnoreParens();
+
+  // if (const BinaryOperator *CondBOp = dyn_cast(cond)) {
+  //   llvm_unreachable("binaryoperator ifstmt NYI");
+  // }
+
+  if (const UnaryOperator *CondUOp = dyn_cast(cond)) {
+// In LLVM the condition is reversed here for efficient codegen.
+// This should be done in CIR prior to LLVM lowering, if we do now
+// we can make CIR based diagnostics misleading.
+//  cir.ternary(!x, t, f) -> cir.ternary(x, f, t)
+assert(!cir::MissingFeatures::shouldReverseUnaryCondOnBoolExpr());
+  }
+
+  if (const ConditionalOperator *CondOp = dyn_cast(cond)) 
{
+
+cgm.errorNYI(cond->getExprLoc(), "Ternary NYI");
+assert(!cir::MissingFeatures::ternaryOp());
+return createDummyValue(loc, cond->getType());
+  }
+
+  // if (const CXXThrowExpr *Throw = dyn_cast(cond)) {

Andres-Salamanca wrote:

Changes applied Let me know if it looks good now

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


[clang] [CIR] Add if statement support (PR #134333)

2025-04-06 Thread via cfe-commits


@@ -442,6 +457,25 @@ class CIRGenFunction : public CIRGenTypeCache {
   mlir::LogicalResult emitDeclStmt(const clang::DeclStmt &s);
   LValue emitDeclRefLValue(const clang::DeclRefExpr *e);
 
+  /// Emit an if on a boolean condition to the specified blocks.
+  /// FIXME: Based on the condition, this might try to simplify the codegen of
+  /// the conditional based on the branch. TrueCount should be the number of

Andres-Salamanca wrote:

Changes applied Let me know if it looks good now

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


[clang] [CIR] Add if statement support (PR #134333)

2025-04-06 Thread via cfe-commits


@@ -135,6 +135,55 @@ mlir::Location CIRGenFunction::getLoc(mlir::Location lhs, 
mlir::Location rhs) {
   return mlir::FusedLoc::get(locs, metadata, &getMLIRContext());
 }
 
+bool CIRGenFunction::ContainsLabel(const Stmt *s, bool ignoreCaseStmts) {

Andres-Salamanca wrote:

Changes applied Let me know if it looks good now

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


[clang] [CIR] Add if statement support (PR #134333)

2025-04-06 Thread via cfe-commits


@@ -263,6 +264,72 @@ static void terminateBody(CIRGenBuilderTy &builder, 
mlir::Region &r,
 b->erase();
 }
 
+mlir::LogicalResult CIRGenFunction::emitIfStmt(const IfStmt &s) {
+  mlir::LogicalResult res = mlir::success();
+  // The else branch of a consteval if statement is always the only branch
+  // that can be runtime evaluated.
+  const Stmt *ConstevalExecuted;
+  if (s.isConsteval()) {
+ConstevalExecuted = s.isNegatedConsteval() ? s.getThen() : s.getElse();
+if (!ConstevalExecuted) {
+  // No runtime code execution required
+  return res;
+}
+  }
+
+  // C99 6.8.4.1: The first substatement is executed if the expression
+  // compares unequal to 0.  The condition must be a scalar type.
+  auto ifStmtBuilder = [&]() -> mlir::LogicalResult {
+if (s.isConsteval())
+  return emitStmt(ConstevalExecuted, /*useCurrentScope=*/true);
+
+if (s.getInit())
+  if (emitStmt(s.getInit(), /*useCurrentScope=*/true).failed())
+return mlir::failure();
+
+if (s.getConditionVariable())
+  emitDecl(*s.getConditionVariable());
+
+// During LLVM codegen, if the condition constant folds and can be elided,

Andres-Salamanca wrote:

Changes applied Let me know if it looks good now

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


[clang] [CIR] Add if statement support (PR #134333)

2025-04-06 Thread via cfe-commits


@@ -263,6 +264,72 @@ static void terminateBody(CIRGenBuilderTy &builder, 
mlir::Region &r,
 b->erase();
 }
 
+mlir::LogicalResult CIRGenFunction::emitIfStmt(const IfStmt &s) {
+  mlir::LogicalResult res = mlir::success();
+  // The else branch of a consteval if statement is always the only branch
+  // that can be runtime evaluated.
+  const Stmt *ConstevalExecuted;
+  if (s.isConsteval()) {
+ConstevalExecuted = s.isNegatedConsteval() ? s.getThen() : s.getElse();

Andres-Salamanca wrote:

I added the test to a new `if-consteval.cpp`, based on [this 
file](https://github.com/llvm/clangir/blob/main/clang/test/CIR/CodeGen/if-consteval.cpp).
  Since we don't support `call` op yet, I tweaked the test slightly.  
Also added the extra `RUN:` line.


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


[clang] [llvm] [DirectX] Use scalar arguments for @llvm.dx.dot intrinsics (PR #134570)

2025-04-06 Thread Justin Bogner via cfe-commits

https://github.com/bogner created 
https://github.com/llvm/llvm-project/pull/134570

The `dx.dot2`, `dot3`, and `dot4` intrinsics exist purely to lower `dx.fdot`, 
and they map exactly to the DXIL ops of the same name. Using vectors for their 
arguments adds unnecessary complexity and causes us to have vector operations 
that are not trivial to lower post-scalarizer.

Similarly, the `dx.dot2add` intrinsic is overly generic for something that only 
needs to lower to a single `dot2AddHalf` DXIL op. Update its signature to match 
the operation it lowers to.

Fixes #134569.

>From 7f8833f723d4a7d4d69160765477ee646fba1083 Mon Sep 17 00:00:00 2001
From: Justin Bogner 
Date: Wed, 2 Apr 2025 15:21:21 -0700
Subject: [PATCH] [DirectX] Use scalar arguments for @llvm.dx.dot intrinsics

The `dx.dot2`, `dot3`, and `dot4` intrinsics exist purely to lower
`dx.fdot`, and they map exactly to the DXIL ops of the same name. Using
vectors for their arguments adds unnecessary complexity and causes us to
have vector operations that are not trivial to lower post-scalarizer.

Similarly, the `dx.dot2add` intrinsic is overly generic for something
that only needs to lower to a single `dot2AddHalf` DXIL op. Update its
signature to match the operation it lowers to.

Fixes #134569.
---
 clang/lib/CodeGen/CGHLSLBuiltins.cpp  | 11 ++-
 clang/test/CodeGenHLSL/builtins/dot2add.hlsl  | 60 ++---
 llvm/include/llvm/IR/IntrinsicsDirectX.td | 39 +
 llvm/lib/Target/DirectX/DXIL.td   |  3 +-
 .../Target/DirectX/DXILIntrinsicExpansion.cpp | 13 ++-
 llvm/lib/Target/DirectX/DXILOpLowering.cpp| 58 -
 llvm/test/CodeGen/DirectX/dot2_error.ll   |  5 +-
 llvm/test/CodeGen/DirectX/dot2add.ll  | 11 ++-
 llvm/test/CodeGen/DirectX/dot3_error.ll   |  6 +-
 llvm/test/CodeGen/DirectX/dot4_error.ll   |  7 +-
 llvm/test/CodeGen/DirectX/fdot.ll | 86 +--
 llvm/test/CodeGen/DirectX/normalize.ll| 12 +--
 12 files changed, 162 insertions(+), 149 deletions(-)

diff --git a/clang/lib/CodeGen/CGHLSLBuiltins.cpp 
b/clang/lib/CodeGen/CGHLSLBuiltins.cpp
index 27d1c69439944..4e92be0664f71 100644
--- a/clang/lib/CodeGen/CGHLSLBuiltins.cpp
+++ b/clang/lib/CodeGen/CGHLSLBuiltins.cpp
@@ -385,12 +385,17 @@ Value *CodeGenFunction::EmitHLSLBuiltinExpr(unsigned 
BuiltinID,
"Intrinsic dot2add is only allowed for dxil architecture");
 Value *A = EmitScalarExpr(E->getArg(0));
 Value *B = EmitScalarExpr(E->getArg(1));
-Value *C = EmitScalarExpr(E->getArg(2));
+Value *Acc = EmitScalarExpr(E->getArg(2));
+
+Value *AX = Builder.CreateExtractElement(A, Builder.getSize(0));
+Value *AY = Builder.CreateExtractElement(A, Builder.getSize(1));
+Value *BX = Builder.CreateExtractElement(B, Builder.getSize(0));
+Value *BY = Builder.CreateExtractElement(B, Builder.getSize(1));
 
 Intrinsic::ID ID = llvm ::Intrinsic::dx_dot2add;
 return Builder.CreateIntrinsic(
-/*ReturnType=*/C->getType(), ID, ArrayRef{A, B, C}, nullptr,
-"dx.dot2add");
+/*ReturnType=*/Acc->getType(), ID,
+ArrayRef{Acc, AX, AY, BX, BY}, nullptr, "dx.dot2add");
   }
   case Builtin::BI__builtin_hlsl_dot4add_i8packed: {
 Value *A = EmitScalarExpr(E->getArg(0));
diff --git a/clang/test/CodeGenHLSL/builtins/dot2add.hlsl 
b/clang/test/CodeGenHLSL/builtins/dot2add.hlsl
index 2464607dd636c..c345e17476e08 100644
--- a/clang/test/CodeGenHLSL/builtins/dot2add.hlsl
+++ b/clang/test/CodeGenHLSL/builtins/dot2add.hlsl
@@ -13,7 +13,11 @@ float test_default_parameter_type(half2 p1, half2 p2, float 
p3) {
   // CHECK-SPIRV:  %[[CONV:.*]] = fpext reassoc nnan ninf nsz arcp afn half 
%[[MUL]] to float
   // CHECK-SPIRV:  %[[C:.*]] = load float, ptr %c.addr.i, align 4
   // CHECK-SPIRV:  %[[RES:.*]] = fadd reassoc nnan ninf nsz arcp afn float 
%[[CONV]], %[[C]]
-  // CHECK-DXIL:  %[[RES:.*]] = call {{.*}} float @llvm.dx.dot2add.v2f16(<2 x 
half> %{{.*}}, <2 x half> %{{.*}}, float %{{.*}})
+  // CHECK-DXIL:  %[[AX:.*]] = extractelement <2 x half> %{{.*}}, i32 0
+  // CHECK-DXIL:  %[[AY:.*]] = extractelement <2 x half> %{{.*}}, i32 1
+  // CHECK-DXIL:  %[[BX:.*]] = extractelement <2 x half> %{{.*}}, i32 0
+  // CHECK-DXIL:  %[[BY:.*]] = extractelement <2 x half> %{{.*}}, i32 1
+  // CHECK-DXIL:  %[[RES:.*]] = call {{.*}} float @llvm.dx.dot2add(float 
%{{.*}}, half %[[AX]], half %[[AY]], half %[[BX]], half %[[BY]])
   // CHECK:  ret float %[[RES]]
   return dot2add(p1, p2, p3);
 }
@@ -25,7 +29,11 @@ float test_float_arg2_type(half2 p1, float2 p2, float p3) {
   // CHECK-SPIRV:  %[[CONV:.*]] = fpext reassoc nnan ninf nsz arcp afn half 
%[[MUL]] to float
   // CHECK-SPIRV:  %[[C:.*]] = load float, ptr %c.addr.i, align 4
   // CHECK-SPIRV:  %[[RES:.*]] = fadd reassoc nnan ninf nsz arcp afn float 
%[[CONV]], %[[C]]
-  // CHECK-DXIL:  %[[RES:.*]] = call {{.*}} float @llvm.dx.dot2add.v2f16(<2 x 
half> %{{.*}}, <2 x half> %{{.*}}, float %{{.*}})
+  // CHECK-DXIL:  %[

[clang] [clang][doc]: Merge entries with duplicate content. (PR #134089)

2025-04-06 Thread via cfe-commits

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


[clang] [llvm] [DirectX] Use scalar arguments for @llvm.dx.dot intrinsics (PR #134570)

2025-04-06 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Justin Bogner (bogner)


Changes

The `dx.dot2`, `dot3`, and `dot4` intrinsics exist purely to lower `dx.fdot`, 
and they map exactly to the DXIL ops of the same name. Using vectors for their 
arguments adds unnecessary complexity and causes us to have vector operations 
that are not trivial to lower post-scalarizer.

Similarly, the `dx.dot2add` intrinsic is overly generic for something that only 
needs to lower to a single `dot2AddHalf` DXIL op. Update its signature to match 
the operation it lowers to.

Fixes #134569.

---

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


12 Files Affected:

- (modified) clang/lib/CodeGen/CGHLSLBuiltins.cpp (+8-3) 
- (modified) clang/test/CodeGenHLSL/builtins/dot2add.hlsl (+50-10) 
- (modified) llvm/include/llvm/IR/IntrinsicsDirectX.td (+24-15) 
- (modified) llvm/lib/Target/DirectX/DXIL.td (+1-2) 
- (modified) llvm/lib/Target/DirectX/DXILIntrinsicExpansion.cpp (+10-3) 
- (modified) llvm/lib/Target/DirectX/DXILOpLowering.cpp (-58) 
- (modified) llvm/test/CodeGen/DirectX/dot2_error.ll (+3-2) 
- (modified) llvm/test/CodeGen/DirectX/dot2add.ll (+8-3) 
- (modified) llvm/test/CodeGen/DirectX/dot3_error.ll (+4-2) 
- (modified) llvm/test/CodeGen/DirectX/dot4_error.ll (+5-2) 
- (modified) llvm/test/CodeGen/DirectX/fdot.ll (+43-43) 
- (modified) llvm/test/CodeGen/DirectX/normalize.ll (+6-6) 


``diff
diff --git a/clang/lib/CodeGen/CGHLSLBuiltins.cpp 
b/clang/lib/CodeGen/CGHLSLBuiltins.cpp
index 27d1c69439944..4e92be0664f71 100644
--- a/clang/lib/CodeGen/CGHLSLBuiltins.cpp
+++ b/clang/lib/CodeGen/CGHLSLBuiltins.cpp
@@ -385,12 +385,17 @@ Value *CodeGenFunction::EmitHLSLBuiltinExpr(unsigned 
BuiltinID,
"Intrinsic dot2add is only allowed for dxil architecture");
 Value *A = EmitScalarExpr(E->getArg(0));
 Value *B = EmitScalarExpr(E->getArg(1));
-Value *C = EmitScalarExpr(E->getArg(2));
+Value *Acc = EmitScalarExpr(E->getArg(2));
+
+Value *AX = Builder.CreateExtractElement(A, Builder.getSize(0));
+Value *AY = Builder.CreateExtractElement(A, Builder.getSize(1));
+Value *BX = Builder.CreateExtractElement(B, Builder.getSize(0));
+Value *BY = Builder.CreateExtractElement(B, Builder.getSize(1));
 
 Intrinsic::ID ID = llvm ::Intrinsic::dx_dot2add;
 return Builder.CreateIntrinsic(
-/*ReturnType=*/C->getType(), ID, ArrayRef{A, B, C}, nullptr,
-"dx.dot2add");
+/*ReturnType=*/Acc->getType(), ID,
+ArrayRef{Acc, AX, AY, BX, BY}, nullptr, "dx.dot2add");
   }
   case Builtin::BI__builtin_hlsl_dot4add_i8packed: {
 Value *A = EmitScalarExpr(E->getArg(0));
diff --git a/clang/test/CodeGenHLSL/builtins/dot2add.hlsl 
b/clang/test/CodeGenHLSL/builtins/dot2add.hlsl
index 2464607dd636c..c345e17476e08 100644
--- a/clang/test/CodeGenHLSL/builtins/dot2add.hlsl
+++ b/clang/test/CodeGenHLSL/builtins/dot2add.hlsl
@@ -13,7 +13,11 @@ float test_default_parameter_type(half2 p1, half2 p2, float 
p3) {
   // CHECK-SPIRV:  %[[CONV:.*]] = fpext reassoc nnan ninf nsz arcp afn half 
%[[MUL]] to float
   // CHECK-SPIRV:  %[[C:.*]] = load float, ptr %c.addr.i, align 4
   // CHECK-SPIRV:  %[[RES:.*]] = fadd reassoc nnan ninf nsz arcp afn float 
%[[CONV]], %[[C]]
-  // CHECK-DXIL:  %[[RES:.*]] = call {{.*}} float @llvm.dx.dot2add.v2f16(<2 x 
half> %{{.*}}, <2 x half> %{{.*}}, float %{{.*}})
+  // CHECK-DXIL:  %[[AX:.*]] = extractelement <2 x half> %{{.*}}, i32 0
+  // CHECK-DXIL:  %[[AY:.*]] = extractelement <2 x half> %{{.*}}, i32 1
+  // CHECK-DXIL:  %[[BX:.*]] = extractelement <2 x half> %{{.*}}, i32 0
+  // CHECK-DXIL:  %[[BY:.*]] = extractelement <2 x half> %{{.*}}, i32 1
+  // CHECK-DXIL:  %[[RES:.*]] = call {{.*}} float @llvm.dx.dot2add(float 
%{{.*}}, half %[[AX]], half %[[AY]], half %[[BX]], half %[[BY]])
   // CHECK:  ret float %[[RES]]
   return dot2add(p1, p2, p3);
 }
@@ -25,7 +29,11 @@ float test_float_arg2_type(half2 p1, float2 p2, float p3) {
   // CHECK-SPIRV:  %[[CONV:.*]] = fpext reassoc nnan ninf nsz arcp afn half 
%[[MUL]] to float
   // CHECK-SPIRV:  %[[C:.*]] = load float, ptr %c.addr.i, align 4
   // CHECK-SPIRV:  %[[RES:.*]] = fadd reassoc nnan ninf nsz arcp afn float 
%[[CONV]], %[[C]]
-  // CHECK-DXIL:  %[[RES:.*]] = call {{.*}} float @llvm.dx.dot2add.v2f16(<2 x 
half> %{{.*}}, <2 x half> %{{.*}}, float %{{.*}})
+  // CHECK-DXIL:  %[[AX:.*]] = extractelement <2 x half> %{{.*}}, i32 0
+  // CHECK-DXIL:  %[[AY:.*]] = extractelement <2 x half> %{{.*}}, i32 1
+  // CHECK-DXIL:  %[[BX:.*]] = extractelement <2 x half> %{{.*}}, i32 0
+  // CHECK-DXIL:  %[[BY:.*]] = extractelement <2 x half> %{{.*}}, i32 1
+  // CHECK-DXIL:  %[[RES:.*]] = call {{.*}} float @llvm.dx.dot2add(float 
%{{.*}}, half %[[AX]], half %[[AY]], half %[[BX]], half %[[BY]])
   // CHECK:  ret float %[[RES]]
   return dot2add(p1, p2, p3);
 }
@@ -37,7 +45,11 @@ float test_float_arg1_type(float2 p1, half2 p2, float p3) {
  

[clang] [Clang][OpenCL][AMDGPU] Allow a kernel to call another kernel (PR #115821)

2025-04-06 Thread Matt Arsenault via cfe-commits

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


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


[clang] clang_EvalResult_getAsCXString impl (PR #134551)

2025-04-06 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Damian Andrei (xTachyon)


Changes

Tries to implement #69749.

>From Discord:
`
In terms of how to solve it... I'm hoping we can extend CXString to be 
length-aware and then add an interface that returns a CXString object instead. 
Perhaps clang_EvalResult_getAsCXString() with a comment explaining that 
getAsStr() is only valid for null-terminated strings?
`


There's some questions I have:

1. Is `size_t` appropriate here? I see some functions using `unsigned`, and 
some using `size_t`.
2. On this new flow to get a string literal, there's at least 2 allocations of 
the string from the 2 `cxstring::createDup`, one when evaluating the result, 
and one when returning it. Is this ok/can it be done better?
3. Is returning a "null" `CXString` on error a good idea?

There's probably more things that I did wrong, so I'm hoping for a review.

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


6 Files Affected:

- (modified) clang/include/clang-c/CXString.h (+3) 
- (modified) clang/include/clang-c/Index.h (+11-4) 
- (modified) clang/tools/libclang/CIndex.cpp (+19-27) 
- (modified) clang/tools/libclang/CXString.cpp (+16-6) 
- (modified) clang/tools/libclang/libclang.map (+6) 
- (modified) clang/unittests/libclang/LibclangTest.cpp (+41) 


``diff
diff --git a/clang/include/clang-c/CXString.h b/clang/include/clang-c/CXString.h
index 63dce4d140ce2..a0ad830230338 100644
--- a/clang/include/clang-c/CXString.h
+++ b/clang/include/clang-c/CXString.h
@@ -14,6 +14,7 @@
 #ifndef LLVM_CLANG_C_CXSTRING_H
 #define LLVM_CLANG_C_CXSTRING_H
 
+#include 
 #include "clang-c/ExternC.h"
 #include "clang-c/Platform.h"
 
@@ -36,6 +37,7 @@ LLVM_CLANG_C_EXTERN_C_BEGIN
  */
 typedef struct {
   const void *data;
+  size_t length;
   unsigned private_flags;
 } CXString;
 
@@ -52,6 +54,7 @@ typedef struct {
  * to `std::string::c_str()`.
  */
 CINDEX_LINKAGE const char *clang_getCString(CXString string);
+CINDEX_LINKAGE const char *clang_getCString2(CXString string, size_t *length);
 
 /**
  * Free the given string.
diff --git a/clang/include/clang-c/Index.h b/clang/include/clang-c/Index.h
index 38e2417dcd181..4ef41d56e43ae 100644
--- a/clang/include/clang-c/Index.h
+++ b/clang/include/clang-c/Index.h
@@ -5918,12 +5918,19 @@ clang_EvalResult_getAsUnsigned(CXEvalResult E);
 CINDEX_LINKAGE double clang_EvalResult_getAsDouble(CXEvalResult E);
 
 /**
- * Returns the evaluation result as a constant string if the
- * kind is other than Int or float. User must not free this pointer,
- * instead call clang_EvalResult_dispose on the CXEvalResult returned
- * by clang_Cursor_Evaluate.
+ * This function behaves the same as clang_EvalResult_getAsCXString, with 2
+ * exceptions:
+ * - the string literal will be truncated if a nul byte is found in the string.
+ * For this reason clang_EvalResult_getAsCXString is recommended.
+ * - User must not free this pointer, instead call clang_EvalResult_dispose on
+ * the CXEvalResult returned by clang_Cursor_Evaluate.
  */
 CINDEX_LINKAGE const char *clang_EvalResult_getAsStr(CXEvalResult E);
+/**
+ * Returns the evaluation result as a constant string if the
+ * kind is other than Int or float. This might include zero bytes.
+ */
+CINDEX_LINKAGE CXString clang_EvalResult_getAsCXString(CXEvalResult E);
 
 /**
  * Disposes the created Eval memory.
diff --git a/clang/tools/libclang/CIndex.cpp b/clang/tools/libclang/CIndex.cpp
index c8db6c92bb4d4..672e791ad3455 100644
--- a/clang/tools/libclang/CIndex.cpp
+++ b/clang/tools/libclang/CIndex.cpp
@@ -4589,13 +4589,13 @@ struct ExprEvalResult {
 unsigned long long unsignedVal;
 long long intVal;
 double floatVal;
-char *stringVal;
+CXString stringVal;
   } EvalData;
   bool IsUnsignedInt;
   ~ExprEvalResult() {
 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
 EvalType != CXEval_Int) {
-  delete[] EvalData.stringVal;
+  clang_disposeString(EvalData.stringVal);
 }
   }
 };
@@ -4651,7 +4651,17 @@ const char *clang_EvalResult_getAsStr(CXEvalResult E) {
   if (!E) {
 return nullptr;
   }
-  return ((ExprEvalResult *)E)->EvalData.stringVal;
+  return clang_getCString(((ExprEvalResult *)E)->EvalData.stringVal);
+}
+
+CXString clang_EvalResult_getAsCXString(CXEvalResult E) {
+  if (!E) {
+return cxstring::createNull();
+  }
+  size_t length;
+  auto data =
+  clang_getCString2(((ExprEvalResult *)E)->EvalData.stringVal, &length);
+  return cxstring::createDup(StringRef(data, length));
 }
 
 static const ExprEvalResult *evaluateExpr(Expr *expr, CXCursor C) {
@@ -4716,11 +4726,7 @@ static const ExprEvalResult *evaluateExpr(Expr *expr, 
CXCursor C) {
 result->EvalType = CXEval_StrLiteral;
   }
 
-  std::string strRef(StrE->getString().str());
-  result->EvalData.stringVal = new char[strRef.size() + 1];
-  strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
-  strRef.size());
-  result

[clang] clang_EvalResult_getAsCXString impl (PR #134551)

2025-04-06 Thread Damian Andrei via cfe-commits

https://github.com/xTachyon updated 
https://github.com/llvm/llvm-project/pull/134551

>From 88a7517918ff8f6a5521527e9e1a141af09035c5 Mon Sep 17 00:00:00 2001
From: Andrei Damian 
Date: Sun, 6 Apr 2025 19:55:59 +0300
Subject: [PATCH] clang_EvalResult_getAsCXString impl

---
 clang/include/clang-c/CXString.h  |  3 ++
 clang/include/clang-c/Index.h | 15 ++--
 clang/tools/libclang/CIndex.cpp   | 46 ++-
 clang/tools/libclang/CXString.cpp | 22 ---
 clang/tools/libclang/libclang.map |  6 +++
 clang/unittests/libclang/LibclangTest.cpp | 41 
 6 files changed, 96 insertions(+), 37 deletions(-)

diff --git a/clang/include/clang-c/CXString.h b/clang/include/clang-c/CXString.h
index 63dce4d140ce2..a0ad830230338 100644
--- a/clang/include/clang-c/CXString.h
+++ b/clang/include/clang-c/CXString.h
@@ -14,6 +14,7 @@
 #ifndef LLVM_CLANG_C_CXSTRING_H
 #define LLVM_CLANG_C_CXSTRING_H
 
+#include 
 #include "clang-c/ExternC.h"
 #include "clang-c/Platform.h"
 
@@ -36,6 +37,7 @@ LLVM_CLANG_C_EXTERN_C_BEGIN
  */
 typedef struct {
   const void *data;
+  size_t length;
   unsigned private_flags;
 } CXString;
 
@@ -52,6 +54,7 @@ typedef struct {
  * to `std::string::c_str()`.
  */
 CINDEX_LINKAGE const char *clang_getCString(CXString string);
+CINDEX_LINKAGE const char *clang_getCString2(CXString string, size_t *length);
 
 /**
  * Free the given string.
diff --git a/clang/include/clang-c/Index.h b/clang/include/clang-c/Index.h
index 38e2417dcd181..4ef41d56e43ae 100644
--- a/clang/include/clang-c/Index.h
+++ b/clang/include/clang-c/Index.h
@@ -5918,12 +5918,19 @@ clang_EvalResult_getAsUnsigned(CXEvalResult E);
 CINDEX_LINKAGE double clang_EvalResult_getAsDouble(CXEvalResult E);
 
 /**
- * Returns the evaluation result as a constant string if the
- * kind is other than Int or float. User must not free this pointer,
- * instead call clang_EvalResult_dispose on the CXEvalResult returned
- * by clang_Cursor_Evaluate.
+ * This function behaves the same as clang_EvalResult_getAsCXString, with 2
+ * exceptions:
+ * - the string literal will be truncated if a nul byte is found in the string.
+ * For this reason clang_EvalResult_getAsCXString is recommended.
+ * - User must not free this pointer, instead call clang_EvalResult_dispose on
+ * the CXEvalResult returned by clang_Cursor_Evaluate.
  */
 CINDEX_LINKAGE const char *clang_EvalResult_getAsStr(CXEvalResult E);
+/**
+ * Returns the evaluation result as a constant string if the
+ * kind is other than Int or float. This might include zero bytes.
+ */
+CINDEX_LINKAGE CXString clang_EvalResult_getAsCXString(CXEvalResult E);
 
 /**
  * Disposes the created Eval memory.
diff --git a/clang/tools/libclang/CIndex.cpp b/clang/tools/libclang/CIndex.cpp
index c8db6c92bb4d4..672e791ad3455 100644
--- a/clang/tools/libclang/CIndex.cpp
+++ b/clang/tools/libclang/CIndex.cpp
@@ -4589,13 +4589,13 @@ struct ExprEvalResult {
 unsigned long long unsignedVal;
 long long intVal;
 double floatVal;
-char *stringVal;
+CXString stringVal;
   } EvalData;
   bool IsUnsignedInt;
   ~ExprEvalResult() {
 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
 EvalType != CXEval_Int) {
-  delete[] EvalData.stringVal;
+  clang_disposeString(EvalData.stringVal);
 }
   }
 };
@@ -4651,7 +4651,17 @@ const char *clang_EvalResult_getAsStr(CXEvalResult E) {
   if (!E) {
 return nullptr;
   }
-  return ((ExprEvalResult *)E)->EvalData.stringVal;
+  return clang_getCString(((ExprEvalResult *)E)->EvalData.stringVal);
+}
+
+CXString clang_EvalResult_getAsCXString(CXEvalResult E) {
+  if (!E) {
+return cxstring::createNull();
+  }
+  size_t length;
+  auto data =
+  clang_getCString2(((ExprEvalResult *)E)->EvalData.stringVal, &length);
+  return cxstring::createDup(StringRef(data, length));
 }
 
 static const ExprEvalResult *evaluateExpr(Expr *expr, CXCursor C) {
@@ -4716,11 +4726,7 @@ static const ExprEvalResult *evaluateExpr(Expr *expr, 
CXCursor C) {
 result->EvalType = CXEval_StrLiteral;
   }
 
-  std::string strRef(StrE->getString().str());
-  result->EvalData.stringVal = new char[strRef.size() + 1];
-  strncpy((char *)result->EvalData.stringVal, strRef.c_str(),
-  strRef.size());
-  result->EvalData.stringVal[strRef.size()] = '\0';
+  result->EvalData.stringVal = cxstring::createDup(StrE->getString());
   return result.release();
 }
   } else if (expr->getStmtClass() == Stmt::ObjCStringLiteralClass ||
@@ -4737,10 +4743,7 @@ static const ExprEvalResult *evaluateExpr(Expr *expr, 
CXCursor C) {
   result->EvalType = CXEval_StrLiteral;
 }
 
-std::string strRef(StrE->getString().str());
-result->EvalData.stringVal = new char[strRef.size() + 1];
-strncpy((char *)result->EvalData.stringVal, strRef.c_str(), strRef.size());
-result->EvalData.stringVal[strRef.size()] = '\0';
+result->EvalData.strin

[clang] [CIR] Add if statement support (PR #134333)

2025-04-06 Thread via cfe-commits


@@ -0,0 +1,254 @@
+// RUN: %clang_cc1 -std=c++17 -triple x86_64-unknown-linux-gnu -fclangir 
-emit-cir %s -o %t.cir
+// RUN: FileCheck --input-file=%t.cir %s --check-prefix=CIR
+// RUN: %clang_cc1 -std=c++17 -triple x86_64-unknown-linux-gnu -fclangir 
-emit-llvm %s -o %t-cir.ll
+// RUN: FileCheck --input-file=%t-cir.ll %s --check-prefix=LLVM
+// RUN: %clang_cc1 -std=c++17 -triple x86_64-unknown-linux-gnu -emit-llvm %s 
-o %t.ll
+// RUN: FileCheck --input-file=%t.ll %s --check-prefix=OGCG
+
+int if0(bool a) {
+
+  if (a)

Andres-Salamanca wrote:

I’ve added a test for the `if (auto x = something)` case  let me know if it 
looks good now! 
I didn’t include the `if (auto x = something; x.something_else)` style yet 
because I was thinking of doing something like:

```cpp
int if_init_and_cond() {
  if (int x = 42; x > 0) {
return x + 2;
  } else {
return x - 2; 
  }
}
```

but `x > 0` fails with BinaryOperator Not Yet Implemented:  

If `if (int x = 42; true)` is good enough for now, I can go ahead and add a 
test for that too  just let me know what you prefer.

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


[clang-tools-extra] [clang-tidy] Switch misc-confusable-identifiers check to a faster algorithm. (PR #130369)

2025-04-06 Thread Richard Smith via cfe-commits

zygoloid wrote:

Ping.

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


[clang] [CIR] Add if statement support (PR #134333)

2025-04-06 Thread via cfe-commits


@@ -447,6 +448,133 @@ mlir::LogicalResult cir::ReturnOp::verify() {
   return success();
 }
 
+//===--===//
+// IfOp
+//===--===//
+
+ParseResult cir::IfOp::parse(OpAsmParser &parser, OperationState &result) {
+  // create the regions for 'then'.
+  result.regions.reserve(2);
+  Region *thenRegion = result.addRegion();
+  Region *elseRegion = result.addRegion();
+
+  mlir::Builder &builder = parser.getBuilder();
+  OpAsmParser::UnresolvedOperand cond;
+  Type boolType = cir::BoolType::get(builder.getContext());
+
+  if (parser.parseOperand(cond) ||
+  parser.resolveOperand(cond, boolType, result.operands))
+return failure();
+
+  // Parse 'then' region.
+  mlir::SMLoc parseThenLoc = parser.getCurrentLocation();
+  if (parser.parseRegion(*thenRegion, /*arguments=*/{}, /*argTypes=*/{}))
+return failure();
+
+  if (ensureRegionTerm(parser, *thenRegion, parseThenLoc).failed())
+return failure();
+
+  // If we find an 'else' keyword, parse the 'else' region.
+  if (!parser.parseOptionalKeyword("else")) {
+mlir::SMLoc parseElseLoc = parser.getCurrentLocation();
+if (parser.parseRegion(*elseRegion, /*arguments=*/{}, /*argTypes=*/{}))
+  return failure();
+if (ensureRegionTerm(parser, *elseRegion, parseElseLoc).failed())
+  return failure();
+  }
+
+  // Parse the optional attribute list.
+  if (parser.parseOptionalAttrDict(result.attributes))
+return failure();
+  return success();
+}
+
+void cir::IfOp::print(OpAsmPrinter &p) {
+
+  p << " " << getCondition() << " ";
+  mlir::Region &thenRegion = this->getThenRegion();
+  p.printRegion(thenRegion,
+/*printEntryBlockArgs=*/false,
+/*printBlockTerminators=*/!omitRegionTerm(thenRegion));
+
+  // Print the 'else' regions if it exists and has a block.
+  mlir::Region &elseRegion = this->getElseRegion();
+  if (!elseRegion.empty()) {
+p << " else ";
+p.printRegion(elseRegion,
+  /*printEntryBlockArgs=*/false,
+  /*printBlockTerminators=*/!omitRegionTerm(elseRegion));
+  }
+
+  p.printOptionalAttrDict(getOperation()->getAttrs());
+}
+
+/// Default callback for IfOp builders.
+void cir::buildTerminatedBody(OpBuilder &builder, Location loc) {
+  // add cir.yield to end of the block
+  builder.create(loc);
+}
+
+/// Given the region at `index`, or the parent operation if `index` is None,
+/// return the successor regions. These are the regions that may be selected
+/// during the flow of control. `operands` is a set of optional attributes that
+/// correspond to a constant value for each operand, or null if that operand is
+/// not a constant.
+void cir::IfOp::getSuccessorRegions(mlir::RegionBranchPoint point,
+SmallVectorImpl ®ions) 
{
+  // The `then` and the `else` region branch back to the parent operation.
+  if (!point.isParent()) {
+regions.push_back(RegionSuccessor());
+return;
+  }
+
+  // Don't consider the else region if it is empty.
+  Region *elseRegion = &this->getElseRegion();
+  if (elseRegion->empty())
+elseRegion = nullptr;
+
+  // Otherwise, the successor is dependent on the condition.
+  // bool condition;
+  // if (auto condAttr = operands.front().dyn_cast_or_null()) {

Andres-Salamanca wrote:

Changes applied Let me know if it looks good now

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


[clang] [clang] fix RecursiveASTVisitor traversal from type to decl (PR #132551)

2025-04-06 Thread Andrey Ali Khan Bolshakov via cfe-commits

bolshakov-a wrote:

@mizvekov, could you clarify please what is the point of traversing the host 
type twice? The tests pass if just remove the `if` statement.

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


[clang] [CIR] Add if statement support (PR #134333)

2025-04-06 Thread via cfe-commits


@@ -316,6 +316,106 @@ void CIRGenFunction::emitIgnoredExpr(const Expr *e) {
   emitLValue(e);
 }
 
+/// Emit an `if` on a boolean condition, filling `then` and `else` into
+/// appropriated regions.
+mlir::LogicalResult CIRGenFunction::emitIfOnBoolExpr(const Expr *cond,
+ const Stmt *thenS,
+ const Stmt *elseS) {
+  // Attempt to be more accurate as possible with IfOp location, generate
+  // one fused location that has either 2 or 4 total locations, depending
+  // on else's availability.
+  auto getStmtLoc = [this](const Stmt &s) {
+return mlir::FusedLoc::get(&getMLIRContext(),
+   {getLoc(s.getSourceRange().getBegin()),
+getLoc(s.getSourceRange().getEnd())});
+  };
+  mlir::Location thenLoc = getStmtLoc(*thenS);
+  std::optional elseLoc;
+  if (elseS)
+elseLoc = getStmtLoc(*elseS);
+
+  mlir::LogicalResult resThen = mlir::success(), resElse = mlir::success();
+  emitIfOnBoolExpr(
+  cond, /*thenBuilder=*/
+  [&](mlir::OpBuilder &, mlir::Location) {
+LexicalScope lexScope{*this, thenLoc, builder.getInsertionBlock()};
+resThen = emitStmt(thenS, /*useCurrentScope=*/true);
+  },
+  thenLoc,
+  /*elseBuilder=*/
+  [&](mlir::OpBuilder &, mlir::Location) {
+assert(elseLoc && "Invalid location for elseS.");
+LexicalScope lexScope{*this, *elseLoc, builder.getInsertionBlock()};
+resElse = emitStmt(elseS, /*useCurrentScope=*/true);
+  },
+  elseLoc);
+
+  return mlir::LogicalResult::success(resThen.succeeded() &&
+  resElse.succeeded());
+}
+
+/// Emit an `if` on a boolean condition, filling `then` and `else` into
+/// appropriated regions.
+cir::IfOp CIRGenFunction::emitIfOnBoolExpr(
+const clang::Expr *cond, BuilderCallbackRef thenBuilder,
+mlir::Location thenLoc, BuilderCallbackRef elseBuilder,
+std::optional elseLoc) {
+
+  SmallVector ifLocs{thenLoc};
+  if (elseLoc)
+ifLocs.push_back(*elseLoc);
+  mlir::Location loc = mlir::FusedLoc::get(&getMLIRContext(), ifLocs);
+
+  // Emit the code with the fully general case.
+  mlir::Value condV = emitOpOnBoolExpr(loc, cond);
+  return builder.create(loc, condV, elseLoc.has_value(),
+   /*thenBuilder=*/thenBuilder,
+   /*elseBuilder=*/elseBuilder);
+}
+
+/// TODO(cir): PGO data
+/// TODO(cir): see EmitBranchOnBoolExpr for extra ideas).
+mlir::Value CIRGenFunction::emitOpOnBoolExpr(mlir::Location loc,
+ const Expr *cond) {
+  // TODO(CIR): scoped ApplyDebugLocation DL(*this, Cond);
+  // TODO(CIR): __builtin_unpredictable and profile counts?
+  cond = cond->IgnoreParens();
+
+  // if (const BinaryOperator *CondBOp = dyn_cast(cond)) {
+  //   llvm_unreachable("binaryoperator ifstmt NYI");
+  // }
+
+  if (const UnaryOperator *CondUOp = dyn_cast(cond)) {
+// In LLVM the condition is reversed here for efficient codegen.
+// This should be done in CIR prior to LLVM lowering, if we do now
+// we can make CIR based diagnostics misleading.
+//  cir.ternary(!x, t, f) -> cir.ternary(x, f, t)
+assert(!cir::MissingFeatures::shouldReverseUnaryCondOnBoolExpr());
+  }
+
+  if (const ConditionalOperator *CondOp = dyn_cast(cond)) 
{
+
+cgm.errorNYI(cond->getExprLoc(), "Ternary NYI");
+assert(!cir::MissingFeatures::ternaryOp());
+return createDummyValue(loc, cond->getType());
+  }
+
+  // if (const CXXThrowExpr *Throw = dyn_cast(cond)) {
+  //   llvm_unreachable("NYI");
+  // }
+
+  // If the branch has a condition wrapped by __builtin_unpredictable,
+  // create metadata that specifies that the branch is unpredictable.
+  // Don't bother if not optimizing because that metadata would not be used.
+  auto *Call = dyn_cast(cond->IgnoreImpCasts());

Andres-Salamanca wrote:

Changes applied Let me know if it looks good now

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


[clang] [CIR] Add if statement support (PR #134333)

2025-04-06 Thread via cfe-commits


@@ -316,6 +316,106 @@ void CIRGenFunction::emitIgnoredExpr(const Expr *e) {
   emitLValue(e);
 }
 
+/// Emit an `if` on a boolean condition, filling `then` and `else` into
+/// appropriated regions.
+mlir::LogicalResult CIRGenFunction::emitIfOnBoolExpr(const Expr *cond,
+ const Stmt *thenS,
+ const Stmt *elseS) {
+  // Attempt to be more accurate as possible with IfOp location, generate
+  // one fused location that has either 2 or 4 total locations, depending
+  // on else's availability.
+  auto getStmtLoc = [this](const Stmt &s) {
+return mlir::FusedLoc::get(&getMLIRContext(),

Andres-Salamanca wrote:

Changes applied Let me know if it looks good now

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


[clang] [CIR] Add if statement support (PR #134333)

2025-04-06 Thread via cfe-commits


@@ -263,6 +264,72 @@ static void terminateBody(CIRGenBuilderTy &builder, 
mlir::Region &r,
 b->erase();
 }
 
+mlir::LogicalResult CIRGenFunction::emitIfStmt(const IfStmt &s) {
+  mlir::LogicalResult res = mlir::success();
+  // The else branch of a consteval if statement is always the only branch
+  // that can be runtime evaluated.
+  const Stmt *ConstevalExecuted;
+  if (s.isConsteval()) {
+ConstevalExecuted = s.isNegatedConsteval() ? s.getThen() : s.getElse();
+if (!ConstevalExecuted) {
+  // No runtime code execution required
+  return res;
+}
+  }
+
+  // C99 6.8.4.1: The first substatement is executed if the expression
+  // compares unequal to 0.  The condition must be a scalar type.
+  auto ifStmtBuilder = [&]() -> mlir::LogicalResult {
+if (s.isConsteval())
+  return emitStmt(ConstevalExecuted, /*useCurrentScope=*/true);
+
+if (s.getInit())
+  if (emitStmt(s.getInit(), /*useCurrentScope=*/true).failed())
+return mlir::failure();
+
+if (s.getConditionVariable())
+  emitDecl(*s.getConditionVariable());
+
+// During LLVM codegen, if the condition constant folds and can be elided,
+// it tries to avoid emitting the condition and the dead arm of the 
if/else.
+// TODO(cir): we skip this in CIRGen, but should implement this as part of

Andres-Salamanca wrote:

Changes applied Let me know if it looks good now

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


[clang] [CIR] Add if statement support (PR #134333)

2025-04-06 Thread via cfe-commits


@@ -316,6 +316,106 @@ void CIRGenFunction::emitIgnoredExpr(const Expr *e) {
   emitLValue(e);
 }
 
+/// Emit an `if` on a boolean condition, filling `then` and `else` into
+/// appropriated regions.
+mlir::LogicalResult CIRGenFunction::emitIfOnBoolExpr(const Expr *cond,
+ const Stmt *thenS,
+ const Stmt *elseS) {
+  // Attempt to be more accurate as possible with IfOp location, generate

Andres-Salamanca wrote:

Changes applied Let me know if it looks good now

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


[clang] [clang] Track final substitution for Subst* AST nodes (PR #132748)

2025-04-06 Thread Thurston Dang via cfe-commits

thurstond wrote:

> This will be fixed here: #134560

Thank you!

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


[clang] [Driver][XCore][NFC] Remove redundant setting of IsIntegratedAssemblerDefault (PR #130397)

2025-04-06 Thread Brad Smith via cfe-commits

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


[clang] Reland [Clang][Cmake] fix libtool duplicate member name warnings (PR #133850)

2025-04-06 Thread Farzon Lotfi via cfe-commits

farzonl wrote:

> I'm still somewhat confused about why that one file in particular is 
> problematic, but I guess if this works it's fine.
> 
> Would making these OBJECT instead of STATIC libraries avoid the issue perhaps?

No OBJECT seems to cause many more linker errors. So i'm going to stick with 
the current solution and merge in the morning if there are no other concerns.

```bash
ld.lld: error: undefined symbol: 
clang::CodeGen::CodeGenFunction::EmitARMBuiltinExpr(unsigned int, 
clang::CallExpr const*, clang::CodeGen::ReturnValueSlot, llvm::Triple::ArchType)
>>> referenced by CGBuiltin.cpp:65 
>>> (/mnt/DevDrive/projects/llvm-project/clang/lib/CodeGen/CGBuiltin.cpp:65)
>>>   
>>> CGBuiltin.cpp.o:(EmitTargetArchBuiltinExpr(clang::CodeGen::CodeGenFunction*,
>>>  unsigned int, clang::CallExpr const*, clang::CodeGen::ReturnValueSlot, 
>>> llvm::Triple::ArchType)) in archive lib/libclangCodeGen.a

ld.lld: error: undefined symbol: 
clang::CodeGen::CodeGenFunction::EmitAArch64BuiltinExpr(unsigned int, 
clang::CallExpr const*, llvm::Triple::ArchType)
>>> referenced by CGBuiltin.cpp:69 
>>> (/mnt/DevDrive/projects/llvm-project/clang/lib/CodeGen/CGBuiltin.cpp:69)
>>>   
>>> CGBuiltin.cpp.o:(EmitTargetArchBuiltinExpr(clang::CodeGen::CodeGenFunction*,
>>>  unsigned int, clang::CallExpr const*, clang::CodeGen::ReturnValueSlot, 
>>> llvm::Triple::ArchType)) in archive lib/libclangCodeGen.a

ld.lld: error: undefined symbol: 
clang::CodeGen::CodeGenFunction::EmitBPFBuiltinExpr(unsigned int, 
clang::CallExpr const*)
>>> referenced by CGBuiltin.cpp:72 
>>> (/mnt/DevDrive/projects/llvm-project/clang/lib/CodeGen/CGBuiltin.cpp:72)
>>>   
>>> CGBuiltin.cpp.o:(EmitTargetArchBuiltinExpr(clang::CodeGen::CodeGenFunction*,
>>>  unsigned int, clang::CallExpr const*, clang::CodeGen::ReturnValueSlot, 
>>> llvm::Triple::ArchType)) in archive lib/libclangCodeGen.a

ld.lld: error: undefined symbol: 
clang::CodeGen::CodeGenFunction::EmitX86BuiltinExpr(unsigned int, 
clang::CallExpr const*)
>>> referenced by CGBuiltin.cpp:75 
>>> (/mnt/DevDrive/projects/llvm-project/clang/lib/CodeGen/CGBuiltin.cpp:75)
>>>   
>>> CGBuiltin.cpp.o:(EmitTargetArchBuiltinExpr(clang::CodeGen::CodeGenFunction*,
>>>  unsigned int, clang::CallExpr const*, clang::CodeGen::ReturnValueSlot, 
>>> llvm::Triple::ArchType)) in archive lib/libclangCodeGen.a

ld.lld: error: undefined symbol: 
clang::CodeGen::CodeGenFunction::EmitPPCBuiltinExpr(unsigned int, 
clang::CallExpr const*)
>>> referenced by CGBuiltin.cpp:80 
>>> (/mnt/DevDrive/projects/llvm-project/clang/lib/CodeGen/CGBuiltin.cpp:80)
>>>   
>>> CGBuiltin.cpp.o:(EmitTargetArchBuiltinExpr(clang::CodeGen::CodeGenFunction*,
>>>  unsigned int, clang::CallExpr const*, clang::CodeGen::ReturnValueSlot, 
>>> llvm::Triple::ArchType)) in archive lib/libclangCodeGen.a

ld.lld: error: undefined symbol: 
clang::CodeGen::CodeGenFunction::EmitAMDGPUBuiltinExpr(unsigned int, 
clang::CallExpr const*)
>>> referenced by CGBuiltin.cpp:83 
>>> (/mnt/DevDrive/projects/llvm-project/clang/lib/CodeGen/CGBuiltin.cpp:83)
>>>   
>>> CGBuiltin.cpp.o:(EmitTargetArchBuiltinExpr(clang::CodeGen::CodeGenFunction*,
>>>  unsigned int, clang::CallExpr const*, clang::CodeGen::ReturnValueSlot, 
>>> llvm::Triple::ArchType)) in archive lib/libclangCodeGen.a
>>> referenced by CGBuiltin.cpp:102 
>>> (/mnt/DevDrive/projects/llvm-project/clang/lib/CodeGen/CGBuiltin.cpp:102)
>>>   
>>> CGBuiltin.cpp.o:(EmitTargetArchBuiltinExpr(clang::CodeGen::CodeGenFunction*,
>>>  unsigned int, clang::CallExpr const*, clang::CodeGen::ReturnValueSlot, 
>>> llvm::Triple::ArchType)) in archive lib/libclangCodeGen.a

ld.lld: error: undefined symbol: 
clang::CodeGen::CodeGenFunction::EmitSystemZBuiltinExpr(unsigned int, 
clang::CallExpr const*)
>>> referenced by CGBuiltin.cpp:85 
>>> (/mnt/DevDrive/projects/llvm-project/clang/lib/CodeGen/CGBuiltin.cpp:85)
>>>   
>>> CGBuiltin.cpp.o:(EmitTargetArchBuiltinExpr(clang::CodeGen::CodeGenFunction*,
>>>  unsigned int, clang::CallExpr const*, clang::CodeGen::ReturnValueSlot, 
>>> llvm::Triple::ArchType)) in archive lib/libclangCodeGen.a

ld.lld: error: undefined symbol: 
clang::CodeGen::CodeGenFunction::EmitNVPTXBuiltinExpr(unsigned int, 
clang::CallExpr const*)
>>> referenced by CGBuiltin.cpp:88 
>>> (/mnt/DevDrive/projects/llvm-project/clang/lib/CodeGen/CGBuiltin.cpp:88)
>>>   
>>> CGBuiltin.cpp.o:(EmitTargetArchBuiltinExpr(clang::CodeGen::CodeGenFunction*,
>>>  unsigned int, clang::CallExpr const*, clang::CodeGen::ReturnValueSlot, 
>>> llvm::Triple::ArchType)) in archive lib/libclangCodeGen.a

ld.lld: error: undefined symbol: 
clang::CodeGen::CodeGenFunction::EmitWebAssemblyBuiltinExpr(unsigned int, 
clang::CallExpr const*)
>>> referenced by CGBuiltin.cpp:91 
>>> (/mnt/DevDrive/projects/llvm-project/clang/lib/CodeGen/CGBuiltin.cpp:91)
>>>   
>>> CGBuiltin.cpp.o:(EmitTargetArchBuiltinExpr(clang::CodeGen::CodeGenF

[clang] [clang-tools-extra] [clang] Do not share ownership of `PreprocessorOptions` (PR #133467)

2025-04-06 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder 
`llvm-clang-x86_64-win-fast` running on `as-builder-3` while building 
`clang-tools-extra,clang` at step 8 "test-build-unified-tree-check-clang-unit".

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


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

```
Step 8 (test-build-unified-tree-check-clang-unit) failure: test (failure)
...
[27/324] Building RC object 
tools\clang\unittests\StaticAnalyzer\CMakeFiles\StaticAnalysisTests.dir\C_\buildbot\as-builder-3\llvm-clang-x86_64-win-fast\llvm-project\llvm\resources\windows_version_resource.rc.res
[28/324] Building CXX object 
tools\clang\unittests\StaticAnalyzer\CMakeFiles\StaticAnalysisTests.dir\Z3CrosscheckOracleTest.cpp.obj
[29/324] Building CXX object 
tools\clang\unittests\Driver\CMakeFiles\ClangDriverTests.dir\ModuleCacheTest.cpp.obj
[30/324] Building CXX object 
tools\clang\unittests\Driver\CMakeFiles\ClangDriverTests.dir\GCCVersionTest.cpp.obj
[31/324] Building CXX object 
tools\clang\unittests\Driver\CMakeFiles\ClangDriverTests.dir\MultilibBuilderTest.cpp.obj
[32/324] Building CXX object 
tools\clang\unittests\Driver\CMakeFiles\ClangDriverTests.dir\MultilibTest.cpp.obj
[33/324] Building RC object 
tools\clang\unittests\ASTMatchers\CMakeFiles\ASTMatchersTests.dir\C_\buildbot\as-builder-3\llvm-clang-x86_64-win-fast\llvm-project\llvm\resources\windows_version_resource.rc.res
[34/324] Building CXX object 
tools\clang\unittests\Driver\CMakeFiles\ClangDriverTests.dir\SanitizerArgsTest.cpp.obj
[35/324] Building RC object 
tools\clang\unittests\ASTMatchers\Dynamic\CMakeFiles\DynamicASTMatchersTests.dir\48b300c34a7217f4dd73b5241653d7e9\llvm-project\llvm\resources\windows_version_resource.rc.res
[36/324] Building CXX object 
tools\clang\unittests\Parse\CMakeFiles\ParseTests.dir\ParseHLSLRootSignatureTest.cpp.obj
FAILED: 
tools/clang/unittests/Parse/CMakeFiles/ParseTests.dir/ParseHLSLRootSignatureTest.cpp.obj
 
C:\ninja\ccache.exe 
C:\PROGRA~1\MICROS~2\2022\COMMUN~1\VC\Tools\MSVC\1438~1.331\bin\Hostx64\x64\cl.exe
  /nologo /TP -DCLANG_BUILD_STATIC -DGTEST_HAS_RTTI=0 -DLLVM_BUILD_STATIC 
-DUNICODE -D_CRT_NONSTDC_NO_DEPRECATE -D_CRT_NONSTDC_NO_WARNINGS 
-D_CRT_SECURE_NO_DEPRECATE -D_CRT_SECURE_NO_WARNINGS -D_HAS_EXCEPTIONS=0 
-D_SCL_SECURE_NO_DEPRECATE -D_SCL_SECURE_NO_WARNINGS -D_UNICODE 
-D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS 
-IC:\buildbot\as-builder-3\llvm-clang-x86_64-win-fast\build\tools\clang\unittests\Parse
 
-IC:\buildbot\as-builder-3\llvm-clang-x86_64-win-fast\llvm-project\clang\unittests\Parse
 
-IC:\buildbot\as-builder-3\llvm-clang-x86_64-win-fast\llvm-project\clang\include
 
-IC:\buildbot\as-builder-3\llvm-clang-x86_64-win-fast\build\tools\clang\include 
-IC:\buildbot\as-builder-3\llvm-clang-x86_64-win-fast\build\include 
-IC:\buildbot\as-builder-3\llvm-clang-x86_64-win-fast\llvm-project\llvm\include 
-IC:\buildbot\as-builder-3\llvm-clang-x86_64-win-fast\llvm-project\third-party\unittest\googletest\include
 
-IC:\buildbot\as-builder-3\llvm-clang-x86_64-win-fast\llvm-project\third-party\unittest\googlemock\include
 /DWIN32 /D_WINDOWS   /Zc:inline /Zc:preprocessor /Zc:__cplusplus /Oi /bigobj 
/permissive- /W4 -wd4141 -wd4146 -wd4244 -wd4267 -wd4291 -wd4351 -wd4456 
-wd4457 -wd4458 -wd4459 -wd4503 -wd4624 -wd4722 -wd4100 -wd4127 -wd4512 -wd4505 
-wd4610 -wd4510 -wd4702 -wd4245 -wd4706 -wd4310 -wd4701 -wd4703 -wd4389 -wd4611 
-wd4805 -wd4204 -wd4577 -wd4091 -wd4592 -wd4319 -wd4709 -wd5105 -wd4324 -wd4251 
-wd4275 -w14062 -we4238 /Gw /O2 /Ob2 /DNDEBUG -MD  /EHs-c- /GR- -std:c++17 
/showIncludes 
/Fotools\clang\unittests\Parse\CMakeFiles\ParseTests.dir\ParseHLSLRootSignatureTest.cpp.obj
 /Fdtools\clang\unittests\Parse\CMakeFiles\ParseTests.dir\ /FS -c 
C:\buildbot\as-builder-3\llvm-clang-x86_64-win-fast\llvm-project\clang\unittests\Parse\ParseHLSLRootSignatureTest.cpp
C:\Program Files\Microsoft Visual 
Studio\2022\Community\VC\Tools\MSVC\14.38.33130\include\memory(3465): error 
C2665: 'clang::Preprocessor::Preprocessor': no overloaded function could 
convert all the argument types
C:\buildbot\as-builder-3\llvm-clang-x86_64-win-fast\llvm-project\clang\include\clang/Lex/Preprocessor.h(1168):
 note: could be 'clang::Preprocessor::Preprocessor(const 
clang::PreprocessorOptions &,clang::DiagnosticsEngine &,const 
clang::LangOptions &,clang::SourceManager &,clang::HeaderSearch 
&,clang::ModuleLoader &,clang::IdentifierInfoLookup 
*,bool,clang::TranslationUnitKind)'
C:\Program Files\Microsoft Visual 
Studio\2022\Community\VC\Tools\MSVC\14.38.33130\include\memory(3465): note: 
'clang::Preprocessor::Preprocessor(const clang::PreprocessorOptions 
&,clang::DiagnosticsEngine &,const clang::LangOptions &,clang::SourceManager 
&,clang::HeaderSearch &,clang::ModuleLoader &,clang::IdentifierInfoLookup 
*,bool,clang::TranslationUnitKind)': cannot convert argument 1 from '_Ty' to 
'const clang::PreprocessorOptions &'

[clang] [CIR] Add if statement support (PR #134333)

2025-04-06 Thread via cfe-commits


@@ -447,6 +448,133 @@ mlir::LogicalResult cir::ReturnOp::verify() {
   return success();
 }
 
+//===--===//
+// IfOp
+//===--===//
+
+ParseResult cir::IfOp::parse(OpAsmParser &parser, OperationState &result) {
+  // create the regions for 'then'.
+  result.regions.reserve(2);
+  Region *thenRegion = result.addRegion();
+  Region *elseRegion = result.addRegion();
+
+  mlir::Builder &builder = parser.getBuilder();
+  OpAsmParser::UnresolvedOperand cond;
+  Type boolType = cir::BoolType::get(builder.getContext());
+
+  if (parser.parseOperand(cond) ||
+  parser.resolveOperand(cond, boolType, result.operands))
+return failure();
+
+  // Parse 'then' region.
+  mlir::SMLoc parseThenLoc = parser.getCurrentLocation();
+  if (parser.parseRegion(*thenRegion, /*arguments=*/{}, /*argTypes=*/{}))
+return failure();
+
+  if (ensureRegionTerm(parser, *thenRegion, parseThenLoc).failed())
+return failure();
+
+  // If we find an 'else' keyword, parse the 'else' region.
+  if (!parser.parseOptionalKeyword("else")) {
+mlir::SMLoc parseElseLoc = parser.getCurrentLocation();
+if (parser.parseRegion(*elseRegion, /*arguments=*/{}, /*argTypes=*/{}))
+  return failure();
+if (ensureRegionTerm(parser, *elseRegion, parseElseLoc).failed())
+  return failure();
+  }
+
+  // Parse the optional attribute list.
+  if (parser.parseOptionalAttrDict(result.attributes))
+return failure();
+  return success();
+}
+
+void cir::IfOp::print(OpAsmPrinter &p) {
+

Andres-Salamanca wrote:

Changes applied Let me know if it looks good now

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


[clang] [CIR] Add if statement support (PR #134333)

2025-04-06 Thread via cfe-commits


@@ -316,6 +316,106 @@ void CIRGenFunction::emitIgnoredExpr(const Expr *e) {
   emitLValue(e);
 }
 
+/// Emit an `if` on a boolean condition, filling `then` and `else` into
+/// appropriated regions.
+mlir::LogicalResult CIRGenFunction::emitIfOnBoolExpr(const Expr *cond,
+ const Stmt *thenS,
+ const Stmt *elseS) {
+  // Attempt to be more accurate as possible with IfOp location, generate
+  // one fused location that has either 2 or 4 total locations, depending
+  // on else's availability.

Andres-Salamanca wrote:

Changes applied Let me know if it looks good now

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


[clang] [clang] fix serialization of SubstNonTypeTemplateParmExpr (PR #134560)

2025-04-06 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Matheus Izvekov (mizvekov)


Changes

This fixes a couple of mistakes introduced when merging 
https://github.com/llvm/llvm-project/pull/132748

Fixes msan failure reported here: 
https://github.com/llvm/llvm-project/pull/132748#issuecomment-2781105225

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


3 Files Affected:

- (modified) clang/lib/AST/ASTContext.cpp (+1-1) 
- (modified) clang/lib/Serialization/ASTReaderStmt.cpp (+1) 
- (modified) clang/lib/Serialization/ASTWriterStmt.cpp (+1) 


``diff
diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index 1b6b3d06ddc1e..320fd4e2f3077 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -7011,7 +7011,7 @@ TemplateName 
ASTContext::getCanonicalTemplateName(TemplateName Name,
 getCanonicalTemplateArgument(subst->getArgumentPack());
 return getSubstTemplateTemplateParmPack(
 canonArgPack, subst->getAssociatedDecl()->getCanonicalDecl(),
-subst->getFinal(), subst->getIndex());
+subst->getIndex(), subst->getFinal());
   }
   case TemplateName::DeducedTemplate: {
 assert(IgnoreDeduced == false);
diff --git a/clang/lib/Serialization/ASTReaderStmt.cpp 
b/clang/lib/Serialization/ASTReaderStmt.cpp
index d26152f3780ed..22fe54b526433 100644
--- a/clang/lib/Serialization/ASTReaderStmt.cpp
+++ b/clang/lib/Serialization/ASTReaderStmt.cpp
@@ -2229,6 +2229,7 @@ void ASTStmtReader::VisitSubstNonTypeTemplateParmExpr(
 E->PackIndex = Record.readInt();
   else
 E->PackIndex = 0;
+  E->Final = CurrentUnpackingBits->getNextBit();
   E->SubstNonTypeTemplateParmExprBits.NameLoc = readSourceLocation();
   E->Replacement = Record.readSubExpr();
 }
diff --git a/clang/lib/Serialization/ASTWriterStmt.cpp 
b/clang/lib/Serialization/ASTWriterStmt.cpp
index 23bb5ff22efaf..d0a0f843c7542 100644
--- a/clang/lib/Serialization/ASTWriterStmt.cpp
+++ b/clang/lib/Serialization/ASTWriterStmt.cpp
@@ -2229,6 +2229,7 @@ void ASTStmtWriter::VisitSubstNonTypeTemplateParmExpr(
   CurrentPackingBits.addBit((bool)E->getPackIndex());
   if (auto PackIndex = E->getPackIndex())
 Record.push_back(*PackIndex + 1);
+  CurrentPackingBits.addBit(E->getFinal());
 
   Record.AddSourceLocation(E->getNameLoc());
   Record.AddStmt(E->getReplacement());

``




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


[clang] [clang-format]: Add `Custom` to `ShortFunctionStyle`; add new AllowShortFunctionsOnASingleLineOptions for granular setup (PR #134337)

2025-04-06 Thread via cfe-commits

irymarchyk wrote:

If this was done previously I think this is doable. I will take a look and make 
appropriate changes. Thanks.

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


[clang] [clang] fix serialization of SubstNonTypeTemplateParmExpr (PR #134560)

2025-04-06 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov created 
https://github.com/llvm/llvm-project/pull/134560

This fixes a couple of mistakes introduced when merging 
https://github.com/llvm/llvm-project/pull/132748

Fixes msan failure reported here: 
https://github.com/llvm/llvm-project/pull/132748#issuecomment-2781105225

>From 0e70eb3b7c8a620977d8468f3443de8e31a97dfa Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Sun, 6 Apr 2025 17:06:46 -0300
Subject: [PATCH] [clang] fix serialization of SubstNonTypeTemplateParmExpr

This fixes a couple of mistakes introduced when merging
https://github.com/llvm/llvm-project/pull/132748

Fixes msan failure reported here: 
https://github.com/llvm/llvm-project/pull/132748#issuecomment-2781105225
---
 clang/lib/AST/ASTContext.cpp  | 2 +-
 clang/lib/Serialization/ASTReaderStmt.cpp | 1 +
 clang/lib/Serialization/ASTWriterStmt.cpp | 1 +
 3 files changed, 3 insertions(+), 1 deletion(-)

diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index 1b6b3d06ddc1e..320fd4e2f3077 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -7011,7 +7011,7 @@ TemplateName 
ASTContext::getCanonicalTemplateName(TemplateName Name,
 getCanonicalTemplateArgument(subst->getArgumentPack());
 return getSubstTemplateTemplateParmPack(
 canonArgPack, subst->getAssociatedDecl()->getCanonicalDecl(),
-subst->getFinal(), subst->getIndex());
+subst->getIndex(), subst->getFinal());
   }
   case TemplateName::DeducedTemplate: {
 assert(IgnoreDeduced == false);
diff --git a/clang/lib/Serialization/ASTReaderStmt.cpp 
b/clang/lib/Serialization/ASTReaderStmt.cpp
index d26152f3780ed..22fe54b526433 100644
--- a/clang/lib/Serialization/ASTReaderStmt.cpp
+++ b/clang/lib/Serialization/ASTReaderStmt.cpp
@@ -2229,6 +2229,7 @@ void ASTStmtReader::VisitSubstNonTypeTemplateParmExpr(
 E->PackIndex = Record.readInt();
   else
 E->PackIndex = 0;
+  E->Final = CurrentUnpackingBits->getNextBit();
   E->SubstNonTypeTemplateParmExprBits.NameLoc = readSourceLocation();
   E->Replacement = Record.readSubExpr();
 }
diff --git a/clang/lib/Serialization/ASTWriterStmt.cpp 
b/clang/lib/Serialization/ASTWriterStmt.cpp
index 23bb5ff22efaf..d0a0f843c7542 100644
--- a/clang/lib/Serialization/ASTWriterStmt.cpp
+++ b/clang/lib/Serialization/ASTWriterStmt.cpp
@@ -2229,6 +2229,7 @@ void ASTStmtWriter::VisitSubstNonTypeTemplateParmExpr(
   CurrentPackingBits.addBit((bool)E->getPackIndex());
   if (auto PackIndex = E->getPackIndex())
 Record.push_back(*PackIndex + 1);
+  CurrentPackingBits.addBit(E->getFinal());
 
   Record.AddSourceLocation(E->getNameLoc());
   Record.AddStmt(E->getReplacement());

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


[clang] [clang] Track final substitution for Subst* AST nodes (PR #132748)

2025-04-06 Thread Matheus Izvekov via cfe-commits

mizvekov wrote:

This will be fixed here: https://github.com/llvm/llvm-project/pull/134560

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


[clang] [clang]: fix reference compatibility in overload resolution (PR #133035)

2025-04-06 Thread Nhat Nguyen via cfe-commits

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


[clang] Add more tests for _Countof (PR #133333)

2025-04-06 Thread Alejandro Colomar via cfe-commits

https://github.com/alejandro-colomar updated 
https://github.com/llvm/llvm-project/pull/13

>From b8f95e71efec49e90ed20bc1f78fe2055caccece Mon Sep 17 00:00:00 2001
From: Alejandro Colomar 
Date: Thu, 27 Mar 2025 23:51:18 +0100
Subject: [PATCH] Add more tests for _Countof

Link: 
Link: 
Cc: Aaron Ballman 
Signed-off-by: Alejandro Colomar 
---
 clang/test/C/C2y/n3369.c | 45 +++-
 1 file changed, 44 insertions(+), 1 deletion(-)

diff --git a/clang/test/C/C2y/n3369.c b/clang/test/C/C2y/n3369.c
index 389828b52b6a2..a4ae6749fb898 100644
--- a/clang/test/C/C2y/n3369.c
+++ b/clang/test/C/C2y/n3369.c
@@ -18,6 +18,8 @@
 #endif
 
 int global_array[12];
+int global_multi_array[12][34];
+int global_num;
 
 void test_parsing_failures() {
   (void)_Countof; // expected-error {{expected expression}}
@@ -36,6 +38,12 @@ void test_semantic_failures() {
 expected-note {{forward declaration of 'struct 
S'}}
   struct T { int x; };
   (void)_Countof(struct T);  // expected-error {{'_Countof' requires an 
argument of array type; 'struct T' invalid}}
+  struct U { int x[3]; };
+  (void)_Countof(struct U);  // expected-error {{'_Countof' requires an 
argument of array type; 'struct U' invalid}}
+  int a[3];
+  (void)_Countof(&a);  // expected-error {{'_Countof' requires an argument of 
array type; 'int (*)[3]' invalid}}
+  int *p;
+  (void)_Countof(p);  // expected-error {{'_Countof' requires an argument of 
array type; 'int *' invalid}}
 }
 
 void test_constant_expression_behavior(int n) {
@@ -81,6 +89,22 @@ void test_with_function_param(int array[12], int 
(*array_ptr)[12], int static_ar
   (void)_Countof(static_array); // expected-error {{'_Countof' requires an 
argument of array type; 'int *' invalid}}
 }
 
+void test_func_fix_fix(int i, char (*a)[3][5], int (*x)[_Countof(*a)]);  // 
expected-note {{passing argument to parameter}}
+void test_func_fix_var(int i, char (*a)[3][i], int (*x)[_Countof(*a)]);  // 
expected-note {{passing argument to parameter}}
+void test_func_fix_uns(int i, char (*a)[3][*], int (*x)[_Countof(*a)]);  // 
expected-note {{passing argument to parameter}}
+
+void test_funcs() {
+  int i3[3];
+  int i5[5];
+  char c35[3][5];
+  test_func_fix_fix(5, &c35, &i3);
+  test_func_fix_fix(5, &c35, &i5); // expected-warning {{incompatible pointer 
types passing 'int (*)[5]' to parameter of type 'int (*)[3]'}}
+  test_func_fix_var(5, &c35, &i3);
+  test_func_fix_var(5, &c35, &i5); // expected-warning {{incompatible pointer 
types passing 'int (*)[5]' to parameter of type 'int (*)[3]'}}
+  test_func_fix_uns(5, &c35, &i3);
+  test_func_fix_uns(5, &c35, &i5); // expected-warning {{incompatible pointer 
types passing 'int (*)[5]' to parameter of type 'int (*)[3]'}}
+}
+
 void test_multidimensional_arrays() {
   int array[12][7];
   static_assert(_Countof(array) == 12);
@@ -102,6 +126,11 @@ void test_unspecified_array_length() {
   static_assert(_Countof(**x) == 3);
 }
 
+void test_completed_array() {
+  int a[] = {1, 2, global_num};
+  static_assert(_Countof(a) == 3);
+}
+
 // Test that the return type of _Countof is what you'd expect (size_t).
 void test_return_type() {
   static_assert(_Generic(typeof(_Countof global_array), typeof(sizeof(0)) : 1, 
default : 0));
@@ -121,10 +150,14 @@ void test_typedefs() {
   static_assert(_Countof(*x) == 12);
 }
 
-void test_zero_size_arrays() {
+void test_zero_size_arrays(int n) {
   int array[0]; // expected-warning {{zero size arrays are an extension}}
   static_assert(_Countof(array) == 0);
   static_assert(_Countof(int[0]) == 0); // expected-warning {{zero size arrays 
are an extension}}
+  int multi_array[0][n]; // expected-warning {{zero size arrays are an 
extension}}
+  static_assert(_Countof(multi_array) == 0);
+  int another_one[0][3]; // expected-warning {{zero size arrays are an 
extension}}
+  static_assert(_Countof(another_one) == 0);
 }
 
 void test_struct_members() {
@@ -144,3 +177,13 @@ void test_compound_literals() {
   static_assert(_Countof((int[2]){}) == 2);
   static_assert(_Countof((int[]){1, 2, 3, 4}) == 4);   
 }
+
+static int test_f1();
+static int test_f2();  // expected-warning {{never defined}}
+
+void test_symbols() {
+  int a[global_num][global_num];
+
+  static_assert(_Countof(global_multi_array[test_f1()]) == 34);
+  (void)_Countof(a[test_f2()]);
+}

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


[clang] Add more tests for _Countof (PR #133333)

2025-04-06 Thread Alejandro Colomar via cfe-commits

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


[clang] Add more tests for _Countof (PR #133333)

2025-04-06 Thread Alejandro Colomar via cfe-commits

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


[clang] Reland [Clang][Cmake] fix libtool duplicate member name warnings (PR #133850)

2025-04-06 Thread Nikita Popov via cfe-commits

nikic wrote:

I'm still somewhat confused about why that one file in particular is 
problematic, but I guess if this works it's fine.

Would making these OBJECT instead of STATIC libraries avoid the issue perhaps?

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


[clang] [clang] fix RecursiveASTVisitor traversal from type to decl (PR #132551)

2025-04-06 Thread Matheus Izvekov via cfe-commits

mizvekov wrote:

Which host type twice?

In case the MemberPointerType represents a class adjustment, this visits the 
actual class type, instead of just the as-written qualifier.

example: https://gcc.godbolt.org/z/M5qfGPGMf

I didn't expect we would have in-tree users of the RecursiveVisitor for this, 
but it seems useful for external users to leave it in, no?

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


[clang] [CIR] Add if statement support (PR #134333)

2025-04-06 Thread via cfe-commits

https://github.com/Andres-Salamanca updated 
https://github.com/llvm/llvm-project/pull/134333

>From 89f0f528f981223273b2c1548c9a71f2ceeca329 Mon Sep 17 00:00:00 2001
From: Andres Salamanca 
Date: Thu, 3 Apr 2025 12:07:25 -0500
Subject: [PATCH 1/2] [CIR] Add if statement support Upstream if statement
 support

Formatted code and added test cases.

added multiple RUN lines for the codegen test
---
 .../include/clang/CIR/Dialect/IR/CIRDialect.h |   4 +
 clang/include/clang/CIR/Dialect/IR/CIROps.td  |  60 -
 clang/include/clang/CIR/MissingFeatures.h |   4 +
 clang/lib/CIR/CodeGen/CIRGenExpr.cpp  | 100 +++
 clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp|  14 +
 clang/lib/CIR/CodeGen/CIRGenFunction.cpp  |  49 
 clang/lib/CIR/CodeGen/CIRGenFunction.h|  34 +++
 clang/lib/CIR/CodeGen/CIRGenStmt.cpp  |  71 -
 clang/lib/CIR/Dialect/IR/CIRDialect.cpp   | 128 +
 .../lib/CIR/Dialect/Transforms/FlattenCFG.cpp |  70 -
 clang/test/CIR/CodeGen/if.cpp | 254 ++
 clang/test/CIR/Lowering/if.cir|  99 +++
 clang/test/CIR/Transforms/if.cir  |  48 
 13 files changed, 926 insertions(+), 9 deletions(-)
 create mode 100644 clang/test/CIR/CodeGen/if.cpp
 create mode 100644 clang/test/CIR/Lowering/if.cir
 create mode 100644 clang/test/CIR/Transforms/if.cir

diff --git a/clang/include/clang/CIR/Dialect/IR/CIRDialect.h 
b/clang/include/clang/CIR/Dialect/IR/CIRDialect.h
index 4d7f537418a90..4d7f0bfd1c253 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIRDialect.h
+++ b/clang/include/clang/CIR/Dialect/IR/CIRDialect.h
@@ -35,6 +35,10 @@
 using BuilderCallbackRef =
 llvm::function_ref;
 
+namespace cir {
+void buildTerminatedBody(mlir::OpBuilder &builder, mlir::Location loc);
+} // namespace cir
+
 // TableGen'erated files for MLIR dialects require that a macro be defined when
 // they are included.  GET_OP_CLASSES tells the file to define the classes for
 // the operations of that dialect.
diff --git a/clang/include/clang/CIR/Dialect/IR/CIROps.td 
b/clang/include/clang/CIR/Dialect/IR/CIROps.td
index 3965372755685..e181a5db3e1b9 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIROps.td
+++ b/clang/include/clang/CIR/Dialect/IR/CIROps.td
@@ -424,8 +424,8 @@ def StoreOp : CIR_Op<"store", [
 // ReturnOp
 
//===--===//
 
-def ReturnOp : CIR_Op<"return", [ParentOneOf<["FuncOp", "ScopeOp", "DoWhileOp",
-  "WhileOp", "ForOp"]>,
+def ReturnOp : CIR_Op<"return", [ParentOneOf<["FuncOp", "ScopeOp", "IfOp",
+ "DoWhileOp", "WhileOp", "ForOp"]>,
  Terminator]> {
   let summary = "Return from function";
   let description = [{
@@ -462,6 +462,58 @@ def ReturnOp : CIR_Op<"return", [ParentOneOf<["FuncOp", 
"ScopeOp", "DoWhileOp",
   let hasVerifier = 1;
 }
 
+//===--===//
+// IfOp
+//===--===//
+
+def IfOp : CIR_Op<"if",
+ [DeclareOpInterfaceMethods,
+ RecursivelySpeculatable, AutomaticAllocationScope, NoRegionArguments]>{
+
+  let summary = "the if-then-else operation";
+  let description = [{
+The `cir.if` operation represents an if-then-else construct for
+conditionally executing two regions of code. The operand is a `cir.bool`
+type.
+
+Examples:
+
+```mlir
+cir.if %b  {
+  ...
+} else {
+  ...
+}
+
+cir.if %c  {
+  ...
+}
+
+cir.if %c  {
+  ...
+  cir.br ^a
+^a:
+  cir.yield
+}
+```
+
+`cir.if` defines no values and the 'else' can be omitted. The if/else
+regions must be terminated. If the region has only one block, the 
terminator
+can be left out, and `cir.yield` terminator will be inserted implictly.
+Otherwise, the region must be explicitly terminated.
+  }];
+  let arguments = (ins CIR_BoolType:$condition);
+  let regions = (region AnyRegion:$thenRegion, AnyRegion:$elseRegion);
+  let hasCustomAssemblyFormat=1;
+  let hasVerifier=1;
+  let skipDefaultBuilders=1;
+  let builders = [
+OpBuilder<(ins "mlir::Value":$cond, "bool":$withElseRegion,
+  CArg<"BuilderCallbackRef", "buildTerminatedBody">:$thenBuilder,
+  CArg<"BuilderCallbackRef", "nullptr">:$elseBuilder)>
+  ];
+}
+
 
//===--===//
 // ConditionOp
 
//===--===//
@@ -512,8 +564,8 @@ def ConditionOp : CIR_Op<"condition", [
 
//===--===//
 
 def YieldOp : CIR_Op<"yield", [ReturnLike, Terminator,
-   ParentOneOf<["ScopeOp", "WhileOp", "ForOp",
-"DoWhileOp"]>]> 

[clang] clang_EvalResult_getAsCXString impl (PR #134551)

2025-04-06 Thread Damian Andrei via cfe-commits

https://github.com/xTachyon created 
https://github.com/llvm/llvm-project/pull/134551

Tries to implement #69749.

>From Discord:
`
In terms of how to solve it... I'm hoping we can extend CXString to be 
length-aware and then add an interface that returns a CXString object instead. 
Perhaps clang_EvalResult_getAsCXString() with a comment explaining that 
getAsStr() is only valid for null-terminated strings?
`


There's some questions I have:

1. Is `size_t` appropriate here? I see some functions using `unsigned`, and 
some using `size_t`.
2. On this new flow to get a string literal, there's at least 2 allocations of 
the string from the 2 `cxstring::createDup`, one when evaluating the result, 
and one when returning it. Is this ok/can it be done better?
3. Is returning a "null" `CXString` on error a good idea?

There's probably more things that I did wrong, so I'm hoping for a review.

>From 0d23f05ff443ef88e52f0cd4e7c50f221642d209 Mon Sep 17 00:00:00 2001
From: Andrei DAMIAN 
Date: Sun, 6 Apr 2025 19:55:59 +0300
Subject: [PATCH] clang_EvalResult_getAsCXString impl

---
 clang/include/clang-c/CXString.h  |  3 ++
 clang/include/clang-c/Index.h | 15 ++--
 clang/tools/libclang/CIndex.cpp   | 46 ++-
 clang/tools/libclang/CXString.cpp | 22 ---
 clang/tools/libclang/libclang.map |  6 +++
 clang/unittests/libclang/LibclangTest.cpp | 41 
 6 files changed, 96 insertions(+), 37 deletions(-)

diff --git a/clang/include/clang-c/CXString.h b/clang/include/clang-c/CXString.h
index 63dce4d140ce2..a0ad830230338 100644
--- a/clang/include/clang-c/CXString.h
+++ b/clang/include/clang-c/CXString.h
@@ -14,6 +14,7 @@
 #ifndef LLVM_CLANG_C_CXSTRING_H
 #define LLVM_CLANG_C_CXSTRING_H
 
+#include 
 #include "clang-c/ExternC.h"
 #include "clang-c/Platform.h"
 
@@ -36,6 +37,7 @@ LLVM_CLANG_C_EXTERN_C_BEGIN
  */
 typedef struct {
   const void *data;
+  size_t length;
   unsigned private_flags;
 } CXString;
 
@@ -52,6 +54,7 @@ typedef struct {
  * to `std::string::c_str()`.
  */
 CINDEX_LINKAGE const char *clang_getCString(CXString string);
+CINDEX_LINKAGE const char *clang_getCString2(CXString string, size_t *length);
 
 /**
  * Free the given string.
diff --git a/clang/include/clang-c/Index.h b/clang/include/clang-c/Index.h
index 38e2417dcd181..4ef41d56e43ae 100644
--- a/clang/include/clang-c/Index.h
+++ b/clang/include/clang-c/Index.h
@@ -5918,12 +5918,19 @@ clang_EvalResult_getAsUnsigned(CXEvalResult E);
 CINDEX_LINKAGE double clang_EvalResult_getAsDouble(CXEvalResult E);
 
 /**
- * Returns the evaluation result as a constant string if the
- * kind is other than Int or float. User must not free this pointer,
- * instead call clang_EvalResult_dispose on the CXEvalResult returned
- * by clang_Cursor_Evaluate.
+ * This function behaves the same as clang_EvalResult_getAsCXString, with 2
+ * exceptions:
+ * - the string literal will be truncated if a nul byte is found in the string.
+ * For this reason clang_EvalResult_getAsCXString is recommended.
+ * - User must not free this pointer, instead call clang_EvalResult_dispose on
+ * the CXEvalResult returned by clang_Cursor_Evaluate.
  */
 CINDEX_LINKAGE const char *clang_EvalResult_getAsStr(CXEvalResult E);
+/**
+ * Returns the evaluation result as a constant string if the
+ * kind is other than Int or float. This might include zero bytes.
+ */
+CINDEX_LINKAGE CXString clang_EvalResult_getAsCXString(CXEvalResult E);
 
 /**
  * Disposes the created Eval memory.
diff --git a/clang/tools/libclang/CIndex.cpp b/clang/tools/libclang/CIndex.cpp
index c8db6c92bb4d4..672e791ad3455 100644
--- a/clang/tools/libclang/CIndex.cpp
+++ b/clang/tools/libclang/CIndex.cpp
@@ -4589,13 +4589,13 @@ struct ExprEvalResult {
 unsigned long long unsignedVal;
 long long intVal;
 double floatVal;
-char *stringVal;
+CXString stringVal;
   } EvalData;
   bool IsUnsignedInt;
   ~ExprEvalResult() {
 if (EvalType != CXEval_UnExposed && EvalType != CXEval_Float &&
 EvalType != CXEval_Int) {
-  delete[] EvalData.stringVal;
+  clang_disposeString(EvalData.stringVal);
 }
   }
 };
@@ -4651,7 +4651,17 @@ const char *clang_EvalResult_getAsStr(CXEvalResult E) {
   if (!E) {
 return nullptr;
   }
-  return ((ExprEvalResult *)E)->EvalData.stringVal;
+  return clang_getCString(((ExprEvalResult *)E)->EvalData.stringVal);
+}
+
+CXString clang_EvalResult_getAsCXString(CXEvalResult E) {
+  if (!E) {
+return cxstring::createNull();
+  }
+  size_t length;
+  auto data =
+  clang_getCString2(((ExprEvalResult *)E)->EvalData.stringVal, &length);
+  return cxstring::createDup(StringRef(data, length));
 }
 
 static const ExprEvalResult *evaluateExpr(Expr *expr, CXCursor C) {
@@ -4716,11 +4726,7 @@ static const ExprEvalResult *evaluateExpr(Expr *expr, 
CXCursor C) {
 result->EvalType = CXEval_StrLiteral;
   }
 
-  std::string strRef(StrE->getString().str());
-  result->

[clang] clang_EvalResult_getAsCXString impl (PR #134551)

2025-04-06 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/134551
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] f2987f2 - [X86][AVX10] Make warning message more informative, NFCI (#134528)

2025-04-06 Thread via cfe-commits

Author: Phoebe Wang
Date: 2025-04-07T08:31:02+08:00
New Revision: f2987f255ae99cc43cd0da61ac42150af71b0ad6

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

LOG: [X86][AVX10] Make warning message more informative, NFCI (#134528)

Added: 


Modified: 
clang/lib/Driver/ToolChains/Arch/X86.cpp
clang/test/Driver/x86-target-features.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Arch/X86.cpp 
b/clang/lib/Driver/ToolChains/Arch/X86.cpp
index 429b041c9c513..e6ac3a9e4b350 100644
--- a/clang/lib/Driver/ToolChains/Arch/X86.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/X86.cpp
@@ -252,7 +252,9 @@ void x86::getX86TargetFeatures(const Driver &D, const 
llvm::Triple &Triple,
 D.Diag(diag::warn_drv_deprecated_arg) << Name << 1 << 
Name.drop_back(4);
   else if (Width == "256")
 D.Diag(diag::warn_drv_deprecated_custom)
-<< Name << "because AVX10/256 is not supported and will be 
removed";
+<< Name
+<< "no alternative argument provided because "
+   "AVX10/256 is not supported and will be removed";
   else
 assert((Width == "256" || Width == "512") && "Invalid vector length.");
   Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
@@ -286,7 +288,9 @@ void x86::getX86TargetFeatures(const Driver &D, const 
llvm::Triple &Triple,
 if (A->getOption().matches(options::OPT_mevex512) ||
 A->getOption().matches(options::OPT_mno_evex512))
   D.Diag(diag::warn_drv_deprecated_custom)
-  << Name << "because AVX10/256 is not supported and will be removed";
+  << Name
+  << "no alternative argument provided because "
+ "AVX10/256 is not supported and will be removed";
 
 if (A->getOption().matches(options::OPT_mapx_features_EQ) ||
 A->getOption().matches(options::OPT_mno_apx_features_EQ)) {

diff  --git a/clang/test/Driver/x86-target-features.c 
b/clang/test/Driver/x86-target-features.c
index 6416a34898e78..9c18098c87026 100644
--- a/clang/test/Driver/x86-target-features.c
+++ b/clang/test/Driver/x86-target-features.c
@@ -411,8 +411,8 @@
 // RUN: %clang --target=i386 -mavx10.2-512 %s -### -o %t.o 2>&1 | FileCheck 
-check-prefixes=AVX10_2_512,WARN-AVX10-512 %s
 // RUN: %clang --target=i386 -mavx10.2-256 -mavx10.1-512 %s -### -o %t.o 2>&1 
| FileCheck -check-prefixes=AVX10_2_256,AVX10_1_512 %s
 // RUN: %clang --target=i386 -mavx10.2-512 -mavx10.1-256 %s -### -o %t.o 2>&1 
| FileCheck -check-prefixes=AVX10_2_512,AVX10_1_256 %s
-// WARN-EVEX512: warning: argument '{{.*}}evex512' is deprecated, because 
AVX10/256 is not supported and will be removed [-Wdeprecated]
-// WARN-AVX10-256: warning: argument 'avx10.{{.*}}-256' is deprecated, because 
AVX10/256 is not supported and will be removed [-Wdeprecated]
+// WARN-EVEX512: warning: argument '{{.*}}evex512' is deprecated, no 
alternative argument provided because AVX10/256 is not supported and will be 
removed [-Wdeprecated]
+// WARN-AVX10-256: warning: argument 'avx10.{{.*}}-256' is deprecated, no 
alternative argument provided because AVX10/256 is not supported and will be 
removed [-Wdeprecated]
 // WARN-AVX10-512: warning: argument 'avx10.{{.*}}-512' is deprecated, use 
'avx10.{{.*}}' instead [-Wdeprecated]
 // EVEX512: "-target-feature" "+evex512"
 // NO-EVEX512: "-target-feature" "-evex512"



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


[clang] [X86][AVX10] Make warning message more informative, NFCI (PR #134528)

2025-04-06 Thread Phoebe Wang via cfe-commits

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


[clang] aef000d - [clang] fix serialization of SubstNonTypeTemplateParmExpr (#134560)

2025-04-06 Thread via cfe-commits

Author: Matheus Izvekov
Date: 2025-04-06T21:57:20-03:00
New Revision: aef000dd43b8ee2397e71f877217a9ecbd23c608

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

LOG: [clang] fix serialization of SubstNonTypeTemplateParmExpr (#134560)

This fixes a couple of mistakes introduced when merging
https://github.com/llvm/llvm-project/pull/132748

Fixes msan failure reported here:
https://github.com/llvm/llvm-project/pull/132748#issuecomment-2781105225

Added: 


Modified: 
clang/lib/AST/ASTContext.cpp
clang/lib/Serialization/ASTReaderStmt.cpp
clang/lib/Serialization/ASTWriterStmt.cpp

Removed: 




diff  --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index 1b6b3d06ddc1e..320fd4e2f3077 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -7011,7 +7011,7 @@ TemplateName 
ASTContext::getCanonicalTemplateName(TemplateName Name,
 getCanonicalTemplateArgument(subst->getArgumentPack());
 return getSubstTemplateTemplateParmPack(
 canonArgPack, subst->getAssociatedDecl()->getCanonicalDecl(),
-subst->getFinal(), subst->getIndex());
+subst->getIndex(), subst->getFinal());
   }
   case TemplateName::DeducedTemplate: {
 assert(IgnoreDeduced == false);

diff  --git a/clang/lib/Serialization/ASTReaderStmt.cpp 
b/clang/lib/Serialization/ASTReaderStmt.cpp
index d26152f3780ed..22fe54b526433 100644
--- a/clang/lib/Serialization/ASTReaderStmt.cpp
+++ b/clang/lib/Serialization/ASTReaderStmt.cpp
@@ -2229,6 +2229,7 @@ void ASTStmtReader::VisitSubstNonTypeTemplateParmExpr(
 E->PackIndex = Record.readInt();
   else
 E->PackIndex = 0;
+  E->Final = CurrentUnpackingBits->getNextBit();
   E->SubstNonTypeTemplateParmExprBits.NameLoc = readSourceLocation();
   E->Replacement = Record.readSubExpr();
 }

diff  --git a/clang/lib/Serialization/ASTWriterStmt.cpp 
b/clang/lib/Serialization/ASTWriterStmt.cpp
index 23bb5ff22efaf..d0a0f843c7542 100644
--- a/clang/lib/Serialization/ASTWriterStmt.cpp
+++ b/clang/lib/Serialization/ASTWriterStmt.cpp
@@ -2229,6 +2229,7 @@ void ASTStmtWriter::VisitSubstNonTypeTemplateParmExpr(
   CurrentPackingBits.addBit((bool)E->getPackIndex());
   if (auto PackIndex = E->getPackIndex())
 Record.push_back(*PackIndex + 1);
+  CurrentPackingBits.addBit(E->getFinal());
 
   Record.AddSourceLocation(E->getNameLoc());
   Record.AddStmt(E->getReplacement());



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


[clang] [clang] fix serialization of SubstNonTypeTemplateParmExpr (PR #134560)

2025-04-06 Thread Matheus Izvekov via cfe-commits

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


[clang] [flang] [driver] Generalize the code that adds the path of libflang_rt.runtime.a. (PR #134362)

2025-04-06 Thread Daniel Chen via cfe-commits

https://github.com/DanielCChen updated 
https://github.com/llvm/llvm-project/pull/134362

>From cd100a70479adbb4619d685e345485eea99987c5 Mon Sep 17 00:00:00 2001
From: Daniel Chen 
Date: Fri, 4 Apr 2025 06:10:56 -0400
Subject: [PATCH 1/2] [driver] Generalize adding the path of
 libflang_rt.runtime.a.

---
 clang/include/clang/Driver/ToolChain.h   |  4 
 clang/lib/Driver/ToolChain.cpp   | 20 ++--
 clang/lib/Driver/ToolChains/AIX.cpp  |  8 
 clang/lib/Driver/ToolChains/AIX.h|  3 ---
 clang/lib/Driver/ToolChains/PPCLinux.cpp | 16 
 clang/lib/Driver/ToolChains/PPCLinux.h   |  3 ---
 flang/test/Driver/linker-flags.f90   |  2 +-
 7 files changed, 23 insertions(+), 33 deletions(-)

diff --git a/clang/include/clang/Driver/ToolChain.h 
b/clang/include/clang/Driver/ToolChain.h
index 076e4296c3090..d0059673d6a67 100644
--- a/clang/include/clang/Driver/ToolChain.h
+++ b/clang/include/clang/Driver/ToolChain.h
@@ -521,6 +521,10 @@ class ToolChain {
   addFortranRuntimeLibraryPath(const llvm::opt::ArgList &Args,
llvm::opt::ArgStringList &CmdArgs) const;
 
+  /// Add the path for libflang_rt.runtime.a
+  void addFlangRTLibPath(const llvm::opt::ArgList &Args,
+ llvm::opt::ArgStringList &CmdArgs) const;
+
   const char *getCompilerRTArgString(const llvm::opt::ArgList &Args,
  StringRef Component,
  FileType Type = ToolChain::FT_Static,
diff --git a/clang/lib/Driver/ToolChain.cpp b/clang/lib/Driver/ToolChain.cpp
index 36d0ae34dec86..054618a44d7bc 100644
--- a/clang/lib/Driver/ToolChain.cpp
+++ b/clang/lib/Driver/ToolChain.cpp
@@ -816,8 +816,7 @@ void ToolChain::addFortranRuntimeLibs(const ArgList &Args,
   if (AsNeeded)
 addAsNeededOption(*this, Args, CmdArgs, /*as_needed=*/false);
 }
-CmdArgs.push_back("-lflang_rt.runtime");
-addArchSpecificRPath(*this, Args, CmdArgs);
+addFlangRTLibPath(Args, CmdArgs);
 
 // needs libexecinfo for backtrace functions
 if (getTriple().isOSFreeBSD() || getTriple().isOSNetBSD() ||
@@ -850,6 +849,23 @@ void ToolChain::addFortranRuntimeLibraryPath(const 
llvm::opt::ArgList &Args,
 CmdArgs.push_back(Args.MakeArgString("-L" + DefaultLibPath));
 }
 
+void ToolChain::addFlangRTLibPath(const ArgList &Args,
+  llvm::opt::ArgStringList &CmdArgs) const {
+  // Link static flang_rt.runtime.a or shared flang_rt.runtime.so
+  const char *Path;
+  if (getVFS().exists(Twine(Path = getCompilerRTArgString(
+Args, "runtime", ToolChain::FT_Static, true
+CmdArgs.push_back(Path);
+  else if (getVFS().exists(
+   Twine(Path = getCompilerRTArgString(
+ Args, "runtime", ToolChain::FT_Shared, true
+CmdArgs.push_back(Path);
+  else {
+CmdArgs.push_back("-lflang_rt.runtime");
+addArchSpecificRPath(*this, Args, CmdArgs);
+  }
+}
+
 // Android target triples contain a target version. If we don't have libraries
 // for the exact target version, we should fall back to the next newest version
 // or a versionless path, if any.
diff --git a/clang/lib/Driver/ToolChains/AIX.cpp 
b/clang/lib/Driver/ToolChains/AIX.cpp
index 26b9d4c772be6..5dc80bc5a3d25 100644
--- a/clang/lib/Driver/ToolChains/AIX.cpp
+++ b/clang/lib/Driver/ToolChains/AIX.cpp
@@ -608,14 +608,6 @@ void AIX::addProfileRTLibs(const llvm::opt::ArgList &Args,
   ToolChain::addProfileRTLibs(Args, CmdArgs);
 }
 
-void AIX::addFortranRuntimeLibs(const ArgList &Args,
-llvm::opt::ArgStringList &CmdArgs) const {
-  // Link flang_rt.runtime.a. On AIX, the static and shared library are all
-  // named .a
-  CmdArgs.push_back(
-  getCompilerRTArgString(Args, "runtime", ToolChain::FT_Static, true));
-}
-
 ToolChain::CXXStdlibType AIX::GetDefaultCXXStdlibType() const {
   return ToolChain::CST_Libcxx;
 }
diff --git a/clang/lib/Driver/ToolChains/AIX.h 
b/clang/lib/Driver/ToolChains/AIX.h
index 17e8370cd1218..8f130f6b54547 100644
--- a/clang/lib/Driver/ToolChains/AIX.h
+++ b/clang/lib/Driver/ToolChains/AIX.h
@@ -87,9 +87,6 @@ class LLVM_LIBRARY_VISIBILITY AIX : public ToolChain {
   void addProfileRTLibs(const llvm::opt::ArgList &Args,
 llvm::opt::ArgStringList &CmdArgs) const override;
 
-  void addFortranRuntimeLibs(const llvm::opt::ArgList &Args,
- llvm::opt::ArgStringList &CmdArgs) const override;
-
   CXXStdlibType GetDefaultCXXStdlibType() const override;
 
   RuntimeLibType GetDefaultRuntimeLibType() const override;
diff --git a/clang/lib/Driver/ToolChains/PPCLinux.cpp 
b/clang/lib/Driver/ToolChains/PPCLinux.cpp
index 575e88c6ab124..0ed0f91ad166c 100644
--- a/clang/lib/Driver/ToolChains/PPCLinux.cpp
+++ b/clang/lib/Driver/ToolChains/PPCLinux.cpp
@@ -12,7 +12,6 @@
 #include "clang/Driver/Options.h"
 #include "llvm/Support/FileSystem.h"

[clang] [flang] [driver] Generalize the code that adds the path of libflang_rt.runtime.a. (PR #134362)

2025-04-06 Thread Daniel Chen via cfe-commits

DanielCChen wrote:

> Can you please explain why you want to link the static library by default? 
> For example, Clang has these options 
> https://clang.llvm.org/docs/ClangCommandLineReference.html#cmdoption-clang-static-libgcc
>  that allow users to force the static linking, and, I think, by default it 
> links shared compiler support libraries.
> 
> Also, how does the full path linking of the shared library works with 
> `-frtlib-add-rpath`?

The `flang-rt` cmake is using the similar frame work to how `compiler-rt` is 
built. It publishes `libflang_rt.runtime.*` to the Clang `resource_dir` no 
matter if it is static or shared although `resource_dir` is normally for static 
libs. As your link points out, unlike Clang, Flang currently does not have a 
compiler option to switch between linking to the static or shared `flang-rt`, 
so the current order in this PR does not dictate the default.  
As the next step, I am planning to add a compiler option `-static-libflang_rt` 
that is similar to `-static-libgcc` for that purpose (or `-dynamic-libflang_rt` 
if we decide to link static `flang-rt` as default).

As for the `frtlib-add-rpath`, The current code before this PR is passing 
`-L/resource_dir/ -lflan_rt.runtime` to the linker. If the shared `flang-rt` is 
present in the `resource_dir`, the linker "prefers" the shared `flang-rt`. 
Users will need to specify `-frtlib-add-rpath` in order to link to the shared 
`flang-rt`. 
The full path linking should not affect that behavior. Users still need the 
`-frtlib-add-rpath` option to link to the shared `flang-rt` with full path 
name. 

I actually missed that in the shared path in this PR. I will push an amendment.

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


[clang] [X86][AVX10] Make warning message more informative, NFCI (PR #134528)

2025-04-06 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder 
`clang-aarch64-sve2-vla-2stage` running on `linaro-g4-02` while building 
`clang` at step 12 "ninja check 2".

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


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

```
Step 12 (ninja check 2) failure: stage 2 checked (failure)
...
PASS: Flang :: Driver/missing-arg.f90 (24782 of 96621)
PASS: Flang :: Driver/parse-fir-error.ll (24783 of 96621)
PASS: Flang :: Driver/phases.f90 (24784 of 96621)
PASS: Flang :: Driver/predefined-macros-compiler-version.F90 (24785 of 96621)
PASS: Flang :: Driver/print-effective-triple.f90 (24786 of 96621)
PASS: Flang :: Driver/print-resource-dir.F90 (24787 of 96621)
PASS: Flang :: Driver/parse-ir-error.f95 (24788 of 96621)
PASS: Flang :: Driver/lto-bc.f90 (24789 of 96621)
PASS: Flang :: Driver/mlir-pass-pipeline.f90 (24790 of 96621)
UNRESOLVED: Flang :: Driver/slp-vectorize.ll (24791 of 96621)
 TEST 'Flang :: Driver/slp-vectorize.ll' FAILED 

Test has no 'RUN:' line

PASS: Flang :: Driver/pass-plugin-not-found.f90 (24792 of 96621)
PASS: Flang :: Driver/fsave-optimization-record.f90 (24793 of 96621)
PASS: Flang :: Driver/print-target-triple.f90 (24794 of 96621)
PASS: Flang :: Driver/scanning-error.f95 (24795 of 96621)
PASS: Flang :: Driver/pthread.f90 (24796 of 96621)
PASS: Flang :: Driver/std2018-wrong.f90 (24797 of 96621)
PASS: Flang :: Driver/mllvm.f90 (24798 of 96621)
PASS: Flang :: Driver/print-pipeline-passes.f90 (24799 of 96621)
PASS: Flang :: Driver/mlink-builtin-bc.f90 (24800 of 96621)
PASS: Flang :: Driver/pp-fixed-form.f90 (24801 of 96621)
PASS: Flang :: Driver/supported-suffices/f03-suffix.f03 (24802 of 96621)
PASS: Flang :: Driver/supported-suffices/f08-suffix.f08 (24803 of 96621)
PASS: Flang :: Driver/multiple-input-files.f90 (24804 of 96621)
PASS: Flang :: Driver/target.f90 (24805 of 96621)
PASS: Flang :: Driver/tco-code-gen-llvm.fir (24806 of 96621)
PASS: Flang :: Driver/lto-flags.f90 (24807 of 96621)
PASS: Flang :: Driver/target-gpu-features.f90 (24808 of 96621)
PASS: Flang :: Driver/prescanner-diag.f90 (24809 of 96621)
PASS: Flang :: Driver/optimization-remark-backend.f90 (24810 of 96621)
PASS: Flang :: Driver/q-unused-arguments.f90 (24811 of 96621)
PASS: Flang :: Driver/no-duplicate-main.f90 (24812 of 96621)
PASS: Flang :: Driver/unsupported-vscale-max-min.f90 (24813 of 96621)
PASS: Flang :: Driver/unparse-use-analyzed.f95 (24814 of 96621)
PASS: Flang :: Driver/optimization-remark-invalid.f90 (24815 of 96621)
PASS: Flang :: Driver/target-machine-error.f90 (24816 of 96621)
PASS: Flang :: Driver/response-file.f90 (24817 of 96621)
PASS: Flang :: Driver/fveclib.f90 (24818 of 96621)
PASS: Flang :: Driver/save-temps.f90 (24819 of 96621)
PASS: Flang :: Driver/std2018.f90 (24820 of 96621)
PASS: Flang :: Driver/save-temps-use-module.f90 (24821 of 96621)
PASS: Flang :: Driver/unparse-with-modules.f90 (24822 of 96621)
PASS: Flang :: Driver/falias-analysis.f90 (24823 of 96621)
PASS: Flang :: Driver/w-arg-unsupported.f90 (24824 of 96621)
PASS: Flang :: Driver/underscoring.f90 (24825 of 96621)
PASS: Flang :: Driver/target-cpu-features-invalid.f90 (24826 of 96621)
PASS: Flang :: Driver/default-optimization-pipelines.f90 (24827 of 96621)

```



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


[clang] [clang] fix serialization of SubstNonTypeTemplateParmExpr (PR #134560)

2025-04-06 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder 
`clang-cmake-x86_64-avx512-win` running on `avx512-intel64-win` while building 
`clang` at step 4 "cmake stage 1".

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


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

```
Step 4 (cmake stage 1) failure: 'cmake -G ...' (failure)
'cmake' is not recognized as an internal or external command,
operable program or batch file.

```



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


[clang-tools-extra] da6e245 - [clang-tidy] Improve `bugprone-capturing-this-in-member-variable` check: add support of `bind` functions. (#132635)

2025-04-06 Thread via cfe-commits

Author: Baranov Victor
Date: 2025-04-07T09:57:55+08:00
New Revision: da6e2454fff3fbc86861e31b60f18d3467354375

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

LOG: [clang-tidy] Improve `bugprone-capturing-this-in-member-variable` check: 
add support of `bind` functions. (#132635)

Improve `bugprone-capturing-this-in-member-variable` check:
Added support of `bind`-like functions that capture and store `this`
pointer in class member.

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

Added: 


Modified: 
clang-tools-extra/clang-tidy/bugprone/CapturingThisInMemberVariableCheck.cpp
clang-tools-extra/clang-tidy/bugprone/CapturingThisInMemberVariableCheck.h
clang-tools-extra/docs/ReleaseNotes.rst

clang-tools-extra/docs/clang-tidy/checks/bugprone/capturing-this-in-member-variable.rst

clang-tools-extra/test/clang-tidy/checkers/bugprone/capturing-this-in-member-variable.cpp

Removed: 




diff  --git 
a/clang-tools-extra/clang-tidy/bugprone/CapturingThisInMemberVariableCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/CapturingThisInMemberVariableCheck.cpp
index add0576a42c33..1bfe384258ddb 100644
--- 
a/clang-tools-extra/clang-tidy/bugprone/CapturingThisInMemberVariableCheck.cpp
+++ 
b/clang-tools-extra/clang-tidy/bugprone/CapturingThisInMemberVariableCheck.cpp
@@ -64,16 +64,23 @@ AST_MATCHER(CXXRecordDecl, correctHandleCaptureThisLambda) {
 
 constexpr const char *DefaultFunctionWrapperTypes =
 "::std::function;::std::move_only_function;::boost::function";
+constexpr const char *DefaultBindFunctions =
+"::std::bind;::boost::bind;::std::bind_front;::std::bind_back;"
+"::boost::compat::bind_front;::boost::compat::bind_back";
 
 CapturingThisInMemberVariableCheck::CapturingThisInMemberVariableCheck(
 StringRef Name, ClangTidyContext *Context)
 : ClangTidyCheck(Name, Context),
   FunctionWrapperTypes(utils::options::parseStringList(
-  Options.get("FunctionWrapperTypes", DefaultFunctionWrapperTypes))) {}
+  Options.get("FunctionWrapperTypes", DefaultFunctionWrapperTypes))),
+  BindFunctions(utils::options::parseStringList(
+  Options.get("BindFunctions", DefaultBindFunctions))) {}
 void CapturingThisInMemberVariableCheck::storeOptions(
 ClangTidyOptions::OptionMap &Opts) {
   Options.store(Opts, "FunctionWrapperTypes",
 utils::options::serializeStringList(FunctionWrapperTypes));
+  Options.store(Opts, "BindFunctions",
+utils::options::serializeStringList(BindFunctions));
 }
 
 void CapturingThisInMemberVariableCheck::registerMatchers(MatchFinder *Finder) 
{
@@ -87,33 +94,52 @@ void 
CapturingThisInMemberVariableCheck::registerMatchers(MatchFinder *Finder) {
   // [self = this]
   capturesVar(varDecl(hasInitializer(cxxThisExpr());
   auto IsLambdaCapturingThis =
-  lambdaExpr(hasAnyCapture(CaptureThis.bind("capture"))).bind("lambda");
-  auto IsInitWithLambda =
-  anyOf(IsLambdaCapturingThis,
-cxxConstructExpr(hasArgument(0, IsLambdaCapturingThis)));
+  lambdaExpr(hasAnyCapture(CaptureThis)).bind("lambda");
+
+  auto IsBindCapturingThis =
+  callExpr(
+  callee(functionDecl(matchers::matchesAnyListedName(BindFunctions))
+ .bind("callee")),
+  hasAnyArgument(cxxThisExpr()))
+  .bind("bind");
+
+  auto IsInitWithLambdaOrBind =
+  anyOf(IsLambdaCapturingThis, IsBindCapturingThis,
+cxxConstructExpr(hasArgument(
+0, anyOf(IsLambdaCapturingThis, IsBindCapturingThis;
+
   Finder->addMatcher(
   cxxRecordDecl(
   anyOf(has(cxxConstructorDecl(
 unless(isCopyConstructor()), unless(isMoveConstructor()),
 hasAnyConstructorInitializer(cxxCtorInitializer(
 isMemberInitializer(), forField(IsStdFunctionField),
-withInitializer(IsInitWithLambda),
+withInitializer(IsInitWithLambdaOrBind),
 has(fieldDecl(IsStdFunctionField,
-  hasInClassInitializer(IsInitWithLambda,
+  hasInClassInitializer(IsInitWithLambdaOrBind,
   unless(correctHandleCaptureThisLambda())),
   this);
 }
-
 void CapturingThisInMemberVariableCheck::check(
 const MatchFinder::MatchResult &Result) {
-  const auto *Capture = Result.Nodes.getNodeAs("capture");
-  const auto *Lambda = Result.Nodes.getNodeAs("lambda");
+  if (const auto *Lambda = Result.Nodes.getNodeAs("lambda")) {
+diag(Lambda->getBeginLoc(),
+ "'this' captured by a lambda and stored in a class member variable; "
+ "disable implicit class copying/moving to prevent potential "
+ "use-after-free")

[clang-tools-extra] [clang-tidy] Improve `bugprone-capturing-this-in-member-variable` check: add support of `bind` functions. (PR #132635)

2025-04-06 Thread Congcong Cai via cfe-commits

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


[clang] 6ce0fd7 - [clang] NFC: clean trailing whitespaces in clang/test/CXX/drs/cwg15xx.cpp

2025-04-06 Thread Matheus Izvekov via cfe-commits

Author: Matheus Izvekov
Date: 2025-04-06T23:42:27-03:00
New Revision: 6ce0fd7f74502a75120bef43f12f56e3a5d80dfd

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

LOG: [clang] NFC: clean trailing whitespaces in clang/test/CXX/drs/cwg15xx.cpp

Added: 


Modified: 
clang/test/CXX/drs/cwg15xx.cpp

Removed: 




diff  --git a/clang/test/CXX/drs/cwg15xx.cpp b/clang/test/CXX/drs/cwg15xx.cpp
index 30ec63999ca28..8e3e49dc42ce0 100644
--- a/clang/test/CXX/drs/cwg15xx.cpp
+++ b/clang/test/CXX/drs/cwg15xx.cpp
@@ -38,7 +38,7 @@ namespace cwg1512 { // cwg1512: 4
   template void 
composite_pointer_type_is_ord() {
 composite_pointer_type_is_base();
 
-typedef __typeof(val() < val()) cmp; // #cwg1512-lt 
+typedef __typeof(val() < val()) cmp; // #cwg1512-lt
 // since-cxx17-warning@#cwg1512-lt {{ordered comparison of function 
pointers ('int (*)() noexcept' and 'int (*)()')}}
 //   since-cxx17-note@#cwg1512-noexcept-1st {{in instantiation of function 
template specialization 'cwg1512::composite_pointer_type_is_ord' requested here}}
 // since-cxx17-warning@#cwg1512-lt {{ordered comparison of function 
pointers ('int (*)()' and 'int (*)() noexcept')}}
@@ -332,7 +332,7 @@ namespace cwg1550 { // cwg1550: 3.4
 namespace cwg1558 { // cwg1558: 12
 #if __cplusplus >= 201103L
   template using first_of = T;
-  template first_of f(int); // #cwg1558-f 
+  template first_of f(int); // #cwg1558-f
   template void f(...) = delete; // #cwg1558-f-deleted
 
   struct X { typedef void type; };
@@ -639,7 +639,7 @@ namespace cwg1591 {  //cwg1591. Deducing array bound and 
element type from initi
 #if __cplusplus >= 201103L
   template int h(T const(&)[N]);
   int X = h({1,2,3});  // T deduced to int, N deduced to 3
-  
+
   template int j(T const(&)[3]);
   int Y = j({42}); // T deduced to int, array bound not 
considered
 
@@ -655,12 +655,12 @@ namespace cwg1591 {  //cwg1591. Deducing array bound and 
element type from initi
 
   template int n(T const(&)[N], T);
   int X1 = n({{1},{2},{3}},Aggr()); // OK, T is Aggr, N is 3
-  
-  
+
+
   namespace check_multi_dim_arrays {
 template int ***f(const T (&a)[N][M][O]); // 
#cwg1591-f-3
 template int **f(const T (&a)[N][M]); // 
#cwg1591-f-2
-   
+
template int *f(const T (&a)[N]); // #cwg1591-f-1
 int ***p3 = f({  {  {1,2}, {3, 4}  }, {  {5,6}, {7, 8}  }, {  {9,10}, {11, 
12}  } });
 int ***p33 = f({  {  {1,2}, {3, 4}  }, {  {5,6}, {7, 8}  }, {  {9,10}, 
{11, 12, 13}  } });
@@ -675,7 +675,7 @@ namespace cwg1591 {  //cwg1591. Deducing array bound and 
element type from initi
   namespace check_multi_dim_arrays_rref {
 template int ***g(T (&&a)[N][M][O]); // 
#cwg1591-g-3
 template int **g(T (&&a)[N][M]); // #cwg1591-g-2
-   
+
 template int *g(T (&&a)[N]); // #cwg1591-g-1
 int ***p3 = g({  {  {1,2}, {3, 4}  }, {  {5,6}, {7, 8}  }, {  {9,10}, {11, 
12}  } });
 int ***p33 = g({  {  {1,2}, {3, 4}  }, {  {5,6}, {7, 8}  }, {  {9,10}, 
{11, 12, 13}  } });
@@ -687,7 +687,7 @@ namespace cwg1591 {  //cwg1591. Deducing array bound and 
element type from initi
 int **p22 = g({  {1,2}, {3, 4}  });
 int *p1 = g({1, 2, 3});
   }
-  
+
   namespace check_arrays_of_init_list {
 template float *h(const std::initializer_list (&)[N]);
 template double *h(const T(&)[N]);
@@ -695,7 +695,7 @@ namespace cwg1591 {  //cwg1591. Deducing array bound and 
element type from initi
 float *fp = h({{1}, {1, 2}, {1, 2, 3}});
   }
   namespace core_reflector_28543 {
-
+
 template int *i(T (&&)[N]);  // #1
 template char *i(std::initializer_list &&);  // #2
 template int **i(T (&&)[N][M]); // #3 #cwg1591-i-2
@@ -704,13 +704,13 @@ namespace cwg1591 {  //cwg1591. Deducing array bound and 
element type from initi
 template short *i(T (&&)[2]);  // #5
 
 template using Arr = T[];
- 
+
 char *pc = i({1, 2, 3}); // OK prefer #2 via 13.3.3.2 [over.ics.rank]
-char *pc2 = i({1, 2}); // #2 also 
+char *pc2 = i({1, 2}); // #2 also
 int *pi = i(Arr{1, 2, 3}); // OK prefer #1
 
 void *pv1 = i({ {1, 2, 3}, {4, 5, 6} }); // ambiguous btw 3 & 4
-// since-cxx11-error@-1 {{call to 'i' is ambiguous}} 
+// since-cxx11-error@-1 {{call to 'i' is ambiguous}}
 //   since-cxx11-note@#cwg1591-i-2 {{candidate function [with T = int, N = 
2, M = 3]}}
 //   since-cxx11-note@#cwg1591-i-1 {{candidate function [with T = int, N = 
2]}}
 char **pcc = i({ {1}, {2, 3} }); // OK #4



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