Skip to content

Commit f29f7f8

Browse files
committed
c++: fix ICE with __type_pack_element [PR113834]
Here we crash on this invalid code because we seem to infinitely recurse and end up with __type_pack_element with index that doesn't tree_fits_shwi_p which then crashes on tree_to_shwi. Thanks to Jakub for suggesting a nicer fix than my original one. PR c++/113834 gcc/cp/ChangeLog: * semantics.cc (finish_type_pack_element): Perform range checking before tree_to_shwi. gcc/testsuite/ChangeLog: * g++.dg/ext/type_pack_element4.C: New test.
1 parent 3a3e0f1 commit f29f7f8

File tree

2 files changed

+20
-4
lines changed

2 files changed

+20
-4
lines changed

gcc/cp/semantics.cc

+3-4
Original file line numberDiff line numberDiff line change
@@ -4650,20 +4650,19 @@ finish_type_pack_element (tree idx, tree types, tsubst_flags_t complain)
46504650
error ("%<__type_pack_element%> index is not an integral constant");
46514651
return error_mark_node;
46524652
}
4653-
HOST_WIDE_INT val = tree_to_shwi (idx);
4654-
if (val < 0)
4653+
if (tree_int_cst_sgn (idx) < 0)
46554654
{
46564655
if (complain & tf_error)
46574656
error ("%<__type_pack_element%> index is negative");
46584657
return error_mark_node;
46594658
}
4660-
if (val >= TREE_VEC_LENGTH (types))
4659+
if (wi::to_widest (idx) >= TREE_VEC_LENGTH (types))
46614660
{
46624661
if (complain & tf_error)
46634662
error ("%<__type_pack_element%> index is out of range");
46644663
return error_mark_node;
46654664
}
4666-
return TREE_VEC_ELT (types, val);
4665+
return TREE_VEC_ELT (types, tree_to_shwi (idx));
46674666
}
46684667

46694668
/* Implement the __direct_bases keyword: Return the direct base classes
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// PR c++/113834
2+
// { dg-do compile { target c++17 } }
3+
4+
template <typename... _Elements> class tuple{};
5+
template <unsigned long __i, typename... _Elements>
6+
__type_pack_element<__i, _Elements...> &get(tuple<_Elements...> &__t) noexcept; // { dg-error "index is out of range" }
7+
tuple<int,int> data;
8+
template <unsigned long Level>
9+
unsigned take_impl(unsigned idx) {
10+
if constexpr (Level != -1){
11+
return take_impl<Level - 1>(get<Level - 1>(data)); // { dg-error "" }
12+
}
13+
return 0;
14+
}
15+
int main() {
16+
take_impl<2>(0);
17+
}

0 commit comments

Comments
 (0)