[clang] af682f0 - [clang] Fix single-element array initialization in constexpr

Mariya Podchishchaeva via cfe-commits cfe-commits at lists.llvm.org
Tue Mar 7 08:05:41 PST 2023


Author: Mariya Podchishchaeva
Date: 2023-03-07T10:57:35-05:00
New Revision: af682f0df83f3364dac7ab92f39c7209dfbce28a

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

LOG: [clang] Fix single-element array initialization in constexpr

https://reviews.llvm.org/D130791 added an improvement that in case array
element has a trivial constructor, it is evaluated once and the result is
re-used for remaining elements. Make sure the constructor is evaluated
for single-elements arrays too.

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

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D145486

Added: 
    clang/test/SemaCXX/constexpr-single-element-array.cpp

Modified: 
    clang/lib/AST/ExprConstant.cpp

Removed: 
    


################################################################################
diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 6b0beb1973893..26c23423b858f 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -10917,7 +10917,7 @@ bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
         for (unsigned I = OldElts; I < N; ++I)
           Value->getArrayInitializedElt(I) = Filler;
 
-      if (HasTrivialConstructor && N == FinalSize) {
+      if (HasTrivialConstructor && N == FinalSize && FinalSize != 1) {
         // If we have a trivial constructor, only evaluate it once and copy
         // the result into all the array elements.
         APValue &FirstResult = Value->getArrayInitializedElt(0);

diff  --git a/clang/test/SemaCXX/constexpr-single-element-array.cpp b/clang/test/SemaCXX/constexpr-single-element-array.cpp
new file mode 100644
index 0000000000000..a01b1a1c8f136
--- /dev/null
+++ b/clang/test/SemaCXX/constexpr-single-element-array.cpp
@@ -0,0 +1,19 @@
+// RUN: %clang_cc1 -std=c++20 -verify %s
+
+// This test makes sure that a single element array doesn't produce
+// spurious errors during constexpr evaluation.
+
+// expected-no-diagnostics
+struct Sub { int x; };
+
+struct S {
+  constexpr S() { Arr[0] = Sub{}; }
+  Sub Arr[1];
+};
+
+constexpr bool test() {
+  S s;
+  return true;
+}
+
+static_assert(test());


        


More information about the cfe-commits mailing list