Tested x86_64-pc-linux-gnu, applying to trunk.

-- 8< --

Since std::vector became usable in constant evaluation in C++20, a vector
variable with static storage duration might be manifestly
constant-evaluated, so we properly try to constant-evaluate its initializer.
But it can never succeed since the result will always refer to the result of
operator new, so trying is a waste of time.  Potentially a large waste of
time for a large vector, as in the testcase in the PR.

So, let's recognize this case and skip trying constant-evaluation.  I do
this only for the case of an integer argument, as that's the case that's
easy to write but slow to (fail to) evaluate.

In the test, I use dg-timeout-factor to lower the default timeout from 300
seconds to 15; on my laptop, compilation without the patch takes about 20
seconds versus about 2 with the patch.

        PR c++/113835

gcc/cp/ChangeLog:

        * constexpr.cc (cxx_eval_outermost_constant_expr): Bail out early
        for std::vector(N).

gcc/testsuite/ChangeLog:

        * g++.dg/cpp2a/constexpr-vector1.C: New test.
---
 gcc/cp/constexpr.cc                            | 9 +++++++++
 gcc/testsuite/g++.dg/cpp2a/constexpr-vector1.C | 8 ++++++++
 2 files changed, 17 insertions(+)
 create mode 100644 gcc/testsuite/g++.dg/cpp2a/constexpr-vector1.C

diff --git a/gcc/cp/constexpr.cc b/gcc/cp/constexpr.cc
index 7e375823d64..dc59f59aa3f 100644
--- a/gcc/cp/constexpr.cc
+++ b/gcc/cp/constexpr.cc
@@ -9127,6 +9127,15 @@ cxx_eval_outermost_constant_expr (tree t, bool 
allow_non_constant,
       tree fndecl = cp_get_callee_fndecl_nofold (x);
       if (fndecl && DECL_IMMEDIATE_FUNCTION_P (fndecl))
        is_consteval = true;
+      /* Don't try to evaluate a std::vector constructor taking an integer, it
+        will fail in the 'if (heap_var)' block below after doing all the work
+        (c++/113835).  This will need adjustment if P3554 is accepted.  Note
+        that evaluation of e.g. the vector default constructor can succeed, so
+        we don't shortcut all vector constructors.  */
+      if (fndecl && DECL_CONSTRUCTOR_P (fndecl) && allow_non_constant
+         && is_std_class (type, "vector") && call_expr_nargs (x) > 1
+         && TREE_CODE (TREE_TYPE (get_nth_callarg (x, 1))) == INTEGER_TYPE)
+       return t;
     }
   if (AGGREGATE_TYPE_P (type) || VECTOR_TYPE_P (type))
     {
diff --git a/gcc/testsuite/g++.dg/cpp2a/constexpr-vector1.C 
b/gcc/testsuite/g++.dg/cpp2a/constexpr-vector1.C
new file mode 100644
index 00000000000..196c6ec51fc
--- /dev/null
+++ b/gcc/testsuite/g++.dg/cpp2a/constexpr-vector1.C
@@ -0,0 +1,8 @@
+// PR c++/113835
+// { dg-timeout-factor 0.05 }
+// { dg-do compile { target c++20_only } }
+
+#include <vector>
+const std::size_t N = 1'000'000;
+std::vector<int> x(N);
+int main() {}

base-commit: fa58ff249a0e63a721ccb6d770c86523d84a212a
-- 
2.49.0

Reply via email to