c++: check arity before deduction w/ explicit targs [PR12672]
authorPatrick Palka <ppalka@redhat.com>
Tue, 31 Aug 2021 17:31:10 +0000 (13:31 -0400)
committerPatrick Palka <ppalka@redhat.com>
Tue, 31 Aug 2021 17:31:10 +0000 (13:31 -0400)
commitf1e7319956928712e8bf4893ebdfeeb6441099ee
tree76e9b8a6158909aad2a40756c067f0ab3d2abf7d
parent92dc5d844a2088db79bc4521be3ecb4e2f284444
c++: check arity before deduction w/ explicit targs [PR12672]

During overload resolution, when the arity of a function template
clearly disagrees with the arity of the call, no specialization of the
function template could yield a viable candidate.  The deduction routine
type_unification_real already notices this situation, but not before
it substitutes explicit template arguments into the template, a step
which could induce a hard error.  Although it's necessary to perform
this substitution first in order to check arity perfectly (since the
substitution can e.g. expand a non-trailing parameter pack), in most
cases we can determine ahead of time whether there's an arity
disagreement without needing to perform deduction at all.

To that end, this patch implements an (approximate) arity check in
add_template_candidate_real that guards actual deduction.  It's enabled
only when there are explicit template arguments since that's when
deduction can force otherwise avoidable template instantiations.  (I
experimented with enabling it unconditionally as an optimization, and
observed some improvements to compile time of about 5% but also some
slowdowns of about the same magnitude, so kept it conditional.)

In passing, this adds a least_p parameter to arity_rejection for sake
of consistent diagnostics with unify_arity.

A couple of testcases needed to be adjusted so that deduction continues
to occur as intended after this change.  Except in unify6.C, where we
were expecting foo<void ()> to be ill-formed due to substitution
forming a function type with an added 'const', but ISTM this is
permitted by [dcl.fct]/7, so I changed the test accordingly.

PR c++/12672

gcc/cp/ChangeLog:

* call.c (rejection_reason::call_varargs_p): Rename this
previously unused member to ...
(rejection_reason::least_p): ... this.
(arity_rejection): Add least_p parameter.
(add_template_candidate_real): When there are explicit
template arguments, check that the arity of the call agrees with
the arity of the function before attempting deduction.
(print_arity_information): Add least_p parameter.
(print_z_candidate): Adjust call to print_arity_information.

gcc/testsuite/ChangeLog:

* g++.dg/cpp0x/decltype29.C: Adjust.
* g++.dg/template/error56.C: Adjust.
* g++.old-deja/g++.pt/unify6.C: Adjust.
* g++.dg/template/explicit-args7.C: New test.
gcc/cp/call.c
gcc/testsuite/g++.dg/cpp0x/decltype29.C
gcc/testsuite/g++.dg/template/error56.C
gcc/testsuite/g++.dg/template/explicit-args7.C [new file with mode: 0644]
gcc/testsuite/g++.old-deja/g++.pt/unify6.C