xref: /dragonfly/contrib/gcc-8.0/gcc/cp/pt.c (revision e215fc28)
1 /* Handle parameterized types (templates) for GNU -*- C++ -*-.
2    Copyright (C) 1992-2018 Free Software Foundation, Inc.
3    Written by Ken Raeburn (raeburn@cygnus.com) while at Watchmaker Computing.
4    Rewritten by Jason Merrill (jason@cygnus.com).
5 
6 This file is part of GCC.
7 
8 GCC is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3, or (at your option)
11 any later version.
12 
13 GCC is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17 
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3.  If not see
20 <http://www.gnu.org/licenses/>.  */
21 
22 /* Known bugs or deficiencies include:
23 
24      all methods must be provided in header files; can't use a source
25      file that contains only the method templates and "just win".  */
26 
27 #include "config.h"
28 #include "system.h"
29 #include "coretypes.h"
30 #include "cp-tree.h"
31 #include "timevar.h"
32 #include "stringpool.h"
33 #include "varasm.h"
34 #include "attribs.h"
35 #include "stor-layout.h"
36 #include "intl.h"
37 #include "c-family/c-objc.h"
38 #include "cp-objcp-common.h"
39 #include "toplev.h"
40 #include "tree-iterator.h"
41 #include "type-utils.h"
42 #include "gimplify.h"
43 #include "gcc-rich-location.h"
44 #include "selftest.h"
45 
46 /* The type of functions taking a tree, and some additional data, and
47    returning an int.  */
48 typedef int (*tree_fn_t) (tree, void*);
49 
50 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
51    instantiations have been deferred, either because their definitions
52    were not yet available, or because we were putting off doing the work.  */
53 struct GTY ((chain_next ("%h.next"))) pending_template
54 {
55   struct pending_template *next;
56   struct tinst_level *tinst;
57 };
58 
59 static GTY(()) struct pending_template *pending_templates;
60 static GTY(()) struct pending_template *last_pending_template;
61 
62 int processing_template_parmlist;
63 static int template_header_count;
64 
65 static GTY(()) tree saved_trees;
66 static vec<int> inline_parm_levels;
67 
68 static GTY(()) struct tinst_level *current_tinst_level;
69 
70 static GTY(()) tree saved_access_scope;
71 
72 /* Live only within one (recursive) call to tsubst_expr.  We use
73    this to pass the statement expression node from the STMT_EXPR
74    to the EXPR_STMT that is its result.  */
75 static tree cur_stmt_expr;
76 
77 // -------------------------------------------------------------------------- //
78 // Local Specialization Stack
79 //
80 // Implementation of the RAII helper for creating new local
81 // specializations.
local_specialization_stack(lss_policy policy)82 local_specialization_stack::local_specialization_stack (lss_policy policy)
83   : saved (local_specializations)
84 {
85   if (policy == lss_blank || !saved)
86     local_specializations = new hash_map<tree, tree>;
87   else
88     local_specializations = new hash_map<tree, tree>(*saved);
89 }
90 
~local_specialization_stack()91 local_specialization_stack::~local_specialization_stack ()
92 {
93   delete local_specializations;
94   local_specializations = saved;
95 }
96 
97 /* True if we've recursed into fn_type_unification too many times.  */
98 static bool excessive_deduction_depth;
99 
100 struct GTY((for_user)) spec_entry
101 {
102   tree tmpl;
103   tree args;
104   tree spec;
105 };
106 
107 struct spec_hasher : ggc_ptr_hash<spec_entry>
108 {
109   static hashval_t hash (spec_entry *);
110   static bool equal (spec_entry *, spec_entry *);
111 };
112 
113 static GTY (()) hash_table<spec_hasher> *decl_specializations;
114 
115 static GTY (()) hash_table<spec_hasher> *type_specializations;
116 
117 /* Contains canonical template parameter types. The vector is indexed by
118    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
119    TREE_LIST, whose TREE_VALUEs contain the canonical template
120    parameters of various types and levels.  */
121 static GTY(()) vec<tree, va_gc> *canonical_template_parms;
122 
123 #define UNIFY_ALLOW_NONE 0
124 #define UNIFY_ALLOW_MORE_CV_QUAL 1
125 #define UNIFY_ALLOW_LESS_CV_QUAL 2
126 #define UNIFY_ALLOW_DERIVED 4
127 #define UNIFY_ALLOW_INTEGER 8
128 #define UNIFY_ALLOW_OUTER_LEVEL 16
129 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
130 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
131 
132 enum template_base_result {
133   tbr_incomplete_type,
134   tbr_ambiguous_baseclass,
135   tbr_success
136 };
137 
138 static void push_access_scope (tree);
139 static void pop_access_scope (tree);
140 static bool resolve_overloaded_unification (tree, tree, tree, tree,
141 					    unification_kind_t, int,
142 					    bool);
143 static int try_one_overload (tree, tree, tree, tree, tree,
144 			     unification_kind_t, int, bool, bool);
145 static int unify (tree, tree, tree, tree, int, bool);
146 static void add_pending_template (tree);
147 static tree reopen_tinst_level (struct tinst_level *);
148 static tree tsubst_initializer_list (tree, tree);
149 static tree get_partial_spec_bindings (tree, tree, tree);
150 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
151 				   bool, bool);
152 static tree coerce_innermost_template_parms (tree, tree, tree, tsubst_flags_t,
153 					      bool, bool);
154 static void tsubst_enum	(tree, tree, tree);
155 static tree add_to_template_args (tree, tree);
156 static tree add_outermost_template_args (tree, tree);
157 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
158 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
159 					     tree);
160 static int type_unification_real (tree, tree, tree, const tree *,
161 				  unsigned int, int, unification_kind_t, int,
162 				  vec<deferred_access_check, va_gc> **,
163 				  bool);
164 static void note_template_header (int);
165 static tree convert_nontype_argument_function (tree, tree, tsubst_flags_t);
166 static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
167 static tree convert_template_argument (tree, tree, tree,
168 				       tsubst_flags_t, int, tree);
169 static tree for_each_template_parm (tree, tree_fn_t, void*,
170 				    hash_set<tree> *, bool, tree_fn_t = NULL);
171 static tree expand_template_argument_pack (tree);
172 static tree build_template_parm_index (int, int, int, tree, tree);
173 static bool inline_needs_template_parms (tree, bool);
174 static void push_inline_template_parms_recursive (tree, int);
175 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
176 static int mark_template_parm (tree, void *);
177 static int template_parm_this_level_p (tree, void *);
178 static tree tsubst_friend_function (tree, tree);
179 static tree tsubst_friend_class (tree, tree);
180 static int can_complete_type_without_circularity (tree);
181 static tree get_bindings (tree, tree, tree, bool);
182 static int template_decl_level (tree);
183 static int check_cv_quals_for_unify (int, tree, tree);
184 static void template_parm_level_and_index (tree, int*, int*);
185 static int unify_pack_expansion (tree, tree, tree,
186 				 tree, unification_kind_t, bool, bool);
187 static tree copy_template_args (tree);
188 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
189 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
190 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
191 static tree most_specialized_partial_spec (tree, tsubst_flags_t);
192 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
193 static tree tsubst_arg_types (tree, tree, tree, tsubst_flags_t, tree);
194 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
195 static bool check_specialization_scope (void);
196 static tree process_partial_specialization (tree);
197 static void set_current_access_from_decl (tree);
198 static enum template_base_result get_template_base (tree, tree, tree, tree,
199 						    bool , tree *);
200 static tree try_class_unification (tree, tree, tree, tree, bool);
201 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
202 					   tree, tree);
203 static bool template_template_parm_bindings_ok_p (tree, tree);
204 static void tsubst_default_arguments (tree, tsubst_flags_t);
205 static tree for_each_template_parm_r (tree *, int *, void *);
206 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
207 static void copy_default_args_to_explicit_spec (tree);
208 static bool invalid_nontype_parm_type_p (tree, tsubst_flags_t);
209 static bool dependent_template_arg_p (tree);
210 static bool any_template_arguments_need_structural_equality_p (tree);
211 static bool dependent_type_p_r (tree);
212 static tree tsubst_copy	(tree, tree, tsubst_flags_t, tree);
213 static tree tsubst_decl (tree, tree, tsubst_flags_t);
214 static void perform_typedefs_access_check (tree tmpl, tree targs);
215 static void append_type_to_template_for_access_check_1 (tree, tree, tree,
216 							location_t);
217 static tree listify (tree);
218 static tree listify_autos (tree, tree);
219 static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
220 static tree instantiate_alias_template (tree, tree, tsubst_flags_t);
221 static bool complex_alias_template_p (const_tree tmpl);
222 static tree tsubst_attributes (tree, tree, tsubst_flags_t, tree);
223 static tree canonicalize_expr_argument (tree, tsubst_flags_t);
224 static tree make_argument_pack (tree);
225 static void register_parameter_specializations (tree, tree);
226 static tree enclosing_instantiation_of (tree tctx);
227 
228 /* Make the current scope suitable for access checking when we are
229    processing T.  T can be FUNCTION_DECL for instantiated function
230    template, VAR_DECL for static member variable, or TYPE_DECL for
231    alias template (needed by instantiate_decl).  */
232 
233 static void
push_access_scope(tree t)234 push_access_scope (tree t)
235 {
236   gcc_assert (VAR_OR_FUNCTION_DECL_P (t)
237 	      || TREE_CODE (t) == TYPE_DECL);
238 
239   if (DECL_FRIEND_CONTEXT (t))
240     push_nested_class (DECL_FRIEND_CONTEXT (t));
241   else if (DECL_CLASS_SCOPE_P (t))
242     push_nested_class (DECL_CONTEXT (t));
243   else
244     push_to_top_level ();
245 
246   if (TREE_CODE (t) == FUNCTION_DECL)
247     {
248       saved_access_scope = tree_cons
249 	(NULL_TREE, current_function_decl, saved_access_scope);
250       current_function_decl = t;
251     }
252 }
253 
254 /* Restore the scope set up by push_access_scope.  T is the node we
255    are processing.  */
256 
257 static void
pop_access_scope(tree t)258 pop_access_scope (tree t)
259 {
260   if (TREE_CODE (t) == FUNCTION_DECL)
261     {
262       current_function_decl = TREE_VALUE (saved_access_scope);
263       saved_access_scope = TREE_CHAIN (saved_access_scope);
264     }
265 
266   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
267     pop_nested_class ();
268   else
269     pop_from_top_level ();
270 }
271 
272 /* Do any processing required when DECL (a member template
273    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
274    to DECL, unless it is a specialization, in which case the DECL
275    itself is returned.  */
276 
277 tree
finish_member_template_decl(tree decl)278 finish_member_template_decl (tree decl)
279 {
280   if (decl == error_mark_node)
281     return error_mark_node;
282 
283   gcc_assert (DECL_P (decl));
284 
285   if (TREE_CODE (decl) == TYPE_DECL)
286     {
287       tree type;
288 
289       type = TREE_TYPE (decl);
290       if (type == error_mark_node)
291 	return error_mark_node;
292       if (MAYBE_CLASS_TYPE_P (type)
293 	  && CLASSTYPE_TEMPLATE_INFO (type)
294 	  && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
295 	{
296 	  tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
297 	  check_member_template (tmpl);
298 	  return tmpl;
299 	}
300       return NULL_TREE;
301     }
302   else if (TREE_CODE (decl) == FIELD_DECL)
303     error ("data member %qD cannot be a member template", decl);
304   else if (DECL_TEMPLATE_INFO (decl))
305     {
306       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
307 	{
308 	  check_member_template (DECL_TI_TEMPLATE (decl));
309 	  return DECL_TI_TEMPLATE (decl);
310 	}
311       else
312 	return decl;
313     }
314   else
315     error ("invalid member template declaration %qD", decl);
316 
317   return error_mark_node;
318 }
319 
320 /* Create a template info node.  */
321 
322 tree
build_template_info(tree template_decl,tree template_args)323 build_template_info (tree template_decl, tree template_args)
324 {
325   tree result = make_node (TEMPLATE_INFO);
326   TI_TEMPLATE (result) = template_decl;
327   TI_ARGS (result) = template_args;
328   return result;
329 }
330 
331 /* Return the template info node corresponding to T, whatever T is.  */
332 
333 tree
get_template_info(const_tree t)334 get_template_info (const_tree t)
335 {
336   tree tinfo = NULL_TREE;
337 
338   if (!t || t == error_mark_node)
339     return NULL;
340 
341   if (TREE_CODE (t) == NAMESPACE_DECL
342       || TREE_CODE (t) == PARM_DECL)
343     return NULL;
344 
345   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
346     tinfo = DECL_TEMPLATE_INFO (t);
347 
348   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
349     t = TREE_TYPE (t);
350 
351   if (OVERLOAD_TYPE_P (t))
352     tinfo = TYPE_TEMPLATE_INFO (t);
353   else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
354     tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
355 
356   return tinfo;
357 }
358 
359 /* Returns the template nesting level of the indicated class TYPE.
360 
361    For example, in:
362      template <class T>
363      struct A
364      {
365        template <class U>
366        struct B {};
367      };
368 
369    A<T>::B<U> has depth two, while A<T> has depth one.
370    Both A<T>::B<int> and A<int>::B<U> have depth one, if
371    they are instantiations, not specializations.
372 
373    This function is guaranteed to return 0 if passed NULL_TREE so
374    that, for example, `template_class_depth (current_class_type)' is
375    always safe.  */
376 
377 int
template_class_depth(tree type)378 template_class_depth (tree type)
379 {
380   int depth;
381 
382   for (depth = 0; type && TREE_CODE (type) != NAMESPACE_DECL; )
383     {
384       tree tinfo = get_template_info (type);
385 
386       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
387 	  && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
388 	++depth;
389 
390       if (DECL_P (type))
391 	type = CP_DECL_CONTEXT (type);
392       else if (LAMBDA_TYPE_P (type))
393 	type = LAMBDA_TYPE_EXTRA_SCOPE (type);
394       else
395 	type = CP_TYPE_CONTEXT (type);
396     }
397 
398   return depth;
399 }
400 
401 /* Subroutine of maybe_begin_member_template_processing.
402    Returns true if processing DECL needs us to push template parms.  */
403 
404 static bool
inline_needs_template_parms(tree decl,bool nsdmi)405 inline_needs_template_parms (tree decl, bool nsdmi)
406 {
407   if (!decl || (!nsdmi && ! DECL_TEMPLATE_INFO (decl)))
408     return false;
409 
410   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
411 	  > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
412 }
413 
414 /* Subroutine of maybe_begin_member_template_processing.
415    Push the template parms in PARMS, starting from LEVELS steps into the
416    chain, and ending at the beginning, since template parms are listed
417    innermost first.  */
418 
419 static void
push_inline_template_parms_recursive(tree parmlist,int levels)420 push_inline_template_parms_recursive (tree parmlist, int levels)
421 {
422   tree parms = TREE_VALUE (parmlist);
423   int i;
424 
425   if (levels > 1)
426     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
427 
428   ++processing_template_decl;
429   current_template_parms
430     = tree_cons (size_int (processing_template_decl),
431 		 parms, current_template_parms);
432   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
433 
434   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
435 	       NULL);
436   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
437     {
438       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
439 
440       if (error_operand_p (parm))
441 	continue;
442 
443       gcc_assert (DECL_P (parm));
444 
445       switch (TREE_CODE (parm))
446 	{
447 	case TYPE_DECL:
448 	case TEMPLATE_DECL:
449 	  pushdecl (parm);
450 	  break;
451 
452 	case PARM_DECL:
453 	  /* Push the CONST_DECL.  */
454 	  pushdecl (TEMPLATE_PARM_DECL (DECL_INITIAL (parm)));
455 	  break;
456 
457 	default:
458 	  gcc_unreachable ();
459 	}
460     }
461 }
462 
463 /* Restore the template parameter context for a member template, a
464    friend template defined in a class definition, or a non-template
465    member of template class.  */
466 
467 void
maybe_begin_member_template_processing(tree decl)468 maybe_begin_member_template_processing (tree decl)
469 {
470   tree parms;
471   int levels = 0;
472   bool nsdmi = TREE_CODE (decl) == FIELD_DECL;
473 
474   if (nsdmi)
475     {
476       tree ctx = DECL_CONTEXT (decl);
477       decl = (CLASSTYPE_TEMPLATE_INFO (ctx)
478 	      /* Disregard full specializations (c++/60999).  */
479 	      && uses_template_parms (ctx)
480 	      ? CLASSTYPE_TI_TEMPLATE (ctx) : NULL_TREE);
481     }
482 
483   if (inline_needs_template_parms (decl, nsdmi))
484     {
485       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
486       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
487 
488       if (DECL_TEMPLATE_SPECIALIZATION (decl))
489 	{
490 	  --levels;
491 	  parms = TREE_CHAIN (parms);
492 	}
493 
494       push_inline_template_parms_recursive (parms, levels);
495     }
496 
497   /* Remember how many levels of template parameters we pushed so that
498      we can pop them later.  */
499   inline_parm_levels.safe_push (levels);
500 }
501 
502 /* Undo the effects of maybe_begin_member_template_processing.  */
503 
504 void
maybe_end_member_template_processing(void)505 maybe_end_member_template_processing (void)
506 {
507   int i;
508   int last;
509 
510   if (inline_parm_levels.length () == 0)
511     return;
512 
513   last = inline_parm_levels.pop ();
514   for (i = 0; i < last; ++i)
515     {
516       --processing_template_decl;
517       current_template_parms = TREE_CHAIN (current_template_parms);
518       poplevel (0, 0, 0);
519     }
520 }
521 
522 /* Return a new template argument vector which contains all of ARGS,
523    but has as its innermost set of arguments the EXTRA_ARGS.  */
524 
525 static tree
add_to_template_args(tree args,tree extra_args)526 add_to_template_args (tree args, tree extra_args)
527 {
528   tree new_args;
529   int extra_depth;
530   int i;
531   int j;
532 
533   if (args == NULL_TREE || extra_args == error_mark_node)
534     return extra_args;
535 
536   extra_depth = TMPL_ARGS_DEPTH (extra_args);
537   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
538 
539   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
540     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
541 
542   for (j = 1; j <= extra_depth; ++j, ++i)
543     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
544 
545   return new_args;
546 }
547 
548 /* Like add_to_template_args, but only the outermost ARGS are added to
549    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
550    (EXTRA_ARGS) levels are added.  This function is used to combine
551    the template arguments from a partial instantiation with the
552    template arguments used to attain the full instantiation from the
553    partial instantiation.  */
554 
555 static tree
add_outermost_template_args(tree args,tree extra_args)556 add_outermost_template_args (tree args, tree extra_args)
557 {
558   tree new_args;
559 
560   /* If there are more levels of EXTRA_ARGS than there are ARGS,
561      something very fishy is going on.  */
562   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
563 
564   /* If *all* the new arguments will be the EXTRA_ARGS, just return
565      them.  */
566   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
567     return extra_args;
568 
569   /* For the moment, we make ARGS look like it contains fewer levels.  */
570   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
571 
572   new_args = add_to_template_args (args, extra_args);
573 
574   /* Now, we restore ARGS to its full dimensions.  */
575   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
576 
577   return new_args;
578 }
579 
580 /* Return the N levels of innermost template arguments from the ARGS.  */
581 
582 tree
get_innermost_template_args(tree args,int n)583 get_innermost_template_args (tree args, int n)
584 {
585   tree new_args;
586   int extra_levels;
587   int i;
588 
589   gcc_assert (n >= 0);
590 
591   /* If N is 1, just return the innermost set of template arguments.  */
592   if (n == 1)
593     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
594 
595   /* If we're not removing anything, just return the arguments we were
596      given.  */
597   extra_levels = TMPL_ARGS_DEPTH (args) - n;
598   gcc_assert (extra_levels >= 0);
599   if (extra_levels == 0)
600     return args;
601 
602   /* Make a new set of arguments, not containing the outer arguments.  */
603   new_args = make_tree_vec (n);
604   for (i = 1; i <= n; ++i)
605     SET_TMPL_ARGS_LEVEL (new_args, i,
606 			 TMPL_ARGS_LEVEL (args, i + extra_levels));
607 
608   return new_args;
609 }
610 
611 /* The inverse of get_innermost_template_args: Return all but the innermost
612    EXTRA_LEVELS levels of template arguments from the ARGS.  */
613 
614 static tree
strip_innermost_template_args(tree args,int extra_levels)615 strip_innermost_template_args (tree args, int extra_levels)
616 {
617   tree new_args;
618   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
619   int i;
620 
621   gcc_assert (n >= 0);
622 
623   /* If N is 1, just return the outermost set of template arguments.  */
624   if (n == 1)
625     return TMPL_ARGS_LEVEL (args, 1);
626 
627   /* If we're not removing anything, just return the arguments we were
628      given.  */
629   gcc_assert (extra_levels >= 0);
630   if (extra_levels == 0)
631     return args;
632 
633   /* Make a new set of arguments, not containing the inner arguments.  */
634   new_args = make_tree_vec (n);
635   for (i = 1; i <= n; ++i)
636     SET_TMPL_ARGS_LEVEL (new_args, i,
637 			 TMPL_ARGS_LEVEL (args, i));
638 
639   return new_args;
640 }
641 
642 /* We've got a template header coming up; push to a new level for storing
643    the parms.  */
644 
645 void
begin_template_parm_list(void)646 begin_template_parm_list (void)
647 {
648   /* We use a non-tag-transparent scope here, which causes pushtag to
649      put tags in this scope, rather than in the enclosing class or
650      namespace scope.  This is the right thing, since we want
651      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
652      global template class, push_template_decl handles putting the
653      TEMPLATE_DECL into top-level scope.  For a nested template class,
654      e.g.:
655 
656        template <class T> struct S1 {
657 	 template <class T> struct S2 {};
658        };
659 
660      pushtag contains special code to insert the TEMPLATE_DECL for S2
661      at the right scope.  */
662   begin_scope (sk_template_parms, NULL);
663   ++processing_template_decl;
664   ++processing_template_parmlist;
665   note_template_header (0);
666 
667   /* Add a dummy parameter level while we process the parameter list.  */
668   current_template_parms
669     = tree_cons (size_int (processing_template_decl),
670 		 make_tree_vec (0),
671 		 current_template_parms);
672 }
673 
674 /* This routine is called when a specialization is declared.  If it is
675    invalid to declare a specialization here, an error is reported and
676    false is returned, otherwise this routine will return true.  */
677 
678 static bool
check_specialization_scope(void)679 check_specialization_scope (void)
680 {
681   tree scope = current_scope ();
682 
683   /* [temp.expl.spec]
684 
685      An explicit specialization shall be declared in the namespace of
686      which the template is a member, or, for member templates, in the
687      namespace of which the enclosing class or enclosing class
688      template is a member.  An explicit specialization of a member
689      function, member class or static data member of a class template
690      shall be declared in the namespace of which the class template
691      is a member.  */
692   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
693     {
694       error ("explicit specialization in non-namespace scope %qD", scope);
695       return false;
696     }
697 
698   /* [temp.expl.spec]
699 
700      In an explicit specialization declaration for a member of a class
701      template or a member template that appears in namespace scope,
702      the member template and some of its enclosing class templates may
703      remain unspecialized, except that the declaration shall not
704      explicitly specialize a class member template if its enclosing
705      class templates are not explicitly specialized as well.  */
706   if (current_template_parms)
707     {
708       error ("enclosing class templates are not explicitly specialized");
709       return false;
710     }
711 
712   return true;
713 }
714 
715 /* We've just seen template <>.  */
716 
717 bool
begin_specialization(void)718 begin_specialization (void)
719 {
720   begin_scope (sk_template_spec, NULL);
721   note_template_header (1);
722   return check_specialization_scope ();
723 }
724 
725 /* Called at then end of processing a declaration preceded by
726    template<>.  */
727 
728 void
end_specialization(void)729 end_specialization (void)
730 {
731   finish_scope ();
732   reset_specialization ();
733 }
734 
735 /* Any template <>'s that we have seen thus far are not referring to a
736    function specialization.  */
737 
738 void
reset_specialization(void)739 reset_specialization (void)
740 {
741   processing_specialization = 0;
742   template_header_count = 0;
743 }
744 
745 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
746    it was of the form template <>.  */
747 
748 static void
note_template_header(int specialization)749 note_template_header (int specialization)
750 {
751   processing_specialization = specialization;
752   template_header_count++;
753 }
754 
755 /* We're beginning an explicit instantiation.  */
756 
757 void
begin_explicit_instantiation(void)758 begin_explicit_instantiation (void)
759 {
760   gcc_assert (!processing_explicit_instantiation);
761   processing_explicit_instantiation = true;
762 }
763 
764 
765 void
end_explicit_instantiation(void)766 end_explicit_instantiation (void)
767 {
768   gcc_assert (processing_explicit_instantiation);
769   processing_explicit_instantiation = false;
770 }
771 
772 /* An explicit specialization or partial specialization of TMPL is being
773    declared.  Check that the namespace in which the specialization is
774    occurring is permissible.  Returns false iff it is invalid to
775    specialize TMPL in the current namespace.  */
776 
777 static bool
check_specialization_namespace(tree tmpl)778 check_specialization_namespace (tree tmpl)
779 {
780   tree tpl_ns = decl_namespace_context (tmpl);
781 
782   /* [tmpl.expl.spec]
783 
784      An explicit specialization shall be declared in a namespace enclosing the
785      specialized template. An explicit specialization whose declarator-id is
786      not qualified shall be declared in the nearest enclosing namespace of the
787      template, or, if the namespace is inline (7.3.1), any namespace from its
788      enclosing namespace set.  */
789   if (current_scope() != DECL_CONTEXT (tmpl)
790       && !at_namespace_scope_p ())
791     {
792       error ("specialization of %qD must appear at namespace scope", tmpl);
793       return false;
794     }
795 
796   if (is_nested_namespace (current_namespace, tpl_ns, cxx_dialect < cxx11))
797     /* Same or enclosing namespace.  */
798     return true;
799   else
800     {
801       permerror (input_location,
802 		 "specialization of %qD in different namespace", tmpl);
803       inform (DECL_SOURCE_LOCATION (tmpl),
804 	      "  from definition of %q#D", tmpl);
805       return false;
806     }
807 }
808 
809 /* SPEC is an explicit instantiation.  Check that it is valid to
810    perform this explicit instantiation in the current namespace.  */
811 
812 static void
check_explicit_instantiation_namespace(tree spec)813 check_explicit_instantiation_namespace (tree spec)
814 {
815   tree ns;
816 
817   /* DR 275: An explicit instantiation shall appear in an enclosing
818      namespace of its template.  */
819   ns = decl_namespace_context (spec);
820   if (!is_nested_namespace (current_namespace, ns))
821     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
822 	       "(which does not enclose namespace %qD)",
823 	       spec, current_namespace, ns);
824 }
825 
826 // Returns the type of a template specialization only if that
827 // specialization needs to be defined. Otherwise (e.g., if the type has
828 // already been defined), the function returns NULL_TREE.
829 static tree
maybe_new_partial_specialization(tree type)830 maybe_new_partial_specialization (tree type)
831 {
832   // An implicit instantiation of an incomplete type implies
833   // the definition of a new class template.
834   //
835   //    template<typename T>
836   //      struct S;
837   //
838   //    template<typename T>
839   //      struct S<T*>;
840   //
841   // Here, S<T*> is an implicit instantiation of S whose type
842   // is incomplete.
843   if (CLASSTYPE_IMPLICIT_INSTANTIATION (type) && !COMPLETE_TYPE_P (type))
844     return type;
845 
846   // It can also be the case that TYPE is a completed specialization.
847   // Continuing the previous example, suppose we also declare:
848   //
849   //    template<typename T>
850   //      requires Integral<T>
851   //        struct S<T*>;
852   //
853   // Here, S<T*> refers to the specialization S<T*> defined
854   // above. However, we need to differentiate definitions because
855   // we intend to define a new partial specialization. In this case,
856   // we rely on the fact that the constraints are different for
857   // this declaration than that above.
858   //
859   // Note that we also get here for injected class names and
860   // late-parsed template definitions. We must ensure that we
861   // do not create new type declarations for those cases.
862   if (flag_concepts && CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
863     {
864       tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
865       tree args = CLASSTYPE_TI_ARGS (type);
866 
867       // If there are no template parameters, this cannot be a new
868       // partial template specializtion?
869       if (!current_template_parms)
870         return NULL_TREE;
871 
872       // The injected-class-name is not a new partial specialization.
873       if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
874 	return NULL_TREE;
875 
876       // If the constraints are not the same as those of the primary
877       // then, we can probably create a new specialization.
878       tree type_constr = current_template_constraints ();
879 
880       if (type == TREE_TYPE (tmpl))
881 	{
882 	  tree main_constr = get_constraints (tmpl);
883 	  if (equivalent_constraints (type_constr, main_constr))
884 	    return NULL_TREE;
885 	}
886 
887       // Also, if there's a pre-existing specialization with matching
888       // constraints, then this also isn't new.
889       tree specs = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
890       while (specs)
891         {
892           tree spec_tmpl = TREE_VALUE (specs);
893           tree spec_args = TREE_PURPOSE (specs);
894           tree spec_constr = get_constraints (spec_tmpl);
895           if (comp_template_args (args, spec_args)
896 	      && equivalent_constraints (type_constr, spec_constr))
897             return NULL_TREE;
898           specs = TREE_CHAIN (specs);
899         }
900 
901       // Create a new type node (and corresponding type decl)
902       // for the newly declared specialization.
903       tree t = make_class_type (TREE_CODE (type));
904       CLASSTYPE_DECLARED_CLASS (t) = CLASSTYPE_DECLARED_CLASS (type);
905       SET_TYPE_TEMPLATE_INFO (t, build_template_info (tmpl, args));
906 
907       /* We only need a separate type node for storing the definition of this
908 	 partial specialization; uses of S<T*> are unconstrained, so all are
909 	 equivalent.  So keep TYPE_CANONICAL the same.  */
910       TYPE_CANONICAL (t) = TYPE_CANONICAL (type);
911 
912       // Build the corresponding type decl.
913       tree d = create_implicit_typedef (DECL_NAME (tmpl), t);
914       DECL_CONTEXT (d) = TYPE_CONTEXT (t);
915       DECL_SOURCE_LOCATION (d) = input_location;
916 
917       return t;
918     }
919 
920   return NULL_TREE;
921 }
922 
923 /* The TYPE is being declared.  If it is a template type, that means it
924    is a partial specialization.  Do appropriate error-checking.  */
925 
926 tree
maybe_process_partial_specialization(tree type)927 maybe_process_partial_specialization (tree type)
928 {
929   tree context;
930 
931   if (type == error_mark_node)
932     return error_mark_node;
933 
934   /* A lambda that appears in specialization context is not itself a
935      specialization.  */
936   if (CLASS_TYPE_P (type) && CLASSTYPE_LAMBDA_EXPR (type))
937     return type;
938 
939   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
940     {
941       error ("name of class shadows template template parameter %qD",
942 	     TYPE_NAME (type));
943       return error_mark_node;
944     }
945 
946   context = TYPE_CONTEXT (type);
947 
948   if (TYPE_ALIAS_P (type))
949     {
950       tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (type);
951 
952       if (tinfo && DECL_ALIAS_TEMPLATE_P (TI_TEMPLATE (tinfo)))
953 	error ("specialization of alias template %qD",
954 	       TI_TEMPLATE (tinfo));
955       else
956 	error ("explicit specialization of non-template %qT", type);
957       return error_mark_node;
958     }
959   else if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
960     {
961       /* This is for ordinary explicit specialization and partial
962 	 specialization of a template class such as:
963 
964 	   template <> class C<int>;
965 
966 	 or:
967 
968 	   template <class T> class C<T*>;
969 
970 	 Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
971 
972       if (tree t = maybe_new_partial_specialization (type))
973 	{
974 	  if (!check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (t))
975 	      && !at_namespace_scope_p ())
976 	    return error_mark_node;
977 	  SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (t);
978 	  DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (t)) = input_location;
979 	  if (processing_template_decl)
980 	    {
981 	      tree decl = push_template_decl (TYPE_MAIN_DECL (t));
982 	      if (decl == error_mark_node)
983 		return error_mark_node;
984 	      return TREE_TYPE (decl);
985 	    }
986 	}
987       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
988 	error ("specialization of %qT after instantiation", type);
989       else if (errorcount && !processing_specialization
990 	        && CLASSTYPE_TEMPLATE_SPECIALIZATION (type)
991 	       && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
992 	/* Trying to define a specialization either without a template<> header
993 	   or in an inappropriate place.  We've already given an error, so just
994 	   bail now so we don't actually define the specialization.  */
995 	return error_mark_node;
996     }
997   else if (CLASS_TYPE_P (type)
998 	   && !CLASSTYPE_USE_TEMPLATE (type)
999 	   && CLASSTYPE_TEMPLATE_INFO (type)
1000 	   && context && CLASS_TYPE_P (context)
1001 	   && CLASSTYPE_TEMPLATE_INFO (context))
1002     {
1003       /* This is for an explicit specialization of member class
1004 	 template according to [temp.expl.spec/18]:
1005 
1006 	   template <> template <class U> class C<int>::D;
1007 
1008 	 The context `C<int>' must be an implicit instantiation.
1009 	 Otherwise this is just a member class template declared
1010 	 earlier like:
1011 
1012 	   template <> class C<int> { template <class U> class D; };
1013 	   template <> template <class U> class C<int>::D;
1014 
1015 	 In the first case, `C<int>::D' is a specialization of `C<T>::D'
1016 	 while in the second case, `C<int>::D' is a primary template
1017 	 and `C<T>::D' may not exist.  */
1018 
1019       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
1020 	  && !COMPLETE_TYPE_P (type))
1021 	{
1022 	  tree t;
1023 	  tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
1024 
1025 	  if (current_namespace
1026 	      != decl_namespace_context (tmpl))
1027 	    {
1028 	      permerror (input_location,
1029 			 "specializing %q#T in different namespace", type);
1030 	      permerror (DECL_SOURCE_LOCATION (tmpl),
1031 			 "  from definition of %q#D", tmpl);
1032 	    }
1033 
1034 	  /* Check for invalid specialization after instantiation:
1035 
1036 	       template <> template <> class C<int>::D<int>;
1037 	       template <> template <class U> class C<int>::D;  */
1038 
1039 	  for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
1040 	       t; t = TREE_CHAIN (t))
1041 	    {
1042 	      tree inst = TREE_VALUE (t);
1043 	      if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst)
1044 		  || !COMPLETE_OR_OPEN_TYPE_P (inst))
1045 		{
1046 		  /* We already have a full specialization of this partial
1047 		     instantiation, or a full specialization has been
1048 		     looked up but not instantiated.  Reassign it to the
1049 		     new member specialization template.  */
1050 		  spec_entry elt;
1051 		  spec_entry *entry;
1052 
1053 		  elt.tmpl = most_general_template (tmpl);
1054 		  elt.args = CLASSTYPE_TI_ARGS (inst);
1055 		  elt.spec = inst;
1056 
1057 		  type_specializations->remove_elt (&elt);
1058 
1059 		  elt.tmpl = tmpl;
1060 		  elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
1061 
1062 		  spec_entry **slot
1063 		    = type_specializations->find_slot (&elt, INSERT);
1064 		  entry = ggc_alloc<spec_entry> ();
1065 		  *entry = elt;
1066 		  *slot = entry;
1067 		}
1068 	      else
1069 		/* But if we've had an implicit instantiation, that's a
1070 		   problem ([temp.expl.spec]/6).  */
1071 		error ("specialization %qT after instantiation %qT",
1072 		       type, inst);
1073 	    }
1074 
1075 	  /* Mark TYPE as a specialization.  And as a result, we only
1076 	     have one level of template argument for the innermost
1077 	     class template.  */
1078 	  SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
1079 	  DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
1080 	  CLASSTYPE_TI_ARGS (type)
1081 	    = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
1082 	}
1083     }
1084   else if (processing_specialization)
1085     {
1086        /* Someday C++0x may allow for enum template specialization.  */
1087       if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
1088 	  && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
1089 	pedwarn (input_location, OPT_Wpedantic, "template specialization "
1090 		 "of %qD not allowed by ISO C++", type);
1091       else
1092 	{
1093 	  error ("explicit specialization of non-template %qT", type);
1094 	  return error_mark_node;
1095 	}
1096     }
1097 
1098   return type;
1099 }
1100 
1101 /* Returns nonzero if we can optimize the retrieval of specializations
1102    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
1103    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
1104 
1105 static inline bool
optimize_specialization_lookup_p(tree tmpl)1106 optimize_specialization_lookup_p (tree tmpl)
1107 {
1108   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
1109 	  && DECL_CLASS_SCOPE_P (tmpl)
1110 	  /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
1111 	     parameter.  */
1112 	  && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
1113 	  /* The optimized lookup depends on the fact that the
1114 	     template arguments for the member function template apply
1115 	     purely to the containing class, which is not true if the
1116 	     containing class is an explicit or partial
1117 	     specialization.  */
1118 	  && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
1119 	  && !DECL_MEMBER_TEMPLATE_P (tmpl)
1120 	  && !DECL_CONV_FN_P (tmpl)
1121 	  /* It is possible to have a template that is not a member
1122 	     template and is not a member of a template class:
1123 
1124 	     template <typename T>
1125 	     struct S { friend A::f(); };
1126 
1127 	     Here, the friend function is a template, but the context does
1128 	     not have template information.  The optimized lookup relies
1129 	     on having ARGS be the template arguments for both the class
1130 	     and the function template.  */
1131 	  && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
1132 }
1133 
1134 /* Make sure ARGS doesn't use any inappropriate typedefs; we should have
1135    gone through coerce_template_parms by now.  */
1136 
1137 static void
verify_unstripped_args_1(tree inner)1138 verify_unstripped_args_1 (tree inner)
1139 {
1140   for (int i = 0; i < TREE_VEC_LENGTH (inner); ++i)
1141     {
1142       tree arg = TREE_VEC_ELT (inner, i);
1143       if (TREE_CODE (arg) == TEMPLATE_DECL)
1144 	/* OK */;
1145       else if (TYPE_P (arg))
1146 	gcc_assert (strip_typedefs (arg, NULL) == arg);
1147       else if (ARGUMENT_PACK_P (arg))
1148 	verify_unstripped_args_1 (ARGUMENT_PACK_ARGS (arg));
1149       else if (strip_typedefs (TREE_TYPE (arg), NULL) != TREE_TYPE (arg))
1150 	/* Allow typedefs on the type of a non-type argument, since a
1151 	   parameter can have them.  */;
1152       else
1153 	gcc_assert (strip_typedefs_expr (arg, NULL) == arg);
1154     }
1155 }
1156 
1157 static void
verify_unstripped_args(tree args)1158 verify_unstripped_args (tree args)
1159 {
1160   ++processing_template_decl;
1161   if (!any_dependent_template_arguments_p (args))
1162     verify_unstripped_args_1 (INNERMOST_TEMPLATE_ARGS (args));
1163   --processing_template_decl;
1164 }
1165 
1166 /* Retrieve the specialization (in the sense of [temp.spec] - a
1167    specialization is either an instantiation or an explicit
1168    specialization) of TMPL for the given template ARGS.  If there is
1169    no such specialization, return NULL_TREE.  The ARGS are a vector of
1170    arguments, or a vector of vectors of arguments, in the case of
1171    templates with more than one level of parameters.
1172 
1173    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
1174    then we search for a partial specialization matching ARGS.  This
1175    parameter is ignored if TMPL is not a class template.
1176 
1177    We can also look up a FIELD_DECL, if it is a lambda capture pack; the
1178    result is a NONTYPE_ARGUMENT_PACK.  */
1179 
1180 static tree
retrieve_specialization(tree tmpl,tree args,hashval_t hash)1181 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
1182 {
1183   if (tmpl == NULL_TREE)
1184     return NULL_TREE;
1185 
1186   if (args == error_mark_node)
1187     return NULL_TREE;
1188 
1189   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL
1190 	      || TREE_CODE (tmpl) == FIELD_DECL);
1191 
1192   /* There should be as many levels of arguments as there are
1193      levels of parameters.  */
1194   gcc_assert (TMPL_ARGS_DEPTH (args)
1195 	      == (TREE_CODE (tmpl) == TEMPLATE_DECL
1196 		  ? TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl))
1197 		  : template_class_depth (DECL_CONTEXT (tmpl))));
1198 
1199   if (flag_checking)
1200     verify_unstripped_args (args);
1201 
1202   /* Lambda functions in templates aren't instantiated normally, but through
1203      tsubst_lambda_expr.  */
1204   if (lambda_fn_in_template_p (tmpl))
1205     return NULL_TREE;
1206 
1207   if (optimize_specialization_lookup_p (tmpl))
1208     {
1209       /* The template arguments actually apply to the containing
1210 	 class.  Find the class specialization with those
1211 	 arguments.  */
1212       tree class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
1213       tree class_specialization
1214 	= retrieve_specialization (class_template, args, 0);
1215       if (!class_specialization)
1216 	return NULL_TREE;
1217 
1218       /* Find the instance of TMPL.  */
1219       tree fns = get_class_binding (class_specialization, DECL_NAME (tmpl));
1220       for (ovl_iterator iter (fns); iter; ++iter)
1221 	{
1222 	  tree fn = *iter;
1223 	  if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl
1224 	      /* using-declarations can add base methods to the method vec,
1225 		 and we don't want those here.  */
1226 	      && DECL_CONTEXT (fn) == class_specialization)
1227 	    return fn;
1228 	}
1229       return NULL_TREE;
1230     }
1231   else
1232     {
1233       spec_entry *found;
1234       spec_entry elt;
1235       hash_table<spec_hasher> *specializations;
1236 
1237       elt.tmpl = tmpl;
1238       elt.args = args;
1239       elt.spec = NULL_TREE;
1240 
1241       if (DECL_CLASS_TEMPLATE_P (tmpl))
1242 	specializations = type_specializations;
1243       else
1244 	specializations = decl_specializations;
1245 
1246       if (hash == 0)
1247 	hash = spec_hasher::hash (&elt);
1248       found = specializations->find_with_hash (&elt, hash);
1249       if (found)
1250 	return found->spec;
1251     }
1252 
1253   return NULL_TREE;
1254 }
1255 
1256 /* Like retrieve_specialization, but for local declarations.  */
1257 
1258 tree
retrieve_local_specialization(tree tmpl)1259 retrieve_local_specialization (tree tmpl)
1260 {
1261   if (local_specializations == NULL)
1262     return NULL_TREE;
1263 
1264   tree *slot = local_specializations->get (tmpl);
1265   return slot ? *slot : NULL_TREE;
1266 }
1267 
1268 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1269 
1270 int
is_specialization_of(tree decl,tree tmpl)1271 is_specialization_of (tree decl, tree tmpl)
1272 {
1273   tree t;
1274 
1275   if (TREE_CODE (decl) == FUNCTION_DECL)
1276     {
1277       for (t = decl;
1278 	   t != NULL_TREE;
1279 	   t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1280 	if (t == tmpl)
1281 	  return 1;
1282     }
1283   else
1284     {
1285       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1286 
1287       for (t = TREE_TYPE (decl);
1288 	   t != NULL_TREE;
1289 	   t = CLASSTYPE_USE_TEMPLATE (t)
1290 	     ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1291 	if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1292 	  return 1;
1293     }
1294 
1295   return 0;
1296 }
1297 
1298 /* Returns nonzero iff DECL is a specialization of friend declaration
1299    FRIEND_DECL according to [temp.friend].  */
1300 
1301 bool
is_specialization_of_friend(tree decl,tree friend_decl)1302 is_specialization_of_friend (tree decl, tree friend_decl)
1303 {
1304   bool need_template = true;
1305   int template_depth;
1306 
1307   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1308 	      || TREE_CODE (decl) == TYPE_DECL);
1309 
1310   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1311      of a template class, we want to check if DECL is a specialization
1312      if this.  */
1313   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1314       && DECL_TEMPLATE_INFO (friend_decl)
1315       && !DECL_USE_TEMPLATE (friend_decl))
1316     {
1317       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1318       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1319       need_template = false;
1320     }
1321   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1322 	   && !PRIMARY_TEMPLATE_P (friend_decl))
1323     need_template = false;
1324 
1325   /* There is nothing to do if this is not a template friend.  */
1326   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1327     return false;
1328 
1329   if (is_specialization_of (decl, friend_decl))
1330     return true;
1331 
1332   /* [temp.friend/6]
1333      A member of a class template may be declared to be a friend of a
1334      non-template class.  In this case, the corresponding member of
1335      every specialization of the class template is a friend of the
1336      class granting friendship.
1337 
1338      For example, given a template friend declaration
1339 
1340        template <class T> friend void A<T>::f();
1341 
1342      the member function below is considered a friend
1343 
1344        template <> struct A<int> {
1345 	 void f();
1346        };
1347 
1348      For this type of template friend, TEMPLATE_DEPTH below will be
1349      nonzero.  To determine if DECL is a friend of FRIEND, we first
1350      check if the enclosing class is a specialization of another.  */
1351 
1352   template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1353   if (template_depth
1354       && DECL_CLASS_SCOPE_P (decl)
1355       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1356 			       CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1357     {
1358       /* Next, we check the members themselves.  In order to handle
1359 	 a few tricky cases, such as when FRIEND_DECL's are
1360 
1361 	   template <class T> friend void A<T>::g(T t);
1362 	   template <class T> template <T t> friend void A<T>::h();
1363 
1364 	 and DECL's are
1365 
1366 	   void A<int>::g(int);
1367 	   template <int> void A<int>::h();
1368 
1369 	 we need to figure out ARGS, the template arguments from
1370 	 the context of DECL.  This is required for template substitution
1371 	 of `T' in the function parameter of `g' and template parameter
1372 	 of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1373 
1374       tree context = DECL_CONTEXT (decl);
1375       tree args = NULL_TREE;
1376       int current_depth = 0;
1377 
1378       while (current_depth < template_depth)
1379 	{
1380 	  if (CLASSTYPE_TEMPLATE_INFO (context))
1381 	    {
1382 	      if (current_depth == 0)
1383 		args = TYPE_TI_ARGS (context);
1384 	      else
1385 		args = add_to_template_args (TYPE_TI_ARGS (context), args);
1386 	      current_depth++;
1387 	    }
1388 	  context = TYPE_CONTEXT (context);
1389 	}
1390 
1391       if (TREE_CODE (decl) == FUNCTION_DECL)
1392 	{
1393 	  bool is_template;
1394 	  tree friend_type;
1395 	  tree decl_type;
1396 	  tree friend_args_type;
1397 	  tree decl_args_type;
1398 
1399 	  /* Make sure that both DECL and FRIEND_DECL are templates or
1400 	     non-templates.  */
1401 	  is_template = DECL_TEMPLATE_INFO (decl)
1402 			&& PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1403 	  if (need_template ^ is_template)
1404 	    return false;
1405 	  else if (is_template)
1406 	    {
1407 	      /* If both are templates, check template parameter list.  */
1408 	      tree friend_parms
1409 		= tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1410 					 args, tf_none);
1411 	      if (!comp_template_parms
1412 		     (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1413 		      friend_parms))
1414 		return false;
1415 
1416 	      decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1417 	    }
1418 	  else
1419 	    decl_type = TREE_TYPE (decl);
1420 
1421 	  friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1422 					      tf_none, NULL_TREE);
1423 	  if (friend_type == error_mark_node)
1424 	    return false;
1425 
1426 	  /* Check if return types match.  */
1427 	  if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1428 	    return false;
1429 
1430 	  /* Check if function parameter types match, ignoring the
1431 	     `this' parameter.  */
1432 	  friend_args_type = TYPE_ARG_TYPES (friend_type);
1433 	  decl_args_type = TYPE_ARG_TYPES (decl_type);
1434 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1435 	    friend_args_type = TREE_CHAIN (friend_args_type);
1436 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1437 	    decl_args_type = TREE_CHAIN (decl_args_type);
1438 
1439 	  return compparms (decl_args_type, friend_args_type);
1440 	}
1441       else
1442 	{
1443 	  /* DECL is a TYPE_DECL */
1444 	  bool is_template;
1445 	  tree decl_type = TREE_TYPE (decl);
1446 
1447 	  /* Make sure that both DECL and FRIEND_DECL are templates or
1448 	     non-templates.  */
1449 	  is_template
1450 	    = CLASSTYPE_TEMPLATE_INFO (decl_type)
1451 	      && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1452 
1453 	  if (need_template ^ is_template)
1454 	    return false;
1455 	  else if (is_template)
1456 	    {
1457 	      tree friend_parms;
1458 	      /* If both are templates, check the name of the two
1459 		 TEMPLATE_DECL's first because is_friend didn't.  */
1460 	      if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1461 		  != DECL_NAME (friend_decl))
1462 		return false;
1463 
1464 	      /* Now check template parameter list.  */
1465 	      friend_parms
1466 		= tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1467 					 args, tf_none);
1468 	      return comp_template_parms
1469 		(DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1470 		 friend_parms);
1471 	    }
1472 	  else
1473 	    return (DECL_NAME (decl)
1474 		    == DECL_NAME (friend_decl));
1475 	}
1476     }
1477   return false;
1478 }
1479 
1480 /* Register the specialization SPEC as a specialization of TMPL with
1481    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1482    is actually just a friend declaration.  ATTRLIST is the list of
1483    attributes that the specialization is declared with or NULL when
1484    it isn't.  Returns SPEC, or an equivalent prior declaration, if
1485    available.
1486 
1487    We also store instantiations of field packs in the hash table, even
1488    though they are not themselves templates, to make lookup easier.  */
1489 
1490 static tree
register_specialization(tree spec,tree tmpl,tree args,bool is_friend,hashval_t hash)1491 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1492 			 hashval_t hash)
1493 {
1494   tree fn;
1495   spec_entry **slot = NULL;
1496   spec_entry elt;
1497 
1498   gcc_assert ((TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec))
1499 	      || (TREE_CODE (tmpl) == FIELD_DECL
1500 		  && TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK));
1501 
1502   if (TREE_CODE (spec) == FUNCTION_DECL
1503       && uses_template_parms (DECL_TI_ARGS (spec)))
1504     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1505        register it; we want the corresponding TEMPLATE_DECL instead.
1506        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1507        the more obvious `uses_template_parms (spec)' to avoid problems
1508        with default function arguments.  In particular, given
1509        something like this:
1510 
1511 	  template <class T> void f(T t1, T t = T())
1512 
1513        the default argument expression is not substituted for in an
1514        instantiation unless and until it is actually needed.  */
1515     return spec;
1516 
1517   if (optimize_specialization_lookup_p (tmpl))
1518     /* We don't put these specializations in the hash table, but we might
1519        want to give an error about a mismatch.  */
1520     fn = retrieve_specialization (tmpl, args, 0);
1521   else
1522     {
1523       elt.tmpl = tmpl;
1524       elt.args = args;
1525       elt.spec = spec;
1526 
1527       if (hash == 0)
1528 	hash = spec_hasher::hash (&elt);
1529 
1530       slot =
1531 	decl_specializations->find_slot_with_hash (&elt, hash, INSERT);
1532       if (*slot)
1533 	fn = ((spec_entry *) *slot)->spec;
1534       else
1535 	fn = NULL_TREE;
1536     }
1537 
1538   /* We can sometimes try to re-register a specialization that we've
1539      already got.  In particular, regenerate_decl_from_template calls
1540      duplicate_decls which will update the specialization list.  But,
1541      we'll still get called again here anyhow.  It's more convenient
1542      to simply allow this than to try to prevent it.  */
1543   if (fn == spec)
1544     return spec;
1545   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1546     {
1547       if (DECL_TEMPLATE_INSTANTIATION (fn))
1548 	{
1549 	  if (DECL_ODR_USED (fn)
1550 	      || DECL_EXPLICIT_INSTANTIATION (fn))
1551 	    {
1552 	      error ("specialization of %qD after instantiation",
1553 		     fn);
1554 	      return error_mark_node;
1555 	    }
1556 	  else
1557 	    {
1558 	      tree clone;
1559 	      /* This situation should occur only if the first
1560 		 specialization is an implicit instantiation, the
1561 		 second is an explicit specialization, and the
1562 		 implicit instantiation has not yet been used.  That
1563 		 situation can occur if we have implicitly
1564 		 instantiated a member function and then specialized
1565 		 it later.
1566 
1567 		 We can also wind up here if a friend declaration that
1568 		 looked like an instantiation turns out to be a
1569 		 specialization:
1570 
1571 		   template <class T> void foo(T);
1572 		   class S { friend void foo<>(int) };
1573 		   template <> void foo(int);
1574 
1575 		 We transform the existing DECL in place so that any
1576 		 pointers to it become pointers to the updated
1577 		 declaration.
1578 
1579 		 If there was a definition for the template, but not
1580 		 for the specialization, we want this to look as if
1581 		 there were no definition, and vice versa.  */
1582 	      DECL_INITIAL (fn) = NULL_TREE;
1583 	      duplicate_decls (spec, fn, is_friend);
1584 	      /* The call to duplicate_decls will have applied
1585 		 [temp.expl.spec]:
1586 
1587 		   An explicit specialization of a function template
1588 		   is inline only if it is explicitly declared to be,
1589 		   and independently of whether its function template
1590 		   is.
1591 
1592 		to the primary function; now copy the inline bits to
1593 		the various clones.  */
1594 	      FOR_EACH_CLONE (clone, fn)
1595 		{
1596 		  DECL_DECLARED_INLINE_P (clone)
1597 		    = DECL_DECLARED_INLINE_P (fn);
1598 		  DECL_SOURCE_LOCATION (clone)
1599 		    = DECL_SOURCE_LOCATION (fn);
1600 		  DECL_DELETED_FN (clone)
1601 		    = DECL_DELETED_FN (fn);
1602 		}
1603 	      check_specialization_namespace (tmpl);
1604 
1605 	      return fn;
1606 	    }
1607 	}
1608       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1609 	{
1610 	  tree dd = duplicate_decls (spec, fn, is_friend);
1611 	  if (dd == error_mark_node)
1612 	    /* We've already complained in duplicate_decls.  */
1613 	    return error_mark_node;
1614 
1615 	  if (dd == NULL_TREE && DECL_INITIAL (spec))
1616 	    /* Dup decl failed, but this is a new definition. Set the
1617 	       line number so any errors match this new
1618 	       definition.  */
1619 	    DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1620 
1621 	  return fn;
1622 	}
1623     }
1624   else if (fn)
1625     return duplicate_decls (spec, fn, is_friend);
1626 
1627   /* A specialization must be declared in the same namespace as the
1628      template it is specializing.  */
1629   if (DECL_P (spec) && DECL_TEMPLATE_SPECIALIZATION (spec)
1630       && !check_specialization_namespace (tmpl))
1631     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1632 
1633   if (slot != NULL /* !optimize_specialization_lookup_p (tmpl) */)
1634     {
1635       spec_entry *entry = ggc_alloc<spec_entry> ();
1636       gcc_assert (tmpl && args && spec);
1637       *entry = elt;
1638       *slot = entry;
1639       if ((TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1640 	   && PRIMARY_TEMPLATE_P (tmpl)
1641 	   && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1642 	  || variable_template_p (tmpl))
1643 	/* If TMPL is a forward declaration of a template function, keep a list
1644 	   of all specializations in case we need to reassign them to a friend
1645 	   template later in tsubst_friend_function.
1646 
1647 	   Also keep a list of all variable template instantiations so that
1648 	   process_partial_specialization can check whether a later partial
1649 	   specialization would have used it.  */
1650 	DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1651 	  = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1652     }
1653 
1654   return spec;
1655 }
1656 
1657 /* Returns true iff two spec_entry nodes are equivalent.  */
1658 
1659 int comparing_specializations;
1660 
1661 bool
equal(spec_entry * e1,spec_entry * e2)1662 spec_hasher::equal (spec_entry *e1, spec_entry *e2)
1663 {
1664   int equal;
1665 
1666   ++comparing_specializations;
1667   equal = (e1->tmpl == e2->tmpl
1668 	   && comp_template_args (e1->args, e2->args));
1669   if (equal && flag_concepts
1670       /* tmpl could be a FIELD_DECL for a capture pack.  */
1671       && TREE_CODE (e1->tmpl) == TEMPLATE_DECL
1672       && VAR_P (DECL_TEMPLATE_RESULT (e1->tmpl))
1673       && uses_template_parms (e1->args))
1674     {
1675       /* Partial specializations of a variable template can be distinguished by
1676 	 constraints.  */
1677       tree c1 = e1->spec ? get_constraints (e1->spec) : NULL_TREE;
1678       tree c2 = e2->spec ? get_constraints (e2->spec) : NULL_TREE;
1679       equal = equivalent_constraints (c1, c2);
1680     }
1681   --comparing_specializations;
1682 
1683   return equal;
1684 }
1685 
1686 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1687 
1688 static hashval_t
hash_tmpl_and_args(tree tmpl,tree args)1689 hash_tmpl_and_args (tree tmpl, tree args)
1690 {
1691   hashval_t val = iterative_hash_object (DECL_UID (tmpl), 0);
1692   return iterative_hash_template_arg (args, val);
1693 }
1694 
1695 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1696    ignoring SPEC.  */
1697 
1698 hashval_t
hash(spec_entry * e)1699 spec_hasher::hash (spec_entry *e)
1700 {
1701   return hash_tmpl_and_args (e->tmpl, e->args);
1702 }
1703 
1704 /* Recursively calculate a hash value for a template argument ARG, for use
1705    in the hash tables of template specializations.  */
1706 
1707 hashval_t
iterative_hash_template_arg(tree arg,hashval_t val)1708 iterative_hash_template_arg (tree arg, hashval_t val)
1709 {
1710   unsigned HOST_WIDE_INT i;
1711   enum tree_code code;
1712   char tclass;
1713 
1714   if (arg == NULL_TREE)
1715     return iterative_hash_object (arg, val);
1716 
1717   if (!TYPE_P (arg))
1718     STRIP_NOPS (arg);
1719 
1720   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
1721     gcc_unreachable ();
1722 
1723   code = TREE_CODE (arg);
1724   tclass = TREE_CODE_CLASS (code);
1725 
1726   val = iterative_hash_object (code, val);
1727 
1728   switch (code)
1729     {
1730     case ERROR_MARK:
1731       return val;
1732 
1733     case IDENTIFIER_NODE:
1734       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1735 
1736     case TREE_VEC:
1737       {
1738 	int i, len = TREE_VEC_LENGTH (arg);
1739 	for (i = 0; i < len; ++i)
1740 	  val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1741 	return val;
1742       }
1743 
1744     case TYPE_PACK_EXPANSION:
1745     case EXPR_PACK_EXPANSION:
1746       val = iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1747       return iterative_hash_template_arg (PACK_EXPANSION_EXTRA_ARGS (arg), val);
1748 
1749     case TYPE_ARGUMENT_PACK:
1750     case NONTYPE_ARGUMENT_PACK:
1751       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1752 
1753     case TREE_LIST:
1754       for (; arg; arg = TREE_CHAIN (arg))
1755 	val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1756       return val;
1757 
1758     case OVERLOAD:
1759       for (lkp_iterator iter (arg); iter; ++iter)
1760 	val = iterative_hash_template_arg (*iter, val);
1761       return val;
1762 
1763     case CONSTRUCTOR:
1764       {
1765 	tree field, value;
1766 	iterative_hash_template_arg (TREE_TYPE (arg), val);
1767 	FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1768 	  {
1769 	    val = iterative_hash_template_arg (field, val);
1770 	    val = iterative_hash_template_arg (value, val);
1771 	  }
1772 	return val;
1773       }
1774 
1775     case PARM_DECL:
1776       if (!DECL_ARTIFICIAL (arg))
1777 	{
1778 	  val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1779 	  val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
1780 	}
1781       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1782 
1783     case TARGET_EXPR:
1784       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1785 
1786     case PTRMEM_CST:
1787       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1788       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1789 
1790     case TEMPLATE_PARM_INDEX:
1791       val = iterative_hash_template_arg
1792 	(TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1793       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1794       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1795 
1796     case TRAIT_EXPR:
1797       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1798       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1799       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1800 
1801     case BASELINK:
1802       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1803 					 val);
1804       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1805 					  val);
1806 
1807     case MODOP_EXPR:
1808       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1809       code = TREE_CODE (TREE_OPERAND (arg, 1));
1810       val = iterative_hash_object (code, val);
1811       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1812 
1813     case LAMBDA_EXPR:
1814       /* A lambda can't appear in a template arg, but don't crash on
1815 	 erroneous input.  */
1816       gcc_assert (seen_error ());
1817       return val;
1818 
1819     case CAST_EXPR:
1820     case IMPLICIT_CONV_EXPR:
1821     case STATIC_CAST_EXPR:
1822     case REINTERPRET_CAST_EXPR:
1823     case CONST_CAST_EXPR:
1824     case DYNAMIC_CAST_EXPR:
1825     case NEW_EXPR:
1826       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1827       /* Now hash operands as usual.  */
1828       break;
1829 
1830     default:
1831       break;
1832     }
1833 
1834   switch (tclass)
1835     {
1836     case tcc_type:
1837       if (alias_template_specialization_p (arg))
1838 	{
1839 	  // We want an alias specialization that survived strip_typedefs
1840 	  // to hash differently from its TYPE_CANONICAL, to avoid hash
1841 	  // collisions that compare as different in template_args_equal.
1842 	  // These could be dependent specializations that strip_typedefs
1843 	  // left alone, or untouched specializations because
1844 	  // coerce_template_parms returns the unconverted template
1845 	  // arguments if it sees incomplete argument packs.
1846 	  tree ti = TYPE_ALIAS_TEMPLATE_INFO (arg);
1847 	  return hash_tmpl_and_args (TI_TEMPLATE (ti), TI_ARGS (ti));
1848 	}
1849       if (TYPE_CANONICAL (arg))
1850 	return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1851 				      val);
1852       else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1853 	return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1854       /* Otherwise just compare the types during lookup.  */
1855       return val;
1856 
1857     case tcc_declaration:
1858     case tcc_constant:
1859       return iterative_hash_expr (arg, val);
1860 
1861     default:
1862       gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1863       {
1864 	unsigned n = cp_tree_operand_length (arg);
1865 	for (i = 0; i < n; ++i)
1866 	  val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1867 	return val;
1868       }
1869     }
1870   gcc_unreachable ();
1871   return 0;
1872 }
1873 
1874 /* Unregister the specialization SPEC as a specialization of TMPL.
1875    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1876    if the SPEC was listed as a specialization of TMPL.
1877 
1878    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1879 
1880 bool
reregister_specialization(tree spec,tree tinfo,tree new_spec)1881 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1882 {
1883   spec_entry *entry;
1884   spec_entry elt;
1885 
1886   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1887   elt.args = TI_ARGS (tinfo);
1888   elt.spec = NULL_TREE;
1889 
1890   entry = decl_specializations->find (&elt);
1891   if (entry != NULL)
1892     {
1893       gcc_assert (entry->spec == spec || entry->spec == new_spec);
1894       gcc_assert (new_spec != NULL_TREE);
1895       entry->spec = new_spec;
1896       return 1;
1897     }
1898 
1899   return 0;
1900 }
1901 
1902 /* Like register_specialization, but for local declarations.  We are
1903    registering SPEC, an instantiation of TMPL.  */
1904 
1905 void
register_local_specialization(tree spec,tree tmpl)1906 register_local_specialization (tree spec, tree tmpl)
1907 {
1908   gcc_assert (tmpl != spec);
1909   local_specializations->put (tmpl, spec);
1910 }
1911 
1912 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1913    specialized class.  */
1914 
1915 bool
explicit_class_specialization_p(tree type)1916 explicit_class_specialization_p (tree type)
1917 {
1918   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1919     return false;
1920   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1921 }
1922 
1923 /* Print the list of functions at FNS, going through all the overloads
1924    for each element of the list.  Alternatively, FNS can not be a
1925    TREE_LIST, in which case it will be printed together with all the
1926    overloads.
1927 
1928    MORE and *STR should respectively be FALSE and NULL when the function
1929    is called from the outside.  They are used internally on recursive
1930    calls.  print_candidates manages the two parameters and leaves NULL
1931    in *STR when it ends.  */
1932 
1933 static void
1934 print_candidates_1 (tree fns, char **str, bool more = false)
1935 {
1936   if (TREE_CODE (fns) == TREE_LIST)
1937     for (; fns; fns = TREE_CHAIN (fns))
1938       print_candidates_1 (TREE_VALUE (fns), str, more || TREE_CHAIN (fns));
1939   else
1940     for (lkp_iterator iter (fns); iter;)
1941       {
1942 	tree cand = *iter;
1943 	++iter;
1944 
1945 	const char *pfx = *str;
1946 	if (!pfx)
1947 	  {
1948 	    if (more || iter)
1949 	      pfx = _("candidates are:");
1950 	    else
1951 	      pfx = _("candidate is:");
1952 	    *str = get_spaces (pfx);
1953 	  }
1954 	inform (DECL_SOURCE_LOCATION (cand), "%s %#qD", pfx, cand);
1955       }
1956 }
1957 
1958 /* Print the list of candidate FNS in an error message.  FNS can also
1959    be a TREE_LIST of non-functions in the case of an ambiguous lookup.  */
1960 
1961 void
print_candidates(tree fns)1962 print_candidates (tree fns)
1963 {
1964   char *str = NULL;
1965   print_candidates_1 (fns, &str);
1966   free (str);
1967 }
1968 
1969 /* Get a (possibly) constrained template declaration for the
1970    purpose of ordering candidates.  */
1971 static tree
get_template_for_ordering(tree list)1972 get_template_for_ordering (tree list)
1973 {
1974   gcc_assert (TREE_CODE (list) == TREE_LIST);
1975   tree f = TREE_VALUE (list);
1976   if (tree ti = DECL_TEMPLATE_INFO (f))
1977     return TI_TEMPLATE (ti);
1978   return f;
1979 }
1980 
1981 /* Among candidates having the same signature, return the
1982    most constrained or NULL_TREE if there is no best candidate.
1983    If the signatures of candidates vary (e.g., template
1984    specialization vs. member function), then there can be no
1985    most constrained.
1986 
1987    Note that we don't compare constraints on the functions
1988    themselves, but rather those of their templates. */
1989 static tree
most_constrained_function(tree candidates)1990 most_constrained_function (tree candidates)
1991 {
1992   // Try to find the best candidate in a first pass.
1993   tree champ = candidates;
1994   for (tree c = TREE_CHAIN (champ); c; c = TREE_CHAIN (c))
1995     {
1996       int winner = more_constrained (get_template_for_ordering (champ),
1997                                      get_template_for_ordering (c));
1998       if (winner == -1)
1999         champ = c; // The candidate is more constrained
2000       else if (winner == 0)
2001         return NULL_TREE; // Neither is more constrained
2002     }
2003 
2004   // Verify that the champ is better than previous candidates.
2005   for (tree c = candidates; c != champ; c = TREE_CHAIN (c)) {
2006     if (!more_constrained (get_template_for_ordering (champ),
2007                            get_template_for_ordering (c)))
2008       return NULL_TREE;
2009   }
2010 
2011   return champ;
2012 }
2013 
2014 
2015 /* Returns the template (one of the functions given by TEMPLATE_ID)
2016    which can be specialized to match the indicated DECL with the
2017    explicit template args given in TEMPLATE_ID.  The DECL may be
2018    NULL_TREE if none is available.  In that case, the functions in
2019    TEMPLATE_ID are non-members.
2020 
2021    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
2022    specialization of a member template.
2023 
2024    The TEMPLATE_COUNT is the number of references to qualifying
2025    template classes that appeared in the name of the function. See
2026    check_explicit_specialization for a more accurate description.
2027 
2028    TSK indicates what kind of template declaration (if any) is being
2029    declared.  TSK_TEMPLATE indicates that the declaration given by
2030    DECL, though a FUNCTION_DECL, has template parameters, and is
2031    therefore a template function.
2032 
2033    The template args (those explicitly specified and those deduced)
2034    are output in a newly created vector *TARGS_OUT.
2035 
2036    If it is impossible to determine the result, an error message is
2037    issued.  The error_mark_node is returned to indicate failure.  */
2038 
2039 static tree
determine_specialization(tree template_id,tree decl,tree * targs_out,int need_member_template,int template_count,tmpl_spec_kind tsk)2040 determine_specialization (tree template_id,
2041 			  tree decl,
2042 			  tree* targs_out,
2043 			  int need_member_template,
2044 			  int template_count,
2045 			  tmpl_spec_kind tsk)
2046 {
2047   tree fns;
2048   tree targs;
2049   tree explicit_targs;
2050   tree candidates = NULL_TREE;
2051 
2052   /* A TREE_LIST of templates of which DECL may be a specialization.
2053      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
2054      corresponding TREE_PURPOSE is the set of template arguments that,
2055      when used to instantiate the template, would produce a function
2056      with the signature of DECL.  */
2057   tree templates = NULL_TREE;
2058   int header_count;
2059   cp_binding_level *b;
2060 
2061   *targs_out = NULL_TREE;
2062 
2063   if (template_id == error_mark_node || decl == error_mark_node)
2064     return error_mark_node;
2065 
2066   /* We shouldn't be specializing a member template of an
2067      unspecialized class template; we already gave an error in
2068      check_specialization_scope, now avoid crashing.  */
2069   if (!VAR_P (decl)
2070       && template_count && DECL_CLASS_SCOPE_P (decl)
2071       && template_class_depth (DECL_CONTEXT (decl)) > 0)
2072     {
2073       gcc_assert (errorcount);
2074       return error_mark_node;
2075     }
2076 
2077   fns = TREE_OPERAND (template_id, 0);
2078   explicit_targs = TREE_OPERAND (template_id, 1);
2079 
2080   if (fns == error_mark_node)
2081     return error_mark_node;
2082 
2083   /* Check for baselinks.  */
2084   if (BASELINK_P (fns))
2085     fns = BASELINK_FUNCTIONS (fns);
2086 
2087   if (TREE_CODE (decl) == FUNCTION_DECL && !is_overloaded_fn (fns))
2088     {
2089       error ("%qD is not a function template", fns);
2090       return error_mark_node;
2091     }
2092   else if (VAR_P (decl) && !variable_template_p (fns))
2093     {
2094       error ("%qD is not a variable template", fns);
2095       return error_mark_node;
2096     }
2097 
2098   /* Count the number of template headers specified for this
2099      specialization.  */
2100   header_count = 0;
2101   for (b = current_binding_level;
2102        b->kind == sk_template_parms;
2103        b = b->level_chain)
2104     ++header_count;
2105 
2106   tree orig_fns = fns;
2107 
2108   if (variable_template_p (fns))
2109     {
2110       tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (fns));
2111       targs = coerce_template_parms (parms, explicit_targs, fns,
2112 				     tf_warning_or_error,
2113 				     /*req_all*/true, /*use_defarg*/true);
2114       if (targs != error_mark_node)
2115         templates = tree_cons (targs, fns, templates);
2116     }
2117   else for (lkp_iterator iter (fns); iter; ++iter)
2118     {
2119       tree fn = *iter;
2120 
2121       if (TREE_CODE (fn) == TEMPLATE_DECL)
2122 	{
2123 	  tree decl_arg_types;
2124 	  tree fn_arg_types;
2125 	  tree insttype;
2126 
2127 	  /* In case of explicit specialization, we need to check if
2128 	     the number of template headers appearing in the specialization
2129 	     is correct. This is usually done in check_explicit_specialization,
2130 	     but the check done there cannot be exhaustive when specializing
2131 	     member functions. Consider the following code:
2132 
2133 	     template <> void A<int>::f(int);
2134 	     template <> template <> void A<int>::f(int);
2135 
2136 	     Assuming that A<int> is not itself an explicit specialization
2137 	     already, the first line specializes "f" which is a non-template
2138 	     member function, whilst the second line specializes "f" which
2139 	     is a template member function. So both lines are syntactically
2140 	     correct, and check_explicit_specialization does not reject
2141 	     them.
2142 
2143 	     Here, we can do better, as we are matching the specialization
2144 	     against the declarations. We count the number of template
2145 	     headers, and we check if they match TEMPLATE_COUNT + 1
2146 	     (TEMPLATE_COUNT is the number of qualifying template classes,
2147 	     plus there must be another header for the member template
2148 	     itself).
2149 
2150 	     Notice that if header_count is zero, this is not a
2151 	     specialization but rather a template instantiation, so there
2152 	     is no check we can perform here.  */
2153 	  if (header_count && header_count != template_count + 1)
2154 	    continue;
2155 
2156 	  /* Check that the number of template arguments at the
2157 	     innermost level for DECL is the same as for FN.  */
2158 	  if (current_binding_level->kind == sk_template_parms
2159 	      && !current_binding_level->explicit_spec_p
2160 	      && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
2161 		  != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
2162 				      (current_template_parms))))
2163 	    continue;
2164 
2165 	  /* DECL might be a specialization of FN.  */
2166 	  decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2167 	  fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
2168 
2169 	  /* For a non-static member function, we need to make sure
2170 	     that the const qualification is the same.  Since
2171 	     get_bindings does not try to merge the "this" parameter,
2172 	     we must do the comparison explicitly.  */
2173 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
2174 	    {
2175 	      if (!same_type_p (TREE_VALUE (fn_arg_types),
2176 				TREE_VALUE (decl_arg_types)))
2177 		continue;
2178 
2179 	      /* And the ref-qualification.  */
2180 	      if (type_memfn_rqual (TREE_TYPE (decl))
2181 		  != type_memfn_rqual (TREE_TYPE (fn)))
2182 		continue;
2183 	    }
2184 
2185 	  /* Skip the "this" parameter and, for constructors of
2186 	     classes with virtual bases, the VTT parameter.  A
2187 	     full specialization of a constructor will have a VTT
2188 	     parameter, but a template never will.  */
2189 	  decl_arg_types
2190 	    = skip_artificial_parms_for (decl, decl_arg_types);
2191 	  fn_arg_types
2192 	    = skip_artificial_parms_for (fn, fn_arg_types);
2193 
2194 	  /* Function templates cannot be specializations; there are
2195 	     no partial specializations of functions.  Therefore, if
2196 	     the type of DECL does not match FN, there is no
2197 	     match.
2198 
2199              Note that it should never be the case that we have both
2200              candidates added here, and for regular member functions
2201              below. */
2202 	  if (tsk == tsk_template)
2203 	    {
2204 	      if (compparms (fn_arg_types, decl_arg_types))
2205 		candidates = tree_cons (NULL_TREE, fn, candidates);
2206 	      continue;
2207 	    }
2208 
2209 	  /* See whether this function might be a specialization of this
2210 	     template.  Suppress access control because we might be trying
2211 	     to make this specialization a friend, and we have already done
2212 	     access control for the declaration of the specialization.  */
2213 	  push_deferring_access_checks (dk_no_check);
2214 	  targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
2215 	  pop_deferring_access_checks ();
2216 
2217 	  if (!targs)
2218 	    /* We cannot deduce template arguments that when used to
2219 	       specialize TMPL will produce DECL.  */
2220 	    continue;
2221 
2222 	  if (uses_template_parms (targs))
2223 	    /* We deduced something involving 'auto', which isn't a valid
2224 	       template argument.  */
2225 	    continue;
2226 
2227           /* Remove, from the set of candidates, all those functions
2228              whose constraints are not satisfied. */
2229           if (flag_concepts && !constraints_satisfied_p (fn, targs))
2230             continue;
2231 
2232           // Then, try to form the new function type.
2233 	  insttype = tsubst (TREE_TYPE (fn), targs, tf_fndecl_type, NULL_TREE);
2234 	  if (insttype == error_mark_node)
2235 	    continue;
2236 	  fn_arg_types
2237 	    = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (insttype));
2238 	  if (!compparms (fn_arg_types, decl_arg_types))
2239 	    continue;
2240 
2241 	  /* Save this template, and the arguments deduced.  */
2242 	  templates = tree_cons (targs, fn, templates);
2243 	}
2244       else if (need_member_template)
2245 	/* FN is an ordinary member function, and we need a
2246 	   specialization of a member template.  */
2247 	;
2248       else if (TREE_CODE (fn) != FUNCTION_DECL)
2249 	/* We can get IDENTIFIER_NODEs here in certain erroneous
2250 	   cases.  */
2251 	;
2252       else if (!DECL_FUNCTION_MEMBER_P (fn))
2253 	/* This is just an ordinary non-member function.  Nothing can
2254 	   be a specialization of that.  */
2255 	;
2256       else if (DECL_ARTIFICIAL (fn))
2257 	/* Cannot specialize functions that are created implicitly.  */
2258 	;
2259       else
2260 	{
2261 	  tree decl_arg_types;
2262 
2263 	  /* This is an ordinary member function.  However, since
2264 	     we're here, we can assume its enclosing class is a
2265 	     template class.  For example,
2266 
2267 	       template <typename T> struct S { void f(); };
2268 	       template <> void S<int>::f() {}
2269 
2270 	     Here, S<int>::f is a non-template, but S<int> is a
2271 	     template class.  If FN has the same type as DECL, we
2272 	     might be in business.  */
2273 
2274 	  if (!DECL_TEMPLATE_INFO (fn))
2275 	    /* Its enclosing class is an explicit specialization
2276 	       of a template class.  This is not a candidate.  */
2277 	    continue;
2278 
2279 	  if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2280 			    TREE_TYPE (TREE_TYPE (fn))))
2281 	    /* The return types differ.  */
2282 	    continue;
2283 
2284 	  /* Adjust the type of DECL in case FN is a static member.  */
2285 	  decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2286 	  if (DECL_STATIC_FUNCTION_P (fn)
2287 	      && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2288 	    decl_arg_types = TREE_CHAIN (decl_arg_types);
2289 
2290 	  if (!compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
2291 			 decl_arg_types))
2292             continue;
2293 
2294 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
2295 	      && (type_memfn_rqual (TREE_TYPE (decl))
2296 		  != type_memfn_rqual (TREE_TYPE (fn))))
2297 	    continue;
2298 
2299           // If the deduced arguments do not satisfy the constraints,
2300           // this is not a candidate.
2301           if (flag_concepts && !constraints_satisfied_p (fn))
2302             continue;
2303 
2304           // Add the candidate.
2305           candidates = tree_cons (NULL_TREE, fn, candidates);
2306 	}
2307     }
2308 
2309   if (templates && TREE_CHAIN (templates))
2310     {
2311       /* We have:
2312 
2313 	   [temp.expl.spec]
2314 
2315 	   It is possible for a specialization with a given function
2316 	   signature to be instantiated from more than one function
2317 	   template.  In such cases, explicit specification of the
2318 	   template arguments must be used to uniquely identify the
2319 	   function template specialization being specialized.
2320 
2321 	 Note that here, there's no suggestion that we're supposed to
2322 	 determine which of the candidate templates is most
2323 	 specialized.  However, we, also have:
2324 
2325 	   [temp.func.order]
2326 
2327 	   Partial ordering of overloaded function template
2328 	   declarations is used in the following contexts to select
2329 	   the function template to which a function template
2330 	   specialization refers:
2331 
2332 	   -- when an explicit specialization refers to a function
2333 	      template.
2334 
2335 	 So, we do use the partial ordering rules, at least for now.
2336 	 This extension can only serve to make invalid programs valid,
2337 	 so it's safe.  And, there is strong anecdotal evidence that
2338 	 the committee intended the partial ordering rules to apply;
2339 	 the EDG front end has that behavior, and John Spicer claims
2340 	 that the committee simply forgot to delete the wording in
2341 	 [temp.expl.spec].  */
2342       tree tmpl = most_specialized_instantiation (templates);
2343       if (tmpl != error_mark_node)
2344 	{
2345 	  templates = tmpl;
2346 	  TREE_CHAIN (templates) = NULL_TREE;
2347 	}
2348     }
2349 
2350   // Concepts allows multiple declarations of member functions
2351   // with the same signature. Like above, we need to rely on
2352   // on the partial ordering of those candidates to determine which
2353   // is the best.
2354   if (flag_concepts && candidates && TREE_CHAIN (candidates))
2355     {
2356       if (tree cand = most_constrained_function (candidates))
2357         {
2358           candidates = cand;
2359           TREE_CHAIN (cand) = NULL_TREE;
2360         }
2361     }
2362 
2363   if (templates == NULL_TREE && candidates == NULL_TREE)
2364     {
2365       error ("template-id %qD for %q+D does not match any template "
2366 	     "declaration", template_id, decl);
2367       if (header_count && header_count != template_count + 1)
2368 	inform (input_location, "saw %d %<template<>%>, need %d for "
2369 		"specializing a member function template",
2370 		header_count, template_count + 1);
2371       else
2372 	print_candidates (orig_fns);
2373       return error_mark_node;
2374     }
2375   else if ((templates && TREE_CHAIN (templates))
2376 	   || (candidates && TREE_CHAIN (candidates))
2377 	   || (templates && candidates))
2378     {
2379       error ("ambiguous template specialization %qD for %q+D",
2380 	     template_id, decl);
2381       candidates = chainon (candidates, templates);
2382       print_candidates (candidates);
2383       return error_mark_node;
2384     }
2385 
2386   /* We have one, and exactly one, match.  */
2387   if (candidates)
2388     {
2389       tree fn = TREE_VALUE (candidates);
2390       *targs_out = copy_node (DECL_TI_ARGS (fn));
2391 
2392       // Propagate the candidate's constraints to the declaration.
2393       set_constraints (decl, get_constraints (fn));
2394 
2395       /* DECL is a re-declaration or partial instantiation of a template
2396 	 function.  */
2397       if (TREE_CODE (fn) == TEMPLATE_DECL)
2398 	return fn;
2399       /* It was a specialization of an ordinary member function in a
2400 	 template class.  */
2401       return DECL_TI_TEMPLATE (fn);
2402     }
2403 
2404   /* It was a specialization of a template.  */
2405   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2406   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2407     {
2408       *targs_out = copy_node (targs);
2409       SET_TMPL_ARGS_LEVEL (*targs_out,
2410 			   TMPL_ARGS_DEPTH (*targs_out),
2411 			   TREE_PURPOSE (templates));
2412     }
2413   else
2414     *targs_out = TREE_PURPOSE (templates);
2415   return TREE_VALUE (templates);
2416 }
2417 
2418 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2419    but with the default argument values filled in from those in the
2420    TMPL_TYPES.  */
2421 
2422 static tree
copy_default_args_to_explicit_spec_1(tree spec_types,tree tmpl_types)2423 copy_default_args_to_explicit_spec_1 (tree spec_types,
2424 				      tree tmpl_types)
2425 {
2426   tree new_spec_types;
2427 
2428   if (!spec_types)
2429     return NULL_TREE;
2430 
2431   if (spec_types == void_list_node)
2432     return void_list_node;
2433 
2434   /* Substitute into the rest of the list.  */
2435   new_spec_types =
2436     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2437 					  TREE_CHAIN (tmpl_types));
2438 
2439   /* Add the default argument for this parameter.  */
2440   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2441 			 TREE_VALUE (spec_types),
2442 			 new_spec_types);
2443 }
2444 
2445 /* DECL is an explicit specialization.  Replicate default arguments
2446    from the template it specializes.  (That way, code like:
2447 
2448      template <class T> void f(T = 3);
2449      template <> void f(double);
2450      void g () { f (); }
2451 
2452    works, as required.)  An alternative approach would be to look up
2453    the correct default arguments at the call-site, but this approach
2454    is consistent with how implicit instantiations are handled.  */
2455 
2456 static void
copy_default_args_to_explicit_spec(tree decl)2457 copy_default_args_to_explicit_spec (tree decl)
2458 {
2459   tree tmpl;
2460   tree spec_types;
2461   tree tmpl_types;
2462   tree new_spec_types;
2463   tree old_type;
2464   tree new_type;
2465   tree t;
2466   tree object_type = NULL_TREE;
2467   tree in_charge = NULL_TREE;
2468   tree vtt = NULL_TREE;
2469 
2470   /* See if there's anything we need to do.  */
2471   tmpl = DECL_TI_TEMPLATE (decl);
2472   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2473   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2474     if (TREE_PURPOSE (t))
2475       break;
2476   if (!t)
2477     return;
2478 
2479   old_type = TREE_TYPE (decl);
2480   spec_types = TYPE_ARG_TYPES (old_type);
2481 
2482   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2483     {
2484       /* Remove the this pointer, but remember the object's type for
2485 	 CV quals.  */
2486       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2487       spec_types = TREE_CHAIN (spec_types);
2488       tmpl_types = TREE_CHAIN (tmpl_types);
2489 
2490       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2491 	{
2492 	  /* DECL may contain more parameters than TMPL due to the extra
2493 	     in-charge parameter in constructors and destructors.  */
2494 	  in_charge = spec_types;
2495 	  spec_types = TREE_CHAIN (spec_types);
2496 	}
2497       if (DECL_HAS_VTT_PARM_P (decl))
2498 	{
2499 	  vtt = spec_types;
2500 	  spec_types = TREE_CHAIN (spec_types);
2501 	}
2502     }
2503 
2504   /* Compute the merged default arguments.  */
2505   new_spec_types =
2506     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2507 
2508   /* Compute the new FUNCTION_TYPE.  */
2509   if (object_type)
2510     {
2511       if (vtt)
2512 	new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2513 					 TREE_VALUE (vtt),
2514 					 new_spec_types);
2515 
2516       if (in_charge)
2517 	/* Put the in-charge parameter back.  */
2518 	new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2519 					 TREE_VALUE (in_charge),
2520 					 new_spec_types);
2521 
2522       new_type = build_method_type_directly (object_type,
2523 					     TREE_TYPE (old_type),
2524 					     new_spec_types);
2525     }
2526   else
2527     new_type = build_function_type (TREE_TYPE (old_type),
2528 				    new_spec_types);
2529   new_type = cp_build_type_attribute_variant (new_type,
2530 					      TYPE_ATTRIBUTES (old_type));
2531   new_type = build_exception_variant (new_type,
2532 				      TYPE_RAISES_EXCEPTIONS (old_type));
2533 
2534   if (TYPE_HAS_LATE_RETURN_TYPE (old_type))
2535     TYPE_HAS_LATE_RETURN_TYPE (new_type) = 1;
2536 
2537   TREE_TYPE (decl) = new_type;
2538 }
2539 
2540 /* Return the number of template headers we expect to see for a definition
2541    or specialization of CTYPE or one of its non-template members.  */
2542 
2543 int
num_template_headers_for_class(tree ctype)2544 num_template_headers_for_class (tree ctype)
2545 {
2546   int num_templates = 0;
2547 
2548   while (ctype && CLASS_TYPE_P (ctype))
2549     {
2550       /* You're supposed to have one `template <...>' for every
2551 	 template class, but you don't need one for a full
2552 	 specialization.  For example:
2553 
2554 	 template <class T> struct S{};
2555 	 template <> struct S<int> { void f(); };
2556 	 void S<int>::f () {}
2557 
2558 	 is correct; there shouldn't be a `template <>' for the
2559 	 definition of `S<int>::f'.  */
2560       if (!CLASSTYPE_TEMPLATE_INFO (ctype))
2561 	/* If CTYPE does not have template information of any
2562 	   kind,  then it is not a template, nor is it nested
2563 	   within a template.  */
2564 	break;
2565       if (explicit_class_specialization_p (ctype))
2566 	break;
2567       if (PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (ctype)))
2568 	++num_templates;
2569 
2570       ctype = TYPE_CONTEXT (ctype);
2571     }
2572 
2573   return num_templates;
2574 }
2575 
2576 /* Do a simple sanity check on the template headers that precede the
2577    variable declaration DECL.  */
2578 
2579 void
check_template_variable(tree decl)2580 check_template_variable (tree decl)
2581 {
2582   tree ctx = CP_DECL_CONTEXT (decl);
2583   int wanted = num_template_headers_for_class (ctx);
2584   if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)
2585       && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl)))
2586     {
2587       if (cxx_dialect < cxx14)
2588         pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2589                  "variable templates only available with "
2590                  "-std=c++14 or -std=gnu++14");
2591 
2592       // Namespace-scope variable templates should have a template header.
2593       ++wanted;
2594     }
2595   if (template_header_count > wanted)
2596     {
2597       bool warned = pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2598 			     "too many template headers for %qD "
2599 	                     "(should be %d)",
2600 			     decl, wanted);
2601       if (warned && CLASS_TYPE_P (ctx)
2602 	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (ctx))
2603 	inform (DECL_SOURCE_LOCATION (decl),
2604 		"members of an explicitly specialized class are defined "
2605 		"without a template header");
2606     }
2607 }
2608 
2609 /* An explicit specialization whose declarator-id or class-head-name is not
2610    qualified shall be declared in the nearest enclosing namespace of the
2611    template, or, if the namespace is inline (7.3.1), any namespace from its
2612    enclosing namespace set.
2613 
2614    If the name declared in the explicit instantiation is an unqualified name,
2615    the explicit instantiation shall appear in the namespace where its template
2616    is declared or, if that namespace is inline (7.3.1), any namespace from its
2617    enclosing namespace set.  */
2618 
2619 void
check_unqualified_spec_or_inst(tree t,location_t loc)2620 check_unqualified_spec_or_inst (tree t, location_t loc)
2621 {
2622   tree tmpl = most_general_template (t);
2623   if (DECL_NAMESPACE_SCOPE_P (tmpl)
2624       && !is_nested_namespace (current_namespace,
2625 			       CP_DECL_CONTEXT (tmpl), true))
2626     {
2627       if (processing_specialization)
2628 	permerror (loc, "explicit specialization of %qD outside its "
2629 		   "namespace must use a nested-name-specifier", tmpl);
2630       else if (processing_explicit_instantiation
2631 	       && cxx_dialect >= cxx11)
2632 	/* This was allowed in C++98, so only pedwarn.  */
2633 	pedwarn (loc, OPT_Wpedantic, "explicit instantiation of %qD "
2634 		 "outside its namespace must use a nested-name-"
2635 		 "specifier", tmpl);
2636     }
2637 }
2638 
2639 /* Warn for a template specialization SPEC that is missing some of a set
2640    of function or type attributes that the template TEMPL is declared with.
2641    ATTRLIST is a list of additional attributes that SPEC should be taken
2642    to ultimately be declared with.  */
2643 
2644 static void
warn_spec_missing_attributes(tree tmpl,tree spec,tree attrlist)2645 warn_spec_missing_attributes (tree tmpl, tree spec, tree attrlist)
2646 {
2647   if (DECL_FUNCTION_TEMPLATE_P (tmpl))
2648     tmpl = DECL_TEMPLATE_RESULT (tmpl);
2649 
2650   if (TREE_CODE (tmpl) != FUNCTION_DECL)
2651     return;
2652 
2653   /* Avoid warning if either declaration or its type is deprecated.  */
2654   if (TREE_DEPRECATED (tmpl)
2655       || TREE_DEPRECATED (spec))
2656     return;
2657 
2658   tree tmpl_type = TREE_TYPE (tmpl);
2659   tree spec_type = TREE_TYPE (spec);
2660 
2661   if (TREE_DEPRECATED (tmpl_type)
2662       || TREE_DEPRECATED (spec_type)
2663       || TREE_DEPRECATED (TREE_TYPE (tmpl_type))
2664       || TREE_DEPRECATED (TREE_TYPE (spec_type)))
2665     return;
2666 
2667   tree tmpl_attrs[] = { DECL_ATTRIBUTES (tmpl), TYPE_ATTRIBUTES (tmpl_type) };
2668   tree spec_attrs[] = { DECL_ATTRIBUTES (spec), TYPE_ATTRIBUTES (spec_type) };
2669 
2670   if (!spec_attrs[0])
2671     spec_attrs[0] = attrlist;
2672   else if (!spec_attrs[1])
2673     spec_attrs[1] = attrlist;
2674 
2675   /* Avoid warning if the primary has no attributes.  */
2676   if (!tmpl_attrs[0] && !tmpl_attrs[1])
2677     return;
2678 
2679   /* Avoid warning if either declaration contains an attribute on
2680      the white list below.  */
2681   const char* const whitelist[] = {
2682     "error", "warning"
2683   };
2684 
2685   for (unsigned i = 0; i != 2; ++i)
2686     for (unsigned j = 0; j != sizeof whitelist / sizeof *whitelist; ++j)
2687       if (lookup_attribute (whitelist[j], tmpl_attrs[i])
2688 	  || lookup_attribute (whitelist[j], spec_attrs[i]))
2689 	return;
2690 
2691   /* Avoid warning if the difference between the primary and
2692      the specialization is not in one of the attributes below.  */
2693   const char* const blacklist[] = {
2694     "alloc_align", "alloc_size", "assume_aligned", "format",
2695     "format_arg", "malloc", "nonnull"
2696   };
2697 
2698   /* Put together a list of the black listed attributes that the primary
2699      template is declared with that the specialization is not, in case
2700      it's not apparent from the most recent declaration of the primary.  */
2701   unsigned nattrs = 0;
2702   pretty_printer str;
2703 
2704   for (unsigned i = 0; i != sizeof blacklist / sizeof *blacklist; ++i)
2705     {
2706       for (unsigned j = 0; j != 2; ++j)
2707 	{
2708 	  if (!lookup_attribute (blacklist[i], tmpl_attrs[j]))
2709 	    continue;
2710 
2711 	  for (unsigned k = 0; k != 1 + !!spec_attrs[1]; ++k)
2712 	    {
2713 	      if (lookup_attribute (blacklist[i], spec_attrs[k]))
2714 		break;
2715 
2716 	      if (nattrs)
2717 		pp_string (&str, ", ");
2718 	      pp_begin_quote (&str, pp_show_color (global_dc->printer));
2719 	      pp_string (&str, blacklist[i]);
2720 	      pp_end_quote (&str, pp_show_color (global_dc->printer));
2721 	      ++nattrs;
2722 	    }
2723 	}
2724     }
2725 
2726   if (!nattrs)
2727     return;
2728 
2729   if (warning_at (DECL_SOURCE_LOCATION (spec), OPT_Wmissing_attributes,
2730 		  "explicit specialization %q#D may be missing attributes",
2731 		  spec))
2732     inform (DECL_SOURCE_LOCATION (tmpl),
2733 	    nattrs > 1
2734 	    ? G_("missing primary template attributes %s")
2735 	    : G_("missing primary template attribute %s"),
2736 	    pp_formatted_text (&str));
2737 }
2738 
2739 /* Check to see if the function just declared, as indicated in
2740    DECLARATOR, and in DECL, is a specialization of a function
2741    template.  We may also discover that the declaration is an explicit
2742    instantiation at this point.
2743 
2744    Returns DECL, or an equivalent declaration that should be used
2745    instead if all goes well.  Issues an error message if something is
2746    amiss.  Returns error_mark_node if the error is not easily
2747    recoverable.
2748 
2749    FLAGS is a bitmask consisting of the following flags:
2750 
2751    2: The function has a definition.
2752    4: The function is a friend.
2753 
2754    The TEMPLATE_COUNT is the number of references to qualifying
2755    template classes that appeared in the name of the function.  For
2756    example, in
2757 
2758      template <class T> struct S { void f(); };
2759      void S<int>::f();
2760 
2761    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2762    classes are not counted in the TEMPLATE_COUNT, so that in
2763 
2764      template <class T> struct S {};
2765      template <> struct S<int> { void f(); }
2766      template <> void S<int>::f();
2767 
2768    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2769    invalid; there should be no template <>.)
2770 
2771    If the function is a specialization, it is marked as such via
2772    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2773    is set up correctly, and it is added to the list of specializations
2774    for that template.  */
2775 
2776 tree
check_explicit_specialization(tree declarator,tree decl,int template_count,int flags,tree attrlist)2777 check_explicit_specialization (tree declarator,
2778 			       tree decl,
2779 			       int template_count,
2780 			       int flags,
2781 			       tree attrlist)
2782 {
2783   int have_def = flags & 2;
2784   int is_friend = flags & 4;
2785   bool is_concept = flags & 8;
2786   int specialization = 0;
2787   int explicit_instantiation = 0;
2788   int member_specialization = 0;
2789   tree ctype = DECL_CLASS_CONTEXT (decl);
2790   tree dname = DECL_NAME (decl);
2791   tmpl_spec_kind tsk;
2792 
2793   if (is_friend)
2794     {
2795       if (!processing_specialization)
2796 	tsk = tsk_none;
2797       else
2798 	tsk = tsk_excessive_parms;
2799     }
2800   else
2801     tsk = current_tmpl_spec_kind (template_count);
2802 
2803   switch (tsk)
2804     {
2805     case tsk_none:
2806       if (processing_specialization && !VAR_P (decl))
2807 	{
2808 	  specialization = 1;
2809 	  SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2810 	}
2811       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2812 	{
2813 	  if (is_friend)
2814 	    /* This could be something like:
2815 
2816 	       template <class T> void f(T);
2817 	       class S { friend void f<>(int); }  */
2818 	    specialization = 1;
2819 	  else
2820 	    {
2821 	      /* This case handles bogus declarations like template <>
2822 		 template <class T> void f<int>(); */
2823 
2824 	      error ("template-id %qD in declaration of primary template",
2825 		     declarator);
2826 	      return decl;
2827 	    }
2828 	}
2829       break;
2830 
2831     case tsk_invalid_member_spec:
2832       /* The error has already been reported in
2833 	 check_specialization_scope.  */
2834       return error_mark_node;
2835 
2836     case tsk_invalid_expl_inst:
2837       error ("template parameter list used in explicit instantiation");
2838 
2839       /* Fall through.  */
2840 
2841     case tsk_expl_inst:
2842       if (have_def)
2843 	error ("definition provided for explicit instantiation");
2844 
2845       explicit_instantiation = 1;
2846       break;
2847 
2848     case tsk_excessive_parms:
2849     case tsk_insufficient_parms:
2850       if (tsk == tsk_excessive_parms)
2851 	error ("too many template parameter lists in declaration of %qD",
2852 	       decl);
2853       else if (template_header_count)
2854 	error("too few template parameter lists in declaration of %qD", decl);
2855       else
2856 	error("explicit specialization of %qD must be introduced by "
2857 	      "%<template <>%>", decl);
2858 
2859       /* Fall through.  */
2860     case tsk_expl_spec:
2861       if (is_concept)
2862         error ("explicit specialization declared %<concept%>");
2863 
2864       if (VAR_P (decl) && TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2865 	/* In cases like template<> constexpr bool v = true;
2866 	   We'll give an error in check_template_variable.  */
2867 	break;
2868 
2869       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2870       if (ctype)
2871 	member_specialization = 1;
2872       else
2873 	specialization = 1;
2874       break;
2875 
2876     case tsk_template:
2877       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2878 	{
2879 	  /* This case handles bogus declarations like template <>
2880 	     template <class T> void f<int>(); */
2881 
2882 	  if (!uses_template_parms (declarator))
2883 	    error ("template-id %qD in declaration of primary template",
2884 		   declarator);
2885 	  else if (variable_template_p (TREE_OPERAND (declarator, 0)))
2886 	    {
2887 	      /* Partial specialization of variable template.  */
2888 	      SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2889 	      specialization = 1;
2890 	      goto ok;
2891 	    }
2892 	  else if (cxx_dialect < cxx14)
2893 	    error ("non-type partial specialization %qD "
2894 		   "is not allowed", declarator);
2895 	  else
2896 	    error ("non-class, non-variable partial specialization %qD "
2897 		   "is not allowed", declarator);
2898 	  return decl;
2899 	ok:;
2900 	}
2901 
2902       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2903 	/* This is a specialization of a member template, without
2904 	   specialization the containing class.  Something like:
2905 
2906 	     template <class T> struct S {
2907 	       template <class U> void f (U);
2908 	     };
2909 	     template <> template <class U> void S<int>::f(U) {}
2910 
2911 	   That's a specialization -- but of the entire template.  */
2912 	specialization = 1;
2913       break;
2914 
2915     default:
2916       gcc_unreachable ();
2917     }
2918 
2919   if ((specialization || member_specialization)
2920       /* This doesn't apply to variable templates.  */
2921       && (TREE_CODE (TREE_TYPE (decl)) == FUNCTION_TYPE
2922           || TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE))
2923     {
2924       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2925       for (; t; t = TREE_CHAIN (t))
2926 	if (TREE_PURPOSE (t))
2927 	  {
2928 	    permerror (input_location,
2929 		       "default argument specified in explicit specialization");
2930 	    break;
2931 	  }
2932     }
2933 
2934   if (specialization || member_specialization || explicit_instantiation)
2935     {
2936       tree tmpl = NULL_TREE;
2937       tree targs = NULL_TREE;
2938       bool was_template_id = (TREE_CODE (declarator) == TEMPLATE_ID_EXPR);
2939 
2940       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2941       if (!was_template_id)
2942 	{
2943 	  tree fns;
2944 
2945 	  gcc_assert (identifier_p (declarator));
2946 	  if (ctype)
2947 	    fns = dname;
2948 	  else
2949 	    {
2950 	      /* If there is no class context, the explicit instantiation
2951 		 must be at namespace scope.  */
2952 	      gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2953 
2954 	      /* Find the namespace binding, using the declaration
2955 		 context.  */
2956 	      fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2957 					   false, true);
2958 	      if (fns == error_mark_node)
2959 		/* If lookup fails, look for a friend declaration so we can
2960 		   give a better diagnostic.  */
2961 		fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2962 					     /*type*/false, /*complain*/true,
2963 					     /*hidden*/true);
2964 
2965 	      if (fns == error_mark_node || !is_overloaded_fn (fns))
2966 		{
2967 		  error ("%qD is not a template function", dname);
2968 		  fns = error_mark_node;
2969 		}
2970 	    }
2971 
2972 	  declarator = lookup_template_function (fns, NULL_TREE);
2973 	}
2974 
2975       if (declarator == error_mark_node)
2976 	return error_mark_node;
2977 
2978       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2979 	{
2980 	  if (!explicit_instantiation)
2981 	    /* A specialization in class scope.  This is invalid,
2982 	       but the error will already have been flagged by
2983 	       check_specialization_scope.  */
2984 	    return error_mark_node;
2985 	  else
2986 	    {
2987 	      /* It's not valid to write an explicit instantiation in
2988 		 class scope, e.g.:
2989 
2990 		   class C { template void f(); }
2991 
2992 		   This case is caught by the parser.  However, on
2993 		   something like:
2994 
2995 		   template class C { void f(); };
2996 
2997 		   (which is invalid) we can get here.  The error will be
2998 		   issued later.  */
2999 	      ;
3000 	    }
3001 
3002 	  return decl;
3003 	}
3004       else if (ctype != NULL_TREE
3005 	       && (identifier_p (TREE_OPERAND (declarator, 0))))
3006 	{
3007 	  // We'll match variable templates in start_decl.
3008 	  if (VAR_P (decl))
3009 	    return decl;
3010 
3011 	  /* Find the list of functions in ctype that have the same
3012 	     name as the declared function.  */
3013 	  tree name = TREE_OPERAND (declarator, 0);
3014 
3015 	  if (constructor_name_p (name, ctype))
3016 	    {
3017 	      if (DECL_CONSTRUCTOR_P (decl)
3018 		  ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
3019 		  : !CLASSTYPE_DESTRUCTOR (ctype))
3020 		{
3021 		  /* From [temp.expl.spec]:
3022 
3023 		     If such an explicit specialization for the member
3024 		     of a class template names an implicitly-declared
3025 		     special member function (clause _special_), the
3026 		     program is ill-formed.
3027 
3028 		     Similar language is found in [temp.explicit].  */
3029 		  error ("specialization of implicitly-declared special member function");
3030 		  return error_mark_node;
3031 		}
3032 
3033 	      name = DECL_NAME (decl);
3034 	    }
3035 
3036 	  /* For a type-conversion operator, We might be looking for
3037 	     `operator int' which will be a specialization of
3038 	     `operator T'.  Grab all the conversion operators, and
3039 	     then select from them.  */
3040 	  tree fns = get_class_binding (ctype, IDENTIFIER_CONV_OP_P (name)
3041 				      ? conv_op_identifier : name);
3042 
3043 	  if (fns == NULL_TREE)
3044 	    {
3045 	      error ("no member function %qD declared in %qT", name, ctype);
3046 	      return error_mark_node;
3047 	    }
3048 	  else
3049 	    TREE_OPERAND (declarator, 0) = fns;
3050 	}
3051 
3052       /* Figure out what exactly is being specialized at this point.
3053 	 Note that for an explicit instantiation, even one for a
3054 	 member function, we cannot tell a priori whether the
3055 	 instantiation is for a member template, or just a member
3056 	 function of a template class.  Even if a member template is
3057 	 being instantiated, the member template arguments may be
3058 	 elided if they can be deduced from the rest of the
3059 	 declaration.  */
3060       tmpl = determine_specialization (declarator, decl,
3061 				       &targs,
3062 				       member_specialization,
3063 				       template_count,
3064 				       tsk);
3065 
3066       if (!tmpl || tmpl == error_mark_node)
3067 	/* We couldn't figure out what this declaration was
3068 	   specializing.  */
3069 	return error_mark_node;
3070       else
3071 	{
3072 	  if (TREE_CODE (decl) == FUNCTION_DECL
3073 	      && DECL_HIDDEN_FRIEND_P (tmpl))
3074 	    {
3075 	      if (pedwarn (DECL_SOURCE_LOCATION (decl), 0,
3076 			   "friend declaration %qD is not visible to "
3077 			   "explicit specialization", tmpl))
3078 		inform (DECL_SOURCE_LOCATION (tmpl),
3079 			"friend declaration here");
3080 	    }
3081 	  else if (!ctype && !is_friend
3082 		   && CP_DECL_CONTEXT (decl) == current_namespace)
3083 	    check_unqualified_spec_or_inst (tmpl, DECL_SOURCE_LOCATION (decl));
3084 
3085 	  tree gen_tmpl = most_general_template (tmpl);
3086 
3087 	  if (explicit_instantiation)
3088 	    {
3089 	      /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
3090 		 is done by do_decl_instantiation later.  */
3091 
3092 	      int arg_depth = TMPL_ARGS_DEPTH (targs);
3093 	      int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
3094 
3095 	      if (arg_depth > parm_depth)
3096 		{
3097 		  /* If TMPL is not the most general template (for
3098 		     example, if TMPL is a friend template that is
3099 		     injected into namespace scope), then there will
3100 		     be too many levels of TARGS.  Remove some of them
3101 		     here.  */
3102 		  int i;
3103 		  tree new_targs;
3104 
3105 		  new_targs = make_tree_vec (parm_depth);
3106 		  for (i = arg_depth - parm_depth; i < arg_depth; ++i)
3107 		    TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
3108 		      = TREE_VEC_ELT (targs, i);
3109 		  targs = new_targs;
3110 		}
3111 
3112 	      return instantiate_template (tmpl, targs, tf_error);
3113 	    }
3114 
3115 	  /* If we thought that the DECL was a member function, but it
3116 	     turns out to be specializing a static member function,
3117 	     make DECL a static member function as well.  */
3118 	  if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3119 	      && DECL_STATIC_FUNCTION_P (tmpl)
3120 	      && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
3121 	    revert_static_member_fn (decl);
3122 
3123 	  /* If this is a specialization of a member template of a
3124 	     template class, we want to return the TEMPLATE_DECL, not
3125 	     the specialization of it.  */
3126 	  if (tsk == tsk_template && !was_template_id)
3127 	    {
3128 	      tree result = DECL_TEMPLATE_RESULT (tmpl);
3129 	      SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3130 	      DECL_INITIAL (result) = NULL_TREE;
3131 	      if (have_def)
3132 		{
3133 		  tree parm;
3134 		  DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
3135 		  DECL_SOURCE_LOCATION (result)
3136 		    = DECL_SOURCE_LOCATION (decl);
3137 		  /* We want to use the argument list specified in the
3138 		     definition, not in the original declaration.  */
3139 		  DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
3140 		  for (parm = DECL_ARGUMENTS (result); parm;
3141 		       parm = DECL_CHAIN (parm))
3142 		    DECL_CONTEXT (parm) = result;
3143 		}
3144 	      return register_specialization (tmpl, gen_tmpl, targs,
3145 					      is_friend, 0);
3146 	    }
3147 
3148 	  /* Set up the DECL_TEMPLATE_INFO for DECL.  */
3149 	  DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
3150 
3151 	  if (was_template_id)
3152 	    TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl)) = true;
3153 
3154 	  /* Inherit default function arguments from the template
3155 	     DECL is specializing.  */
3156 	  if (DECL_FUNCTION_TEMPLATE_P (tmpl))
3157 	    copy_default_args_to_explicit_spec (decl);
3158 
3159 	  /* This specialization has the same protection as the
3160 	     template it specializes.  */
3161 	  TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
3162 	  TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
3163 
3164           /* 7.1.1-1 [dcl.stc]
3165 
3166              A storage-class-specifier shall not be specified in an
3167              explicit specialization...
3168 
3169              The parser rejects these, so unless action is taken here,
3170              explicit function specializations will always appear with
3171              global linkage.
3172 
3173              The action recommended by the C++ CWG in response to C++
3174              defect report 605 is to make the storage class and linkage
3175              of the explicit specialization match the templated function:
3176 
3177              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
3178            */
3179           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
3180             {
3181               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
3182               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
3183 
3184               /* A concept cannot be specialized.  */
3185               if (DECL_DECLARED_CONCEPT_P (tmpl_func))
3186                 {
3187                   error ("explicit specialization of function concept %qD",
3188                          gen_tmpl);
3189                   return error_mark_node;
3190                 }
3191 
3192               /* This specialization has the same linkage and visibility as
3193                  the function template it specializes.  */
3194               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
3195 	      if (! TREE_PUBLIC (decl))
3196 		{
3197 		  DECL_INTERFACE_KNOWN (decl) = 1;
3198 		  DECL_NOT_REALLY_EXTERN (decl) = 1;
3199 		}
3200               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
3201               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
3202                 {
3203                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
3204                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
3205                 }
3206             }
3207 
3208 	  /* If DECL is a friend declaration, declared using an
3209 	     unqualified name, the namespace associated with DECL may
3210 	     have been set incorrectly.  For example, in:
3211 
3212 	       template <typename T> void f(T);
3213 	       namespace N {
3214 		 struct S { friend void f<int>(int); }
3215 	       }
3216 
3217 	     we will have set the DECL_CONTEXT for the friend
3218 	     declaration to N, rather than to the global namespace.  */
3219 	  if (DECL_NAMESPACE_SCOPE_P (decl))
3220 	    DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
3221 
3222 	  if (is_friend && !have_def)
3223 	    /* This is not really a declaration of a specialization.
3224 	       It's just the name of an instantiation.  But, it's not
3225 	       a request for an instantiation, either.  */
3226 	    SET_DECL_IMPLICIT_INSTANTIATION (decl);
3227 	  else if (TREE_CODE (decl) == FUNCTION_DECL)
3228 	    /* A specialization is not necessarily COMDAT.  */
3229 	    DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
3230 				  && DECL_DECLARED_INLINE_P (decl));
3231 	  else if (VAR_P (decl))
3232 	    DECL_COMDAT (decl) = false;
3233 
3234 	  /* If this is a full specialization, register it so that we can find
3235 	     it again.  Partial specializations will be registered in
3236 	     process_partial_specialization.  */
3237 	  if (!processing_template_decl)
3238 	    {
3239 	      warn_spec_missing_attributes (gen_tmpl, decl, attrlist);
3240 
3241 	      decl = register_specialization (decl, gen_tmpl, targs,
3242 					      is_friend, 0);
3243 	    }
3244 
3245 
3246 	  /* A 'structor should already have clones.  */
3247 	  gcc_assert (decl == error_mark_node
3248 		      || variable_template_p (tmpl)
3249 		      || !(DECL_CONSTRUCTOR_P (decl)
3250 			   || DECL_DESTRUCTOR_P (decl))
3251 		      || DECL_CLONED_FUNCTION_P (DECL_CHAIN (decl)));
3252 	}
3253     }
3254 
3255   return decl;
3256 }
3257 
3258 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
3259    parameters.  These are represented in the same format used for
3260    DECL_TEMPLATE_PARMS.  */
3261 
3262 int
comp_template_parms(const_tree parms1,const_tree parms2)3263 comp_template_parms (const_tree parms1, const_tree parms2)
3264 {
3265   const_tree p1;
3266   const_tree p2;
3267 
3268   if (parms1 == parms2)
3269     return 1;
3270 
3271   for (p1 = parms1, p2 = parms2;
3272        p1 != NULL_TREE && p2 != NULL_TREE;
3273        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
3274     {
3275       tree t1 = TREE_VALUE (p1);
3276       tree t2 = TREE_VALUE (p2);
3277       int i;
3278 
3279       gcc_assert (TREE_CODE (t1) == TREE_VEC);
3280       gcc_assert (TREE_CODE (t2) == TREE_VEC);
3281 
3282       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
3283 	return 0;
3284 
3285       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
3286 	{
3287           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
3288           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
3289 
3290           /* If either of the template parameters are invalid, assume
3291              they match for the sake of error recovery. */
3292           if (error_operand_p (parm1) || error_operand_p (parm2))
3293             return 1;
3294 
3295 	  if (TREE_CODE (parm1) != TREE_CODE (parm2))
3296 	    return 0;
3297 
3298 	  if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
3299               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
3300                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
3301 	    continue;
3302 	  else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
3303 	    return 0;
3304 	}
3305     }
3306 
3307   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
3308     /* One set of parameters has more parameters lists than the
3309        other.  */
3310     return 0;
3311 
3312   return 1;
3313 }
3314 
3315 /* Determine whether PARM is a parameter pack.  */
3316 
3317 bool
template_parameter_pack_p(const_tree parm)3318 template_parameter_pack_p (const_tree parm)
3319 {
3320   /* Determine if we have a non-type template parameter pack.  */
3321   if (TREE_CODE (parm) == PARM_DECL)
3322     return (DECL_TEMPLATE_PARM_P (parm)
3323             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
3324   if (TREE_CODE (parm) == TEMPLATE_PARM_INDEX)
3325     return TEMPLATE_PARM_PARAMETER_PACK (parm);
3326 
3327   /* If this is a list of template parameters, we could get a
3328      TYPE_DECL or a TEMPLATE_DECL.  */
3329   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
3330     parm = TREE_TYPE (parm);
3331 
3332   /* Otherwise it must be a type template parameter.  */
3333   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
3334 	   || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
3335 	  && TEMPLATE_TYPE_PARAMETER_PACK (parm));
3336 }
3337 
3338 /* Determine if T is a function parameter pack.  */
3339 
3340 bool
function_parameter_pack_p(const_tree t)3341 function_parameter_pack_p (const_tree t)
3342 {
3343   if (t && TREE_CODE (t) == PARM_DECL)
3344     return DECL_PACK_P (t);
3345   return false;
3346 }
3347 
3348 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
3349    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
3350 
3351 tree
get_function_template_decl(const_tree primary_func_tmpl_inst)3352 get_function_template_decl (const_tree primary_func_tmpl_inst)
3353 {
3354   if (! primary_func_tmpl_inst
3355       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
3356       || ! primary_template_specialization_p (primary_func_tmpl_inst))
3357     return NULL;
3358 
3359   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
3360 }
3361 
3362 /* Return true iff the function parameter PARAM_DECL was expanded
3363    from the function parameter pack PACK.  */
3364 
3365 bool
function_parameter_expanded_from_pack_p(tree param_decl,tree pack)3366 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
3367 {
3368   if (DECL_ARTIFICIAL (param_decl)
3369       || !function_parameter_pack_p (pack))
3370     return false;
3371 
3372   /* The parameter pack and its pack arguments have the same
3373      DECL_PARM_INDEX.  */
3374   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
3375 }
3376 
3377 /* Determine whether ARGS describes a variadic template args list,
3378    i.e., one that is terminated by a template argument pack.  */
3379 
3380 static bool
template_args_variadic_p(tree args)3381 template_args_variadic_p (tree args)
3382 {
3383   int nargs;
3384   tree last_parm;
3385 
3386   if (args == NULL_TREE)
3387     return false;
3388 
3389   args = INNERMOST_TEMPLATE_ARGS (args);
3390   nargs = TREE_VEC_LENGTH (args);
3391 
3392   if (nargs == 0)
3393     return false;
3394 
3395   last_parm = TREE_VEC_ELT (args, nargs - 1);
3396 
3397   return ARGUMENT_PACK_P (last_parm);
3398 }
3399 
3400 /* Generate a new name for the parameter pack name NAME (an
3401    IDENTIFIER_NODE) that incorporates its */
3402 
3403 static tree
make_ith_pack_parameter_name(tree name,int i)3404 make_ith_pack_parameter_name (tree name, int i)
3405 {
3406   /* Munge the name to include the parameter index.  */
3407 #define NUMBUF_LEN 128
3408   char numbuf[NUMBUF_LEN];
3409   char* newname;
3410   int newname_len;
3411 
3412   if (name == NULL_TREE)
3413     return name;
3414   snprintf (numbuf, NUMBUF_LEN, "%i", i);
3415   newname_len = IDENTIFIER_LENGTH (name)
3416 	        + strlen (numbuf) + 2;
3417   newname = (char*)alloca (newname_len);
3418   snprintf (newname, newname_len,
3419 	    "%s#%i", IDENTIFIER_POINTER (name), i);
3420   return get_identifier (newname);
3421 }
3422 
3423 /* Return true if T is a primary function, class or alias template
3424    specialization, not including the template pattern.  */
3425 
3426 bool
primary_template_specialization_p(const_tree t)3427 primary_template_specialization_p (const_tree t)
3428 {
3429   if (!t)
3430     return false;
3431 
3432   if (TREE_CODE (t) == FUNCTION_DECL || VAR_P (t))
3433     return (DECL_LANG_SPECIFIC (t)
3434 	    && DECL_USE_TEMPLATE (t)
3435 	    && DECL_TEMPLATE_INFO (t)
3436 	    && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t)));
3437   else if (CLASS_TYPE_P (t) && !TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
3438     return (CLASSTYPE_TEMPLATE_INFO (t)
3439 	    && CLASSTYPE_USE_TEMPLATE (t)
3440 	    && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t)));
3441   else if (alias_template_specialization_p (t))
3442     return true;
3443   return false;
3444 }
3445 
3446 /* Return true if PARM is a template template parameter.  */
3447 
3448 bool
template_template_parameter_p(const_tree parm)3449 template_template_parameter_p (const_tree parm)
3450 {
3451   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
3452 }
3453 
3454 /* Return true iff PARM is a DECL representing a type template
3455    parameter.  */
3456 
3457 bool
template_type_parameter_p(const_tree parm)3458 template_type_parameter_p (const_tree parm)
3459 {
3460   return (parm
3461 	  && (TREE_CODE (parm) == TYPE_DECL
3462 	      || TREE_CODE (parm) == TEMPLATE_DECL)
3463 	  && DECL_TEMPLATE_PARM_P (parm));
3464 }
3465 
3466 /* Return the template parameters of T if T is a
3467    primary template instantiation, NULL otherwise.  */
3468 
3469 tree
get_primary_template_innermost_parameters(const_tree t)3470 get_primary_template_innermost_parameters (const_tree t)
3471 {
3472   tree parms = NULL, template_info = NULL;
3473 
3474   if ((template_info = get_template_info (t))
3475       && primary_template_specialization_p (t))
3476     parms = INNERMOST_TEMPLATE_PARMS
3477 	(DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
3478 
3479   return parms;
3480 }
3481 
3482 /* Return the template parameters of the LEVELth level from the full list
3483    of template parameters PARMS.  */
3484 
3485 tree
get_template_parms_at_level(tree parms,int level)3486 get_template_parms_at_level (tree parms, int level)
3487 {
3488   tree p;
3489   if (!parms
3490       || TREE_CODE (parms) != TREE_LIST
3491       || level > TMPL_PARMS_DEPTH (parms))
3492     return NULL_TREE;
3493 
3494   for (p = parms; p; p = TREE_CHAIN (p))
3495     if (TMPL_PARMS_DEPTH (p) == level)
3496       return p;
3497 
3498   return NULL_TREE;
3499 }
3500 
3501 /* Returns the template arguments of T if T is a template instantiation,
3502    NULL otherwise.  */
3503 
3504 tree
get_template_innermost_arguments(const_tree t)3505 get_template_innermost_arguments (const_tree t)
3506 {
3507   tree args = NULL, template_info = NULL;
3508 
3509   if ((template_info = get_template_info (t))
3510       && TI_ARGS (template_info))
3511     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
3512 
3513   return args;
3514 }
3515 
3516 /* Return the argument pack elements of T if T is a template argument pack,
3517    NULL otherwise.  */
3518 
3519 tree
get_template_argument_pack_elems(const_tree t)3520 get_template_argument_pack_elems (const_tree t)
3521 {
3522   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
3523       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
3524     return NULL;
3525 
3526   return ARGUMENT_PACK_ARGS (t);
3527 }
3528 
3529 /* In an ARGUMENT_PACK_SELECT, the actual underlying argument that the
3530    ARGUMENT_PACK_SELECT represents. */
3531 
3532 static tree
argument_pack_select_arg(tree t)3533 argument_pack_select_arg (tree t)
3534 {
3535   tree args = ARGUMENT_PACK_ARGS (ARGUMENT_PACK_SELECT_FROM_PACK (t));
3536   tree arg = TREE_VEC_ELT (args, ARGUMENT_PACK_SELECT_INDEX (t));
3537 
3538   /* If the selected argument is an expansion E, that most likely means we were
3539      called from gen_elem_of_pack_expansion_instantiation during the
3540      substituting of an argument pack (of which the Ith element is a pack
3541      expansion, where I is ARGUMENT_PACK_SELECT_INDEX) into a pack expansion.
3542      In this case, the Ith element resulting from this substituting is going to
3543      be a pack expansion, which pattern is the pattern of E.  Let's return the
3544      pattern of E, and gen_elem_of_pack_expansion_instantiation will build the
3545      resulting pack expansion from it.  */
3546   if (PACK_EXPANSION_P (arg))
3547     {
3548       /* Make sure we aren't throwing away arg info.  */
3549       gcc_assert (!PACK_EXPANSION_EXTRA_ARGS (arg));
3550       arg = PACK_EXPANSION_PATTERN (arg);
3551     }
3552 
3553   return arg;
3554 }
3555 
3556 
3557 /* True iff FN is a function representing a built-in variadic parameter
3558    pack.  */
3559 
3560 bool
builtin_pack_fn_p(tree fn)3561 builtin_pack_fn_p (tree fn)
3562 {
3563   if (!fn
3564       || TREE_CODE (fn) != FUNCTION_DECL
3565       || !DECL_IS_BUILTIN (fn))
3566     return false;
3567 
3568   if (id_equal (DECL_NAME (fn), "__integer_pack"))
3569     return true;
3570 
3571   return false;
3572 }
3573 
3574 /* True iff CALL is a call to a function representing a built-in variadic
3575    parameter pack.  */
3576 
3577 static bool
builtin_pack_call_p(tree call)3578 builtin_pack_call_p (tree call)
3579 {
3580   if (TREE_CODE (call) != CALL_EXPR)
3581     return false;
3582   return builtin_pack_fn_p (CALL_EXPR_FN (call));
3583 }
3584 
3585 /* Return a TREE_VEC for the expansion of __integer_pack(HI).  */
3586 
3587 static tree
expand_integer_pack(tree call,tree args,tsubst_flags_t complain,tree in_decl)3588 expand_integer_pack (tree call, tree args, tsubst_flags_t complain,
3589 		     tree in_decl)
3590 {
3591   tree ohi = CALL_EXPR_ARG (call, 0);
3592   tree hi = tsubst_copy_and_build (ohi, args, complain, in_decl,
3593 				   false/*fn*/, true/*int_cst*/);
3594 
3595   if (value_dependent_expression_p (hi))
3596     {
3597       if (hi != ohi)
3598 	{
3599 	  call = copy_node (call);
3600 	  CALL_EXPR_ARG (call, 0) = hi;
3601 	}
3602       tree ex = make_pack_expansion (call, complain);
3603       tree vec = make_tree_vec (1);
3604       TREE_VEC_ELT (vec, 0) = ex;
3605       return vec;
3606     }
3607   else
3608     {
3609       hi = cxx_constant_value (hi);
3610       int len = valid_constant_size_p (hi) ? tree_to_shwi (hi) : -1;
3611 
3612       /* Calculate the largest value of len that won't make the size of the vec
3613 	 overflow an int.  The compiler will exceed resource limits long before
3614 	 this, but it seems a decent place to diagnose.  */
3615       int max = ((INT_MAX - sizeof (tree_vec)) / sizeof (tree)) + 1;
3616 
3617       if (len < 0 || len > max)
3618 	{
3619 	  if ((complain & tf_error)
3620 	      && hi != error_mark_node)
3621 	    error ("argument to __integer_pack must be between 0 and %d", max);
3622 	  return error_mark_node;
3623 	}
3624 
3625       tree vec = make_tree_vec (len);
3626 
3627       for (int i = 0; i < len; ++i)
3628 	TREE_VEC_ELT (vec, i) = size_int (i);
3629 
3630       return vec;
3631     }
3632 }
3633 
3634 /* Return a TREE_VEC for the expansion of built-in template parameter pack
3635    CALL.  */
3636 
3637 static tree
expand_builtin_pack_call(tree call,tree args,tsubst_flags_t complain,tree in_decl)3638 expand_builtin_pack_call (tree call, tree args, tsubst_flags_t complain,
3639 			  tree in_decl)
3640 {
3641   if (!builtin_pack_call_p (call))
3642     return NULL_TREE;
3643 
3644   tree fn = CALL_EXPR_FN (call);
3645 
3646   if (id_equal (DECL_NAME (fn), "__integer_pack"))
3647     return expand_integer_pack (call, args, complain, in_decl);
3648 
3649   return NULL_TREE;
3650 }
3651 
3652 /* Structure used to track the progress of find_parameter_packs_r.  */
3653 struct find_parameter_pack_data
3654 {
3655   /* TREE_LIST that will contain all of the parameter packs found by
3656      the traversal.  */
3657   tree* parameter_packs;
3658 
3659   /* Set of AST nodes that have been visited by the traversal.  */
3660   hash_set<tree> *visited;
3661 
3662   /* True iff we're making a type pack expansion.  */
3663   bool type_pack_expansion_p;
3664 };
3665 
3666 /* Identifies all of the argument packs that occur in a template
3667    argument and appends them to the TREE_LIST inside DATA, which is a
3668    find_parameter_pack_data structure. This is a subroutine of
3669    make_pack_expansion and uses_parameter_packs.  */
3670 static tree
find_parameter_packs_r(tree * tp,int * walk_subtrees,void * data)3671 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
3672 {
3673   tree t = *tp;
3674   struct find_parameter_pack_data* ppd =
3675     (struct find_parameter_pack_data*)data;
3676   bool parameter_pack_p = false;
3677 
3678   /* Handle type aliases/typedefs.  */
3679   if (TYPE_ALIAS_P (t))
3680     {
3681       if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
3682 	cp_walk_tree (&TI_ARGS (tinfo),
3683 		      &find_parameter_packs_r,
3684 		      ppd, ppd->visited);
3685       *walk_subtrees = 0;
3686       return NULL_TREE;
3687     }
3688 
3689   /* Identify whether this is a parameter pack or not.  */
3690   switch (TREE_CODE (t))
3691     {
3692     case TEMPLATE_PARM_INDEX:
3693       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3694         parameter_pack_p = true;
3695       break;
3696 
3697     case TEMPLATE_TYPE_PARM:
3698       t = TYPE_MAIN_VARIANT (t);
3699       /* FALLTHRU */
3700     case TEMPLATE_TEMPLATE_PARM:
3701       /* If the placeholder appears in the decl-specifier-seq of a function
3702 	 parameter pack (14.6.3), or the type-specifier-seq of a type-id that
3703 	 is a pack expansion, the invented template parameter is a template
3704 	 parameter pack.  */
3705       if (ppd->type_pack_expansion_p && is_auto (t))
3706 	TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
3707       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3708         parameter_pack_p = true;
3709       break;
3710 
3711     case FIELD_DECL:
3712     case PARM_DECL:
3713       if (DECL_PACK_P (t))
3714         {
3715           /* We don't want to walk into the type of a PARM_DECL,
3716              because we don't want to see the type parameter pack.  */
3717           *walk_subtrees = 0;
3718 	  parameter_pack_p = true;
3719         }
3720       break;
3721 
3722     case VAR_DECL:
3723       if (DECL_PACK_P (t))
3724         {
3725           /* We don't want to walk into the type of a variadic capture proxy,
3726              because we don't want to see the type parameter pack.  */
3727           *walk_subtrees = 0;
3728 	  parameter_pack_p = true;
3729         }
3730       else if (variable_template_specialization_p (t))
3731 	{
3732 	  cp_walk_tree (&DECL_TI_ARGS (t),
3733 			find_parameter_packs_r,
3734 			ppd, ppd->visited);
3735 	  *walk_subtrees = 0;
3736 	}
3737       break;
3738 
3739     case CALL_EXPR:
3740       if (builtin_pack_call_p (t))
3741 	parameter_pack_p = true;
3742       break;
3743 
3744     case BASES:
3745       parameter_pack_p = true;
3746       break;
3747     default:
3748       /* Not a parameter pack.  */
3749       break;
3750     }
3751 
3752   if (parameter_pack_p)
3753     {
3754       /* Add this parameter pack to the list.  */
3755       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
3756     }
3757 
3758   if (TYPE_P (t))
3759     cp_walk_tree (&TYPE_CONTEXT (t),
3760 		  &find_parameter_packs_r, ppd, ppd->visited);
3761 
3762   /* This switch statement will return immediately if we don't find a
3763      parameter pack.  */
3764   switch (TREE_CODE (t))
3765     {
3766     case TEMPLATE_PARM_INDEX:
3767       return NULL_TREE;
3768 
3769     case BOUND_TEMPLATE_TEMPLATE_PARM:
3770       /* Check the template itself.  */
3771       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)),
3772 		    &find_parameter_packs_r, ppd, ppd->visited);
3773       /* Check the template arguments.  */
3774       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd,
3775 		    ppd->visited);
3776       *walk_subtrees = 0;
3777       return NULL_TREE;
3778 
3779     case TEMPLATE_TYPE_PARM:
3780     case TEMPLATE_TEMPLATE_PARM:
3781       return NULL_TREE;
3782 
3783     case PARM_DECL:
3784       return NULL_TREE;
3785 
3786     case DECL_EXPR:
3787       /* Ignore the declaration of a capture proxy for a parameter pack.  */
3788       if (is_capture_proxy (DECL_EXPR_DECL (t)))
3789 	*walk_subtrees = 0;
3790       return NULL_TREE;
3791 
3792     case RECORD_TYPE:
3793       if (TYPE_PTRMEMFUNC_P (t))
3794 	return NULL_TREE;
3795       /* Fall through.  */
3796 
3797     case UNION_TYPE:
3798     case ENUMERAL_TYPE:
3799       if (TYPE_TEMPLATE_INFO (t))
3800 	cp_walk_tree (&TYPE_TI_ARGS (t),
3801 		      &find_parameter_packs_r, ppd, ppd->visited);
3802 
3803       *walk_subtrees = 0;
3804       return NULL_TREE;
3805 
3806     case TEMPLATE_DECL:
3807       if (!DECL_TEMPLATE_TEMPLATE_PARM_P (t))
3808 	return NULL_TREE;
3809       gcc_fallthrough();
3810 
3811     case CONSTRUCTOR:
3812       cp_walk_tree (&TREE_TYPE (t),
3813 		    &find_parameter_packs_r, ppd, ppd->visited);
3814       return NULL_TREE;
3815 
3816     case TYPENAME_TYPE:
3817       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
3818                    ppd, ppd->visited);
3819       *walk_subtrees = 0;
3820       return NULL_TREE;
3821 
3822     case TYPE_PACK_EXPANSION:
3823     case EXPR_PACK_EXPANSION:
3824       *walk_subtrees = 0;
3825       return NULL_TREE;
3826 
3827     case INTEGER_TYPE:
3828       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r,
3829 		    ppd, ppd->visited);
3830       *walk_subtrees = 0;
3831       return NULL_TREE;
3832 
3833     case IDENTIFIER_NODE:
3834       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd,
3835 		    ppd->visited);
3836       *walk_subtrees = 0;
3837       return NULL_TREE;
3838 
3839     case LAMBDA_EXPR:
3840       {
3841 	/* Look at explicit captures.  */
3842 	for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (t);
3843 	     cap; cap = TREE_CHAIN (cap))
3844 	  cp_walk_tree (&TREE_VALUE (cap), &find_parameter_packs_r, ppd,
3845 			ppd->visited);
3846 	/* Since we defer implicit capture, look in the parms and body.  */
3847 	tree fn = lambda_function (t);
3848 	cp_walk_tree (&TREE_TYPE (fn), &find_parameter_packs_r, ppd,
3849 		      ppd->visited);
3850 	cp_walk_tree (&DECL_SAVED_TREE (fn), &find_parameter_packs_r, ppd,
3851 		      ppd->visited);
3852 	*walk_subtrees = 0;
3853 	return NULL_TREE;
3854       }
3855 
3856     case DECLTYPE_TYPE:
3857       {
3858 	/* When traversing a DECLTYPE_TYPE_EXPR, we need to set
3859 	   type_pack_expansion_p to false so that any placeholders
3860 	   within the expression don't get marked as parameter packs.  */
3861 	bool type_pack_expansion_p = ppd->type_pack_expansion_p;
3862 	ppd->type_pack_expansion_p = false;
3863 	cp_walk_tree (&DECLTYPE_TYPE_EXPR (t), &find_parameter_packs_r,
3864 		      ppd, ppd->visited);
3865 	ppd->type_pack_expansion_p = type_pack_expansion_p;
3866 	*walk_subtrees = 0;
3867 	return NULL_TREE;
3868       }
3869 
3870     case IF_STMT:
3871       cp_walk_tree (&IF_COND (t), &find_parameter_packs_r,
3872 		    ppd, ppd->visited);
3873       cp_walk_tree (&THEN_CLAUSE (t), &find_parameter_packs_r,
3874 		    ppd, ppd->visited);
3875       cp_walk_tree (&ELSE_CLAUSE (t), &find_parameter_packs_r,
3876 		    ppd, ppd->visited);
3877       /* Don't walk into IF_STMT_EXTRA_ARGS.  */
3878       *walk_subtrees = 0;
3879       return NULL_TREE;
3880 
3881     default:
3882       return NULL_TREE;
3883     }
3884 
3885   return NULL_TREE;
3886 }
3887 
3888 /* Determines if the expression or type T uses any parameter packs.  */
3889 bool
uses_parameter_packs(tree t)3890 uses_parameter_packs (tree t)
3891 {
3892   tree parameter_packs = NULL_TREE;
3893   struct find_parameter_pack_data ppd;
3894   ppd.parameter_packs = &parameter_packs;
3895   ppd.visited = new hash_set<tree>;
3896   ppd.type_pack_expansion_p = false;
3897   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3898   delete ppd.visited;
3899   return parameter_packs != NULL_TREE;
3900 }
3901 
3902 /* Turn ARG, which may be an expression, type, or a TREE_LIST
3903    representation a base-class initializer into a parameter pack
3904    expansion. If all goes well, the resulting node will be an
3905    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
3906    respectively.  */
3907 tree
make_pack_expansion(tree arg,tsubst_flags_t complain)3908 make_pack_expansion (tree arg, tsubst_flags_t complain)
3909 {
3910   tree result;
3911   tree parameter_packs = NULL_TREE;
3912   bool for_types = false;
3913   struct find_parameter_pack_data ppd;
3914 
3915   if (!arg || arg == error_mark_node)
3916     return arg;
3917 
3918   if (TREE_CODE (arg) == TREE_LIST && TREE_PURPOSE (arg))
3919     {
3920       /* A TREE_LIST with a non-null TREE_PURPOSE is for a base
3921          class initializer.  In this case, the TREE_PURPOSE will be a
3922          _TYPE node (representing the base class expansion we're
3923          initializing) and the TREE_VALUE will be a TREE_LIST
3924          containing the initialization arguments.
3925 
3926          The resulting expansion looks somewhat different from most
3927          expansions. Rather than returning just one _EXPANSION, we
3928          return a TREE_LIST whose TREE_PURPOSE is a
3929          TYPE_PACK_EXPANSION containing the bases that will be
3930          initialized.  The TREE_VALUE will be identical to the
3931          original TREE_VALUE, which is a list of arguments that will
3932          be passed to each base.  We do not introduce any new pack
3933          expansion nodes into the TREE_VALUE (although it is possible
3934          that some already exist), because the TREE_PURPOSE and
3935          TREE_VALUE all need to be expanded together with the same
3936          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3937          resulting TREE_PURPOSE will mention the parameter packs in
3938          both the bases and the arguments to the bases.  */
3939       tree purpose;
3940       tree value;
3941       tree parameter_packs = NULL_TREE;
3942 
3943       /* Determine which parameter packs will be used by the base
3944          class expansion.  */
3945       ppd.visited = new hash_set<tree>;
3946       ppd.parameter_packs = &parameter_packs;
3947       ppd.type_pack_expansion_p = true;
3948       gcc_assert (TYPE_P (TREE_PURPOSE (arg)));
3949       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r,
3950                     &ppd, ppd.visited);
3951 
3952       if (parameter_packs == NULL_TREE)
3953         {
3954 	  if (complain & tf_error)
3955 	    error ("base initializer expansion %qT contains no parameter packs",
3956 		   arg);
3957           delete ppd.visited;
3958           return error_mark_node;
3959         }
3960 
3961       if (TREE_VALUE (arg) != void_type_node)
3962         {
3963           /* Collect the sets of parameter packs used in each of the
3964              initialization arguments.  */
3965           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3966             {
3967               /* Determine which parameter packs will be expanded in this
3968                  argument.  */
3969               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r,
3970                             &ppd, ppd.visited);
3971             }
3972         }
3973 
3974       delete ppd.visited;
3975 
3976       /* Create the pack expansion type for the base type.  */
3977       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3978       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3979       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3980       PACK_EXPANSION_LOCAL_P (purpose) = at_function_scope_p ();
3981 
3982       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3983 	 they will rarely be compared to anything.  */
3984       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3985 
3986       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3987     }
3988 
3989   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3990     for_types = true;
3991 
3992   /* Build the PACK_EXPANSION_* node.  */
3993   result = for_types
3994      ? cxx_make_type (TYPE_PACK_EXPANSION)
3995      : make_node (EXPR_PACK_EXPANSION);
3996   SET_PACK_EXPANSION_PATTERN (result, arg);
3997   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3998     {
3999       /* Propagate type and const-expression information.  */
4000       TREE_TYPE (result) = TREE_TYPE (arg);
4001       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
4002       /* Mark this read now, since the expansion might be length 0.  */
4003       mark_exp_read (arg);
4004     }
4005   else
4006     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
4007        they will rarely be compared to anything.  */
4008     SET_TYPE_STRUCTURAL_EQUALITY (result);
4009 
4010   /* Determine which parameter packs will be expanded.  */
4011   ppd.parameter_packs = &parameter_packs;
4012   ppd.visited = new hash_set<tree>;
4013   ppd.type_pack_expansion_p = TYPE_P (arg);
4014   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
4015   delete ppd.visited;
4016 
4017   /* Make sure we found some parameter packs.  */
4018   if (parameter_packs == NULL_TREE)
4019     {
4020       if (complain & tf_error)
4021 	{
4022 	  if (TYPE_P (arg))
4023 	    error ("expansion pattern %qT contains no argument packs", arg);
4024 	  else
4025 	    error ("expansion pattern %qE contains no argument packs", arg);
4026 	}
4027       return error_mark_node;
4028     }
4029   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
4030 
4031   PACK_EXPANSION_LOCAL_P (result) = at_function_scope_p ();
4032 
4033   return result;
4034 }
4035 
4036 /* Checks T for any "bare" parameter packs, which have not yet been
4037    expanded, and issues an error if any are found. This operation can
4038    only be done on full expressions or types (e.g., an expression
4039    statement, "if" condition, etc.), because we could have expressions like:
4040 
4041      foo(f(g(h(args)))...)
4042 
4043    where "args" is a parameter pack. check_for_bare_parameter_packs
4044    should not be called for the subexpressions args, h(args),
4045    g(h(args)), or f(g(h(args))), because we would produce erroneous
4046    error messages.
4047 
4048    Returns TRUE and emits an error if there were bare parameter packs,
4049    returns FALSE otherwise.  */
4050 bool
check_for_bare_parameter_packs(tree t,location_t loc)4051 check_for_bare_parameter_packs (tree t, location_t loc /* = UNKNOWN_LOCATION */)
4052 {
4053   tree parameter_packs = NULL_TREE;
4054   struct find_parameter_pack_data ppd;
4055 
4056   if (!processing_template_decl || !t || t == error_mark_node)
4057     return false;
4058 
4059   /* A lambda might use a parameter pack from the containing context.  */
4060   if (current_class_type && LAMBDA_TYPE_P (current_class_type)
4061       && CLASSTYPE_TEMPLATE_INFO (current_class_type))
4062     return false;
4063 
4064   if (TREE_CODE (t) == TYPE_DECL)
4065     t = TREE_TYPE (t);
4066 
4067   ppd.parameter_packs = &parameter_packs;
4068   ppd.visited = new hash_set<tree>;
4069   ppd.type_pack_expansion_p = false;
4070   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
4071   delete ppd.visited;
4072 
4073   if (parameter_packs)
4074     {
4075       if (loc == UNKNOWN_LOCATION)
4076 	loc = EXPR_LOC_OR_LOC (t, input_location);
4077       error_at (loc, "parameter packs not expanded with %<...%>:");
4078       while (parameter_packs)
4079         {
4080           tree pack = TREE_VALUE (parameter_packs);
4081           tree name = NULL_TREE;
4082 
4083           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
4084               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
4085             name = TYPE_NAME (pack);
4086           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
4087             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
4088 	  else if (TREE_CODE (pack) == CALL_EXPR)
4089 	    name = DECL_NAME (CALL_EXPR_FN (pack));
4090           else
4091             name = DECL_NAME (pack);
4092 
4093 	  if (name)
4094 	    inform (loc, "        %qD", name);
4095 	  else
4096 	    inform (loc, "        <anonymous>");
4097 
4098           parameter_packs = TREE_CHAIN (parameter_packs);
4099         }
4100 
4101       return true;
4102     }
4103 
4104   return false;
4105 }
4106 
4107 /* Expand any parameter packs that occur in the template arguments in
4108    ARGS.  */
4109 tree
expand_template_argument_pack(tree args)4110 expand_template_argument_pack (tree args)
4111 {
4112   if (args == error_mark_node)
4113     return error_mark_node;
4114 
4115   tree result_args = NULL_TREE;
4116   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
4117   int num_result_args = -1;
4118   int non_default_args_count = -1;
4119 
4120   /* First, determine if we need to expand anything, and the number of
4121      slots we'll need.  */
4122   for (in_arg = 0; in_arg < nargs; ++in_arg)
4123     {
4124       tree arg = TREE_VEC_ELT (args, in_arg);
4125       if (arg == NULL_TREE)
4126 	return args;
4127       if (ARGUMENT_PACK_P (arg))
4128         {
4129           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
4130           if (num_result_args < 0)
4131             num_result_args = in_arg + num_packed;
4132           else
4133             num_result_args += num_packed;
4134         }
4135       else
4136         {
4137           if (num_result_args >= 0)
4138             num_result_args++;
4139         }
4140     }
4141 
4142   /* If no expansion is necessary, we're done.  */
4143   if (num_result_args < 0)
4144     return args;
4145 
4146   /* Expand arguments.  */
4147   result_args = make_tree_vec (num_result_args);
4148   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
4149     non_default_args_count =
4150       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
4151   for (in_arg = 0; in_arg < nargs; ++in_arg)
4152     {
4153       tree arg = TREE_VEC_ELT (args, in_arg);
4154       if (ARGUMENT_PACK_P (arg))
4155         {
4156           tree packed = ARGUMENT_PACK_ARGS (arg);
4157           int i, num_packed = TREE_VEC_LENGTH (packed);
4158           for (i = 0; i < num_packed; ++i, ++out_arg)
4159             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
4160 	  if (non_default_args_count > 0)
4161 	    non_default_args_count += num_packed - 1;
4162         }
4163       else
4164         {
4165           TREE_VEC_ELT (result_args, out_arg) = arg;
4166           ++out_arg;
4167         }
4168     }
4169   if (non_default_args_count >= 0)
4170     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
4171   return result_args;
4172 }
4173 
4174 /* Checks if DECL shadows a template parameter.
4175 
4176    [temp.local]: A template-parameter shall not be redeclared within its
4177    scope (including nested scopes).
4178 
4179    Emits an error and returns TRUE if the DECL shadows a parameter,
4180    returns FALSE otherwise.  */
4181 
4182 bool
check_template_shadow(tree decl)4183 check_template_shadow (tree decl)
4184 {
4185   tree olddecl;
4186 
4187   /* If we're not in a template, we can't possibly shadow a template
4188      parameter.  */
4189   if (!current_template_parms)
4190     return true;
4191 
4192   /* Figure out what we're shadowing.  */
4193   decl = OVL_FIRST (decl);
4194   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
4195 
4196   /* If there's no previous binding for this name, we're not shadowing
4197      anything, let alone a template parameter.  */
4198   if (!olddecl)
4199     return true;
4200 
4201   /* If we're not shadowing a template parameter, we're done.  Note
4202      that OLDDECL might be an OVERLOAD (or perhaps even an
4203      ERROR_MARK), so we can't just blithely assume it to be a _DECL
4204      node.  */
4205   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
4206     return true;
4207 
4208   /* We check for decl != olddecl to avoid bogus errors for using a
4209      name inside a class.  We check TPFI to avoid duplicate errors for
4210      inline member templates.  */
4211   if (decl == olddecl
4212       || (DECL_TEMPLATE_PARM_P (decl)
4213 	  && TEMPLATE_PARMS_FOR_INLINE (current_template_parms)))
4214     return true;
4215 
4216   /* Don't complain about the injected class name, as we've already
4217      complained about the class itself.  */
4218   if (DECL_SELF_REFERENCE_P (decl))
4219     return false;
4220 
4221   if (DECL_TEMPLATE_PARM_P (decl))
4222     error ("declaration of template parameter %q+D shadows "
4223 	   "template parameter", decl);
4224   else
4225     error ("declaration of %q+#D shadows template parameter", decl);
4226   inform (DECL_SOURCE_LOCATION (olddecl),
4227 	  "template parameter %qD declared here", olddecl);
4228   return false;
4229 }
4230 
4231 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
4232    ORIG_LEVEL, DECL, and TYPE.  */
4233 
4234 static tree
build_template_parm_index(int index,int level,int orig_level,tree decl,tree type)4235 build_template_parm_index (int index,
4236 			   int level,
4237 			   int orig_level,
4238 			   tree decl,
4239 			   tree type)
4240 {
4241   tree t = make_node (TEMPLATE_PARM_INDEX);
4242   TEMPLATE_PARM_IDX (t) = index;
4243   TEMPLATE_PARM_LEVEL (t) = level;
4244   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
4245   TEMPLATE_PARM_DECL (t) = decl;
4246   TREE_TYPE (t) = type;
4247   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
4248   TREE_READONLY (t) = TREE_READONLY (decl);
4249 
4250   return t;
4251 }
4252 
4253 /* Find the canonical type parameter for the given template type
4254    parameter.  Returns the canonical type parameter, which may be TYPE
4255    if no such parameter existed.  */
4256 
4257 static tree
canonical_type_parameter(tree type)4258 canonical_type_parameter (tree type)
4259 {
4260   tree list;
4261   int idx = TEMPLATE_TYPE_IDX (type);
4262   if (!canonical_template_parms)
4263     vec_alloc (canonical_template_parms, idx + 1);
4264 
4265   if (canonical_template_parms->length () <= (unsigned) idx)
4266     vec_safe_grow_cleared (canonical_template_parms, idx + 1);
4267 
4268   list = (*canonical_template_parms)[idx];
4269   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
4270     list = TREE_CHAIN (list);
4271 
4272   if (list)
4273     return TREE_VALUE (list);
4274   else
4275     {
4276       (*canonical_template_parms)[idx]
4277 	= tree_cons (NULL_TREE, type, (*canonical_template_parms)[idx]);
4278       return type;
4279     }
4280 }
4281 
4282 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
4283    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
4284    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
4285    new one is created.  */
4286 
4287 static tree
reduce_template_parm_level(tree index,tree type,int levels,tree args,tsubst_flags_t complain)4288 reduce_template_parm_level (tree index, tree type, int levels, tree args,
4289 			    tsubst_flags_t complain)
4290 {
4291   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
4292       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
4293 	  != TEMPLATE_PARM_LEVEL (index) - levels)
4294       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
4295     {
4296       tree orig_decl = TEMPLATE_PARM_DECL (index);
4297       tree decl, t;
4298 
4299       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
4300 			 TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
4301       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
4302       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
4303       DECL_ARTIFICIAL (decl) = 1;
4304       SET_DECL_TEMPLATE_PARM_P (decl);
4305 
4306       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
4307 				     TEMPLATE_PARM_LEVEL (index) - levels,
4308 				     TEMPLATE_PARM_ORIG_LEVEL (index),
4309 				     decl, type);
4310       TEMPLATE_PARM_DESCENDANTS (index) = t;
4311       TEMPLATE_PARM_PARAMETER_PACK (t)
4312 	= TEMPLATE_PARM_PARAMETER_PACK (index);
4313 
4314 	/* Template template parameters need this.  */
4315       if (TREE_CODE (decl) == TEMPLATE_DECL)
4316 	{
4317 	  DECL_TEMPLATE_RESULT (decl)
4318 	    = build_decl (DECL_SOURCE_LOCATION (decl),
4319 			  TYPE_DECL, DECL_NAME (decl), type);
4320 	  DECL_ARTIFICIAL (DECL_TEMPLATE_RESULT (decl)) = true;
4321 	  DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
4322 	    (DECL_TEMPLATE_PARMS (orig_decl), args, complain);
4323 	}
4324     }
4325 
4326   return TEMPLATE_PARM_DESCENDANTS (index);
4327 }
4328 
4329 /* Process information from new template parameter PARM and append it
4330    to the LIST being built.  This new parameter is a non-type
4331    parameter iff IS_NON_TYPE is true. This new parameter is a
4332    parameter pack iff IS_PARAMETER_PACK is true.  The location of PARM
4333    is in PARM_LOC.  */
4334 
4335 tree
process_template_parm(tree list,location_t parm_loc,tree parm,bool is_non_type,bool is_parameter_pack)4336 process_template_parm (tree list, location_t parm_loc, tree parm,
4337 		       bool is_non_type, bool is_parameter_pack)
4338 {
4339   tree decl = 0;
4340   int idx = 0;
4341 
4342   gcc_assert (TREE_CODE (parm) == TREE_LIST);
4343   tree defval = TREE_PURPOSE (parm);
4344   tree constr = TREE_TYPE (parm);
4345 
4346   if (list)
4347     {
4348       tree p = tree_last (list);
4349 
4350       if (p && TREE_VALUE (p) != error_mark_node)
4351         {
4352           p = TREE_VALUE (p);
4353           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
4354             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
4355           else
4356             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
4357         }
4358 
4359       ++idx;
4360     }
4361 
4362   if (is_non_type)
4363     {
4364       parm = TREE_VALUE (parm);
4365 
4366       SET_DECL_TEMPLATE_PARM_P (parm);
4367 
4368       if (TREE_TYPE (parm) != error_mark_node)
4369 	{
4370 	  /* [temp.param]
4371 
4372 	     The top-level cv-qualifiers on the template-parameter are
4373 	     ignored when determining its type.  */
4374 	  TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
4375 	  if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
4376 	    TREE_TYPE (parm) = error_mark_node;
4377 	  else if (uses_parameter_packs (TREE_TYPE (parm))
4378 		   && !is_parameter_pack
4379 		   /* If we're in a nested template parameter list, the template
4380 		      template parameter could be a parameter pack.  */
4381 		   && processing_template_parmlist == 1)
4382 	    {
4383 	      /* This template parameter is not a parameter pack, but it
4384 		 should be. Complain about "bare" parameter packs.  */
4385 	      check_for_bare_parameter_packs (TREE_TYPE (parm));
4386 
4387 	      /* Recover by calling this a parameter pack.  */
4388 	      is_parameter_pack = true;
4389 	    }
4390 	}
4391 
4392       /* A template parameter is not modifiable.  */
4393       TREE_CONSTANT (parm) = 1;
4394       TREE_READONLY (parm) = 1;
4395       decl = build_decl (parm_loc,
4396 			 CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
4397       TREE_CONSTANT (decl) = 1;
4398       TREE_READONLY (decl) = 1;
4399       DECL_INITIAL (parm) = DECL_INITIAL (decl)
4400 	= build_template_parm_index (idx, processing_template_decl,
4401 				     processing_template_decl,
4402 				     decl, TREE_TYPE (parm));
4403 
4404       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))
4405 	= is_parameter_pack;
4406     }
4407   else
4408     {
4409       tree t;
4410       parm = TREE_VALUE (TREE_VALUE (parm));
4411 
4412       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
4413 	{
4414 	  t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
4415 	  /* This is for distinguishing between real templates and template
4416 	     template parameters */
4417 	  TREE_TYPE (parm) = t;
4418 	  TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
4419 	  decl = parm;
4420 	}
4421       else
4422 	{
4423 	  t = cxx_make_type (TEMPLATE_TYPE_PARM);
4424 	  /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
4425 	  decl = build_decl (parm_loc,
4426 			     TYPE_DECL, parm, t);
4427 	}
4428 
4429       TYPE_NAME (t) = decl;
4430       TYPE_STUB_DECL (t) = decl;
4431       parm = decl;
4432       TEMPLATE_TYPE_PARM_INDEX (t)
4433 	= build_template_parm_index (idx, processing_template_decl,
4434 				     processing_template_decl,
4435 				     decl, TREE_TYPE (parm));
4436       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
4437       TYPE_CANONICAL (t) = canonical_type_parameter (t);
4438     }
4439   DECL_ARTIFICIAL (decl) = 1;
4440   SET_DECL_TEMPLATE_PARM_P (decl);
4441 
4442   /* Build requirements for the type/template parameter.
4443      This must be done after SET_DECL_TEMPLATE_PARM_P or
4444      process_template_parm could fail. */
4445   tree reqs = finish_shorthand_constraint (parm, constr);
4446 
4447   pushdecl (decl);
4448 
4449   if (defval && TREE_CODE (defval) == OVERLOAD)
4450     lookup_keep (defval, true);
4451 
4452   /* Build the parameter node linking the parameter declaration,
4453      its default argument (if any), and its constraints (if any). */
4454   parm = build_tree_list (defval, parm);
4455   TEMPLATE_PARM_CONSTRAINTS (parm) = reqs;
4456 
4457   return chainon (list, parm);
4458 }
4459 
4460 /* The end of a template parameter list has been reached.  Process the
4461    tree list into a parameter vector, converting each parameter into a more
4462    useful form.	 Type parameters are saved as IDENTIFIER_NODEs, and others
4463    as PARM_DECLs.  */
4464 
4465 tree
end_template_parm_list(tree parms)4466 end_template_parm_list (tree parms)
4467 {
4468   int nparms;
4469   tree parm, next;
4470   tree saved_parmlist = make_tree_vec (list_length (parms));
4471 
4472   /* Pop the dummy parameter level and add the real one.  */
4473   current_template_parms = TREE_CHAIN (current_template_parms);
4474 
4475   current_template_parms
4476     = tree_cons (size_int (processing_template_decl),
4477 		 saved_parmlist, current_template_parms);
4478 
4479   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
4480     {
4481       next = TREE_CHAIN (parm);
4482       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
4483       TREE_CHAIN (parm) = NULL_TREE;
4484     }
4485 
4486   --processing_template_parmlist;
4487 
4488   return saved_parmlist;
4489 }
4490 
4491 // Explicitly indicate the end of the template parameter list. We assume
4492 // that the current template parameters have been constructed and/or
4493 // managed explicitly, as when creating new template template parameters
4494 // from a shorthand constraint.
4495 void
end_template_parm_list()4496 end_template_parm_list ()
4497 {
4498   --processing_template_parmlist;
4499 }
4500 
4501 /* end_template_decl is called after a template declaration is seen.  */
4502 
4503 void
end_template_decl(void)4504 end_template_decl (void)
4505 {
4506   reset_specialization ();
4507 
4508   if (! processing_template_decl)
4509     return;
4510 
4511   /* This matches the pushlevel in begin_template_parm_list.  */
4512   finish_scope ();
4513 
4514   --processing_template_decl;
4515   current_template_parms = TREE_CHAIN (current_template_parms);
4516 }
4517 
4518 /* Takes a TREE_LIST representing a template parameter and convert it
4519    into an argument suitable to be passed to the type substitution
4520    functions.  Note that If the TREE_LIST contains an error_mark
4521    node, the returned argument is error_mark_node.  */
4522 
4523 tree
template_parm_to_arg(tree t)4524 template_parm_to_arg (tree t)
4525 {
4526 
4527   if (t == NULL_TREE
4528       || TREE_CODE (t) != TREE_LIST)
4529     return t;
4530 
4531   if (error_operand_p (TREE_VALUE (t)))
4532     return error_mark_node;
4533 
4534   t = TREE_VALUE (t);
4535 
4536   if (TREE_CODE (t) == TYPE_DECL
4537       || TREE_CODE (t) == TEMPLATE_DECL)
4538     {
4539       t = TREE_TYPE (t);
4540 
4541       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
4542 	{
4543 	  /* Turn this argument into a TYPE_ARGUMENT_PACK
4544 	     with a single element, which expands T.  */
4545 	  tree vec = make_tree_vec (1);
4546 	  if (CHECKING_P)
4547 	    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4548 
4549 	  TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4550 
4551 	  t = cxx_make_type (TYPE_ARGUMENT_PACK);
4552 	  SET_ARGUMENT_PACK_ARGS (t, vec);
4553 	}
4554     }
4555   else
4556     {
4557       t = DECL_INITIAL (t);
4558 
4559       if (TEMPLATE_PARM_PARAMETER_PACK (t))
4560 	{
4561 	  /* Turn this argument into a NONTYPE_ARGUMENT_PACK
4562 	     with a single element, which expands T.  */
4563 	  tree vec = make_tree_vec (1);
4564 	  if (CHECKING_P)
4565 	    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4566 
4567 	  t = convert_from_reference (t);
4568 	  TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4569 
4570 	  t  = make_node (NONTYPE_ARGUMENT_PACK);
4571 	  SET_ARGUMENT_PACK_ARGS (t, vec);
4572 	}
4573       else
4574 	t = convert_from_reference (t);
4575     }
4576   return t;
4577 }
4578 
4579 /* Given a single level of template parameters (a TREE_VEC), return it
4580    as a set of template arguments.  */
4581 
4582 static tree
template_parms_level_to_args(tree parms)4583 template_parms_level_to_args (tree parms)
4584 {
4585   tree a = copy_node (parms);
4586   TREE_TYPE (a) = NULL_TREE;
4587   for (int i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
4588     TREE_VEC_ELT (a, i) = template_parm_to_arg (TREE_VEC_ELT (a, i));
4589 
4590   if (CHECKING_P)
4591     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
4592 
4593   return a;
4594 }
4595 
4596 /* Given a set of template parameters, return them as a set of template
4597    arguments.  The template parameters are represented as a TREE_VEC, in
4598    the form documented in cp-tree.h for template arguments.  */
4599 
4600 static tree
template_parms_to_args(tree parms)4601 template_parms_to_args (tree parms)
4602 {
4603   tree header;
4604   tree args = NULL_TREE;
4605   int length = TMPL_PARMS_DEPTH (parms);
4606   int l = length;
4607 
4608   /* If there is only one level of template parameters, we do not
4609      create a TREE_VEC of TREE_VECs.  Instead, we return a single
4610      TREE_VEC containing the arguments.  */
4611   if (length > 1)
4612     args = make_tree_vec (length);
4613 
4614   for (header = parms; header; header = TREE_CHAIN (header))
4615     {
4616       tree a = template_parms_level_to_args (TREE_VALUE (header));
4617 
4618       if (length > 1)
4619 	TREE_VEC_ELT (args, --l) = a;
4620       else
4621 	args = a;
4622     }
4623 
4624   return args;
4625 }
4626 
4627 /* Within the declaration of a template, return the currently active
4628    template parameters as an argument TREE_VEC.  */
4629 
4630 static tree
current_template_args(void)4631 current_template_args (void)
4632 {
4633   return template_parms_to_args (current_template_parms);
4634 }
4635 
4636 /* Update the declared TYPE by doing any lookups which were thought to be
4637    dependent, but are not now that we know the SCOPE of the declarator.  */
4638 
4639 tree
maybe_update_decl_type(tree orig_type,tree scope)4640 maybe_update_decl_type (tree orig_type, tree scope)
4641 {
4642   tree type = orig_type;
4643 
4644   if (type == NULL_TREE)
4645     return type;
4646 
4647   if (TREE_CODE (orig_type) == TYPE_DECL)
4648     type = TREE_TYPE (type);
4649 
4650   if (scope && TYPE_P (scope) && dependent_type_p (scope)
4651       && dependent_type_p (type)
4652       /* Don't bother building up the args in this case.  */
4653       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
4654     {
4655       /* tsubst in the args corresponding to the template parameters,
4656 	 including auto if present.  Most things will be unchanged, but
4657 	 make_typename_type and tsubst_qualified_id will resolve
4658 	 TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
4659       tree args = current_template_args ();
4660       tree auto_node = type_uses_auto (type);
4661       tree pushed;
4662       if (auto_node)
4663 	{
4664 	  tree auto_vec = make_tree_vec (1);
4665 	  TREE_VEC_ELT (auto_vec, 0) = auto_node;
4666 	  args = add_to_template_args (args, auto_vec);
4667 	}
4668       pushed = push_scope (scope);
4669       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
4670       if (pushed)
4671 	pop_scope (scope);
4672     }
4673 
4674   if (type == error_mark_node)
4675     return orig_type;
4676 
4677   if (TREE_CODE (orig_type) == TYPE_DECL)
4678     {
4679       if (same_type_p (type, TREE_TYPE (orig_type)))
4680 	type = orig_type;
4681       else
4682 	type = TYPE_NAME (type);
4683     }
4684   return type;
4685 }
4686 
4687 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
4688    template PARMS and constraints, CONSTR.  If MEMBER_TEMPLATE_P is true,
4689    the new  template is a member template. */
4690 
4691 tree
build_template_decl(tree decl,tree parms,bool member_template_p)4692 build_template_decl (tree decl, tree parms, bool member_template_p)
4693 {
4694   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
4695   SET_DECL_LANGUAGE (tmpl, DECL_LANGUAGE (decl));
4696   DECL_TEMPLATE_PARMS (tmpl) = parms;
4697   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
4698   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
4699   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
4700 
4701   return tmpl;
4702 }
4703 
4704 struct template_parm_data
4705 {
4706   /* The level of the template parameters we are currently
4707      processing.  */
4708   int level;
4709 
4710   /* The index of the specialization argument we are currently
4711      processing.  */
4712   int current_arg;
4713 
4714   /* An array whose size is the number of template parameters.  The
4715      elements are nonzero if the parameter has been used in any one
4716      of the arguments processed so far.  */
4717   int* parms;
4718 
4719   /* An array whose size is the number of template arguments.  The
4720      elements are nonzero if the argument makes use of template
4721      parameters of this level.  */
4722   int* arg_uses_template_parms;
4723 };
4724 
4725 /* Subroutine of push_template_decl used to see if each template
4726    parameter in a partial specialization is used in the explicit
4727    argument list.  If T is of the LEVEL given in DATA (which is
4728    treated as a template_parm_data*), then DATA->PARMS is marked
4729    appropriately.  */
4730 
4731 static int
mark_template_parm(tree t,void * data)4732 mark_template_parm (tree t, void* data)
4733 {
4734   int level;
4735   int idx;
4736   struct template_parm_data* tpd = (struct template_parm_data*) data;
4737 
4738   template_parm_level_and_index (t, &level, &idx);
4739 
4740   if (level == tpd->level)
4741     {
4742       tpd->parms[idx] = 1;
4743       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
4744     }
4745 
4746   /* In C++17 the type of a non-type argument is a deduced context.  */
4747   if (cxx_dialect >= cxx17
4748       && TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4749     for_each_template_parm (TREE_TYPE (t),
4750 			    &mark_template_parm,
4751 			    data,
4752 			    NULL,
4753 			    /*include_nondeduced_p=*/false);
4754 
4755   /* Return zero so that for_each_template_parm will continue the
4756      traversal of the tree; we want to mark *every* template parm.  */
4757   return 0;
4758 }
4759 
4760 /* Process the partial specialization DECL.  */
4761 
4762 static tree
process_partial_specialization(tree decl)4763 process_partial_specialization (tree decl)
4764 {
4765   tree type = TREE_TYPE (decl);
4766   tree tinfo = get_template_info (decl);
4767   tree maintmpl = TI_TEMPLATE (tinfo);
4768   tree specargs = TI_ARGS (tinfo);
4769   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
4770   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
4771   tree inner_parms;
4772   tree inst;
4773   int nargs = TREE_VEC_LENGTH (inner_args);
4774   int ntparms;
4775   int  i;
4776   bool did_error_intro = false;
4777   struct template_parm_data tpd;
4778   struct template_parm_data tpd2;
4779 
4780   gcc_assert (current_template_parms);
4781 
4782   /* A concept cannot be specialized.  */
4783   if (flag_concepts && variable_concept_p (maintmpl))
4784     {
4785       error ("specialization of variable concept %q#D", maintmpl);
4786       return error_mark_node;
4787     }
4788 
4789   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
4790   ntparms = TREE_VEC_LENGTH (inner_parms);
4791 
4792   /* We check that each of the template parameters given in the
4793      partial specialization is used in the argument list to the
4794      specialization.  For example:
4795 
4796        template <class T> struct S;
4797        template <class T> struct S<T*>;
4798 
4799      The second declaration is OK because `T*' uses the template
4800      parameter T, whereas
4801 
4802        template <class T> struct S<int>;
4803 
4804      is no good.  Even trickier is:
4805 
4806        template <class T>
4807        struct S1
4808        {
4809 	  template <class U>
4810 	  struct S2;
4811 	  template <class U>
4812 	  struct S2<T>;
4813        };
4814 
4815      The S2<T> declaration is actually invalid; it is a
4816      full-specialization.  Of course,
4817 
4818 	  template <class U>
4819 	  struct S2<T (*)(U)>;
4820 
4821      or some such would have been OK.  */
4822   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
4823   tpd.parms = XALLOCAVEC (int, ntparms);
4824   memset (tpd.parms, 0, sizeof (int) * ntparms);
4825 
4826   tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4827   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
4828   for (i = 0; i < nargs; ++i)
4829     {
4830       tpd.current_arg = i;
4831       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
4832 			      &mark_template_parm,
4833 			      &tpd,
4834 			      NULL,
4835 			      /*include_nondeduced_p=*/false);
4836     }
4837   for (i = 0; i < ntparms; ++i)
4838     if (tpd.parms[i] == 0)
4839       {
4840 	/* One of the template parms was not used in a deduced context in the
4841 	   specialization.  */
4842 	if (!did_error_intro)
4843 	  {
4844 	    error ("template parameters not deducible in "
4845 		   "partial specialization:");
4846 	    did_error_intro = true;
4847 	  }
4848 
4849 	inform (input_location, "        %qD",
4850 		TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
4851       }
4852 
4853   if (did_error_intro)
4854     return error_mark_node;
4855 
4856   /* [temp.class.spec]
4857 
4858      The argument list of the specialization shall not be identical to
4859      the implicit argument list of the primary template.  */
4860   tree main_args
4861     = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (maintmpl)));
4862   if (comp_template_args (inner_args, INNERMOST_TEMPLATE_ARGS (main_args))
4863       && (!flag_concepts
4864 	  || !strictly_subsumes (current_template_constraints (),
4865 				 get_constraints (maintmpl))))
4866     {
4867       if (!flag_concepts)
4868         error ("partial specialization %q+D does not specialize "
4869 	       "any template arguments; to define the primary template, "
4870 	       "remove the template argument list", decl);
4871       else
4872         error ("partial specialization %q+D does not specialize any "
4873 	       "template arguments and is not more constrained than "
4874 	       "the primary template; to define the primary template, "
4875 	       "remove the template argument list", decl);
4876       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
4877     }
4878 
4879   /* A partial specialization that replaces multiple parameters of the
4880      primary template with a pack expansion is less specialized for those
4881      parameters.  */
4882   if (nargs < DECL_NTPARMS (maintmpl))
4883     {
4884       error ("partial specialization is not more specialized than the "
4885 	     "primary template because it replaces multiple parameters "
4886 	     "with a pack expansion");
4887       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
4888       /* Avoid crash in process_partial_specialization.  */
4889       return decl;
4890     }
4891 
4892   /* If we aren't in a dependent class, we can actually try deduction.  */
4893   else if (tpd.level == 1
4894 	   /* FIXME we should be able to handle a partial specialization of a
4895 	      partial instantiation, but currently we can't (c++/41727).  */
4896 	   && TMPL_ARGS_DEPTH (specargs) == 1
4897 	   && !get_partial_spec_bindings (maintmpl, maintmpl, specargs))
4898     {
4899       if (permerror (input_location, "partial specialization %qD is not "
4900 		     "more specialized than", decl))
4901 	inform (DECL_SOURCE_LOCATION (maintmpl), "primary template %qD",
4902 		maintmpl);
4903     }
4904 
4905   /* [temp.class.spec]
4906 
4907      A partially specialized non-type argument expression shall not
4908      involve template parameters of the partial specialization except
4909      when the argument expression is a simple identifier.
4910 
4911      The type of a template parameter corresponding to a specialized
4912      non-type argument shall not be dependent on a parameter of the
4913      specialization.
4914 
4915      Also, we verify that pack expansions only occur at the
4916      end of the argument list.  */
4917   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
4918   tpd2.parms = 0;
4919   for (i = 0; i < nargs; ++i)
4920     {
4921       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
4922       tree arg = TREE_VEC_ELT (inner_args, i);
4923       tree packed_args = NULL_TREE;
4924       int j, len = 1;
4925 
4926       if (ARGUMENT_PACK_P (arg))
4927         {
4928           /* Extract the arguments from the argument pack. We'll be
4929              iterating over these in the following loop.  */
4930           packed_args = ARGUMENT_PACK_ARGS (arg);
4931           len = TREE_VEC_LENGTH (packed_args);
4932         }
4933 
4934       for (j = 0; j < len; j++)
4935         {
4936           if (packed_args)
4937             /* Get the Jth argument in the parameter pack.  */
4938             arg = TREE_VEC_ELT (packed_args, j);
4939 
4940           if (PACK_EXPANSION_P (arg))
4941             {
4942               /* Pack expansions must come at the end of the
4943                  argument list.  */
4944               if ((packed_args && j < len - 1)
4945                   || (!packed_args && i < nargs - 1))
4946                 {
4947                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4948                     error ("parameter pack argument %qE must be at the "
4949 			   "end of the template argument list", arg);
4950                   else
4951                     error ("parameter pack argument %qT must be at the "
4952 			   "end of the template argument list", arg);
4953                 }
4954             }
4955 
4956           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4957             /* We only care about the pattern.  */
4958             arg = PACK_EXPANSION_PATTERN (arg);
4959 
4960           if (/* These first two lines are the `non-type' bit.  */
4961               !TYPE_P (arg)
4962               && TREE_CODE (arg) != TEMPLATE_DECL
4963               /* This next two lines are the `argument expression is not just a
4964                  simple identifier' condition and also the `specialized
4965                  non-type argument' bit.  */
4966               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX
4967 	      && !(REFERENCE_REF_P (arg)
4968 		   && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_PARM_INDEX))
4969             {
4970               if ((!packed_args && tpd.arg_uses_template_parms[i])
4971                   || (packed_args && uses_template_parms (arg)))
4972                 error ("template argument %qE involves template parameter(s)",
4973                        arg);
4974               else
4975                 {
4976                   /* Look at the corresponding template parameter,
4977                      marking which template parameters its type depends
4978                      upon.  */
4979                   tree type = TREE_TYPE (parm);
4980 
4981                   if (!tpd2.parms)
4982                     {
4983                       /* We haven't yet initialized TPD2.  Do so now.  */
4984                       tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4985                       /* The number of parameters here is the number in the
4986                          main template, which, as checked in the assertion
4987                          above, is NARGS.  */
4988                       tpd2.parms = XALLOCAVEC (int, nargs);
4989                       tpd2.level =
4990                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
4991                     }
4992 
4993                   /* Mark the template parameters.  But this time, we're
4994                      looking for the template parameters of the main
4995                      template, not in the specialization.  */
4996                   tpd2.current_arg = i;
4997                   tpd2.arg_uses_template_parms[i] = 0;
4998                   memset (tpd2.parms, 0, sizeof (int) * nargs);
4999                   for_each_template_parm (type,
5000                                           &mark_template_parm,
5001                                           &tpd2,
5002                                           NULL,
5003 					  /*include_nondeduced_p=*/false);
5004 
5005                   if (tpd2.arg_uses_template_parms [i])
5006                     {
5007                       /* The type depended on some template parameters.
5008                          If they are fully specialized in the
5009                          specialization, that's OK.  */
5010                       int j;
5011                       int count = 0;
5012                       for (j = 0; j < nargs; ++j)
5013                         if (tpd2.parms[j] != 0
5014                             && tpd.arg_uses_template_parms [j])
5015                           ++count;
5016                       if (count != 0)
5017                         error_n (input_location, count,
5018                                  "type %qT of template argument %qE depends "
5019                                  "on a template parameter",
5020                                  "type %qT of template argument %qE depends "
5021                                  "on template parameters",
5022                                  type,
5023                                  arg);
5024                     }
5025                 }
5026             }
5027         }
5028     }
5029 
5030   /* We should only get here once.  */
5031   if (TREE_CODE (decl) == TYPE_DECL)
5032     gcc_assert (!COMPLETE_TYPE_P (type));
5033 
5034   // Build the template decl.
5035   tree tmpl = build_template_decl (decl, current_template_parms,
5036 				   DECL_MEMBER_TEMPLATE_P (maintmpl));
5037   TREE_TYPE (tmpl) = type;
5038   DECL_TEMPLATE_RESULT (tmpl) = decl;
5039   SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5040   DECL_TEMPLATE_INFO (tmpl) = build_template_info (maintmpl, specargs);
5041   DECL_PRIMARY_TEMPLATE (tmpl) = maintmpl;
5042 
5043   /* Give template template parms a DECL_CONTEXT of the template
5044      for which they are a parameter.  */
5045   for (i = 0; i < ntparms; ++i)
5046     {
5047       tree parm = TREE_VALUE (TREE_VEC_ELT (inner_parms, i));
5048       if (TREE_CODE (parm) == TEMPLATE_DECL)
5049 	DECL_CONTEXT (parm) = tmpl;
5050     }
5051 
5052   if (VAR_P (decl))
5053     /* We didn't register this in check_explicit_specialization so we could
5054        wait until the constraints were set.  */
5055     decl = register_specialization (decl, maintmpl, specargs, false, 0);
5056   else
5057     associate_classtype_constraints (type);
5058 
5059   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
5060     = tree_cons (specargs, tmpl,
5061                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
5062   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
5063 
5064   for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
5065        inst = TREE_CHAIN (inst))
5066     {
5067       tree instance = TREE_VALUE (inst);
5068       if (TYPE_P (instance)
5069 	  ? (COMPLETE_TYPE_P (instance)
5070 	     && CLASSTYPE_IMPLICIT_INSTANTIATION (instance))
5071 	  : DECL_TEMPLATE_INSTANTIATION (instance))
5072 	{
5073 	  tree spec = most_specialized_partial_spec (instance, tf_none);
5074 	  tree inst_decl = (DECL_P (instance)
5075 			    ? instance : TYPE_NAME (instance));
5076 	  if (!spec)
5077 	    /* OK */;
5078 	  else if (spec == error_mark_node)
5079 	    permerror (input_location,
5080 		       "declaration of %qD ambiguates earlier template "
5081 		       "instantiation for %qD", decl, inst_decl);
5082 	  else if (TREE_VALUE (spec) == tmpl)
5083 	    permerror (input_location,
5084 		       "partial specialization of %qD after instantiation "
5085 		       "of %qD", decl, inst_decl);
5086 	}
5087     }
5088 
5089   return decl;
5090 }
5091 
5092 /* PARM is a template parameter of some form; return the corresponding
5093    TEMPLATE_PARM_INDEX.  */
5094 
5095 static tree
get_template_parm_index(tree parm)5096 get_template_parm_index (tree parm)
5097 {
5098   if (TREE_CODE (parm) == PARM_DECL
5099       || TREE_CODE (parm) == CONST_DECL)
5100     parm = DECL_INITIAL (parm);
5101   else if (TREE_CODE (parm) == TYPE_DECL
5102 	   || TREE_CODE (parm) == TEMPLATE_DECL)
5103     parm = TREE_TYPE (parm);
5104   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
5105       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM
5106       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
5107     parm = TEMPLATE_TYPE_PARM_INDEX (parm);
5108   gcc_assert (TREE_CODE (parm) == TEMPLATE_PARM_INDEX);
5109   return parm;
5110 }
5111 
5112 /* Subroutine of fixed_parameter_pack_p below.  Look for any template
5113    parameter packs used by the template parameter PARM.  */
5114 
5115 static void
fixed_parameter_pack_p_1(tree parm,struct find_parameter_pack_data * ppd)5116 fixed_parameter_pack_p_1 (tree parm, struct find_parameter_pack_data *ppd)
5117 {
5118   /* A type parm can't refer to another parm.  */
5119   if (TREE_CODE (parm) == TYPE_DECL || parm == error_mark_node)
5120     return;
5121   else if (TREE_CODE (parm) == PARM_DECL)
5122     {
5123       cp_walk_tree (&TREE_TYPE (parm), &find_parameter_packs_r,
5124 		    ppd, ppd->visited);
5125       return;
5126     }
5127 
5128   gcc_assert (TREE_CODE (parm) == TEMPLATE_DECL);
5129 
5130   tree vec = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
5131   for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
5132     fixed_parameter_pack_p_1 (TREE_VALUE (TREE_VEC_ELT (vec, i)), ppd);
5133 }
5134 
5135 /* PARM is a template parameter pack.  Return any parameter packs used in
5136    its type or the type of any of its template parameters.  If there are
5137    any such packs, it will be instantiated into a fixed template parameter
5138    list by partial instantiation rather than be fully deduced.  */
5139 
5140 tree
fixed_parameter_pack_p(tree parm)5141 fixed_parameter_pack_p (tree parm)
5142 {
5143   /* This can only be true in a member template.  */
5144   if (TEMPLATE_PARM_ORIG_LEVEL (get_template_parm_index (parm)) < 2)
5145     return NULL_TREE;
5146   /* This can only be true for a parameter pack.  */
5147   if (!template_parameter_pack_p (parm))
5148     return NULL_TREE;
5149   /* A type parm can't refer to another parm.  */
5150   if (TREE_CODE (parm) == TYPE_DECL)
5151     return NULL_TREE;
5152 
5153   tree parameter_packs = NULL_TREE;
5154   struct find_parameter_pack_data ppd;
5155   ppd.parameter_packs = &parameter_packs;
5156   ppd.visited = new hash_set<tree>;
5157   ppd.type_pack_expansion_p = false;
5158 
5159   fixed_parameter_pack_p_1 (parm, &ppd);
5160 
5161   delete ppd.visited;
5162   return parameter_packs;
5163 }
5164 
5165 /* Check that a template declaration's use of default arguments and
5166    parameter packs is not invalid.  Here, PARMS are the template
5167    parameters.  IS_PRIMARY is true if DECL is the thing declared by
5168    a primary template.  IS_PARTIAL is true if DECL is a partial
5169    specialization.
5170 
5171    IS_FRIEND_DECL is nonzero if DECL is either a non-defining friend
5172    function template declaration or a friend class template
5173    declaration.  In the function case, 1 indicates a declaration, 2
5174    indicates a redeclaration.  When IS_FRIEND_DECL=2, no errors are
5175    emitted for extraneous default arguments.
5176 
5177    Returns TRUE if there were no errors found, FALSE otherwise. */
5178 
5179 bool
check_default_tmpl_args(tree decl,tree parms,bool is_primary,bool is_partial,int is_friend_decl)5180 check_default_tmpl_args (tree decl, tree parms, bool is_primary,
5181                          bool is_partial, int is_friend_decl)
5182 {
5183   const char *msg;
5184   int last_level_to_check;
5185   tree parm_level;
5186   bool no_errors = true;
5187 
5188   /* [temp.param]
5189 
5190      A default template-argument shall not be specified in a
5191      function template declaration or a function template definition, nor
5192      in the template-parameter-list of the definition of a member of a
5193      class template.  */
5194 
5195   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL
5196       || (TREE_CODE (decl) == FUNCTION_DECL && DECL_LOCAL_FUNCTION_P (decl)))
5197     /* You can't have a function template declaration in a local
5198        scope, nor you can you define a member of a class template in a
5199        local scope.  */
5200     return true;
5201 
5202   if ((TREE_CODE (decl) == TYPE_DECL
5203        && TREE_TYPE (decl)
5204        && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5205       || (TREE_CODE (decl) == FUNCTION_DECL
5206 	  && LAMBDA_FUNCTION_P (decl)))
5207     /* A lambda doesn't have an explicit declaration; don't complain
5208        about the parms of the enclosing class.  */
5209     return true;
5210 
5211   if (current_class_type
5212       && !TYPE_BEING_DEFINED (current_class_type)
5213       && DECL_LANG_SPECIFIC (decl)
5214       && DECL_DECLARES_FUNCTION_P (decl)
5215       /* If this is either a friend defined in the scope of the class
5216 	 or a member function.  */
5217       && (DECL_FUNCTION_MEMBER_P (decl)
5218 	  ? same_type_p (DECL_CONTEXT (decl), current_class_type)
5219 	  : DECL_FRIEND_CONTEXT (decl)
5220 	  ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
5221 	  : false)
5222       /* And, if it was a member function, it really was defined in
5223 	 the scope of the class.  */
5224       && (!DECL_FUNCTION_MEMBER_P (decl)
5225 	  || DECL_INITIALIZED_IN_CLASS_P (decl)))
5226     /* We already checked these parameters when the template was
5227        declared, so there's no need to do it again now.  This function
5228        was defined in class scope, but we're processing its body now
5229        that the class is complete.  */
5230     return true;
5231 
5232   /* Core issue 226 (C++0x only): the following only applies to class
5233      templates.  */
5234   if (is_primary
5235       && ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL))
5236     {
5237       /* [temp.param]
5238 
5239          If a template-parameter has a default template-argument, all
5240          subsequent template-parameters shall have a default
5241          template-argument supplied.  */
5242       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
5243         {
5244           tree inner_parms = TREE_VALUE (parm_level);
5245           int ntparms = TREE_VEC_LENGTH (inner_parms);
5246           int seen_def_arg_p = 0;
5247           int i;
5248 
5249           for (i = 0; i < ntparms; ++i)
5250             {
5251               tree parm = TREE_VEC_ELT (inner_parms, i);
5252 
5253               if (parm == error_mark_node)
5254                 continue;
5255 
5256               if (TREE_PURPOSE (parm))
5257                 seen_def_arg_p = 1;
5258               else if (seen_def_arg_p
5259 		       && !template_parameter_pack_p (TREE_VALUE (parm)))
5260                 {
5261                   error ("no default argument for %qD", TREE_VALUE (parm));
5262                   /* For better subsequent error-recovery, we indicate that
5263                      there should have been a default argument.  */
5264                   TREE_PURPOSE (parm) = error_mark_node;
5265                   no_errors = false;
5266                 }
5267 	      else if (!is_partial
5268 		       && !is_friend_decl
5269 		       /* Don't complain about an enclosing partial
5270 			  specialization.  */
5271 		       && parm_level == parms
5272 		       && TREE_CODE (decl) == TYPE_DECL
5273 		       && i < ntparms - 1
5274 		       && template_parameter_pack_p (TREE_VALUE (parm))
5275 		       /* A fixed parameter pack will be partially
5276 			  instantiated into a fixed length list.  */
5277 		       && !fixed_parameter_pack_p (TREE_VALUE (parm)))
5278 		{
5279 		  /* A primary class template can only have one
5280 		     parameter pack, at the end of the template
5281 		     parameter list.  */
5282 
5283 		  error ("parameter pack %q+D must be at the end of the"
5284 			 " template parameter list", TREE_VALUE (parm));
5285 
5286 		  TREE_VALUE (TREE_VEC_ELT (inner_parms, i))
5287 		    = error_mark_node;
5288 		  no_errors = false;
5289 		}
5290             }
5291         }
5292     }
5293 
5294   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
5295       || is_partial
5296       || !is_primary
5297       || is_friend_decl)
5298     /* For an ordinary class template, default template arguments are
5299        allowed at the innermost level, e.g.:
5300 	 template <class T = int>
5301 	 struct S {};
5302        but, in a partial specialization, they're not allowed even
5303        there, as we have in [temp.class.spec]:
5304 
5305 	 The template parameter list of a specialization shall not
5306 	 contain default template argument values.
5307 
5308        So, for a partial specialization, or for a function template
5309        (in C++98/C++03), we look at all of them.  */
5310     ;
5311   else
5312     /* But, for a primary class template that is not a partial
5313        specialization we look at all template parameters except the
5314        innermost ones.  */
5315     parms = TREE_CHAIN (parms);
5316 
5317   /* Figure out what error message to issue.  */
5318   if (is_friend_decl == 2)
5319     msg = G_("default template arguments may not be used in function template "
5320 	     "friend re-declaration");
5321   else if (is_friend_decl)
5322     msg = G_("default template arguments may not be used in template "
5323 	     "friend declarations");
5324   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
5325     msg = G_("default template arguments may not be used in function templates "
5326 	     "without -std=c++11 or -std=gnu++11");
5327   else if (is_partial)
5328     msg = G_("default template arguments may not be used in "
5329 	     "partial specializations");
5330   else if (current_class_type && CLASSTYPE_IS_TEMPLATE (current_class_type))
5331     msg = G_("default argument for template parameter for class enclosing %qD");
5332   else
5333     /* Per [temp.param]/9, "A default template-argument shall not be
5334        specified in the template-parameter-lists of the definition of
5335        a member of a class template that appears outside of the member's
5336        class.", thus if we aren't handling a member of a class template
5337        there is no need to examine the parameters.  */
5338     return true;
5339 
5340   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
5341     /* If we're inside a class definition, there's no need to
5342        examine the parameters to the class itself.  On the one
5343        hand, they will be checked when the class is defined, and,
5344        on the other, default arguments are valid in things like:
5345 	 template <class T = double>
5346 	 struct S { template <class U> void f(U); };
5347        Here the default argument for `S' has no bearing on the
5348        declaration of `f'.  */
5349     last_level_to_check = template_class_depth (current_class_type) + 1;
5350   else
5351     /* Check everything.  */
5352     last_level_to_check = 0;
5353 
5354   for (parm_level = parms;
5355        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
5356        parm_level = TREE_CHAIN (parm_level))
5357     {
5358       tree inner_parms = TREE_VALUE (parm_level);
5359       int i;
5360       int ntparms;
5361 
5362       ntparms = TREE_VEC_LENGTH (inner_parms);
5363       for (i = 0; i < ntparms; ++i)
5364         {
5365           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
5366             continue;
5367 
5368 	  if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
5369 	    {
5370 	      if (msg)
5371 	        {
5372                   no_errors = false;
5373                   if (is_friend_decl == 2)
5374                     return no_errors;
5375 
5376 		  error (msg, decl);
5377 		  msg = 0;
5378 	        }
5379 
5380 	      /* Clear out the default argument so that we are not
5381 	         confused later.  */
5382 	      TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
5383 	    }
5384         }
5385 
5386       /* At this point, if we're still interested in issuing messages,
5387 	 they must apply to classes surrounding the object declared.  */
5388       if (msg)
5389 	msg = G_("default argument for template parameter for class "
5390 		 "enclosing %qD");
5391     }
5392 
5393   return no_errors;
5394 }
5395 
5396 /* Worker for push_template_decl_real, called via
5397    for_each_template_parm.  DATA is really an int, indicating the
5398    level of the parameters we are interested in.  If T is a template
5399    parameter of that level, return nonzero.  */
5400 
5401 static int
template_parm_this_level_p(tree t,void * data)5402 template_parm_this_level_p (tree t, void* data)
5403 {
5404   int this_level = *(int *)data;
5405   int level;
5406 
5407   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5408     level = TEMPLATE_PARM_LEVEL (t);
5409   else
5410     level = TEMPLATE_TYPE_LEVEL (t);
5411   return level == this_level;
5412 }
5413 
5414 /* Worker for uses_outer_template_parms, called via for_each_template_parm.
5415    DATA is really an int, indicating the innermost outer level of parameters.
5416    If T is a template parameter of that level or further out, return
5417    nonzero.  */
5418 
5419 static int
template_parm_outer_level(tree t,void * data)5420 template_parm_outer_level (tree t, void *data)
5421 {
5422   int this_level = *(int *)data;
5423   int level;
5424 
5425   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5426     level = TEMPLATE_PARM_LEVEL (t);
5427   else
5428     level = TEMPLATE_TYPE_LEVEL (t);
5429   return level <= this_level;
5430 }
5431 
5432 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
5433    parameters given by current_template_args, or reuses a
5434    previously existing one, if appropriate.  Returns the DECL, or an
5435    equivalent one, if it is replaced via a call to duplicate_decls.
5436 
5437    If IS_FRIEND is true, DECL is a friend declaration.  */
5438 
5439 tree
push_template_decl_real(tree decl,bool is_friend)5440 push_template_decl_real (tree decl, bool is_friend)
5441 {
5442   tree tmpl;
5443   tree args;
5444   tree info;
5445   tree ctx;
5446   bool is_primary;
5447   bool is_partial;
5448   int new_template_p = 0;
5449   /* True if the template is a member template, in the sense of
5450      [temp.mem].  */
5451   bool member_template_p = false;
5452 
5453   if (decl == error_mark_node || !current_template_parms)
5454     return error_mark_node;
5455 
5456   /* See if this is a partial specialization.  */
5457   is_partial = ((DECL_IMPLICIT_TYPEDEF_P (decl)
5458 		 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
5459 		 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
5460 		|| (VAR_P (decl)
5461 		    && DECL_LANG_SPECIFIC (decl)
5462 		    && DECL_TEMPLATE_SPECIALIZATION (decl)
5463 		    && TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl))));
5464 
5465   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
5466     is_friend = true;
5467 
5468   if (is_friend)
5469     /* For a friend, we want the context of the friend, not
5470        the type of which it is a friend.  */
5471     ctx = CP_DECL_CONTEXT (decl);
5472   else if (CP_DECL_CONTEXT (decl)
5473 	   && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
5474     /* In the case of a virtual function, we want the class in which
5475        it is defined.  */
5476     ctx = CP_DECL_CONTEXT (decl);
5477   else
5478     /* Otherwise, if we're currently defining some class, the DECL
5479        is assumed to be a member of the class.  */
5480     ctx = current_scope ();
5481 
5482   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
5483     ctx = NULL_TREE;
5484 
5485   if (!DECL_CONTEXT (decl))
5486     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5487 
5488   /* See if this is a primary template.  */
5489   if (is_friend && ctx
5490       && uses_template_parms_level (ctx, processing_template_decl))
5491     /* A friend template that specifies a class context, i.e.
5492          template <typename T> friend void A<T>::f();
5493        is not primary.  */
5494     is_primary = false;
5495   else if (TREE_CODE (decl) == TYPE_DECL
5496 	   && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5497     is_primary = false;
5498   else
5499     is_primary = template_parm_scope_p ();
5500 
5501   if (is_primary)
5502     {
5503       warning (OPT_Wtemplates, "template %qD declared", decl);
5504 
5505       if (DECL_CLASS_SCOPE_P (decl))
5506 	member_template_p = true;
5507       if (TREE_CODE (decl) == TYPE_DECL
5508 	  && anon_aggrname_p (DECL_NAME (decl)))
5509 	{
5510 	  error ("template class without a name");
5511 	  return error_mark_node;
5512 	}
5513       else if (TREE_CODE (decl) == FUNCTION_DECL)
5514 	{
5515 	  if (member_template_p)
5516 	    {
5517 	      if (DECL_OVERRIDE_P (decl) || DECL_FINAL_P (decl))
5518 		error ("member template %qD may not have virt-specifiers", decl);
5519 	    }
5520 	  if (DECL_DESTRUCTOR_P (decl))
5521 	    {
5522 	      /* [temp.mem]
5523 
5524 		 A destructor shall not be a member template.  */
5525 	      error ("destructor %qD declared as member template", decl);
5526 	      return error_mark_node;
5527 	    }
5528 	  if (IDENTIFIER_NEWDEL_OP_P (DECL_NAME (decl))
5529 	      && (!prototype_p (TREE_TYPE (decl))
5530 		  || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
5531 		  || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5532 		  || (TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5533 		      == void_list_node)))
5534 	    {
5535 	      /* [basic.stc.dynamic.allocation]
5536 
5537 		 An allocation function can be a function
5538 		 template. ... Template allocation functions shall
5539 		 have two or more parameters.  */
5540 	      error ("invalid template declaration of %qD", decl);
5541 	      return error_mark_node;
5542 	    }
5543 	}
5544       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5545 	       && CLASS_TYPE_P (TREE_TYPE (decl)))
5546 	{
5547 	  /* Class template, set TEMPLATE_TYPE_PARM_FOR_CLASS.  */
5548 	  tree parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
5549 	  for (int i = 0; i < TREE_VEC_LENGTH (parms); ++i)
5550 	    {
5551 	      tree t = TREE_VALUE (TREE_VEC_ELT (parms, i));
5552 	      if (TREE_CODE (t) == TYPE_DECL)
5553 		t = TREE_TYPE (t);
5554 	      if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
5555 		TEMPLATE_TYPE_PARM_FOR_CLASS (t) = true;
5556 	    }
5557 	}
5558       else if (TREE_CODE (decl) == TYPE_DECL
5559 	       && TYPE_DECL_ALIAS_P (decl))
5560 	/* alias-declaration */
5561 	gcc_assert (!DECL_ARTIFICIAL (decl));
5562       else if (VAR_P (decl))
5563 	/* C++14 variable template. */;
5564       else
5565 	{
5566 	  error ("template declaration of %q#D", decl);
5567 	  return error_mark_node;
5568 	}
5569     }
5570 
5571   /* Check to see that the rules regarding the use of default
5572      arguments are not being violated.  We check args for a friend
5573      functions when we know whether it's a definition, introducing
5574      declaration or re-declaration.  */
5575   if (!is_friend || TREE_CODE (decl) != FUNCTION_DECL)
5576     check_default_tmpl_args (decl, current_template_parms,
5577 			     is_primary, is_partial, is_friend);
5578 
5579   /* Ensure that there are no parameter packs in the type of this
5580      declaration that have not been expanded.  */
5581   if (TREE_CODE (decl) == FUNCTION_DECL)
5582     {
5583       /* Check each of the arguments individually to see if there are
5584          any bare parameter packs.  */
5585       tree type = TREE_TYPE (decl);
5586       tree arg = DECL_ARGUMENTS (decl);
5587       tree argtype = TYPE_ARG_TYPES (type);
5588 
5589       while (arg && argtype)
5590         {
5591           if (!DECL_PACK_P (arg)
5592               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
5593             {
5594             /* This is a PARM_DECL that contains unexpanded parameter
5595                packs. We have already complained about this in the
5596                check_for_bare_parameter_packs call, so just replace
5597                these types with ERROR_MARK_NODE.  */
5598               TREE_TYPE (arg) = error_mark_node;
5599               TREE_VALUE (argtype) = error_mark_node;
5600             }
5601 
5602           arg = DECL_CHAIN (arg);
5603           argtype = TREE_CHAIN (argtype);
5604         }
5605 
5606       /* Check for bare parameter packs in the return type and the
5607          exception specifiers.  */
5608       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
5609 	/* Errors were already issued, set return type to int
5610 	   as the frontend doesn't expect error_mark_node as
5611 	   the return type.  */
5612 	TREE_TYPE (type) = integer_type_node;
5613       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
5614 	TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
5615     }
5616   else if (check_for_bare_parameter_packs ((TREE_CODE (decl) == TYPE_DECL
5617 					    && TYPE_DECL_ALIAS_P (decl))
5618 					   ? DECL_ORIGINAL_TYPE (decl)
5619 					   : TREE_TYPE (decl)))
5620     {
5621       TREE_TYPE (decl) = error_mark_node;
5622       return error_mark_node;
5623     }
5624 
5625   if (is_partial)
5626     return process_partial_specialization (decl);
5627 
5628   args = current_template_args ();
5629 
5630   if (!ctx
5631       || TREE_CODE (ctx) == FUNCTION_DECL
5632       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
5633       || (TREE_CODE (decl) == TYPE_DECL
5634 	  && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5635       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
5636     {
5637       if (DECL_LANG_SPECIFIC (decl)
5638 	  && DECL_TEMPLATE_INFO (decl)
5639 	  && DECL_TI_TEMPLATE (decl))
5640 	tmpl = DECL_TI_TEMPLATE (decl);
5641       /* If DECL is a TYPE_DECL for a class-template, then there won't
5642 	 be DECL_LANG_SPECIFIC.  The information equivalent to
5643 	 DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
5644       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5645 	       && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
5646 	       && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
5647 	{
5648 	  /* Since a template declaration already existed for this
5649 	     class-type, we must be redeclaring it here.  Make sure
5650 	     that the redeclaration is valid.  */
5651 	  redeclare_class_template (TREE_TYPE (decl),
5652 				    current_template_parms,
5653 				    current_template_constraints ());
5654 	  /* We don't need to create a new TEMPLATE_DECL; just use the
5655 	     one we already had.  */
5656 	  tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
5657 	}
5658       else
5659 	{
5660 	  tmpl = build_template_decl (decl, current_template_parms,
5661 				      member_template_p);
5662 	  new_template_p = 1;
5663 
5664 	  if (DECL_LANG_SPECIFIC (decl)
5665 	      && DECL_TEMPLATE_SPECIALIZATION (decl))
5666 	    {
5667 	      /* A specialization of a member template of a template
5668 		 class.  */
5669 	      SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5670 	      DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
5671 	      DECL_TEMPLATE_INFO (decl) = NULL_TREE;
5672 	    }
5673 	}
5674     }
5675   else
5676     {
5677       tree a, t, current, parms;
5678       int i;
5679       tree tinfo = get_template_info (decl);
5680 
5681       if (!tinfo)
5682 	{
5683 	  error ("template definition of non-template %q#D", decl);
5684 	  return error_mark_node;
5685 	}
5686 
5687       tmpl = TI_TEMPLATE (tinfo);
5688 
5689       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
5690 	  && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
5691 	  && DECL_TEMPLATE_SPECIALIZATION (decl)
5692 	  && DECL_MEMBER_TEMPLATE_P (tmpl))
5693 	{
5694 	  tree new_tmpl;
5695 
5696 	  /* The declaration is a specialization of a member
5697 	     template, declared outside the class.  Therefore, the
5698 	     innermost template arguments will be NULL, so we
5699 	     replace them with the arguments determined by the
5700 	     earlier call to check_explicit_specialization.  */
5701 	  args = DECL_TI_ARGS (decl);
5702 
5703 	  new_tmpl
5704 	    = build_template_decl (decl, current_template_parms,
5705 				   member_template_p);
5706 	  DECL_TEMPLATE_RESULT (new_tmpl) = decl;
5707 	  TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
5708 	  DECL_TI_TEMPLATE (decl) = new_tmpl;
5709 	  SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
5710 	  DECL_TEMPLATE_INFO (new_tmpl)
5711 	    = build_template_info (tmpl, args);
5712 
5713 	  register_specialization (new_tmpl,
5714 				   most_general_template (tmpl),
5715 				   args,
5716 				   is_friend, 0);
5717 	  return decl;
5718 	}
5719 
5720       /* Make sure the template headers we got make sense.  */
5721 
5722       parms = DECL_TEMPLATE_PARMS (tmpl);
5723       i = TMPL_PARMS_DEPTH (parms);
5724       if (TMPL_ARGS_DEPTH (args) != i)
5725 	{
5726 	  error ("expected %d levels of template parms for %q#D, got %d",
5727 		 i, decl, TMPL_ARGS_DEPTH (args));
5728 	  DECL_INTERFACE_KNOWN (decl) = 1;
5729 	  return error_mark_node;
5730 	}
5731       else
5732 	for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
5733 	  {
5734 	    a = TMPL_ARGS_LEVEL (args, i);
5735 	    t = INNERMOST_TEMPLATE_PARMS (parms);
5736 
5737 	    if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
5738 	      {
5739 		if (current == decl)
5740 		  error ("got %d template parameters for %q#D",
5741 			 TREE_VEC_LENGTH (a), decl);
5742 		else
5743 		  error ("got %d template parameters for %q#T",
5744 			 TREE_VEC_LENGTH (a), current);
5745 		error ("  but %d required", TREE_VEC_LENGTH (t));
5746 		/* Avoid crash in import_export_decl.  */
5747 		DECL_INTERFACE_KNOWN (decl) = 1;
5748 		return error_mark_node;
5749 	      }
5750 
5751 	    if (current == decl)
5752 	      current = ctx;
5753 	    else if (current == NULL_TREE)
5754 	      /* Can happen in erroneous input.  */
5755 	      break;
5756 	    else
5757 	      current = get_containing_scope (current);
5758 	  }
5759 
5760       /* Check that the parms are used in the appropriate qualifying scopes
5761 	 in the declarator.  */
5762       if (!comp_template_args
5763 	  (TI_ARGS (tinfo),
5764 	   TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
5765 	{
5766 	  error ("template arguments to %qD do not match original "
5767 		 "template %qD", decl, DECL_TEMPLATE_RESULT (tmpl));
5768 	  if (!uses_template_parms (TI_ARGS (tinfo)))
5769 	    inform (input_location, "use %<template<>%> for"
5770 		    " an explicit specialization");
5771 	  /* Avoid crash in import_export_decl.  */
5772 	  DECL_INTERFACE_KNOWN (decl) = 1;
5773 	  return error_mark_node;
5774 	}
5775     }
5776 
5777   DECL_TEMPLATE_RESULT (tmpl) = decl;
5778   TREE_TYPE (tmpl) = TREE_TYPE (decl);
5779 
5780   /* Push template declarations for global functions and types.  Note
5781      that we do not try to push a global template friend declared in a
5782      template class; such a thing may well depend on the template
5783      parameters of the class.  */
5784   if (new_template_p && !ctx
5785       && !(is_friend && template_class_depth (current_class_type) > 0))
5786     {
5787       tmpl = pushdecl_namespace_level (tmpl, is_friend);
5788       if (tmpl == error_mark_node)
5789 	return error_mark_node;
5790 
5791       /* Hide template friend classes that haven't been declared yet.  */
5792       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
5793 	{
5794 	  DECL_ANTICIPATED (tmpl) = 1;
5795 	  DECL_FRIEND_P (tmpl) = 1;
5796 	}
5797     }
5798 
5799   if (is_primary)
5800     {
5801       tree parms = DECL_TEMPLATE_PARMS (tmpl);
5802 
5803       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
5804 
5805       /* Give template template parms a DECL_CONTEXT of the template
5806 	 for which they are a parameter.  */
5807       parms = INNERMOST_TEMPLATE_PARMS (parms);
5808       for (int i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
5809 	{
5810 	  tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5811 	  if (TREE_CODE (parm) == TEMPLATE_DECL)
5812 	    DECL_CONTEXT (parm) = tmpl;
5813 	}
5814 
5815       if (TREE_CODE (decl) == TYPE_DECL
5816 	  && TYPE_DECL_ALIAS_P (decl)
5817 	  && complex_alias_template_p (tmpl))
5818 	TEMPLATE_DECL_COMPLEX_ALIAS_P (tmpl) = true;
5819     }
5820 
5821   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
5822      back to its most general template.  If TMPL is a specialization,
5823      ARGS may only have the innermost set of arguments.  Add the missing
5824      argument levels if necessary.  */
5825   if (DECL_TEMPLATE_INFO (tmpl))
5826     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
5827 
5828   info = build_template_info (tmpl, args);
5829 
5830   if (DECL_IMPLICIT_TYPEDEF_P (decl))
5831     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
5832   else
5833     {
5834       if (is_primary)
5835 	retrofit_lang_decl (decl);
5836       if (DECL_LANG_SPECIFIC (decl))
5837 	DECL_TEMPLATE_INFO (decl) = info;
5838     }
5839 
5840   if (flag_implicit_templates
5841       && !is_friend
5842       && TREE_PUBLIC (decl)
5843       && VAR_OR_FUNCTION_DECL_P (decl))
5844     /* Set DECL_COMDAT on template instantiations; if we force
5845        them to be emitted by explicit instantiation or -frepo,
5846        mark_needed will tell cgraph to do the right thing.  */
5847     DECL_COMDAT (decl) = true;
5848 
5849   return DECL_TEMPLATE_RESULT (tmpl);
5850 }
5851 
5852 tree
push_template_decl(tree decl)5853 push_template_decl (tree decl)
5854 {
5855   return push_template_decl_real (decl, false);
5856 }
5857 
5858 /* FN is an inheriting constructor that inherits from the constructor
5859    template INHERITED; turn FN into a constructor template with a matching
5860    template header.  */
5861 
5862 tree
add_inherited_template_parms(tree fn,tree inherited)5863 add_inherited_template_parms (tree fn, tree inherited)
5864 {
5865   tree inner_parms
5866     = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (inherited));
5867   inner_parms = copy_node (inner_parms);
5868   tree parms
5869     = tree_cons (size_int (processing_template_decl + 1),
5870 		 inner_parms, current_template_parms);
5871   tree tmpl = build_template_decl (fn, parms, /*member*/true);
5872   tree args = template_parms_to_args (parms);
5873   DECL_TEMPLATE_INFO (fn) = build_template_info (tmpl, args);
5874   TREE_TYPE (tmpl) = TREE_TYPE (fn);
5875   DECL_TEMPLATE_RESULT (tmpl) = fn;
5876   DECL_ARTIFICIAL (tmpl) = true;
5877   DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
5878   return tmpl;
5879 }
5880 
5881 /* Called when a class template TYPE is redeclared with the indicated
5882    template PARMS, e.g.:
5883 
5884      template <class T> struct S;
5885      template <class T> struct S {};  */
5886 
5887 bool
redeclare_class_template(tree type,tree parms,tree cons)5888 redeclare_class_template (tree type, tree parms, tree cons)
5889 {
5890   tree tmpl;
5891   tree tmpl_parms;
5892   int i;
5893 
5894   if (!TYPE_TEMPLATE_INFO (type))
5895     {
5896       error ("%qT is not a template type", type);
5897       return false;
5898     }
5899 
5900   tmpl = TYPE_TI_TEMPLATE (type);
5901   if (!PRIMARY_TEMPLATE_P (tmpl))
5902     /* The type is nested in some template class.  Nothing to worry
5903        about here; there are no new template parameters for the nested
5904        type.  */
5905     return true;
5906 
5907   if (!parms)
5908     {
5909       error ("template specifiers not specified in declaration of %qD",
5910 	     tmpl);
5911       return false;
5912     }
5913 
5914   parms = INNERMOST_TEMPLATE_PARMS (parms);
5915   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
5916 
5917   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
5918     {
5919       error_n (input_location, TREE_VEC_LENGTH (parms),
5920                "redeclared with %d template parameter",
5921                "redeclared with %d template parameters",
5922                TREE_VEC_LENGTH (parms));
5923       inform_n (DECL_SOURCE_LOCATION (tmpl), TREE_VEC_LENGTH (tmpl_parms),
5924                 "previous declaration %qD used %d template parameter",
5925                 "previous declaration %qD used %d template parameters",
5926                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
5927       return false;
5928     }
5929 
5930   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
5931     {
5932       tree tmpl_parm;
5933       tree parm;
5934       tree tmpl_default;
5935       tree parm_default;
5936 
5937       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
5938           || TREE_VEC_ELT (parms, i) == error_mark_node)
5939         continue;
5940 
5941       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
5942       if (error_operand_p (tmpl_parm))
5943 	return false;
5944 
5945       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5946       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
5947       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
5948 
5949       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
5950 	 TEMPLATE_DECL.  */
5951       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
5952 	  || (TREE_CODE (tmpl_parm) != TYPE_DECL
5953 	      && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
5954 	  || (TREE_CODE (tmpl_parm) != PARM_DECL
5955 	      && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
5956 		  != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
5957 	  || (TREE_CODE (tmpl_parm) == PARM_DECL
5958 	      && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
5959 		  != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
5960 	{
5961 	  error ("template parameter %q+#D", tmpl_parm);
5962 	  error ("redeclared here as %q#D", parm);
5963 	  return false;
5964 	}
5965 
5966       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
5967 	{
5968 	  /* We have in [temp.param]:
5969 
5970 	     A template-parameter may not be given default arguments
5971 	     by two different declarations in the same scope.  */
5972 	  error_at (input_location, "redefinition of default argument for %q#D", parm);
5973 	  inform (DECL_SOURCE_LOCATION (tmpl_parm),
5974 		  "original definition appeared here");
5975 	  return false;
5976 	}
5977 
5978       if (parm_default != NULL_TREE)
5979 	/* Update the previous template parameters (which are the ones
5980 	   that will really count) with the new default value.  */
5981 	TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
5982       else if (tmpl_default != NULL_TREE)
5983 	/* Update the new parameters, too; they'll be used as the
5984 	   parameters for any members.  */
5985 	TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
5986 
5987       /* Give each template template parm in this redeclaration a
5988 	 DECL_CONTEXT of the template for which they are a parameter.  */
5989       if (TREE_CODE (parm) == TEMPLATE_DECL)
5990 	{
5991 	  gcc_assert (DECL_CONTEXT (parm) == NULL_TREE);
5992 	  DECL_CONTEXT (parm) = tmpl;
5993 	}
5994 
5995       if (TREE_CODE (parm) == TYPE_DECL)
5996 	TEMPLATE_TYPE_PARM_FOR_CLASS (TREE_TYPE (parm)) = true;
5997     }
5998 
5999   // Cannot redeclare a class template with a different set of constraints.
6000   if (!equivalent_constraints (get_constraints (tmpl), cons))
6001     {
6002       error_at (input_location, "redeclaration %q#D with different "
6003                                 "constraints", tmpl);
6004       inform (DECL_SOURCE_LOCATION (tmpl),
6005               "original declaration appeared here");
6006     }
6007 
6008     return true;
6009 }
6010 
6011 /* The actual substitution part of instantiate_non_dependent_expr_sfinae,
6012    to be used when the caller has already checked
6013    (processing_template_decl
6014     && !instantiation_dependent_expression_p (expr)
6015     && potential_constant_expression (expr))
6016    and cleared processing_template_decl.  */
6017 
6018 tree
instantiate_non_dependent_expr_internal(tree expr,tsubst_flags_t complain)6019 instantiate_non_dependent_expr_internal (tree expr, tsubst_flags_t complain)
6020 {
6021   return tsubst_copy_and_build (expr,
6022 				/*args=*/NULL_TREE,
6023 				complain,
6024 				/*in_decl=*/NULL_TREE,
6025 				/*function_p=*/false,
6026 				/*integral_constant_expression_p=*/true);
6027 }
6028 
6029 /* Simplify EXPR if it is a non-dependent expression.  Returns the
6030    (possibly simplified) expression.  */
6031 
6032 tree
instantiate_non_dependent_expr_sfinae(tree expr,tsubst_flags_t complain)6033 instantiate_non_dependent_expr_sfinae (tree expr, tsubst_flags_t complain)
6034 {
6035   if (expr == NULL_TREE)
6036     return NULL_TREE;
6037 
6038   /* If we're in a template, but EXPR isn't value dependent, simplify
6039      it.  We're supposed to treat:
6040 
6041        template <typename T> void f(T[1 + 1]);
6042        template <typename T> void f(T[2]);
6043 
6044      as two declarations of the same function, for example.  */
6045   if (processing_template_decl
6046       && is_nondependent_constant_expression (expr))
6047     {
6048       processing_template_decl_sentinel s;
6049       expr = instantiate_non_dependent_expr_internal (expr, complain);
6050     }
6051   return expr;
6052 }
6053 
6054 tree
instantiate_non_dependent_expr(tree expr)6055 instantiate_non_dependent_expr (tree expr)
6056 {
6057   return instantiate_non_dependent_expr_sfinae (expr, tf_error);
6058 }
6059 
6060 /* Like instantiate_non_dependent_expr, but return NULL_TREE rather than
6061    an uninstantiated expression.  */
6062 
6063 tree
instantiate_non_dependent_or_null(tree expr)6064 instantiate_non_dependent_or_null (tree expr)
6065 {
6066   if (expr == NULL_TREE)
6067     return NULL_TREE;
6068   if (processing_template_decl)
6069     {
6070       if (!is_nondependent_constant_expression (expr))
6071 	expr = NULL_TREE;
6072       else
6073 	{
6074 	  processing_template_decl_sentinel s;
6075 	  expr = instantiate_non_dependent_expr_internal (expr, tf_error);
6076 	}
6077     }
6078   return expr;
6079 }
6080 
6081 /* True iff T is a specialization of a variable template.  */
6082 
6083 bool
variable_template_specialization_p(tree t)6084 variable_template_specialization_p (tree t)
6085 {
6086   if (!VAR_P (t) || !DECL_LANG_SPECIFIC (t) || !DECL_TEMPLATE_INFO (t))
6087     return false;
6088   tree tmpl = DECL_TI_TEMPLATE (t);
6089   return variable_template_p (tmpl);
6090 }
6091 
6092 /* Return TRUE iff T is a type alias, a TEMPLATE_DECL for an alias
6093    template declaration, or a TYPE_DECL for an alias declaration.  */
6094 
6095 bool
alias_type_or_template_p(tree t)6096 alias_type_or_template_p (tree t)
6097 {
6098   if (t == NULL_TREE)
6099     return false;
6100   return ((TREE_CODE (t) == TYPE_DECL && TYPE_DECL_ALIAS_P (t))
6101 	  || (TYPE_P (t)
6102 	      && TYPE_NAME (t)
6103 	      && TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
6104 	  || DECL_ALIAS_TEMPLATE_P (t));
6105 }
6106 
6107 /* Return TRUE iff T is a specialization of an alias template.  */
6108 
6109 bool
alias_template_specialization_p(const_tree t)6110 alias_template_specialization_p (const_tree t)
6111 {
6112   /* It's an alias template specialization if it's an alias and its
6113      TYPE_NAME is a specialization of a primary template.  */
6114   if (TYPE_ALIAS_P (t))
6115     if (tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t))
6116       return PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo));
6117 
6118   return false;
6119 }
6120 
6121 /* An alias template is complex from a SFINAE perspective if a template-id
6122    using that alias can be ill-formed when the expansion is not, as with
6123    the void_t template.  We determine this by checking whether the
6124    expansion for the alias template uses all its template parameters.  */
6125 
6126 struct uses_all_template_parms_data
6127 {
6128   int level;
6129   bool *seen;
6130 };
6131 
6132 static int
uses_all_template_parms_r(tree t,void * data_)6133 uses_all_template_parms_r (tree t, void *data_)
6134 {
6135   struct uses_all_template_parms_data &data
6136     = *(struct uses_all_template_parms_data*)data_;
6137   tree idx = get_template_parm_index (t);
6138 
6139   if (TEMPLATE_PARM_LEVEL (idx) == data.level)
6140     data.seen[TEMPLATE_PARM_IDX (idx)] = true;
6141   return 0;
6142 }
6143 
6144 static bool
complex_alias_template_p(const_tree tmpl)6145 complex_alias_template_p (const_tree tmpl)
6146 {
6147   struct uses_all_template_parms_data data;
6148   tree pat = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6149   tree parms = DECL_TEMPLATE_PARMS (tmpl);
6150   data.level = TMPL_PARMS_DEPTH (parms);
6151   int len = TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS (parms));
6152   data.seen = XALLOCAVEC (bool, len);
6153   for (int i = 0; i < len; ++i)
6154     data.seen[i] = false;
6155 
6156   for_each_template_parm (pat, uses_all_template_parms_r, &data, NULL, true);
6157   for (int i = 0; i < len; ++i)
6158     if (!data.seen[i])
6159       return true;
6160   return false;
6161 }
6162 
6163 /* Return TRUE iff T is a specialization of a complex alias template with
6164    dependent template-arguments.  */
6165 
6166 bool
dependent_alias_template_spec_p(const_tree t)6167 dependent_alias_template_spec_p (const_tree t)
6168 {
6169   if (!alias_template_specialization_p (t))
6170     return false;
6171 
6172   tree tinfo = TYPE_ALIAS_TEMPLATE_INFO (t);
6173   if (!TEMPLATE_DECL_COMPLEX_ALIAS_P (TI_TEMPLATE (tinfo)))
6174     return false;
6175 
6176   tree args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo));
6177   if (!any_dependent_template_arguments_p (args))
6178     return false;
6179 
6180   return true;
6181 }
6182 
6183 /* Return the number of innermost template parameters in TMPL.  */
6184 
6185 static int
num_innermost_template_parms(tree tmpl)6186 num_innermost_template_parms (tree tmpl)
6187 {
6188   tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
6189   return TREE_VEC_LENGTH (parms);
6190 }
6191 
6192 /* Return either TMPL or another template that it is equivalent to under DR
6193    1286: An alias that just changes the name of a template is equivalent to
6194    the other template.  */
6195 
6196 static tree
get_underlying_template(tree tmpl)6197 get_underlying_template (tree tmpl)
6198 {
6199   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
6200   while (DECL_ALIAS_TEMPLATE_P (tmpl))
6201     {
6202       /* Determine if the alias is equivalent to an underlying template.  */
6203       tree orig_type = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
6204       tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (orig_type);
6205       if (!tinfo)
6206 	break;
6207 
6208       tree underlying = TI_TEMPLATE (tinfo);
6209       if (!PRIMARY_TEMPLATE_P (underlying)
6210 	  || (num_innermost_template_parms (tmpl)
6211 	      != num_innermost_template_parms (underlying)))
6212 	break;
6213 
6214       tree alias_args = INNERMOST_TEMPLATE_ARGS
6215 	(template_parms_to_args (DECL_TEMPLATE_PARMS (tmpl)));
6216       if (!comp_template_args (TI_ARGS (tinfo), alias_args))
6217 	break;
6218 
6219       /* Alias is equivalent.  Strip it and repeat.  */
6220       tmpl = underlying;
6221     }
6222 
6223   return tmpl;
6224 }
6225 
6226 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
6227    must be a reference-to-function or a pointer-to-function type, as specified
6228    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
6229    and check that the resulting function has external linkage.  */
6230 
6231 static tree
convert_nontype_argument_function(tree type,tree expr,tsubst_flags_t complain)6232 convert_nontype_argument_function (tree type, tree expr,
6233 				   tsubst_flags_t complain)
6234 {
6235   tree fns = expr;
6236   tree fn, fn_no_ptr;
6237   linkage_kind linkage;
6238 
6239   fn = instantiate_type (type, fns, tf_none);
6240   if (fn == error_mark_node)
6241     return error_mark_node;
6242 
6243   if (value_dependent_expression_p (fn))
6244     goto accept;
6245 
6246   fn_no_ptr = strip_fnptr_conv (fn);
6247   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
6248     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
6249   if (BASELINK_P (fn_no_ptr))
6250     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
6251 
6252   /* [temp.arg.nontype]/1
6253 
6254      A template-argument for a non-type, non-template template-parameter
6255      shall be one of:
6256      [...]
6257      -- the address of an object or function with external [C++11: or
6258         internal] linkage.  */
6259 
6260   if (TREE_CODE (fn_no_ptr) != FUNCTION_DECL)
6261     {
6262       if (complain & tf_error)
6263 	{
6264 	  error ("%qE is not a valid template argument for type %qT",
6265 		 expr, type);
6266 	  if (TYPE_PTR_P (type))
6267 	    inform (input_location, "it must be the address of a function "
6268 		    "with external linkage");
6269 	  else
6270 	    inform (input_location, "it must be the name of a function with "
6271 		    "external linkage");
6272 	}
6273       return NULL_TREE;
6274     }
6275 
6276   linkage = decl_linkage (fn_no_ptr);
6277   if (cxx_dialect >= cxx11 ? linkage == lk_none : linkage != lk_external)
6278     {
6279       if (complain & tf_error)
6280 	{
6281 	  if (cxx_dialect >= cxx11)
6282 	    error ("%qE is not a valid template argument for type %qT "
6283 		   "because %qD has no linkage",
6284 		   expr, type, fn_no_ptr);
6285 	  else
6286 	    error ("%qE is not a valid template argument for type %qT "
6287 		   "because %qD does not have external linkage",
6288 		   expr, type, fn_no_ptr);
6289 	}
6290       return NULL_TREE;
6291     }
6292 
6293  accept:
6294   if (TREE_CODE (type) == REFERENCE_TYPE)
6295     {
6296       if (REFERENCE_REF_P (fn))
6297 	fn = TREE_OPERAND (fn, 0);
6298       else
6299 	fn = build_address (fn);
6300     }
6301   if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (fn)))
6302     fn = build_nop (type, fn);
6303 
6304   return fn;
6305 }
6306 
6307 /* Subroutine of convert_nontype_argument.
6308    Check if EXPR of type TYPE is a valid pointer-to-member constant.
6309    Emit an error otherwise.  */
6310 
6311 static bool
check_valid_ptrmem_cst_expr(tree type,tree expr,tsubst_flags_t complain)6312 check_valid_ptrmem_cst_expr (tree type, tree expr,
6313 			     tsubst_flags_t complain)
6314 {
6315   location_t loc = EXPR_LOC_OR_LOC (expr, input_location);
6316   tree orig_expr = expr;
6317   STRIP_NOPS (expr);
6318   if (null_ptr_cst_p (expr))
6319     return true;
6320   if (TREE_CODE (expr) == PTRMEM_CST
6321       && same_type_p (TYPE_PTRMEM_CLASS_TYPE (type),
6322 		      PTRMEM_CST_CLASS (expr)))
6323     return true;
6324   if (cxx_dialect >= cxx11 && null_member_pointer_value_p (expr))
6325     return true;
6326   if (processing_template_decl
6327       && TREE_CODE (expr) == ADDR_EXPR
6328       && TREE_CODE (TREE_OPERAND (expr, 0)) == OFFSET_REF)
6329     return true;
6330   if (complain & tf_error)
6331     {
6332       error_at (loc, "%qE is not a valid template argument for type %qT",
6333 		orig_expr, type);
6334       if (TREE_CODE (expr) != PTRMEM_CST)
6335 	inform (loc, "it must be a pointer-to-member of the form %<&X::Y%>");
6336       else
6337 	inform (loc, "because it is a member of %qT", PTRMEM_CST_CLASS (expr));
6338     }
6339   return false;
6340 }
6341 
6342 /* Returns TRUE iff the address of OP is value-dependent.
6343 
6344    14.6.2.4 [temp.dep.temp]:
6345    A non-integral non-type template-argument is dependent if its type is
6346    dependent or it has either of the following forms
6347      qualified-id
6348      & qualified-id
6349    and contains a nested-name-specifier which specifies a class-name that
6350    names a dependent type.
6351 
6352    We generalize this to just say that the address of a member of a
6353    dependent class is value-dependent; the above doesn't cover the
6354    address of a static data member named with an unqualified-id.  */
6355 
6356 static bool
has_value_dependent_address(tree op)6357 has_value_dependent_address (tree op)
6358 {
6359   /* We could use get_inner_reference here, but there's no need;
6360      this is only relevant for template non-type arguments, which
6361      can only be expressed as &id-expression.  */
6362   if (DECL_P (op))
6363     {
6364       tree ctx = CP_DECL_CONTEXT (op);
6365       if (TYPE_P (ctx) && dependent_type_p (ctx))
6366 	return true;
6367     }
6368 
6369   return false;
6370 }
6371 
6372 /* The next set of functions are used for providing helpful explanatory
6373    diagnostics for failed overload resolution.  Their messages should be
6374    indented by two spaces for consistency with the messages in
6375    call.c  */
6376 
6377 static int
unify_success(bool)6378 unify_success (bool /*explain_p*/)
6379 {
6380   return 0;
6381 }
6382 
6383 /* Other failure functions should call this one, to provide a single function
6384    for setting a breakpoint on.  */
6385 
6386 static int
unify_invalid(bool)6387 unify_invalid (bool /*explain_p*/)
6388 {
6389   return 1;
6390 }
6391 
6392 static int
unify_parameter_deduction_failure(bool explain_p,tree parm)6393 unify_parameter_deduction_failure (bool explain_p, tree parm)
6394 {
6395   if (explain_p)
6396     inform (input_location,
6397 	    "  couldn't deduce template parameter %qD", parm);
6398   return unify_invalid (explain_p);
6399 }
6400 
6401 static int
unify_cv_qual_mismatch(bool explain_p,tree parm,tree arg)6402 unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
6403 {
6404   if (explain_p)
6405     inform (input_location,
6406 	    "  types %qT and %qT have incompatible cv-qualifiers",
6407 	    parm, arg);
6408   return unify_invalid (explain_p);
6409 }
6410 
6411 static int
unify_type_mismatch(bool explain_p,tree parm,tree arg)6412 unify_type_mismatch (bool explain_p, tree parm, tree arg)
6413 {
6414   if (explain_p)
6415     inform (input_location, "  mismatched types %qT and %qT", parm, arg);
6416   return unify_invalid (explain_p);
6417 }
6418 
6419 static int
unify_parameter_pack_mismatch(bool explain_p,tree parm,tree arg)6420 unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
6421 {
6422   if (explain_p)
6423     inform (input_location,
6424 	    "  template parameter %qD is not a parameter pack, but "
6425 	    "argument %qD is",
6426 	    parm, arg);
6427   return unify_invalid (explain_p);
6428 }
6429 
6430 static int
unify_ptrmem_cst_mismatch(bool explain_p,tree parm,tree arg)6431 unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
6432 {
6433   if (explain_p)
6434     inform (input_location,
6435 	    "  template argument %qE does not match "
6436 	    "pointer-to-member constant %qE",
6437 	    arg, parm);
6438   return unify_invalid (explain_p);
6439 }
6440 
6441 static int
unify_expression_unequal(bool explain_p,tree parm,tree arg)6442 unify_expression_unequal (bool explain_p, tree parm, tree arg)
6443 {
6444   if (explain_p)
6445     inform (input_location, "  %qE is not equivalent to %qE", parm, arg);
6446   return unify_invalid (explain_p);
6447 }
6448 
6449 static int
unify_parameter_pack_inconsistent(bool explain_p,tree old_arg,tree new_arg)6450 unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
6451 {
6452   if (explain_p)
6453     inform (input_location,
6454 	    "  inconsistent parameter pack deduction with %qT and %qT",
6455 	    old_arg, new_arg);
6456   return unify_invalid (explain_p);
6457 }
6458 
6459 static int
unify_inconsistency(bool explain_p,tree parm,tree first,tree second)6460 unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
6461 {
6462   if (explain_p)
6463     {
6464       if (TYPE_P (parm))
6465 	inform (input_location,
6466 		"  deduced conflicting types for parameter %qT (%qT and %qT)",
6467 		parm, first, second);
6468       else
6469 	inform (input_location,
6470 		"  deduced conflicting values for non-type parameter "
6471 		"%qE (%qE and %qE)", parm, first, second);
6472     }
6473   return unify_invalid (explain_p);
6474 }
6475 
6476 static int
unify_vla_arg(bool explain_p,tree arg)6477 unify_vla_arg (bool explain_p, tree arg)
6478 {
6479   if (explain_p)
6480     inform (input_location,
6481 	    "  variable-sized array type %qT is not "
6482 	    "a valid template argument",
6483 	    arg);
6484   return unify_invalid (explain_p);
6485 }
6486 
6487 static int
unify_method_type_error(bool explain_p,tree arg)6488 unify_method_type_error (bool explain_p, tree arg)
6489 {
6490   if (explain_p)
6491     inform (input_location,
6492 	    "  member function type %qT is not a valid template argument",
6493 	    arg);
6494   return unify_invalid (explain_p);
6495 }
6496 
6497 static int
6498 unify_arity (bool explain_p, int have, int wanted, bool least_p = false)
6499 {
6500   if (explain_p)
6501     {
6502       if (least_p)
6503 	inform_n (input_location, wanted,
6504 		  "  candidate expects at least %d argument, %d provided",
6505 		  "  candidate expects at least %d arguments, %d provided",
6506 		  wanted, have);
6507       else
6508 	inform_n (input_location, wanted,
6509 		  "  candidate expects %d argument, %d provided",
6510 		  "  candidate expects %d arguments, %d provided",
6511 		  wanted, have);
6512     }
6513   return unify_invalid (explain_p);
6514 }
6515 
6516 static int
unify_too_many_arguments(bool explain_p,int have,int wanted)6517 unify_too_many_arguments (bool explain_p, int have, int wanted)
6518 {
6519   return unify_arity (explain_p, have, wanted);
6520 }
6521 
6522 static int
6523 unify_too_few_arguments (bool explain_p, int have, int wanted,
6524 			 bool least_p = false)
6525 {
6526   return unify_arity (explain_p, have, wanted, least_p);
6527 }
6528 
6529 static int
unify_arg_conversion(bool explain_p,tree to_type,tree from_type,tree arg)6530 unify_arg_conversion (bool explain_p, tree to_type,
6531 		      tree from_type, tree arg)
6532 {
6533   if (explain_p)
6534     inform (EXPR_LOC_OR_LOC (arg, input_location),
6535 	    "  cannot convert %qE (type %qT) to type %qT",
6536 	    arg, from_type, to_type);
6537   return unify_invalid (explain_p);
6538 }
6539 
6540 static int
unify_no_common_base(bool explain_p,enum template_base_result r,tree parm,tree arg)6541 unify_no_common_base (bool explain_p, enum template_base_result r,
6542 		      tree parm, tree arg)
6543 {
6544   if (explain_p)
6545     switch (r)
6546       {
6547       case tbr_ambiguous_baseclass:
6548 	inform (input_location, "  %qT is an ambiguous base class of %qT",
6549 		parm, arg);
6550 	break;
6551       default:
6552 	inform (input_location, "  %qT is not derived from %qT", arg, parm);
6553 	break;
6554       }
6555   return unify_invalid (explain_p);
6556 }
6557 
6558 static int
unify_inconsistent_template_template_parameters(bool explain_p)6559 unify_inconsistent_template_template_parameters (bool explain_p)
6560 {
6561   if (explain_p)
6562     inform (input_location,
6563 	    "  template parameters of a template template argument are "
6564 	    "inconsistent with other deduced template arguments");
6565   return unify_invalid (explain_p);
6566 }
6567 
6568 static int
unify_template_deduction_failure(bool explain_p,tree parm,tree arg)6569 unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
6570 {
6571   if (explain_p)
6572     inform (input_location,
6573 	    "  can't deduce a template for %qT from non-template type %qT",
6574 	    parm, arg);
6575   return unify_invalid (explain_p);
6576 }
6577 
6578 static int
unify_template_argument_mismatch(bool explain_p,tree parm,tree arg)6579 unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
6580 {
6581   if (explain_p)
6582     inform (input_location,
6583 	    "  template argument %qE does not match %qE", arg, parm);
6584   return unify_invalid (explain_p);
6585 }
6586 
6587 /* Attempt to convert the non-type template parameter EXPR to the
6588    indicated TYPE.  If the conversion is successful, return the
6589    converted value.  If the conversion is unsuccessful, return
6590    NULL_TREE if we issued an error message, or error_mark_node if we
6591    did not.  We issue error messages for out-and-out bad template
6592    parameters, but not simply because the conversion failed, since we
6593    might be just trying to do argument deduction.  Both TYPE and EXPR
6594    must be non-dependent.
6595 
6596    The conversion follows the special rules described in
6597    [temp.arg.nontype], and it is much more strict than an implicit
6598    conversion.
6599 
6600    This function is called twice for each template argument (see
6601    lookup_template_class for a more accurate description of this
6602    problem). This means that we need to handle expressions which
6603    are not valid in a C++ source, but can be created from the
6604    first call (for instance, casts to perform conversions). These
6605    hacks can go away after we fix the double coercion problem.  */
6606 
6607 static tree
convert_nontype_argument(tree type,tree expr,tsubst_flags_t complain)6608 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
6609 {
6610   tree expr_type;
6611   location_t loc = EXPR_LOC_OR_LOC (expr, input_location);
6612   tree orig_expr = expr;
6613 
6614   /* Detect immediately string literals as invalid non-type argument.
6615      This special-case is not needed for correctness (we would easily
6616      catch this later), but only to provide better diagnostic for this
6617      common user mistake. As suggested by DR 100, we do not mention
6618      linkage issues in the diagnostic as this is not the point.  */
6619   /* FIXME we're making this OK.  */
6620   if (TREE_CODE (expr) == STRING_CST)
6621     {
6622       if (complain & tf_error)
6623 	error ("%qE is not a valid template argument for type %qT "
6624 	       "because string literals can never be used in this context",
6625 	       expr, type);
6626       return NULL_TREE;
6627     }
6628 
6629   /* Add the ADDR_EXPR now for the benefit of
6630      value_dependent_expression_p.  */
6631   if (TYPE_PTROBV_P (type)
6632       && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
6633     {
6634       expr = decay_conversion (expr, complain);
6635       if (expr == error_mark_node)
6636 	return error_mark_node;
6637     }
6638 
6639   /* If we are in a template, EXPR may be non-dependent, but still
6640      have a syntactic, rather than semantic, form.  For example, EXPR
6641      might be a SCOPE_REF, rather than the VAR_DECL to which the
6642      SCOPE_REF refers.  Preserving the qualifying scope is necessary
6643      so that access checking can be performed when the template is
6644      instantiated -- but here we need the resolved form so that we can
6645      convert the argument.  */
6646   bool non_dep = false;
6647   if (TYPE_REF_OBJ_P (type)
6648       && has_value_dependent_address (expr))
6649     /* If we want the address and it's value-dependent, don't fold.  */;
6650   else if (processing_template_decl
6651 	   && is_nondependent_constant_expression (expr))
6652     non_dep = true;
6653   if (error_operand_p (expr))
6654     return error_mark_node;
6655   expr_type = TREE_TYPE (expr);
6656 
6657   /* If the argument is non-dependent, perform any conversions in
6658      non-dependent context as well.  */
6659   processing_template_decl_sentinel s (non_dep);
6660   if (non_dep)
6661     expr = instantiate_non_dependent_expr_internal (expr, complain);
6662 
6663   if (value_dependent_expression_p (expr))
6664     expr = canonicalize_expr_argument (expr, complain);
6665 
6666   /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
6667      to a non-type argument of "nullptr".  */
6668   if (NULLPTR_TYPE_P (expr_type) && TYPE_PTR_OR_PTRMEM_P (type))
6669     expr = fold_simple (convert (type, expr));
6670 
6671   /* In C++11, integral or enumeration non-type template arguments can be
6672      arbitrary constant expressions.  Pointer and pointer to
6673      member arguments can be general constant expressions that evaluate
6674      to a null value, but otherwise still need to be of a specific form.  */
6675   if (cxx_dialect >= cxx11)
6676     {
6677       if (TREE_CODE (expr) == PTRMEM_CST)
6678 	/* A PTRMEM_CST is already constant, and a valid template
6679 	   argument for a parameter of pointer to member type, we just want
6680 	   to leave it in that form rather than lower it to a
6681 	   CONSTRUCTOR.  */;
6682       else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type)
6683 	       || cxx_dialect >= cxx17)
6684 	{
6685 	  /* C++17: A template-argument for a non-type template-parameter shall
6686 	     be a converted constant expression (8.20) of the type of the
6687 	     template-parameter.  */
6688 	  expr = build_converted_constant_expr (type, expr, complain);
6689 	  if (expr == error_mark_node)
6690 	    return error_mark_node;
6691 	  expr = maybe_constant_value (expr);
6692 	  expr = convert_from_reference (expr);
6693 	}
6694       else if (TYPE_PTR_OR_PTRMEM_P (type))
6695 	{
6696 	  tree folded = maybe_constant_value (expr);
6697 	  if (TYPE_PTR_P (type) ? integer_zerop (folded)
6698 	      : null_member_pointer_value_p (folded))
6699 	    expr = folded;
6700 	}
6701     }
6702 
6703   if (TREE_CODE (type) == REFERENCE_TYPE)
6704     expr = mark_lvalue_use (expr);
6705   else
6706     expr = mark_rvalue_use (expr);
6707 
6708   /* HACK: Due to double coercion, we can get a
6709      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
6710      which is the tree that we built on the first call (see
6711      below when coercing to reference to object or to reference to
6712      function). We just strip everything and get to the arg.
6713      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
6714      for examples.  */
6715   if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
6716     {
6717       tree probe_type, probe = expr;
6718       if (REFERENCE_REF_P (probe))
6719 	probe = TREE_OPERAND (probe, 0);
6720       probe_type = TREE_TYPE (probe);
6721       if (TREE_CODE (probe) == NOP_EXPR)
6722 	{
6723 	  /* ??? Maybe we could use convert_from_reference here, but we
6724 	     would need to relax its constraints because the NOP_EXPR
6725 	     could actually change the type to something more cv-qualified,
6726 	     and this is not folded by convert_from_reference.  */
6727 	  tree addr = TREE_OPERAND (probe, 0);
6728 	  if (TREE_CODE (probe_type) == REFERENCE_TYPE
6729 	      && TREE_CODE (addr) == ADDR_EXPR
6730 	      && TYPE_PTR_P (TREE_TYPE (addr))
6731 	      && (same_type_ignoring_top_level_qualifiers_p
6732 		  (TREE_TYPE (probe_type),
6733 		   TREE_TYPE (TREE_TYPE (addr)))))
6734 	    {
6735 	      expr = TREE_OPERAND (addr, 0);
6736 	      expr_type = TREE_TYPE (probe_type);
6737 	    }
6738 	}
6739     }
6740 
6741   /* [temp.arg.nontype]/5, bullet 1
6742 
6743      For a non-type template-parameter of integral or enumeration type,
6744      integral promotions (_conv.prom_) and integral conversions
6745      (_conv.integral_) are applied.  */
6746   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
6747     {
6748       if (cxx_dialect < cxx11)
6749 	{
6750 	  tree t = build_converted_constant_expr (type, expr, complain);
6751 	  t = maybe_constant_value (t);
6752 	  if (t != error_mark_node)
6753 	    expr = t;
6754 	}
6755 
6756       if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
6757 	return error_mark_node;
6758 
6759       /* Notice that there are constant expressions like '4 % 0' which
6760 	 do not fold into integer constants.  */
6761       if (TREE_CODE (expr) != INTEGER_CST
6762 	  && !value_dependent_expression_p (expr))
6763 	{
6764 	  if (complain & tf_error)
6765 	    {
6766 	      int errs = errorcount, warns = warningcount + werrorcount;
6767 	      if (!require_potential_constant_expression (expr))
6768 		expr = error_mark_node;
6769 	      else
6770 		expr = cxx_constant_value (expr);
6771 	      if (errorcount > errs || warningcount + werrorcount > warns)
6772 		inform (loc, "in template argument for type %qT", type);
6773 	      if (expr == error_mark_node)
6774 		return NULL_TREE;
6775 	      /* else cxx_constant_value complained but gave us
6776 		 a real constant, so go ahead.  */
6777 	      if (TREE_CODE (expr) != INTEGER_CST)
6778 		{
6779 		  /* Some assemble time constant expressions like
6780 		     (intptr_t)&&lab1 - (intptr_t)&&lab2 or
6781 		     4 + (intptr_t)&&var satisfy reduced_constant_expression_p
6782 		     as we can emit them into .rodata initializers of
6783 		     variables, yet they can't fold into an INTEGER_CST at
6784 		     compile time.  Refuse them here.  */
6785 		  gcc_checking_assert (reduced_constant_expression_p (expr));
6786 		  error_at (loc, "template argument %qE for type %qT not "
6787 				 "a constant integer", expr, type);
6788 		  return NULL_TREE;
6789 		}
6790 	    }
6791 	  else
6792 	    return NULL_TREE;
6793 	}
6794 
6795       /* Avoid typedef problems.  */
6796       if (TREE_TYPE (expr) != type)
6797 	expr = fold_convert (type, expr);
6798     }
6799   /* [temp.arg.nontype]/5, bullet 2
6800 
6801      For a non-type template-parameter of type pointer to object,
6802      qualification conversions (_conv.qual_) and the array-to-pointer
6803      conversion (_conv.array_) are applied.  */
6804   else if (TYPE_PTROBV_P (type))
6805     {
6806       tree decayed = expr;
6807 
6808       /* Look through any NOP_EXPRs around an ADDR_EXPR, whether they come from
6809 	 decay_conversion or an explicit cast.  If it's a problematic cast,
6810 	 we'll complain about it below.  */
6811       if (TREE_CODE (expr) == NOP_EXPR)
6812 	{
6813 	  tree probe = expr;
6814 	  STRIP_NOPS (probe);
6815 	  if (TREE_CODE (probe) == ADDR_EXPR
6816 	      && TYPE_PTR_P (TREE_TYPE (probe)))
6817 	    {
6818 	      expr = probe;
6819 	      expr_type = TREE_TYPE (expr);
6820 	    }
6821 	}
6822 
6823       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
6824 
6825 	 A template-argument for a non-type, non-template template-parameter
6826 	 shall be one of: [...]
6827 
6828 	 -- the name of a non-type template-parameter;
6829 	 -- the address of an object or function with external linkage, [...]
6830 	    expressed as "& id-expression" where the & is optional if the name
6831 	    refers to a function or array, or if the corresponding
6832 	    template-parameter is a reference.
6833 
6834 	Here, we do not care about functions, as they are invalid anyway
6835 	for a parameter of type pointer-to-object.  */
6836 
6837       if (value_dependent_expression_p (expr))
6838 	/* Non-type template parameters are OK.  */
6839 	;
6840       else if (cxx_dialect >= cxx11 && integer_zerop (expr))
6841 	/* Null pointer values are OK in C++11.  */;
6842       else if (TREE_CODE (expr) != ADDR_EXPR)
6843 	{
6844 	  if (VAR_P (expr))
6845 	    {
6846 	      if (complain & tf_error)
6847 		error ("%qD is not a valid template argument "
6848 		       "because %qD is a variable, not the address of "
6849 		       "a variable", orig_expr, expr);
6850 	      return NULL_TREE;
6851 	    }
6852 	  if (POINTER_TYPE_P (expr_type))
6853 	    {
6854 	      if (complain & tf_error)
6855 		error ("%qE is not a valid template argument for %qT "
6856 		       "because it is not the address of a variable",
6857 		       orig_expr, type);
6858 	      return NULL_TREE;
6859 	    }
6860 	  /* Other values, like integer constants, might be valid
6861 	     non-type arguments of some other type.  */
6862 	  return error_mark_node;
6863 	}
6864       else
6865 	{
6866 	  tree decl = TREE_OPERAND (expr, 0);
6867 
6868 	  if (!VAR_P (decl))
6869 	    {
6870 	      if (complain & tf_error)
6871 		error ("%qE is not a valid template argument of type %qT "
6872 		       "because %qE is not a variable", orig_expr, type, decl);
6873 	      return NULL_TREE;
6874 	    }
6875 	  else if (cxx_dialect < cxx11 && !DECL_EXTERNAL_LINKAGE_P (decl))
6876 	    {
6877 	      if (complain & tf_error)
6878 		error ("%qE is not a valid template argument of type %qT "
6879 		       "because %qD does not have external linkage",
6880 		       orig_expr, type, decl);
6881 	      return NULL_TREE;
6882 	    }
6883 	  else if ((cxx_dialect >= cxx11 && cxx_dialect < cxx17)
6884 		   && decl_linkage (decl) == lk_none)
6885 	    {
6886 	      if (complain & tf_error)
6887 		error ("%qE is not a valid template argument of type %qT "
6888 		       "because %qD has no linkage", orig_expr, type, decl);
6889 	      return NULL_TREE;
6890 	    }
6891 	  /* C++17: For a non-type template-parameter of reference or pointer
6892 	     type, the value of the constant expression shall not refer to (or
6893 	     for a pointer type, shall not be the address of):
6894 	       * a subobject (4.5),
6895 	       * a temporary object (15.2),
6896 	       * a string literal (5.13.5),
6897 	       * the result of a typeid expression (8.2.8), or
6898 	       * a predefined __func__ variable (11.4.1).  */
6899 	  else if (DECL_ARTIFICIAL (decl))
6900 	    {
6901 	      if (complain & tf_error)
6902 		error ("the address of %qD is not a valid template argument",
6903 		       decl);
6904 	      return NULL_TREE;
6905 	    }
6906 	  else if (!same_type_ignoring_top_level_qualifiers_p
6907 		   (strip_array_types (TREE_TYPE (type)),
6908 		    strip_array_types (TREE_TYPE (decl))))
6909 	    {
6910 	      if (complain & tf_error)
6911 		error ("the address of the %qT subobject of %qD is not a "
6912 		       "valid template argument", TREE_TYPE (type), decl);
6913 	      return NULL_TREE;
6914 	    }
6915 	  else if (!TREE_STATIC (decl) && !DECL_EXTERNAL (decl))
6916 	    {
6917 	      if (complain & tf_error)
6918 		error ("the address of %qD is not a valid template argument "
6919 		       "because it does not have static storage duration",
6920 		       decl);
6921 	      return NULL_TREE;
6922 	    }
6923 	}
6924 
6925       expr = decayed;
6926 
6927       expr = perform_qualification_conversions (type, expr);
6928       if (expr == error_mark_node)
6929 	return error_mark_node;
6930     }
6931   /* [temp.arg.nontype]/5, bullet 3
6932 
6933      For a non-type template-parameter of type reference to object, no
6934      conversions apply. The type referred to by the reference may be more
6935      cv-qualified than the (otherwise identical) type of the
6936      template-argument. The template-parameter is bound directly to the
6937      template-argument, which must be an lvalue.  */
6938   else if (TYPE_REF_OBJ_P (type))
6939     {
6940       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
6941 						      expr_type))
6942 	return error_mark_node;
6943 
6944       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
6945 	{
6946 	  if (complain & tf_error)
6947 	    error ("%qE is not a valid template argument for type %qT "
6948 		   "because of conflicts in cv-qualification", expr, type);
6949 	  return NULL_TREE;
6950 	}
6951 
6952       if (!lvalue_p (expr))
6953 	{
6954 	  if (complain & tf_error)
6955 	    error ("%qE is not a valid template argument for type %qT "
6956 		   "because it is not an lvalue", expr, type);
6957 	  return NULL_TREE;
6958 	}
6959 
6960       /* [temp.arg.nontype]/1
6961 
6962 	 A template-argument for a non-type, non-template template-parameter
6963 	 shall be one of: [...]
6964 
6965 	 -- the address of an object or function with external linkage.  */
6966       if (INDIRECT_REF_P (expr)
6967 	  && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
6968 	{
6969 	  expr = TREE_OPERAND (expr, 0);
6970 	  if (DECL_P (expr))
6971 	    {
6972 	      if (complain & tf_error)
6973 		error ("%q#D is not a valid template argument for type %qT "
6974 		       "because a reference variable does not have a constant "
6975 		       "address", expr, type);
6976 	      return NULL_TREE;
6977 	    }
6978 	}
6979 
6980       if (TYPE_REF_OBJ_P (TREE_TYPE (expr))
6981 	  && value_dependent_expression_p (expr))
6982 	/* OK, dependent reference.  We don't want to ask whether a DECL is
6983 	   itself value-dependent, since what we want here is its address.  */;
6984       else
6985 	{
6986 	  if (!DECL_P (expr))
6987 	    {
6988 	      if (complain & tf_error)
6989 		error ("%qE is not a valid template argument for type %qT "
6990 		       "because it is not an object with linkage",
6991 		       expr, type);
6992 	      return NULL_TREE;
6993 	    }
6994 
6995 	  /* DR 1155 allows internal linkage in C++11 and up.  */
6996 	  linkage_kind linkage = decl_linkage (expr);
6997 	  if (linkage < (cxx_dialect >= cxx11 ? lk_internal : lk_external))
6998 	    {
6999 	      if (complain & tf_error)
7000 		error ("%qE is not a valid template argument for type %qT "
7001 		       "because object %qD does not have linkage",
7002 		       expr, type, expr);
7003 	      return NULL_TREE;
7004 	    }
7005 
7006 	  expr = build_address (expr);
7007 	}
7008 
7009       if (!same_type_p (type, TREE_TYPE (expr)))
7010 	expr = build_nop (type, expr);
7011     }
7012   /* [temp.arg.nontype]/5, bullet 4
7013 
7014      For a non-type template-parameter of type pointer to function, only
7015      the function-to-pointer conversion (_conv.func_) is applied. If the
7016      template-argument represents a set of overloaded functions (or a
7017      pointer to such), the matching function is selected from the set
7018      (_over.over_).  */
7019   else if (TYPE_PTRFN_P (type))
7020     {
7021       /* If the argument is a template-id, we might not have enough
7022 	 context information to decay the pointer.  */
7023       if (!type_unknown_p (expr_type))
7024 	{
7025 	  expr = decay_conversion (expr, complain);
7026 	  if (expr == error_mark_node)
7027 	    return error_mark_node;
7028 	}
7029 
7030       if (cxx_dialect >= cxx11 && integer_zerop (expr))
7031 	/* Null pointer values are OK in C++11.  */
7032 	return perform_qualification_conversions (type, expr);
7033 
7034       expr = convert_nontype_argument_function (type, expr, complain);
7035       if (!expr || expr == error_mark_node)
7036 	return expr;
7037     }
7038   /* [temp.arg.nontype]/5, bullet 5
7039 
7040      For a non-type template-parameter of type reference to function, no
7041      conversions apply. If the template-argument represents a set of
7042      overloaded functions, the matching function is selected from the set
7043      (_over.over_).  */
7044   else if (TYPE_REFFN_P (type))
7045     {
7046       if (TREE_CODE (expr) == ADDR_EXPR)
7047 	{
7048 	  if (complain & tf_error)
7049 	    {
7050 	      error ("%qE is not a valid template argument for type %qT "
7051 		     "because it is a pointer", expr, type);
7052 	      inform (input_location, "try using %qE instead",
7053 		      TREE_OPERAND (expr, 0));
7054 	    }
7055 	  return NULL_TREE;
7056 	}
7057 
7058       expr = convert_nontype_argument_function (type, expr, complain);
7059       if (!expr || expr == error_mark_node)
7060 	return expr;
7061     }
7062   /* [temp.arg.nontype]/5, bullet 6
7063 
7064      For a non-type template-parameter of type pointer to member function,
7065      no conversions apply. If the template-argument represents a set of
7066      overloaded member functions, the matching member function is selected
7067      from the set (_over.over_).  */
7068   else if (TYPE_PTRMEMFUNC_P (type))
7069     {
7070       expr = instantiate_type (type, expr, tf_none);
7071       if (expr == error_mark_node)
7072 	return error_mark_node;
7073 
7074       /* [temp.arg.nontype] bullet 1 says the pointer to member
7075          expression must be a pointer-to-member constant.  */
7076       if (!value_dependent_expression_p (expr)
7077 	  && !check_valid_ptrmem_cst_expr (type, expr, complain))
7078 	return NULL_TREE;
7079 
7080       /* Repeated conversion can't deal with a conversion that turns PTRMEM_CST
7081 	 into a CONSTRUCTOR, so build up a new PTRMEM_CST instead.  */
7082       if (fnptr_conv_p (type, TREE_TYPE (expr)))
7083 	expr = make_ptrmem_cst (type, PTRMEM_CST_MEMBER (expr));
7084     }
7085   /* [temp.arg.nontype]/5, bullet 7
7086 
7087      For a non-type template-parameter of type pointer to data member,
7088      qualification conversions (_conv.qual_) are applied.  */
7089   else if (TYPE_PTRDATAMEM_P (type))
7090     {
7091       /* [temp.arg.nontype] bullet 1 says the pointer to member
7092          expression must be a pointer-to-member constant.  */
7093       if (!value_dependent_expression_p (expr)
7094 	  && !check_valid_ptrmem_cst_expr (type, expr, complain))
7095 	return NULL_TREE;
7096 
7097       expr = perform_qualification_conversions (type, expr);
7098       if (expr == error_mark_node)
7099 	return expr;
7100     }
7101   else if (NULLPTR_TYPE_P (type))
7102     {
7103       if (!NULLPTR_TYPE_P (TREE_TYPE (expr)))
7104 	{
7105 	  if (complain & tf_error)
7106 	    error ("%qE is not a valid template argument for type %qT "
7107 		   "because it is of type %qT", expr, type, TREE_TYPE (expr));
7108 	  return NULL_TREE;
7109 	}
7110       return expr;
7111     }
7112   /* A template non-type parameter must be one of the above.  */
7113   else
7114     gcc_unreachable ();
7115 
7116   /* Sanity check: did we actually convert the argument to the
7117      right type?  */
7118   gcc_assert (same_type_ignoring_top_level_qualifiers_p
7119 	      (type, TREE_TYPE (expr)));
7120   return convert_from_reference (expr);
7121 }
7122 
7123 /* Subroutine of coerce_template_template_parms, which returns 1 if
7124    PARM_PARM and ARG_PARM match using the rule for the template
7125    parameters of template template parameters. Both PARM and ARG are
7126    template parameters; the rest of the arguments are the same as for
7127    coerce_template_template_parms.
7128  */
7129 static int
coerce_template_template_parm(tree parm,tree arg,tsubst_flags_t complain,tree in_decl,tree outer_args)7130 coerce_template_template_parm (tree parm,
7131                               tree arg,
7132                               tsubst_flags_t complain,
7133                               tree in_decl,
7134                               tree outer_args)
7135 {
7136   if (arg == NULL_TREE || error_operand_p (arg)
7137       || parm == NULL_TREE || error_operand_p (parm))
7138     return 0;
7139 
7140   if (TREE_CODE (arg) != TREE_CODE (parm))
7141     return 0;
7142 
7143   switch (TREE_CODE (parm))
7144     {
7145     case TEMPLATE_DECL:
7146       /* We encounter instantiations of templates like
7147 	 template <template <template <class> class> class TT>
7148 	 class C;  */
7149       {
7150 	tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
7151 	tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
7152 
7153 	if (!coerce_template_template_parms
7154 	    (parmparm, argparm, complain, in_decl, outer_args))
7155 	  return 0;
7156       }
7157       /* Fall through.  */
7158 
7159     case TYPE_DECL:
7160       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
7161 	  && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
7162 	/* Argument is a parameter pack but parameter is not.  */
7163 	return 0;
7164       break;
7165 
7166     case PARM_DECL:
7167       /* The tsubst call is used to handle cases such as
7168 
7169            template <int> class C {};
7170 	   template <class T, template <T> class TT> class D {};
7171 	   D<int, C> d;
7172 
7173 	 i.e. the parameter list of TT depends on earlier parameters.  */
7174       if (!uses_template_parms (TREE_TYPE (arg)))
7175 	{
7176 	  tree t = tsubst (TREE_TYPE (parm), outer_args, complain, in_decl);
7177 	  if (!uses_template_parms (t)
7178 	      && !same_type_p (t, TREE_TYPE (arg)))
7179 	    return 0;
7180 	}
7181 
7182       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
7183 	  && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
7184 	/* Argument is a parameter pack but parameter is not.  */
7185 	return 0;
7186 
7187       break;
7188 
7189     default:
7190       gcc_unreachable ();
7191     }
7192 
7193   return 1;
7194 }
7195 
7196 /* Coerce template argument list ARGLIST for use with template
7197    template-parameter TEMPL.  */
7198 
7199 static tree
coerce_template_args_for_ttp(tree templ,tree arglist,tsubst_flags_t complain)7200 coerce_template_args_for_ttp (tree templ, tree arglist,
7201 			      tsubst_flags_t complain)
7202 {
7203   /* Consider an example where a template template parameter declared as
7204 
7205      template <class T, class U = std::allocator<T> > class TT
7206 
7207      The template parameter level of T and U are one level larger than
7208      of TT.  To proper process the default argument of U, say when an
7209      instantiation `TT<int>' is seen, we need to build the full
7210      arguments containing {int} as the innermost level.  Outer levels,
7211      available when not appearing as default template argument, can be
7212      obtained from the arguments of the enclosing template.
7213 
7214      Suppose that TT is later substituted with std::vector.  The above
7215      instantiation is `TT<int, std::allocator<T> >' with TT at
7216      level 1, and T at level 2, while the template arguments at level 1
7217      becomes {std::vector} and the inner level 2 is {int}.  */
7218 
7219   tree outer = DECL_CONTEXT (templ);
7220   if (outer)
7221     {
7222       if (DECL_TEMPLATE_SPECIALIZATION (outer))
7223 	/* We want arguments for the partial specialization, not arguments for
7224 	   the primary template.  */
7225 	outer = template_parms_to_args (DECL_TEMPLATE_PARMS (outer));
7226       else
7227 	outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
7228     }
7229   else if (current_template_parms)
7230     {
7231       /* This is an argument of the current template, so we haven't set
7232 	 DECL_CONTEXT yet.  */
7233       tree relevant_template_parms;
7234 
7235       /* Parameter levels that are greater than the level of the given
7236 	 template template parm are irrelevant.  */
7237       relevant_template_parms = current_template_parms;
7238       while (TMPL_PARMS_DEPTH (relevant_template_parms)
7239 	     != TEMPLATE_TYPE_LEVEL (TREE_TYPE (templ)))
7240 	relevant_template_parms = TREE_CHAIN (relevant_template_parms);
7241 
7242       outer = template_parms_to_args (relevant_template_parms);
7243     }
7244 
7245   if (outer)
7246     arglist = add_to_template_args (outer, arglist);
7247 
7248   tree parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
7249   return coerce_template_parms (parmlist, arglist, templ,
7250 				complain,
7251 				/*require_all_args=*/true,
7252 				/*use_default_args=*/true);
7253 }
7254 
7255 /* A cache of template template parameters with match-all default
7256    arguments.  */
7257 static GTY((deletable)) hash_map<tree,tree> *defaulted_ttp_cache;
7258 static void
store_defaulted_ttp(tree v,tree t)7259 store_defaulted_ttp (tree v, tree t)
7260 {
7261   if (!defaulted_ttp_cache)
7262     defaulted_ttp_cache = hash_map<tree,tree>::create_ggc (13);
7263   defaulted_ttp_cache->put (v, t);
7264 }
7265 static tree
lookup_defaulted_ttp(tree v)7266 lookup_defaulted_ttp (tree v)
7267 {
7268   if (defaulted_ttp_cache)
7269     if (tree *p = defaulted_ttp_cache->get (v))
7270       return *p;
7271   return NULL_TREE;
7272 }
7273 
7274 /* T is a bound template template-parameter.  Copy its arguments into default
7275    arguments of the template template-parameter's template parameters.  */
7276 
7277 static tree
add_defaults_to_ttp(tree otmpl)7278 add_defaults_to_ttp (tree otmpl)
7279 {
7280   if (tree c = lookup_defaulted_ttp (otmpl))
7281     return c;
7282 
7283   tree ntmpl = copy_node (otmpl);
7284 
7285   tree ntype = copy_node (TREE_TYPE (otmpl));
7286   TYPE_STUB_DECL (ntype) = TYPE_NAME (ntype) = ntmpl;
7287   TYPE_MAIN_VARIANT (ntype) = ntype;
7288   TYPE_POINTER_TO (ntype) = TYPE_REFERENCE_TO (ntype) = NULL_TREE;
7289   TYPE_NAME (ntype) = ntmpl;
7290   SET_TYPE_STRUCTURAL_EQUALITY (ntype);
7291 
7292   tree idx = TEMPLATE_TYPE_PARM_INDEX (ntype)
7293     = copy_node (TEMPLATE_TYPE_PARM_INDEX (ntype));
7294   TEMPLATE_PARM_DECL (idx) = ntmpl;
7295   TREE_TYPE (ntmpl) = TREE_TYPE (idx) = ntype;
7296 
7297   tree oparms = DECL_TEMPLATE_PARMS (otmpl);
7298   tree parms = DECL_TEMPLATE_PARMS (ntmpl) = copy_node (oparms);
7299   TREE_CHAIN (parms) = TREE_CHAIN (oparms);
7300   tree vec = TREE_VALUE (parms) = copy_node (TREE_VALUE (parms));
7301   for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
7302     {
7303       tree o = TREE_VEC_ELT (vec, i);
7304       if (!template_parameter_pack_p (TREE_VALUE (o)))
7305 	{
7306 	  tree n = TREE_VEC_ELT (vec, i) = copy_node (o);
7307 	  TREE_PURPOSE (n) = any_targ_node;
7308 	}
7309     }
7310 
7311   store_defaulted_ttp (otmpl, ntmpl);
7312   return ntmpl;
7313 }
7314 
7315 /* ARG is a bound potential template template-argument, and PARGS is a list
7316    of arguments for the corresponding template template-parameter.  Adjust
7317    PARGS as appropriate for application to ARG's template, and if ARG is a
7318    BOUND_TEMPLATE_TEMPLATE_PARM, possibly adjust it to add default template
7319    arguments to the template template parameter.  */
7320 
7321 static tree
coerce_ttp_args_for_tta(tree & arg,tree pargs,tsubst_flags_t complain)7322 coerce_ttp_args_for_tta (tree& arg, tree pargs, tsubst_flags_t complain)
7323 {
7324   ++processing_template_decl;
7325   tree arg_tmpl = TYPE_TI_TEMPLATE (arg);
7326   if (DECL_TEMPLATE_TEMPLATE_PARM_P (arg_tmpl))
7327     {
7328       /* When comparing two template template-parameters in partial ordering,
7329 	 rewrite the one currently being used as an argument to have default
7330 	 arguments for all parameters.  */
7331       arg_tmpl = add_defaults_to_ttp (arg_tmpl);
7332       pargs = coerce_template_args_for_ttp (arg_tmpl, pargs, complain);
7333       if (pargs != error_mark_node)
7334 	arg = bind_template_template_parm (TREE_TYPE (arg_tmpl),
7335 					   TYPE_TI_ARGS (arg));
7336     }
7337   else
7338     {
7339       tree aparms
7340 	= INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (arg_tmpl));
7341       pargs = coerce_template_parms (aparms, pargs, arg_tmpl, complain,
7342 				       /*require_all*/true,
7343 				       /*use_default*/true);
7344     }
7345   --processing_template_decl;
7346   return pargs;
7347 }
7348 
7349 /* Subroutine of unify for the case when PARM is a
7350    BOUND_TEMPLATE_TEMPLATE_PARM.  */
7351 
7352 static int
unify_bound_ttp_args(tree tparms,tree targs,tree parm,tree & arg,bool explain_p)7353 unify_bound_ttp_args (tree tparms, tree targs, tree parm, tree& arg,
7354 		      bool explain_p)
7355 {
7356   tree parmvec = TYPE_TI_ARGS (parm);
7357   tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
7358 
7359   /* The template template parm might be variadic and the argument
7360      not, so flatten both argument lists.  */
7361   parmvec = expand_template_argument_pack (parmvec);
7362   argvec = expand_template_argument_pack (argvec);
7363 
7364   if (flag_new_ttp)
7365     {
7366       /* In keeping with P0522R0, adjust P's template arguments
7367 	 to apply to A's template; then flatten it again.  */
7368       tree nparmvec = parmvec;
7369       nparmvec = coerce_ttp_args_for_tta (arg, parmvec, tf_none);
7370       nparmvec = expand_template_argument_pack (nparmvec);
7371 
7372       if (unify (tparms, targs, nparmvec, argvec,
7373 		 UNIFY_ALLOW_NONE, explain_p))
7374 	return 1;
7375 
7376       /* If the P0522 adjustment eliminated a pack expansion, deduce
7377 	 empty packs.  */
7378       if (flag_new_ttp
7379 	  && TREE_VEC_LENGTH (nparmvec) < TREE_VEC_LENGTH (parmvec)
7380 	  && unify_pack_expansion (tparms, targs, parmvec, argvec,
7381 				   DEDUCE_EXACT, /*sub*/true, explain_p))
7382 	return 1;
7383     }
7384   else
7385     {
7386       /* Deduce arguments T, i from TT<T> or TT<i>.
7387 	 We check each element of PARMVEC and ARGVEC individually
7388 	 rather than the whole TREE_VEC since they can have
7389 	 different number of elements, which is allowed under N2555.  */
7390 
7391       int len = TREE_VEC_LENGTH (parmvec);
7392 
7393       /* Check if the parameters end in a pack, making them
7394 	 variadic.  */
7395       int parm_variadic_p = 0;
7396       if (len > 0
7397 	  && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
7398 	parm_variadic_p = 1;
7399 
7400       for (int i = 0; i < len - parm_variadic_p; ++i)
7401 	/* If the template argument list of P contains a pack
7402 	   expansion that is not the last template argument, the
7403 	   entire template argument list is a non-deduced
7404 	   context.  */
7405 	if (PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, i)))
7406 	  return unify_success (explain_p);
7407 
7408       if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
7409 	return unify_too_few_arguments (explain_p,
7410 					TREE_VEC_LENGTH (argvec), len);
7411 
7412       for (int i = 0; i < len - parm_variadic_p; ++i)
7413 	if (unify (tparms, targs,
7414 		   TREE_VEC_ELT (parmvec, i),
7415 		   TREE_VEC_ELT (argvec, i),
7416 		   UNIFY_ALLOW_NONE, explain_p))
7417 	  return 1;
7418 
7419       if (parm_variadic_p
7420 	  && unify_pack_expansion (tparms, targs,
7421 				   parmvec, argvec,
7422 				   DEDUCE_EXACT,
7423 				   /*subr=*/true, explain_p))
7424 	return 1;
7425     }
7426 
7427   return 0;
7428 }
7429 
7430 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
7431    template template parameters.  Both PARM_PARMS and ARG_PARMS are
7432    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
7433    or PARM_DECL.
7434 
7435    Consider the example:
7436      template <class T> class A;
7437      template<template <class U> class TT> class B;
7438 
7439    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
7440    the parameters to A, and OUTER_ARGS contains A.  */
7441 
7442 static int
coerce_template_template_parms(tree parm_parms,tree arg_parms,tsubst_flags_t complain,tree in_decl,tree outer_args)7443 coerce_template_template_parms (tree parm_parms,
7444 				tree arg_parms,
7445 				tsubst_flags_t complain,
7446 				tree in_decl,
7447 				tree outer_args)
7448 {
7449   int nparms, nargs, i;
7450   tree parm, arg;
7451   int variadic_p = 0;
7452 
7453   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
7454   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
7455 
7456   nparms = TREE_VEC_LENGTH (parm_parms);
7457   nargs = TREE_VEC_LENGTH (arg_parms);
7458 
7459   if (flag_new_ttp)
7460     {
7461       /* P0522R0: A template template-parameter P is at least as specialized as
7462 	 a template template-argument A if, given the following rewrite to two
7463 	 function templates, the function template corresponding to P is at
7464 	 least as specialized as the function template corresponding to A
7465 	 according to the partial ordering rules for function templates
7466 	 ([temp.func.order]). Given an invented class template X with the
7467 	 template parameter list of A (including default arguments):
7468 
7469 	 * Each of the two function templates has the same template parameters,
7470 	 respectively, as P or A.
7471 
7472 	 * Each function template has a single function parameter whose type is
7473 	 a specialization of X with template arguments corresponding to the
7474 	 template parameters from the respective function template where, for
7475 	 each template parameter PP in the template parameter list of the
7476 	 function template, a corresponding template argument AA is formed. If
7477 	 PP declares a parameter pack, then AA is the pack expansion
7478 	 PP... ([temp.variadic]); otherwise, AA is the id-expression PP.
7479 
7480 	 If the rewrite produces an invalid type, then P is not at least as
7481 	 specialized as A.  */
7482 
7483       /* So coerce P's args to apply to A's parms, and then deduce between A's
7484 	 args and the converted args.  If that succeeds, A is at least as
7485 	 specialized as P, so they match.*/
7486       tree pargs = template_parms_level_to_args (parm_parms);
7487       ++processing_template_decl;
7488       pargs = coerce_template_parms (arg_parms, pargs, NULL_TREE, tf_none,
7489 				     /*require_all*/true, /*use_default*/true);
7490       --processing_template_decl;
7491       if (pargs != error_mark_node)
7492 	{
7493 	  tree targs = make_tree_vec (nargs);
7494 	  tree aargs = template_parms_level_to_args (arg_parms);
7495 	  if (!unify (arg_parms, targs, aargs, pargs, UNIFY_ALLOW_NONE,
7496 		      /*explain*/false))
7497 	    return 1;
7498 	}
7499     }
7500 
7501   /* Determine whether we have a parameter pack at the end of the
7502      template template parameter's template parameter list.  */
7503   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
7504     {
7505       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
7506 
7507       if (error_operand_p (parm))
7508 	return 0;
7509 
7510       switch (TREE_CODE (parm))
7511         {
7512         case TEMPLATE_DECL:
7513         case TYPE_DECL:
7514           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
7515             variadic_p = 1;
7516           break;
7517 
7518         case PARM_DECL:
7519           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
7520             variadic_p = 1;
7521           break;
7522 
7523         default:
7524           gcc_unreachable ();
7525         }
7526     }
7527 
7528   if (nargs != nparms
7529       && !(variadic_p && nargs >= nparms - 1))
7530     return 0;
7531 
7532   /* Check all of the template parameters except the parameter pack at
7533      the end (if any).  */
7534   for (i = 0; i < nparms - variadic_p; ++i)
7535     {
7536       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
7537           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
7538         continue;
7539 
7540       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
7541       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
7542 
7543       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
7544                                           outer_args))
7545 	return 0;
7546 
7547     }
7548 
7549   if (variadic_p)
7550     {
7551       /* Check each of the template parameters in the template
7552 	 argument against the template parameter pack at the end of
7553 	 the template template parameter.  */
7554       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
7555 	return 0;
7556 
7557       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
7558 
7559       for (; i < nargs; ++i)
7560         {
7561           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
7562             continue;
7563 
7564           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
7565 
7566           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
7567                                               outer_args))
7568             return 0;
7569         }
7570     }
7571 
7572   return 1;
7573 }
7574 
7575 /* Verifies that the deduced template arguments (in TARGS) for the
7576    template template parameters (in TPARMS) represent valid bindings,
7577    by comparing the template parameter list of each template argument
7578    to the template parameter list of its corresponding template
7579    template parameter, in accordance with DR150. This
7580    routine can only be called after all template arguments have been
7581    deduced. It will return TRUE if all of the template template
7582    parameter bindings are okay, FALSE otherwise.  */
7583 bool
template_template_parm_bindings_ok_p(tree tparms,tree targs)7584 template_template_parm_bindings_ok_p (tree tparms, tree targs)
7585 {
7586   int i, ntparms = TREE_VEC_LENGTH (tparms);
7587   bool ret = true;
7588 
7589   /* We're dealing with template parms in this process.  */
7590   ++processing_template_decl;
7591 
7592   targs = INNERMOST_TEMPLATE_ARGS (targs);
7593 
7594   for (i = 0; i < ntparms; ++i)
7595     {
7596       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
7597       tree targ = TREE_VEC_ELT (targs, i);
7598 
7599       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
7600 	{
7601 	  tree packed_args = NULL_TREE;
7602 	  int idx, len = 1;
7603 
7604 	  if (ARGUMENT_PACK_P (targ))
7605 	    {
7606 	      /* Look inside the argument pack.  */
7607 	      packed_args = ARGUMENT_PACK_ARGS (targ);
7608 	      len = TREE_VEC_LENGTH (packed_args);
7609 	    }
7610 
7611 	  for (idx = 0; idx < len; ++idx)
7612 	    {
7613 	      tree targ_parms = NULL_TREE;
7614 
7615 	      if (packed_args)
7616 		/* Extract the next argument from the argument
7617 		   pack.  */
7618 		targ = TREE_VEC_ELT (packed_args, idx);
7619 
7620 	      if (PACK_EXPANSION_P (targ))
7621 		/* Look at the pattern of the pack expansion.  */
7622 		targ = PACK_EXPANSION_PATTERN (targ);
7623 
7624 	      /* Extract the template parameters from the template
7625 		 argument.  */
7626 	      if (TREE_CODE (targ) == TEMPLATE_DECL)
7627 		targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
7628 	      else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
7629 		targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
7630 
7631 	      /* Verify that we can coerce the template template
7632 		 parameters from the template argument to the template
7633 		 parameter.  This requires an exact match.  */
7634 	      if (targ_parms
7635 		  && !coerce_template_template_parms
7636 		       (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
7637 			targ_parms,
7638 			tf_none,
7639 			tparm,
7640 			targs))
7641 		{
7642 		  ret = false;
7643 		  goto out;
7644 		}
7645 	    }
7646 	}
7647     }
7648 
7649  out:
7650 
7651   --processing_template_decl;
7652   return ret;
7653 }
7654 
7655 /* Since type attributes aren't mangled, we need to strip them from
7656    template type arguments.  */
7657 
7658 static tree
canonicalize_type_argument(tree arg,tsubst_flags_t complain)7659 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
7660 {
7661   if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
7662     return arg;
7663   bool removed_attributes = false;
7664   tree canon = strip_typedefs (arg, &removed_attributes);
7665   if (removed_attributes
7666       && (complain & tf_warning))
7667     warning (OPT_Wignored_attributes,
7668 	     "ignoring attributes on template argument %qT", arg);
7669   return canon;
7670 }
7671 
7672 /* And from inside dependent non-type arguments like sizeof(Type).  */
7673 
7674 static tree
canonicalize_expr_argument(tree arg,tsubst_flags_t complain)7675 canonicalize_expr_argument (tree arg, tsubst_flags_t complain)
7676 {
7677   if (!arg || arg == error_mark_node)
7678     return arg;
7679   bool removed_attributes = false;
7680   tree canon = strip_typedefs_expr (arg, &removed_attributes);
7681   if (removed_attributes
7682       && (complain & tf_warning))
7683     warning (OPT_Wignored_attributes,
7684 	     "ignoring attributes in template argument %qE", arg);
7685   return canon;
7686 }
7687 
7688 // A template declaration can be substituted for a constrained
7689 // template template parameter only when the argument is more
7690 // constrained than the parameter.
7691 static bool
is_compatible_template_arg(tree parm,tree arg)7692 is_compatible_template_arg (tree parm, tree arg)
7693 {
7694   tree parm_cons = get_constraints (parm);
7695 
7696   /* For now, allow constrained template template arguments
7697      and unconstrained template template parameters.  */
7698   if (parm_cons == NULL_TREE)
7699     return true;
7700 
7701   tree arg_cons = get_constraints (arg);
7702 
7703   // If the template parameter is constrained, we need to rewrite its
7704   // constraints in terms of the ARG's template parameters. This ensures
7705   // that all of the template parameter types will have the same depth.
7706   //
7707   // Note that this is only valid when coerce_template_template_parm is
7708   // true for the innermost template parameters of PARM and ARG. In other
7709   // words, because coercion is successful, this conversion will be valid.
7710   if (parm_cons)
7711     {
7712       tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (arg));
7713       parm_cons = tsubst_constraint_info (parm_cons,
7714 					  INNERMOST_TEMPLATE_ARGS (args),
7715 					  tf_none, NULL_TREE);
7716       if (parm_cons == error_mark_node)
7717         return false;
7718     }
7719 
7720   return subsumes (parm_cons, arg_cons);
7721 }
7722 
7723 // Convert a placeholder argument into a binding to the original
7724 // parameter. The original parameter is saved as the TREE_TYPE of
7725 // ARG.
7726 static inline tree
convert_wildcard_argument(tree parm,tree arg)7727 convert_wildcard_argument (tree parm, tree arg)
7728 {
7729   TREE_TYPE (arg) = parm;
7730   return arg;
7731 }
7732 
7733 /* We can't fully resolve ARG given as a non-type template argument to TYPE,
7734    because one of them is dependent.  But we need to represent the
7735    conversion for the benefit of cp_tree_equal.  */
7736 
7737 static tree
maybe_convert_nontype_argument(tree type,tree arg)7738 maybe_convert_nontype_argument (tree type, tree arg)
7739 {
7740   /* Auto parms get no conversion.  */
7741   if (type_uses_auto (type))
7742     return arg;
7743   /* We don't need or want to add this conversion now if we're going to use the
7744      argument for deduction.  */
7745   if (value_dependent_expression_p (arg))
7746     return arg;
7747 
7748   type = cv_unqualified (type);
7749   tree argtype = TREE_TYPE (arg);
7750   if (same_type_p (type, argtype))
7751     return arg;
7752 
7753   arg = build1 (IMPLICIT_CONV_EXPR, type, arg);
7754   IMPLICIT_CONV_EXPR_NONTYPE_ARG (arg) = true;
7755   return arg;
7756 }
7757 
7758 /* Convert the indicated template ARG as necessary to match the
7759    indicated template PARM.  Returns the converted ARG, or
7760    error_mark_node if the conversion was unsuccessful.  Error and
7761    warning messages are issued under control of COMPLAIN.  This
7762    conversion is for the Ith parameter in the parameter list.  ARGS is
7763    the full set of template arguments deduced so far.  */
7764 
7765 static tree
convert_template_argument(tree parm,tree arg,tree args,tsubst_flags_t complain,int i,tree in_decl)7766 convert_template_argument (tree parm,
7767 			   tree arg,
7768 			   tree args,
7769 			   tsubst_flags_t complain,
7770 			   int i,
7771 			   tree in_decl)
7772 {
7773   tree orig_arg;
7774   tree val;
7775   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
7776 
7777   if (parm == error_mark_node)
7778     return error_mark_node;
7779 
7780   /* Trivially convert placeholders. */
7781   if (TREE_CODE (arg) == WILDCARD_DECL)
7782     return convert_wildcard_argument (parm, arg);
7783 
7784   if (arg == any_targ_node)
7785     return arg;
7786 
7787   if (TREE_CODE (arg) == TREE_LIST
7788       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
7789     {
7790       /* The template argument was the name of some
7791 	 member function.  That's usually
7792 	 invalid, but static members are OK.  In any
7793 	 case, grab the underlying fields/functions
7794 	 and issue an error later if required.  */
7795       orig_arg = TREE_VALUE (arg);
7796       TREE_TYPE (arg) = unknown_type_node;
7797     }
7798 
7799   orig_arg = arg;
7800 
7801   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
7802   requires_type = (TREE_CODE (parm) == TYPE_DECL
7803 		   || requires_tmpl_type);
7804 
7805   /* When determining whether an argument pack expansion is a template,
7806      look at the pattern.  */
7807   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
7808     arg = PACK_EXPANSION_PATTERN (arg);
7809 
7810   /* Deal with an injected-class-name used as a template template arg.  */
7811   if (requires_tmpl_type && CLASS_TYPE_P (arg))
7812     {
7813       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
7814       if (TREE_CODE (t) == TEMPLATE_DECL)
7815 	{
7816 	  if (cxx_dialect >= cxx11)
7817 	    /* OK under DR 1004.  */;
7818 	  else if (complain & tf_warning_or_error)
7819 	    pedwarn (input_location, OPT_Wpedantic, "injected-class-name %qD"
7820 		     " used as template template argument", TYPE_NAME (arg));
7821 	  else if (flag_pedantic_errors)
7822 	    t = arg;
7823 
7824 	  arg = t;
7825 	}
7826     }
7827 
7828   is_tmpl_type =
7829     ((TREE_CODE (arg) == TEMPLATE_DECL
7830       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
7831      || (requires_tmpl_type && TREE_CODE (arg) == TYPE_ARGUMENT_PACK)
7832      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
7833      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
7834 
7835   if (is_tmpl_type
7836       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
7837 	  || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
7838     arg = TYPE_STUB_DECL (arg);
7839 
7840   is_type = TYPE_P (arg) || is_tmpl_type;
7841 
7842   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
7843       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
7844     {
7845       if (TREE_CODE (TREE_OPERAND (arg, 1)) == BIT_NOT_EXPR)
7846 	{
7847 	  if (complain & tf_error)
7848 	    error ("invalid use of destructor %qE as a type", orig_arg);
7849 	  return error_mark_node;
7850 	}
7851 
7852       permerror (input_location,
7853 		 "to refer to a type member of a template parameter, "
7854 		 "use %<typename %E%>", orig_arg);
7855 
7856       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
7857 				     TREE_OPERAND (arg, 1),
7858 				     typename_type,
7859 				     complain);
7860       arg = orig_arg;
7861       is_type = 1;
7862     }
7863   if (is_type != requires_type)
7864     {
7865       if (in_decl)
7866 	{
7867 	  if (complain & tf_error)
7868 	    {
7869 	      error ("type/value mismatch at argument %d in template "
7870 		     "parameter list for %qD",
7871 		     i + 1, in_decl);
7872 	      if (is_type)
7873 		inform (input_location,
7874 			"  expected a constant of type %qT, got %qT",
7875 			TREE_TYPE (parm),
7876 			(DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
7877 	      else if (requires_tmpl_type)
7878 		inform (input_location,
7879 			"  expected a class template, got %qE", orig_arg);
7880 	      else
7881 		inform (input_location,
7882 			"  expected a type, got %qE", orig_arg);
7883 	    }
7884 	}
7885       return error_mark_node;
7886     }
7887   if (is_tmpl_type ^ requires_tmpl_type)
7888     {
7889       if (in_decl && (complain & tf_error))
7890 	{
7891 	  error ("type/value mismatch at argument %d in template "
7892 		 "parameter list for %qD",
7893 		 i + 1, in_decl);
7894 	  if (is_tmpl_type)
7895 	    inform (input_location,
7896 		    "  expected a type, got %qT", DECL_NAME (arg));
7897 	  else
7898 	    inform (input_location,
7899 		    "  expected a class template, got %qT", orig_arg);
7900 	}
7901       return error_mark_node;
7902     }
7903 
7904   if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
7905     /* We already did the appropriate conversion when packing args.  */
7906     val = orig_arg;
7907   else if (is_type)
7908     {
7909       if (requires_tmpl_type)
7910 	{
7911 	  if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
7912 	    /* The number of argument required is not known yet.
7913 	       Just accept it for now.  */
7914 	    val = orig_arg;
7915 	  else
7916 	    {
7917 	      tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
7918 	      tree argparm;
7919 
7920 	      /* Strip alias templates that are equivalent to another
7921 		 template.  */
7922 	      arg = get_underlying_template (arg);
7923               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
7924 
7925 	      if (coerce_template_template_parms (parmparm, argparm,
7926 						  complain, in_decl,
7927 						  args))
7928 		{
7929 		  val = arg;
7930 
7931 		  /* TEMPLATE_TEMPLATE_PARM node is preferred over
7932 		     TEMPLATE_DECL.  */
7933 		  if (val != error_mark_node)
7934                     {
7935                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
7936                         val = TREE_TYPE (val);
7937 		      if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
7938 			val = make_pack_expansion (val, complain);
7939                     }
7940 		}
7941 	      else
7942 		{
7943 		  if (in_decl && (complain & tf_error))
7944 		    {
7945 		      error ("type/value mismatch at argument %d in "
7946 			     "template parameter list for %qD",
7947 			     i + 1, in_decl);
7948 		      inform (input_location,
7949 			      "  expected a template of type %qD, got %qT",
7950 			      parm, orig_arg);
7951 		    }
7952 
7953 		  val = error_mark_node;
7954 		}
7955 
7956               // Check that the constraints are compatible before allowing the
7957               // substitution.
7958               if (val != error_mark_node)
7959                 if (!is_compatible_template_arg (parm, arg))
7960                   {
7961 		    if (in_decl && (complain & tf_error))
7962                       {
7963                         error ("constraint mismatch at argument %d in "
7964                                "template parameter list for %qD",
7965                                i + 1, in_decl);
7966                         inform (input_location, "  expected %qD but got %qD",
7967                                 parm, arg);
7968                       }
7969 		    val = error_mark_node;
7970                   }
7971 	    }
7972 	}
7973       else
7974 	val = orig_arg;
7975       /* We only form one instance of each template specialization.
7976 	 Therefore, if we use a non-canonical variant (i.e., a
7977 	 typedef), any future messages referring to the type will use
7978 	 the typedef, which is confusing if those future uses do not
7979 	 themselves also use the typedef.  */
7980       if (TYPE_P (val))
7981 	val = canonicalize_type_argument (val, complain);
7982     }
7983   else
7984     {
7985       tree t = TREE_TYPE (parm);
7986 
7987       if (TEMPLATE_PARM_LEVEL (get_template_parm_index (parm))
7988 	  > TMPL_ARGS_DEPTH (args))
7989 	/* We don't have enough levels of args to do any substitution.  This
7990 	   can happen in the context of -fnew-ttp-matching.  */;
7991       else if (tree a = type_uses_auto (t))
7992 	{
7993 	  t = do_auto_deduction (t, arg, a, complain, adc_unify, args);
7994 	  if (t == error_mark_node)
7995 	    return error_mark_node;
7996 	}
7997       else
7998 	t = tsubst (t, args, complain, in_decl);
7999 
8000       if (invalid_nontype_parm_type_p (t, complain))
8001 	return error_mark_node;
8002 
8003       if (!type_dependent_expression_p (orig_arg)
8004 	  && !uses_template_parms (t))
8005 	/* We used to call digest_init here.  However, digest_init
8006 	   will report errors, which we don't want when complain
8007 	   is zero.  More importantly, digest_init will try too
8008 	   hard to convert things: for example, `0' should not be
8009 	   converted to pointer type at this point according to
8010 	   the standard.  Accepting this is not merely an
8011 	   extension, since deciding whether or not these
8012 	   conversions can occur is part of determining which
8013 	   function template to call, or whether a given explicit
8014 	   argument specification is valid.  */
8015 	val = convert_nontype_argument (t, orig_arg, complain);
8016       else
8017 	{
8018 	  val = canonicalize_expr_argument (orig_arg, complain);
8019 	  val = maybe_convert_nontype_argument (t, val);
8020 	}
8021 
8022 
8023       if (val == NULL_TREE)
8024 	val = error_mark_node;
8025       else if (val == error_mark_node && (complain & tf_error))
8026 	error ("could not convert template argument %qE from %qT to %qT",
8027 	       orig_arg, TREE_TYPE (orig_arg), t);
8028 
8029       if (INDIRECT_REF_P (val))
8030         {
8031           /* Reject template arguments that are references to built-in
8032              functions with no library fallbacks.  */
8033           const_tree inner = TREE_OPERAND (val, 0);
8034 	  const_tree innertype = TREE_TYPE (inner);
8035 	  if (innertype
8036 	      && TREE_CODE (innertype) == REFERENCE_TYPE
8037 	      && TREE_CODE (TREE_TYPE (innertype)) == FUNCTION_TYPE
8038 	      && TREE_OPERAND_LENGTH (inner) > 0
8039               && reject_gcc_builtin (TREE_OPERAND (inner, 0)))
8040               return error_mark_node;
8041         }
8042 
8043       if (TREE_CODE (val) == SCOPE_REF)
8044 	{
8045 	  /* Strip typedefs from the SCOPE_REF.  */
8046 	  tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
8047 	  tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
8048 						   complain);
8049 	  val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
8050 				      QUALIFIED_NAME_IS_TEMPLATE (val));
8051 	}
8052     }
8053 
8054   return val;
8055 }
8056 
8057 /* Coerces the remaining template arguments in INNER_ARGS (from
8058    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
8059    Returns the coerced argument pack. PARM_IDX is the position of this
8060    parameter in the template parameter list. ARGS is the original
8061    template argument list.  */
8062 static tree
coerce_template_parameter_pack(tree parms,int parm_idx,tree args,tree inner_args,int arg_idx,tree new_args,int * lost,tree in_decl,tsubst_flags_t complain)8063 coerce_template_parameter_pack (tree parms,
8064                                 int parm_idx,
8065                                 tree args,
8066                                 tree inner_args,
8067                                 int arg_idx,
8068                                 tree new_args,
8069                                 int* lost,
8070                                 tree in_decl,
8071                                 tsubst_flags_t complain)
8072 {
8073   tree parm = TREE_VEC_ELT (parms, parm_idx);
8074   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8075   tree packed_args;
8076   tree argument_pack;
8077   tree packed_parms = NULL_TREE;
8078 
8079   if (arg_idx > nargs)
8080     arg_idx = nargs;
8081 
8082   if (tree packs = fixed_parameter_pack_p (TREE_VALUE (parm)))
8083     {
8084       /* When the template parameter is a non-type template parameter pack
8085          or template template parameter pack whose type or template
8086          parameters use parameter packs, we know exactly how many arguments
8087          we are looking for.  Build a vector of the instantiated decls for
8088          these template parameters in PACKED_PARMS.  */
8089       /* We can't use make_pack_expansion here because it would interpret a
8090 	 _DECL as a use rather than a declaration.  */
8091       tree decl = TREE_VALUE (parm);
8092       tree exp = cxx_make_type (TYPE_PACK_EXPANSION);
8093       SET_PACK_EXPANSION_PATTERN (exp, decl);
8094       PACK_EXPANSION_PARAMETER_PACKS (exp) = packs;
8095       SET_TYPE_STRUCTURAL_EQUALITY (exp);
8096 
8097       TREE_VEC_LENGTH (args)--;
8098       packed_parms = tsubst_pack_expansion (exp, args, complain, decl);
8099       TREE_VEC_LENGTH (args)++;
8100 
8101       if (packed_parms == error_mark_node)
8102         return error_mark_node;
8103 
8104       /* If we're doing a partial instantiation of a member template,
8105          verify that all of the types used for the non-type
8106          template parameter pack are, in fact, valid for non-type
8107          template parameters.  */
8108       if (arg_idx < nargs
8109           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
8110         {
8111           int j, len = TREE_VEC_LENGTH (packed_parms);
8112           for (j = 0; j < len; ++j)
8113             {
8114               tree t = TREE_TYPE (TREE_VEC_ELT (packed_parms, j));
8115               if (invalid_nontype_parm_type_p (t, complain))
8116                 return error_mark_node;
8117             }
8118 	  /* We don't know how many args we have yet, just
8119 	     use the unconverted ones for now.  */
8120 	  return NULL_TREE;
8121         }
8122 
8123       packed_args = make_tree_vec (TREE_VEC_LENGTH (packed_parms));
8124     }
8125   /* Check if we have a placeholder pack, which indicates we're
8126      in the context of a introduction list.  In that case we want
8127      to match this pack to the single placeholder.  */
8128   else if (arg_idx < nargs
8129            && TREE_CODE (TREE_VEC_ELT (inner_args, arg_idx)) == WILDCARD_DECL
8130            && WILDCARD_PACK_P (TREE_VEC_ELT (inner_args, arg_idx)))
8131     {
8132       nargs = arg_idx + 1;
8133       packed_args = make_tree_vec (1);
8134     }
8135   else
8136     packed_args = make_tree_vec (nargs - arg_idx);
8137 
8138   /* Convert the remaining arguments, which will be a part of the
8139      parameter pack "parm".  */
8140   int first_pack_arg = arg_idx;
8141   for (; arg_idx < nargs; ++arg_idx)
8142     {
8143       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
8144       tree actual_parm = TREE_VALUE (parm);
8145       int pack_idx = arg_idx - first_pack_arg;
8146 
8147       if (packed_parms)
8148         {
8149 	  /* Once we've packed as many args as we have types, stop.  */
8150 	  if (pack_idx >= TREE_VEC_LENGTH (packed_parms))
8151 	    break;
8152 	  else if (PACK_EXPANSION_P (arg))
8153 	    /* We don't know how many args we have yet, just
8154 	       use the unconverted ones for now.  */
8155 	    return NULL_TREE;
8156 	  else
8157 	    actual_parm = TREE_VEC_ELT (packed_parms, pack_idx);
8158         }
8159 
8160       if (arg == error_mark_node)
8161 	{
8162 	  if (complain & tf_error)
8163 	    error ("template argument %d is invalid", arg_idx + 1);
8164 	}
8165       else
8166 	arg = convert_template_argument (actual_parm,
8167 					 arg, new_args, complain, parm_idx,
8168 					 in_decl);
8169       if (arg == error_mark_node)
8170         (*lost)++;
8171       TREE_VEC_ELT (packed_args, pack_idx) = arg;
8172     }
8173 
8174   if (arg_idx - first_pack_arg < TREE_VEC_LENGTH (packed_args)
8175       && TREE_VEC_LENGTH (packed_args) > 0)
8176     {
8177       if (complain & tf_error)
8178 	error ("wrong number of template arguments (%d, should be %d)",
8179 	       arg_idx - first_pack_arg, TREE_VEC_LENGTH (packed_args));
8180       return error_mark_node;
8181     }
8182 
8183   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
8184       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
8185     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
8186   else
8187     {
8188       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
8189       TREE_CONSTANT (argument_pack) = 1;
8190     }
8191 
8192   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
8193   if (CHECKING_P)
8194     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
8195 					 TREE_VEC_LENGTH (packed_args));
8196   return argument_pack;
8197 }
8198 
8199 /* Returns the number of pack expansions in the template argument vector
8200    ARGS.  */
8201 
8202 static int
pack_expansion_args_count(tree args)8203 pack_expansion_args_count (tree args)
8204 {
8205   int i;
8206   int count = 0;
8207   if (args)
8208     for (i = 0; i < TREE_VEC_LENGTH (args); ++i)
8209       {
8210 	tree elt = TREE_VEC_ELT (args, i);
8211 	if (elt && PACK_EXPANSION_P (elt))
8212 	  ++count;
8213       }
8214   return count;
8215 }
8216 
8217 /* Convert all template arguments to their appropriate types, and
8218    return a vector containing the innermost resulting template
8219    arguments.  If any error occurs, return error_mark_node. Error and
8220    warning messages are issued under control of COMPLAIN.
8221 
8222    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
8223    for arguments not specified in ARGS.  Otherwise, if
8224    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
8225    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
8226    USE_DEFAULT_ARGS is false, then all arguments must be specified in
8227    ARGS.  */
8228 
8229 static tree
coerce_template_parms(tree parms,tree args,tree in_decl,tsubst_flags_t complain,bool require_all_args,bool use_default_args)8230 coerce_template_parms (tree parms,
8231 		       tree args,
8232 		       tree in_decl,
8233 		       tsubst_flags_t complain,
8234 		       bool require_all_args,
8235 		       bool use_default_args)
8236 {
8237   int nparms, nargs, parm_idx, arg_idx, lost = 0;
8238   tree orig_inner_args;
8239   tree inner_args;
8240   tree new_args;
8241   tree new_inner_args;
8242   int saved_unevaluated_operand;
8243   int saved_inhibit_evaluation_warnings;
8244 
8245   /* When used as a boolean value, indicates whether this is a
8246      variadic template parameter list. Since it's an int, we can also
8247      subtract it from nparms to get the number of non-variadic
8248      parameters.  */
8249   int variadic_p = 0;
8250   int variadic_args_p = 0;
8251   int post_variadic_parms = 0;
8252 
8253   /* Adjustment to nparms for fixed parameter packs.  */
8254   int fixed_pack_adjust = 0;
8255   int fixed_packs = 0;
8256   int missing = 0;
8257 
8258   /* Likewise for parameters with default arguments.  */
8259   int default_p = 0;
8260 
8261   if (args == error_mark_node)
8262     return error_mark_node;
8263 
8264   nparms = TREE_VEC_LENGTH (parms);
8265 
8266   /* Determine if there are any parameter packs or default arguments.  */
8267   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
8268     {
8269       tree parm = TREE_VEC_ELT (parms, parm_idx);
8270       if (variadic_p)
8271 	++post_variadic_parms;
8272       if (template_parameter_pack_p (TREE_VALUE (parm)))
8273 	++variadic_p;
8274       if (TREE_PURPOSE (parm))
8275 	++default_p;
8276     }
8277 
8278   inner_args = orig_inner_args = INNERMOST_TEMPLATE_ARGS (args);
8279   /* If there are no parameters that follow a parameter pack, we need to
8280      expand any argument packs so that we can deduce a parameter pack from
8281      some non-packed args followed by an argument pack, as in variadic85.C.
8282      If there are such parameters, we need to leave argument packs intact
8283      so the arguments are assigned properly.  This can happen when dealing
8284      with a nested class inside a partial specialization of a class
8285      template, as in variadic92.C, or when deducing a template parameter pack
8286      from a sub-declarator, as in variadic114.C.  */
8287   if (!post_variadic_parms)
8288     inner_args = expand_template_argument_pack (inner_args);
8289 
8290   /* Count any pack expansion args.  */
8291   variadic_args_p = pack_expansion_args_count (inner_args);
8292 
8293   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
8294   if ((nargs - variadic_args_p > nparms && !variadic_p)
8295       || (nargs < nparms - variadic_p
8296 	  && require_all_args
8297 	  && !variadic_args_p
8298 	  && (!use_default_args
8299 	      || (TREE_VEC_ELT (parms, nargs) != error_mark_node
8300                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
8301     {
8302     bad_nargs:
8303       if (complain & tf_error)
8304 	{
8305           if (variadic_p || default_p)
8306             {
8307               nparms -= variadic_p + default_p;
8308 	      error ("wrong number of template arguments "
8309 		     "(%d, should be at least %d)", nargs, nparms);
8310             }
8311 	  else
8312 	     error ("wrong number of template arguments "
8313 		    "(%d, should be %d)", nargs, nparms);
8314 
8315 	  if (in_decl)
8316 	    inform (DECL_SOURCE_LOCATION (in_decl),
8317 		    "provided for %qD", in_decl);
8318 	}
8319 
8320       return error_mark_node;
8321     }
8322   /* We can't pass a pack expansion to a non-pack parameter of an alias
8323      template (DR 1430).  */
8324   else if (in_decl
8325 	   && (DECL_ALIAS_TEMPLATE_P (in_decl)
8326 	       || concept_template_p (in_decl))
8327 	   && variadic_args_p
8328 	   && nargs - variadic_args_p < nparms - variadic_p)
8329     {
8330       if (complain & tf_error)
8331 	{
8332 	  for (int i = 0; i < TREE_VEC_LENGTH (inner_args); ++i)
8333 	    {
8334 	      tree arg = TREE_VEC_ELT (inner_args, i);
8335 	      tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
8336 
8337 	      if (PACK_EXPANSION_P (arg)
8338 		  && !template_parameter_pack_p (parm))
8339 		{
8340 		  if (DECL_ALIAS_TEMPLATE_P (in_decl))
8341 		    error_at (location_of (arg),
8342 			      "pack expansion argument for non-pack parameter "
8343 			      "%qD of alias template %qD", parm, in_decl);
8344 		  else
8345 		    error_at (location_of (arg),
8346 			      "pack expansion argument for non-pack parameter "
8347 			      "%qD of concept %qD", parm, in_decl);
8348 		  inform (DECL_SOURCE_LOCATION (parm), "declared here");
8349 		  goto found;
8350 		}
8351 	    }
8352 	  gcc_unreachable ();
8353 	found:;
8354 	}
8355       return error_mark_node;
8356     }
8357 
8358   /* We need to evaluate the template arguments, even though this
8359      template-id may be nested within a "sizeof".  */
8360   saved_unevaluated_operand = cp_unevaluated_operand;
8361   cp_unevaluated_operand = 0;
8362   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
8363   c_inhibit_evaluation_warnings = 0;
8364   new_inner_args = make_tree_vec (nparms);
8365   new_args = add_outermost_template_args (args, new_inner_args);
8366   int pack_adjust = 0;
8367   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
8368     {
8369       tree arg;
8370       tree parm;
8371 
8372       /* Get the Ith template parameter.  */
8373       parm = TREE_VEC_ELT (parms, parm_idx);
8374 
8375       if (parm == error_mark_node)
8376 	{
8377 	  TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
8378 	  continue;
8379 	}
8380 
8381       /* Calculate the next argument.  */
8382       if (arg_idx < nargs)
8383 	arg = TREE_VEC_ELT (inner_args, arg_idx);
8384       else
8385 	arg = NULL_TREE;
8386 
8387       if (template_parameter_pack_p (TREE_VALUE (parm))
8388 	  && !(arg && ARGUMENT_PACK_P (arg)))
8389         {
8390 	  /* Some arguments will be placed in the
8391 	     template parameter pack PARM.  */
8392 	  arg = coerce_template_parameter_pack (parms, parm_idx, args,
8393 						inner_args, arg_idx,
8394 						new_args, &lost,
8395 						in_decl, complain);
8396 
8397 	  if (arg == NULL_TREE)
8398 	    {
8399 	      /* We don't know how many args we have yet, just use the
8400 		 unconverted (and still packed) ones for now.  */
8401 	      new_inner_args = orig_inner_args;
8402 	      arg_idx = nargs;
8403 	      break;
8404 	    }
8405 
8406           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
8407 
8408           /* Store this argument.  */
8409           if (arg == error_mark_node)
8410 	    {
8411 	      lost++;
8412 	      /* We are done with all of the arguments.  */
8413 	      arg_idx = nargs;
8414 	      break;
8415 	    }
8416 	  else
8417 	    {
8418 	      pack_adjust = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg)) - 1;
8419 	      arg_idx += pack_adjust;
8420 	      if (fixed_parameter_pack_p (TREE_VALUE (parm)))
8421 		{
8422 		  ++fixed_packs;
8423 		  fixed_pack_adjust += pack_adjust;
8424 		}
8425 	    }
8426 
8427           continue;
8428         }
8429       else if (arg)
8430 	{
8431           if (PACK_EXPANSION_P (arg))
8432             {
8433 	      /* "If every valid specialization of a variadic template
8434 		 requires an empty template parameter pack, the template is
8435 		 ill-formed, no diagnostic required."  So check that the
8436 		 pattern works with this parameter.  */
8437 	      tree pattern = PACK_EXPANSION_PATTERN (arg);
8438 	      tree conv = convert_template_argument (TREE_VALUE (parm),
8439 						     pattern, new_args,
8440 						     complain, parm_idx,
8441 						     in_decl);
8442 	      if (conv == error_mark_node)
8443 		{
8444 		  if (complain & tf_error)
8445 		    inform (input_location, "so any instantiation with a "
8446 			    "non-empty parameter pack would be ill-formed");
8447 		  ++lost;
8448 		}
8449 	      else if (TYPE_P (conv) && !TYPE_P (pattern))
8450 		/* Recover from missing typename.  */
8451 		TREE_VEC_ELT (inner_args, arg_idx)
8452 		  = make_pack_expansion (conv, complain);
8453 
8454               /* We don't know how many args we have yet, just
8455                  use the unconverted ones for now.  */
8456               new_inner_args = inner_args;
8457 	      arg_idx = nargs;
8458               break;
8459             }
8460         }
8461       else if (require_all_args)
8462 	{
8463 	  /* There must be a default arg in this case.  */
8464 	  arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
8465 				     complain, in_decl);
8466 	  /* The position of the first default template argument,
8467 	     is also the number of non-defaulted arguments in NEW_INNER_ARGS.
8468 	     Record that.  */
8469 	  if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
8470 	    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
8471 						 arg_idx - pack_adjust);
8472 	}
8473       else
8474 	break;
8475 
8476       if (arg == error_mark_node)
8477 	{
8478 	  if (complain & tf_error)
8479 	    error ("template argument %d is invalid", arg_idx + 1);
8480 	}
8481       else if (!arg)
8482 	{
8483 	  /* This can occur if there was an error in the template
8484 	     parameter list itself (which we would already have
8485 	     reported) that we are trying to recover from, e.g., a class
8486 	     template with a parameter list such as
8487 	     template<typename..., typename> (cpp0x/variadic150.C).  */
8488 	  ++lost;
8489 
8490 	  /* This can also happen with a fixed parameter pack (71834).  */
8491 	  if (arg_idx >= nargs)
8492 	    ++missing;
8493 	}
8494       else
8495 	arg = convert_template_argument (TREE_VALUE (parm),
8496 					 arg, new_args, complain,
8497                                          parm_idx, in_decl);
8498 
8499       if (arg == error_mark_node)
8500 	lost++;
8501       TREE_VEC_ELT (new_inner_args, arg_idx - pack_adjust) = arg;
8502     }
8503   cp_unevaluated_operand = saved_unevaluated_operand;
8504   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
8505 
8506   if (missing || arg_idx < nargs - variadic_args_p)
8507     {
8508       /* If we had fixed parameter packs, we didn't know how many arguments we
8509 	 actually needed earlier; now we do.  */
8510       nparms += fixed_pack_adjust;
8511       variadic_p -= fixed_packs;
8512       goto bad_nargs;
8513     }
8514 
8515   if (arg_idx < nargs)
8516     {
8517       /* We had some pack expansion arguments that will only work if the packs
8518 	 are empty, but wait until instantiation time to complain.
8519 	 See variadic-ttp3.C.  */
8520       int len = nparms + (nargs - arg_idx);
8521       tree args = make_tree_vec (len);
8522       int i = 0;
8523       for (; i < nparms; ++i)
8524 	TREE_VEC_ELT (args, i) = TREE_VEC_ELT (new_inner_args, i);
8525       for (; i < len; ++i, ++arg_idx)
8526 	TREE_VEC_ELT (args, i) = TREE_VEC_ELT (inner_args,
8527 					       arg_idx - pack_adjust);
8528       new_inner_args = args;
8529     }
8530 
8531   if (lost)
8532     {
8533       gcc_assert (!(complain & tf_error) || seen_error ());
8534       return error_mark_node;
8535     }
8536 
8537   if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
8538     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
8539 					 TREE_VEC_LENGTH (new_inner_args));
8540 
8541   return new_inner_args;
8542 }
8543 
8544 /* Convert all template arguments to their appropriate types, and
8545    return a vector containing the innermost resulting template
8546    arguments.  If any error occurs, return error_mark_node. Error and
8547    warning messages are not issued.
8548 
8549    Note that no function argument deduction is performed, and default
8550    arguments are used to fill in unspecified arguments. */
8551 tree
coerce_template_parms(tree parms,tree args,tree in_decl)8552 coerce_template_parms (tree parms, tree args, tree in_decl)
8553 {
8554   return coerce_template_parms (parms, args, in_decl, tf_none, true, true);
8555 }
8556 
8557 /* Convert all template arguments to their appropriate type, and
8558    instantiate default arguments as needed. This returns a vector
8559    containing the innermost resulting template arguments, or
8560    error_mark_node if unsuccessful.  */
8561 tree
coerce_template_parms(tree parms,tree args,tree in_decl,tsubst_flags_t complain)8562 coerce_template_parms (tree parms, tree args, tree in_decl,
8563                        tsubst_flags_t complain)
8564 {
8565   return coerce_template_parms (parms, args, in_decl, complain, true, true);
8566 }
8567 
8568 /* Like coerce_template_parms.  If PARMS represents all template
8569    parameters levels, this function returns a vector of vectors
8570    representing all the resulting argument levels.  Note that in this
8571    case, only the innermost arguments are coerced because the
8572    outermost ones are supposed to have been coerced already.
8573 
8574    Otherwise, if PARMS represents only (the innermost) vector of
8575    parameters, this function returns a vector containing just the
8576    innermost resulting arguments.  */
8577 
8578 static tree
coerce_innermost_template_parms(tree parms,tree args,tree in_decl,tsubst_flags_t complain,bool require_all_args,bool use_default_args)8579 coerce_innermost_template_parms (tree parms,
8580 				  tree args,
8581 				  tree in_decl,
8582 				  tsubst_flags_t complain,
8583 				  bool require_all_args,
8584 				  bool use_default_args)
8585 {
8586   int parms_depth = TMPL_PARMS_DEPTH (parms);
8587   int args_depth = TMPL_ARGS_DEPTH (args);
8588   tree coerced_args;
8589 
8590   if (parms_depth > 1)
8591     {
8592       coerced_args = make_tree_vec (parms_depth);
8593       tree level;
8594       int cur_depth;
8595 
8596       for (level = parms, cur_depth = parms_depth;
8597 	   parms_depth > 0 && level != NULL_TREE;
8598 	   level = TREE_CHAIN (level), --cur_depth)
8599 	{
8600 	  tree l;
8601 	  if (cur_depth == args_depth)
8602 	    l = coerce_template_parms (TREE_VALUE (level),
8603 				       args, in_decl, complain,
8604 				       require_all_args,
8605 				       use_default_args);
8606 	  else
8607 	    l = TMPL_ARGS_LEVEL (args, cur_depth);
8608 
8609 	  if (l == error_mark_node)
8610 	    return error_mark_node;
8611 
8612 	  SET_TMPL_ARGS_LEVEL (coerced_args, cur_depth, l);
8613 	}
8614     }
8615   else
8616     coerced_args = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parms),
8617 					  args, in_decl, complain,
8618 					  require_all_args,
8619 					  use_default_args);
8620   return coerced_args;
8621 }
8622 
8623 /* Returns 1 if template args OT and NT are equivalent.  */
8624 
8625 int
template_args_equal(tree ot,tree nt,bool partial_order)8626 template_args_equal (tree ot, tree nt, bool partial_order /* = false */)
8627 {
8628   if (nt == ot)
8629     return 1;
8630   if (nt == NULL_TREE || ot == NULL_TREE)
8631     return false;
8632   if (nt == any_targ_node || ot == any_targ_node)
8633     return true;
8634 
8635   if (TREE_CODE (nt) == TREE_VEC)
8636     /* For member templates */
8637     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
8638   else if (PACK_EXPANSION_P (ot))
8639     return (PACK_EXPANSION_P (nt)
8640 	    && template_args_equal (PACK_EXPANSION_PATTERN (ot),
8641 				    PACK_EXPANSION_PATTERN (nt))
8642 	    && template_args_equal (PACK_EXPANSION_EXTRA_ARGS (ot),
8643 				    PACK_EXPANSION_EXTRA_ARGS (nt)));
8644   else if (ARGUMENT_PACK_P (ot))
8645     {
8646       int i, len;
8647       tree opack, npack;
8648 
8649       if (!ARGUMENT_PACK_P (nt))
8650 	return 0;
8651 
8652       opack = ARGUMENT_PACK_ARGS (ot);
8653       npack = ARGUMENT_PACK_ARGS (nt);
8654       len = TREE_VEC_LENGTH (opack);
8655       if (TREE_VEC_LENGTH (npack) != len)
8656 	return 0;
8657       for (i = 0; i < len; ++i)
8658 	if (!template_args_equal (TREE_VEC_ELT (opack, i),
8659 				  TREE_VEC_ELT (npack, i)))
8660 	  return 0;
8661       return 1;
8662     }
8663   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
8664     gcc_unreachable ();
8665   else if (TYPE_P (nt))
8666     {
8667       if (!TYPE_P (ot))
8668 	return false;
8669       /* Don't treat an alias template specialization with dependent
8670 	 arguments as equivalent to its underlying type when used as a
8671 	 template argument; we need them to be distinct so that we
8672 	 substitute into the specialization arguments at instantiation
8673 	 time.  And aliases can't be equivalent without being ==, so
8674 	 we don't need to look any deeper.
8675 
8676          During partial ordering, however, we need to treat them normally so
8677          that we can order uses of the same alias with different
8678          cv-qualification (79960).  */
8679       if (!partial_order
8680 	  && (TYPE_ALIAS_P (nt) || TYPE_ALIAS_P (ot)))
8681 	return false;
8682       else
8683 	return same_type_p (ot, nt);
8684     }
8685   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
8686     return 0;
8687   else
8688     {
8689       /* Try to treat a template non-type argument that has been converted
8690 	 to the parameter type as equivalent to one that hasn't yet.  */
8691       for (enum tree_code code1 = TREE_CODE (ot);
8692 	   CONVERT_EXPR_CODE_P (code1)
8693 	     || code1 == NON_LVALUE_EXPR;
8694 	   code1 = TREE_CODE (ot))
8695 	ot = TREE_OPERAND (ot, 0);
8696       for (enum tree_code code2 = TREE_CODE (nt);
8697 	   CONVERT_EXPR_CODE_P (code2)
8698 	     || code2 == NON_LVALUE_EXPR;
8699 	   code2 = TREE_CODE (nt))
8700 	nt = TREE_OPERAND (nt, 0);
8701 
8702       return cp_tree_equal (ot, nt);
8703     }
8704 }
8705 
8706 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets of
8707    template arguments.  Returns 0 otherwise, and updates OLDARG_PTR and
8708    NEWARG_PTR with the offending arguments if they are non-NULL.  */
8709 
8710 int
comp_template_args(tree oldargs,tree newargs,tree * oldarg_ptr,tree * newarg_ptr,bool partial_order)8711 comp_template_args (tree oldargs, tree newargs,
8712 		    tree *oldarg_ptr, tree *newarg_ptr,
8713 		    bool partial_order)
8714 {
8715   int i;
8716 
8717   if (oldargs == newargs)
8718     return 1;
8719 
8720   if (!oldargs || !newargs)
8721     return 0;
8722 
8723   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
8724     return 0;
8725 
8726   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
8727     {
8728       tree nt = TREE_VEC_ELT (newargs, i);
8729       tree ot = TREE_VEC_ELT (oldargs, i);
8730 
8731       if (! template_args_equal (ot, nt, partial_order))
8732 	{
8733 	  if (oldarg_ptr != NULL)
8734 	    *oldarg_ptr = ot;
8735 	  if (newarg_ptr != NULL)
8736 	    *newarg_ptr = nt;
8737 	  return 0;
8738 	}
8739     }
8740   return 1;
8741 }
8742 
8743 inline bool
comp_template_args_porder(tree oargs,tree nargs)8744 comp_template_args_porder (tree oargs, tree nargs)
8745 {
8746   return comp_template_args (oargs, nargs, NULL, NULL, true);
8747 }
8748 
8749 /* Implement a freelist interface for objects of type T.
8750 
8751    Head is a separate object, rather than a regular member, so that we
8752    can define it as a GTY deletable pointer, which is highly
8753    desirable.  A data member could be declared that way, but then the
8754    containing object would implicitly get GTY((user)), which would
8755    prevent us from instantiating freelists as global objects.
8756    Although this way we can create freelist global objects, they're
8757    such thin wrappers that instantiating temporaries at every use
8758    loses nothing and saves permanent storage for the freelist object.
8759 
8760    Member functions next, anew, poison and reinit have default
8761    implementations that work for most of the types we're interested
8762    in, but if they don't work for some type, they should be explicitly
8763    specialized.  See the comments before them for requirements, and
8764    the example specializations for the tree_list_freelist.  */
8765 template <typename T>
8766 class freelist
8767 {
8768   /* Return the next object in a chain.  We could just do type
8769      punning, but if we access the object with its underlying type, we
8770      avoid strict-aliasing trouble.  This needs only work between
8771      poison and reinit.  */
next(T * obj)8772   static T *&next (T *obj) { return obj->next; }
8773 
8774   /* Return a newly allocated, uninitialized or minimally-initialized
8775      object of type T.  Any initialization performed by anew should
8776      either remain across the life of the object and the execution of
8777      poison, or be redone by reinit.  */
anew()8778   static T *anew () { return ggc_alloc<T> (); }
8779 
8780   /* Optionally scribble all over the bits holding the object, so that
8781      they become (mostly?) uninitialized memory.  This is called while
8782      preparing to make the object part of the free list.  */
poison(T * obj)8783   static void poison (T *obj) {
8784     T *p ATTRIBUTE_UNUSED = obj;
8785     T **q ATTRIBUTE_UNUSED = &next (obj);
8786 
8787 #ifdef ENABLE_GC_CHECKING
8788     /* Poison the data, to indicate the data is garbage.  */
8789     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, sizeof (*p)));
8790     memset (p, 0xa5, sizeof (*p));
8791 #endif
8792     /* Let valgrind know the object is free.  */
8793     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, sizeof (*p)));
8794 
8795     /* Let valgrind know the next portion of the object is available,
8796        but uninitialized.  */
8797     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
8798   }
8799 
8800   /* Bring an object that underwent at least one lifecycle after anew
8801      and before the most recent free and poison, back to a usable
8802      state, reinitializing whatever is needed for it to be
8803      functionally equivalent to an object just allocated and returned
8804      by anew.  This may poison or clear the next field, used by
8805      freelist housekeeping after poison was called.  */
reinit(T * obj)8806   static void reinit (T *obj) {
8807     T **q ATTRIBUTE_UNUSED = &next (obj);
8808 
8809 #ifdef ENABLE_GC_CHECKING
8810     memset (q, 0xa5, sizeof (*q));
8811 #endif
8812     /* Let valgrind know the entire object is available, but
8813        uninitialized.  */
8814     VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (*obj)));
8815   }
8816 
8817   /* Reference a GTY-deletable pointer that points to the first object
8818      in the free list proper.  */
8819   T *&head;
8820 public:
8821   /* Construct a freelist object chaining objects off of HEAD.  */
freelist(T * & head)8822   freelist (T *&head) : head(head) {}
8823 
8824   /* Add OBJ to the free object list.  The former head becomes OBJ's
8825      successor.  */
free(T * obj)8826   void free (T *obj)
8827   {
8828     poison (obj);
8829     next (obj) = head;
8830     head = obj;
8831   }
8832 
8833   /* Take an object from the free list, if one is available, or
8834      allocate a new one.  Objects taken from the free list should be
8835      regarded as filled with garbage, except for bits that are
8836      configured to be preserved across free and alloc.  */
alloc()8837   T *alloc ()
8838   {
8839     if (head)
8840       {
8841 	T *obj = head;
8842 	head = next (head);
8843 	reinit (obj);
8844 	return obj;
8845       }
8846     else
8847       return anew ();
8848   }
8849 };
8850 
8851 /* Explicitly specialize the interfaces for freelist<tree_node>: we
8852    want to allocate a TREE_LIST using the usual interface, and ensure
8853    TREE_CHAIN remains functional.  Alas, we have to duplicate a bit of
8854    build_tree_list logic in reinit, so this could go out of sync.  */
8855 template <>
8856 inline tree &
next(tree obj)8857 freelist<tree_node>::next (tree obj)
8858 {
8859   return TREE_CHAIN (obj);
8860 }
8861 template <>
8862 inline tree
anew()8863 freelist<tree_node>::anew ()
8864 {
8865   return build_tree_list (NULL, NULL);
8866 }
8867 template <>
8868 inline void
poison(tree obj ATTRIBUTE_UNUSED)8869 freelist<tree_node>::poison (tree obj ATTRIBUTE_UNUSED)
8870 {
8871   int size ATTRIBUTE_UNUSED = sizeof (tree_list);
8872   tree p ATTRIBUTE_UNUSED = obj;
8873   tree_base *b ATTRIBUTE_UNUSED = &obj->base;
8874   tree *q ATTRIBUTE_UNUSED = &next (obj);
8875 
8876 #ifdef ENABLE_GC_CHECKING
8877   gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
8878 
8879   /* Poison the data, to indicate the data is garbage.  */
8880   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (p, size));
8881   memset (p, 0xa5, size);
8882 #endif
8883   /* Let valgrind know the object is free.  */
8884   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_NOACCESS (p, size));
8885   /* But we still want to use the TREE_CODE and TREE_CHAIN parts.  */
8886   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
8887   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (q, sizeof (*q)));
8888 
8889 #ifdef ENABLE_GC_CHECKING
8890   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (b, sizeof (*b)));
8891   /* Keep TREE_CHAIN functional.  */
8892   TREE_SET_CODE (obj, TREE_LIST);
8893 #else
8894   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
8895 #endif
8896 }
8897 template <>
8898 inline void
reinit(tree obj ATTRIBUTE_UNUSED)8899 freelist<tree_node>::reinit (tree obj ATTRIBUTE_UNUSED)
8900 {
8901   tree_base *b ATTRIBUTE_UNUSED = &obj->base;
8902 
8903 #ifdef ENABLE_GC_CHECKING
8904   gcc_checking_assert (TREE_CODE (obj) == TREE_LIST);
8905   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
8906   memset (obj, 0, sizeof (tree_list));
8907 #endif
8908 
8909   /* Let valgrind know the entire object is available, but
8910      uninitialized.  */
8911   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_UNDEFINED (obj, sizeof (tree_list)));
8912 
8913 #ifdef ENABLE_GC_CHECKING
8914   TREE_SET_CODE (obj, TREE_LIST);
8915 #else
8916   VALGRIND_DISCARD (VALGRIND_MAKE_MEM_DEFINED (b, sizeof (*b)));
8917 #endif
8918 }
8919 
8920 /* Point to the first object in the TREE_LIST freelist.  */
8921 static GTY((deletable)) tree tree_list_freelist_head;
8922 /* Return the/an actual TREE_LIST freelist.  */
8923 static inline freelist<tree_node>
tree_list_freelist()8924 tree_list_freelist ()
8925 {
8926   return tree_list_freelist_head;
8927 }
8928 
8929 /* Point to the first object in the tinst_level freelist.  */
8930 static GTY((deletable)) tinst_level *tinst_level_freelist_head;
8931 /* Return the/an actual tinst_level freelist.  */
8932 static inline freelist<tinst_level>
tinst_level_freelist()8933 tinst_level_freelist ()
8934 {
8935   return tinst_level_freelist_head;
8936 }
8937 
8938 /* Point to the first object in the pending_template freelist.  */
8939 static GTY((deletable)) pending_template *pending_template_freelist_head;
8940 /* Return the/an actual pending_template freelist.  */
8941 static inline freelist<pending_template>
pending_template_freelist()8942 pending_template_freelist ()
8943 {
8944   return pending_template_freelist_head;
8945 }
8946 
8947 /* Build the TREE_LIST object out of a split list, store it
8948    permanently, and return it.  */
8949 tree
to_list()8950 tinst_level::to_list ()
8951 {
8952   gcc_assert (split_list_p ());
8953   tree ret = tree_list_freelist ().alloc ();
8954   TREE_PURPOSE (ret) = tldcl;
8955   TREE_VALUE (ret) = targs;
8956   tldcl = ret;
8957   targs = NULL;
8958   gcc_assert (tree_list_p ());
8959   return ret;
8960 }
8961 
8962 const unsigned short tinst_level::refcount_infinity;
8963 
8964 /* Increment OBJ's refcount unless it is already infinite.  */
8965 static tinst_level *
inc_refcount_use(tinst_level * obj)8966 inc_refcount_use (tinst_level *obj)
8967 {
8968   if (obj && obj->refcount != tinst_level::refcount_infinity)
8969     ++obj->refcount;
8970   return obj;
8971 }
8972 
8973 /* Release storage for OBJ and node, if it's a TREE_LIST.  */
8974 void
free(tinst_level * obj)8975 tinst_level::free (tinst_level *obj)
8976 {
8977   if (obj->tree_list_p ())
8978     tree_list_freelist ().free (obj->get_node ());
8979   tinst_level_freelist ().free (obj);
8980 }
8981 
8982 /* Decrement OBJ's refcount if not infinite.  If it reaches zero, release
8983    OBJ's DECL and OBJ, and start over with the tinst_level object that
8984    used to be referenced by OBJ's NEXT.  */
8985 static void
dec_refcount_use(tinst_level * obj)8986 dec_refcount_use (tinst_level *obj)
8987 {
8988   while (obj
8989 	 && obj->refcount != tinst_level::refcount_infinity
8990 	 && !--obj->refcount)
8991     {
8992       tinst_level *next = obj->next;
8993       tinst_level::free (obj);
8994       obj = next;
8995     }
8996 }
8997 
8998 /* Modify PTR so that it points to OBJ, adjusting the refcounts of OBJ
8999    and of the former PTR.  Omitting the second argument is equivalent
9000    to passing (T*)NULL; this is allowed because passing the
9001    zero-valued integral constant NULL confuses type deduction and/or
9002    overload resolution.  */
9003 template <typename T>
9004 static void
9005 set_refcount_ptr (T *& ptr, T *obj = NULL)
9006 {
9007   T *save = ptr;
9008   ptr = inc_refcount_use (obj);
9009   dec_refcount_use (save);
9010 }
9011 
9012 static void
add_pending_template(tree d)9013 add_pending_template (tree d)
9014 {
9015   tree ti = (TYPE_P (d)
9016 	     ? CLASSTYPE_TEMPLATE_INFO (d)
9017 	     : DECL_TEMPLATE_INFO (d));
9018   struct pending_template *pt;
9019   int level;
9020 
9021   if (TI_PENDING_TEMPLATE_FLAG (ti))
9022     return;
9023 
9024   /* We are called both from instantiate_decl, where we've already had a
9025      tinst_level pushed, and instantiate_template, where we haven't.
9026      Compensate.  */
9027   gcc_assert (TREE_CODE (d) != TREE_LIST);
9028   level = !current_tinst_level
9029     || current_tinst_level->maybe_get_node () != d;
9030 
9031   if (level)
9032     push_tinst_level (d);
9033 
9034   pt = pending_template_freelist ().alloc ();
9035   pt->next = NULL;
9036   pt->tinst = NULL;
9037   set_refcount_ptr (pt->tinst, current_tinst_level);
9038   if (last_pending_template)
9039     last_pending_template->next = pt;
9040   else
9041     pending_templates = pt;
9042 
9043   last_pending_template = pt;
9044 
9045   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
9046 
9047   if (level)
9048     pop_tinst_level ();
9049 }
9050 
9051 
9052 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
9053    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
9054    documentation for TEMPLATE_ID_EXPR.  */
9055 
9056 tree
lookup_template_function(tree fns,tree arglist)9057 lookup_template_function (tree fns, tree arglist)
9058 {
9059   tree type;
9060 
9061   if (fns == error_mark_node || arglist == error_mark_node)
9062     return error_mark_node;
9063 
9064   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
9065 
9066   if (!is_overloaded_fn (fns) && !identifier_p (fns))
9067     {
9068       error ("%q#D is not a function template", fns);
9069       return error_mark_node;
9070     }
9071 
9072   if (BASELINK_P (fns))
9073     {
9074       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
9075 					 unknown_type_node,
9076 					 BASELINK_FUNCTIONS (fns),
9077 					 arglist);
9078       return fns;
9079     }
9080 
9081   type = TREE_TYPE (fns);
9082   if (TREE_CODE (fns) == OVERLOAD || !type)
9083     type = unknown_type_node;
9084 
9085   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
9086 }
9087 
9088 /* Within the scope of a template class S<T>, the name S gets bound
9089    (in build_self_reference) to a TYPE_DECL for the class, not a
9090    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
9091    or one of its enclosing classes, and that type is a template,
9092    return the associated TEMPLATE_DECL.  Otherwise, the original
9093    DECL is returned.
9094 
9095    Also handle the case when DECL is a TREE_LIST of ambiguous
9096    injected-class-names from different bases.  */
9097 
9098 tree
maybe_get_template_decl_from_type_decl(tree decl)9099 maybe_get_template_decl_from_type_decl (tree decl)
9100 {
9101   if (decl == NULL_TREE)
9102     return decl;
9103 
9104   /* DR 176: A lookup that finds an injected-class-name (10.2
9105      [class.member.lookup]) can result in an ambiguity in certain cases
9106      (for example, if it is found in more than one base class). If all of
9107      the injected-class-names that are found refer to specializations of
9108      the same class template, and if the name is followed by a
9109      template-argument-list, the reference refers to the class template
9110      itself and not a specialization thereof, and is not ambiguous.  */
9111   if (TREE_CODE (decl) == TREE_LIST)
9112     {
9113       tree t, tmpl = NULL_TREE;
9114       for (t = decl; t; t = TREE_CHAIN (t))
9115 	{
9116 	  tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
9117 	  if (!tmpl)
9118 	    tmpl = elt;
9119 	  else if (tmpl != elt)
9120 	    break;
9121 	}
9122       if (tmpl && t == NULL_TREE)
9123 	return tmpl;
9124       else
9125 	return decl;
9126     }
9127 
9128   return (decl != NULL_TREE
9129 	  && DECL_SELF_REFERENCE_P (decl)
9130 	  && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
9131     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
9132 }
9133 
9134 /* Given an IDENTIFIER_NODE (or type TEMPLATE_DECL) and a chain of
9135    parameters, find the desired type.
9136 
9137    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
9138 
9139    IN_DECL, if non-NULL, is the template declaration we are trying to
9140    instantiate.
9141 
9142    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
9143    the class we are looking up.
9144 
9145    Issue error and warning messages under control of COMPLAIN.
9146 
9147    If the template class is really a local class in a template
9148    function, then the FUNCTION_CONTEXT is the function in which it is
9149    being instantiated.
9150 
9151    ??? Note that this function is currently called *twice* for each
9152    template-id: the first time from the parser, while creating the
9153    incomplete type (finish_template_type), and the second type during the
9154    real instantiation (instantiate_template_class). This is surely something
9155    that we want to avoid. It also causes some problems with argument
9156    coercion (see convert_nontype_argument for more information on this).  */
9157 
9158 static tree
lookup_template_class_1(tree d1,tree arglist,tree in_decl,tree context,int entering_scope,tsubst_flags_t complain)9159 lookup_template_class_1 (tree d1, tree arglist, tree in_decl, tree context,
9160 			 int entering_scope, tsubst_flags_t complain)
9161 {
9162   tree templ = NULL_TREE, parmlist;
9163   tree t;
9164   spec_entry **slot;
9165   spec_entry *entry;
9166   spec_entry elt;
9167   hashval_t hash;
9168 
9169   if (identifier_p (d1))
9170     {
9171       tree value = innermost_non_namespace_value (d1);
9172       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
9173 	templ = value;
9174       else
9175 	{
9176 	  if (context)
9177 	    push_decl_namespace (context);
9178 	  templ = lookup_name (d1);
9179 	  templ = maybe_get_template_decl_from_type_decl (templ);
9180 	  if (context)
9181 	    pop_decl_namespace ();
9182 	}
9183       if (templ)
9184 	context = DECL_CONTEXT (templ);
9185     }
9186   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
9187     {
9188       tree type = TREE_TYPE (d1);
9189 
9190       /* If we are declaring a constructor, say A<T>::A<T>, we will get
9191 	 an implicit typename for the second A.  Deal with it.  */
9192       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
9193 	type = TREE_TYPE (type);
9194 
9195       if (CLASSTYPE_TEMPLATE_INFO (type))
9196 	{
9197 	  templ = CLASSTYPE_TI_TEMPLATE (type);
9198 	  d1 = DECL_NAME (templ);
9199 	}
9200     }
9201   else if (TREE_CODE (d1) == ENUMERAL_TYPE
9202 	   || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
9203     {
9204       templ = TYPE_TI_TEMPLATE (d1);
9205       d1 = DECL_NAME (templ);
9206     }
9207   else if (DECL_TYPE_TEMPLATE_P (d1))
9208     {
9209       templ = d1;
9210       d1 = DECL_NAME (templ);
9211       context = DECL_CONTEXT (templ);
9212     }
9213   else if (DECL_TEMPLATE_TEMPLATE_PARM_P (d1))
9214     {
9215       templ = d1;
9216       d1 = DECL_NAME (templ);
9217     }
9218 
9219   /* Issue an error message if we didn't find a template.  */
9220   if (! templ)
9221     {
9222       if (complain & tf_error)
9223 	error ("%qT is not a template", d1);
9224       return error_mark_node;
9225     }
9226 
9227   if (TREE_CODE (templ) != TEMPLATE_DECL
9228 	 /* Make sure it's a user visible template, if it was named by
9229 	    the user.  */
9230       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
9231 	  && !PRIMARY_TEMPLATE_P (templ)))
9232     {
9233       if (complain & tf_error)
9234 	{
9235 	  error ("non-template type %qT used as a template", d1);
9236 	  if (in_decl)
9237 	    error ("for template declaration %q+D", in_decl);
9238 	}
9239       return error_mark_node;
9240     }
9241 
9242   complain &= ~tf_user;
9243 
9244   /* An alias that just changes the name of a template is equivalent to the
9245      other template, so if any of the arguments are pack expansions, strip
9246      the alias to avoid problems with a pack expansion passed to a non-pack
9247      alias template parameter (DR 1430).  */
9248   if (pack_expansion_args_count (INNERMOST_TEMPLATE_ARGS (arglist)))
9249     templ = get_underlying_template (templ);
9250 
9251   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
9252     {
9253       tree parm;
9254       tree arglist2 = coerce_template_args_for_ttp (templ, arglist, complain);
9255       if (arglist2 == error_mark_node
9256 	  || (!uses_template_parms (arglist2)
9257 	      && check_instantiated_args (templ, arglist2, complain)))
9258 	return error_mark_node;
9259 
9260       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
9261       return parm;
9262     }
9263   else
9264     {
9265       tree template_type = TREE_TYPE (templ);
9266       tree gen_tmpl;
9267       tree type_decl;
9268       tree found = NULL_TREE;
9269       int arg_depth;
9270       int parm_depth;
9271       int is_dependent_type;
9272       int use_partial_inst_tmpl = false;
9273 
9274       if (template_type == error_mark_node)
9275 	/* An error occurred while building the template TEMPL, and a
9276 	   diagnostic has most certainly been emitted for that
9277 	   already.  Let's propagate that error.  */
9278 	return error_mark_node;
9279 
9280       gen_tmpl = most_general_template (templ);
9281       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
9282       parm_depth = TMPL_PARMS_DEPTH (parmlist);
9283       arg_depth = TMPL_ARGS_DEPTH (arglist);
9284 
9285       if (arg_depth == 1 && parm_depth > 1)
9286 	{
9287 	  /* We've been given an incomplete set of template arguments.
9288 	     For example, given:
9289 
9290 	       template <class T> struct S1 {
9291 		 template <class U> struct S2 {};
9292 		 template <class U> struct S2<U*> {};
9293 		};
9294 
9295 	     we will be called with an ARGLIST of `U*', but the
9296 	     TEMPLATE will be `template <class T> template
9297 	     <class U> struct S1<T>::S2'.  We must fill in the missing
9298 	     arguments.  */
9299 	  tree ti = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (templ));
9300 	  arglist = add_outermost_template_args (TI_ARGS (ti), arglist);
9301 	  arg_depth = TMPL_ARGS_DEPTH (arglist);
9302 	}
9303 
9304       /* Now we should have enough arguments.  */
9305       gcc_assert (parm_depth == arg_depth);
9306 
9307       /* From here on, we're only interested in the most general
9308 	 template.  */
9309 
9310       /* Calculate the BOUND_ARGS.  These will be the args that are
9311 	 actually tsubst'd into the definition to create the
9312 	 instantiation.  */
9313       arglist = coerce_innermost_template_parms (parmlist, arglist, gen_tmpl,
9314 						 complain,
9315 						 /*require_all_args=*/true,
9316 						 /*use_default_args=*/true);
9317 
9318       if (arglist == error_mark_node)
9319 	/* We were unable to bind the arguments.  */
9320 	return error_mark_node;
9321 
9322       /* In the scope of a template class, explicit references to the
9323 	 template class refer to the type of the template, not any
9324 	 instantiation of it.  For example, in:
9325 
9326 	   template <class T> class C { void f(C<T>); }
9327 
9328 	 the `C<T>' is just the same as `C'.  Outside of the
9329 	 class, however, such a reference is an instantiation.  */
9330       if (entering_scope
9331 	  || !PRIMARY_TEMPLATE_P (gen_tmpl)
9332 	  || currently_open_class (template_type))
9333 	{
9334 	  tree tinfo = TYPE_TEMPLATE_INFO (template_type);
9335 
9336 	  if (tinfo && comp_template_args (TI_ARGS (tinfo), arglist))
9337 	    return template_type;
9338 	}
9339 
9340       /* If we already have this specialization, return it.  */
9341       elt.tmpl = gen_tmpl;
9342       elt.args = arglist;
9343       elt.spec = NULL_TREE;
9344       hash = spec_hasher::hash (&elt);
9345       entry = type_specializations->find_with_hash (&elt, hash);
9346 
9347       if (entry)
9348 	return entry->spec;
9349 
9350       /* If the the template's constraints are not satisfied,
9351          then we cannot form a valid type.
9352 
9353          Note that the check is deferred until after the hash
9354          lookup. This prevents redundant checks on previously
9355          instantiated specializations. */
9356       if (flag_concepts && !constraints_satisfied_p (gen_tmpl, arglist))
9357         {
9358           if (complain & tf_error)
9359             {
9360               error ("template constraint failure");
9361               diagnose_constraints (input_location, gen_tmpl, arglist);
9362             }
9363           return error_mark_node;
9364         }
9365 
9366       is_dependent_type = uses_template_parms (arglist);
9367 
9368       /* If the deduced arguments are invalid, then the binding
9369 	 failed.  */
9370       if (!is_dependent_type
9371 	  && check_instantiated_args (gen_tmpl,
9372 				      INNERMOST_TEMPLATE_ARGS (arglist),
9373 				      complain))
9374 	return error_mark_node;
9375 
9376       if (!is_dependent_type
9377 	  && !PRIMARY_TEMPLATE_P (gen_tmpl)
9378 	  && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
9379 	  && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
9380 	{
9381 	  found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
9382 				      DECL_NAME (gen_tmpl),
9383 				      /*tag_scope=*/ts_global);
9384 	  return found;
9385 	}
9386 
9387       context = DECL_CONTEXT (gen_tmpl);
9388       if (context && TYPE_P (context))
9389 	{
9390 	  context = tsubst_aggr_type (context, arglist, complain, in_decl, true);
9391 	  context = complete_type (context);
9392 	}
9393       else
9394 	context = tsubst (context, arglist, complain, in_decl);
9395 
9396       if (context == error_mark_node)
9397 	return error_mark_node;
9398 
9399       if (!context)
9400 	context = global_namespace;
9401 
9402       /* Create the type.  */
9403       if (DECL_ALIAS_TEMPLATE_P (gen_tmpl))
9404 	{
9405 	  /* The user referred to a specialization of an alias
9406 	    template represented by GEN_TMPL.
9407 
9408 	    [temp.alias]/2 says:
9409 
9410 	        When a template-id refers to the specialization of an
9411 		alias template, it is equivalent to the associated
9412 		type obtained by substitution of its
9413 		template-arguments for the template-parameters in the
9414 		type-id of the alias template.  */
9415 
9416 	  t = tsubst (TREE_TYPE (gen_tmpl), arglist, complain, in_decl);
9417 	  /* Note that the call above (by indirectly calling
9418 	     register_specialization in tsubst_decl) registers the
9419 	     TYPE_DECL representing the specialization of the alias
9420 	     template.  So next time someone substitutes ARGLIST for
9421 	     the template parms into the alias template (GEN_TMPL),
9422 	     she'll get that TYPE_DECL back.  */
9423 
9424 	  if (t == error_mark_node)
9425 	    return t;
9426 	}
9427       else if (TREE_CODE (template_type) == ENUMERAL_TYPE)
9428 	{
9429 	  if (!is_dependent_type)
9430 	    {
9431 	      set_current_access_from_decl (TYPE_NAME (template_type));
9432 	      t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
9433 			      tsubst (ENUM_UNDERLYING_TYPE (template_type),
9434 				      arglist, complain, in_decl),
9435 			      tsubst_attributes (TYPE_ATTRIBUTES (template_type),
9436 						 arglist, complain, in_decl),
9437 			      SCOPED_ENUM_P (template_type), NULL);
9438 
9439 	      if (t == error_mark_node)
9440 		return t;
9441 	    }
9442 	  else
9443             {
9444               /* We don't want to call start_enum for this type, since
9445                  the values for the enumeration constants may involve
9446                  template parameters.  And, no one should be interested
9447                  in the enumeration constants for such a type.  */
9448               t = cxx_make_type (ENUMERAL_TYPE);
9449               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
9450             }
9451           SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
9452 	  ENUM_FIXED_UNDERLYING_TYPE_P (t)
9453 	    = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
9454 	}
9455       else if (CLASS_TYPE_P (template_type))
9456 	{
9457 	  /* Lambda closures are regenerated in tsubst_lambda_expr, not
9458 	     instantiated here.  */
9459 	  gcc_assert (!LAMBDA_TYPE_P (template_type));
9460 
9461 	  t = make_class_type (TREE_CODE (template_type));
9462 	  CLASSTYPE_DECLARED_CLASS (t)
9463 	    = CLASSTYPE_DECLARED_CLASS (template_type);
9464 	  SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
9465 
9466 	  /* A local class.  Make sure the decl gets registered properly.  */
9467 	  if (context == current_function_decl)
9468 	    if (pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current)
9469 		== error_mark_node)
9470 	      return error_mark_node;
9471 
9472 	  if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
9473 	    /* This instantiation is another name for the primary
9474 	       template type. Set the TYPE_CANONICAL field
9475 	       appropriately. */
9476 	    TYPE_CANONICAL (t) = template_type;
9477 	  else if (any_template_arguments_need_structural_equality_p (arglist))
9478 	    /* Some of the template arguments require structural
9479 	       equality testing, so this template class requires
9480 	       structural equality testing. */
9481 	    SET_TYPE_STRUCTURAL_EQUALITY (t);
9482 	}
9483       else
9484 	gcc_unreachable ();
9485 
9486       /* If we called start_enum or pushtag above, this information
9487 	 will already be set up.  */
9488       if (!TYPE_NAME (t))
9489 	{
9490 	  TYPE_CONTEXT (t) = FROB_CONTEXT (context);
9491 
9492 	  type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
9493 	  DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
9494 	  DECL_SOURCE_LOCATION (type_decl)
9495 	    = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
9496 	}
9497       else
9498 	type_decl = TYPE_NAME (t);
9499 
9500       if (CLASS_TYPE_P (template_type))
9501 	{
9502 	  TREE_PRIVATE (type_decl)
9503 	    = TREE_PRIVATE (TYPE_MAIN_DECL (template_type));
9504 	  TREE_PROTECTED (type_decl)
9505 	    = TREE_PROTECTED (TYPE_MAIN_DECL (template_type));
9506 	  if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
9507 	    {
9508 	      DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
9509 	      DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
9510 	    }
9511 	}
9512 
9513       if (OVERLOAD_TYPE_P (t)
9514 	  && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
9515 	{
9516 	  static const char *tags[] = {"abi_tag", "may_alias"};
9517 
9518 	  for (unsigned ix = 0; ix != 2; ix++)
9519 	    {
9520 	      tree attributes
9521 		= lookup_attribute (tags[ix], TYPE_ATTRIBUTES (template_type));
9522 
9523 	      if (attributes)
9524 		TYPE_ATTRIBUTES (t)
9525 		  = tree_cons (TREE_PURPOSE (attributes),
9526 			       TREE_VALUE (attributes),
9527 			       TYPE_ATTRIBUTES (t));
9528 	    }
9529 	}
9530 
9531       /* Let's consider the explicit specialization of a member
9532          of a class template specialization that is implicitly instantiated,
9533 	 e.g.:
9534 	     template<class T>
9535 	     struct S
9536 	     {
9537 	       template<class U> struct M {}; //#0
9538 	     };
9539 
9540 	     template<>
9541 	     template<>
9542 	     struct S<int>::M<char> //#1
9543 	     {
9544 	       int i;
9545 	     };
9546 	[temp.expl.spec]/4 says this is valid.
9547 
9548 	In this case, when we write:
9549 	S<int>::M<char> m;
9550 
9551 	M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
9552 	the one of #0.
9553 
9554 	When we encounter #1, we want to store the partial instantiation
9555 	of M (template<class T> S<int>::M<T>) in its CLASSTYPE_TI_TEMPLATE.
9556 
9557 	For all cases other than this "explicit specialization of member of a
9558 	class template", we just want to store the most general template into
9559 	the CLASSTYPE_TI_TEMPLATE of M.
9560 
9561 	This case of "explicit specialization of member of a class template"
9562 	only happens when:
9563 	1/ the enclosing class is an instantiation of, and therefore not
9564 	the same as, the context of the most general template, and
9565 	2/ we aren't looking at the partial instantiation itself, i.e.
9566 	the innermost arguments are not the same as the innermost parms of
9567 	the most general template.
9568 
9569 	So it's only when 1/ and 2/ happens that we want to use the partial
9570 	instantiation of the member template in lieu of its most general
9571 	template.  */
9572 
9573       if (PRIMARY_TEMPLATE_P (gen_tmpl)
9574 	  && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
9575 	  /* the enclosing class must be an instantiation...  */
9576 	  && CLASS_TYPE_P (context)
9577 	  && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
9578 	{
9579 	  TREE_VEC_LENGTH (arglist)--;
9580 	  ++processing_template_decl;
9581 	  tree tinfo = TYPE_TEMPLATE_INFO_MAYBE_ALIAS (TREE_TYPE (gen_tmpl));
9582 	  tree partial_inst_args =
9583 	    tsubst (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo)),
9584 		    arglist, complain, NULL_TREE);
9585 	  --processing_template_decl;
9586 	  TREE_VEC_LENGTH (arglist)++;
9587 	  if (partial_inst_args == error_mark_node)
9588 	    return error_mark_node;
9589 	  use_partial_inst_tmpl =
9590 	    /*...and we must not be looking at the partial instantiation
9591 	     itself. */
9592 	    !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
9593 				 partial_inst_args);
9594 	}
9595 
9596       if (!use_partial_inst_tmpl)
9597 	/* This case is easy; there are no member templates involved.  */
9598 	found = gen_tmpl;
9599       else
9600 	{
9601 	  /* This is a full instantiation of a member template.  Find
9602 	     the partial instantiation of which this is an instance.  */
9603 
9604 	  /* Temporarily reduce by one the number of levels in the ARGLIST
9605 	     so as to avoid comparing the last set of arguments.  */
9606 	  TREE_VEC_LENGTH (arglist)--;
9607 	  found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
9608 	  TREE_VEC_LENGTH (arglist)++;
9609 	  /* FOUND is either a proper class type, or an alias
9610 	     template specialization.  In the later case, it's a
9611 	     TYPE_DECL, resulting from the substituting of arguments
9612 	     for parameters in the TYPE_DECL of the alias template
9613 	     done earlier.  So be careful while getting the template
9614 	     of FOUND.  */
9615 	  found = (TREE_CODE (found) == TEMPLATE_DECL
9616 		   ? found
9617 		   : (TREE_CODE (found) == TYPE_DECL
9618 		      ? DECL_TI_TEMPLATE (found)
9619 		      : CLASSTYPE_TI_TEMPLATE (found)));
9620 	}
9621 
9622       // Build template info for the new specialization.
9623       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
9624 
9625       elt.spec = t;
9626       slot = type_specializations->find_slot_with_hash (&elt, hash, INSERT);
9627       entry = ggc_alloc<spec_entry> ();
9628       *entry = elt;
9629       *slot = entry;
9630 
9631       /* Note this use of the partial instantiation so we can check it
9632 	 later in maybe_process_partial_specialization.  */
9633       DECL_TEMPLATE_INSTANTIATIONS (found)
9634 	= tree_cons (arglist, t,
9635 		     DECL_TEMPLATE_INSTANTIATIONS (found));
9636 
9637       if (TREE_CODE (template_type) == ENUMERAL_TYPE && !is_dependent_type
9638 	  && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
9639 	/* Now that the type has been registered on the instantiations
9640 	   list, we set up the enumerators.  Because the enumeration
9641 	   constants may involve the enumeration type itself, we make
9642 	   sure to register the type first, and then create the
9643 	   constants.  That way, doing tsubst_expr for the enumeration
9644 	   constants won't result in recursive calls here; we'll find
9645 	   the instantiation and exit above.  */
9646 	tsubst_enum (template_type, t, arglist);
9647 
9648       if (CLASS_TYPE_P (template_type) && is_dependent_type)
9649 	/* If the type makes use of template parameters, the
9650 	   code that generates debugging information will crash.  */
9651 	DECL_IGNORED_P (TYPE_MAIN_DECL (t)) = 1;
9652 
9653       /* Possibly limit visibility based on template args.  */
9654       TREE_PUBLIC (type_decl) = 1;
9655       determine_visibility (type_decl);
9656 
9657       inherit_targ_abi_tags (t);
9658 
9659       return t;
9660     }
9661 }
9662 
9663 /* Wrapper for lookup_template_class_1.  */
9664 
9665 tree
lookup_template_class(tree d1,tree arglist,tree in_decl,tree context,int entering_scope,tsubst_flags_t complain)9666 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
9667                        int entering_scope, tsubst_flags_t complain)
9668 {
9669   tree ret;
9670   timevar_push (TV_TEMPLATE_INST);
9671   ret = lookup_template_class_1 (d1, arglist, in_decl, context,
9672                                  entering_scope, complain);
9673   timevar_pop (TV_TEMPLATE_INST);
9674   return ret;
9675 }
9676 
9677 /* Return a TEMPLATE_ID_EXPR for the given variable template and ARGLIST.  */
9678 
9679 tree
lookup_template_variable(tree templ,tree arglist)9680 lookup_template_variable (tree templ, tree arglist)
9681 {
9682   /* The type of the expression is NULL_TREE since the template-id could refer
9683      to an explicit or partial specialization. */
9684   tree type = NULL_TREE;
9685   if (flag_concepts && variable_concept_p (templ))
9686     /* Except that concepts are always bool.  */
9687     type = boolean_type_node;
9688   return build2 (TEMPLATE_ID_EXPR, type, templ, arglist);
9689 }
9690 
9691 /* Instantiate a variable declaration from a TEMPLATE_ID_EXPR for use. */
9692 
9693 tree
finish_template_variable(tree var,tsubst_flags_t complain)9694 finish_template_variable (tree var, tsubst_flags_t complain)
9695 {
9696   tree templ = TREE_OPERAND (var, 0);
9697   tree arglist = TREE_OPERAND (var, 1);
9698 
9699   /* We never want to return a VAR_DECL for a variable concept, since they
9700      aren't instantiated.  In a template, leave the TEMPLATE_ID_EXPR alone.  */
9701   bool concept_p = flag_concepts && variable_concept_p (templ);
9702   if (concept_p && processing_template_decl)
9703     return var;
9704 
9705   tree tmpl_args = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (templ));
9706   arglist = add_outermost_template_args (tmpl_args, arglist);
9707 
9708   templ = most_general_template (templ);
9709   tree parms = DECL_TEMPLATE_PARMS (templ);
9710   arglist = coerce_innermost_template_parms (parms, arglist, templ, complain,
9711 					     /*req_all*/true,
9712 					     /*use_default*/true);
9713 
9714   if (flag_concepts && !constraints_satisfied_p (templ, arglist))
9715     {
9716       if (complain & tf_error)
9717 	{
9718 	  error ("use of invalid variable template %qE", var);
9719 	  diagnose_constraints (location_of (var), templ, arglist);
9720 	}
9721       return error_mark_node;
9722     }
9723 
9724   /* If a template-id refers to a specialization of a variable
9725      concept, then the expression is true if and only if the
9726      concept's constraints are satisfied by the given template
9727      arguments.
9728 
9729      NOTE: This is an extension of Concepts Lite TS that
9730      allows constraints to be used in expressions. */
9731   if (concept_p)
9732     {
9733       tree decl = DECL_TEMPLATE_RESULT (templ);
9734       return evaluate_variable_concept (decl, arglist);
9735     }
9736 
9737   return instantiate_template (templ, arglist, complain);
9738 }
9739 
9740 /* Construct a TEMPLATE_ID_EXPR for the given variable template TEMPL having
9741    TARGS template args, and instantiate it if it's not dependent.  */
9742 
9743 tree
lookup_and_finish_template_variable(tree templ,tree targs,tsubst_flags_t complain)9744 lookup_and_finish_template_variable (tree templ, tree targs,
9745 				     tsubst_flags_t complain)
9746 {
9747   templ = lookup_template_variable (templ, targs);
9748   if (!any_dependent_template_arguments_p (targs))
9749     {
9750       templ = finish_template_variable (templ, complain);
9751       mark_used (templ);
9752     }
9753 
9754   return convert_from_reference (templ);
9755 }
9756 
9757 
9758 struct pair_fn_data
9759 {
9760   tree_fn_t fn;
9761   tree_fn_t any_fn;
9762   void *data;
9763   /* True when we should also visit template parameters that occur in
9764      non-deduced contexts.  */
9765   bool include_nondeduced_p;
9766   hash_set<tree> *visited;
9767 };
9768 
9769 /* Called from for_each_template_parm via walk_tree.  */
9770 
9771 static tree
for_each_template_parm_r(tree * tp,int * walk_subtrees,void * d)9772 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
9773 {
9774   tree t = *tp;
9775   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
9776   tree_fn_t fn = pfd->fn;
9777   void *data = pfd->data;
9778   tree result = NULL_TREE;
9779 
9780 #define WALK_SUBTREE(NODE)						\
9781   do									\
9782     {									\
9783       result = for_each_template_parm (NODE, fn, data, pfd->visited,	\
9784 				       pfd->include_nondeduced_p,	\
9785 				       pfd->any_fn);			\
9786       if (result) goto out;						\
9787     }									\
9788   while (0)
9789 
9790   if (pfd->any_fn && (*pfd->any_fn)(t, data))
9791     return t;
9792 
9793   if (TYPE_P (t)
9794       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE))
9795     WALK_SUBTREE (TYPE_CONTEXT (t));
9796 
9797   switch (TREE_CODE (t))
9798     {
9799     case RECORD_TYPE:
9800       if (TYPE_PTRMEMFUNC_P (t))
9801 	break;
9802       /* Fall through.  */
9803 
9804     case UNION_TYPE:
9805     case ENUMERAL_TYPE:
9806       if (!TYPE_TEMPLATE_INFO (t))
9807 	*walk_subtrees = 0;
9808       else
9809 	WALK_SUBTREE (TYPE_TI_ARGS (t));
9810       break;
9811 
9812     case INTEGER_TYPE:
9813       WALK_SUBTREE (TYPE_MIN_VALUE (t));
9814       WALK_SUBTREE (TYPE_MAX_VALUE (t));
9815       break;
9816 
9817     case METHOD_TYPE:
9818       /* Since we're not going to walk subtrees, we have to do this
9819 	 explicitly here.  */
9820       WALK_SUBTREE (TYPE_METHOD_BASETYPE (t));
9821       /* Fall through.  */
9822 
9823     case FUNCTION_TYPE:
9824       /* Check the return type.  */
9825       WALK_SUBTREE (TREE_TYPE (t));
9826 
9827       /* Check the parameter types.  Since default arguments are not
9828 	 instantiated until they are needed, the TYPE_ARG_TYPES may
9829 	 contain expressions that involve template parameters.  But,
9830 	 no-one should be looking at them yet.  And, once they're
9831 	 instantiated, they don't contain template parameters, so
9832 	 there's no point in looking at them then, either.  */
9833       {
9834 	tree parm;
9835 
9836 	for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
9837 	  WALK_SUBTREE (TREE_VALUE (parm));
9838 
9839 	/* Since we've already handled the TYPE_ARG_TYPES, we don't
9840 	   want walk_tree walking into them itself.  */
9841 	*walk_subtrees = 0;
9842       }
9843 
9844       if (flag_noexcept_type)
9845 	{
9846 	  tree spec = TYPE_RAISES_EXCEPTIONS (t);
9847 	  if (spec)
9848 	    WALK_SUBTREE (TREE_PURPOSE (spec));
9849 	}
9850       break;
9851 
9852     case TYPEOF_TYPE:
9853     case DECLTYPE_TYPE:
9854     case UNDERLYING_TYPE:
9855       if (pfd->include_nondeduced_p
9856 	  && for_each_template_parm (TYPE_VALUES_RAW (t), fn, data,
9857 				     pfd->visited,
9858 				     pfd->include_nondeduced_p,
9859 				     pfd->any_fn))
9860 	return error_mark_node;
9861       *walk_subtrees = false;
9862       break;
9863 
9864     case FUNCTION_DECL:
9865     case VAR_DECL:
9866       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
9867 	WALK_SUBTREE (DECL_TI_ARGS (t));
9868       /* Fall through.  */
9869 
9870     case PARM_DECL:
9871     case CONST_DECL:
9872       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t))
9873 	WALK_SUBTREE (DECL_INITIAL (t));
9874       if (DECL_CONTEXT (t)
9875 	  && pfd->include_nondeduced_p)
9876 	WALK_SUBTREE (DECL_CONTEXT (t));
9877       break;
9878 
9879     case BOUND_TEMPLATE_TEMPLATE_PARM:
9880       /* Record template parameters such as `T' inside `TT<T>'.  */
9881       WALK_SUBTREE (TYPE_TI_ARGS (t));
9882       /* Fall through.  */
9883 
9884     case TEMPLATE_TEMPLATE_PARM:
9885     case TEMPLATE_TYPE_PARM:
9886     case TEMPLATE_PARM_INDEX:
9887       if (fn && (*fn)(t, data))
9888 	return t;
9889       else if (!fn)
9890 	return t;
9891       break;
9892 
9893     case TEMPLATE_DECL:
9894       /* A template template parameter is encountered.  */
9895       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
9896 	WALK_SUBTREE (TREE_TYPE (t));
9897 
9898       /* Already substituted template template parameter */
9899       *walk_subtrees = 0;
9900       break;
9901 
9902     case TYPENAME_TYPE:
9903       /* A template-id in a TYPENAME_TYPE might be a deduced context after
9904 	 partial instantiation.  */
9905       WALK_SUBTREE (TYPENAME_TYPE_FULLNAME (t));
9906       break;
9907 
9908     case CONSTRUCTOR:
9909       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
9910 	  && pfd->include_nondeduced_p)
9911 	WALK_SUBTREE (TYPE_PTRMEMFUNC_FN_TYPE (TREE_TYPE (t)));
9912       break;
9913 
9914     case INDIRECT_REF:
9915     case COMPONENT_REF:
9916       /* If there's no type, then this thing must be some expression
9917 	 involving template parameters.  */
9918       if (!fn && !TREE_TYPE (t))
9919 	return error_mark_node;
9920       break;
9921 
9922     case MODOP_EXPR:
9923     case CAST_EXPR:
9924     case IMPLICIT_CONV_EXPR:
9925     case REINTERPRET_CAST_EXPR:
9926     case CONST_CAST_EXPR:
9927     case STATIC_CAST_EXPR:
9928     case DYNAMIC_CAST_EXPR:
9929     case ARROW_EXPR:
9930     case DOTSTAR_EXPR:
9931     case TYPEID_EXPR:
9932     case PSEUDO_DTOR_EXPR:
9933       if (!fn)
9934 	return error_mark_node;
9935       break;
9936 
9937     default:
9938       break;
9939     }
9940 
9941   #undef WALK_SUBTREE
9942 
9943   /* We didn't find any template parameters we liked.  */
9944  out:
9945   return result;
9946 }
9947 
9948 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
9949    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
9950    call FN with the parameter and the DATA.
9951    If FN returns nonzero, the iteration is terminated, and
9952    for_each_template_parm returns 1.  Otherwise, the iteration
9953    continues.  If FN never returns a nonzero value, the value
9954    returned by for_each_template_parm is 0.  If FN is NULL, it is
9955    considered to be the function which always returns 1.
9956 
9957    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
9958    parameters that occur in non-deduced contexts.  When false, only
9959    visits those template parameters that can be deduced.  */
9960 
9961 static tree
for_each_template_parm(tree t,tree_fn_t fn,void * data,hash_set<tree> * visited,bool include_nondeduced_p,tree_fn_t any_fn)9962 for_each_template_parm (tree t, tree_fn_t fn, void* data,
9963 			hash_set<tree> *visited,
9964 			bool include_nondeduced_p,
9965 			tree_fn_t any_fn)
9966 {
9967   struct pair_fn_data pfd;
9968   tree result;
9969 
9970   /* Set up.  */
9971   pfd.fn = fn;
9972   pfd.any_fn = any_fn;
9973   pfd.data = data;
9974   pfd.include_nondeduced_p = include_nondeduced_p;
9975 
9976   /* Walk the tree.  (Conceptually, we would like to walk without
9977      duplicates, but for_each_template_parm_r recursively calls
9978      for_each_template_parm, so we would need to reorganize a fair
9979      bit to use walk_tree_without_duplicates, so we keep our own
9980      visited list.)  */
9981   if (visited)
9982     pfd.visited = visited;
9983   else
9984     pfd.visited = new hash_set<tree>;
9985   result = cp_walk_tree (&t,
9986 		         for_each_template_parm_r,
9987 		         &pfd,
9988 		         pfd.visited);
9989 
9990   /* Clean up.  */
9991   if (!visited)
9992     {
9993       delete pfd.visited;
9994       pfd.visited = 0;
9995     }
9996 
9997   return result;
9998 }
9999 
10000 /* Returns true if T depends on any template parameter.  */
10001 
10002 int
uses_template_parms(tree t)10003 uses_template_parms (tree t)
10004 {
10005   if (t == NULL_TREE)
10006     return false;
10007 
10008   bool dependent_p;
10009   int saved_processing_template_decl;
10010 
10011   saved_processing_template_decl = processing_template_decl;
10012   if (!saved_processing_template_decl)
10013     processing_template_decl = 1;
10014   if (TYPE_P (t))
10015     dependent_p = dependent_type_p (t);
10016   else if (TREE_CODE (t) == TREE_VEC)
10017     dependent_p = any_dependent_template_arguments_p (t);
10018   else if (TREE_CODE (t) == TREE_LIST)
10019     dependent_p = (uses_template_parms (TREE_VALUE (t))
10020 		   || uses_template_parms (TREE_CHAIN (t)));
10021   else if (TREE_CODE (t) == TYPE_DECL)
10022     dependent_p = dependent_type_p (TREE_TYPE (t));
10023   else if (DECL_P (t)
10024 	   || EXPR_P (t)
10025 	   || TREE_CODE (t) == TEMPLATE_PARM_INDEX
10026 	   || TREE_CODE (t) == OVERLOAD
10027 	   || BASELINK_P (t)
10028 	   || identifier_p (t)
10029 	   || TREE_CODE (t) == TRAIT_EXPR
10030 	   || TREE_CODE (t) == CONSTRUCTOR
10031 	   || CONSTANT_CLASS_P (t))
10032     dependent_p = (type_dependent_expression_p (t)
10033 		   || value_dependent_expression_p (t));
10034   else
10035     {
10036       gcc_assert (t == error_mark_node);
10037       dependent_p = false;
10038     }
10039 
10040   processing_template_decl = saved_processing_template_decl;
10041 
10042   return dependent_p;
10043 }
10044 
10045 /* Returns true iff current_function_decl is an incompletely instantiated
10046    template.  Useful instead of processing_template_decl because the latter
10047    is set to 0 during instantiate_non_dependent_expr.  */
10048 
10049 bool
in_template_function(void)10050 in_template_function (void)
10051 {
10052   tree fn = current_function_decl;
10053   bool ret;
10054   ++processing_template_decl;
10055   ret = (fn && DECL_LANG_SPECIFIC (fn)
10056 	 && DECL_TEMPLATE_INFO (fn)
10057 	 && any_dependent_template_arguments_p (DECL_TI_ARGS (fn)));
10058   --processing_template_decl;
10059   return ret;
10060 }
10061 
10062 /* Returns true if T depends on any template parameter with level LEVEL.  */
10063 
10064 bool
uses_template_parms_level(tree t,int level)10065 uses_template_parms_level (tree t, int level)
10066 {
10067   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
10068 				 /*include_nondeduced_p=*/true);
10069 }
10070 
10071 /* Returns true if the signature of DECL depends on any template parameter from
10072    its enclosing class.  */
10073 
10074 bool
uses_outer_template_parms(tree decl)10075 uses_outer_template_parms (tree decl)
10076 {
10077   int depth = template_class_depth (CP_DECL_CONTEXT (decl));
10078   if (depth == 0)
10079     return false;
10080   if (for_each_template_parm (TREE_TYPE (decl), template_parm_outer_level,
10081 			      &depth, NULL, /*include_nondeduced_p=*/true))
10082     return true;
10083   if (PRIMARY_TEMPLATE_P (decl)
10084       && for_each_template_parm (INNERMOST_TEMPLATE_PARMS
10085 				 (DECL_TEMPLATE_PARMS (decl)),
10086 				 template_parm_outer_level,
10087 				 &depth, NULL, /*include_nondeduced_p=*/true))
10088     return true;
10089   tree ci = get_constraints (decl);
10090   if (ci)
10091     ci = CI_ASSOCIATED_CONSTRAINTS (ci);
10092   if (ci && for_each_template_parm (ci, template_parm_outer_level,
10093 				    &depth, NULL, /*nondeduced*/true))
10094     return true;
10095   return false;
10096 }
10097 
10098 /* Returns TRUE iff INST is an instantiation we don't need to do in an
10099    ill-formed translation unit, i.e. a variable or function that isn't
10100    usable in a constant expression.  */
10101 
10102 static inline bool
neglectable_inst_p(tree d)10103 neglectable_inst_p (tree d)
10104 {
10105   return (d && DECL_P (d)
10106 	  && !undeduced_auto_decl (d)
10107 	  && !(TREE_CODE (d) == FUNCTION_DECL ? DECL_DECLARED_CONSTEXPR_P (d)
10108 	       : decl_maybe_constant_var_p (d)));
10109 }
10110 
10111 /* Returns TRUE iff we should refuse to instantiate DECL because it's
10112    neglectable and instantiated from within an erroneous instantiation.  */
10113 
10114 static bool
limit_bad_template_recursion(tree decl)10115 limit_bad_template_recursion (tree decl)
10116 {
10117   struct tinst_level *lev = current_tinst_level;
10118   int errs = errorcount + sorrycount;
10119   if (lev == NULL || errs == 0 || !neglectable_inst_p (decl))
10120     return false;
10121 
10122   for (; lev; lev = lev->next)
10123     if (neglectable_inst_p (lev->maybe_get_node ()))
10124       break;
10125 
10126   return (lev && errs > lev->errors);
10127 }
10128 
10129 static int tinst_depth;
10130 extern int max_tinst_depth;
10131 int depth_reached;
10132 
10133 static GTY(()) struct tinst_level *last_error_tinst_level;
10134 
10135 /* We're starting to instantiate D; record the template instantiation context
10136    at LOC for diagnostics and to restore it later.  */
10137 
10138 static bool
push_tinst_level_loc(tree tldcl,tree targs,location_t loc)10139 push_tinst_level_loc (tree tldcl, tree targs, location_t loc)
10140 {
10141   struct tinst_level *new_level;
10142 
10143   if (tinst_depth >= max_tinst_depth)
10144     {
10145       /* Tell error.c not to try to instantiate any templates.  */
10146       at_eof = 2;
10147       fatal_error (input_location,
10148 		   "template instantiation depth exceeds maximum of %d"
10149                    " (use -ftemplate-depth= to increase the maximum)",
10150                    max_tinst_depth);
10151       return false;
10152     }
10153 
10154   /* If the current instantiation caused problems, don't let it instantiate
10155      anything else.  Do allow deduction substitution and decls usable in
10156      constant expressions.  */
10157   if (!targs && limit_bad_template_recursion (tldcl))
10158     return false;
10159 
10160   /* When not -quiet, dump template instantiations other than functions, since
10161      announce_function will take care of those.  */
10162   if (!quiet_flag && !targs
10163       && TREE_CODE (tldcl) != TREE_LIST
10164       && TREE_CODE (tldcl) != FUNCTION_DECL)
10165     fprintf (stderr, " %s", decl_as_string (tldcl, TFF_DECL_SPECIFIERS));
10166 
10167   new_level = tinst_level_freelist ().alloc ();
10168   new_level->tldcl = tldcl;
10169   new_level->targs = targs;
10170   new_level->locus = loc;
10171   new_level->errors = errorcount + sorrycount;
10172   new_level->next = NULL;
10173   new_level->refcount = 0;
10174   set_refcount_ptr (new_level->next, current_tinst_level);
10175   set_refcount_ptr (current_tinst_level, new_level);
10176 
10177   ++tinst_depth;
10178   if (GATHER_STATISTICS && (tinst_depth > depth_reached))
10179     depth_reached = tinst_depth;
10180 
10181   return true;
10182 }
10183 
10184 /* We're starting substitution of TMPL<ARGS>; record the template
10185    substitution context for diagnostics and to restore it later.  */
10186 
10187 static bool
push_tinst_level(tree tmpl,tree args)10188 push_tinst_level (tree tmpl, tree args)
10189 {
10190   return push_tinst_level_loc (tmpl, args, input_location);
10191 }
10192 
10193 /* We're starting to instantiate D; record INPUT_LOCATION and the
10194    template instantiation context for diagnostics and to restore it
10195    later.  */
10196 
10197 bool
push_tinst_level(tree d)10198 push_tinst_level (tree d)
10199 {
10200   return push_tinst_level_loc (d, input_location);
10201 }
10202 
10203 /* Likewise, but record LOC as the program location.  */
10204 
10205 bool
push_tinst_level_loc(tree d,location_t loc)10206 push_tinst_level_loc (tree d, location_t loc)
10207 {
10208   gcc_assert (TREE_CODE (d) != TREE_LIST);
10209   return push_tinst_level_loc (d, NULL, loc);
10210 }
10211 
10212 /* We're done instantiating this template; return to the instantiation
10213    context.  */
10214 
10215 void
pop_tinst_level(void)10216 pop_tinst_level (void)
10217 {
10218   /* Restore the filename and line number stashed away when we started
10219      this instantiation.  */
10220   input_location = current_tinst_level->locus;
10221   set_refcount_ptr (current_tinst_level, current_tinst_level->next);
10222   --tinst_depth;
10223 }
10224 
10225 /* We're instantiating a deferred template; restore the template
10226    instantiation context in which the instantiation was requested, which
10227    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
10228 
10229 static tree
reopen_tinst_level(struct tinst_level * level)10230 reopen_tinst_level (struct tinst_level *level)
10231 {
10232   struct tinst_level *t;
10233 
10234   tinst_depth = 0;
10235   for (t = level; t; t = t->next)
10236     ++tinst_depth;
10237 
10238   set_refcount_ptr (current_tinst_level, level);
10239   pop_tinst_level ();
10240   if (current_tinst_level)
10241     current_tinst_level->errors = errorcount+sorrycount;
10242   return level->maybe_get_node ();
10243 }
10244 
10245 /* Returns the TINST_LEVEL which gives the original instantiation
10246    context.  */
10247 
10248 struct tinst_level *
outermost_tinst_level(void)10249 outermost_tinst_level (void)
10250 {
10251   struct tinst_level *level = current_tinst_level;
10252   if (level)
10253     while (level->next)
10254       level = level->next;
10255   return level;
10256 }
10257 
10258 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
10259    vector of template arguments, as for tsubst.
10260 
10261    Returns an appropriate tsubst'd friend declaration.  */
10262 
10263 static tree
tsubst_friend_function(tree decl,tree args)10264 tsubst_friend_function (tree decl, tree args)
10265 {
10266   tree new_friend;
10267 
10268   if (TREE_CODE (decl) == FUNCTION_DECL
10269       && DECL_TEMPLATE_INSTANTIATION (decl)
10270       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
10271     /* This was a friend declared with an explicit template
10272        argument list, e.g.:
10273 
10274        friend void f<>(T);
10275 
10276        to indicate that f was a template instantiation, not a new
10277        function declaration.  Now, we have to figure out what
10278        instantiation of what template.  */
10279     {
10280       tree template_id, arglist, fns;
10281       tree new_args;
10282       tree tmpl;
10283       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
10284 
10285       /* Friend functions are looked up in the containing namespace scope.
10286 	 We must enter that scope, to avoid finding member functions of the
10287 	 current class with same name.  */
10288       push_nested_namespace (ns);
10289       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
10290 			 tf_warning_or_error, NULL_TREE,
10291 			 /*integral_constant_expression_p=*/false);
10292       pop_nested_namespace (ns);
10293       arglist = tsubst (DECL_TI_ARGS (decl), args,
10294 			tf_warning_or_error, NULL_TREE);
10295       template_id = lookup_template_function (fns, arglist);
10296 
10297       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
10298       tmpl = determine_specialization (template_id, new_friend,
10299 				       &new_args,
10300 				       /*need_member_template=*/0,
10301 				       TREE_VEC_LENGTH (args),
10302 				       tsk_none);
10303       return instantiate_template (tmpl, new_args, tf_error);
10304     }
10305 
10306   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
10307 
10308   /* The NEW_FRIEND will look like an instantiation, to the
10309      compiler, but is not an instantiation from the point of view of
10310      the language.  For example, we might have had:
10311 
10312      template <class T> struct S {
10313        template <class U> friend void f(T, U);
10314      };
10315 
10316      Then, in S<int>, template <class U> void f(int, U) is not an
10317      instantiation of anything.  */
10318   if (new_friend == error_mark_node)
10319     return error_mark_node;
10320 
10321   DECL_USE_TEMPLATE (new_friend) = 0;
10322   if (TREE_CODE (decl) == TEMPLATE_DECL)
10323     {
10324       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
10325       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
10326 	= DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
10327     }
10328 
10329   /* The mangled name for the NEW_FRIEND is incorrect.  The function
10330      is not a template instantiation and should not be mangled like
10331      one.  Therefore, we forget the mangling here; we'll recompute it
10332      later if we need it.  */
10333   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
10334     {
10335       SET_DECL_RTL (new_friend, NULL);
10336       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
10337     }
10338 
10339   if (DECL_NAMESPACE_SCOPE_P (new_friend))
10340     {
10341       tree old_decl;
10342       tree new_friend_template_info;
10343       tree new_friend_result_template_info;
10344       tree ns;
10345       int  new_friend_is_defn;
10346 
10347       /* We must save some information from NEW_FRIEND before calling
10348 	 duplicate decls since that function will free NEW_FRIEND if
10349 	 possible.  */
10350       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
10351       new_friend_is_defn =
10352 	    (DECL_INITIAL (DECL_TEMPLATE_RESULT
10353 			   (template_for_substitution (new_friend)))
10354 	     != NULL_TREE);
10355       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
10356 	{
10357 	  /* This declaration is a `primary' template.  */
10358 	  DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
10359 
10360 	  new_friend_result_template_info
10361 	    = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
10362 	}
10363       else
10364 	new_friend_result_template_info = NULL_TREE;
10365 
10366       /* Inside pushdecl_namespace_level, we will push into the
10367 	 current namespace. However, the friend function should go
10368 	 into the namespace of the template.  */
10369       ns = decl_namespace_context (new_friend);
10370       push_nested_namespace (ns);
10371       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
10372       pop_nested_namespace (ns);
10373 
10374       if (old_decl == error_mark_node)
10375 	return error_mark_node;
10376 
10377       if (old_decl != new_friend)
10378 	{
10379 	  /* This new friend declaration matched an existing
10380 	     declaration.  For example, given:
10381 
10382 	       template <class T> void f(T);
10383 	       template <class U> class C {
10384 		 template <class T> friend void f(T) {}
10385 	       };
10386 
10387 	     the friend declaration actually provides the definition
10388 	     of `f', once C has been instantiated for some type.  So,
10389 	     old_decl will be the out-of-class template declaration,
10390 	     while new_friend is the in-class definition.
10391 
10392 	     But, if `f' was called before this point, the
10393 	     instantiation of `f' will have DECL_TI_ARGS corresponding
10394 	     to `T' but not to `U', references to which might appear
10395 	     in the definition of `f'.  Previously, the most general
10396 	     template for an instantiation of `f' was the out-of-class
10397 	     version; now it is the in-class version.  Therefore, we
10398 	     run through all specialization of `f', adding to their
10399 	     DECL_TI_ARGS appropriately.  In particular, they need a
10400 	     new set of outer arguments, corresponding to the
10401 	     arguments for this class instantiation.
10402 
10403 	     The same situation can arise with something like this:
10404 
10405 	       friend void f(int);
10406 	       template <class T> class C {
10407 		 friend void f(T) {}
10408 	       };
10409 
10410 	     when `C<int>' is instantiated.  Now, `f(int)' is defined
10411 	     in the class.  */
10412 
10413 	  if (!new_friend_is_defn)
10414 	    /* On the other hand, if the in-class declaration does
10415 	       *not* provide a definition, then we don't want to alter
10416 	       existing definitions.  We can just leave everything
10417 	       alone.  */
10418 	    ;
10419 	  else
10420 	    {
10421 	      tree new_template = TI_TEMPLATE (new_friend_template_info);
10422 	      tree new_args = TI_ARGS (new_friend_template_info);
10423 
10424 	      /* Overwrite whatever template info was there before, if
10425 		 any, with the new template information pertaining to
10426 		 the declaration.  */
10427 	      DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
10428 
10429 	      if (TREE_CODE (old_decl) != TEMPLATE_DECL)
10430 		{
10431 		  /* We should have called reregister_specialization in
10432 		     duplicate_decls.  */
10433 		  gcc_assert (retrieve_specialization (new_template,
10434 						       new_args, 0)
10435 			      == old_decl);
10436 
10437 		  /* Instantiate it if the global has already been used.  */
10438 		  if (DECL_ODR_USED (old_decl))
10439 		    instantiate_decl (old_decl, /*defer_ok=*/true,
10440 				      /*expl_inst_class_mem_p=*/false);
10441 		}
10442 	      else
10443 		{
10444 		  tree t;
10445 
10446 		  /* Indicate that the old function template is a partial
10447 		     instantiation.  */
10448 		  DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
10449 		    = new_friend_result_template_info;
10450 
10451 		  gcc_assert (new_template
10452 			      == most_general_template (new_template));
10453 		  gcc_assert (new_template != old_decl);
10454 
10455 		  /* Reassign any specializations already in the hash table
10456 		     to the new more general template, and add the
10457 		     additional template args.  */
10458 		  for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
10459 		       t != NULL_TREE;
10460 		       t = TREE_CHAIN (t))
10461 		    {
10462 		      tree spec = TREE_VALUE (t);
10463 		      spec_entry elt;
10464 
10465 		      elt.tmpl = old_decl;
10466 		      elt.args = DECL_TI_ARGS (spec);
10467 		      elt.spec = NULL_TREE;
10468 
10469 		      decl_specializations->remove_elt (&elt);
10470 
10471 		      DECL_TI_ARGS (spec)
10472 			= add_outermost_template_args (new_args,
10473 						       DECL_TI_ARGS (spec));
10474 
10475 		      register_specialization
10476 			(spec, new_template, DECL_TI_ARGS (spec), true, 0);
10477 
10478 		    }
10479 		  DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
10480 		}
10481 	    }
10482 
10483 	  /* The information from NEW_FRIEND has been merged into OLD_DECL
10484 	     by duplicate_decls.  */
10485 	  new_friend = old_decl;
10486 	}
10487     }
10488   else
10489     {
10490       tree context = DECL_CONTEXT (new_friend);
10491       bool dependent_p;
10492 
10493       /* In the code
10494 	   template <class T> class C {
10495 	     template <class U> friend void C1<U>::f (); // case 1
10496 	     friend void C2<T>::f ();			 // case 2
10497 	   };
10498 	 we only need to make sure CONTEXT is a complete type for
10499 	 case 2.  To distinguish between the two cases, we note that
10500 	 CONTEXT of case 1 remains dependent type after tsubst while
10501 	 this isn't true for case 2.  */
10502       ++processing_template_decl;
10503       dependent_p = dependent_type_p (context);
10504       --processing_template_decl;
10505 
10506       if (!dependent_p
10507 	  && !complete_type_or_else (context, NULL_TREE))
10508 	return error_mark_node;
10509 
10510       if (COMPLETE_TYPE_P (context))
10511 	{
10512 	  tree fn = new_friend;
10513 	  /* do_friend adds the TEMPLATE_DECL for any member friend
10514 	     template even if it isn't a member template, i.e.
10515 	       template <class T> friend A<T>::f();
10516 	     Look through it in that case.  */
10517 	  if (TREE_CODE (fn) == TEMPLATE_DECL
10518 	      && !PRIMARY_TEMPLATE_P (fn))
10519 	    fn = DECL_TEMPLATE_RESULT (fn);
10520 	  /* Check to see that the declaration is really present, and,
10521 	     possibly obtain an improved declaration.  */
10522 	  fn = check_classfn (context, fn, NULL_TREE);
10523 
10524 	  if (fn)
10525 	    new_friend = fn;
10526 	}
10527     }
10528 
10529   return new_friend;
10530 }
10531 
10532 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
10533    template arguments, as for tsubst.
10534 
10535    Returns an appropriate tsubst'd friend type or error_mark_node on
10536    failure.  */
10537 
10538 static tree
tsubst_friend_class(tree friend_tmpl,tree args)10539 tsubst_friend_class (tree friend_tmpl, tree args)
10540 {
10541   tree tmpl;
10542 
10543   if (DECL_TEMPLATE_TEMPLATE_PARM_P (friend_tmpl))
10544     {
10545       tmpl = tsubst (TREE_TYPE (friend_tmpl), args, tf_none, NULL_TREE);
10546       return TREE_TYPE (tmpl);
10547     }
10548 
10549   tree context = CP_DECL_CONTEXT (friend_tmpl);
10550   if (TREE_CODE (context) == NAMESPACE_DECL)
10551     push_nested_namespace (context);
10552   else
10553     push_nested_class (context);
10554 
10555   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), /*prefer_type=*/false,
10556 			   /*non_class=*/false, /*block_p=*/false,
10557 			   /*namespaces_only=*/false, LOOKUP_HIDDEN);
10558 
10559   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
10560     {
10561       /* The friend template has already been declared.  Just
10562 	 check to see that the declarations match, and install any new
10563 	 default parameters.  We must tsubst the default parameters,
10564 	 of course.  We only need the innermost template parameters
10565 	 because that is all that redeclare_class_template will look
10566 	 at.  */
10567       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
10568 	  > TMPL_ARGS_DEPTH (args))
10569 	{
10570 	  tree parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
10571 					      args, tf_warning_or_error);
10572           location_t saved_input_location = input_location;
10573           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
10574           tree cons = get_constraints (tmpl);
10575           redeclare_class_template (TREE_TYPE (tmpl), parms, cons);
10576           input_location = saved_input_location;
10577 	}
10578     }
10579   else
10580     {
10581       /* The friend template has not already been declared.  In this
10582 	 case, the instantiation of the template class will cause the
10583 	 injection of this template into the namespace scope.  */
10584       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
10585 
10586       if (tmpl != error_mark_node)
10587 	{
10588 	  /* The new TMPL is not an instantiation of anything, so we
10589 	     forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE
10590 	     for the new type because that is supposed to be the
10591 	     corresponding template decl, i.e., TMPL.  */
10592 	  DECL_USE_TEMPLATE (tmpl) = 0;
10593 	  DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
10594 	  CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
10595 	  CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
10596 	    = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
10597 
10598 	  /* It is hidden.  */
10599 	  retrofit_lang_decl (DECL_TEMPLATE_RESULT (tmpl));
10600 	  DECL_ANTICIPATED (tmpl)
10601 	    = DECL_ANTICIPATED (DECL_TEMPLATE_RESULT (tmpl)) = true;
10602 
10603 	  /* Inject this template into the enclosing namspace scope.  */
10604 	  tmpl = pushdecl_namespace_level (tmpl, true);
10605 	}
10606     }
10607 
10608   if (TREE_CODE (context) == NAMESPACE_DECL)
10609     pop_nested_namespace (context);
10610   else
10611     pop_nested_class ();
10612 
10613   return TREE_TYPE (tmpl);
10614 }
10615 
10616 /* Returns zero if TYPE cannot be completed later due to circularity.
10617    Otherwise returns one.  */
10618 
10619 static int
can_complete_type_without_circularity(tree type)10620 can_complete_type_without_circularity (tree type)
10621 {
10622   if (type == NULL_TREE || type == error_mark_node)
10623     return 0;
10624   else if (COMPLETE_TYPE_P (type))
10625     return 1;
10626   else if (TREE_CODE (type) == ARRAY_TYPE)
10627     return can_complete_type_without_circularity (TREE_TYPE (type));
10628   else if (CLASS_TYPE_P (type)
10629 	   && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
10630     return 0;
10631   else
10632     return 1;
10633 }
10634 
10635 static tree tsubst_omp_clauses (tree, enum c_omp_region_type, tree,
10636 				tsubst_flags_t, tree);
10637 
10638 /* Instantiate a single dependent attribute T (a TREE_LIST), and return either
10639    T or a new TREE_LIST, possibly a chain in the case of a pack expansion.  */
10640 
10641 static tree
tsubst_attribute(tree t,tree * decl_p,tree args,tsubst_flags_t complain,tree in_decl)10642 tsubst_attribute (tree t, tree *decl_p, tree args,
10643 		  tsubst_flags_t complain, tree in_decl)
10644 {
10645   gcc_assert (ATTR_IS_DEPENDENT (t));
10646 
10647   tree val = TREE_VALUE (t);
10648   if (val == NULL_TREE)
10649     /* Nothing to do.  */;
10650   else if ((flag_openmp || flag_openmp_simd)
10651 	   && is_attribute_p ("omp declare simd",
10652 			      get_attribute_name (t)))
10653     {
10654       tree clauses = TREE_VALUE (val);
10655       clauses = tsubst_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD, args,
10656 				    complain, in_decl);
10657       c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
10658       clauses = finish_omp_clauses (clauses, C_ORT_OMP_DECLARE_SIMD);
10659       tree parms = DECL_ARGUMENTS (*decl_p);
10660       clauses
10661 	= c_omp_declare_simd_clauses_to_numbers (parms, clauses);
10662       if (clauses)
10663 	val = build_tree_list (NULL_TREE, clauses);
10664       else
10665 	val = NULL_TREE;
10666     }
10667   /* If the first attribute argument is an identifier, don't
10668      pass it through tsubst.  Attributes like mode, format,
10669      cleanup and several target specific attributes expect it
10670      unmodified.  */
10671   else if (attribute_takes_identifier_p (get_attribute_name (t)))
10672     {
10673       tree chain
10674 	= tsubst_expr (TREE_CHAIN (val), args, complain, in_decl,
10675 		       /*integral_constant_expression_p=*/false);
10676       if (chain != TREE_CHAIN (val))
10677 	val = tree_cons (NULL_TREE, TREE_VALUE (val), chain);
10678     }
10679   else if (PACK_EXPANSION_P (val))
10680     {
10681       /* An attribute pack expansion.  */
10682       tree purp = TREE_PURPOSE (t);
10683       tree pack = tsubst_pack_expansion (val, args, complain, in_decl);
10684       if (pack == error_mark_node)
10685 	return error_mark_node;
10686       int len = TREE_VEC_LENGTH (pack);
10687       tree list = NULL_TREE;
10688       tree *q = &list;
10689       for (int i = 0; i < len; ++i)
10690 	{
10691 	  tree elt = TREE_VEC_ELT (pack, i);
10692 	  *q = build_tree_list (purp, elt);
10693 	  q = &TREE_CHAIN (*q);
10694 	}
10695       return list;
10696     }
10697   else
10698     val = tsubst_expr (val, args, complain, in_decl,
10699 		       /*integral_constant_expression_p=*/false);
10700 
10701   if (val != TREE_VALUE (t))
10702     return build_tree_list (TREE_PURPOSE (t), val);
10703   return t;
10704 }
10705 
10706 /* Instantiate any dependent attributes in ATTRIBUTES, returning either it
10707    unchanged or a new TREE_LIST chain.  */
10708 
10709 static tree
tsubst_attributes(tree attributes,tree args,tsubst_flags_t complain,tree in_decl)10710 tsubst_attributes (tree attributes, tree args,
10711 		   tsubst_flags_t complain, tree in_decl)
10712 {
10713   tree last_dep = NULL_TREE;
10714 
10715   for (tree t = attributes; t; t = TREE_CHAIN (t))
10716     if (ATTR_IS_DEPENDENT (t))
10717       {
10718 	last_dep = t;
10719 	attributes = copy_list (attributes);
10720 	break;
10721       }
10722 
10723   if (last_dep)
10724     for (tree *p = &attributes; *p; )
10725       {
10726 	tree t = *p;
10727 	if (ATTR_IS_DEPENDENT (t))
10728 	  {
10729 	    tree subst = tsubst_attribute (t, NULL, args, complain, in_decl);
10730 	    if (subst != t)
10731 	      {
10732 		*p = subst;
10733 		while (*p)
10734 		  p = &TREE_CHAIN (*p);
10735 		*p = TREE_CHAIN (t);
10736 		continue;
10737 	      }
10738 	  }
10739 	p = &TREE_CHAIN (*p);
10740       }
10741 
10742   return attributes;
10743 }
10744 
10745 /* Apply any attributes which had to be deferred until instantiation
10746    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
10747    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
10748 
10749 static void
apply_late_template_attributes(tree * decl_p,tree attributes,int attr_flags,tree args,tsubst_flags_t complain,tree in_decl)10750 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
10751 				tree args, tsubst_flags_t complain, tree in_decl)
10752 {
10753   tree last_dep = NULL_TREE;
10754   tree t;
10755   tree *p;
10756 
10757   if (attributes == NULL_TREE)
10758     return;
10759 
10760   if (DECL_P (*decl_p))
10761     {
10762       if (TREE_TYPE (*decl_p) == error_mark_node)
10763 	return;
10764       p = &DECL_ATTRIBUTES (*decl_p);
10765       /* DECL_ATTRIBUTES comes from copy_node in tsubst_decl, and is identical
10766          to our attributes parameter.  */
10767       gcc_assert (*p == attributes);
10768     }
10769   else
10770     {
10771       p = &TYPE_ATTRIBUTES (*decl_p);
10772       /* TYPE_ATTRIBUTES was set up (with abi_tag and may_alias) in
10773 	 lookup_template_class_1, and should be preserved.  */
10774       gcc_assert (*p != attributes);
10775       while (*p)
10776 	p = &TREE_CHAIN (*p);
10777     }
10778 
10779   for (t = attributes; t; t = TREE_CHAIN (t))
10780     if (ATTR_IS_DEPENDENT (t))
10781       {
10782 	last_dep = t;
10783 	attributes = copy_list (attributes);
10784 	break;
10785       }
10786 
10787   *p = attributes;
10788   if (last_dep)
10789     {
10790       tree late_attrs = NULL_TREE;
10791       tree *q = &late_attrs;
10792 
10793       for (; *p; )
10794 	{
10795 	  t = *p;
10796 	  if (ATTR_IS_DEPENDENT (t))
10797 	    {
10798 	      *p = TREE_CHAIN (t);
10799 	      TREE_CHAIN (t) = NULL_TREE;
10800 	      *q = tsubst_attribute (t, decl_p, args, complain, in_decl);
10801 	      while (*q)
10802 		q = &TREE_CHAIN (*q);
10803 	    }
10804 	  else
10805 	    p = &TREE_CHAIN (t);
10806 	}
10807 
10808       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
10809     }
10810 }
10811 
10812 /* Perform (or defer) access check for typedefs that were referenced
10813    from within the template TMPL code.
10814    This is a subroutine of instantiate_decl and instantiate_class_template.
10815    TMPL is the template to consider and TARGS is the list of arguments of
10816    that template.  */
10817 
10818 static void
perform_typedefs_access_check(tree tmpl,tree targs)10819 perform_typedefs_access_check (tree tmpl, tree targs)
10820 {
10821   location_t saved_location;
10822   unsigned i;
10823   qualified_typedef_usage_t *iter;
10824 
10825   if (!tmpl
10826       || (!CLASS_TYPE_P (tmpl)
10827 	  && TREE_CODE (tmpl) != FUNCTION_DECL))
10828     return;
10829 
10830   saved_location = input_location;
10831   FOR_EACH_VEC_SAFE_ELT (get_types_needing_access_check (tmpl), i, iter)
10832     {
10833       tree type_decl = iter->typedef_decl;
10834       tree type_scope = iter->context;
10835 
10836       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
10837 	continue;
10838 
10839       if (uses_template_parms (type_decl))
10840 	type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
10841       if (uses_template_parms (type_scope))
10842 	type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
10843 
10844       /* Make access check error messages point to the location
10845          of the use of the typedef.  */
10846       input_location = iter->locus;
10847       perform_or_defer_access_check (TYPE_BINFO (type_scope),
10848 				     type_decl, type_decl,
10849 				     tf_warning_or_error);
10850     }
10851     input_location = saved_location;
10852 }
10853 
10854 static tree
instantiate_class_template_1(tree type)10855 instantiate_class_template_1 (tree type)
10856 {
10857   tree templ, args, pattern, t, member;
10858   tree typedecl;
10859   tree pbinfo;
10860   tree base_list;
10861   unsigned int saved_maximum_field_alignment;
10862   tree fn_context;
10863 
10864   if (type == error_mark_node)
10865     return error_mark_node;
10866 
10867   if (COMPLETE_OR_OPEN_TYPE_P (type)
10868       || uses_template_parms (type))
10869     return type;
10870 
10871   /* Figure out which template is being instantiated.  */
10872   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
10873   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
10874 
10875   /* Mark the type as in the process of being defined.  */
10876   TYPE_BEING_DEFINED (type) = 1;
10877 
10878   /* We may be in the middle of deferred access check.  Disable
10879      it now.  */
10880   deferring_access_check_sentinel acs (dk_no_deferred);
10881 
10882   /* Determine what specialization of the original template to
10883      instantiate.  */
10884   t = most_specialized_partial_spec (type, tf_warning_or_error);
10885   if (t == error_mark_node)
10886     return error_mark_node;
10887   else if (t)
10888     {
10889       /* This TYPE is actually an instantiation of a partial
10890 	 specialization.  We replace the innermost set of ARGS with
10891 	 the arguments appropriate for substitution.  For example,
10892 	 given:
10893 
10894 	   template <class T> struct S {};
10895 	   template <class T> struct S<T*> {};
10896 
10897 	 and supposing that we are instantiating S<int*>, ARGS will
10898 	 presently be {int*} -- but we need {int}.  */
10899       pattern = TREE_TYPE (t);
10900       args = TREE_PURPOSE (t);
10901     }
10902   else
10903     {
10904       pattern = TREE_TYPE (templ);
10905       args = CLASSTYPE_TI_ARGS (type);
10906     }
10907 
10908   /* If the template we're instantiating is incomplete, then clearly
10909      there's nothing we can do.  */
10910   if (!COMPLETE_TYPE_P (pattern))
10911     {
10912       /* We can try again later.  */
10913       TYPE_BEING_DEFINED (type) = 0;
10914       return type;
10915     }
10916 
10917   /* If we've recursively instantiated too many templates, stop.  */
10918   if (! push_tinst_level (type))
10919     return type;
10920 
10921   int saved_unevaluated_operand = cp_unevaluated_operand;
10922   int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
10923 
10924   fn_context = decl_function_context (TYPE_MAIN_DECL (type));
10925   /* Also avoid push_to_top_level for a lambda in an NSDMI.  */
10926   if (!fn_context && LAMBDA_TYPE_P (type) && TYPE_CLASS_SCOPE_P (type))
10927     fn_context = error_mark_node;
10928   if (!fn_context)
10929     push_to_top_level ();
10930   else
10931     {
10932       cp_unevaluated_operand = 0;
10933       c_inhibit_evaluation_warnings = 0;
10934     }
10935   /* Use #pragma pack from the template context.  */
10936   saved_maximum_field_alignment = maximum_field_alignment;
10937   maximum_field_alignment = TYPE_PRECISION (pattern);
10938 
10939   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
10940 
10941   /* Set the input location to the most specialized template definition.
10942      This is needed if tsubsting causes an error.  */
10943   typedecl = TYPE_MAIN_DECL (pattern);
10944   input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
10945     DECL_SOURCE_LOCATION (typedecl);
10946 
10947   TYPE_PACKED (type) = TYPE_PACKED (pattern);
10948   SET_TYPE_ALIGN (type, TYPE_ALIGN (pattern));
10949   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
10950   CLASSTYPE_NON_AGGREGATE (type) = CLASSTYPE_NON_AGGREGATE (pattern);
10951   if (ANON_AGGR_TYPE_P (pattern))
10952     SET_ANON_AGGR_TYPE_P (type);
10953   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
10954     {
10955       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
10956       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
10957       /* Adjust visibility for template arguments.  */
10958       determine_visibility (TYPE_MAIN_DECL (type));
10959     }
10960   if (CLASS_TYPE_P (type))
10961     CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
10962 
10963   pbinfo = TYPE_BINFO (pattern);
10964 
10965   /* We should never instantiate a nested class before its enclosing
10966      class; we need to look up the nested class by name before we can
10967      instantiate it, and that lookup should instantiate the enclosing
10968      class.  */
10969   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
10970 	      || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
10971 
10972   base_list = NULL_TREE;
10973   if (BINFO_N_BASE_BINFOS (pbinfo))
10974     {
10975       tree pbase_binfo;
10976       tree pushed_scope;
10977       int i;
10978 
10979       /* We must enter the scope containing the type, as that is where
10980 	 the accessibility of types named in dependent bases are
10981 	 looked up from.  */
10982       pushed_scope = push_scope (CP_TYPE_CONTEXT (type));
10983 
10984       /* Substitute into each of the bases to determine the actual
10985 	 basetypes.  */
10986       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
10987 	{
10988 	  tree base;
10989 	  tree access = BINFO_BASE_ACCESS (pbinfo, i);
10990           tree expanded_bases = NULL_TREE;
10991           int idx, len = 1;
10992 
10993           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
10994             {
10995               expanded_bases =
10996 		tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
10997 				       args, tf_error, NULL_TREE);
10998               if (expanded_bases == error_mark_node)
10999                 continue;
11000 
11001               len = TREE_VEC_LENGTH (expanded_bases);
11002             }
11003 
11004           for (idx = 0; idx < len; idx++)
11005             {
11006               if (expanded_bases)
11007                 /* Extract the already-expanded base class.  */
11008                 base = TREE_VEC_ELT (expanded_bases, idx);
11009               else
11010                 /* Substitute to figure out the base class.  */
11011                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error,
11012                                NULL_TREE);
11013 
11014               if (base == error_mark_node)
11015                 continue;
11016 
11017               base_list = tree_cons (access, base, base_list);
11018               if (BINFO_VIRTUAL_P (pbase_binfo))
11019                 TREE_TYPE (base_list) = integer_type_node;
11020             }
11021 	}
11022 
11023       /* The list is now in reverse order; correct that.  */
11024       base_list = nreverse (base_list);
11025 
11026       if (pushed_scope)
11027 	pop_scope (pushed_scope);
11028     }
11029   /* Now call xref_basetypes to set up all the base-class
11030      information.  */
11031   xref_basetypes (type, base_list);
11032 
11033   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
11034 				  (int) ATTR_FLAG_TYPE_IN_PLACE,
11035 				  args, tf_error, NULL_TREE);
11036   fixup_attribute_variants (type);
11037 
11038   /* Now that our base classes are set up, enter the scope of the
11039      class, so that name lookups into base classes, etc. will work
11040      correctly.  This is precisely analogous to what we do in
11041      begin_class_definition when defining an ordinary non-template
11042      class, except we also need to push the enclosing classes.  */
11043   push_nested_class (type);
11044 
11045   /* Now members are processed in the order of declaration.  */
11046   for (member = CLASSTYPE_DECL_LIST (pattern);
11047        member; member = TREE_CHAIN (member))
11048     {
11049       tree t = TREE_VALUE (member);
11050 
11051       if (TREE_PURPOSE (member))
11052 	{
11053 	  if (TYPE_P (t))
11054 	    {
11055 	      if (LAMBDA_TYPE_P (t))
11056 		/* A closure type for a lambda in an NSDMI or default argument.
11057 		   Ignore it; it will be regenerated when needed.  */
11058 		continue;
11059 
11060 	      /* Build new CLASSTYPE_NESTED_UTDS.  */
11061 
11062 	      tree newtag;
11063 	      bool class_template_p;
11064 
11065 	      class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
11066 				  && TYPE_LANG_SPECIFIC (t)
11067 				  && CLASSTYPE_IS_TEMPLATE (t));
11068 	      /* If the member is a class template, then -- even after
11069 		 substitution -- there may be dependent types in the
11070 		 template argument list for the class.  We increment
11071 		 PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
11072 		 that function will assume that no types are dependent
11073 		 when outside of a template.  */
11074 	      if (class_template_p)
11075 		++processing_template_decl;
11076 	      newtag = tsubst (t, args, tf_error, NULL_TREE);
11077 	      if (class_template_p)
11078 		--processing_template_decl;
11079 	      if (newtag == error_mark_node)
11080 		continue;
11081 
11082 	      if (TREE_CODE (newtag) != ENUMERAL_TYPE)
11083 		{
11084 		  tree name = TYPE_IDENTIFIER (t);
11085 
11086 		  if (class_template_p)
11087 		    /* Unfortunately, lookup_template_class sets
11088 		       CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
11089 		       instantiation (i.e., for the type of a member
11090 		       template class nested within a template class.)
11091 		       This behavior is required for
11092 		       maybe_process_partial_specialization to work
11093 		       correctly, but is not accurate in this case;
11094 		       the TAG is not an instantiation of anything.
11095 		       (The corresponding TEMPLATE_DECL is an
11096 		       instantiation, but the TYPE is not.) */
11097 		    CLASSTYPE_USE_TEMPLATE (newtag) = 0;
11098 
11099 		  /* Now, we call pushtag to put this NEWTAG into the scope of
11100 		     TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
11101 		     pushtag calling push_template_decl.  We don't have to do
11102 		     this for enums because it will already have been done in
11103 		     tsubst_enum.  */
11104 		  if (name)
11105 		    SET_IDENTIFIER_TYPE_VALUE (name, newtag);
11106 		  pushtag (name, newtag, /*tag_scope=*/ts_current);
11107 		}
11108 	    }
11109 	  else if (DECL_DECLARES_FUNCTION_P (t))
11110 	    {
11111 	      tree r;
11112 
11113 	      if (TREE_CODE (t) == TEMPLATE_DECL)
11114 		++processing_template_decl;
11115 	      r = tsubst (t, args, tf_error, NULL_TREE);
11116 	      if (TREE_CODE (t) == TEMPLATE_DECL)
11117 		--processing_template_decl;
11118 	      set_current_access_from_decl (r);
11119 	      finish_member_declaration (r);
11120 	      /* Instantiate members marked with attribute used.  */
11121 	      if (r != error_mark_node && DECL_PRESERVE_P (r))
11122 		mark_used (r);
11123 	      if (TREE_CODE (r) == FUNCTION_DECL
11124 		  && DECL_OMP_DECLARE_REDUCTION_P (r))
11125 		cp_check_omp_declare_reduction (r);
11126 	    }
11127 	  else if ((DECL_CLASS_TEMPLATE_P (t) || DECL_IMPLICIT_TYPEDEF_P (t))
11128 		   && LAMBDA_TYPE_P (TREE_TYPE (t)))
11129 	    /* A closure type for a lambda in an NSDMI or default argument.
11130 	       Ignore it; it will be regenerated when needed.  */;
11131 	  else
11132 	    {
11133 	      /* Build new TYPE_FIELDS.  */
11134               if (TREE_CODE (t) == STATIC_ASSERT)
11135                 {
11136                   tree condition;
11137 
11138 		  ++c_inhibit_evaluation_warnings;
11139 		  condition =
11140 		    tsubst_expr (STATIC_ASSERT_CONDITION (t), args,
11141 				 tf_warning_or_error, NULL_TREE,
11142 				 /*integral_constant_expression_p=*/true);
11143 		  --c_inhibit_evaluation_warnings;
11144 
11145                   finish_static_assert (condition,
11146                                         STATIC_ASSERT_MESSAGE (t),
11147                                         STATIC_ASSERT_SOURCE_LOCATION (t),
11148                                         /*member_p=*/true);
11149                 }
11150 	      else if (TREE_CODE (t) != CONST_DECL)
11151 		{
11152 		  tree r;
11153 		  tree vec = NULL_TREE;
11154 		  int len = 1;
11155 
11156 		  /* The file and line for this declaration, to
11157 		     assist in error message reporting.  Since we
11158 		     called push_tinst_level above, we don't need to
11159 		     restore these.  */
11160 		  input_location = DECL_SOURCE_LOCATION (t);
11161 
11162 		  if (TREE_CODE (t) == TEMPLATE_DECL)
11163 		    ++processing_template_decl;
11164 		  r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
11165 		  if (TREE_CODE (t) == TEMPLATE_DECL)
11166 		    --processing_template_decl;
11167 
11168 		  if (TREE_CODE (r) == TREE_VEC)
11169 		    {
11170 		      /* A capture pack became multiple fields.  */
11171 		      vec = r;
11172 		      len = TREE_VEC_LENGTH (vec);
11173 		    }
11174 
11175 		  for (int i = 0; i < len; ++i)
11176 		    {
11177 		      if (vec)
11178 			r = TREE_VEC_ELT (vec, i);
11179 		      if (VAR_P (r))
11180 			{
11181 			  /* In [temp.inst]:
11182 
11183 			     [t]he initialization (and any associated
11184 			     side-effects) of a static data member does
11185 			     not occur unless the static data member is
11186 			     itself used in a way that requires the
11187 			     definition of the static data member to
11188 			     exist.
11189 
11190 			     Therefore, we do not substitute into the
11191 			     initialized for the static data member here.  */
11192 			  finish_static_data_member_decl
11193 			    (r,
11194 			     /*init=*/NULL_TREE,
11195 			     /*init_const_expr_p=*/false,
11196 			     /*asmspec_tree=*/NULL_TREE,
11197 			     /*flags=*/0);
11198 			  /* Instantiate members marked with attribute used. */
11199 			  if (r != error_mark_node && DECL_PRESERVE_P (r))
11200 			    mark_used (r);
11201 			}
11202 		      else if (TREE_CODE (r) == FIELD_DECL)
11203 			{
11204 			  /* Determine whether R has a valid type and can be
11205 			     completed later.  If R is invalid, then its type
11206 			     is replaced by error_mark_node.  */
11207 			  tree rtype = TREE_TYPE (r);
11208 			  if (can_complete_type_without_circularity (rtype))
11209 			    complete_type (rtype);
11210 
11211 			  if (!complete_or_array_type_p (rtype))
11212 			    {
11213 			      /* If R's type couldn't be completed and
11214 				 it isn't a flexible array member (whose
11215 				 type is incomplete by definition) give
11216 				 an error.  */
11217 			      cxx_incomplete_type_error (r, rtype);
11218 			      TREE_TYPE (r) = error_mark_node;
11219 			    }
11220 			  else if (TREE_CODE (rtype) == ARRAY_TYPE
11221 				   && TYPE_DOMAIN (rtype) == NULL_TREE
11222 				   && (TREE_CODE (type) == UNION_TYPE
11223 				       || TREE_CODE (type) == QUAL_UNION_TYPE))
11224 			    {
11225 			      error ("flexible array member %qD in union", r);
11226 			      TREE_TYPE (r) = error_mark_node;
11227 			    }
11228 			}
11229 
11230 		      /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
11231 			 such a thing will already have been added to the field
11232 			 list by tsubst_enum in finish_member_declaration in the
11233 			 CLASSTYPE_NESTED_UTDS case above.  */
11234 		      if (!(TREE_CODE (r) == TYPE_DECL
11235 			    && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
11236 			    && DECL_ARTIFICIAL (r)))
11237 			{
11238 			  set_current_access_from_decl (r);
11239 			  finish_member_declaration (r);
11240 			}
11241 		    }
11242 		}
11243 	    }
11244 	}
11245       else
11246 	{
11247 	  if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t)
11248 	      || DECL_TEMPLATE_TEMPLATE_PARM_P (t))
11249 	    {
11250 	      /* Build new CLASSTYPE_FRIEND_CLASSES.  */
11251 
11252 	      tree friend_type = t;
11253 	      bool adjust_processing_template_decl = false;
11254 
11255 	      if (TREE_CODE (friend_type) == TEMPLATE_DECL)
11256 		{
11257 		  /* template <class T> friend class C;  */
11258 		  friend_type = tsubst_friend_class (friend_type, args);
11259 		  adjust_processing_template_decl = true;
11260 		}
11261 	      else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
11262 		{
11263 		  /* template <class T> friend class C::D;  */
11264 		  friend_type = tsubst (friend_type, args,
11265 					tf_warning_or_error, NULL_TREE);
11266 		  if (TREE_CODE (friend_type) == TEMPLATE_DECL)
11267 		    friend_type = TREE_TYPE (friend_type);
11268 		  adjust_processing_template_decl = true;
11269 		}
11270 	      else if (TREE_CODE (friend_type) == TYPENAME_TYPE
11271 		       || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
11272 		{
11273 		  /* This could be either
11274 
11275 		       friend class T::C;
11276 
11277 		     when dependent_type_p is false or
11278 
11279 		       template <class U> friend class T::C;
11280 
11281 		     otherwise.  */
11282 		  /* Bump processing_template_decl in case this is something like
11283 		     template <class T> friend struct A<T>::B.  */
11284 		  ++processing_template_decl;
11285 		  friend_type = tsubst (friend_type, args,
11286 					tf_warning_or_error, NULL_TREE);
11287 		  if (dependent_type_p (friend_type))
11288 		    adjust_processing_template_decl = true;
11289 		  --processing_template_decl;
11290 		}
11291 	      else if (TREE_CODE (friend_type) != BOUND_TEMPLATE_TEMPLATE_PARM
11292 		       && !CLASSTYPE_USE_TEMPLATE (friend_type)
11293 		       && TYPE_HIDDEN_P (friend_type))
11294 		{
11295 		  /* friend class C;
11296 
11297 		     where C hasn't been declared yet.  Let's lookup name
11298 		     from namespace scope directly, bypassing any name that
11299 		     come from dependent base class.  */
11300 		  tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
11301 
11302 		  /* The call to xref_tag_from_type does injection for friend
11303 		     classes.  */
11304 		  push_nested_namespace (ns);
11305 		  friend_type =
11306 		    xref_tag_from_type (friend_type, NULL_TREE,
11307 					/*tag_scope=*/ts_current);
11308 		  pop_nested_namespace (ns);
11309 		}
11310 	      else if (uses_template_parms (friend_type))
11311 		/* friend class C<T>;  */
11312 		friend_type = tsubst (friend_type, args,
11313 				      tf_warning_or_error, NULL_TREE);
11314 	      /* Otherwise it's
11315 
11316 		   friend class C;
11317 
11318 		 where C is already declared or
11319 
11320 		   friend class C<int>;
11321 
11322 		 We don't have to do anything in these cases.  */
11323 
11324 	      if (adjust_processing_template_decl)
11325 		/* Trick make_friend_class into realizing that the friend
11326 		   we're adding is a template, not an ordinary class.  It's
11327 		   important that we use make_friend_class since it will
11328 		   perform some error-checking and output cross-reference
11329 		   information.  */
11330 		++processing_template_decl;
11331 
11332 	      if (friend_type != error_mark_node)
11333 		make_friend_class (type, friend_type, /*complain=*/false);
11334 
11335 	      if (adjust_processing_template_decl)
11336 		--processing_template_decl;
11337 	    }
11338 	  else
11339 	    {
11340 	      /* Build new DECL_FRIENDLIST.  */
11341 	      tree r;
11342 
11343 	      /* The file and line for this declaration, to
11344 		 assist in error message reporting.  Since we
11345 		 called push_tinst_level above, we don't need to
11346 		 restore these.  */
11347 	      input_location = DECL_SOURCE_LOCATION (t);
11348 
11349 	      if (TREE_CODE (t) == TEMPLATE_DECL)
11350 		{
11351 		  ++processing_template_decl;
11352 		  push_deferring_access_checks (dk_no_check);
11353 		}
11354 
11355 	      r = tsubst_friend_function (t, args);
11356 	      add_friend (type, r, /*complain=*/false);
11357 	      if (TREE_CODE (t) == TEMPLATE_DECL)
11358 		{
11359 		  pop_deferring_access_checks ();
11360 		  --processing_template_decl;
11361 		}
11362 	    }
11363 	}
11364     }
11365 
11366   if (fn_context)
11367     {
11368       /* Restore these before substituting into the lambda capture
11369 	 initializers.  */
11370       cp_unevaluated_operand = saved_unevaluated_operand;
11371       c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
11372     }
11373 
11374   /* Set the file and line number information to whatever is given for
11375      the class itself.  This puts error messages involving generated
11376      implicit functions at a predictable point, and the same point
11377      that would be used for non-template classes.  */
11378   input_location = DECL_SOURCE_LOCATION (typedecl);
11379 
11380   unreverse_member_declarations (type);
11381   finish_struct_1 (type);
11382   TYPE_BEING_DEFINED (type) = 0;
11383 
11384   /* We don't instantiate default arguments for member functions.  14.7.1:
11385 
11386      The implicit instantiation of a class template specialization causes
11387      the implicit instantiation of the declarations, but not of the
11388      definitions or default arguments, of the class member functions,
11389      member classes, static data members and member templates....  */
11390 
11391   /* Some typedefs referenced from within the template code need to be access
11392      checked at template instantiation time, i.e now. These types were
11393      added to the template at parsing time. Let's get those and perform
11394      the access checks then.  */
11395   perform_typedefs_access_check (pattern, args);
11396   perform_deferred_access_checks (tf_warning_or_error);
11397   pop_nested_class ();
11398   maximum_field_alignment = saved_maximum_field_alignment;
11399   if (!fn_context)
11400     pop_from_top_level ();
11401   pop_tinst_level ();
11402 
11403   /* The vtable for a template class can be emitted in any translation
11404      unit in which the class is instantiated.  When there is no key
11405      method, however, finish_struct_1 will already have added TYPE to
11406      the keyed_classes.  */
11407   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
11408     vec_safe_push (keyed_classes, type);
11409 
11410   return type;
11411 }
11412 
11413 /* Wrapper for instantiate_class_template_1.  */
11414 
11415 tree
instantiate_class_template(tree type)11416 instantiate_class_template (tree type)
11417 {
11418   tree ret;
11419   timevar_push (TV_TEMPLATE_INST);
11420   ret = instantiate_class_template_1 (type);
11421   timevar_pop (TV_TEMPLATE_INST);
11422   return ret;
11423 }
11424 
11425 static tree
tsubst_template_arg(tree t,tree args,tsubst_flags_t complain,tree in_decl)11426 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11427 {
11428   tree r;
11429 
11430   if (!t)
11431     r = t;
11432   else if (TYPE_P (t))
11433     r = tsubst (t, args, complain, in_decl);
11434   else
11435     {
11436       if (!(complain & tf_warning))
11437 	++c_inhibit_evaluation_warnings;
11438       r = tsubst_expr (t, args, complain, in_decl,
11439 		       /*integral_constant_expression_p=*/true);
11440       if (!(complain & tf_warning))
11441 	--c_inhibit_evaluation_warnings;
11442     }
11443   return r;
11444 }
11445 
11446 /* Given a function parameter pack TMPL_PARM and some function parameters
11447    instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
11448    and set *SPEC_P to point at the next point in the list.  */
11449 
11450 tree
extract_fnparm_pack(tree tmpl_parm,tree * spec_p)11451 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
11452 {
11453   /* Collect all of the extra "packed" parameters into an
11454      argument pack.  */
11455   tree parmvec;
11456   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
11457   tree spec_parm = *spec_p;
11458   int i, len;
11459 
11460   for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
11461     if (tmpl_parm
11462 	&& !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
11463       break;
11464 
11465   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
11466   parmvec = make_tree_vec (len);
11467   spec_parm = *spec_p;
11468   for (i = 0; i < len; i++, spec_parm = DECL_CHAIN (spec_parm))
11469     {
11470       tree elt = spec_parm;
11471       if (DECL_PACK_P (elt))
11472 	elt = make_pack_expansion (elt);
11473       TREE_VEC_ELT (parmvec, i) = elt;
11474     }
11475 
11476   /* Build the argument packs.  */
11477   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
11478   *spec_p = spec_parm;
11479 
11480   return argpack;
11481 }
11482 
11483 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
11484    NONTYPE_ARGUMENT_PACK.  */
11485 
11486 static tree
make_fnparm_pack(tree spec_parm)11487 make_fnparm_pack (tree spec_parm)
11488 {
11489   return extract_fnparm_pack (NULL_TREE, &spec_parm);
11490 }
11491 
11492 /* Return 1 if the Ith element of the argument pack ARG_PACK is a
11493    pack expansion with no extra args, 2 if it has extra args, or 0
11494    if it is not a pack expansion.  */
11495 
11496 static int
argument_pack_element_is_expansion_p(tree arg_pack,int i)11497 argument_pack_element_is_expansion_p (tree arg_pack, int i)
11498 {
11499   tree vec = ARGUMENT_PACK_ARGS (arg_pack);
11500   if (i >= TREE_VEC_LENGTH (vec))
11501     return 0;
11502   tree elt = TREE_VEC_ELT (vec, i);
11503   if (DECL_P (elt))
11504     /* A decl pack is itself an expansion.  */
11505     elt = TREE_TYPE (elt);
11506   if (!PACK_EXPANSION_P (elt))
11507     return 0;
11508   if (PACK_EXPANSION_EXTRA_ARGS (elt))
11509     return 2;
11510   return 1;
11511 }
11512 
11513 
11514 /* Creates and return an ARGUMENT_PACK_SELECT tree node.  */
11515 
11516 static tree
make_argument_pack_select(tree arg_pack,unsigned index)11517 make_argument_pack_select (tree arg_pack, unsigned index)
11518 {
11519   tree aps = make_node (ARGUMENT_PACK_SELECT);
11520 
11521   ARGUMENT_PACK_SELECT_FROM_PACK (aps) = arg_pack;
11522   ARGUMENT_PACK_SELECT_INDEX (aps) = index;
11523 
11524   return aps;
11525 }
11526 
11527 /*  This is a subroutine of tsubst_pack_expansion.
11528 
11529     It returns TRUE if we need to use the PACK_EXPANSION_EXTRA_ARGS
11530     mechanism to store the (non complete list of) arguments of the
11531     substitution and return a non substituted pack expansion, in order
11532     to wait for when we have enough arguments to really perform the
11533     substitution.  */
11534 
11535 static bool
use_pack_expansion_extra_args_p(tree parm_packs,int arg_pack_len,bool has_empty_arg)11536 use_pack_expansion_extra_args_p (tree parm_packs,
11537 				 int arg_pack_len,
11538 				 bool has_empty_arg)
11539 {
11540   /* If one pack has an expansion and another pack has a normal
11541      argument or if one pack has an empty argument and an another
11542      one hasn't then tsubst_pack_expansion cannot perform the
11543      substitution and need to fall back on the
11544      PACK_EXPANSION_EXTRA mechanism.  */
11545   if (parm_packs == NULL_TREE)
11546     return false;
11547   else if (has_empty_arg)
11548     return true;
11549 
11550   bool has_expansion_arg = false;
11551   for (int i = 0 ; i < arg_pack_len; ++i)
11552     {
11553       bool has_non_expansion_arg = false;
11554       for (tree parm_pack = parm_packs;
11555 	   parm_pack;
11556 	   parm_pack = TREE_CHAIN (parm_pack))
11557 	{
11558 	  tree arg = TREE_VALUE (parm_pack);
11559 
11560 	  int exp = argument_pack_element_is_expansion_p (arg, i);
11561 	  if (exp == 2)
11562 	    /* We can't substitute a pack expansion with extra args into
11563 	       our pattern.  */
11564 	    return true;
11565 	  else if (exp)
11566 	    has_expansion_arg = true;
11567 	  else
11568 	    has_non_expansion_arg = true;
11569 	}
11570 
11571       if (has_expansion_arg && has_non_expansion_arg)
11572 	return true;
11573     }
11574   return false;
11575 }
11576 
11577 /* [temp.variadic]/6 says that:
11578 
11579        The instantiation of a pack expansion [...]
11580        produces a list E1,E2, ..., En, where N is the number of elements
11581        in the pack expansion parameters.
11582 
11583    This subroutine of tsubst_pack_expansion produces one of these Ei.
11584 
11585    PATTERN is the pattern of the pack expansion.  PARM_PACKS is a
11586    TREE_LIST in which each TREE_PURPOSE is a parameter pack of
11587    PATTERN, and each TREE_VALUE is its corresponding argument pack.
11588    INDEX is the index 'i' of the element Ei to produce.  ARGS,
11589    COMPLAIN, and IN_DECL are the same parameters as for the
11590    tsubst_pack_expansion function.
11591 
11592    The function returns the resulting Ei upon successful completion,
11593    or error_mark_node.
11594 
11595    Note that this function possibly modifies the ARGS parameter, so
11596    it's the responsibility of the caller to restore it.  */
11597 
11598 static tree
gen_elem_of_pack_expansion_instantiation(tree pattern,tree parm_packs,unsigned index,tree args,tsubst_flags_t complain,tree in_decl)11599 gen_elem_of_pack_expansion_instantiation (tree pattern,
11600 					  tree parm_packs,
11601 					  unsigned index,
11602 					  tree args /* This parm gets
11603 						       modified.  */,
11604 					  tsubst_flags_t complain,
11605 					  tree in_decl)
11606 {
11607   tree t;
11608   bool ith_elem_is_expansion = false;
11609 
11610   /* For each parameter pack, change the substitution of the parameter
11611      pack to the ith argument in its argument pack, then expand the
11612      pattern.  */
11613   for (tree pack = parm_packs; pack; pack = TREE_CHAIN (pack))
11614     {
11615       tree parm = TREE_PURPOSE (pack);
11616       tree arg_pack = TREE_VALUE (pack);
11617       tree aps;			/* instance of ARGUMENT_PACK_SELECT.  */
11618 
11619       ith_elem_is_expansion |=
11620 	argument_pack_element_is_expansion_p (arg_pack, index);
11621 
11622       /* Select the Ith argument from the pack.  */
11623       if (TREE_CODE (parm) == PARM_DECL
11624 	  || VAR_P (parm)
11625 	  || TREE_CODE (parm) == FIELD_DECL)
11626 	{
11627 	  if (index == 0)
11628 	    {
11629 	      aps = make_argument_pack_select (arg_pack, index);
11630 	      if (!mark_used (parm, complain) && !(complain & tf_error))
11631 		return error_mark_node;
11632 	      register_local_specialization (aps, parm);
11633 	    }
11634 	  else
11635 	    aps = retrieve_local_specialization (parm);
11636 	}
11637       else
11638 	{
11639 	  int idx, level;
11640 	  template_parm_level_and_index (parm, &level, &idx);
11641 
11642 	  if (index == 0)
11643 	    {
11644 	      aps = make_argument_pack_select (arg_pack, index);
11645 	      /* Update the corresponding argument.  */
11646 	      TMPL_ARG (args, level, idx) = aps;
11647 	    }
11648 	  else
11649 	    /* Re-use the ARGUMENT_PACK_SELECT.  */
11650 	    aps = TMPL_ARG (args, level, idx);
11651 	}
11652       ARGUMENT_PACK_SELECT_INDEX (aps) = index;
11653     }
11654 
11655   /* Substitute into the PATTERN with the (possibly altered)
11656      arguments.  */
11657   if (pattern == in_decl)
11658     /* Expanding a fixed parameter pack from
11659        coerce_template_parameter_pack.  */
11660     t = tsubst_decl (pattern, args, complain);
11661   else if (pattern == error_mark_node)
11662     t = error_mark_node;
11663   else if (constraint_p (pattern))
11664     {
11665       if (processing_template_decl)
11666 	t = tsubst_constraint (pattern, args, complain, in_decl);
11667       else
11668 	t = (constraints_satisfied_p (pattern, args)
11669 	     ? boolean_true_node : boolean_false_node);
11670     }
11671   else if (!TYPE_P (pattern))
11672     t = tsubst_expr (pattern, args, complain, in_decl,
11673 		     /*integral_constant_expression_p=*/false);
11674   else
11675     t = tsubst (pattern, args, complain, in_decl);
11676 
11677   /*  If the Ith argument pack element is a pack expansion, then
11678       the Ith element resulting from the substituting is going to
11679       be a pack expansion as well.  */
11680   if (ith_elem_is_expansion)
11681     t = make_pack_expansion (t, complain);
11682 
11683   return t;
11684 }
11685 
11686 /* When the unexpanded parameter pack in a fold expression expands to an empty
11687    sequence, the value of the expression is as follows; the program is
11688    ill-formed if the operator is not listed in this table.
11689 
11690    &&	true
11691    ||	false
11692    ,	void()  */
11693 
11694 tree
expand_empty_fold(tree t,tsubst_flags_t complain)11695 expand_empty_fold (tree t, tsubst_flags_t complain)
11696 {
11697   tree_code code = (tree_code)TREE_INT_CST_LOW (TREE_OPERAND (t, 0));
11698   if (!FOLD_EXPR_MODIFY_P (t))
11699     switch (code)
11700       {
11701       case TRUTH_ANDIF_EXPR:
11702 	return boolean_true_node;
11703       case TRUTH_ORIF_EXPR:
11704 	return boolean_false_node;
11705       case COMPOUND_EXPR:
11706 	return void_node;
11707       default:
11708 	break;
11709       }
11710 
11711   if (complain & tf_error)
11712     error_at (location_of (t),
11713 	      "fold of empty expansion over %O", code);
11714   return error_mark_node;
11715 }
11716 
11717 /* Given a fold-expression T and a current LEFT and RIGHT operand,
11718    form an expression that combines the two terms using the
11719    operator of T. */
11720 
11721 static tree
fold_expression(tree t,tree left,tree right,tsubst_flags_t complain)11722 fold_expression (tree t, tree left, tree right, tsubst_flags_t complain)
11723 {
11724   tree op = FOLD_EXPR_OP (t);
11725   tree_code code = (tree_code)TREE_INT_CST_LOW (op);
11726 
11727   // Handle compound assignment operators.
11728   if (FOLD_EXPR_MODIFY_P (t))
11729     return build_x_modify_expr (input_location, left, code, right, complain);
11730 
11731   switch (code)
11732     {
11733     case COMPOUND_EXPR:
11734       return build_x_compound_expr (input_location, left, right, complain);
11735     default:
11736       return build_x_binary_op (input_location, code,
11737                                 left, TREE_CODE (left),
11738                                 right, TREE_CODE (right),
11739                                 /*overload=*/NULL,
11740                                 complain);
11741     }
11742 }
11743 
11744 /* Substitute ARGS into the pack of a fold expression T. */
11745 
11746 static inline tree
tsubst_fold_expr_pack(tree t,tree args,tsubst_flags_t complain,tree in_decl)11747 tsubst_fold_expr_pack (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11748 {
11749   return tsubst_pack_expansion (FOLD_EXPR_PACK (t), args, complain, in_decl);
11750 }
11751 
11752 /* Substitute ARGS into the pack of a fold expression T. */
11753 
11754 static inline tree
tsubst_fold_expr_init(tree t,tree args,tsubst_flags_t complain,tree in_decl)11755 tsubst_fold_expr_init (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11756 {
11757   return tsubst_expr (FOLD_EXPR_INIT (t), args, complain, in_decl, false);
11758 }
11759 
11760 /* Expand a PACK of arguments into a grouped as left fold.
11761    Given a pack containing elements A0, A1, ..., An and an
11762    operator @, this builds the expression:
11763 
11764       ((A0 @ A1) @ A2) ... @ An
11765 
11766    Note that PACK must not be empty.
11767 
11768    The operator is defined by the original fold expression T. */
11769 
11770 static tree
expand_left_fold(tree t,tree pack,tsubst_flags_t complain)11771 expand_left_fold (tree t, tree pack, tsubst_flags_t complain)
11772 {
11773   tree left = TREE_VEC_ELT (pack, 0);
11774   for (int i = 1; i < TREE_VEC_LENGTH (pack); ++i)
11775     {
11776       tree right = TREE_VEC_ELT (pack, i);
11777       left = fold_expression (t, left, right, complain);
11778     }
11779   return left;
11780 }
11781 
11782 /* Substitute into a unary left fold expression. */
11783 
11784 static tree
tsubst_unary_left_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)11785 tsubst_unary_left_fold (tree t, tree args, tsubst_flags_t complain,
11786                         tree in_decl)
11787 {
11788   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
11789   if (pack == error_mark_node)
11790     return error_mark_node;
11791   if (PACK_EXPANSION_P (pack))
11792     {
11793       tree r = copy_node (t);
11794       FOLD_EXPR_PACK (r) = pack;
11795       return r;
11796     }
11797   if (TREE_VEC_LENGTH (pack) == 0)
11798     return expand_empty_fold (t, complain);
11799   else
11800     return expand_left_fold (t, pack, complain);
11801 }
11802 
11803 /* Substitute into a binary left fold expression.
11804 
11805    Do ths by building a single (non-empty) vector of argumnts and
11806    building the expression from those elements. */
11807 
11808 static tree
tsubst_binary_left_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)11809 tsubst_binary_left_fold (tree t, tree args, tsubst_flags_t complain,
11810                          tree in_decl)
11811 {
11812   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
11813   if (pack == error_mark_node)
11814     return error_mark_node;
11815   tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
11816   if (init == error_mark_node)
11817     return error_mark_node;
11818 
11819   if (PACK_EXPANSION_P (pack))
11820     {
11821       tree r = copy_node (t);
11822       FOLD_EXPR_PACK (r) = pack;
11823       FOLD_EXPR_INIT (r) = init;
11824       return r;
11825     }
11826 
11827   tree vec = make_tree_vec (TREE_VEC_LENGTH (pack) + 1);
11828   TREE_VEC_ELT (vec, 0) = init;
11829   for (int i = 0; i < TREE_VEC_LENGTH (pack); ++i)
11830     TREE_VEC_ELT (vec, i + 1) = TREE_VEC_ELT (pack, i);
11831 
11832   return expand_left_fold (t, vec, complain);
11833 }
11834 
11835 /* Expand a PACK of arguments into a grouped as right fold.
11836    Given a pack containing elementns A0, A1, ..., and an
11837    operator @, this builds the expression:
11838 
11839       A0@ ... (An-2 @ (An-1 @ An))
11840 
11841    Note that PACK must not be empty.
11842 
11843    The operator is defined by the original fold expression T. */
11844 
11845 tree
expand_right_fold(tree t,tree pack,tsubst_flags_t complain)11846 expand_right_fold (tree t, tree pack, tsubst_flags_t complain)
11847 {
11848   // Build the expression.
11849   int n = TREE_VEC_LENGTH (pack);
11850   tree right = TREE_VEC_ELT (pack, n - 1);
11851   for (--n; n != 0; --n)
11852     {
11853       tree left = TREE_VEC_ELT (pack, n - 1);
11854       right = fold_expression (t, left, right, complain);
11855     }
11856   return right;
11857 }
11858 
11859 /* Substitute into a unary right fold expression. */
11860 
11861 static tree
tsubst_unary_right_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)11862 tsubst_unary_right_fold (tree t, tree args, tsubst_flags_t complain,
11863                          tree in_decl)
11864 {
11865   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
11866   if (pack == error_mark_node)
11867     return error_mark_node;
11868   if (PACK_EXPANSION_P (pack))
11869     {
11870       tree r = copy_node (t);
11871       FOLD_EXPR_PACK (r) = pack;
11872       return r;
11873     }
11874   if (TREE_VEC_LENGTH (pack) == 0)
11875     return expand_empty_fold (t, complain);
11876   else
11877     return expand_right_fold (t, pack, complain);
11878 }
11879 
11880 /* Substitute into a binary right fold expression.
11881 
11882    Do ths by building a single (non-empty) vector of arguments and
11883    building the expression from those elements. */
11884 
11885 static tree
tsubst_binary_right_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)11886 tsubst_binary_right_fold (tree t, tree args, tsubst_flags_t complain,
11887                          tree in_decl)
11888 {
11889   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
11890   if (pack == error_mark_node)
11891     return error_mark_node;
11892   tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
11893   if (init == error_mark_node)
11894     return error_mark_node;
11895 
11896   if (PACK_EXPANSION_P (pack))
11897     {
11898       tree r = copy_node (t);
11899       FOLD_EXPR_PACK (r) = pack;
11900       FOLD_EXPR_INIT (r) = init;
11901       return r;
11902     }
11903 
11904   int n = TREE_VEC_LENGTH (pack);
11905   tree vec = make_tree_vec (n + 1);
11906   for (int i = 0; i < n; ++i)
11907     TREE_VEC_ELT (vec, i) = TREE_VEC_ELT (pack, i);
11908   TREE_VEC_ELT (vec, n) = init;
11909 
11910   return expand_right_fold (t, vec, complain);
11911 }
11912 
11913 /* Walk through the pattern of a pack expansion, adding everything in
11914    local_specializations to a list.  */
11915 
11916 struct el_data
11917 {
11918   hash_set<tree> internal;
11919   tree extra;
11920   tsubst_flags_t complain;
11921 
el_datael_data11922   el_data (tsubst_flags_t c)
11923     : extra (NULL_TREE), complain (c) {}
11924 };
11925 static tree
extract_locals_r(tree * tp,int *,void * data_)11926 extract_locals_r (tree *tp, int */*walk_subtrees*/, void *data_)
11927 {
11928   el_data &data = *reinterpret_cast<el_data*>(data_);
11929   tree *extra = &data.extra;
11930   tsubst_flags_t complain = data.complain;
11931 
11932   if (TYPE_P (*tp) && typedef_variant_p (*tp))
11933     /* Remember local typedefs (85214).  */
11934     tp = &TYPE_NAME (*tp);
11935 
11936   if (TREE_CODE (*tp) == DECL_EXPR)
11937     data.internal.add (DECL_EXPR_DECL (*tp));
11938   else if (tree spec = retrieve_local_specialization (*tp))
11939     {
11940       if (data.internal.contains (*tp))
11941 	/* Don't mess with variables declared within the pattern.  */
11942 	return NULL_TREE;
11943       if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
11944 	{
11945 	  /* Maybe pull out the PARM_DECL for a partial instantiation.  */
11946 	  tree args = ARGUMENT_PACK_ARGS (spec);
11947 	  if (TREE_VEC_LENGTH (args) == 1)
11948 	    {
11949 	      tree elt = TREE_VEC_ELT (args, 0);
11950 	      if (PACK_EXPANSION_P (elt))
11951 		elt = PACK_EXPANSION_PATTERN (elt);
11952 	      if (DECL_PACK_P (elt))
11953 		spec = elt;
11954 	    }
11955 	  if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
11956 	    {
11957 	      /* Handle lambda capture here, since we aren't doing any
11958 		 substitution now, and so tsubst_copy won't call
11959 		 process_outer_var_ref.  */
11960 	      tree args = ARGUMENT_PACK_ARGS (spec);
11961 	      int len = TREE_VEC_LENGTH (args);
11962 	      for (int i = 0; i < len; ++i)
11963 		{
11964 		  tree arg = TREE_VEC_ELT (args, i);
11965 		  tree carg = arg;
11966 		  if (outer_automatic_var_p (arg))
11967 		    carg = process_outer_var_ref (arg, complain);
11968 		  if (carg != arg)
11969 		    {
11970 		      /* Make a new NONTYPE_ARGUMENT_PACK of the capture
11971 			 proxies.  */
11972 		      if (i == 0)
11973 			{
11974 			  spec = copy_node (spec);
11975 			  args = copy_node (args);
11976 			  SET_ARGUMENT_PACK_ARGS (spec, args);
11977 			  register_local_specialization (spec, *tp);
11978 			}
11979 		      TREE_VEC_ELT (args, i) = carg;
11980 		    }
11981 		}
11982 	    }
11983 	}
11984       if (outer_automatic_var_p (spec))
11985 	spec = process_outer_var_ref (spec, complain);
11986       *extra = tree_cons (*tp, spec, *extra);
11987     }
11988   return NULL_TREE;
11989 }
11990 static tree
extract_local_specs(tree pattern,tsubst_flags_t complain)11991 extract_local_specs (tree pattern, tsubst_flags_t complain)
11992 {
11993   el_data data (complain);
11994   cp_walk_tree_without_duplicates (&pattern, extract_locals_r, &data);
11995   return data.extra;
11996 }
11997 
11998 /* Extract any uses of local_specializations from PATTERN and add them to ARGS
11999    for use in PACK_EXPANSION_EXTRA_ARGS.  */
12000 
12001 tree
build_extra_args(tree pattern,tree args,tsubst_flags_t complain)12002 build_extra_args (tree pattern, tree args, tsubst_flags_t complain)
12003 {
12004   tree extra = args;
12005   if (local_specializations)
12006     if (tree locals = extract_local_specs (pattern, complain))
12007       extra = tree_cons (NULL_TREE, extra, locals);
12008   return extra;
12009 }
12010 
12011 /* Apply any local specializations from PACK_EXPANSION_EXTRA_ARGS and add the
12012    normal template args to ARGS.  */
12013 
12014 tree
add_extra_args(tree extra,tree args)12015 add_extra_args (tree extra, tree args)
12016 {
12017   if (extra && TREE_CODE (extra) == TREE_LIST)
12018     {
12019       for (tree elt = TREE_CHAIN (extra); elt; elt = TREE_CHAIN (elt))
12020 	{
12021 	  /* The partial instantiation involved local declarations collected in
12022 	     extract_local_specs; map from the general template to our local
12023 	     context.  */
12024 	  tree gen = TREE_PURPOSE (elt);
12025 	  tree inst = TREE_VALUE (elt);
12026 	  if (DECL_P (inst))
12027 	    if (tree local = retrieve_local_specialization (inst))
12028 	      inst = local;
12029 	  /* else inst is already a full instantiation of the pack.  */
12030 	  register_local_specialization (inst, gen);
12031 	}
12032       gcc_assert (!TREE_PURPOSE (extra));
12033       extra = TREE_VALUE (extra);
12034     }
12035   return add_to_template_args (extra, args);
12036 }
12037 
12038 /* Substitute ARGS into T, which is an pack expansion
12039    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
12040    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
12041    (if only a partial substitution could be performed) or
12042    ERROR_MARK_NODE if there was an error.  */
12043 tree
tsubst_pack_expansion(tree t,tree args,tsubst_flags_t complain,tree in_decl)12044 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
12045 		       tree in_decl)
12046 {
12047   tree pattern;
12048   tree pack, packs = NULL_TREE;
12049   bool unsubstituted_packs = false;
12050   bool unsubstituted_fn_pack = false;
12051   int i, len = -1;
12052   tree result;
12053   hash_map<tree, tree> *saved_local_specializations = NULL;
12054   bool need_local_specializations = false;
12055   int levels;
12056 
12057   gcc_assert (PACK_EXPANSION_P (t));
12058   pattern = PACK_EXPANSION_PATTERN (t);
12059 
12060   /* Add in any args remembered from an earlier partial instantiation.  */
12061   args = add_extra_args (PACK_EXPANSION_EXTRA_ARGS (t), args);
12062 
12063   levels = TMPL_ARGS_DEPTH (args);
12064 
12065   /* Determine the argument packs that will instantiate the parameter
12066      packs used in the expansion expression. While we're at it,
12067      compute the number of arguments to be expanded and make sure it
12068      is consistent.  */
12069   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
12070        pack = TREE_CHAIN (pack))
12071     {
12072       tree parm_pack = TREE_VALUE (pack);
12073       tree arg_pack = NULL_TREE;
12074       tree orig_arg = NULL_TREE;
12075       int level = 0;
12076 
12077       if (TREE_CODE (parm_pack) == BASES)
12078 	{
12079 	  gcc_assert (parm_pack == pattern);
12080 	  if (BASES_DIRECT (parm_pack))
12081 	    return calculate_direct_bases (tsubst_expr (BASES_TYPE (parm_pack),
12082 							args, complain,
12083 							in_decl, false),
12084 					   complain);
12085 	  else
12086 	    return calculate_bases (tsubst_expr (BASES_TYPE (parm_pack),
12087 						 args, complain, in_decl,
12088 						 false), complain);
12089 	}
12090       else if (builtin_pack_call_p (parm_pack))
12091 	{
12092 	  /* ??? Support use in other patterns.  */
12093 	  gcc_assert (parm_pack == pattern);
12094 	  return expand_builtin_pack_call (parm_pack, args,
12095 					   complain, in_decl);
12096 	}
12097       else if (TREE_CODE (parm_pack) == PARM_DECL)
12098 	{
12099 	  /* We know we have correct local_specializations if this
12100 	     expansion is at function scope, or if we're dealing with a
12101 	     local parameter in a requires expression; for the latter,
12102 	     tsubst_requires_expr set it up appropriately.  */
12103 	  if (PACK_EXPANSION_LOCAL_P (t) || CONSTRAINT_VAR_P (parm_pack))
12104 	    arg_pack = retrieve_local_specialization (parm_pack);
12105 	  else
12106 	    /* We can't rely on local_specializations for a parameter
12107 	       name used later in a function declaration (such as in a
12108 	       late-specified return type).  Even if it exists, it might
12109 	       have the wrong value for a recursive call.  */
12110 	    need_local_specializations = true;
12111 
12112 	  if (!arg_pack)
12113 	    {
12114 	      /* This parameter pack was used in an unevaluated context.  Just
12115 		 make a dummy decl, since it's only used for its type.  */
12116 	      ++cp_unevaluated_operand;
12117 	      arg_pack = tsubst_decl (parm_pack, args, complain);
12118 	      --cp_unevaluated_operand;
12119 	      if (arg_pack && DECL_PACK_P (arg_pack))
12120 		/* Partial instantiation of the parm_pack, we can't build
12121 		   up an argument pack yet.  */
12122 		arg_pack = NULL_TREE;
12123 	      else
12124 		arg_pack = make_fnparm_pack (arg_pack);
12125 	    }
12126 	  else if (argument_pack_element_is_expansion_p (arg_pack, 0))
12127 	    /* This argument pack isn't fully instantiated yet.  We set this
12128 	       flag rather than clear arg_pack because we do want to do the
12129 	       optimization below, and we don't want to substitute directly
12130 	       into the pattern (as that would expose a NONTYPE_ARGUMENT_PACK
12131 	       where it isn't expected).  */
12132 	    unsubstituted_fn_pack = true;
12133 	}
12134       else if (is_normal_capture_proxy (parm_pack))
12135 	{
12136 	  arg_pack = retrieve_local_specialization (parm_pack);
12137 	  if (argument_pack_element_is_expansion_p (arg_pack, 0))
12138 	    unsubstituted_fn_pack = true;
12139 	}
12140       else
12141         {
12142 	  int idx;
12143           template_parm_level_and_index (parm_pack, &level, &idx);
12144 
12145           if (level <= levels)
12146             arg_pack = TMPL_ARG (args, level, idx);
12147         }
12148 
12149       orig_arg = arg_pack;
12150       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
12151 	arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
12152 
12153       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
12154 	/* This can only happen if we forget to expand an argument
12155 	   pack somewhere else. Just return an error, silently.  */
12156 	{
12157 	  result = make_tree_vec (1);
12158 	  TREE_VEC_ELT (result, 0) = error_mark_node;
12159 	  return result;
12160 	}
12161 
12162       if (arg_pack)
12163         {
12164           int my_len =
12165             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
12166 
12167 	  /* Don't bother trying to do a partial substitution with
12168 	     incomplete packs; we'll try again after deduction.  */
12169           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
12170             return t;
12171 
12172           if (len < 0)
12173 	    len = my_len;
12174           else if (len != my_len
12175 		   && !unsubstituted_fn_pack)
12176             {
12177 	      if (!(complain & tf_error))
12178 		/* Fail quietly.  */;
12179               else if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
12180                 error ("mismatched argument pack lengths while expanding %qT",
12181                        pattern);
12182               else
12183                 error ("mismatched argument pack lengths while expanding %qE",
12184                        pattern);
12185               return error_mark_node;
12186             }
12187 
12188           /* Keep track of the parameter packs and their corresponding
12189              argument packs.  */
12190           packs = tree_cons (parm_pack, arg_pack, packs);
12191           TREE_TYPE (packs) = orig_arg;
12192         }
12193       else
12194 	{
12195 	  /* We can't substitute for this parameter pack.  We use a flag as
12196 	     well as the missing_level counter because function parameter
12197 	     packs don't have a level.  */
12198 	  gcc_assert (processing_template_decl || is_auto (parm_pack));
12199 	  unsubstituted_packs = true;
12200 	}
12201     }
12202 
12203   /* If the expansion is just T..., return the matching argument pack, unless
12204      we need to call convert_from_reference on all the elements.  This is an
12205      important optimization; see c++/68422.  */
12206   if (!unsubstituted_packs
12207       && TREE_PURPOSE (packs) == pattern)
12208     {
12209       tree args = ARGUMENT_PACK_ARGS (TREE_VALUE (packs));
12210 
12211       /* If the argument pack is a single pack expansion, pull it out.  */
12212       if (TREE_VEC_LENGTH (args) == 1
12213 	  && pack_expansion_args_count (args))
12214 	return TREE_VEC_ELT (args, 0);
12215 
12216       /* Types need no adjustment, nor does sizeof..., and if we still have
12217 	 some pack expansion args we won't do anything yet.  */
12218       if (TREE_CODE (t) == TYPE_PACK_EXPANSION
12219 	  || PACK_EXPANSION_SIZEOF_P (t)
12220 	  || pack_expansion_args_count (args))
12221 	return args;
12222       /* Also optimize expression pack expansions if we can tell that the
12223 	 elements won't have reference type.  */
12224       tree type = TREE_TYPE (pattern);
12225       if (type && TREE_CODE (type) != REFERENCE_TYPE
12226 	  && !PACK_EXPANSION_P (type)
12227 	  && !WILDCARD_TYPE_P (type))
12228 	return args;
12229       /* Otherwise use the normal path so we get convert_from_reference.  */
12230     }
12231 
12232   /* We cannot expand this expansion expression, because we don't have
12233      all of the argument packs we need.  */
12234   if (use_pack_expansion_extra_args_p (packs, len, unsubstituted_packs))
12235     {
12236       /* We got some full packs, but we can't substitute them in until we
12237 	 have values for all the packs.  So remember these until then.  */
12238 
12239       t = make_pack_expansion (pattern, complain);
12240       PACK_EXPANSION_EXTRA_ARGS (t)
12241 	= build_extra_args (pattern, args, complain);
12242       return t;
12243     }
12244   else if (unsubstituted_packs)
12245     {
12246       /* There were no real arguments, we're just replacing a parameter
12247 	 pack with another version of itself. Substitute into the
12248 	 pattern and return a PACK_EXPANSION_*. The caller will need to
12249 	 deal with that.  */
12250       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
12251 	t = tsubst_expr (pattern, args, complain, in_decl,
12252 			 /*integral_constant_expression_p=*/false);
12253       else
12254 	t = tsubst (pattern, args, complain, in_decl);
12255       t = make_pack_expansion (t, complain);
12256       return t;
12257     }
12258 
12259   gcc_assert (len >= 0);
12260 
12261   if (need_local_specializations)
12262     {
12263       /* We're in a late-specified return type, so create our own local
12264 	 specializations map; the current map is either NULL or (in the
12265 	 case of recursive unification) might have bindings that we don't
12266 	 want to use or alter.  */
12267       saved_local_specializations = local_specializations;
12268       local_specializations = new hash_map<tree, tree>;
12269     }
12270 
12271   /* For each argument in each argument pack, substitute into the
12272      pattern.  */
12273   result = make_tree_vec (len);
12274   tree elem_args = copy_template_args (args);
12275   for (i = 0; i < len; ++i)
12276     {
12277       t = gen_elem_of_pack_expansion_instantiation (pattern, packs,
12278 						    i,
12279 						    elem_args, complain,
12280 						    in_decl);
12281       TREE_VEC_ELT (result, i) = t;
12282       if (t == error_mark_node)
12283 	{
12284 	  result = error_mark_node;
12285 	  break;
12286 	}
12287     }
12288 
12289   /* Update ARGS to restore the substitution from parameter packs to
12290      their argument packs.  */
12291   for (pack = packs; pack; pack = TREE_CHAIN (pack))
12292     {
12293       tree parm = TREE_PURPOSE (pack);
12294 
12295       if (TREE_CODE (parm) == PARM_DECL
12296 	  || VAR_P (parm)
12297 	  || TREE_CODE (parm) == FIELD_DECL)
12298         register_local_specialization (TREE_TYPE (pack), parm);
12299       else
12300         {
12301           int idx, level;
12302 
12303 	  if (TREE_VALUE (pack) == NULL_TREE)
12304 	    continue;
12305 
12306           template_parm_level_and_index (parm, &level, &idx);
12307 
12308           /* Update the corresponding argument.  */
12309           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
12310             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
12311               TREE_TYPE (pack);
12312           else
12313             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
12314         }
12315     }
12316 
12317   if (need_local_specializations)
12318     {
12319       delete local_specializations;
12320       local_specializations = saved_local_specializations;
12321     }
12322 
12323   /* If the dependent pack arguments were such that we end up with only a
12324      single pack expansion again, there's no need to keep it in a TREE_VEC.  */
12325   if (len == 1 && TREE_CODE (result) == TREE_VEC
12326       && PACK_EXPANSION_P (TREE_VEC_ELT (result, 0)))
12327     return TREE_VEC_ELT (result, 0);
12328 
12329   return result;
12330 }
12331 
12332 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
12333    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
12334    parameter packs; all parms generated from a function parameter pack will
12335    have the same DECL_PARM_INDEX.  */
12336 
12337 tree
get_pattern_parm(tree parm,tree tmpl)12338 get_pattern_parm (tree parm, tree tmpl)
12339 {
12340   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
12341   tree patparm;
12342 
12343   if (DECL_ARTIFICIAL (parm))
12344     {
12345       for (patparm = DECL_ARGUMENTS (pattern);
12346 	   patparm; patparm = DECL_CHAIN (patparm))
12347 	if (DECL_ARTIFICIAL (patparm)
12348 	    && DECL_NAME (parm) == DECL_NAME (patparm))
12349 	  break;
12350     }
12351   else
12352     {
12353       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
12354       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
12355       gcc_assert (DECL_PARM_INDEX (patparm)
12356 		  == DECL_PARM_INDEX (parm));
12357     }
12358 
12359   return patparm;
12360 }
12361 
12362 /* Make an argument pack out of the TREE_VEC VEC.  */
12363 
12364 static tree
make_argument_pack(tree vec)12365 make_argument_pack (tree vec)
12366 {
12367   tree pack;
12368   tree elt = TREE_VEC_ELT (vec, 0);
12369   if (TYPE_P (elt))
12370     pack = cxx_make_type (TYPE_ARGUMENT_PACK);
12371   else
12372     {
12373       pack = make_node (NONTYPE_ARGUMENT_PACK);
12374       TREE_CONSTANT (pack) = 1;
12375     }
12376   SET_ARGUMENT_PACK_ARGS (pack, vec);
12377   return pack;
12378 }
12379 
12380 /* Return an exact copy of template args T that can be modified
12381    independently.  */
12382 
12383 static tree
copy_template_args(tree t)12384 copy_template_args (tree t)
12385 {
12386   if (t == error_mark_node)
12387     return t;
12388 
12389   int len = TREE_VEC_LENGTH (t);
12390   tree new_vec = make_tree_vec (len);
12391 
12392   for (int i = 0; i < len; ++i)
12393     {
12394       tree elt = TREE_VEC_ELT (t, i);
12395       if (elt && TREE_CODE (elt) == TREE_VEC)
12396 	elt = copy_template_args (elt);
12397       TREE_VEC_ELT (new_vec, i) = elt;
12398     }
12399 
12400   NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_vec)
12401     = NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
12402 
12403   return new_vec;
12404 }
12405 
12406 /* Substitute ARGS into the vector or list of template arguments T.  */
12407 
12408 static tree
tsubst_template_args(tree t,tree args,tsubst_flags_t complain,tree in_decl)12409 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12410 {
12411   tree orig_t = t;
12412   int len, need_new = 0, i, expanded_len_adjust = 0, out;
12413   tree *elts;
12414 
12415   if (t == error_mark_node)
12416     return error_mark_node;
12417 
12418   len = TREE_VEC_LENGTH (t);
12419   elts = XALLOCAVEC (tree, len);
12420 
12421   for (i = 0; i < len; i++)
12422     {
12423       tree orig_arg = TREE_VEC_ELT (t, i);
12424       tree new_arg;
12425 
12426       if (TREE_CODE (orig_arg) == TREE_VEC)
12427 	new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
12428       else if (PACK_EXPANSION_P (orig_arg))
12429         {
12430           /* Substitute into an expansion expression.  */
12431           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
12432 
12433           if (TREE_CODE (new_arg) == TREE_VEC)
12434             /* Add to the expanded length adjustment the number of
12435                expanded arguments. We subtract one from this
12436                measurement, because the argument pack expression
12437                itself is already counted as 1 in
12438                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
12439                the argument pack is empty.  */
12440             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
12441         }
12442       else if (ARGUMENT_PACK_P (orig_arg))
12443         {
12444           /* Substitute into each of the arguments.  */
12445           new_arg = TYPE_P (orig_arg)
12446             ? cxx_make_type (TREE_CODE (orig_arg))
12447             : make_node (TREE_CODE (orig_arg));
12448 
12449 	  tree pack_args = tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
12450 						 args, complain, in_decl);
12451           if (pack_args == error_mark_node)
12452             new_arg = error_mark_node;
12453 	  else
12454 	    SET_ARGUMENT_PACK_ARGS (new_arg, pack_args);
12455 
12456           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK)
12457 	    TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
12458         }
12459       else
12460 	new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
12461 
12462       if (new_arg == error_mark_node)
12463 	return error_mark_node;
12464 
12465       elts[i] = new_arg;
12466       if (new_arg != orig_arg)
12467 	need_new = 1;
12468     }
12469 
12470   if (!need_new)
12471     return t;
12472 
12473   /* Make space for the expanded arguments coming from template
12474      argument packs.  */
12475   t = make_tree_vec (len + expanded_len_adjust);
12476   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
12477      arguments for a member template.
12478      In that case each TREE_VEC in ORIG_T represents a level of template
12479      arguments, and ORIG_T won't carry any non defaulted argument count.
12480      It will rather be the nested TREE_VECs that will carry one.
12481      In other words, ORIG_T carries a non defaulted argument count only
12482      if it doesn't contain any nested TREE_VEC.  */
12483   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
12484     {
12485       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
12486       count += expanded_len_adjust;
12487       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
12488     }
12489   for (i = 0, out = 0; i < len; i++)
12490     {
12491       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
12492            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
12493           && TREE_CODE (elts[i]) == TREE_VEC)
12494         {
12495           int idx;
12496 
12497           /* Now expand the template argument pack "in place".  */
12498           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
12499             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
12500         }
12501       else
12502         {
12503           TREE_VEC_ELT (t, out) = elts[i];
12504           out++;
12505         }
12506     }
12507 
12508   return t;
12509 }
12510 
12511 /* Substitute ARGS into one level PARMS of template parameters.  */
12512 
12513 static tree
tsubst_template_parms_level(tree parms,tree args,tsubst_flags_t complain)12514 tsubst_template_parms_level (tree parms, tree args, tsubst_flags_t complain)
12515 {
12516   if (parms == error_mark_node)
12517     return error_mark_node;
12518 
12519   tree new_vec = make_tree_vec (TREE_VEC_LENGTH (parms));
12520 
12521   for (int i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
12522     {
12523       tree tuple = TREE_VEC_ELT (parms, i);
12524 
12525       if (tuple == error_mark_node)
12526 	continue;
12527 
12528       TREE_VEC_ELT (new_vec, i) =
12529 	tsubst_template_parm (tuple, args, complain);
12530     }
12531 
12532   return new_vec;
12533 }
12534 
12535 /* Return the result of substituting ARGS into the template parameters
12536    given by PARMS.  If there are m levels of ARGS and m + n levels of
12537    PARMS, then the result will contain n levels of PARMS.  For
12538    example, if PARMS is `template <class T> template <class U>
12539    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
12540    result will be `template <int*, double, class V>'.  */
12541 
12542 static tree
tsubst_template_parms(tree parms,tree args,tsubst_flags_t complain)12543 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
12544 {
12545   tree r = NULL_TREE;
12546   tree* new_parms;
12547 
12548   /* When substituting into a template, we must set
12549      PROCESSING_TEMPLATE_DECL as the template parameters may be
12550      dependent if they are based on one-another, and the dependency
12551      predicates are short-circuit outside of templates.  */
12552   ++processing_template_decl;
12553 
12554   for (new_parms = &r;
12555        parms && TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
12556        new_parms = &(TREE_CHAIN (*new_parms)),
12557 	 parms = TREE_CHAIN (parms))
12558     {
12559       tree new_vec = tsubst_template_parms_level (TREE_VALUE (parms),
12560 						  args, complain);
12561       *new_parms =
12562 	tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
12563 			     - TMPL_ARGS_DEPTH (args)),
12564 		   new_vec, NULL_TREE);
12565     }
12566 
12567   --processing_template_decl;
12568 
12569   return r;
12570 }
12571 
12572 /* Return the result of substituting ARGS into one template parameter
12573    given by T. T Must be a TREE_LIST which TREE_VALUE is the template
12574    parameter and which TREE_PURPOSE is the default argument of the
12575    template parameter.  */
12576 
12577 static tree
tsubst_template_parm(tree t,tree args,tsubst_flags_t complain)12578 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
12579 {
12580   tree default_value, parm_decl;
12581 
12582   if (args == NULL_TREE
12583       || t == NULL_TREE
12584       || t == error_mark_node)
12585     return t;
12586 
12587   gcc_assert (TREE_CODE (t) == TREE_LIST);
12588 
12589   default_value = TREE_PURPOSE (t);
12590   parm_decl = TREE_VALUE (t);
12591 
12592   parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
12593   if (TREE_CODE (parm_decl) == PARM_DECL
12594       && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
12595     parm_decl = error_mark_node;
12596   default_value = tsubst_template_arg (default_value, args,
12597 				       complain, NULL_TREE);
12598 
12599   return build_tree_list (default_value, parm_decl);
12600 }
12601 
12602 /* Substitute the ARGS into the indicated aggregate (or enumeration)
12603    type T.  If T is not an aggregate or enumeration type, it is
12604    handled as if by tsubst.  IN_DECL is as for tsubst.  If
12605    ENTERING_SCOPE is nonzero, T is the context for a template which
12606    we are presently tsubst'ing.  Return the substituted value.  */
12607 
12608 static tree
tsubst_aggr_type(tree t,tree args,tsubst_flags_t complain,tree in_decl,int entering_scope)12609 tsubst_aggr_type (tree t,
12610 		  tree args,
12611 		  tsubst_flags_t complain,
12612 		  tree in_decl,
12613 		  int entering_scope)
12614 {
12615   if (t == NULL_TREE)
12616     return NULL_TREE;
12617 
12618   switch (TREE_CODE (t))
12619     {
12620     case RECORD_TYPE:
12621       if (TYPE_PTRMEMFUNC_P (t))
12622 	return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
12623 
12624       /* Fall through.  */
12625     case ENUMERAL_TYPE:
12626     case UNION_TYPE:
12627       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
12628 	{
12629 	  tree argvec;
12630 	  tree context;
12631 	  tree r;
12632 	  int saved_unevaluated_operand;
12633 	  int saved_inhibit_evaluation_warnings;
12634 
12635 	  /* In "sizeof(X<I>)" we need to evaluate "I".  */
12636 	  saved_unevaluated_operand = cp_unevaluated_operand;
12637 	  cp_unevaluated_operand = 0;
12638 	  saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
12639 	  c_inhibit_evaluation_warnings = 0;
12640 
12641 	  /* First, determine the context for the type we are looking
12642 	     up.  */
12643 	  context = TYPE_CONTEXT (t);
12644 	  if (context && TYPE_P (context))
12645 	    {
12646 	      context = tsubst_aggr_type (context, args, complain,
12647 					  in_decl, /*entering_scope=*/1);
12648 	      /* If context is a nested class inside a class template,
12649 	         it may still need to be instantiated (c++/33959).  */
12650 	      context = complete_type (context);
12651 	    }
12652 
12653 	  /* Then, figure out what arguments are appropriate for the
12654 	     type we are trying to find.  For example, given:
12655 
12656 	       template <class T> struct S;
12657 	       template <class T, class U> void f(T, U) { S<U> su; }
12658 
12659 	     and supposing that we are instantiating f<int, double>,
12660 	     then our ARGS will be {int, double}, but, when looking up
12661 	     S we only want {double}.  */
12662 	  argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
12663 					 complain, in_decl);
12664 	  if (argvec == error_mark_node)
12665 	    r = error_mark_node;
12666 	  else
12667 	    {
12668 	      r = lookup_template_class (t, argvec, in_decl, context,
12669 					 entering_scope, complain);
12670 	      r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
12671 	    }
12672 
12673 	  cp_unevaluated_operand = saved_unevaluated_operand;
12674 	  c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
12675 
12676 	  return r;
12677 	}
12678       else
12679 	/* This is not a template type, so there's nothing to do.  */
12680 	return t;
12681 
12682     default:
12683       return tsubst (t, args, complain, in_decl);
12684     }
12685 }
12686 
12687 static GTY((cache)) tree_cache_map *defarg_inst;
12688 
12689 /* Substitute into the default argument ARG (a default argument for
12690    FN), which has the indicated TYPE.  */
12691 
12692 tree
tsubst_default_argument(tree fn,int parmnum,tree type,tree arg,tsubst_flags_t complain)12693 tsubst_default_argument (tree fn, int parmnum, tree type, tree arg,
12694 			 tsubst_flags_t complain)
12695 {
12696   tree saved_class_ptr = NULL_TREE;
12697   tree saved_class_ref = NULL_TREE;
12698   int errs = errorcount + sorrycount;
12699 
12700   /* This can happen in invalid code.  */
12701   if (TREE_CODE (arg) == DEFAULT_ARG)
12702     return arg;
12703 
12704   tree parm = FUNCTION_FIRST_USER_PARM (fn);
12705   parm = chain_index (parmnum, parm);
12706   tree parmtype = TREE_TYPE (parm);
12707   if (DECL_BY_REFERENCE (parm))
12708     parmtype = TREE_TYPE (parmtype);
12709   if (parmtype == error_mark_node)
12710     return error_mark_node;
12711 
12712   gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, parmtype));
12713 
12714   tree *slot;
12715   if (defarg_inst && (slot = defarg_inst->get (parm)))
12716     return *slot;
12717 
12718   /* This default argument came from a template.  Instantiate the
12719      default argument here, not in tsubst.  In the case of
12720      something like:
12721 
12722        template <class T>
12723        struct S {
12724 	 static T t();
12725 	 void f(T = t());
12726        };
12727 
12728      we must be careful to do name lookup in the scope of S<T>,
12729      rather than in the current class.  */
12730   push_access_scope (fn);
12731   /* The "this" pointer is not valid in a default argument.  */
12732   if (cfun)
12733     {
12734       saved_class_ptr = current_class_ptr;
12735       cp_function_chain->x_current_class_ptr = NULL_TREE;
12736       saved_class_ref = current_class_ref;
12737       cp_function_chain->x_current_class_ref = NULL_TREE;
12738     }
12739 
12740   start_lambda_scope (parm);
12741 
12742   push_deferring_access_checks(dk_no_deferred);
12743   /* The default argument expression may cause implicitly defined
12744      member functions to be synthesized, which will result in garbage
12745      collection.  We must treat this situation as if we were within
12746      the body of function so as to avoid collecting live data on the
12747      stack.  */
12748   ++function_depth;
12749   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
12750 		     complain, NULL_TREE,
12751 		     /*integral_constant_expression_p=*/false);
12752   --function_depth;
12753   pop_deferring_access_checks();
12754 
12755   finish_lambda_scope ();
12756 
12757   /* Restore the "this" pointer.  */
12758   if (cfun)
12759     {
12760       cp_function_chain->x_current_class_ptr = saved_class_ptr;
12761       cp_function_chain->x_current_class_ref = saved_class_ref;
12762     }
12763 
12764   if (errorcount+sorrycount > errs
12765       && (complain & tf_warning_or_error))
12766     inform (input_location,
12767 	    "  when instantiating default argument for call to %qD", fn);
12768 
12769   /* Make sure the default argument is reasonable.  */
12770   arg = check_default_argument (type, arg, complain);
12771 
12772   pop_access_scope (fn);
12773 
12774   if (arg != error_mark_node && !cp_unevaluated_operand)
12775     {
12776       if (!defarg_inst)
12777 	defarg_inst = tree_cache_map::create_ggc (37);
12778       defarg_inst->put (parm, arg);
12779     }
12780 
12781   return arg;
12782 }
12783 
12784 /* Substitute into all the default arguments for FN.  */
12785 
12786 static void
tsubst_default_arguments(tree fn,tsubst_flags_t complain)12787 tsubst_default_arguments (tree fn, tsubst_flags_t complain)
12788 {
12789   tree arg;
12790   tree tmpl_args;
12791 
12792   tmpl_args = DECL_TI_ARGS (fn);
12793 
12794   /* If this function is not yet instantiated, we certainly don't need
12795      its default arguments.  */
12796   if (uses_template_parms (tmpl_args))
12797     return;
12798   /* Don't do this again for clones.  */
12799   if (DECL_CLONED_FUNCTION_P (fn))
12800     return;
12801 
12802   int i = 0;
12803   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
12804        arg;
12805        arg = TREE_CHAIN (arg), ++i)
12806     if (TREE_PURPOSE (arg))
12807       TREE_PURPOSE (arg) = tsubst_default_argument (fn, i,
12808 						    TREE_VALUE (arg),
12809 						    TREE_PURPOSE (arg),
12810 						    complain);
12811 }
12812 
12813 /* Subroutine of tsubst_decl for the case when T is a FUNCTION_DECL.  */
12814 
12815 static tree
tsubst_function_decl(tree t,tree args,tsubst_flags_t complain,tree lambda_fntype)12816 tsubst_function_decl (tree t, tree args, tsubst_flags_t complain,
12817 		      tree lambda_fntype)
12818 {
12819   tree gen_tmpl, argvec;
12820   hashval_t hash = 0;
12821   tree in_decl = t;
12822 
12823   /* Nobody should be tsubst'ing into non-template functions.  */
12824   gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
12825 
12826   if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
12827     {
12828       /* If T is not dependent, just return it.  */
12829       if (!uses_template_parms (DECL_TI_ARGS (t)))
12830 	return t;
12831 
12832       /* Calculate the most general template of which R is a
12833 	 specialization.  */
12834       gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
12835 
12836       /* We're substituting a lambda function under tsubst_lambda_expr but not
12837 	 directly from it; find the matching function we're already inside.
12838 	 But don't do this if T is a generic lambda with a single level of
12839 	 template parms, as in that case we're doing a normal instantiation. */
12840       if (LAMBDA_FUNCTION_P (t) && !lambda_fntype
12841 	  && (!generic_lambda_fn_p (t)
12842 	      || TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)) > 1))
12843 	return enclosing_instantiation_of (t);
12844 
12845       /* Calculate the complete set of arguments used to
12846 	 specialize R.  */
12847       argvec = tsubst_template_args (DECL_TI_ARGS
12848 				     (DECL_TEMPLATE_RESULT
12849 				      (DECL_TI_TEMPLATE (t))),
12850 				     args, complain, in_decl);
12851       if (argvec == error_mark_node)
12852 	return error_mark_node;
12853 
12854       /* Check to see if we already have this specialization.  */
12855       if (!lambda_fntype)
12856 	{
12857 	  hash = hash_tmpl_and_args (gen_tmpl, argvec);
12858 	  if (tree spec = retrieve_specialization (gen_tmpl, argvec, hash))
12859 	    return spec;
12860 	}
12861 
12862       /* We can see more levels of arguments than parameters if
12863 	 there was a specialization of a member template, like
12864 	 this:
12865 
12866 	 template <class T> struct S { template <class U> void f(); }
12867 	 template <> template <class U> void S<int>::f(U);
12868 
12869 	 Here, we'll be substituting into the specialization,
12870 	 because that's where we can find the code we actually
12871 	 want to generate, but we'll have enough arguments for
12872 	 the most general template.
12873 
12874 	 We also deal with the peculiar case:
12875 
12876 	 template <class T> struct S {
12877 	   template <class U> friend void f();
12878 	 };
12879 	 template <class U> void f() {}
12880 	 template S<int>;
12881 	 template void f<double>();
12882 
12883 	 Here, the ARGS for the instantiation of will be {int,
12884 	 double}.  But, we only need as many ARGS as there are
12885 	 levels of template parameters in CODE_PATTERN.  We are
12886 	 careful not to get fooled into reducing the ARGS in
12887 	 situations like:
12888 
12889 	 template <class T> struct S { template <class U> void f(U); }
12890 	 template <class T> template <> void S<T>::f(int) {}
12891 
12892 	 which we can spot because the pattern will be a
12893 	 specialization in this case.  */
12894       int args_depth = TMPL_ARGS_DEPTH (args);
12895       int parms_depth =
12896 	TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
12897 
12898       if (args_depth > parms_depth && !DECL_TEMPLATE_SPECIALIZATION (t))
12899 	args = get_innermost_template_args (args, parms_depth);
12900     }
12901   else
12902     {
12903       /* This special case arises when we have something like this:
12904 
12905 	 template <class T> struct S {
12906 	 friend void f<int>(int, double);
12907 	 };
12908 
12909 	 Here, the DECL_TI_TEMPLATE for the friend declaration
12910 	 will be an IDENTIFIER_NODE.  We are being called from
12911 	 tsubst_friend_function, and we want only to create a
12912 	 new decl (R) with appropriate types so that we can call
12913 	 determine_specialization.  */
12914       gen_tmpl = NULL_TREE;
12915       argvec = NULL_TREE;
12916     }
12917 
12918   tree closure = (lambda_fntype ? TYPE_METHOD_BASETYPE (lambda_fntype)
12919 		  : NULL_TREE);
12920   tree ctx = closure ? closure : DECL_CONTEXT (t);
12921   bool member = ctx && TYPE_P (ctx);
12922 
12923   if (member && !closure)
12924     ctx = tsubst_aggr_type (ctx, args,
12925 			    complain, t, /*entering_scope=*/1);
12926 
12927   tree type = (lambda_fntype ? lambda_fntype
12928 	       : tsubst (TREE_TYPE (t), args,
12929 			 complain | tf_fndecl_type, in_decl));
12930   if (type == error_mark_node)
12931     return error_mark_node;
12932 
12933   /* If we hit excessive deduction depth, the type is bogus even if
12934      it isn't error_mark_node, so don't build a decl.  */
12935   if (excessive_deduction_depth)
12936     return error_mark_node;
12937 
12938   /* We do NOT check for matching decls pushed separately at this
12939      point, as they may not represent instantiations of this
12940      template, and in any case are considered separate under the
12941      discrete model.  */
12942   tree r = copy_decl (t);
12943   DECL_USE_TEMPLATE (r) = 0;
12944   TREE_TYPE (r) = type;
12945   /* Clear out the mangled name and RTL for the instantiation.  */
12946   SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
12947   SET_DECL_RTL (r, NULL);
12948   /* Leave DECL_INITIAL set on deleted instantiations.  */
12949   if (!DECL_DELETED_FN (r))
12950     DECL_INITIAL (r) = NULL_TREE;
12951   DECL_CONTEXT (r) = ctx;
12952 
12953   /* OpenMP UDRs have the only argument a reference to the declared
12954      type.  We want to diagnose if the declared type is a reference,
12955      which is invalid, but as references to references are usually
12956      quietly merged, diagnose it here.  */
12957   if (DECL_OMP_DECLARE_REDUCTION_P (t))
12958     {
12959       tree argtype
12960 	= TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (t))));
12961       argtype = tsubst (argtype, args, complain, in_decl);
12962       if (TREE_CODE (argtype) == REFERENCE_TYPE)
12963 	error_at (DECL_SOURCE_LOCATION (t),
12964 		  "reference type %qT in "
12965 		  "%<#pragma omp declare reduction%>", argtype);
12966       if (strchr (IDENTIFIER_POINTER (DECL_NAME (t)), '~') == NULL)
12967 	DECL_NAME (r) = omp_reduction_id (ERROR_MARK, DECL_NAME (t),
12968 					  argtype);
12969     }
12970 
12971   if (member && DECL_CONV_FN_P (r))
12972     /* Type-conversion operator.  Reconstruct the name, in
12973        case it's the name of one of the template's parameters.  */
12974     DECL_NAME (r) = make_conv_op_name (TREE_TYPE (type));
12975 
12976   tree parms = DECL_ARGUMENTS (t);
12977   if (closure)
12978     parms = DECL_CHAIN (parms);
12979   parms = tsubst (parms, args, complain, t);
12980   for (tree parm = parms; parm; parm = DECL_CHAIN (parm))
12981     DECL_CONTEXT (parm) = r;
12982   if (closure)
12983     {
12984       tree tparm = build_this_parm (r, closure, type_memfn_quals (type));
12985       DECL_CHAIN (tparm) = parms;
12986       parms = tparm;
12987     }
12988   DECL_ARGUMENTS (r) = parms;
12989   DECL_RESULT (r) = NULL_TREE;
12990 
12991   TREE_STATIC (r) = 0;
12992   TREE_PUBLIC (r) = TREE_PUBLIC (t);
12993   DECL_EXTERNAL (r) = 1;
12994   /* If this is an instantiation of a function with internal
12995      linkage, we already know what object file linkage will be
12996      assigned to the instantiation.  */
12997   DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
12998   DECL_DEFER_OUTPUT (r) = 0;
12999   DECL_CHAIN (r) = NULL_TREE;
13000   DECL_PENDING_INLINE_INFO (r) = 0;
13001   DECL_PENDING_INLINE_P (r) = 0;
13002   DECL_SAVED_TREE (r) = NULL_TREE;
13003   DECL_STRUCT_FUNCTION (r) = NULL;
13004   TREE_USED (r) = 0;
13005   /* We'll re-clone as appropriate in instantiate_template.  */
13006   DECL_CLONED_FUNCTION (r) = NULL_TREE;
13007 
13008   /* If we aren't complaining now, return on error before we register
13009      the specialization so that we'll complain eventually.  */
13010   if ((complain & tf_error) == 0
13011       && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
13012       && !grok_op_properties (r, /*complain=*/false))
13013     return error_mark_node;
13014 
13015   /* When instantiating a constrained member, substitute
13016      into the constraints to create a new constraint.  */
13017   if (tree ci = get_constraints (t))
13018     if (member)
13019       {
13020 	ci = tsubst_constraint_info (ci, argvec, complain, NULL_TREE);
13021 	set_constraints (r, ci);
13022       }
13023 
13024   if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
13025     SET_DECL_FRIEND_CONTEXT (r,
13026 			     tsubst (DECL_FRIEND_CONTEXT (t),
13027 				     args, complain, in_decl));
13028 
13029   /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
13030      this in the special friend case mentioned above where
13031      GEN_TMPL is NULL.  */
13032   if (gen_tmpl && !closure)
13033     {
13034       DECL_TEMPLATE_INFO (r)
13035 	= build_template_info (gen_tmpl, argvec);
13036       SET_DECL_IMPLICIT_INSTANTIATION (r);
13037 
13038       tree new_r
13039 	= register_specialization (r, gen_tmpl, argvec, false, hash);
13040       if (new_r != r)
13041 	/* We instantiated this while substituting into
13042 	   the type earlier (template/friend54.C).  */
13043 	return new_r;
13044 
13045       /* We're not supposed to instantiate default arguments
13046 	 until they are called, for a template.  But, for a
13047 	 declaration like:
13048 
13049 	 template <class T> void f ()
13050 	 { extern void g(int i = T()); }
13051 
13052 	 we should do the substitution when the template is
13053 	 instantiated.  We handle the member function case in
13054 	 instantiate_class_template since the default arguments
13055 	 might refer to other members of the class.  */
13056       if (!member
13057 	  && !PRIMARY_TEMPLATE_P (gen_tmpl)
13058 	  && !uses_template_parms (argvec))
13059 	tsubst_default_arguments (r, complain);
13060     }
13061   else
13062     DECL_TEMPLATE_INFO (r) = NULL_TREE;
13063 
13064   /* Copy the list of befriending classes.  */
13065   for (tree *friends = &DECL_BEFRIENDING_CLASSES (r);
13066        *friends;
13067        friends = &TREE_CHAIN (*friends))
13068     {
13069       *friends = copy_node (*friends);
13070       TREE_VALUE (*friends)
13071 	= tsubst (TREE_VALUE (*friends), args, complain, in_decl);
13072     }
13073 
13074   if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
13075     {
13076       maybe_retrofit_in_chrg (r);
13077       if (DECL_CONSTRUCTOR_P (r) && !grok_ctor_properties (ctx, r))
13078 	return error_mark_node;
13079       /* If this is an instantiation of a member template, clone it.
13080 	 If it isn't, that'll be handled by
13081 	 clone_constructors_and_destructors.  */
13082       if (PRIMARY_TEMPLATE_P (gen_tmpl))
13083 	clone_function_decl (r, /*update_methods=*/false);
13084     }
13085   else if ((complain & tf_error) != 0
13086 	   && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
13087 	   && !grok_op_properties (r, /*complain=*/true))
13088     return error_mark_node;
13089 
13090   /* Possibly limit visibility based on template args.  */
13091   DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
13092   if (DECL_VISIBILITY_SPECIFIED (t))
13093     {
13094       DECL_VISIBILITY_SPECIFIED (r) = 0;
13095       DECL_ATTRIBUTES (r)
13096 	= remove_attribute ("visibility", DECL_ATTRIBUTES (r));
13097     }
13098   determine_visibility (r);
13099   if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
13100       && !processing_template_decl)
13101     defaulted_late_check (r);
13102 
13103   apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
13104 				  args, complain, in_decl);
13105   return r;
13106 }
13107 
13108 /* Subroutine of tsubst_decl for the case when T is a TEMPLATE_DECL.  */
13109 
13110 static tree
tsubst_template_decl(tree t,tree args,tsubst_flags_t complain,tree lambda_fntype)13111 tsubst_template_decl (tree t, tree args, tsubst_flags_t complain,
13112 		      tree lambda_fntype)
13113 {
13114   /* We can get here when processing a member function template,
13115      member class template, or template template parameter.  */
13116   tree decl = DECL_TEMPLATE_RESULT (t);
13117   tree in_decl = t;
13118   tree spec;
13119   tree tmpl_args;
13120   tree full_args;
13121   tree r;
13122   hashval_t hash = 0;
13123 
13124   if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
13125     {
13126       /* Template template parameter is treated here.  */
13127       tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13128       if (new_type == error_mark_node)
13129 	r = error_mark_node;
13130       /* If we get a real template back, return it.  This can happen in
13131 	 the context of most_specialized_partial_spec.  */
13132       else if (TREE_CODE (new_type) == TEMPLATE_DECL)
13133 	r = new_type;
13134       else
13135 	/* The new TEMPLATE_DECL was built in
13136 	   reduce_template_parm_level.  */
13137 	r = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (new_type);
13138       return r;
13139     }
13140 
13141   if (!lambda_fntype)
13142     {
13143       /* We might already have an instance of this template.
13144 	 The ARGS are for the surrounding class type, so the
13145 	 full args contain the tsubst'd args for the context,
13146 	 plus the innermost args from the template decl.  */
13147       tmpl_args = DECL_CLASS_TEMPLATE_P (t)
13148 	? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
13149 	: DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
13150       /* Because this is a template, the arguments will still be
13151 	 dependent, even after substitution.  If
13152 	 PROCESSING_TEMPLATE_DECL is not set, the dependency
13153 	 predicates will short-circuit.  */
13154       ++processing_template_decl;
13155       full_args = tsubst_template_args (tmpl_args, args,
13156 					complain, in_decl);
13157       --processing_template_decl;
13158       if (full_args == error_mark_node)
13159 	return error_mark_node;
13160 
13161       /* If this is a default template template argument,
13162 	 tsubst might not have changed anything.  */
13163       if (full_args == tmpl_args)
13164 	return t;
13165 
13166       hash = hash_tmpl_and_args (t, full_args);
13167       spec = retrieve_specialization (t, full_args, hash);
13168       if (spec != NULL_TREE)
13169 	return spec;
13170     }
13171 
13172   /* Make a new template decl.  It will be similar to the
13173      original, but will record the current template arguments.
13174      We also create a new function declaration, which is just
13175      like the old one, but points to this new template, rather
13176      than the old one.  */
13177   r = copy_decl (t);
13178   gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
13179   DECL_CHAIN (r) = NULL_TREE;
13180 
13181   // Build new template info linking to the original template decl.
13182   if (!lambda_fntype)
13183     {
13184       DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
13185       SET_DECL_IMPLICIT_INSTANTIATION (r);
13186     }
13187   else
13188     DECL_TEMPLATE_INFO (r) = NULL_TREE;
13189 
13190   /* The template parameters for this new template are all the
13191      template parameters for the old template, except the
13192      outermost level of parameters.  */
13193   DECL_TEMPLATE_PARMS (r)
13194     = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
13195 			     complain);
13196 
13197   if (TREE_CODE (decl) == TYPE_DECL
13198       && !TYPE_DECL_ALIAS_P (decl))
13199     {
13200       tree new_type;
13201       ++processing_template_decl;
13202       new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13203       --processing_template_decl;
13204       if (new_type == error_mark_node)
13205 	return error_mark_node;
13206 
13207       TREE_TYPE (r) = new_type;
13208       /* For a partial specialization, we need to keep pointing to
13209 	 the primary template.  */
13210       if (!DECL_TEMPLATE_SPECIALIZATION (t))
13211 	CLASSTYPE_TI_TEMPLATE (new_type) = r;
13212       DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
13213       DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
13214       DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
13215     }
13216   else
13217     {
13218       tree new_decl;
13219       ++processing_template_decl;
13220       if (TREE_CODE (decl) == FUNCTION_DECL)
13221 	new_decl = tsubst_function_decl (decl, args, complain, lambda_fntype);
13222       else
13223 	new_decl = tsubst (decl, args, complain, in_decl);
13224       --processing_template_decl;
13225       if (new_decl == error_mark_node)
13226 	return error_mark_node;
13227 
13228       DECL_TEMPLATE_RESULT (r) = new_decl;
13229       TREE_TYPE (r) = TREE_TYPE (new_decl);
13230       DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
13231       if (lambda_fntype)
13232 	{
13233 	  tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (r));
13234 	  DECL_TEMPLATE_INFO (new_decl) = build_template_info (r, args);
13235 	}
13236       else
13237 	{
13238 	  DECL_TI_TEMPLATE (new_decl) = r;
13239 	  DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
13240 	}
13241     }
13242 
13243   DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
13244   DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
13245 
13246   if (PRIMARY_TEMPLATE_P (t))
13247     DECL_PRIMARY_TEMPLATE (r) = r;
13248 
13249   if (TREE_CODE (decl) != TYPE_DECL && !VAR_P (decl)
13250       && !lambda_fntype)
13251     /* Record this non-type partial instantiation.  */
13252     register_specialization (r, t,
13253 			     DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
13254 			     false, hash);
13255 
13256   return r;
13257 }
13258 
13259 /* True if FN is the op() for a lambda in an uninstantiated template.  */
13260 
13261 bool
lambda_fn_in_template_p(tree fn)13262 lambda_fn_in_template_p (tree fn)
13263 {
13264   if (!fn || !LAMBDA_FUNCTION_P (fn))
13265     return false;
13266   tree closure = DECL_CONTEXT (fn);
13267   return CLASSTYPE_TEMPLATE_INFO (closure) != NULL_TREE;
13268 }
13269 
13270 /* We're instantiating a variable from template function TCTX.  Return the
13271    corresponding current enclosing scope.  This gets complicated because lambda
13272    functions in templates are regenerated rather than instantiated, but generic
13273    lambda functions are subsequently instantiated.  */
13274 
13275 static tree
enclosing_instantiation_of(tree otctx)13276 enclosing_instantiation_of (tree otctx)
13277 {
13278   tree tctx = otctx;
13279   tree fn = current_function_decl;
13280   int lambda_count = 0;
13281 
13282   for (; tctx && lambda_fn_in_template_p (tctx);
13283        tctx = decl_function_context (tctx))
13284     ++lambda_count;
13285   for (; fn; fn = decl_function_context (fn))
13286     {
13287       tree ofn = fn;
13288       int flambda_count = 0;
13289       for (; flambda_count < lambda_count && fn && LAMBDA_FUNCTION_P (fn);
13290 	   fn = decl_function_context (fn))
13291 	++flambda_count;
13292       if ((fn && DECL_TEMPLATE_INFO (fn))
13293 	  ? most_general_template (fn) != most_general_template (tctx)
13294 	  : fn != tctx)
13295 	continue;
13296       gcc_assert (DECL_NAME (ofn) == DECL_NAME (otctx)
13297 		  || DECL_CONV_FN_P (ofn));
13298       return ofn;
13299     }
13300   gcc_unreachable ();
13301 }
13302 
13303 /* Substitute the ARGS into the T, which is a _DECL.  Return the
13304    result of the substitution.  Issue error and warning messages under
13305    control of COMPLAIN.  */
13306 
13307 static tree
tsubst_decl(tree t,tree args,tsubst_flags_t complain)13308 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
13309 {
13310 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
13311   location_t saved_loc;
13312   tree r = NULL_TREE;
13313   tree in_decl = t;
13314   hashval_t hash = 0;
13315 
13316   /* Set the filename and linenumber to improve error-reporting.  */
13317   saved_loc = input_location;
13318   input_location = DECL_SOURCE_LOCATION (t);
13319 
13320   switch (TREE_CODE (t))
13321     {
13322     case TEMPLATE_DECL:
13323       r = tsubst_template_decl (t, args, complain, /*lambda*/NULL_TREE);
13324       break;
13325 
13326     case FUNCTION_DECL:
13327       r = tsubst_function_decl (t, args, complain, /*lambda*/NULL_TREE);
13328       break;
13329 
13330     case PARM_DECL:
13331       {
13332 	tree type = NULL_TREE;
13333         int i, len = 1;
13334         tree expanded_types = NULL_TREE;
13335         tree prev_r = NULL_TREE;
13336         tree first_r = NULL_TREE;
13337 
13338         if (DECL_PACK_P (t))
13339           {
13340             /* If there is a local specialization that isn't a
13341                parameter pack, it means that we're doing a "simple"
13342                substitution from inside tsubst_pack_expansion. Just
13343                return the local specialization (which will be a single
13344                parm).  */
13345             tree spec = retrieve_local_specialization (t);
13346             if (spec
13347                 && TREE_CODE (spec) == PARM_DECL
13348                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
13349               RETURN (spec);
13350 
13351             /* Expand the TYPE_PACK_EXPANSION that provides the types for
13352                the parameters in this function parameter pack.  */
13353             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
13354 						    complain, in_decl);
13355             if (TREE_CODE (expanded_types) == TREE_VEC)
13356               {
13357                 len = TREE_VEC_LENGTH (expanded_types);
13358 
13359                 /* Zero-length parameter packs are boring. Just substitute
13360                    into the chain.  */
13361                 if (len == 0)
13362                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
13363 				  TREE_CHAIN (t)));
13364               }
13365             else
13366               {
13367                 /* All we did was update the type. Make a note of that.  */
13368                 type = expanded_types;
13369                 expanded_types = NULL_TREE;
13370               }
13371           }
13372 
13373         /* Loop through all of the parameters we'll build. When T is
13374            a function parameter pack, LEN is the number of expanded
13375            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
13376         r = NULL_TREE;
13377         for (i = 0; i < len; ++i)
13378           {
13379             prev_r = r;
13380             r = copy_node (t);
13381             if (DECL_TEMPLATE_PARM_P (t))
13382               SET_DECL_TEMPLATE_PARM_P (r);
13383 
13384             if (expanded_types)
13385               /* We're on the Ith parameter of the function parameter
13386                  pack.  */
13387               {
13388                 /* Get the Ith type.  */
13389                 type = TREE_VEC_ELT (expanded_types, i);
13390 
13391 		/* Rename the parameter to include the index.  */
13392 		DECL_NAME (r)
13393 		  = make_ith_pack_parameter_name (DECL_NAME (r), i);
13394               }
13395             else if (!type)
13396               /* We're dealing with a normal parameter.  */
13397               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13398 
13399             type = type_decays_to (type);
13400             TREE_TYPE (r) = type;
13401             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
13402 
13403             if (DECL_INITIAL (r))
13404               {
13405                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
13406                   DECL_INITIAL (r) = TREE_TYPE (r);
13407                 else
13408                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
13409                                              complain, in_decl);
13410               }
13411 
13412             DECL_CONTEXT (r) = NULL_TREE;
13413 
13414             if (!DECL_TEMPLATE_PARM_P (r))
13415               DECL_ARG_TYPE (r) = type_passed_as (type);
13416 
13417 	    apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
13418 					    args, complain, in_decl);
13419 
13420             /* Keep track of the first new parameter we
13421                generate. That's what will be returned to the
13422                caller.  */
13423             if (!first_r)
13424               first_r = r;
13425 
13426             /* Build a proper chain of parameters when substituting
13427                into a function parameter pack.  */
13428             if (prev_r)
13429               DECL_CHAIN (prev_r) = r;
13430           }
13431 
13432 	/* If cp_unevaluated_operand is set, we're just looking for a
13433 	   single dummy parameter, so don't keep going.  */
13434 	if (DECL_CHAIN (t) && !cp_unevaluated_operand)
13435 	  DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
13436 				   complain, DECL_CHAIN (t));
13437 
13438         /* FIRST_R contains the start of the chain we've built.  */
13439         r = first_r;
13440       }
13441       break;
13442 
13443     case FIELD_DECL:
13444       {
13445 	tree type = NULL_TREE;
13446 	tree vec = NULL_TREE;
13447 	tree expanded_types = NULL_TREE;
13448 	int len = 1;
13449 
13450 	if (PACK_EXPANSION_P (TREE_TYPE (t)))
13451 	  {
13452 	    /* This field is a lambda capture pack.  Return a TREE_VEC of
13453 	       the expanded fields to instantiate_class_template_1.  */
13454             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
13455 						    complain, in_decl);
13456             if (TREE_CODE (expanded_types) == TREE_VEC)
13457               {
13458                 len = TREE_VEC_LENGTH (expanded_types);
13459 		vec = make_tree_vec (len);
13460               }
13461             else
13462               {
13463                 /* All we did was update the type. Make a note of that.  */
13464                 type = expanded_types;
13465                 expanded_types = NULL_TREE;
13466               }
13467 	  }
13468 
13469 	for (int i = 0; i < len; ++i)
13470 	  {
13471 	    r = copy_decl (t);
13472 	    if (expanded_types)
13473 	      {
13474 		type = TREE_VEC_ELT (expanded_types, i);
13475 		DECL_NAME (r)
13476 		  = make_ith_pack_parameter_name (DECL_NAME (r), i);
13477 	      }
13478             else if (!type)
13479               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13480 
13481 	    if (type == error_mark_node)
13482 	      RETURN (error_mark_node);
13483 	    TREE_TYPE (r) = type;
13484 	    cp_apply_type_quals_to_decl (cp_type_quals (type), r);
13485 
13486 	    if (DECL_C_BIT_FIELD (r))
13487 	      /* For bit-fields, DECL_BIT_FIELD_REPRESENTATIVE gives the
13488 		 number of bits.  */
13489 	      DECL_BIT_FIELD_REPRESENTATIVE (r)
13490 		= tsubst_expr (DECL_BIT_FIELD_REPRESENTATIVE (t), args,
13491 			       complain, in_decl,
13492 			       /*integral_constant_expression_p=*/true);
13493 	    if (DECL_INITIAL (t))
13494 	      {
13495 		/* Set up DECL_TEMPLATE_INFO so that we can get at the
13496 		   NSDMI in perform_member_init.  Still set DECL_INITIAL
13497 		   so that we know there is one.  */
13498 		DECL_INITIAL (r) = void_node;
13499 		gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
13500 		retrofit_lang_decl (r);
13501 		DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
13502 	      }
13503 	    /* We don't have to set DECL_CONTEXT here; it is set by
13504 	       finish_member_declaration.  */
13505 	    DECL_CHAIN (r) = NULL_TREE;
13506 
13507 	    apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
13508 					    args, complain, in_decl);
13509 
13510 	    if (vec)
13511 	      TREE_VEC_ELT (vec, i) = r;
13512 	  }
13513 
13514 	if (vec)
13515 	  r = vec;
13516       }
13517       break;
13518 
13519     case USING_DECL:
13520       /* We reach here only for member using decls.  We also need to check
13521 	 uses_template_parms because DECL_DEPENDENT_P is not set for a
13522 	 using-declaration that designates a member of the current
13523 	 instantiation (c++/53549).  */
13524       if (DECL_DEPENDENT_P (t)
13525 	  || uses_template_parms (USING_DECL_SCOPE (t)))
13526 	{
13527 	  tree scope = USING_DECL_SCOPE (t);
13528 	  tree name = tsubst_copy (DECL_NAME (t), args, complain, in_decl);
13529 	  if (PACK_EXPANSION_P (scope))
13530 	    {
13531 	      tree vec = tsubst_pack_expansion (scope, args, complain, in_decl);
13532 	      int len = TREE_VEC_LENGTH (vec);
13533 	      r = make_tree_vec (len);
13534 	      for (int i = 0; i < len; ++i)
13535 		{
13536 		  tree escope = TREE_VEC_ELT (vec, i);
13537 		  tree elt = do_class_using_decl (escope, name);
13538 		  if (!elt)
13539 		    {
13540 		      r = error_mark_node;
13541 		      break;
13542 		    }
13543 		  else
13544 		    {
13545 		      TREE_PROTECTED (elt) = TREE_PROTECTED (t);
13546 		      TREE_PRIVATE (elt) = TREE_PRIVATE (t);
13547 		    }
13548 		  TREE_VEC_ELT (r, i) = elt;
13549 		}
13550 	    }
13551 	  else
13552 	    {
13553 	      tree inst_scope = tsubst_copy (USING_DECL_SCOPE (t), args,
13554 					     complain, in_decl);
13555 	      r = do_class_using_decl (inst_scope, name);
13556 	      if (!r)
13557 		r = error_mark_node;
13558 	      else
13559 		{
13560 		  TREE_PROTECTED (r) = TREE_PROTECTED (t);
13561 		  TREE_PRIVATE (r) = TREE_PRIVATE (t);
13562 		}
13563 	    }
13564 	}
13565       else
13566 	{
13567 	  r = copy_node (t);
13568 	  DECL_CHAIN (r) = NULL_TREE;
13569 	}
13570       break;
13571 
13572     case TYPE_DECL:
13573     case VAR_DECL:
13574       {
13575 	tree argvec = NULL_TREE;
13576 	tree gen_tmpl = NULL_TREE;
13577 	tree spec;
13578 	tree tmpl = NULL_TREE;
13579 	tree ctx;
13580 	tree type = NULL_TREE;
13581 	bool local_p;
13582 
13583 	if (TREE_TYPE (t) == error_mark_node)
13584 	  RETURN (error_mark_node);
13585 
13586 	if (TREE_CODE (t) == TYPE_DECL
13587 	    && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
13588 	  {
13589 	    /* If this is the canonical decl, we don't have to
13590 	       mess with instantiations, and often we can't (for
13591 	       typename, template type parms and such).  Note that
13592 	       TYPE_NAME is not correct for the above test if
13593 	       we've copied the type for a typedef.  */
13594 	    type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13595 	    if (type == error_mark_node)
13596 	      RETURN (error_mark_node);
13597 	    r = TYPE_NAME (type);
13598 	    break;
13599 	  }
13600 
13601 	/* Check to see if we already have the specialization we
13602 	   need.  */
13603 	spec = NULL_TREE;
13604 	if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
13605 	  {
13606 	    /* T is a static data member or namespace-scope entity.
13607 	       We have to substitute into namespace-scope variables
13608 	       (not just variable templates) because of cases like:
13609 
13610 	         template <class T> void f() { extern T t; }
13611 
13612 	       where the entity referenced is not known until
13613 	       instantiation time.  */
13614 	    local_p = false;
13615 	    ctx = DECL_CONTEXT (t);
13616 	    if (DECL_CLASS_SCOPE_P (t))
13617 	      {
13618 		ctx = tsubst_aggr_type (ctx, args,
13619 					complain,
13620 					in_decl, /*entering_scope=*/1);
13621 		/* If CTX is unchanged, then T is in fact the
13622 		   specialization we want.  That situation occurs when
13623 		   referencing a static data member within in its own
13624 		   class.  We can use pointer equality, rather than
13625 		   same_type_p, because DECL_CONTEXT is always
13626 		   canonical...  */
13627 		if (ctx == DECL_CONTEXT (t)
13628 		    /* ... unless T is a member template; in which
13629 		       case our caller can be willing to create a
13630 		       specialization of that template represented
13631 		       by T.  */
13632 		    && !(DECL_TI_TEMPLATE (t)
13633 			 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (t))))
13634 		  spec = t;
13635 	      }
13636 
13637 	    if (!spec)
13638 	      {
13639 		tmpl = DECL_TI_TEMPLATE (t);
13640 		gen_tmpl = most_general_template (tmpl);
13641 		argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
13642 		if (argvec != error_mark_node)
13643 		  argvec = (coerce_innermost_template_parms
13644 			    (DECL_TEMPLATE_PARMS (gen_tmpl),
13645 			     argvec, t, complain,
13646 			     /*all*/true, /*defarg*/true));
13647 		if (argvec == error_mark_node)
13648 		  RETURN (error_mark_node);
13649 		hash = hash_tmpl_and_args (gen_tmpl, argvec);
13650 		spec = retrieve_specialization (gen_tmpl, argvec, hash);
13651 	      }
13652 	  }
13653 	else
13654 	  {
13655 	    /* A local variable.  */
13656 	    local_p = true;
13657 	    /* Subsequent calls to pushdecl will fill this in.  */
13658 	    ctx = NULL_TREE;
13659 	    /* Unless this is a reference to a static variable from an
13660 	       enclosing function, in which case we need to fill it in now.  */
13661 	    if (TREE_STATIC (t))
13662 	      {
13663 		tree fn = enclosing_instantiation_of (DECL_CONTEXT (t));
13664 		if (fn != current_function_decl)
13665 		  ctx = fn;
13666 	      }
13667 	    spec = retrieve_local_specialization (t);
13668 	  }
13669 	/* If we already have the specialization we need, there is
13670 	   nothing more to do.  */
13671 	if (spec)
13672 	  {
13673 	    r = spec;
13674 	    break;
13675 	  }
13676 
13677 	/* Create a new node for the specialization we need.  */
13678 	r = copy_decl (t);
13679 	if (type == NULL_TREE)
13680 	  {
13681 	    if (is_typedef_decl (t))
13682 	      type = DECL_ORIGINAL_TYPE (t);
13683 	    else
13684 	      type = TREE_TYPE (t);
13685 	    if (VAR_P (t)
13686 		&& VAR_HAD_UNKNOWN_BOUND (t)
13687 		&& type != error_mark_node)
13688 	      type = strip_array_domain (type);
13689 	    tree sub_args = args;
13690 	    if (tree auto_node = type_uses_auto (type))
13691 	      {
13692 		/* Mask off any template args past the variable's context so we
13693 		   don't replace the auto with an unrelated argument.  */
13694 		int nouter = TEMPLATE_TYPE_LEVEL (auto_node) - 1;
13695 		int extra = TMPL_ARGS_DEPTH (args) - nouter;
13696 		if (extra > 0)
13697 		  /* This should never happen with the new lambda instantiation
13698 		     model, but keep the handling just in case.  */
13699 		  gcc_assert (!CHECKING_P),
13700 		  sub_args = strip_innermost_template_args (args, extra);
13701 	      }
13702 	    type = tsubst (type, sub_args, complain, in_decl);
13703 	  }
13704 	if (VAR_P (r))
13705 	  {
13706 	    /* Even if the original location is out of scope, the
13707 	       newly substituted one is not.  */
13708 	    DECL_DEAD_FOR_LOCAL (r) = 0;
13709 	    DECL_INITIALIZED_P (r) = 0;
13710 	    DECL_TEMPLATE_INSTANTIATED (r) = 0;
13711 	    if (type == error_mark_node)
13712 	      RETURN (error_mark_node);
13713 	    if (TREE_CODE (type) == FUNCTION_TYPE)
13714 	      {
13715 		/* It may seem that this case cannot occur, since:
13716 
13717 		   typedef void f();
13718 		   void g() { f x; }
13719 
13720 		   declares a function, not a variable.  However:
13721 
13722 		   typedef void f();
13723 		   template <typename T> void g() { T t; }
13724 		   template void g<f>();
13725 
13726 		   is an attempt to declare a variable with function
13727 		   type.  */
13728 		error ("variable %qD has function type",
13729 		       /* R is not yet sufficiently initialized, so we
13730 			  just use its name.  */
13731 		       DECL_NAME (r));
13732 		RETURN (error_mark_node);
13733 	      }
13734 	    type = complete_type (type);
13735 	    /* Wait until cp_finish_decl to set this again, to handle
13736 	       circular dependency (template/instantiate6.C). */
13737 	    DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
13738 	    type = check_var_type (DECL_NAME (r), type);
13739 
13740 	    if (DECL_HAS_VALUE_EXPR_P (t))
13741 	      {
13742 		tree ve = DECL_VALUE_EXPR (t);
13743 		ve = tsubst_expr (ve, args, complain, in_decl,
13744 				  /*constant_expression_p=*/false);
13745 		if (REFERENCE_REF_P (ve))
13746 		  {
13747 		    gcc_assert (TREE_CODE (type) == REFERENCE_TYPE);
13748 		    ve = TREE_OPERAND (ve, 0);
13749 		  }
13750 		SET_DECL_VALUE_EXPR (r, ve);
13751 	      }
13752 	    if (CP_DECL_THREAD_LOCAL_P (r)
13753 		&& !processing_template_decl)
13754 	      set_decl_tls_model (r, decl_default_tls_model (r));
13755 	  }
13756 	else if (DECL_SELF_REFERENCE_P (t))
13757 	  SET_DECL_SELF_REFERENCE_P (r);
13758 	TREE_TYPE (r) = type;
13759 	cp_apply_type_quals_to_decl (cp_type_quals (type), r);
13760 	DECL_CONTEXT (r) = ctx;
13761 	/* Clear out the mangled name and RTL for the instantiation.  */
13762 	SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
13763 	if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
13764 	  SET_DECL_RTL (r, NULL);
13765 	/* The initializer must not be expanded until it is required;
13766 	   see [temp.inst].  */
13767 	DECL_INITIAL (r) = NULL_TREE;
13768 	DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
13769 	if (VAR_P (r))
13770 	  {
13771 	    if (DECL_LANG_SPECIFIC (r))
13772 	      SET_DECL_DEPENDENT_INIT_P (r, false);
13773 
13774 	    SET_DECL_MODE (r, VOIDmode);
13775 
13776 	    /* Possibly limit visibility based on template args.  */
13777 	    DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
13778 	    if (DECL_VISIBILITY_SPECIFIED (t))
13779 	      {
13780 		DECL_VISIBILITY_SPECIFIED (r) = 0;
13781 		DECL_ATTRIBUTES (r)
13782 		  = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
13783 	      }
13784 	    determine_visibility (r);
13785 	  }
13786 
13787 	if (!local_p)
13788 	  {
13789 	    /* A static data member declaration is always marked
13790 	       external when it is declared in-class, even if an
13791 	       initializer is present.  We mimic the non-template
13792 	       processing here.  */
13793 	    DECL_EXTERNAL (r) = 1;
13794 	    if (DECL_NAMESPACE_SCOPE_P (t))
13795 	      DECL_NOT_REALLY_EXTERN (r) = 1;
13796 
13797 	    DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
13798 	    SET_DECL_IMPLICIT_INSTANTIATION (r);
13799 	    register_specialization (r, gen_tmpl, argvec, false, hash);
13800 	  }
13801 	else
13802 	  {
13803 	    if (DECL_LANG_SPECIFIC (r))
13804 	      DECL_TEMPLATE_INFO (r) = NULL_TREE;
13805 	    if (!cp_unevaluated_operand)
13806 	      register_local_specialization (r, t);
13807 	  }
13808 
13809 	DECL_CHAIN (r) = NULL_TREE;
13810 
13811 	apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
13812 					/*flags=*/0,
13813 					args, complain, in_decl);
13814 
13815 	/* Preserve a typedef that names a type.  */
13816 	if (is_typedef_decl (r) && type != error_mark_node)
13817 	  {
13818 	    DECL_ORIGINAL_TYPE (r) = NULL_TREE;
13819 	    set_underlying_type (r);
13820 	    if (TYPE_DECL_ALIAS_P (r))
13821 	      /* An alias template specialization can be dependent
13822 		 even if its underlying type is not.  */
13823 	      TYPE_DEPENDENT_P_VALID (TREE_TYPE (r)) = false;
13824 	  }
13825 
13826 	layout_decl (r, 0);
13827       }
13828       break;
13829 
13830     default:
13831       gcc_unreachable ();
13832     }
13833 #undef RETURN
13834 
13835  out:
13836   /* Restore the file and line information.  */
13837   input_location = saved_loc;
13838 
13839   return r;
13840 }
13841 
13842 /* Substitute into the ARG_TYPES of a function type.
13843    If END is a TREE_CHAIN, leave it and any following types
13844    un-substituted.  */
13845 
13846 static tree
tsubst_arg_types(tree arg_types,tree args,tree end,tsubst_flags_t complain,tree in_decl)13847 tsubst_arg_types (tree arg_types,
13848 		  tree args,
13849 		  tree end,
13850 		  tsubst_flags_t complain,
13851 		  tree in_decl)
13852 {
13853   tree remaining_arg_types;
13854   tree type = NULL_TREE;
13855   int i = 1;
13856   tree expanded_args = NULL_TREE;
13857   tree default_arg;
13858 
13859   if (!arg_types || arg_types == void_list_node || arg_types == end)
13860     return arg_types;
13861 
13862   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
13863 					  args, end, complain, in_decl);
13864   if (remaining_arg_types == error_mark_node)
13865     return error_mark_node;
13866 
13867   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
13868     {
13869       /* For a pack expansion, perform substitution on the
13870          entire expression. Later on, we'll handle the arguments
13871          one-by-one.  */
13872       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
13873                                             args, complain, in_decl);
13874 
13875       if (TREE_CODE (expanded_args) == TREE_VEC)
13876         /* So that we'll spin through the parameters, one by one.  */
13877         i = TREE_VEC_LENGTH (expanded_args);
13878       else
13879         {
13880           /* We only partially substituted into the parameter
13881              pack. Our type is TYPE_PACK_EXPANSION.  */
13882           type = expanded_args;
13883           expanded_args = NULL_TREE;
13884         }
13885     }
13886 
13887   while (i > 0) {
13888     --i;
13889 
13890     if (expanded_args)
13891       type = TREE_VEC_ELT (expanded_args, i);
13892     else if (!type)
13893       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
13894 
13895     if (type == error_mark_node)
13896       return error_mark_node;
13897     if (VOID_TYPE_P (type))
13898       {
13899         if (complain & tf_error)
13900           {
13901             error ("invalid parameter type %qT", type);
13902             if (in_decl)
13903               error ("in declaration %q+D", in_decl);
13904           }
13905         return error_mark_node;
13906     }
13907     /* DR 657. */
13908     if (abstract_virtuals_error_sfinae (ACU_PARM, type, complain))
13909       return error_mark_node;
13910 
13911     /* Do array-to-pointer, function-to-pointer conversion, and ignore
13912        top-level qualifiers as required.  */
13913     type = cv_unqualified (type_decays_to (type));
13914 
13915     /* We do not substitute into default arguments here.  The standard
13916        mandates that they be instantiated only when needed, which is
13917        done in build_over_call.  */
13918     default_arg = TREE_PURPOSE (arg_types);
13919 
13920     /* Except that we do substitute default arguments under tsubst_lambda_expr,
13921        since the new op() won't have any associated template arguments for us
13922        to refer to later.  */
13923     if (lambda_fn_in_template_p (in_decl))
13924       default_arg = tsubst_copy_and_build (default_arg, args, complain, in_decl,
13925 					   false/*fn*/, false/*constexpr*/);
13926 
13927     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
13928       {
13929         /* We've instantiated a template before its default arguments
13930            have been parsed.  This can happen for a nested template
13931            class, and is not an error unless we require the default
13932            argument in a call of this function.  */
13933         remaining_arg_types =
13934           tree_cons (default_arg, type, remaining_arg_types);
13935         vec_safe_push (DEFARG_INSTANTIATIONS(default_arg), remaining_arg_types);
13936       }
13937     else
13938       remaining_arg_types =
13939         hash_tree_cons (default_arg, type, remaining_arg_types);
13940   }
13941 
13942   return remaining_arg_types;
13943 }
13944 
13945 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
13946    *not* handle the exception-specification for FNTYPE, because the
13947    initial substitution of explicitly provided template parameters
13948    during argument deduction forbids substitution into the
13949    exception-specification:
13950 
13951      [temp.deduct]
13952 
13953      All references in the function type of the function template to  the
13954      corresponding template parameters are replaced by the specified tem-
13955      plate argument values.  If a substitution in a template parameter or
13956      in  the function type of the function template results in an invalid
13957      type, type deduction fails.  [Note: The equivalent  substitution  in
13958      exception specifications is done only when the function is instanti-
13959      ated, at which point a program is  ill-formed  if  the  substitution
13960      results in an invalid type.]  */
13961 
13962 static tree
tsubst_function_type(tree t,tree args,tsubst_flags_t complain,tree in_decl)13963 tsubst_function_type (tree t,
13964 		      tree args,
13965 		      tsubst_flags_t complain,
13966 		      tree in_decl)
13967 {
13968   tree return_type;
13969   tree arg_types = NULL_TREE;
13970   tree fntype;
13971 
13972   /* The TYPE_CONTEXT is not used for function/method types.  */
13973   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
13974 
13975   /* DR 1227: Mixing immediate and non-immediate contexts in deduction
13976      failure.  */
13977   bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
13978 
13979   if (late_return_type_p)
13980     {
13981       /* Substitute the argument types.  */
13982       arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
13983 				    complain, in_decl);
13984       if (arg_types == error_mark_node)
13985 	return error_mark_node;
13986 
13987       tree save_ccp = current_class_ptr;
13988       tree save_ccr = current_class_ref;
13989       tree this_type = (TREE_CODE (t) == METHOD_TYPE
13990 			? TREE_TYPE (TREE_VALUE (arg_types)) : NULL_TREE);
13991       bool do_inject = this_type && CLASS_TYPE_P (this_type);
13992       if (do_inject)
13993 	{
13994 	  /* DR 1207: 'this' is in scope in the trailing return type.  */
13995 	  inject_this_parameter (this_type, cp_type_quals (this_type));
13996 	}
13997 
13998       /* Substitute the return type.  */
13999       return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14000 
14001       if (do_inject)
14002 	{
14003 	  current_class_ptr = save_ccp;
14004 	  current_class_ref = save_ccr;
14005 	}
14006     }
14007   else
14008     /* Substitute the return type.  */
14009     return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14010 
14011   if (return_type == error_mark_node)
14012     return error_mark_node;
14013   /* DR 486 clarifies that creation of a function type with an
14014      invalid return type is a deduction failure.  */
14015   if (TREE_CODE (return_type) == ARRAY_TYPE
14016       || TREE_CODE (return_type) == FUNCTION_TYPE)
14017     {
14018       if (complain & tf_error)
14019 	{
14020 	  if (TREE_CODE (return_type) == ARRAY_TYPE)
14021 	    error ("function returning an array");
14022 	  else
14023 	    error ("function returning a function");
14024 	}
14025       return error_mark_node;
14026     }
14027   /* And DR 657. */
14028   if (abstract_virtuals_error_sfinae (ACU_RETURN, return_type, complain))
14029     return error_mark_node;
14030 
14031   if (!late_return_type_p)
14032     {
14033       /* Substitute the argument types.  */
14034       arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
14035 				    complain, in_decl);
14036       if (arg_types == error_mark_node)
14037 	return error_mark_node;
14038     }
14039 
14040   /* Construct a new type node and return it.  */
14041   if (TREE_CODE (t) == FUNCTION_TYPE)
14042     {
14043       fntype = build_function_type (return_type, arg_types);
14044       fntype = apply_memfn_quals (fntype,
14045 				  type_memfn_quals (t),
14046 				  type_memfn_rqual (t));
14047     }
14048   else
14049     {
14050       tree r = TREE_TYPE (TREE_VALUE (arg_types));
14051       /* Don't pick up extra function qualifiers from the basetype.  */
14052       r = cp_build_qualified_type_real (r, type_memfn_quals (t), complain);
14053       if (! MAYBE_CLASS_TYPE_P (r))
14054 	{
14055 	  /* [temp.deduct]
14056 
14057 	     Type deduction may fail for any of the following
14058 	     reasons:
14059 
14060 	     -- Attempting to create "pointer to member of T" when T
14061 	     is not a class type.  */
14062 	  if (complain & tf_error)
14063 	    error ("creating pointer to member function of non-class type %qT",
14064 		      r);
14065 	  return error_mark_node;
14066 	}
14067 
14068       fntype = build_method_type_directly (r, return_type,
14069 					   TREE_CHAIN (arg_types));
14070       fntype = build_ref_qualified_type (fntype, type_memfn_rqual (t));
14071     }
14072   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
14073 
14074   if (late_return_type_p)
14075     TYPE_HAS_LATE_RETURN_TYPE (fntype) = 1;
14076 
14077   return fntype;
14078 }
14079 
14080 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
14081    ARGS into that specification, and return the substituted
14082    specification.  If there is no specification, return NULL_TREE.  */
14083 
14084 static tree
tsubst_exception_specification(tree fntype,tree args,tsubst_flags_t complain,tree in_decl,bool defer_ok)14085 tsubst_exception_specification (tree fntype,
14086 				tree args,
14087 				tsubst_flags_t complain,
14088 				tree in_decl,
14089 				bool defer_ok)
14090 {
14091   tree specs;
14092   tree new_specs;
14093 
14094   specs = TYPE_RAISES_EXCEPTIONS (fntype);
14095   new_specs = NULL_TREE;
14096   if (specs && TREE_PURPOSE (specs))
14097     {
14098       /* A noexcept-specifier.  */
14099       tree expr = TREE_PURPOSE (specs);
14100       if (TREE_CODE (expr) == INTEGER_CST)
14101 	new_specs = expr;
14102       else if (defer_ok)
14103 	{
14104 	  /* Defer instantiation of noexcept-specifiers to avoid
14105 	     excessive instantiations (c++/49107).  */
14106 	  new_specs = make_node (DEFERRED_NOEXCEPT);
14107 	  if (DEFERRED_NOEXCEPT_SPEC_P (specs))
14108 	    {
14109 	      /* We already partially instantiated this member template,
14110 		 so combine the new args with the old.  */
14111 	      DEFERRED_NOEXCEPT_PATTERN (new_specs)
14112 		= DEFERRED_NOEXCEPT_PATTERN (expr);
14113 	      DEFERRED_NOEXCEPT_ARGS (new_specs)
14114 		= add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
14115 	    }
14116 	  else
14117 	    {
14118 	      DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
14119 	      DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
14120 	    }
14121 	}
14122       else
14123 	new_specs = tsubst_copy_and_build
14124 	  (expr, args, complain, in_decl, /*function_p=*/false,
14125 	   /*integral_constant_expression_p=*/true);
14126       new_specs = build_noexcept_spec (new_specs, complain);
14127     }
14128   else if (specs)
14129     {
14130       if (! TREE_VALUE (specs))
14131 	new_specs = specs;
14132       else
14133 	while (specs)
14134 	  {
14135 	    tree spec;
14136             int i, len = 1;
14137             tree expanded_specs = NULL_TREE;
14138 
14139             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
14140               {
14141                 /* Expand the pack expansion type.  */
14142                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
14143                                                        args, complain,
14144                                                        in_decl);
14145 
14146 		if (expanded_specs == error_mark_node)
14147 		  return error_mark_node;
14148 		else if (TREE_CODE (expanded_specs) == TREE_VEC)
14149 		  len = TREE_VEC_LENGTH (expanded_specs);
14150 		else
14151 		  {
14152 		    /* We're substituting into a member template, so
14153 		       we got a TYPE_PACK_EXPANSION back.  Add that
14154 		       expansion and move on.  */
14155 		    gcc_assert (TREE_CODE (expanded_specs)
14156 				== TYPE_PACK_EXPANSION);
14157 		    new_specs = add_exception_specifier (new_specs,
14158 							 expanded_specs,
14159 							 complain);
14160 		    specs = TREE_CHAIN (specs);
14161 		    continue;
14162 		  }
14163               }
14164 
14165             for (i = 0; i < len; ++i)
14166               {
14167                 if (expanded_specs)
14168                   spec = TREE_VEC_ELT (expanded_specs, i);
14169                 else
14170                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
14171                 if (spec == error_mark_node)
14172                   return spec;
14173                 new_specs = add_exception_specifier (new_specs, spec,
14174                                                      complain);
14175               }
14176 
14177             specs = TREE_CHAIN (specs);
14178 	  }
14179     }
14180   return new_specs;
14181 }
14182 
14183 /* Take the tree structure T and replace template parameters used
14184    therein with the argument vector ARGS.  IN_DECL is an associated
14185    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
14186    Issue error and warning messages under control of COMPLAIN.  Note
14187    that we must be relatively non-tolerant of extensions here, in
14188    order to preserve conformance; if we allow substitutions that
14189    should not be allowed, we may allow argument deductions that should
14190    not succeed, and therefore report ambiguous overload situations
14191    where there are none.  In theory, we could allow the substitution,
14192    but indicate that it should have failed, and allow our caller to
14193    make sure that the right thing happens, but we don't try to do this
14194    yet.
14195 
14196    This function is used for dealing with types, decls and the like;
14197    for expressions, use tsubst_expr or tsubst_copy.  */
14198 
14199 tree
tsubst(tree t,tree args,tsubst_flags_t complain,tree in_decl)14200 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
14201 {
14202   enum tree_code code;
14203   tree type, r = NULL_TREE;
14204 
14205   if (t == NULL_TREE || t == error_mark_node
14206       || t == integer_type_node
14207       || t == void_type_node
14208       || t == char_type_node
14209       || t == unknown_type_node
14210       || TREE_CODE (t) == NAMESPACE_DECL
14211       || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
14212     return t;
14213 
14214   if (DECL_P (t))
14215     return tsubst_decl (t, args, complain);
14216 
14217   if (args == NULL_TREE)
14218     return t;
14219 
14220   code = TREE_CODE (t);
14221 
14222   if (code == IDENTIFIER_NODE)
14223     type = IDENTIFIER_TYPE_VALUE (t);
14224   else
14225     type = TREE_TYPE (t);
14226 
14227   gcc_assert (type != unknown_type_node);
14228 
14229   /* Reuse typedefs.  We need to do this to handle dependent attributes,
14230      such as attribute aligned.  */
14231   if (TYPE_P (t)
14232       && typedef_variant_p (t))
14233     {
14234       tree decl = TYPE_NAME (t);
14235 
14236       if (alias_template_specialization_p (t))
14237 	{
14238 	  /* DECL represents an alias template and we want to
14239 	     instantiate it.  */
14240 	  tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
14241 	  tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
14242 	  r = instantiate_alias_template (tmpl, gen_args, complain);
14243 	}
14244       else if (DECL_CLASS_SCOPE_P (decl)
14245 	       && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
14246 	       && uses_template_parms (DECL_CONTEXT (decl)))
14247 	{
14248 	  tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
14249 	  tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
14250 	  r = retrieve_specialization (tmpl, gen_args, 0);
14251 	}
14252       else if (DECL_FUNCTION_SCOPE_P (decl)
14253 	       && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
14254 	       && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
14255 	r = retrieve_local_specialization (decl);
14256       else
14257 	/* The typedef is from a non-template context.  */
14258 	return t;
14259 
14260       if (r)
14261 	{
14262 	  r = TREE_TYPE (r);
14263 	  r = cp_build_qualified_type_real
14264 	    (r, cp_type_quals (t) | cp_type_quals (r),
14265 	     complain | tf_ignore_bad_quals);
14266 	  return r;
14267 	}
14268       else
14269 	{
14270 	  /* We don't have an instantiation yet, so drop the typedef.  */
14271 	  int quals = cp_type_quals (t);
14272 	  t = DECL_ORIGINAL_TYPE (decl);
14273 	  t = cp_build_qualified_type_real (t, quals,
14274 					    complain | tf_ignore_bad_quals);
14275 	}
14276     }
14277 
14278   bool fndecl_type = (complain & tf_fndecl_type);
14279   complain &= ~tf_fndecl_type;
14280 
14281   if (type
14282       && code != TYPENAME_TYPE
14283       && code != TEMPLATE_TYPE_PARM
14284       && code != TEMPLATE_PARM_INDEX
14285       && code != IDENTIFIER_NODE
14286       && code != FUNCTION_TYPE
14287       && code != METHOD_TYPE)
14288     type = tsubst (type, args, complain, in_decl);
14289   if (type == error_mark_node)
14290     return error_mark_node;
14291 
14292   switch (code)
14293     {
14294     case RECORD_TYPE:
14295     case UNION_TYPE:
14296     case ENUMERAL_TYPE:
14297       return tsubst_aggr_type (t, args, complain, in_decl,
14298 			       /*entering_scope=*/0);
14299 
14300     case ERROR_MARK:
14301     case IDENTIFIER_NODE:
14302     case VOID_TYPE:
14303     case REAL_TYPE:
14304     case COMPLEX_TYPE:
14305     case VECTOR_TYPE:
14306     case BOOLEAN_TYPE:
14307     case NULLPTR_TYPE:
14308     case LANG_TYPE:
14309       return t;
14310 
14311     case INTEGER_TYPE:
14312       if (t == integer_type_node)
14313 	return t;
14314 
14315       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
14316           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
14317         return t;
14318 
14319       {
14320 	tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
14321 
14322 	max = tsubst_expr (omax, args, complain, in_decl,
14323 			   /*integral_constant_expression_p=*/false);
14324 
14325 	/* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
14326 	   needed.  */
14327 	if (TREE_CODE (max) == NOP_EXPR
14328 	    && TREE_SIDE_EFFECTS (omax)
14329 	    && !TREE_TYPE (max))
14330 	  TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
14331 
14332 	/* If we're in a partial instantiation, preserve the magic NOP_EXPR
14333 	   with TREE_SIDE_EFFECTS that indicates this is not an integral
14334 	   constant expression.  */
14335 	if (processing_template_decl
14336 	    && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
14337 	  {
14338 	    gcc_assert (TREE_CODE (max) == NOP_EXPR);
14339 	    TREE_SIDE_EFFECTS (max) = 1;
14340 	  }
14341 
14342 	return compute_array_index_type (NULL_TREE, max, complain);
14343       }
14344 
14345     case TEMPLATE_TYPE_PARM:
14346     case TEMPLATE_TEMPLATE_PARM:
14347     case BOUND_TEMPLATE_TEMPLATE_PARM:
14348     case TEMPLATE_PARM_INDEX:
14349       {
14350 	int idx;
14351 	int level;
14352 	int levels;
14353 	tree arg = NULL_TREE;
14354 
14355 	/* Early in template argument deduction substitution, we don't
14356 	   want to reduce the level of 'auto', or it will be confused
14357 	   with a normal template parm in subsequent deduction.  */
14358 	if (is_auto (t) && (complain & tf_partial))
14359 	  return t;
14360 
14361 	r = NULL_TREE;
14362 
14363 	gcc_assert (TREE_VEC_LENGTH (args) > 0);
14364 	template_parm_level_and_index (t, &level, &idx);
14365 
14366 	levels = TMPL_ARGS_DEPTH (args);
14367 	if (level <= levels
14368 	    && TREE_VEC_LENGTH (TMPL_ARGS_LEVEL (args, level)) > 0)
14369 	  {
14370 	    arg = TMPL_ARG (args, level, idx);
14371 
14372 	    /* See through ARGUMENT_PACK_SELECT arguments. */
14373 	    if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
14374 	      arg = argument_pack_select_arg (arg);
14375 	  }
14376 
14377 	if (arg == error_mark_node)
14378 	  return error_mark_node;
14379 	else if (arg != NULL_TREE)
14380 	  {
14381 	    if (ARGUMENT_PACK_P (arg))
14382 	      /* If ARG is an argument pack, we don't actually want to
14383 		 perform a substitution here, because substitutions
14384 		 for argument packs are only done
14385 		 element-by-element. We can get to this point when
14386 		 substituting the type of a non-type template
14387 		 parameter pack, when that type actually contains
14388 		 template parameter packs from an outer template, e.g.,
14389 
14390 	         template<typename... Types> struct A {
14391 		   template<Types... Values> struct B { };
14392                  };  */
14393 	      return t;
14394 
14395 	    if (code == TEMPLATE_TYPE_PARM)
14396 	      {
14397 		int quals;
14398 		gcc_assert (TYPE_P (arg));
14399 
14400 		quals = cp_type_quals (arg) | cp_type_quals (t);
14401 
14402 		return cp_build_qualified_type_real
14403 		  (arg, quals, complain | tf_ignore_bad_quals);
14404 	      }
14405 	    else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
14406 	      {
14407 		/* We are processing a type constructed from a
14408 		   template template parameter.  */
14409 		tree argvec = tsubst (TYPE_TI_ARGS (t),
14410 				      args, complain, in_decl);
14411 		if (argvec == error_mark_node)
14412 		  return error_mark_node;
14413 
14414 		gcc_assert (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
14415 			    || TREE_CODE (arg) == TEMPLATE_DECL
14416 			    || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
14417 
14418 		if (TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
14419 		  /* Consider this code:
14420 
14421 			template <template <class> class Template>
14422 			struct Internal {
14423 			template <class Arg> using Bind = Template<Arg>;
14424 			};
14425 
14426 			template <template <class> class Template, class Arg>
14427 			using Instantiate = Template<Arg>; //#0
14428 
14429 			template <template <class> class Template,
14430                                   class Argument>
14431 			using Bind =
14432 			  Instantiate<Internal<Template>::template Bind,
14433 				      Argument>; //#1
14434 
14435 		     When #1 is parsed, the
14436 		     BOUND_TEMPLATE_TEMPLATE_PARM representing the
14437 		     parameter `Template' in #0 matches the
14438 		     UNBOUND_CLASS_TEMPLATE representing the argument
14439 		     `Internal<Template>::template Bind'; We then want
14440 		     to assemble the type `Bind<Argument>' that can't
14441 		     be fully created right now, because
14442 		     `Internal<Template>' not being complete, the Bind
14443 		     template cannot be looked up in that context.  So
14444 		     we need to "store" `Bind<Argument>' for later
14445 		     when the context of Bind becomes complete.  Let's
14446 		     store that in a TYPENAME_TYPE.  */
14447 		  return make_typename_type (TYPE_CONTEXT (arg),
14448 					     build_nt (TEMPLATE_ID_EXPR,
14449 						       TYPE_IDENTIFIER (arg),
14450 						       argvec),
14451 					     typename_type,
14452 					     complain);
14453 
14454 		/* We can get a TEMPLATE_TEMPLATE_PARM here when we
14455 		   are resolving nested-types in the signature of a
14456 		   member function templates.  Otherwise ARG is a
14457 		   TEMPLATE_DECL and is the real template to be
14458 		   instantiated.  */
14459 		if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
14460 		  arg = TYPE_NAME (arg);
14461 
14462 		r = lookup_template_class (arg,
14463 					   argvec, in_decl,
14464 					   DECL_CONTEXT (arg),
14465 					    /*entering_scope=*/0,
14466 					   complain);
14467 		return cp_build_qualified_type_real
14468 		  (r, cp_type_quals (t) | cp_type_quals (r), complain);
14469 	      }
14470 	    else if (code == TEMPLATE_TEMPLATE_PARM)
14471 	      return arg;
14472 	    else
14473 	      /* TEMPLATE_PARM_INDEX.  */
14474 	      return convert_from_reference (unshare_expr (arg));
14475 	  }
14476 
14477 	if (level == 1)
14478 	  /* This can happen during the attempted tsubst'ing in
14479 	     unify.  This means that we don't yet have any information
14480 	     about the template parameter in question.  */
14481 	  return t;
14482 
14483 	/* If we get here, we must have been looking at a parm for a
14484 	   more deeply nested template.  Make a new version of this
14485 	   template parameter, but with a lower level.  */
14486 	switch (code)
14487 	  {
14488 	  case TEMPLATE_TYPE_PARM:
14489 	  case TEMPLATE_TEMPLATE_PARM:
14490 	  case BOUND_TEMPLATE_TEMPLATE_PARM:
14491 	    if (cp_type_quals (t))
14492 	      {
14493 		r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
14494 		r = cp_build_qualified_type_real
14495 		  (r, cp_type_quals (t),
14496 		   complain | (code == TEMPLATE_TYPE_PARM
14497 			       ? tf_ignore_bad_quals : 0));
14498 	      }
14499 	    else if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
14500 		     && PLACEHOLDER_TYPE_CONSTRAINTS (t)
14501 		     && (r = (TEMPLATE_PARM_DESCENDANTS
14502 			      (TEMPLATE_TYPE_PARM_INDEX (t))))
14503 		     && (r = TREE_TYPE (r))
14504 		     && !PLACEHOLDER_TYPE_CONSTRAINTS (r))
14505 	      /* Break infinite recursion when substituting the constraints
14506 		 of a constrained placeholder.  */;
14507 	    else if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
14508 		     && !PLACEHOLDER_TYPE_CONSTRAINTS (t)
14509 		     && !CLASS_PLACEHOLDER_TEMPLATE (t)
14510 		     && (arg = TEMPLATE_TYPE_PARM_INDEX (t),
14511 			 r = TEMPLATE_PARM_DESCENDANTS (arg))
14512 		     && (TEMPLATE_PARM_LEVEL (r)
14513 			 == TEMPLATE_PARM_LEVEL (arg) - levels))
14514 		/* Cache the simple case of lowering a type parameter.  */
14515 	      r = TREE_TYPE (r);
14516 	    else
14517 	      {
14518 		r = copy_type (t);
14519 		TEMPLATE_TYPE_PARM_INDEX (r)
14520 		  = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
14521 						r, levels, args, complain);
14522 		TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
14523 		TYPE_MAIN_VARIANT (r) = r;
14524 		TYPE_POINTER_TO (r) = NULL_TREE;
14525 		TYPE_REFERENCE_TO (r) = NULL_TREE;
14526 
14527                 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
14528 		  {
14529 		    /* Propagate constraints on placeholders.  */
14530 		    if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (t))
14531 		      PLACEHOLDER_TYPE_CONSTRAINTS (r)
14532 			= tsubst_constraint (constr, args, complain, in_decl);
14533 		    else if (tree pl = CLASS_PLACEHOLDER_TEMPLATE (t))
14534 		      {
14535 			pl = tsubst_copy (pl, args, complain, in_decl);
14536 			CLASS_PLACEHOLDER_TEMPLATE (r) = pl;
14537 		      }
14538 		  }
14539 
14540 		if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
14541 		  /* We have reduced the level of the template
14542 		     template parameter, but not the levels of its
14543 		     template parameters, so canonical_type_parameter
14544 		     will not be able to find the canonical template
14545 		     template parameter for this level. Thus, we
14546 		     require structural equality checking to compare
14547 		     TEMPLATE_TEMPLATE_PARMs. */
14548 		  SET_TYPE_STRUCTURAL_EQUALITY (r);
14549 		else if (TYPE_STRUCTURAL_EQUALITY_P (t))
14550 		  SET_TYPE_STRUCTURAL_EQUALITY (r);
14551 		else
14552 		  TYPE_CANONICAL (r) = canonical_type_parameter (r);
14553 
14554 		if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
14555 		  {
14556 		    tree tinfo = TYPE_TEMPLATE_INFO (t);
14557 		    /* We might need to substitute into the types of non-type
14558 		       template parameters.  */
14559 		    tree tmpl = tsubst (TI_TEMPLATE (tinfo), args,
14560 					complain, in_decl);
14561 		    if (tmpl == error_mark_node)
14562 		      return error_mark_node;
14563 		    tree argvec = tsubst (TI_ARGS (tinfo), args,
14564 					  complain, in_decl);
14565 		    if (argvec == error_mark_node)
14566 		      return error_mark_node;
14567 
14568 		    TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
14569 		      = build_template_info (tmpl, argvec);
14570 		  }
14571 	      }
14572 	    break;
14573 
14574 	  case TEMPLATE_PARM_INDEX:
14575 	    /* OK, now substitute the type of the non-type parameter.  We
14576 	       couldn't do it earlier because it might be an auto parameter,
14577 	       and we wouldn't need to if we had an argument.  */
14578 	    type = tsubst (type, args, complain, in_decl);
14579 	    if (type == error_mark_node)
14580 	      return error_mark_node;
14581 	    r = reduce_template_parm_level (t, type, levels, args, complain);
14582 	    break;
14583 
14584 	  default:
14585 	    gcc_unreachable ();
14586 	  }
14587 
14588 	return r;
14589       }
14590 
14591     case TREE_LIST:
14592       {
14593 	tree purpose, value, chain;
14594 
14595 	if (t == void_list_node)
14596 	  return t;
14597 
14598 	purpose = TREE_PURPOSE (t);
14599 	if (purpose)
14600 	  {
14601 	    purpose = tsubst (purpose, args, complain, in_decl);
14602 	    if (purpose == error_mark_node)
14603 	      return error_mark_node;
14604 	  }
14605 	value = TREE_VALUE (t);
14606 	if (value)
14607 	  {
14608 	    value = tsubst (value, args, complain, in_decl);
14609 	    if (value == error_mark_node)
14610 	      return error_mark_node;
14611 	  }
14612 	chain = TREE_CHAIN (t);
14613 	if (chain && chain != void_type_node)
14614 	  {
14615 	    chain = tsubst (chain, args, complain, in_decl);
14616 	    if (chain == error_mark_node)
14617 	      return error_mark_node;
14618 	  }
14619 	if (purpose == TREE_PURPOSE (t)
14620 	    && value == TREE_VALUE (t)
14621 	    && chain == TREE_CHAIN (t))
14622 	  return t;
14623 	return hash_tree_cons (purpose, value, chain);
14624       }
14625 
14626     case TREE_BINFO:
14627       /* We should never be tsubsting a binfo.  */
14628       gcc_unreachable ();
14629 
14630     case TREE_VEC:
14631       /* A vector of template arguments.  */
14632       gcc_assert (!type);
14633       return tsubst_template_args (t, args, complain, in_decl);
14634 
14635     case POINTER_TYPE:
14636     case REFERENCE_TYPE:
14637       {
14638 	if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
14639 	  return t;
14640 
14641 	/* [temp.deduct]
14642 
14643 	   Type deduction may fail for any of the following
14644 	   reasons:
14645 
14646 	   -- Attempting to create a pointer to reference type.
14647 	   -- Attempting to create a reference to a reference type or
14648 	      a reference to void.
14649 
14650 	  Core issue 106 says that creating a reference to a reference
14651 	  during instantiation is no longer a cause for failure. We
14652 	  only enforce this check in strict C++98 mode.  */
14653 	if ((TREE_CODE (type) == REFERENCE_TYPE
14654 	     && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
14655 	    || (code == REFERENCE_TYPE && VOID_TYPE_P (type)))
14656 	  {
14657 	    static location_t last_loc;
14658 
14659 	    /* We keep track of the last time we issued this error
14660 	       message to avoid spewing a ton of messages during a
14661 	       single bad template instantiation.  */
14662 	    if (complain & tf_error
14663 		&& last_loc != input_location)
14664 	      {
14665 		if (VOID_TYPE_P (type))
14666 		  error ("forming reference to void");
14667                else if (code == POINTER_TYPE)
14668                  error ("forming pointer to reference type %qT", type);
14669                else
14670 		  error ("forming reference to reference type %qT", type);
14671 		last_loc = input_location;
14672 	      }
14673 
14674 	    return error_mark_node;
14675 	  }
14676 	else if (TREE_CODE (type) == FUNCTION_TYPE
14677 		 && (type_memfn_quals (type) != TYPE_UNQUALIFIED
14678 		     || type_memfn_rqual (type) != REF_QUAL_NONE))
14679 	  {
14680 	    if (complain & tf_error)
14681 	      {
14682 		if (code == POINTER_TYPE)
14683 		  error ("forming pointer to qualified function type %qT",
14684 			 type);
14685 		else
14686 		  error ("forming reference to qualified function type %qT",
14687 			 type);
14688 	      }
14689 	    return error_mark_node;
14690 	  }
14691 	else if (code == POINTER_TYPE)
14692 	  {
14693 	    r = build_pointer_type (type);
14694 	    if (TREE_CODE (type) == METHOD_TYPE)
14695 	      r = build_ptrmemfunc_type (r);
14696 	  }
14697 	else if (TREE_CODE (type) == REFERENCE_TYPE)
14698 	  /* In C++0x, during template argument substitution, when there is an
14699 	     attempt to create a reference to a reference type, reference
14700 	     collapsing is applied as described in [14.3.1/4 temp.arg.type]:
14701 
14702 	     "If a template-argument for a template-parameter T names a type
14703 	     that is a reference to a type A, an attempt to create the type
14704 	     'lvalue reference to cv T' creates the type 'lvalue reference to
14705 	     A,' while an attempt to create the type type rvalue reference to
14706 	     cv T' creates the type T"
14707 	  */
14708 	  r = cp_build_reference_type
14709 	      (TREE_TYPE (type),
14710 	       TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
14711 	else
14712 	  r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
14713 	r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
14714 
14715 	if (r != error_mark_node)
14716 	  /* Will this ever be needed for TYPE_..._TO values?  */
14717 	  layout_type (r);
14718 
14719 	return r;
14720       }
14721     case OFFSET_TYPE:
14722       {
14723 	r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
14724 	if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
14725 	  {
14726 	    /* [temp.deduct]
14727 
14728 	       Type deduction may fail for any of the following
14729 	       reasons:
14730 
14731 	       -- Attempting to create "pointer to member of T" when T
14732 		  is not a class type.  */
14733 	    if (complain & tf_error)
14734 	      error ("creating pointer to member of non-class type %qT", r);
14735 	    return error_mark_node;
14736 	  }
14737 	if (TREE_CODE (type) == REFERENCE_TYPE)
14738 	  {
14739 	    if (complain & tf_error)
14740 	      error ("creating pointer to member reference type %qT", type);
14741 	    return error_mark_node;
14742 	  }
14743 	if (VOID_TYPE_P (type))
14744 	  {
14745 	    if (complain & tf_error)
14746 	      error ("creating pointer to member of type void");
14747 	    return error_mark_node;
14748 	  }
14749 	gcc_assert (TREE_CODE (type) != METHOD_TYPE);
14750 	if (TREE_CODE (type) == FUNCTION_TYPE)
14751 	  {
14752 	    /* The type of the implicit object parameter gets its
14753 	       cv-qualifiers from the FUNCTION_TYPE. */
14754 	    tree memptr;
14755 	    tree method_type
14756 	      = build_memfn_type (type, r, type_memfn_quals (type),
14757 				  type_memfn_rqual (type));
14758 	    memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
14759 	    return cp_build_qualified_type_real (memptr, cp_type_quals (t),
14760 						 complain);
14761 	  }
14762 	else
14763 	  return cp_build_qualified_type_real (build_ptrmem_type (r, type),
14764 					       cp_type_quals (t),
14765 					       complain);
14766       }
14767     case FUNCTION_TYPE:
14768     case METHOD_TYPE:
14769       {
14770 	tree fntype;
14771 	tree specs;
14772 	fntype = tsubst_function_type (t, args, complain, in_decl);
14773 	if (fntype == error_mark_node)
14774 	  return error_mark_node;
14775 
14776 	/* Substitute the exception specification.  */
14777 	specs = tsubst_exception_specification (t, args, complain, in_decl,
14778 						/*defer_ok*/fndecl_type);
14779 	if (specs == error_mark_node)
14780 	  return error_mark_node;
14781 	if (specs)
14782 	  fntype = build_exception_variant (fntype, specs);
14783 	return fntype;
14784       }
14785     case ARRAY_TYPE:
14786       {
14787 	tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
14788 	if (domain == error_mark_node)
14789 	  return error_mark_node;
14790 
14791 	/* As an optimization, we avoid regenerating the array type if
14792 	   it will obviously be the same as T.  */
14793 	if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
14794 	  return t;
14795 
14796 	/* These checks should match the ones in create_array_type_for_decl.
14797 
14798 	   [temp.deduct]
14799 
14800 	   The deduction may fail for any of the following reasons:
14801 
14802 	   -- Attempting to create an array with an element type that
14803 	      is void, a function type, or a reference type, or [DR337]
14804 	      an abstract class type.  */
14805 	if (VOID_TYPE_P (type)
14806 	    || TREE_CODE (type) == FUNCTION_TYPE
14807 	    || (TREE_CODE (type) == ARRAY_TYPE
14808 		&& TYPE_DOMAIN (type) == NULL_TREE)
14809 	    || TREE_CODE (type) == REFERENCE_TYPE)
14810 	  {
14811 	    if (complain & tf_error)
14812 	      error ("creating array of %qT", type);
14813 	    return error_mark_node;
14814 	  }
14815 
14816 	if (abstract_virtuals_error_sfinae (ACU_ARRAY, type, complain))
14817 	  return error_mark_node;
14818 
14819 	r = build_cplus_array_type (type, domain);
14820 
14821 	if (TYPE_USER_ALIGN (t))
14822 	  {
14823 	    SET_TYPE_ALIGN (r, TYPE_ALIGN (t));
14824 	    TYPE_USER_ALIGN (r) = 1;
14825 	  }
14826 
14827 	return r;
14828       }
14829 
14830     case TYPENAME_TYPE:
14831       {
14832 	tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
14833 				     in_decl, /*entering_scope=*/1);
14834 	if (ctx == error_mark_node)
14835 	  return error_mark_node;
14836 
14837 	tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
14838 			      complain, in_decl);
14839 	if (f == error_mark_node)
14840 	  return error_mark_node;
14841 
14842 	if (!MAYBE_CLASS_TYPE_P (ctx))
14843 	  {
14844 	    if (complain & tf_error)
14845 	      error ("%qT is not a class, struct, or union type", ctx);
14846 	    return error_mark_node;
14847 	  }
14848 	else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
14849 	  {
14850 	    /* Normally, make_typename_type does not require that the CTX
14851 	       have complete type in order to allow things like:
14852 
14853 		 template <class T> struct S { typename S<T>::X Y; };
14854 
14855 	       But, such constructs have already been resolved by this
14856 	       point, so here CTX really should have complete type, unless
14857 	       it's a partial instantiation.  */
14858 	    ctx = complete_type (ctx);
14859 	    if (!COMPLETE_TYPE_P (ctx))
14860 	      {
14861 		if (complain & tf_error)
14862 		  cxx_incomplete_type_error (NULL_TREE, ctx);
14863 		return error_mark_node;
14864 	      }
14865 	  }
14866 
14867 	f = make_typename_type (ctx, f, typename_type,
14868 				complain | tf_keep_type_decl);
14869 	if (f == error_mark_node)
14870 	  return f;
14871 	if (TREE_CODE (f) == TYPE_DECL)
14872 	  {
14873 	    complain |= tf_ignore_bad_quals;
14874 	    f = TREE_TYPE (f);
14875 	  }
14876 
14877 	if (TREE_CODE (f) != TYPENAME_TYPE)
14878 	  {
14879 	    if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
14880 	      {
14881 		if (complain & tf_error)
14882 		  error ("%qT resolves to %qT, which is not an enumeration type",
14883 			 t, f);
14884 		else
14885 		  return error_mark_node;
14886 	      }
14887 	    else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
14888 	      {
14889 		if (complain & tf_error)
14890 		  error ("%qT resolves to %qT, which is is not a class type",
14891 			 t, f);
14892 		else
14893 		  return error_mark_node;
14894 	      }
14895 	  }
14896 
14897 	return cp_build_qualified_type_real
14898 	  (f, cp_type_quals (f) | cp_type_quals (t), complain);
14899       }
14900 
14901     case UNBOUND_CLASS_TEMPLATE:
14902       {
14903 	tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
14904 				     in_decl, /*entering_scope=*/1);
14905 	tree name = TYPE_IDENTIFIER (t);
14906 	tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
14907 
14908 	if (ctx == error_mark_node || name == error_mark_node)
14909 	  return error_mark_node;
14910 
14911 	if (parm_list)
14912 	  parm_list = tsubst_template_parms (parm_list, args, complain);
14913 	return make_unbound_class_template (ctx, name, parm_list, complain);
14914       }
14915 
14916     case TYPEOF_TYPE:
14917       {
14918 	tree type;
14919 
14920 	++cp_unevaluated_operand;
14921 	++c_inhibit_evaluation_warnings;
14922 
14923 	type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
14924 			    complain, in_decl,
14925 			    /*integral_constant_expression_p=*/false);
14926 
14927 	--cp_unevaluated_operand;
14928 	--c_inhibit_evaluation_warnings;
14929 
14930 	type = finish_typeof (type);
14931 	return cp_build_qualified_type_real (type,
14932 					     cp_type_quals (t)
14933 					     | cp_type_quals (type),
14934 					     complain);
14935       }
14936 
14937     case DECLTYPE_TYPE:
14938       {
14939 	tree type;
14940 
14941 	++cp_unevaluated_operand;
14942 	++c_inhibit_evaluation_warnings;
14943 
14944 	type = tsubst_copy_and_build (DECLTYPE_TYPE_EXPR (t), args,
14945 				      complain|tf_decltype, in_decl,
14946 				      /*function_p*/false,
14947 				      /*integral_constant_expression*/false);
14948 
14949 	if (DECLTYPE_FOR_INIT_CAPTURE (t))
14950 	  {
14951 	    if (type == NULL_TREE)
14952 	      {
14953 		if (complain & tf_error)
14954 		  error ("empty initializer in lambda init-capture");
14955 		type = error_mark_node;
14956 	      }
14957 	    else if (TREE_CODE (type) == TREE_LIST)
14958 	      type = build_x_compound_expr_from_list (type, ELK_INIT, complain);
14959 	  }
14960 
14961 	--cp_unevaluated_operand;
14962 	--c_inhibit_evaluation_warnings;
14963 
14964 	if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
14965 	  type = lambda_capture_field_type (type,
14966 					    DECLTYPE_FOR_INIT_CAPTURE (t),
14967 					    DECLTYPE_FOR_REF_CAPTURE (t));
14968 	else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
14969 	  type = lambda_proxy_type (type);
14970 	else
14971 	  {
14972 	    bool id = DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t);
14973 	    if (id && TREE_CODE (DECLTYPE_TYPE_EXPR (t)) == BIT_NOT_EXPR
14974 		&& EXPR_P (type))
14975 	      /* In a template ~id could be either a complement expression
14976 		 or an unqualified-id naming a destructor; if instantiating
14977 		 it produces an expression, it's not an id-expression or
14978 		 member access.  */
14979 	      id = false;
14980 	    type = finish_decltype_type (type, id, complain);
14981 	  }
14982 	return cp_build_qualified_type_real (type,
14983 					     cp_type_quals (t)
14984 					     | cp_type_quals (type),
14985 					     complain | tf_ignore_bad_quals);
14986       }
14987 
14988     case UNDERLYING_TYPE:
14989       {
14990 	tree type = tsubst (UNDERLYING_TYPE_TYPE (t), args,
14991 			    complain, in_decl);
14992 	return finish_underlying_type (type);
14993       }
14994 
14995     case TYPE_ARGUMENT_PACK:
14996     case NONTYPE_ARGUMENT_PACK:
14997       {
14998         tree r;
14999 
15000 	if (code == NONTYPE_ARGUMENT_PACK)
15001 	  r = make_node (code);
15002 	else
15003 	  r = cxx_make_type (code);
15004 
15005 	tree pack_args = ARGUMENT_PACK_ARGS (t);
15006 	pack_args = tsubst_template_args (pack_args, args, complain, in_decl);
15007 	SET_ARGUMENT_PACK_ARGS (r, pack_args);
15008 
15009 	return r;
15010       }
15011 
15012     case VOID_CST:
15013     case INTEGER_CST:
15014     case REAL_CST:
15015     case STRING_CST:
15016     case PLUS_EXPR:
15017     case MINUS_EXPR:
15018     case NEGATE_EXPR:
15019     case NOP_EXPR:
15020     case INDIRECT_REF:
15021     case ADDR_EXPR:
15022     case CALL_EXPR:
15023     case ARRAY_REF:
15024     case SCOPE_REF:
15025       /* We should use one of the expression tsubsts for these codes.  */
15026       gcc_unreachable ();
15027 
15028     default:
15029       sorry ("use of %qs in template", get_tree_code_name (code));
15030       return error_mark_node;
15031     }
15032 }
15033 
15034 /* tsubst a BASELINK.  OBJECT_TYPE, if non-NULL, is the type of the
15035    expression on the left-hand side of the "." or "->" operator.  We
15036    only do the lookup if we had a dependent BASELINK.  Otherwise we
15037    adjust it onto the instantiated heirarchy.  */
15038 
15039 static tree
tsubst_baselink(tree baselink,tree object_type,tree args,tsubst_flags_t complain,tree in_decl)15040 tsubst_baselink (tree baselink, tree object_type,
15041 		 tree args, tsubst_flags_t complain, tree in_decl)
15042 {
15043   bool qualified_p = BASELINK_QUALIFIED_P (baselink);
15044   tree qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
15045   qualifying_scope = tsubst (qualifying_scope, args, complain, in_decl);
15046 
15047   tree optype = BASELINK_OPTYPE (baselink);
15048   optype = tsubst (optype, args, complain, in_decl);
15049 
15050   tree template_args = NULL_TREE;
15051   bool template_id_p = false;
15052   tree fns = BASELINK_FUNCTIONS (baselink);
15053   if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
15054     {
15055       template_id_p = true;
15056       template_args = TREE_OPERAND (fns, 1);
15057       fns = TREE_OPERAND (fns, 0);
15058       if (template_args)
15059 	template_args = tsubst_template_args (template_args, args,
15060 					      complain, in_decl);
15061     }
15062 
15063   tree binfo_type = BINFO_TYPE (BASELINK_BINFO (baselink));
15064   binfo_type = tsubst (binfo_type, args, complain, in_decl);
15065   bool dependent_p = binfo_type != BINFO_TYPE (BASELINK_BINFO (baselink));
15066 
15067   if (dependent_p)
15068     {
15069       tree name = OVL_NAME (fns);
15070       if (IDENTIFIER_CONV_OP_P (name))
15071 	name = make_conv_op_name (optype);
15072 
15073       if (name == complete_dtor_identifier)
15074 	/* Treat as-if non-dependent below.  */
15075 	dependent_p = false;
15076 
15077       baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
15078       if (!baselink)
15079 	{
15080 	  if ((complain & tf_error)
15081 	      && constructor_name_p (name, qualifying_scope))
15082 	    error ("cannot call constructor %<%T::%D%> directly",
15083 		   qualifying_scope, name);
15084 	  return error_mark_node;
15085 	}
15086 
15087       if (BASELINK_P (baselink))
15088 	fns = BASELINK_FUNCTIONS (baselink);
15089     }
15090   else
15091     /* We're going to overwrite pieces below, make a duplicate.  */
15092     baselink = copy_node (baselink);
15093 
15094   /* If lookup found a single function, mark it as used at this point.
15095      (If lookup found multiple functions the one selected later by
15096      overload resolution will be marked as used at that point.)  */
15097   if (!template_id_p && !really_overloaded_fn (fns))
15098     {
15099       tree fn = OVL_FIRST (fns);
15100       bool ok = mark_used (fn, complain);
15101       if (!ok && !(complain & tf_error))
15102 	return error_mark_node;
15103       if (ok && BASELINK_P (baselink))
15104 	/* We might have instantiated an auto function.  */
15105 	TREE_TYPE (baselink) = TREE_TYPE (fn);
15106     }
15107 
15108   if (BASELINK_P (baselink))
15109     {
15110       /* Add back the template arguments, if present.  */
15111       if (template_id_p)
15112 	BASELINK_FUNCTIONS (baselink)
15113 	  = build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, template_args);
15114 
15115       /* Update the conversion operator type.  */
15116       BASELINK_OPTYPE (baselink) = optype;
15117     }
15118 
15119   if (!object_type)
15120     object_type = current_class_type;
15121 
15122   if (qualified_p || !dependent_p)
15123     {
15124       baselink = adjust_result_of_qualified_name_lookup (baselink,
15125 							 qualifying_scope,
15126 							 object_type);
15127       if (!qualified_p)
15128 	/* We need to call adjust_result_of_qualified_name_lookup in case the
15129 	   destructor names a base class, but we unset BASELINK_QUALIFIED_P
15130 	   so that we still get virtual function binding.  */
15131 	BASELINK_QUALIFIED_P (baselink) = false;
15132     }
15133 
15134   return baselink;
15135 }
15136 
15137 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
15138    true if the qualified-id will be a postfix-expression in-and-of
15139    itself; false if more of the postfix-expression follows the
15140    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
15141    of "&".  */
15142 
15143 static tree
tsubst_qualified_id(tree qualified_id,tree args,tsubst_flags_t complain,tree in_decl,bool done,bool address_p)15144 tsubst_qualified_id (tree qualified_id, tree args,
15145 		     tsubst_flags_t complain, tree in_decl,
15146 		     bool done, bool address_p)
15147 {
15148   tree expr;
15149   tree scope;
15150   tree name;
15151   bool is_template;
15152   tree template_args;
15153   location_t loc = UNKNOWN_LOCATION;
15154 
15155   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
15156 
15157   /* Figure out what name to look up.  */
15158   name = TREE_OPERAND (qualified_id, 1);
15159   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
15160     {
15161       is_template = true;
15162       loc = EXPR_LOCATION (name);
15163       template_args = TREE_OPERAND (name, 1);
15164       if (template_args)
15165 	template_args = tsubst_template_args (template_args, args,
15166 					      complain, in_decl);
15167       if (template_args == error_mark_node)
15168 	return error_mark_node;
15169       name = TREE_OPERAND (name, 0);
15170     }
15171   else
15172     {
15173       is_template = false;
15174       template_args = NULL_TREE;
15175     }
15176 
15177   /* Substitute into the qualifying scope.  When there are no ARGS, we
15178      are just trying to simplify a non-dependent expression.  In that
15179      case the qualifying scope may be dependent, and, in any case,
15180      substituting will not help.  */
15181   scope = TREE_OPERAND (qualified_id, 0);
15182   if (args)
15183     {
15184       scope = tsubst (scope, args, complain, in_decl);
15185       expr = tsubst_copy (name, args, complain, in_decl);
15186     }
15187   else
15188     expr = name;
15189 
15190   if (dependent_scope_p (scope))
15191     {
15192       if (is_template)
15193 	expr = build_min_nt_loc (loc, TEMPLATE_ID_EXPR, expr, template_args);
15194       tree r = build_qualified_name (NULL_TREE, scope, expr,
15195 				     QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
15196       REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (qualified_id);
15197       return r;
15198     }
15199 
15200   if (!BASELINK_P (name) && !DECL_P (expr))
15201     {
15202       if (TREE_CODE (expr) == BIT_NOT_EXPR)
15203 	{
15204 	  /* A BIT_NOT_EXPR is used to represent a destructor.  */
15205 	  if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
15206 	    {
15207 	      error ("qualifying type %qT does not match destructor name ~%qT",
15208 		     scope, TREE_OPERAND (expr, 0));
15209 	      expr = error_mark_node;
15210 	    }
15211 	  else
15212 	    expr = lookup_qualified_name (scope, complete_dtor_identifier,
15213 					  /*is_type_p=*/0, false);
15214 	}
15215       else
15216 	expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
15217       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
15218 		     ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
15219 	{
15220 	  if (complain & tf_error)
15221 	    {
15222 	      error ("dependent-name %qE is parsed as a non-type, but "
15223 		     "instantiation yields a type", qualified_id);
15224 	      inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
15225 	    }
15226 	  return error_mark_node;
15227 	}
15228     }
15229 
15230   if (DECL_P (expr))
15231     {
15232       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
15233 					   scope);
15234       /* Remember that there was a reference to this entity.  */
15235       if (!mark_used (expr, complain) && !(complain & tf_error))
15236 	return error_mark_node;
15237     }
15238 
15239   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
15240     {
15241       if (complain & tf_error)
15242 	qualified_name_lookup_error (scope,
15243 				     TREE_OPERAND (qualified_id, 1),
15244 				     expr, input_location);
15245       return error_mark_node;
15246     }
15247 
15248   if (is_template)
15249     {
15250       /* We may be repeating a check already done during parsing, but
15251 	 if it was well-formed and passed then, it will pass again
15252 	 now, and if it didn't, we wouldn't have got here.  The case
15253 	 we want to catch is when we couldn't tell then, and can now,
15254 	 namely when templ prior to substitution was an
15255 	 identifier.  */
15256       if (flag_concepts && check_auto_in_tmpl_args (expr, template_args))
15257 	return error_mark_node;
15258 
15259       if (variable_template_p (expr))
15260 	expr = lookup_and_finish_template_variable (expr, template_args,
15261 						    complain);
15262       else
15263 	expr = lookup_template_function (expr, template_args);
15264     }
15265 
15266   if (expr == error_mark_node && complain & tf_error)
15267     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
15268 				 expr, input_location);
15269   else if (TYPE_P (scope))
15270     {
15271       expr = (adjust_result_of_qualified_name_lookup
15272 	      (expr, scope, current_nonlambda_class_type ()));
15273       expr = (finish_qualified_id_expr
15274 	      (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
15275 	       QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
15276 	       /*template_arg_p=*/false, complain));
15277     }
15278 
15279   /* Expressions do not generally have reference type.  */
15280   if (TREE_CODE (expr) != SCOPE_REF
15281       /* However, if we're about to form a pointer-to-member, we just
15282 	 want the referenced member referenced.  */
15283       && TREE_CODE (expr) != OFFSET_REF)
15284     expr = convert_from_reference (expr);
15285 
15286   if (REF_PARENTHESIZED_P (qualified_id))
15287     expr = force_paren_expr (expr);
15288 
15289   return expr;
15290 }
15291 
15292 /* tsubst the initializer for a VAR_DECL.  INIT is the unsubstituted
15293    initializer, DECL is the substituted VAR_DECL.  Other arguments are as
15294    for tsubst.  */
15295 
15296 static tree
tsubst_init(tree init,tree decl,tree args,tsubst_flags_t complain,tree in_decl)15297 tsubst_init (tree init, tree decl, tree args,
15298 	     tsubst_flags_t complain, tree in_decl)
15299 {
15300   if (!init)
15301     return NULL_TREE;
15302 
15303   init = tsubst_expr (init, args, complain, in_decl, false);
15304 
15305   if (!init && TREE_TYPE (decl) != error_mark_node)
15306     {
15307       /* If we had an initializer but it
15308 	 instantiated to nothing,
15309 	 value-initialize the object.  This will
15310 	 only occur when the initializer was a
15311 	 pack expansion where the parameter packs
15312 	 used in that expansion were of length
15313 	 zero.  */
15314       init = build_value_init (TREE_TYPE (decl),
15315 			       complain);
15316       if (TREE_CODE (init) == AGGR_INIT_EXPR)
15317 	init = get_target_expr_sfinae (init, complain);
15318       if (TREE_CODE (init) == TARGET_EXPR)
15319 	TARGET_EXPR_DIRECT_INIT_P (init) = true;
15320     }
15321 
15322   return init;
15323 }
15324 
15325 /* Like tsubst, but deals with expressions.  This function just replaces
15326    template parms; to finish processing the resultant expression, use
15327    tsubst_copy_and_build or tsubst_expr.  */
15328 
15329 static tree
tsubst_copy(tree t,tree args,tsubst_flags_t complain,tree in_decl)15330 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
15331 {
15332   enum tree_code code;
15333   tree r;
15334 
15335   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
15336     return t;
15337 
15338   code = TREE_CODE (t);
15339 
15340   switch (code)
15341     {
15342     case PARM_DECL:
15343       r = retrieve_local_specialization (t);
15344 
15345       if (r == NULL_TREE)
15346 	{
15347 	  /* We get here for a use of 'this' in an NSDMI.  */
15348 	  if (DECL_NAME (t) == this_identifier && current_class_ptr)
15349 	    return current_class_ptr;
15350 
15351 	  /* This can happen for a parameter name used later in a function
15352 	     declaration (such as in a late-specified return type).  Just
15353 	     make a dummy decl, since it's only used for its type.  */
15354 	  gcc_assert (cp_unevaluated_operand != 0);
15355 	  r = tsubst_decl (t, args, complain);
15356 	  /* Give it the template pattern as its context; its true context
15357 	     hasn't been instantiated yet and this is good enough for
15358 	     mangling.  */
15359 	  DECL_CONTEXT (r) = DECL_CONTEXT (t);
15360 	}
15361 
15362       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
15363 	r = argument_pack_select_arg (r);
15364       if (!mark_used (r, complain) && !(complain & tf_error))
15365 	return error_mark_node;
15366       return r;
15367 
15368     case CONST_DECL:
15369       {
15370 	tree enum_type;
15371 	tree v;
15372 
15373 	if (DECL_TEMPLATE_PARM_P (t))
15374 	  return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
15375 	/* There is no need to substitute into namespace-scope
15376 	   enumerators.  */
15377 	if (DECL_NAMESPACE_SCOPE_P (t))
15378 	  return t;
15379 	/* If ARGS is NULL, then T is known to be non-dependent.  */
15380 	if (args == NULL_TREE)
15381 	  return scalar_constant_value (t);
15382 
15383 	/* Unfortunately, we cannot just call lookup_name here.
15384 	   Consider:
15385 
15386 	     template <int I> int f() {
15387 	     enum E { a = I };
15388 	     struct S { void g() { E e = a; } };
15389 	     };
15390 
15391 	   When we instantiate f<7>::S::g(), say, lookup_name is not
15392 	   clever enough to find f<7>::a.  */
15393 	enum_type
15394 	  = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
15395 			      /*entering_scope=*/0);
15396 
15397 	for (v = TYPE_VALUES (enum_type);
15398 	     v != NULL_TREE;
15399 	     v = TREE_CHAIN (v))
15400 	  if (TREE_PURPOSE (v) == DECL_NAME (t))
15401 	    return TREE_VALUE (v);
15402 
15403 	  /* We didn't find the name.  That should never happen; if
15404 	     name-lookup found it during preliminary parsing, we
15405 	     should find it again here during instantiation.  */
15406 	gcc_unreachable ();
15407       }
15408       return t;
15409 
15410     case FIELD_DECL:
15411       if (DECL_CONTEXT (t))
15412 	{
15413 	  tree ctx;
15414 
15415 	  ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
15416 				  /*entering_scope=*/1);
15417 	  if (ctx != DECL_CONTEXT (t))
15418 	    {
15419 	      tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
15420 	      if (!r)
15421 		{
15422 		  if (complain & tf_error)
15423 		    error ("using invalid field %qD", t);
15424 		  return error_mark_node;
15425 		}
15426 	      return r;
15427 	    }
15428 	}
15429 
15430       return t;
15431 
15432     case VAR_DECL:
15433     case FUNCTION_DECL:
15434       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
15435 	r = tsubst (t, args, complain, in_decl);
15436       else if (local_variable_p (t)
15437 	       && uses_template_parms (DECL_CONTEXT (t)))
15438 	{
15439 	  r = retrieve_local_specialization (t);
15440 	  if (r == NULL_TREE)
15441 	    {
15442 	      /* First try name lookup to find the instantiation.  */
15443 	      r = lookup_name (DECL_NAME (t));
15444 	      if (r && !is_capture_proxy (r))
15445 		{
15446 		  /* Make sure that the one we found is the one we want.  */
15447 		  tree ctx = enclosing_instantiation_of (DECL_CONTEXT (t));
15448 		  if (ctx != DECL_CONTEXT (r))
15449 		    r = NULL_TREE;
15450 		}
15451 
15452 	      if (r)
15453 		/* OK */;
15454 	      else
15455 		{
15456 		  /* This can happen for a variable used in a
15457 		     late-specified return type of a local lambda, or for a
15458 		     local static or constant.  Building a new VAR_DECL
15459 		     should be OK in all those cases.  */
15460 		  r = tsubst_decl (t, args, complain);
15461 		  if (local_specializations)
15462 		    /* Avoid infinite recursion (79640).  */
15463 		    register_local_specialization (r, t);
15464 		  if (decl_maybe_constant_var_p (r))
15465 		    {
15466 		      /* We can't call cp_finish_decl, so handle the
15467 			 initializer by hand.  */
15468 		      tree init = tsubst_init (DECL_INITIAL (t), r, args,
15469 					       complain, in_decl);
15470 		      if (!processing_template_decl)
15471 			init = maybe_constant_init (init);
15472 		      if (processing_template_decl
15473 			  ? potential_constant_expression (init)
15474 			  : reduced_constant_expression_p (init))
15475 			DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
15476 			  = TREE_CONSTANT (r) = true;
15477 		      DECL_INITIAL (r) = init;
15478 		      if (tree auto_node = type_uses_auto (TREE_TYPE (r)))
15479 			TREE_TYPE (r)
15480 			  = do_auto_deduction (TREE_TYPE (r), init, auto_node,
15481 					       complain, adc_variable_type);
15482 		    }
15483 		  gcc_assert (cp_unevaluated_operand || TREE_STATIC (r)
15484 			      || decl_constant_var_p (r)
15485 			      || errorcount || sorrycount);
15486 		  if (!processing_template_decl
15487 		      && !TREE_STATIC (r))
15488 		    r = process_outer_var_ref (r, complain);
15489 		}
15490 	      /* Remember this for subsequent uses.  */
15491 	      if (local_specializations)
15492 		register_local_specialization (r, t);
15493 	    }
15494 	  if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
15495 	    r = argument_pack_select_arg (r);
15496 	}
15497       else
15498 	r = t;
15499       if (!mark_used (r, complain))
15500 	return error_mark_node;
15501       return r;
15502 
15503     case NAMESPACE_DECL:
15504       return t;
15505 
15506     case OVERLOAD:
15507       /* An OVERLOAD will always be a non-dependent overload set; an
15508 	 overload set from function scope will just be represented with an
15509 	 IDENTIFIER_NODE, and from class scope with a BASELINK.  */
15510       gcc_assert (!uses_template_parms (t));
15511       /* We must have marked any lookups as persistent.  */
15512       gcc_assert (!OVL_LOOKUP_P (t) || OVL_USED_P (t));
15513       return t;
15514 
15515     case BASELINK:
15516       return tsubst_baselink (t, current_nonlambda_class_type (),
15517 			      args, complain, in_decl);
15518 
15519     case TEMPLATE_DECL:
15520       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
15521 	return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
15522 		       args, complain, in_decl);
15523       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
15524 	return tsubst (t, args, complain, in_decl);
15525       else if (DECL_CLASS_SCOPE_P (t)
15526 	       && uses_template_parms (DECL_CONTEXT (t)))
15527 	{
15528 	  /* Template template argument like the following example need
15529 	     special treatment:
15530 
15531 	       template <template <class> class TT> struct C {};
15532 	       template <class T> struct D {
15533 		 template <class U> struct E {};
15534 		 C<E> c;				// #1
15535 	       };
15536 	       D<int> d;				// #2
15537 
15538 	     We are processing the template argument `E' in #1 for
15539 	     the template instantiation #2.  Originally, `E' is a
15540 	     TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
15541 	     have to substitute this with one having context `D<int>'.  */
15542 
15543 	  tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
15544 	  if (dependent_scope_p (context))
15545 	    {
15546 	      /* When rewriting a constructor into a deduction guide, a
15547 		 non-dependent name can become dependent, so memtmpl<args>
15548 		 becomes context::template memtmpl<args>.  */
15549 	      tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15550 	      return build_qualified_name (type, context, DECL_NAME (t),
15551 					   /*template*/true);
15552 	    }
15553 	  return lookup_field (context, DECL_NAME(t), 0, false);
15554 	}
15555       else
15556 	/* Ordinary template template argument.  */
15557 	return t;
15558 
15559     case NON_LVALUE_EXPR:
15560     case VIEW_CONVERT_EXPR:
15561 	{
15562 	  /* Handle location wrappers by substituting the wrapped node
15563 	     first, *then* reusing the resulting type.  Doing the type
15564 	     first ensures that we handle template parameters and
15565 	     parameter pack expansions.  */
15566 	  gcc_assert (location_wrapper_p (t));
15567 	  tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15568 	  return maybe_wrap_with_location (op0, EXPR_LOCATION (t));
15569 	}
15570 
15571     case CAST_EXPR:
15572     case REINTERPRET_CAST_EXPR:
15573     case CONST_CAST_EXPR:
15574     case STATIC_CAST_EXPR:
15575     case DYNAMIC_CAST_EXPR:
15576     case IMPLICIT_CONV_EXPR:
15577     case CONVERT_EXPR:
15578     case NOP_EXPR:
15579       {
15580 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15581 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15582 	return build1 (code, type, op0);
15583       }
15584 
15585     case SIZEOF_EXPR:
15586       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
15587 	  || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
15588         {
15589           tree expanded, op = TREE_OPERAND (t, 0);
15590 	  int len = 0;
15591 
15592 	  if (SIZEOF_EXPR_TYPE_P (t))
15593 	    op = TREE_TYPE (op);
15594 
15595 	  ++cp_unevaluated_operand;
15596 	  ++c_inhibit_evaluation_warnings;
15597 	  /* We only want to compute the number of arguments.  */
15598 	  if (PACK_EXPANSION_P (op))
15599 	    expanded = tsubst_pack_expansion (op, args, complain, in_decl);
15600 	  else
15601 	    expanded = tsubst_template_args (ARGUMENT_PACK_ARGS (op),
15602 					     args, complain, in_decl);
15603 	  --cp_unevaluated_operand;
15604 	  --c_inhibit_evaluation_warnings;
15605 
15606 	  if (TREE_CODE (expanded) == TREE_VEC)
15607 	    {
15608 	      len = TREE_VEC_LENGTH (expanded);
15609 	      /* Set TREE_USED for the benefit of -Wunused.  */
15610 	      for (int i = 0; i < len; i++)
15611 		if (DECL_P (TREE_VEC_ELT (expanded, i)))
15612 		  TREE_USED (TREE_VEC_ELT (expanded, i)) = true;
15613 	    }
15614 
15615 	  if (expanded == error_mark_node)
15616 	    return error_mark_node;
15617 	  else if (PACK_EXPANSION_P (expanded)
15618 		   || (TREE_CODE (expanded) == TREE_VEC
15619 		       && pack_expansion_args_count (expanded)))
15620 
15621 	    {
15622 	      if (PACK_EXPANSION_P (expanded))
15623 		/* OK.  */;
15624 	      else if (TREE_VEC_LENGTH (expanded) == 1)
15625 		expanded = TREE_VEC_ELT (expanded, 0);
15626 	      else
15627 		expanded = make_argument_pack (expanded);
15628 
15629 	      if (TYPE_P (expanded))
15630 		return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR,
15631 						   false,
15632 						   complain & tf_error);
15633 	      else
15634 		return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
15635                                                    complain & tf_error);
15636 	    }
15637 	  else
15638 	    return build_int_cst (size_type_node, len);
15639         }
15640       if (SIZEOF_EXPR_TYPE_P (t))
15641 	{
15642 	  r = tsubst (TREE_TYPE (TREE_OPERAND (t, 0)),
15643 		      args, complain, in_decl);
15644 	  r = build1 (NOP_EXPR, r, error_mark_node);
15645 	  r = build1 (SIZEOF_EXPR,
15646 		      tsubst (TREE_TYPE (t), args, complain, in_decl), r);
15647 	  SIZEOF_EXPR_TYPE_P (r) = 1;
15648 	  return r;
15649 	}
15650       /* Fall through */
15651 
15652     case INDIRECT_REF:
15653     case NEGATE_EXPR:
15654     case TRUTH_NOT_EXPR:
15655     case BIT_NOT_EXPR:
15656     case ADDR_EXPR:
15657     case UNARY_PLUS_EXPR:      /* Unary + */
15658     case ALIGNOF_EXPR:
15659     case AT_ENCODE_EXPR:
15660     case ARROW_EXPR:
15661     case THROW_EXPR:
15662     case TYPEID_EXPR:
15663     case REALPART_EXPR:
15664     case IMAGPART_EXPR:
15665     case PAREN_EXPR:
15666       {
15667 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15668 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15669 	r = build1 (code, type, op0);
15670 	if (code == ALIGNOF_EXPR)
15671 	  ALIGNOF_EXPR_STD_P (r) = ALIGNOF_EXPR_STD_P (t);
15672 	return r;
15673       }
15674 
15675     case COMPONENT_REF:
15676       {
15677 	tree object;
15678 	tree name;
15679 
15680 	object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15681 	name = TREE_OPERAND (t, 1);
15682 	if (TREE_CODE (name) == BIT_NOT_EXPR)
15683 	  {
15684 	    name = tsubst_copy (TREE_OPERAND (name, 0), args,
15685 				complain, in_decl);
15686 	    name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
15687 	  }
15688 	else if (TREE_CODE (name) == SCOPE_REF
15689 		 && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
15690 	  {
15691 	    tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
15692 				     complain, in_decl);
15693 	    name = TREE_OPERAND (name, 1);
15694 	    name = tsubst_copy (TREE_OPERAND (name, 0), args,
15695 				complain, in_decl);
15696 	    name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
15697 	    name = build_qualified_name (/*type=*/NULL_TREE,
15698 					 base, name,
15699 					 /*template_p=*/false);
15700 	  }
15701 	else if (BASELINK_P (name))
15702 	  name = tsubst_baselink (name,
15703 				  non_reference (TREE_TYPE (object)),
15704 				  args, complain,
15705 				  in_decl);
15706 	else
15707 	  name = tsubst_copy (name, args, complain, in_decl);
15708 	return build_nt (COMPONENT_REF, object, name, NULL_TREE);
15709       }
15710 
15711     case PLUS_EXPR:
15712     case MINUS_EXPR:
15713     case MULT_EXPR:
15714     case TRUNC_DIV_EXPR:
15715     case CEIL_DIV_EXPR:
15716     case FLOOR_DIV_EXPR:
15717     case ROUND_DIV_EXPR:
15718     case EXACT_DIV_EXPR:
15719     case BIT_AND_EXPR:
15720     case BIT_IOR_EXPR:
15721     case BIT_XOR_EXPR:
15722     case TRUNC_MOD_EXPR:
15723     case FLOOR_MOD_EXPR:
15724     case TRUTH_ANDIF_EXPR:
15725     case TRUTH_ORIF_EXPR:
15726     case TRUTH_AND_EXPR:
15727     case TRUTH_OR_EXPR:
15728     case RSHIFT_EXPR:
15729     case LSHIFT_EXPR:
15730     case RROTATE_EXPR:
15731     case LROTATE_EXPR:
15732     case EQ_EXPR:
15733     case NE_EXPR:
15734     case MAX_EXPR:
15735     case MIN_EXPR:
15736     case LE_EXPR:
15737     case GE_EXPR:
15738     case LT_EXPR:
15739     case GT_EXPR:
15740     case COMPOUND_EXPR:
15741     case DOTSTAR_EXPR:
15742     case MEMBER_REF:
15743     case PREDECREMENT_EXPR:
15744     case PREINCREMENT_EXPR:
15745     case POSTDECREMENT_EXPR:
15746     case POSTINCREMENT_EXPR:
15747       {
15748 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15749 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15750 	return build_nt (code, op0, op1);
15751       }
15752 
15753     case SCOPE_REF:
15754       {
15755 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15756 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15757 	return build_qualified_name (/*type=*/NULL_TREE, op0, op1,
15758 				     QUALIFIED_NAME_IS_TEMPLATE (t));
15759       }
15760 
15761     case ARRAY_REF:
15762       {
15763 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15764 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15765 	return build_nt (ARRAY_REF, op0, op1, NULL_TREE, NULL_TREE);
15766       }
15767 
15768     case CALL_EXPR:
15769       {
15770 	int n = VL_EXP_OPERAND_LENGTH (t);
15771 	tree result = build_vl_exp (CALL_EXPR, n);
15772 	int i;
15773 	for (i = 0; i < n; i++)
15774 	  TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
15775 					     complain, in_decl);
15776 	return result;
15777       }
15778 
15779     case COND_EXPR:
15780     case MODOP_EXPR:
15781     case PSEUDO_DTOR_EXPR:
15782     case VEC_PERM_EXPR:
15783       {
15784 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15785 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15786 	tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
15787 	r = build_nt (code, op0, op1, op2);
15788 	TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
15789 	return r;
15790       }
15791 
15792     case NEW_EXPR:
15793       {
15794 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15795 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15796 	tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
15797 	r = build_nt (code, op0, op1, op2);
15798 	NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
15799 	return r;
15800       }
15801 
15802     case DELETE_EXPR:
15803       {
15804 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15805 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15806 	r = build_nt (code, op0, op1);
15807 	DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
15808 	DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
15809 	return r;
15810       }
15811 
15812     case TEMPLATE_ID_EXPR:
15813       {
15814 	/* Substituted template arguments */
15815 	tree fn = TREE_OPERAND (t, 0);
15816 	tree targs = TREE_OPERAND (t, 1);
15817 
15818 	fn = tsubst_copy (fn, args, complain, in_decl);
15819 	if (targs)
15820 	  targs = tsubst_template_args (targs, args, complain, in_decl);
15821 
15822 	return lookup_template_function (fn, targs);
15823       }
15824 
15825     case TREE_LIST:
15826       {
15827 	tree purpose, value, chain;
15828 
15829 	if (t == void_list_node)
15830 	  return t;
15831 
15832 	purpose = TREE_PURPOSE (t);
15833 	if (purpose)
15834 	  purpose = tsubst_copy (purpose, args, complain, in_decl);
15835 	value = TREE_VALUE (t);
15836 	if (value)
15837 	  value = tsubst_copy (value, args, complain, in_decl);
15838 	chain = TREE_CHAIN (t);
15839 	if (chain && chain != void_type_node)
15840 	  chain = tsubst_copy (chain, args, complain, in_decl);
15841 	if (purpose == TREE_PURPOSE (t)
15842 	    && value == TREE_VALUE (t)
15843 	    && chain == TREE_CHAIN (t))
15844 	  return t;
15845 	return tree_cons (purpose, value, chain);
15846       }
15847 
15848     case RECORD_TYPE:
15849     case UNION_TYPE:
15850     case ENUMERAL_TYPE:
15851     case INTEGER_TYPE:
15852     case TEMPLATE_TYPE_PARM:
15853     case TEMPLATE_TEMPLATE_PARM:
15854     case BOUND_TEMPLATE_TEMPLATE_PARM:
15855     case TEMPLATE_PARM_INDEX:
15856     case POINTER_TYPE:
15857     case REFERENCE_TYPE:
15858     case OFFSET_TYPE:
15859     case FUNCTION_TYPE:
15860     case METHOD_TYPE:
15861     case ARRAY_TYPE:
15862     case TYPENAME_TYPE:
15863     case UNBOUND_CLASS_TEMPLATE:
15864     case TYPEOF_TYPE:
15865     case DECLTYPE_TYPE:
15866     case TYPE_DECL:
15867       return tsubst (t, args, complain, in_decl);
15868 
15869     case USING_DECL:
15870       t = DECL_NAME (t);
15871       /* Fall through.  */
15872     case IDENTIFIER_NODE:
15873       if (IDENTIFIER_CONV_OP_P (t))
15874 	{
15875 	  tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15876 	  return make_conv_op_name (new_type);
15877 	}
15878       else
15879 	return t;
15880 
15881     case CONSTRUCTOR:
15882       /* This is handled by tsubst_copy_and_build.  */
15883       gcc_unreachable ();
15884 
15885     case VA_ARG_EXPR:
15886       {
15887 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15888 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15889 	return build_x_va_arg (EXPR_LOCATION (t), op0, type);
15890       }
15891 
15892     case CLEANUP_POINT_EXPR:
15893       /* We shouldn't have built any of these during initial template
15894 	 generation.  Instead, they should be built during instantiation
15895 	 in response to the saved STMT_IS_FULL_EXPR_P setting.  */
15896       gcc_unreachable ();
15897 
15898     case OFFSET_REF:
15899       {
15900 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15901 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15902 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15903 	r = build2 (code, type, op0, op1);
15904 	PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
15905 	if (!mark_used (TREE_OPERAND (r, 1), complain)
15906 	    && !(complain & tf_error))
15907 	  return error_mark_node;
15908 	return r;
15909       }
15910 
15911     case EXPR_PACK_EXPANSION:
15912       error ("invalid use of pack expansion expression");
15913       return error_mark_node;
15914 
15915     case NONTYPE_ARGUMENT_PACK:
15916       error ("use %<...%> to expand argument pack");
15917       return error_mark_node;
15918 
15919     case VOID_CST:
15920       gcc_checking_assert (t == void_node && VOID_TYPE_P (TREE_TYPE (t)));
15921       return t;
15922 
15923     case INTEGER_CST:
15924     case REAL_CST:
15925     case STRING_CST:
15926     case COMPLEX_CST:
15927       {
15928 	/* Instantiate any typedefs in the type.  */
15929 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15930 	r = fold_convert (type, t);
15931 	gcc_assert (TREE_CODE (r) == code);
15932 	return r;
15933       }
15934 
15935     case PTRMEM_CST:
15936       /* These can sometimes show up in a partial instantiation, but never
15937 	 involve template parms.  */
15938       gcc_assert (!uses_template_parms (t));
15939       return t;
15940 
15941     case UNARY_LEFT_FOLD_EXPR:
15942       return tsubst_unary_left_fold (t, args, complain, in_decl);
15943     case UNARY_RIGHT_FOLD_EXPR:
15944       return tsubst_unary_right_fold (t, args, complain, in_decl);
15945     case BINARY_LEFT_FOLD_EXPR:
15946       return tsubst_binary_left_fold (t, args, complain, in_decl);
15947     case BINARY_RIGHT_FOLD_EXPR:
15948       return tsubst_binary_right_fold (t, args, complain, in_decl);
15949     case PREDICT_EXPR:
15950       return t;
15951 
15952     case DEBUG_BEGIN_STMT:
15953       /* ??? There's no point in copying it for now, but maybe some
15954 	 day it will contain more information, such as a pointer back
15955 	 to the containing function, inlined copy or so.  */
15956       return t;
15957 
15958     default:
15959       /* We shouldn't get here, but keep going if !flag_checking.  */
15960       if (flag_checking)
15961 	gcc_unreachable ();
15962       return t;
15963     }
15964 }
15965 
15966 /* Helper function for tsubst_omp_clauses, used for instantiation of
15967    OMP_CLAUSE_DECL of clauses.  */
15968 
15969 static tree
tsubst_omp_clause_decl(tree decl,tree args,tsubst_flags_t complain,tree in_decl)15970 tsubst_omp_clause_decl (tree decl, tree args, tsubst_flags_t complain,
15971 			tree in_decl)
15972 {
15973   if (decl == NULL_TREE)
15974     return NULL_TREE;
15975 
15976   /* Handle an OpenMP array section represented as a TREE_LIST (or
15977      OMP_CLAUSE_DEPEND_KIND).  An OMP_CLAUSE_DEPEND (with a depend
15978      kind of OMP_CLAUSE_DEPEND_SINK) can also be represented as a
15979      TREE_LIST.  We can handle it exactly the same as an array section
15980      (purpose, value, and a chain), even though the nomenclature
15981      (low_bound, length, etc) is different.  */
15982   if (TREE_CODE (decl) == TREE_LIST)
15983     {
15984       tree low_bound
15985 	= tsubst_expr (TREE_PURPOSE (decl), args, complain, in_decl,
15986 		       /*integral_constant_expression_p=*/false);
15987       tree length = tsubst_expr (TREE_VALUE (decl), args, complain, in_decl,
15988 				 /*integral_constant_expression_p=*/false);
15989       tree chain = tsubst_omp_clause_decl (TREE_CHAIN (decl), args, complain,
15990 					   in_decl);
15991       if (TREE_PURPOSE (decl) == low_bound
15992 	  && TREE_VALUE (decl) == length
15993 	  && TREE_CHAIN (decl) == chain)
15994 	return decl;
15995       tree ret = tree_cons (low_bound, length, chain);
15996       OMP_CLAUSE_DEPEND_SINK_NEGATIVE (ret)
15997 	= OMP_CLAUSE_DEPEND_SINK_NEGATIVE (decl);
15998       return ret;
15999     }
16000   tree ret = tsubst_expr (decl, args, complain, in_decl,
16001 			  /*integral_constant_expression_p=*/false);
16002   /* Undo convert_from_reference tsubst_expr could have called.  */
16003   if (decl
16004       && REFERENCE_REF_P (ret)
16005       && !REFERENCE_REF_P (decl))
16006     ret = TREE_OPERAND (ret, 0);
16007   return ret;
16008 }
16009 
16010 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
16011 
16012 static tree
tsubst_omp_clauses(tree clauses,enum c_omp_region_type ort,tree args,tsubst_flags_t complain,tree in_decl)16013 tsubst_omp_clauses (tree clauses, enum c_omp_region_type ort,
16014 		    tree args, tsubst_flags_t complain, tree in_decl)
16015 {
16016   tree new_clauses = NULL_TREE, nc, oc;
16017   tree linear_no_step = NULL_TREE;
16018 
16019   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
16020     {
16021       nc = copy_node (oc);
16022       OMP_CLAUSE_CHAIN (nc) = new_clauses;
16023       new_clauses = nc;
16024 
16025       switch (OMP_CLAUSE_CODE (nc))
16026 	{
16027 	case OMP_CLAUSE_LASTPRIVATE:
16028 	  if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
16029 	    {
16030 	      OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
16031 	      tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
16032 			   in_decl, /*integral_constant_expression_p=*/false);
16033 	      OMP_CLAUSE_LASTPRIVATE_STMT (nc)
16034 		= pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
16035 	    }
16036 	  /* FALLTHRU */
16037 	case OMP_CLAUSE_PRIVATE:
16038 	case OMP_CLAUSE_SHARED:
16039 	case OMP_CLAUSE_FIRSTPRIVATE:
16040 	case OMP_CLAUSE_COPYIN:
16041 	case OMP_CLAUSE_COPYPRIVATE:
16042 	case OMP_CLAUSE_UNIFORM:
16043 	case OMP_CLAUSE_DEPEND:
16044 	case OMP_CLAUSE_FROM:
16045 	case OMP_CLAUSE_TO:
16046 	case OMP_CLAUSE_MAP:
16047 	case OMP_CLAUSE_USE_DEVICE_PTR:
16048 	case OMP_CLAUSE_IS_DEVICE_PTR:
16049 	  OMP_CLAUSE_DECL (nc)
16050 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
16051 				      in_decl);
16052 	  break;
16053 	case OMP_CLAUSE_TILE:
16054 	case OMP_CLAUSE_IF:
16055 	case OMP_CLAUSE_NUM_THREADS:
16056 	case OMP_CLAUSE_SCHEDULE:
16057 	case OMP_CLAUSE_COLLAPSE:
16058 	case OMP_CLAUSE_FINAL:
16059 	case OMP_CLAUSE_DEVICE:
16060 	case OMP_CLAUSE_DIST_SCHEDULE:
16061 	case OMP_CLAUSE_NUM_TEAMS:
16062 	case OMP_CLAUSE_THREAD_LIMIT:
16063 	case OMP_CLAUSE_SAFELEN:
16064 	case OMP_CLAUSE_SIMDLEN:
16065 	case OMP_CLAUSE_NUM_TASKS:
16066 	case OMP_CLAUSE_GRAINSIZE:
16067 	case OMP_CLAUSE_PRIORITY:
16068 	case OMP_CLAUSE_ORDERED:
16069 	case OMP_CLAUSE_HINT:
16070 	case OMP_CLAUSE_NUM_GANGS:
16071 	case OMP_CLAUSE_NUM_WORKERS:
16072 	case OMP_CLAUSE_VECTOR_LENGTH:
16073 	case OMP_CLAUSE_WORKER:
16074 	case OMP_CLAUSE_VECTOR:
16075 	case OMP_CLAUSE_ASYNC:
16076 	case OMP_CLAUSE_WAIT:
16077 	  OMP_CLAUSE_OPERAND (nc, 0)
16078 	    = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain,
16079 			   in_decl, /*integral_constant_expression_p=*/false);
16080 	  break;
16081 	case OMP_CLAUSE_REDUCTION:
16082 	  if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc))
16083 	    {
16084 	      tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc);
16085 	      if (TREE_CODE (placeholder) == SCOPE_REF)
16086 		{
16087 		  tree scope = tsubst (TREE_OPERAND (placeholder, 0), args,
16088 				       complain, in_decl);
16089 		  OMP_CLAUSE_REDUCTION_PLACEHOLDER (nc)
16090 		    = build_qualified_name (NULL_TREE, scope,
16091 					    TREE_OPERAND (placeholder, 1),
16092 					    false);
16093 		}
16094 	      else
16095 		gcc_assert (identifier_p (placeholder));
16096 	    }
16097 	  OMP_CLAUSE_DECL (nc)
16098 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
16099 				      in_decl);
16100 	  break;
16101 	case OMP_CLAUSE_GANG:
16102 	case OMP_CLAUSE_ALIGNED:
16103 	  OMP_CLAUSE_DECL (nc)
16104 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
16105 				      in_decl);
16106 	  OMP_CLAUSE_OPERAND (nc, 1)
16107 	    = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 1), args, complain,
16108 			   in_decl, /*integral_constant_expression_p=*/false);
16109 	  break;
16110 	case OMP_CLAUSE_LINEAR:
16111 	  OMP_CLAUSE_DECL (nc)
16112 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
16113 				      in_decl);
16114 	  if (OMP_CLAUSE_LINEAR_STEP (oc) == NULL_TREE)
16115 	    {
16116 	      gcc_assert (!linear_no_step);
16117 	      linear_no_step = nc;
16118 	    }
16119 	  else if (OMP_CLAUSE_LINEAR_VARIABLE_STRIDE (oc))
16120 	    OMP_CLAUSE_LINEAR_STEP (nc)
16121 	      = tsubst_omp_clause_decl (OMP_CLAUSE_LINEAR_STEP (oc), args,
16122 					complain, in_decl);
16123 	  else
16124 	    OMP_CLAUSE_LINEAR_STEP (nc)
16125 	      = tsubst_expr (OMP_CLAUSE_LINEAR_STEP (oc), args, complain,
16126 			     in_decl,
16127 			     /*integral_constant_expression_p=*/false);
16128 	  break;
16129 	case OMP_CLAUSE_NOWAIT:
16130 	case OMP_CLAUSE_DEFAULT:
16131 	case OMP_CLAUSE_UNTIED:
16132 	case OMP_CLAUSE_MERGEABLE:
16133 	case OMP_CLAUSE_INBRANCH:
16134 	case OMP_CLAUSE_NOTINBRANCH:
16135 	case OMP_CLAUSE_PROC_BIND:
16136 	case OMP_CLAUSE_FOR:
16137 	case OMP_CLAUSE_PARALLEL:
16138 	case OMP_CLAUSE_SECTIONS:
16139 	case OMP_CLAUSE_TASKGROUP:
16140 	case OMP_CLAUSE_NOGROUP:
16141 	case OMP_CLAUSE_THREADS:
16142 	case OMP_CLAUSE_SIMD:
16143 	case OMP_CLAUSE_DEFAULTMAP:
16144 	case OMP_CLAUSE_INDEPENDENT:
16145 	case OMP_CLAUSE_AUTO:
16146 	case OMP_CLAUSE_SEQ:
16147 	  break;
16148 	default:
16149 	  gcc_unreachable ();
16150 	}
16151       if ((ort & C_ORT_OMP_DECLARE_SIMD) == C_ORT_OMP)
16152 	switch (OMP_CLAUSE_CODE (nc))
16153 	  {
16154 	  case OMP_CLAUSE_SHARED:
16155 	  case OMP_CLAUSE_PRIVATE:
16156 	  case OMP_CLAUSE_FIRSTPRIVATE:
16157 	  case OMP_CLAUSE_LASTPRIVATE:
16158 	  case OMP_CLAUSE_COPYPRIVATE:
16159 	  case OMP_CLAUSE_LINEAR:
16160 	  case OMP_CLAUSE_REDUCTION:
16161 	  case OMP_CLAUSE_USE_DEVICE_PTR:
16162 	  case OMP_CLAUSE_IS_DEVICE_PTR:
16163 	    /* tsubst_expr on SCOPE_REF results in returning
16164 	       finish_non_static_data_member result.  Undo that here.  */
16165 	    if (TREE_CODE (OMP_CLAUSE_DECL (oc)) == SCOPE_REF
16166 		&& (TREE_CODE (TREE_OPERAND (OMP_CLAUSE_DECL (oc), 1))
16167 		    == IDENTIFIER_NODE))
16168 	      {
16169 		tree t = OMP_CLAUSE_DECL (nc);
16170 		tree v = t;
16171 		while (v)
16172 		  switch (TREE_CODE (v))
16173 		    {
16174 		    case COMPONENT_REF:
16175 		    case MEM_REF:
16176 		    case INDIRECT_REF:
16177 		    CASE_CONVERT:
16178 		    case POINTER_PLUS_EXPR:
16179 		      v = TREE_OPERAND (v, 0);
16180 		      continue;
16181 		    case PARM_DECL:
16182 		      if (DECL_CONTEXT (v) == current_function_decl
16183 			  && DECL_ARTIFICIAL (v)
16184 			  && DECL_NAME (v) == this_identifier)
16185 			OMP_CLAUSE_DECL (nc) = TREE_OPERAND (t, 1);
16186 		      /* FALLTHRU */
16187 		    default:
16188 		      v = NULL_TREE;
16189 		      break;
16190 		    }
16191 	      }
16192 	    else if (VAR_P (OMP_CLAUSE_DECL (oc))
16193 		     && DECL_HAS_VALUE_EXPR_P (OMP_CLAUSE_DECL (oc))
16194 		     && DECL_ARTIFICIAL (OMP_CLAUSE_DECL (oc))
16195 		     && DECL_LANG_SPECIFIC (OMP_CLAUSE_DECL (oc))
16196 		     && DECL_OMP_PRIVATIZED_MEMBER (OMP_CLAUSE_DECL (oc)))
16197 	      {
16198 		tree decl = OMP_CLAUSE_DECL (nc);
16199 		if (VAR_P (decl))
16200 		  {
16201 		    retrofit_lang_decl (decl);
16202 		    DECL_OMP_PRIVATIZED_MEMBER (decl) = 1;
16203 		  }
16204 	      }
16205 	    break;
16206 	  default:
16207 	    break;
16208 	  }
16209     }
16210 
16211   new_clauses = nreverse (new_clauses);
16212   if (ort != C_ORT_OMP_DECLARE_SIMD)
16213     {
16214       new_clauses = finish_omp_clauses (new_clauses, ort);
16215       if (linear_no_step)
16216 	for (nc = new_clauses; nc; nc = OMP_CLAUSE_CHAIN (nc))
16217 	  if (nc == linear_no_step)
16218 	    {
16219 	      OMP_CLAUSE_LINEAR_STEP (nc) = NULL_TREE;
16220 	      break;
16221 	    }
16222     }
16223   return new_clauses;
16224 }
16225 
16226 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
16227 
16228 static tree
tsubst_copy_asm_operands(tree t,tree args,tsubst_flags_t complain,tree in_decl)16229 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
16230 			  tree in_decl)
16231 {
16232 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
16233 
16234   tree purpose, value, chain;
16235 
16236   if (t == NULL)
16237     return t;
16238 
16239   if (TREE_CODE (t) != TREE_LIST)
16240     return tsubst_copy_and_build (t, args, complain, in_decl,
16241 				  /*function_p=*/false,
16242 				  /*integral_constant_expression_p=*/false);
16243 
16244   if (t == void_list_node)
16245     return t;
16246 
16247   purpose = TREE_PURPOSE (t);
16248   if (purpose)
16249     purpose = RECUR (purpose);
16250   value = TREE_VALUE (t);
16251   if (value)
16252     {
16253       if (TREE_CODE (value) != LABEL_DECL)
16254 	value = RECUR (value);
16255       else
16256 	{
16257 	  value = lookup_label (DECL_NAME (value));
16258 	  gcc_assert (TREE_CODE (value) == LABEL_DECL);
16259 	  TREE_USED (value) = 1;
16260 	}
16261     }
16262   chain = TREE_CHAIN (t);
16263   if (chain && chain != void_type_node)
16264     chain = RECUR (chain);
16265   return tree_cons (purpose, value, chain);
16266 #undef RECUR
16267 }
16268 
16269 /* Used to temporarily communicate the list of #pragma omp parallel
16270    clauses to #pragma omp for instantiation if they are combined
16271    together.  */
16272 
16273 static tree *omp_parallel_combined_clauses;
16274 
16275 /* Substitute one OMP_FOR iterator.  */
16276 
16277 static void
tsubst_omp_for_iterator(tree t,int i,tree declv,tree orig_declv,tree initv,tree condv,tree incrv,tree * clauses,tree args,tsubst_flags_t complain,tree in_decl,bool integral_constant_expression_p)16278 tsubst_omp_for_iterator (tree t, int i, tree declv, tree orig_declv,
16279 			 tree initv, tree condv, tree incrv, tree *clauses,
16280 			 tree args, tsubst_flags_t complain, tree in_decl,
16281 			 bool integral_constant_expression_p)
16282 {
16283 #define RECUR(NODE)				\
16284   tsubst_expr ((NODE), args, complain, in_decl,	\
16285 	       integral_constant_expression_p)
16286   tree decl, init, cond, incr;
16287 
16288   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
16289   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
16290 
16291   if (orig_declv && OMP_FOR_ORIG_DECLS (t))
16292     {
16293       tree o = TREE_VEC_ELT (OMP_FOR_ORIG_DECLS (t), i);
16294       TREE_VEC_ELT (orig_declv, i) = RECUR (o);
16295     }
16296 
16297   decl = TREE_OPERAND (init, 0);
16298   init = TREE_OPERAND (init, 1);
16299   tree decl_expr = NULL_TREE;
16300   if (init && TREE_CODE (init) == DECL_EXPR)
16301     {
16302       /* We need to jump through some hoops to handle declarations in the
16303 	 init-statement, since we might need to handle auto deduction,
16304 	 but we need to keep control of initialization.  */
16305       decl_expr = init;
16306       init = DECL_INITIAL (DECL_EXPR_DECL (init));
16307       decl = tsubst_decl (decl, args, complain);
16308     }
16309   else
16310     {
16311       if (TREE_CODE (decl) == SCOPE_REF)
16312 	{
16313 	  decl = RECUR (decl);
16314 	  if (TREE_CODE (decl) == COMPONENT_REF)
16315 	    {
16316 	      tree v = decl;
16317 	      while (v)
16318 		switch (TREE_CODE (v))
16319 		  {
16320 		  case COMPONENT_REF:
16321 		  case MEM_REF:
16322 		  case INDIRECT_REF:
16323 		  CASE_CONVERT:
16324 		  case POINTER_PLUS_EXPR:
16325 		    v = TREE_OPERAND (v, 0);
16326 		    continue;
16327 		  case PARM_DECL:
16328 		    if (DECL_CONTEXT (v) == current_function_decl
16329 			&& DECL_ARTIFICIAL (v)
16330 			&& DECL_NAME (v) == this_identifier)
16331 		      {
16332 			decl = TREE_OPERAND (decl, 1);
16333 			decl = omp_privatize_field (decl, false);
16334 		      }
16335 		    /* FALLTHRU */
16336 		  default:
16337 		    v = NULL_TREE;
16338 		    break;
16339 		  }
16340 	    }
16341 	}
16342       else
16343 	decl = RECUR (decl);
16344     }
16345   init = RECUR (init);
16346 
16347   tree auto_node = type_uses_auto (TREE_TYPE (decl));
16348   if (auto_node && init)
16349     TREE_TYPE (decl)
16350       = do_auto_deduction (TREE_TYPE (decl), init, auto_node, complain);
16351 
16352   gcc_assert (!type_dependent_expression_p (decl));
16353 
16354   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
16355     {
16356       if (decl_expr)
16357 	{
16358 	  /* Declare the variable, but don't let that initialize it.  */
16359 	  tree init_sav = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
16360 	  DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL_TREE;
16361 	  RECUR (decl_expr);
16362 	  DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init_sav;
16363 	}
16364 
16365       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
16366       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
16367       if (TREE_CODE (incr) == MODIFY_EXPR)
16368 	{
16369 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
16370 	  tree rhs = RECUR (TREE_OPERAND (incr, 1));
16371 	  incr = build_x_modify_expr (EXPR_LOCATION (incr), lhs,
16372 				      NOP_EXPR, rhs, complain);
16373 	}
16374       else
16375 	incr = RECUR (incr);
16376       TREE_VEC_ELT (declv, i) = decl;
16377       TREE_VEC_ELT (initv, i) = init;
16378       TREE_VEC_ELT (condv, i) = cond;
16379       TREE_VEC_ELT (incrv, i) = incr;
16380       return;
16381     }
16382 
16383   if (decl_expr)
16384     {
16385       /* Declare and initialize the variable.  */
16386       RECUR (decl_expr);
16387       init = NULL_TREE;
16388     }
16389   else if (init)
16390     {
16391       tree *pc;
16392       int j;
16393       for (j = (omp_parallel_combined_clauses == NULL ? 1 : 0); j < 2; j++)
16394 	{
16395 	  for (pc = j ? clauses : omp_parallel_combined_clauses; *pc; )
16396 	    {
16397 	      if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_PRIVATE
16398 		  && OMP_CLAUSE_DECL (*pc) == decl)
16399 		break;
16400 	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_LASTPRIVATE
16401 		       && OMP_CLAUSE_DECL (*pc) == decl)
16402 		{
16403 		  if (j)
16404 		    break;
16405 		  /* Move lastprivate (decl) clause to OMP_FOR_CLAUSES.  */
16406 		  tree c = *pc;
16407 		  *pc = OMP_CLAUSE_CHAIN (c);
16408 		  OMP_CLAUSE_CHAIN (c) = *clauses;
16409 		  *clauses = c;
16410 		}
16411 	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_FIRSTPRIVATE
16412 		       && OMP_CLAUSE_DECL (*pc) == decl)
16413 		{
16414 		  error ("iteration variable %qD should not be firstprivate",
16415 			 decl);
16416 		  *pc = OMP_CLAUSE_CHAIN (*pc);
16417 		}
16418 	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_REDUCTION
16419 		       && OMP_CLAUSE_DECL (*pc) == decl)
16420 		{
16421 		  error ("iteration variable %qD should not be reduction",
16422 			 decl);
16423 		  *pc = OMP_CLAUSE_CHAIN (*pc);
16424 		}
16425 	      else
16426 		pc = &OMP_CLAUSE_CHAIN (*pc);
16427 	    }
16428 	  if (*pc)
16429 	    break;
16430 	}
16431       if (*pc == NULL_TREE)
16432 	{
16433 	  tree c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
16434 	  OMP_CLAUSE_DECL (c) = decl;
16435 	  c = finish_omp_clauses (c, C_ORT_OMP);
16436 	  if (c)
16437 	    {
16438 	      OMP_CLAUSE_CHAIN (c) = *clauses;
16439 	      *clauses = c;
16440 	    }
16441 	}
16442     }
16443   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
16444   if (COMPARISON_CLASS_P (cond))
16445     {
16446       tree op0 = RECUR (TREE_OPERAND (cond, 0));
16447       tree op1 = RECUR (TREE_OPERAND (cond, 1));
16448       cond = build2 (TREE_CODE (cond), boolean_type_node, op0, op1);
16449     }
16450   else
16451     cond = RECUR (cond);
16452   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
16453   switch (TREE_CODE (incr))
16454     {
16455     case PREINCREMENT_EXPR:
16456     case PREDECREMENT_EXPR:
16457     case POSTINCREMENT_EXPR:
16458     case POSTDECREMENT_EXPR:
16459       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
16460 		     RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
16461       break;
16462     case MODIFY_EXPR:
16463       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
16464 	  || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
16465 	{
16466 	  tree rhs = TREE_OPERAND (incr, 1);
16467 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
16468 	  tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
16469 	  tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
16470 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
16471 			 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
16472 				 rhs0, rhs1));
16473 	}
16474       else
16475 	incr = RECUR (incr);
16476       break;
16477     case MODOP_EXPR:
16478       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
16479 	  || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
16480 	{
16481 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
16482 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
16483 			 build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
16484 				 TREE_TYPE (decl), lhs,
16485 				 RECUR (TREE_OPERAND (incr, 2))));
16486 	}
16487       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
16488 	       && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
16489 		   || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
16490 	{
16491 	  tree rhs = TREE_OPERAND (incr, 2);
16492 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
16493 	  tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
16494 	  tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
16495 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
16496 			 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
16497 				 rhs0, rhs1));
16498 	}
16499       else
16500 	incr = RECUR (incr);
16501       break;
16502     default:
16503       incr = RECUR (incr);
16504       break;
16505     }
16506 
16507   TREE_VEC_ELT (declv, i) = decl;
16508   TREE_VEC_ELT (initv, i) = init;
16509   TREE_VEC_ELT (condv, i) = cond;
16510   TREE_VEC_ELT (incrv, i) = incr;
16511 #undef RECUR
16512 }
16513 
16514 /* Helper function of tsubst_expr, find OMP_TEAMS inside
16515    of OMP_TARGET's body.  */
16516 
16517 static tree
tsubst_find_omp_teams(tree * tp,int * walk_subtrees,void *)16518 tsubst_find_omp_teams (tree *tp, int *walk_subtrees, void *)
16519 {
16520   *walk_subtrees = 0;
16521   switch (TREE_CODE (*tp))
16522     {
16523     case OMP_TEAMS:
16524       return *tp;
16525     case BIND_EXPR:
16526     case STATEMENT_LIST:
16527       *walk_subtrees = 1;
16528       break;
16529     default:
16530       break;
16531     }
16532   return NULL_TREE;
16533 }
16534 
16535 /* Helper function for tsubst_expr.  For decomposition declaration
16536    artificial base DECL, which is tsubsted PATTERN_DECL, tsubst
16537    also the corresponding decls representing the identifiers
16538    of the decomposition declaration.  Return DECL if successful
16539    or error_mark_node otherwise, set *FIRST to the first decl
16540    in the list chained through DECL_CHAIN and *CNT to the number
16541    of such decls.  */
16542 
16543 static tree
tsubst_decomp_names(tree decl,tree pattern_decl,tree args,tsubst_flags_t complain,tree in_decl,tree * first,unsigned int * cnt)16544 tsubst_decomp_names (tree decl, tree pattern_decl, tree args,
16545 		     tsubst_flags_t complain, tree in_decl, tree *first,
16546 		     unsigned int *cnt)
16547 {
16548   tree decl2, decl3, prev = decl;
16549   *cnt = 0;
16550   gcc_assert (DECL_NAME (decl) == NULL_TREE);
16551   for (decl2 = DECL_CHAIN (pattern_decl);
16552        decl2
16553        && VAR_P (decl2)
16554        && DECL_DECOMPOSITION_P (decl2)
16555        && DECL_NAME (decl2);
16556        decl2 = DECL_CHAIN (decl2))
16557     {
16558       if (TREE_TYPE (decl2) == error_mark_node && *cnt == 0)
16559 	{
16560 	  gcc_assert (errorcount);
16561 	  return error_mark_node;
16562 	}
16563       (*cnt)++;
16564       gcc_assert (DECL_DECOMP_BASE (decl2) == pattern_decl);
16565       gcc_assert (DECL_HAS_VALUE_EXPR_P (decl2));
16566       tree v = DECL_VALUE_EXPR (decl2);
16567       DECL_HAS_VALUE_EXPR_P (decl2) = 0;
16568       SET_DECL_VALUE_EXPR (decl2, NULL_TREE);
16569       decl3 = tsubst (decl2, args, complain, in_decl);
16570       SET_DECL_VALUE_EXPR (decl2, v);
16571       DECL_HAS_VALUE_EXPR_P (decl2) = 1;
16572       if (VAR_P (decl3))
16573 	DECL_TEMPLATE_INSTANTIATED (decl3) = 1;
16574       else
16575 	{
16576 	  gcc_assert (errorcount);
16577 	  decl = error_mark_node;
16578 	  continue;
16579 	}
16580       maybe_push_decl (decl3);
16581       if (error_operand_p (decl3))
16582 	decl = error_mark_node;
16583       else if (decl != error_mark_node
16584 	       && DECL_CHAIN (decl3) != prev
16585 	       && decl != prev)
16586 	{
16587 	  gcc_assert (errorcount);
16588 	  decl = error_mark_node;
16589 	}
16590       else
16591 	prev = decl3;
16592     }
16593   *first = prev;
16594   return decl;
16595 }
16596 
16597 /* Like tsubst_copy for expressions, etc. but also does semantic
16598    processing.  */
16599 
16600 tree
tsubst_expr(tree t,tree args,tsubst_flags_t complain,tree in_decl,bool integral_constant_expression_p)16601 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
16602 	     bool integral_constant_expression_p)
16603 {
16604 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
16605 #define RECUR(NODE)				\
16606   tsubst_expr ((NODE), args, complain, in_decl,	\
16607 	       integral_constant_expression_p)
16608 
16609   tree stmt, tmp;
16610   tree r;
16611   location_t loc;
16612 
16613   if (t == NULL_TREE || t == error_mark_node)
16614     return t;
16615 
16616   loc = input_location;
16617   if (EXPR_HAS_LOCATION (t))
16618     input_location = EXPR_LOCATION (t);
16619   if (STATEMENT_CODE_P (TREE_CODE (t)))
16620     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
16621 
16622   switch (TREE_CODE (t))
16623     {
16624     case STATEMENT_LIST:
16625       {
16626 	tree_stmt_iterator i;
16627 	for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
16628 	  RECUR (tsi_stmt (i));
16629 	break;
16630       }
16631 
16632     case CTOR_INITIALIZER:
16633       finish_mem_initializers (tsubst_initializer_list
16634 			       (TREE_OPERAND (t, 0), args));
16635       break;
16636 
16637     case RETURN_EXPR:
16638       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
16639       break;
16640 
16641     case EXPR_STMT:
16642       tmp = RECUR (EXPR_STMT_EXPR (t));
16643       if (EXPR_STMT_STMT_EXPR_RESULT (t))
16644 	finish_stmt_expr_expr (tmp, cur_stmt_expr);
16645       else
16646 	finish_expr_stmt (tmp);
16647       break;
16648 
16649     case USING_STMT:
16650       finish_local_using_directive (USING_STMT_NAMESPACE (t),
16651 				    /*attribs=*/NULL_TREE);
16652       break;
16653 
16654     case DECL_EXPR:
16655       {
16656 	tree decl, pattern_decl;
16657 	tree init;
16658 
16659 	pattern_decl = decl = DECL_EXPR_DECL (t);
16660 	if (TREE_CODE (decl) == LABEL_DECL)
16661 	  finish_label_decl (DECL_NAME (decl));
16662 	else if (TREE_CODE (decl) == USING_DECL)
16663 	  {
16664 	    tree scope = USING_DECL_SCOPE (decl);
16665 	    tree name = DECL_NAME (decl);
16666 
16667 	    scope = tsubst (scope, args, complain, in_decl);
16668 	    decl = lookup_qualified_name (scope, name,
16669 					  /*is_type_p=*/false,
16670 					  /*complain=*/false);
16671 	    if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
16672 	      qualified_name_lookup_error (scope, name, decl, input_location);
16673 	    else
16674 	      finish_local_using_decl (decl, scope, name);
16675 	  }
16676 	else if (is_capture_proxy (decl)
16677 		 && !DECL_TEMPLATE_INSTANTIATION (current_function_decl))
16678 	  {
16679 	    /* We're in tsubst_lambda_expr, we've already inserted a new
16680 	       capture proxy, so look it up and register it.  */
16681 	    tree inst;
16682 	    if (DECL_PACK_P (decl))
16683 	      {
16684 		inst = (retrieve_local_specialization
16685 			(DECL_CAPTURED_VARIABLE (decl)));
16686 		gcc_assert (TREE_CODE (inst) == NONTYPE_ARGUMENT_PACK);
16687 	      }
16688 	    else
16689 	      {
16690 		inst = lookup_name_real (DECL_NAME (decl), 0, 0,
16691 					 /*block_p=*/true, 0, LOOKUP_HIDDEN);
16692 		gcc_assert (inst != decl && is_capture_proxy (inst));
16693 	      }
16694 	    register_local_specialization (inst, decl);
16695 	    break;
16696 	  }
16697 	else if (DECL_IMPLICIT_TYPEDEF_P (decl)
16698 		 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
16699 	  /* Don't copy the old closure; we'll create a new one in
16700 	     tsubst_lambda_expr.  */
16701 	  break;
16702 	else
16703 	  {
16704 	    init = DECL_INITIAL (decl);
16705 	    decl = tsubst (decl, args, complain, in_decl);
16706 	    if (decl != error_mark_node)
16707 	      {
16708 		/* By marking the declaration as instantiated, we avoid
16709 		   trying to instantiate it.  Since instantiate_decl can't
16710 		   handle local variables, and since we've already done
16711 		   all that needs to be done, that's the right thing to
16712 		   do.  */
16713 		if (VAR_P (decl))
16714 		  DECL_TEMPLATE_INSTANTIATED (decl) = 1;
16715 		if (VAR_P (decl) && !DECL_NAME (decl)
16716 		    && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
16717 		  /* Anonymous aggregates are a special case.  */
16718 		  finish_anon_union (decl);
16719 		else if (is_capture_proxy (DECL_EXPR_DECL (t)))
16720 		  {
16721 		    DECL_CONTEXT (decl) = current_function_decl;
16722 		    if (DECL_NAME (decl) == this_identifier)
16723 		      {
16724 			tree lam = DECL_CONTEXT (current_function_decl);
16725 			lam = CLASSTYPE_LAMBDA_EXPR (lam);
16726 			LAMBDA_EXPR_THIS_CAPTURE (lam) = decl;
16727 		      }
16728 		    insert_capture_proxy (decl);
16729 		  }
16730 		else if (DECL_IMPLICIT_TYPEDEF_P (t))
16731 		  /* We already did a pushtag.  */;
16732 		else if (TREE_CODE (decl) == FUNCTION_DECL
16733 			 && DECL_OMP_DECLARE_REDUCTION_P (decl)
16734 			 && DECL_FUNCTION_SCOPE_P (pattern_decl))
16735 		  {
16736 		    DECL_CONTEXT (decl) = NULL_TREE;
16737 		    pushdecl (decl);
16738 		    DECL_CONTEXT (decl) = current_function_decl;
16739 		    cp_check_omp_declare_reduction (decl);
16740 		  }
16741 		else
16742 		  {
16743 		    int const_init = false;
16744 		    unsigned int cnt = 0;
16745 		    tree first = NULL_TREE, ndecl = error_mark_node;
16746 		    maybe_push_decl (decl);
16747 
16748 		    if (VAR_P (decl)
16749 			&& DECL_DECOMPOSITION_P (decl)
16750 			&& TREE_TYPE (pattern_decl) != error_mark_node)
16751 		      ndecl = tsubst_decomp_names (decl, pattern_decl, args,
16752 						   complain, in_decl, &first,
16753 						   &cnt);
16754 
16755 		    if (VAR_P (decl)
16756 			&& DECL_PRETTY_FUNCTION_P (decl))
16757 		      {
16758 			/* For __PRETTY_FUNCTION__ we have to adjust the
16759 			   initializer.  */
16760 			const char *const name
16761 			  = cxx_printable_name (current_function_decl, 2);
16762 			init = cp_fname_init (name, &TREE_TYPE (decl));
16763 		      }
16764 		    else
16765 		      init = tsubst_init (init, decl, args, complain, in_decl);
16766 
16767 		    if (VAR_P (decl))
16768 		      const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
16769 				    (pattern_decl));
16770 
16771 		    if (ndecl != error_mark_node)
16772 		      cp_maybe_mangle_decomp (ndecl, first, cnt);
16773 
16774 		    cp_finish_decl (decl, init, const_init, NULL_TREE, 0);
16775 
16776 		    if (ndecl != error_mark_node)
16777 		      cp_finish_decomp (ndecl, first, cnt);
16778 		  }
16779 	      }
16780 	  }
16781 
16782 	break;
16783       }
16784 
16785     case FOR_STMT:
16786       stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
16787       RECUR (FOR_INIT_STMT (t));
16788       finish_init_stmt (stmt);
16789       tmp = RECUR (FOR_COND (t));
16790       finish_for_cond (tmp, stmt, false, 0);
16791       tmp = RECUR (FOR_EXPR (t));
16792       finish_for_expr (tmp, stmt);
16793       {
16794 	bool prev = note_iteration_stmt_body_start ();
16795 	RECUR (FOR_BODY (t));
16796 	note_iteration_stmt_body_end (prev);
16797       }
16798       finish_for_stmt (stmt);
16799       break;
16800 
16801     case RANGE_FOR_STMT:
16802       {
16803 	/* Construct another range_for, if this is not a final
16804 	   substitution (for inside inside a generic lambda of a
16805 	   template).  Otherwise convert to a regular for.  */
16806         tree decl, expr;
16807         stmt = (processing_template_decl
16808 		? begin_range_for_stmt (NULL_TREE, NULL_TREE)
16809 		: begin_for_stmt (NULL_TREE, NULL_TREE));
16810         decl = RANGE_FOR_DECL (t);
16811         decl = tsubst (decl, args, complain, in_decl);
16812         maybe_push_decl (decl);
16813         expr = RECUR (RANGE_FOR_EXPR (t));
16814 
16815 	tree decomp_first = NULL_TREE;
16816 	unsigned decomp_cnt = 0;
16817 	if (VAR_P (decl) && DECL_DECOMPOSITION_P (decl))
16818 	  decl = tsubst_decomp_names (decl, RANGE_FOR_DECL (t), args,
16819 				      complain, in_decl,
16820 				      &decomp_first, &decomp_cnt);
16821 
16822 	if (processing_template_decl)
16823 	  {
16824 	    RANGE_FOR_IVDEP (stmt) = RANGE_FOR_IVDEP (t);
16825 	    RANGE_FOR_UNROLL (stmt) = RANGE_FOR_UNROLL (t);
16826 	    finish_range_for_decl (stmt, decl, expr);
16827 	    if (decomp_first && decl != error_mark_node)
16828 	      cp_finish_decomp (decl, decomp_first, decomp_cnt);
16829 	  }
16830 	else
16831 	  {
16832 	    unsigned short unroll = (RANGE_FOR_UNROLL (t)
16833 				     ? tree_to_uhwi (RANGE_FOR_UNROLL (t)) : 0);
16834 	    stmt = cp_convert_range_for (stmt, decl, expr,
16835 					 decomp_first, decomp_cnt,
16836 					 RANGE_FOR_IVDEP (t), unroll);
16837 	  }
16838 
16839 	bool prev = note_iteration_stmt_body_start ();
16840         RECUR (RANGE_FOR_BODY (t));
16841 	note_iteration_stmt_body_end (prev);
16842         finish_for_stmt (stmt);
16843       }
16844       break;
16845 
16846     case WHILE_STMT:
16847       stmt = begin_while_stmt ();
16848       tmp = RECUR (WHILE_COND (t));
16849       finish_while_stmt_cond (tmp, stmt, false, 0);
16850       {
16851 	bool prev = note_iteration_stmt_body_start ();
16852 	RECUR (WHILE_BODY (t));
16853 	note_iteration_stmt_body_end (prev);
16854       }
16855       finish_while_stmt (stmt);
16856       break;
16857 
16858     case DO_STMT:
16859       stmt = begin_do_stmt ();
16860       {
16861 	bool prev = note_iteration_stmt_body_start ();
16862 	RECUR (DO_BODY (t));
16863 	note_iteration_stmt_body_end (prev);
16864       }
16865       finish_do_body (stmt);
16866       tmp = RECUR (DO_COND (t));
16867       finish_do_stmt (tmp, stmt, false, 0);
16868       break;
16869 
16870     case IF_STMT:
16871       stmt = begin_if_stmt ();
16872       IF_STMT_CONSTEXPR_P (stmt) = IF_STMT_CONSTEXPR_P (t);
16873       if (IF_STMT_CONSTEXPR_P (t))
16874 	args = add_extra_args (IF_STMT_EXTRA_ARGS (t), args);
16875       tmp = RECUR (IF_COND (t));
16876       tmp = finish_if_stmt_cond (tmp, stmt);
16877       if (IF_STMT_CONSTEXPR_P (t)
16878 	  && instantiation_dependent_expression_p (tmp))
16879 	{
16880 	  /* We're partially instantiating a generic lambda, but the condition
16881 	     of the constexpr if is still dependent.  Don't substitute into the
16882 	     branches now, just remember the template arguments.  */
16883 	  do_poplevel (IF_SCOPE (stmt));
16884 	  IF_COND (stmt) = IF_COND (t);
16885 	  THEN_CLAUSE (stmt) = THEN_CLAUSE (t);
16886 	  ELSE_CLAUSE (stmt) = ELSE_CLAUSE (t);
16887 	  IF_STMT_EXTRA_ARGS (stmt) = build_extra_args (t, args, complain);
16888 	  add_stmt (stmt);
16889 	  break;
16890 	}
16891       if (IF_STMT_CONSTEXPR_P (t) && integer_zerop (tmp))
16892 	/* Don't instantiate the THEN_CLAUSE. */;
16893       else
16894 	{
16895 	  bool inhibit = integer_zerop (fold_non_dependent_expr (tmp));
16896 	  if (inhibit)
16897 	    ++c_inhibit_evaluation_warnings;
16898 	  RECUR (THEN_CLAUSE (t));
16899 	  if (inhibit)
16900 	    --c_inhibit_evaluation_warnings;
16901 	}
16902       finish_then_clause (stmt);
16903 
16904       if (IF_STMT_CONSTEXPR_P (t) && integer_nonzerop (tmp))
16905 	/* Don't instantiate the ELSE_CLAUSE. */;
16906       else if (ELSE_CLAUSE (t))
16907 	{
16908 	  bool inhibit = integer_nonzerop (fold_non_dependent_expr (tmp));
16909 	  begin_else_clause (stmt);
16910 	  if (inhibit)
16911 	    ++c_inhibit_evaluation_warnings;
16912 	  RECUR (ELSE_CLAUSE (t));
16913 	  if (inhibit)
16914 	    --c_inhibit_evaluation_warnings;
16915 	  finish_else_clause (stmt);
16916 	}
16917 
16918       finish_if_stmt (stmt);
16919       break;
16920 
16921     case BIND_EXPR:
16922       if (BIND_EXPR_BODY_BLOCK (t))
16923 	stmt = begin_function_body ();
16924       else
16925 	stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
16926 				    ? BCS_TRY_BLOCK : 0);
16927 
16928       RECUR (BIND_EXPR_BODY (t));
16929 
16930       if (BIND_EXPR_BODY_BLOCK (t))
16931 	finish_function_body (stmt);
16932       else
16933 	finish_compound_stmt (stmt);
16934       break;
16935 
16936     case BREAK_STMT:
16937       finish_break_stmt ();
16938       break;
16939 
16940     case CONTINUE_STMT:
16941       finish_continue_stmt ();
16942       break;
16943 
16944     case SWITCH_STMT:
16945       stmt = begin_switch_stmt ();
16946       tmp = RECUR (SWITCH_STMT_COND (t));
16947       finish_switch_cond (tmp, stmt);
16948       RECUR (SWITCH_STMT_BODY (t));
16949       finish_switch_stmt (stmt);
16950       break;
16951 
16952     case CASE_LABEL_EXPR:
16953       {
16954 	tree low = RECUR (CASE_LOW (t));
16955 	tree high = RECUR (CASE_HIGH (t));
16956 	tree l = finish_case_label (EXPR_LOCATION (t), low, high);
16957 	if (l && TREE_CODE (l) == CASE_LABEL_EXPR)
16958 	  FALLTHROUGH_LABEL_P (CASE_LABEL (l))
16959 	    = FALLTHROUGH_LABEL_P (CASE_LABEL (t));
16960       }
16961       break;
16962 
16963     case LABEL_EXPR:
16964       {
16965 	tree decl = LABEL_EXPR_LABEL (t);
16966 	tree label;
16967 
16968 	label = finish_label_stmt (DECL_NAME (decl));
16969 	if (TREE_CODE (label) == LABEL_DECL)
16970 	  FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
16971 	if (DECL_ATTRIBUTES (decl) != NULL_TREE)
16972 	  cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
16973       }
16974       break;
16975 
16976     case GOTO_EXPR:
16977       tmp = GOTO_DESTINATION (t);
16978       if (TREE_CODE (tmp) != LABEL_DECL)
16979 	/* Computed goto's must be tsubst'd into.  On the other hand,
16980 	   non-computed gotos must not be; the identifier in question
16981 	   will have no binding.  */
16982 	tmp = RECUR (tmp);
16983       else
16984 	tmp = DECL_NAME (tmp);
16985       finish_goto_stmt (tmp);
16986       break;
16987 
16988     case ASM_EXPR:
16989       {
16990 	tree string = RECUR (ASM_STRING (t));
16991 	tree outputs = tsubst_copy_asm_operands (ASM_OUTPUTS (t), args,
16992 						 complain, in_decl);
16993 	tree inputs = tsubst_copy_asm_operands (ASM_INPUTS (t), args,
16994 						complain, in_decl);
16995 	tree clobbers = tsubst_copy_asm_operands (ASM_CLOBBERS (t), args,
16996 	 					  complain, in_decl);
16997 	tree labels = tsubst_copy_asm_operands (ASM_LABELS (t), args,
16998 						complain, in_decl);
16999 	tmp = finish_asm_stmt (ASM_VOLATILE_P (t), string, outputs, inputs,
17000 			       clobbers, labels, ASM_INLINE_P (t));
17001 	tree asm_expr = tmp;
17002 	if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
17003 	  asm_expr = TREE_OPERAND (asm_expr, 0);
17004 	ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
17005       }
17006       break;
17007 
17008     case TRY_BLOCK:
17009       if (CLEANUP_P (t))
17010 	{
17011 	  stmt = begin_try_block ();
17012 	  RECUR (TRY_STMTS (t));
17013 	  finish_cleanup_try_block (stmt);
17014 	  finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
17015 	}
17016       else
17017 	{
17018 	  tree compound_stmt = NULL_TREE;
17019 
17020 	  if (FN_TRY_BLOCK_P (t))
17021 	    stmt = begin_function_try_block (&compound_stmt);
17022 	  else
17023 	    stmt = begin_try_block ();
17024 
17025 	  RECUR (TRY_STMTS (t));
17026 
17027 	  if (FN_TRY_BLOCK_P (t))
17028 	    finish_function_try_block (stmt);
17029 	  else
17030 	    finish_try_block (stmt);
17031 
17032 	  RECUR (TRY_HANDLERS (t));
17033 	  if (FN_TRY_BLOCK_P (t))
17034 	    finish_function_handler_sequence (stmt, compound_stmt);
17035 	  else
17036 	    finish_handler_sequence (stmt);
17037 	}
17038       break;
17039 
17040     case HANDLER:
17041       {
17042 	tree decl = HANDLER_PARMS (t);
17043 
17044 	if (decl)
17045 	  {
17046 	    decl = tsubst (decl, args, complain, in_decl);
17047 	    /* Prevent instantiate_decl from trying to instantiate
17048 	       this variable.  We've already done all that needs to be
17049 	       done.  */
17050 	    if (decl != error_mark_node)
17051 	      DECL_TEMPLATE_INSTANTIATED (decl) = 1;
17052 	  }
17053 	stmt = begin_handler ();
17054 	finish_handler_parms (decl, stmt);
17055 	RECUR (HANDLER_BODY (t));
17056 	finish_handler (stmt);
17057       }
17058       break;
17059 
17060     case TAG_DEFN:
17061       tmp = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
17062       if (CLASS_TYPE_P (tmp))
17063 	{
17064 	  /* Local classes are not independent templates; they are
17065 	     instantiated along with their containing function.  And this
17066 	     way we don't have to deal with pushing out of one local class
17067 	     to instantiate a member of another local class.  */
17068 	  /* Closures are handled by the LAMBDA_EXPR.  */
17069 	  gcc_assert (!LAMBDA_TYPE_P (TREE_TYPE (t)));
17070 	  complete_type (tmp);
17071 	  for (tree fld = TYPE_FIELDS (tmp); fld; fld = DECL_CHAIN (fld))
17072 	    if ((VAR_P (fld)
17073 		 || (TREE_CODE (fld) == FUNCTION_DECL
17074 		     && !DECL_ARTIFICIAL (fld)))
17075 		&& DECL_TEMPLATE_INSTANTIATION (fld))
17076 	      instantiate_decl (fld, /*defer_ok=*/false,
17077 				/*expl_inst_class=*/false);
17078 	}
17079       break;
17080 
17081     case STATIC_ASSERT:
17082       {
17083 	tree condition;
17084 
17085 	++c_inhibit_evaluation_warnings;
17086         condition =
17087           tsubst_expr (STATIC_ASSERT_CONDITION (t),
17088                        args,
17089                        complain, in_decl,
17090                        /*integral_constant_expression_p=*/true);
17091 	--c_inhibit_evaluation_warnings;
17092 
17093         finish_static_assert (condition,
17094                               STATIC_ASSERT_MESSAGE (t),
17095                               STATIC_ASSERT_SOURCE_LOCATION (t),
17096                               /*member_p=*/false);
17097       }
17098       break;
17099 
17100     case OACC_KERNELS:
17101     case OACC_PARALLEL:
17102       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_ACC, args, complain,
17103 				in_decl);
17104       stmt = begin_omp_parallel ();
17105       RECUR (OMP_BODY (t));
17106       finish_omp_construct (TREE_CODE (t), stmt, tmp);
17107       break;
17108 
17109     case OMP_PARALLEL:
17110       r = push_omp_privatization_clauses (OMP_PARALLEL_COMBINED (t));
17111       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t), C_ORT_OMP, args,
17112 				complain, in_decl);
17113       if (OMP_PARALLEL_COMBINED (t))
17114 	omp_parallel_combined_clauses = &tmp;
17115       stmt = begin_omp_parallel ();
17116       RECUR (OMP_PARALLEL_BODY (t));
17117       gcc_assert (omp_parallel_combined_clauses == NULL);
17118       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
17119 	= OMP_PARALLEL_COMBINED (t);
17120       pop_omp_privatization_clauses (r);
17121       break;
17122 
17123     case OMP_TASK:
17124       r = push_omp_privatization_clauses (false);
17125       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
17126 				complain, in_decl);
17127       stmt = begin_omp_task ();
17128       RECUR (OMP_TASK_BODY (t));
17129       finish_omp_task (tmp, stmt);
17130       pop_omp_privatization_clauses (r);
17131       break;
17132 
17133     case OMP_FOR:
17134     case OMP_SIMD:
17135     case OMP_DISTRIBUTE:
17136     case OMP_TASKLOOP:
17137     case OACC_LOOP:
17138       {
17139 	tree clauses, body, pre_body;
17140 	tree declv = NULL_TREE, initv = NULL_TREE, condv = NULL_TREE;
17141 	tree orig_declv = NULL_TREE;
17142 	tree incrv = NULL_TREE;
17143 	enum c_omp_region_type ort = C_ORT_OMP;
17144 	int i;
17145 
17146 	if (TREE_CODE (t) == OACC_LOOP)
17147 	  ort = C_ORT_ACC;
17148 
17149 	r = push_omp_privatization_clauses (OMP_FOR_INIT (t) == NULL_TREE);
17150 	clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t), ort, args, complain,
17151 				      in_decl);
17152 	if (OMP_FOR_INIT (t) != NULL_TREE)
17153 	  {
17154 	    declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
17155 	    if (OMP_FOR_ORIG_DECLS (t))
17156 	      orig_declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
17157 	    initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
17158 	    condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
17159 	    incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
17160 	  }
17161 
17162 	stmt = begin_omp_structured_block ();
17163 
17164 	pre_body = push_stmt_list ();
17165 	RECUR (OMP_FOR_PRE_BODY (t));
17166 	pre_body = pop_stmt_list (pre_body);
17167 
17168 	if (OMP_FOR_INIT (t) != NULL_TREE)
17169 	  for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
17170 	    tsubst_omp_for_iterator (t, i, declv, orig_declv, initv, condv,
17171 				     incrv, &clauses, args, complain, in_decl,
17172 				     integral_constant_expression_p);
17173 	omp_parallel_combined_clauses = NULL;
17174 
17175 	body = push_stmt_list ();
17176 	RECUR (OMP_FOR_BODY (t));
17177 	body = pop_stmt_list (body);
17178 
17179 	if (OMP_FOR_INIT (t) != NULL_TREE)
17180 	  t = finish_omp_for (EXPR_LOCATION (t), TREE_CODE (t), declv,
17181 			      orig_declv, initv, condv, incrv, body, pre_body,
17182 			      NULL, clauses);
17183 	else
17184 	  {
17185 	    t = make_node (TREE_CODE (t));
17186 	    TREE_TYPE (t) = void_type_node;
17187 	    OMP_FOR_BODY (t) = body;
17188 	    OMP_FOR_PRE_BODY (t) = pre_body;
17189 	    OMP_FOR_CLAUSES (t) = clauses;
17190 	    SET_EXPR_LOCATION (t, EXPR_LOCATION (t));
17191 	    add_stmt (t);
17192 	  }
17193 
17194 	add_stmt (finish_omp_structured_block (stmt));
17195 	pop_omp_privatization_clauses (r);
17196       }
17197       break;
17198 
17199     case OMP_SECTIONS:
17200       omp_parallel_combined_clauses = NULL;
17201       /* FALLTHRU */
17202     case OMP_SINGLE:
17203     case OMP_TEAMS:
17204     case OMP_CRITICAL:
17205       r = push_omp_privatization_clauses (TREE_CODE (t) == OMP_TEAMS
17206 					  && OMP_TEAMS_COMBINED (t));
17207       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_OMP, args, complain,
17208 				in_decl);
17209       stmt = push_stmt_list ();
17210       RECUR (OMP_BODY (t));
17211       stmt = pop_stmt_list (stmt);
17212 
17213       t = copy_node (t);
17214       OMP_BODY (t) = stmt;
17215       OMP_CLAUSES (t) = tmp;
17216       add_stmt (t);
17217       pop_omp_privatization_clauses (r);
17218       break;
17219 
17220     case OACC_DATA:
17221     case OMP_TARGET_DATA:
17222     case OMP_TARGET:
17223       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), (TREE_CODE (t) == OACC_DATA)
17224 				? C_ORT_ACC : C_ORT_OMP, args, complain,
17225 				in_decl);
17226       keep_next_level (true);
17227       stmt = begin_omp_structured_block ();
17228 
17229       RECUR (OMP_BODY (t));
17230       stmt = finish_omp_structured_block (stmt);
17231 
17232       t = copy_node (t);
17233       OMP_BODY (t) = stmt;
17234       OMP_CLAUSES (t) = tmp;
17235       if (TREE_CODE (t) == OMP_TARGET && OMP_TARGET_COMBINED (t))
17236 	{
17237 	  tree teams = cp_walk_tree (&stmt, tsubst_find_omp_teams, NULL, NULL);
17238 	  if (teams)
17239 	    {
17240 	      /* For combined target teams, ensure the num_teams and
17241 		 thread_limit clause expressions are evaluated on the host,
17242 		 before entering the target construct.  */
17243 	      tree c;
17244 	      for (c = OMP_TEAMS_CLAUSES (teams);
17245 		   c; c = OMP_CLAUSE_CHAIN (c))
17246 		if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS
17247 		     || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_THREAD_LIMIT)
17248 		    && TREE_CODE (OMP_CLAUSE_OPERAND (c, 0)) != INTEGER_CST)
17249 		  {
17250 		    tree expr = OMP_CLAUSE_OPERAND (c, 0);
17251 		    expr = force_target_expr (TREE_TYPE (expr), expr, tf_none);
17252 		    if (expr == error_mark_node)
17253 		      continue;
17254 		    tmp = TARGET_EXPR_SLOT (expr);
17255 		    add_stmt (expr);
17256 		    OMP_CLAUSE_OPERAND (c, 0) = expr;
17257 		    tree tc = build_omp_clause (OMP_CLAUSE_LOCATION (c),
17258 						OMP_CLAUSE_FIRSTPRIVATE);
17259 		    OMP_CLAUSE_DECL (tc) = tmp;
17260 		    OMP_CLAUSE_CHAIN (tc) = OMP_TARGET_CLAUSES (t);
17261 		    OMP_TARGET_CLAUSES (t) = tc;
17262 		  }
17263 	    }
17264 	}
17265       add_stmt (t);
17266       break;
17267 
17268     case OACC_DECLARE:
17269       t = copy_node (t);
17270       tmp = tsubst_omp_clauses (OACC_DECLARE_CLAUSES (t), C_ORT_ACC, args,
17271 				complain, in_decl);
17272       OACC_DECLARE_CLAUSES (t) = tmp;
17273       add_stmt (t);
17274       break;
17275 
17276     case OMP_TARGET_UPDATE:
17277     case OMP_TARGET_ENTER_DATA:
17278     case OMP_TARGET_EXIT_DATA:
17279       tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_OMP, args,
17280 				complain, in_decl);
17281       t = copy_node (t);
17282       OMP_STANDALONE_CLAUSES (t) = tmp;
17283       add_stmt (t);
17284       break;
17285 
17286     case OACC_ENTER_DATA:
17287     case OACC_EXIT_DATA:
17288     case OACC_UPDATE:
17289       tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_ACC, args,
17290 				complain, in_decl);
17291       t = copy_node (t);
17292       OMP_STANDALONE_CLAUSES (t) = tmp;
17293       add_stmt (t);
17294       break;
17295 
17296     case OMP_ORDERED:
17297       tmp = tsubst_omp_clauses (OMP_ORDERED_CLAUSES (t), C_ORT_OMP, args,
17298 				complain, in_decl);
17299       stmt = push_stmt_list ();
17300       RECUR (OMP_BODY (t));
17301       stmt = pop_stmt_list (stmt);
17302 
17303       t = copy_node (t);
17304       OMP_BODY (t) = stmt;
17305       OMP_ORDERED_CLAUSES (t) = tmp;
17306       add_stmt (t);
17307       break;
17308 
17309     case OMP_SECTION:
17310     case OMP_MASTER:
17311     case OMP_TASKGROUP:
17312       stmt = push_stmt_list ();
17313       RECUR (OMP_BODY (t));
17314       stmt = pop_stmt_list (stmt);
17315 
17316       t = copy_node (t);
17317       OMP_BODY (t) = stmt;
17318       add_stmt (t);
17319       break;
17320 
17321     case OMP_ATOMIC:
17322       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
17323       if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
17324 	{
17325 	  tree op1 = TREE_OPERAND (t, 1);
17326 	  tree rhs1 = NULL_TREE;
17327 	  tree lhs, rhs;
17328 	  if (TREE_CODE (op1) == COMPOUND_EXPR)
17329 	    {
17330 	      rhs1 = RECUR (TREE_OPERAND (op1, 0));
17331 	      op1 = TREE_OPERAND (op1, 1);
17332 	    }
17333 	  lhs = RECUR (TREE_OPERAND (op1, 0));
17334 	  rhs = RECUR (TREE_OPERAND (op1, 1));
17335 	  finish_omp_atomic (OMP_ATOMIC, TREE_CODE (op1), lhs, rhs,
17336 			     NULL_TREE, NULL_TREE, rhs1,
17337 			     OMP_ATOMIC_SEQ_CST (t));
17338 	}
17339       else
17340 	{
17341 	  tree op1 = TREE_OPERAND (t, 1);
17342 	  tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
17343 	  tree rhs1 = NULL_TREE;
17344 	  enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
17345 	  enum tree_code opcode = NOP_EXPR;
17346 	  if (code == OMP_ATOMIC_READ)
17347 	    {
17348 	      v = RECUR (TREE_OPERAND (op1, 0));
17349 	      lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
17350 	    }
17351 	  else if (code == OMP_ATOMIC_CAPTURE_OLD
17352 		   || code == OMP_ATOMIC_CAPTURE_NEW)
17353 	    {
17354 	      tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
17355 	      v = RECUR (TREE_OPERAND (op1, 0));
17356 	      lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
17357 	      if (TREE_CODE (op11) == COMPOUND_EXPR)
17358 		{
17359 		  rhs1 = RECUR (TREE_OPERAND (op11, 0));
17360 		  op11 = TREE_OPERAND (op11, 1);
17361 		}
17362 	      lhs = RECUR (TREE_OPERAND (op11, 0));
17363 	      rhs = RECUR (TREE_OPERAND (op11, 1));
17364 	      opcode = TREE_CODE (op11);
17365 	      if (opcode == MODIFY_EXPR)
17366 		opcode = NOP_EXPR;
17367 	    }
17368 	  else
17369 	    {
17370 	      code = OMP_ATOMIC;
17371 	      lhs = RECUR (TREE_OPERAND (op1, 0));
17372 	      rhs = RECUR (TREE_OPERAND (op1, 1));
17373 	    }
17374 	  finish_omp_atomic (code, opcode, lhs, rhs, v, lhs1, rhs1,
17375 			     OMP_ATOMIC_SEQ_CST (t));
17376 	}
17377       break;
17378 
17379     case TRANSACTION_EXPR:
17380       {
17381 	int flags = 0;
17382 	flags |= (TRANSACTION_EXPR_OUTER (t) ? TM_STMT_ATTR_OUTER : 0);
17383 	flags |= (TRANSACTION_EXPR_RELAXED (t) ? TM_STMT_ATTR_RELAXED : 0);
17384 
17385         if (TRANSACTION_EXPR_IS_STMT (t))
17386           {
17387 	    tree body = TRANSACTION_EXPR_BODY (t);
17388 	    tree noex = NULL_TREE;
17389 	    if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
17390 	      {
17391 		noex = MUST_NOT_THROW_COND (body);
17392 		if (noex == NULL_TREE)
17393 		  noex = boolean_true_node;
17394 		body = TREE_OPERAND (body, 0);
17395 	      }
17396             stmt = begin_transaction_stmt (input_location, NULL, flags);
17397             RECUR (body);
17398             finish_transaction_stmt (stmt, NULL, flags, RECUR (noex));
17399           }
17400         else
17401           {
17402             stmt = build_transaction_expr (EXPR_LOCATION (t),
17403 					   RECUR (TRANSACTION_EXPR_BODY (t)),
17404 					   flags, NULL_TREE);
17405             RETURN (stmt);
17406           }
17407       }
17408       break;
17409 
17410     case MUST_NOT_THROW_EXPR:
17411       {
17412 	tree op0 = RECUR (TREE_OPERAND (t, 0));
17413 	tree cond = RECUR (MUST_NOT_THROW_COND (t));
17414 	RETURN (build_must_not_throw_expr (op0, cond));
17415       }
17416 
17417     case EXPR_PACK_EXPANSION:
17418       error ("invalid use of pack expansion expression");
17419       RETURN (error_mark_node);
17420 
17421     case NONTYPE_ARGUMENT_PACK:
17422       error ("use %<...%> to expand argument pack");
17423       RETURN (error_mark_node);
17424 
17425     case COMPOUND_EXPR:
17426       tmp = RECUR (TREE_OPERAND (t, 0));
17427       if (tmp == NULL_TREE)
17428 	/* If the first operand was a statement, we're done with it.  */
17429 	RETURN (RECUR (TREE_OPERAND (t, 1)));
17430       RETURN (build_x_compound_expr (EXPR_LOCATION (t), tmp,
17431 				    RECUR (TREE_OPERAND (t, 1)),
17432 				    complain));
17433 
17434     case ANNOTATE_EXPR:
17435       tmp = RECUR (TREE_OPERAND (t, 0));
17436       RETURN (build3_loc (EXPR_LOCATION (t), ANNOTATE_EXPR,
17437 			  TREE_TYPE (tmp), tmp,
17438 			  RECUR (TREE_OPERAND (t, 1)),
17439 			  RECUR (TREE_OPERAND (t, 2))));
17440 
17441     default:
17442       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
17443 
17444       RETURN (tsubst_copy_and_build (t, args, complain, in_decl,
17445 				    /*function_p=*/false,
17446 				    integral_constant_expression_p));
17447     }
17448 
17449   RETURN (NULL_TREE);
17450  out:
17451   input_location = loc;
17452   return r;
17453 #undef RECUR
17454 #undef RETURN
17455 }
17456 
17457 /* Instantiate the special body of the artificial DECL_OMP_DECLARE_REDUCTION
17458    function.  For description of the body see comment above
17459    cp_parser_omp_declare_reduction_exprs.  */
17460 
17461 static void
tsubst_omp_udr(tree t,tree args,tsubst_flags_t complain,tree in_decl)17462 tsubst_omp_udr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
17463 {
17464   if (t == NULL_TREE || t == error_mark_node)
17465     return;
17466 
17467   gcc_assert (TREE_CODE (t) == STATEMENT_LIST);
17468 
17469   tree_stmt_iterator tsi;
17470   int i;
17471   tree stmts[7];
17472   memset (stmts, 0, sizeof stmts);
17473   for (i = 0, tsi = tsi_start (t);
17474        i < 7 && !tsi_end_p (tsi);
17475        i++, tsi_next (&tsi))
17476     stmts[i] = tsi_stmt (tsi);
17477   gcc_assert (tsi_end_p (tsi));
17478 
17479   if (i >= 3)
17480     {
17481       gcc_assert (TREE_CODE (stmts[0]) == DECL_EXPR
17482 		  && TREE_CODE (stmts[1]) == DECL_EXPR);
17483       tree omp_out = tsubst (DECL_EXPR_DECL (stmts[0]),
17484 			     args, complain, in_decl);
17485       tree omp_in = tsubst (DECL_EXPR_DECL (stmts[1]),
17486 			    args, complain, in_decl);
17487       DECL_CONTEXT (omp_out) = current_function_decl;
17488       DECL_CONTEXT (omp_in) = current_function_decl;
17489       keep_next_level (true);
17490       tree block = begin_omp_structured_block ();
17491       tsubst_expr (stmts[2], args, complain, in_decl, false);
17492       block = finish_omp_structured_block (block);
17493       block = maybe_cleanup_point_expr_void (block);
17494       add_decl_expr (omp_out);
17495       if (TREE_NO_WARNING (DECL_EXPR_DECL (stmts[0])))
17496 	TREE_NO_WARNING (omp_out) = 1;
17497       add_decl_expr (omp_in);
17498       finish_expr_stmt (block);
17499     }
17500   if (i >= 6)
17501     {
17502       gcc_assert (TREE_CODE (stmts[3]) == DECL_EXPR
17503 		  && TREE_CODE (stmts[4]) == DECL_EXPR);
17504       tree omp_priv = tsubst (DECL_EXPR_DECL (stmts[3]),
17505 			      args, complain, in_decl);
17506       tree omp_orig = tsubst (DECL_EXPR_DECL (stmts[4]),
17507 			      args, complain, in_decl);
17508       DECL_CONTEXT (omp_priv) = current_function_decl;
17509       DECL_CONTEXT (omp_orig) = current_function_decl;
17510       keep_next_level (true);
17511       tree block = begin_omp_structured_block ();
17512       tsubst_expr (stmts[5], args, complain, in_decl, false);
17513       block = finish_omp_structured_block (block);
17514       block = maybe_cleanup_point_expr_void (block);
17515       cp_walk_tree (&block, cp_remove_omp_priv_cleanup_stmt, omp_priv, NULL);
17516       add_decl_expr (omp_priv);
17517       add_decl_expr (omp_orig);
17518       finish_expr_stmt (block);
17519       if (i == 7)
17520 	add_decl_expr (omp_orig);
17521     }
17522 }
17523 
17524 /* T is a postfix-expression that is not being used in a function
17525    call.  Return the substituted version of T.  */
17526 
17527 static tree
tsubst_non_call_postfix_expression(tree t,tree args,tsubst_flags_t complain,tree in_decl)17528 tsubst_non_call_postfix_expression (tree t, tree args,
17529 				    tsubst_flags_t complain,
17530 				    tree in_decl)
17531 {
17532   if (TREE_CODE (t) == SCOPE_REF)
17533     t = tsubst_qualified_id (t, args, complain, in_decl,
17534 			     /*done=*/false, /*address_p=*/false);
17535   else
17536     t = tsubst_copy_and_build (t, args, complain, in_decl,
17537 			       /*function_p=*/false,
17538 			       /*integral_constant_expression_p=*/false);
17539 
17540   return t;
17541 }
17542 
17543 /* T is a LAMBDA_EXPR.  Generate a new LAMBDA_EXPR for the current
17544    instantiation context.  Instantiating a pack expansion containing a lambda
17545    might result in multiple lambdas all based on the same lambda in the
17546    template.  */
17547 
17548 tree
tsubst_lambda_expr(tree t,tree args,tsubst_flags_t complain,tree in_decl)17549 tsubst_lambda_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
17550 {
17551   tree oldfn = lambda_function (t);
17552   in_decl = oldfn;
17553 
17554   tree r = build_lambda_expr ();
17555 
17556   LAMBDA_EXPR_LOCATION (r)
17557     = LAMBDA_EXPR_LOCATION (t);
17558   LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
17559     = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
17560   LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
17561 
17562   if (LAMBDA_EXPR_EXTRA_SCOPE (t) == NULL_TREE)
17563     /* A lambda in a default argument outside a class gets no
17564        LAMBDA_EXPR_EXTRA_SCOPE, as specified by the ABI.  But
17565        tsubst_default_argument calls start_lambda_scope, so we need to
17566        specifically ignore it here, and use the global scope.  */
17567     record_null_lambda_scope (r);
17568   else
17569     record_lambda_scope (r);
17570 
17571   gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
17572 	      && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
17573 
17574   for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (t); cap;
17575        cap = TREE_CHAIN (cap))
17576     {
17577       tree field = TREE_PURPOSE (cap);
17578       if (PACK_EXPANSION_P (field))
17579 	field = PACK_EXPANSION_PATTERN (field);
17580       field = tsubst_decl (field, args, complain);
17581 
17582       if (field == error_mark_node)
17583 	return error_mark_node;
17584 
17585       tree init = TREE_VALUE (cap);
17586       if (PACK_EXPANSION_P (init))
17587 	init = tsubst_pack_expansion (init, args, complain, in_decl);
17588       else
17589 	init = tsubst_copy_and_build (init, args, complain, in_decl,
17590 				      /*fn*/false, /*constexpr*/false);
17591 
17592       if (TREE_CODE (field) == TREE_VEC)
17593 	{
17594 	  int len = TREE_VEC_LENGTH (field);
17595 	  gcc_assert (TREE_CODE (init) == TREE_VEC
17596 		      && TREE_VEC_LENGTH (init) == len);
17597 	  for (int i = 0; i < len; ++i)
17598 	    LAMBDA_EXPR_CAPTURE_LIST (r)
17599 	      = tree_cons (TREE_VEC_ELT (field, i),
17600 			   TREE_VEC_ELT (init, i),
17601 			   LAMBDA_EXPR_CAPTURE_LIST (r));
17602 	}
17603       else
17604 	{
17605 	  LAMBDA_EXPR_CAPTURE_LIST (r)
17606 	    = tree_cons (field, init, LAMBDA_EXPR_CAPTURE_LIST (r));
17607 
17608 	  if (id_equal (DECL_NAME (field), "__this"))
17609 	    LAMBDA_EXPR_THIS_CAPTURE (r) = field;
17610 	}
17611     }
17612 
17613   tree type = begin_lambda_type (r);
17614   if (type == error_mark_node)
17615     return error_mark_node;
17616 
17617   /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
17618   determine_visibility (TYPE_NAME (type));
17619 
17620   register_capture_members (LAMBDA_EXPR_CAPTURE_LIST (r));
17621 
17622   tree oldtmpl = (generic_lambda_fn_p (oldfn)
17623 		  ? DECL_TI_TEMPLATE (oldfn)
17624 		  : NULL_TREE);
17625 
17626   tree fntype = static_fn_type (oldfn);
17627   if (oldtmpl)
17628     ++processing_template_decl;
17629   fntype = tsubst (fntype, args, complain, in_decl);
17630   if (oldtmpl)
17631     --processing_template_decl;
17632 
17633   if (fntype == error_mark_node)
17634     r = error_mark_node;
17635   else
17636     {
17637       /* Fix the type of 'this'.  */
17638       fntype = build_memfn_type (fntype, type,
17639 				 type_memfn_quals (fntype),
17640 				 type_memfn_rqual (fntype));
17641       tree fn, tmpl;
17642       if (oldtmpl)
17643 	{
17644 	  tmpl = tsubst_template_decl (oldtmpl, args, complain, fntype);
17645 	  fn = DECL_TEMPLATE_RESULT (tmpl);
17646 	  finish_member_declaration (tmpl);
17647 	}
17648       else
17649 	{
17650 	  tmpl = NULL_TREE;
17651 	  fn = tsubst_function_decl (oldfn, args, complain, fntype);
17652 	  finish_member_declaration (fn);
17653 	}
17654 
17655       /* Let finish_function set this.  */
17656       DECL_DECLARED_CONSTEXPR_P (fn) = false;
17657 
17658       bool nested = cfun;
17659       if (nested)
17660 	push_function_context ();
17661       else
17662 	/* Still increment function_depth so that we don't GC in the
17663 	   middle of an expression.  */
17664 	++function_depth;
17665 
17666       local_specialization_stack s (lss_copy);
17667 
17668       tree body = start_lambda_function (fn, r);
17669 
17670       register_parameter_specializations (oldfn, fn);
17671 
17672       if (oldtmpl)
17673 	{
17674 	  /* We might not partially instantiate some parts of the function, so
17675 	     copy these flags from the original template.  */
17676 	  language_function *ol = DECL_STRUCT_FUNCTION (oldfn)->language;
17677 	  current_function_returns_value = ol->returns_value;
17678 	  current_function_returns_null = ol->returns_null;
17679 	  current_function_returns_abnormally = ol->returns_abnormally;
17680 	  current_function_infinite_loop = ol->infinite_loop;
17681 	}
17682 
17683       tsubst_expr (DECL_SAVED_TREE (oldfn), args, complain, r,
17684 		   /*constexpr*/false);
17685 
17686       finish_lambda_function (body);
17687 
17688       if (nested)
17689 	pop_function_context ();
17690       else
17691 	--function_depth;
17692 
17693       /* The capture list was built up in reverse order; fix that now.  */
17694       LAMBDA_EXPR_CAPTURE_LIST (r)
17695 	= nreverse (LAMBDA_EXPR_CAPTURE_LIST (r));
17696 
17697       LAMBDA_EXPR_THIS_CAPTURE (r) = NULL_TREE;
17698 
17699       maybe_add_lambda_conv_op (type);
17700     }
17701 
17702   finish_struct (type, /*attr*/NULL_TREE);
17703 
17704   insert_pending_capture_proxies ();
17705 
17706   return r;
17707 }
17708 
17709 /* Like tsubst but deals with expressions and performs semantic
17710    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
17711 
17712 tree
tsubst_copy_and_build(tree t,tree args,tsubst_flags_t complain,tree in_decl,bool function_p,bool integral_constant_expression_p)17713 tsubst_copy_and_build (tree t,
17714 		       tree args,
17715 		       tsubst_flags_t complain,
17716 		       tree in_decl,
17717 		       bool function_p,
17718 		       bool integral_constant_expression_p)
17719 {
17720 #define RETURN(EXP) do { retval = (EXP); goto out; } while(0)
17721 #define RECUR(NODE)						\
17722   tsubst_copy_and_build (NODE, args, complain, in_decl, 	\
17723 			 /*function_p=*/false,			\
17724 			 integral_constant_expression_p)
17725 
17726   tree retval, op1;
17727   location_t loc;
17728 
17729   if (t == NULL_TREE || t == error_mark_node)
17730     return t;
17731 
17732   loc = input_location;
17733   if (EXPR_HAS_LOCATION (t))
17734     input_location = EXPR_LOCATION (t);
17735 
17736   /* N3276 decltype magic only applies to calls at the top level or on the
17737      right side of a comma.  */
17738   tsubst_flags_t decltype_flag = (complain & tf_decltype);
17739   complain &= ~tf_decltype;
17740 
17741   switch (TREE_CODE (t))
17742     {
17743     case USING_DECL:
17744       t = DECL_NAME (t);
17745       /* Fall through.  */
17746     case IDENTIFIER_NODE:
17747       {
17748 	tree decl;
17749 	cp_id_kind idk;
17750 	bool non_integral_constant_expression_p;
17751 	const char *error_msg;
17752 
17753 	if (IDENTIFIER_CONV_OP_P (t))
17754 	  {
17755 	    tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17756 	    t = make_conv_op_name (new_type);
17757 	  }
17758 
17759 	/* Look up the name.  */
17760 	decl = lookup_name (t);
17761 
17762 	/* By convention, expressions use ERROR_MARK_NODE to indicate
17763 	   failure, not NULL_TREE.  */
17764 	if (decl == NULL_TREE)
17765 	  decl = error_mark_node;
17766 
17767 	decl = finish_id_expression (t, decl, NULL_TREE,
17768 				     &idk,
17769 				     integral_constant_expression_p,
17770           /*allow_non_integral_constant_expression_p=*/(cxx_dialect >= cxx11),
17771 				     &non_integral_constant_expression_p,
17772 				     /*template_p=*/false,
17773 				     /*done=*/true,
17774 				     /*address_p=*/false,
17775 				     /*template_arg_p=*/false,
17776 				     &error_msg,
17777 				     input_location);
17778 	if (error_msg)
17779 	  error (error_msg);
17780 	if (!function_p && identifier_p (decl))
17781 	  {
17782 	    if (complain & tf_error)
17783 	      unqualified_name_lookup_error (decl);
17784 	    decl = error_mark_node;
17785 	  }
17786 	RETURN (decl);
17787       }
17788 
17789     case TEMPLATE_ID_EXPR:
17790       {
17791 	tree object;
17792 	tree templ = RECUR (TREE_OPERAND (t, 0));
17793 	tree targs = TREE_OPERAND (t, 1);
17794 
17795 	if (targs)
17796 	  targs = tsubst_template_args (targs, args, complain, in_decl);
17797 	if (targs == error_mark_node)
17798 	  RETURN (error_mark_node);
17799 
17800 	if (TREE_CODE (templ) == SCOPE_REF)
17801 	  {
17802 	    tree name = TREE_OPERAND (templ, 1);
17803 	    tree tid = lookup_template_function (name, targs);
17804 	    TREE_OPERAND (templ, 1) = tid;
17805 	    RETURN (templ);
17806 	  }
17807 
17808 	if (variable_template_p (templ))
17809 	  RETURN (lookup_and_finish_template_variable (templ, targs, complain));
17810 
17811 	if (TREE_CODE (templ) == COMPONENT_REF)
17812 	  {
17813 	    object = TREE_OPERAND (templ, 0);
17814 	    templ = TREE_OPERAND (templ, 1);
17815 	  }
17816 	else
17817 	  object = NULL_TREE;
17818 	templ = lookup_template_function (templ, targs);
17819 
17820 	if (object)
17821 	  RETURN (build3 (COMPONENT_REF, TREE_TYPE (templ),
17822 			 object, templ, NULL_TREE));
17823 	else
17824 	  RETURN (baselink_for_fns (templ));
17825       }
17826 
17827     case INDIRECT_REF:
17828       {
17829 	tree r = RECUR (TREE_OPERAND (t, 0));
17830 
17831 	if (REFERENCE_REF_P (t))
17832 	  {
17833 	    /* A type conversion to reference type will be enclosed in
17834 	       such an indirect ref, but the substitution of the cast
17835 	       will have also added such an indirect ref.  */
17836 	    r = convert_from_reference (r);
17837 	  }
17838 	else
17839 	  r = build_x_indirect_ref (input_location, r, RO_UNARY_STAR,
17840 				    complain|decltype_flag);
17841 
17842 	if (REF_PARENTHESIZED_P (t))
17843 	  r = force_paren_expr (r);
17844 
17845 	RETURN (r);
17846       }
17847 
17848     case NOP_EXPR:
17849       {
17850 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17851 	tree op0 = RECUR (TREE_OPERAND (t, 0));
17852 	RETURN (build_nop (type, op0));
17853       }
17854 
17855     case IMPLICIT_CONV_EXPR:
17856       {
17857 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17858 	tree expr = RECUR (TREE_OPERAND (t, 0));
17859 	if (dependent_type_p (type) || type_dependent_expression_p (expr))
17860 	  {
17861 	    retval = copy_node (t);
17862 	    TREE_TYPE (retval) = type;
17863 	    TREE_OPERAND (retval, 0) = expr;
17864 	    RETURN (retval);
17865 	  }
17866 	if (IMPLICIT_CONV_EXPR_NONTYPE_ARG (t))
17867 	  /* We'll pass this to convert_nontype_argument again, we don't need
17868 	     to actually perform any conversion here.  */
17869 	  RETURN (expr);
17870 	int flags = LOOKUP_IMPLICIT;
17871 	if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
17872 	  flags = LOOKUP_NORMAL;
17873 	RETURN (perform_implicit_conversion_flags (type, expr, complain,
17874 						  flags));
17875       }
17876 
17877     case CONVERT_EXPR:
17878       {
17879 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17880 	tree op0 = RECUR (TREE_OPERAND (t, 0));
17881 	if (op0 == error_mark_node)
17882 	  RETURN (error_mark_node);
17883 	RETURN (build1 (CONVERT_EXPR, type, op0));
17884       }
17885 
17886     case CAST_EXPR:
17887     case REINTERPRET_CAST_EXPR:
17888     case CONST_CAST_EXPR:
17889     case DYNAMIC_CAST_EXPR:
17890     case STATIC_CAST_EXPR:
17891       {
17892 	tree type;
17893 	tree op, r = NULL_TREE;
17894 
17895 	type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17896 	if (integral_constant_expression_p
17897 	    && !cast_valid_in_integral_constant_expression_p (type))
17898 	  {
17899             if (complain & tf_error)
17900               error ("a cast to a type other than an integral or "
17901                      "enumeration type cannot appear in a constant-expression");
17902 	    RETURN (error_mark_node);
17903 	  }
17904 
17905 	op = RECUR (TREE_OPERAND (t, 0));
17906 
17907 	warning_sentinel s(warn_useless_cast);
17908 	warning_sentinel s2(warn_ignored_qualifiers);
17909 	switch (TREE_CODE (t))
17910 	  {
17911 	  case CAST_EXPR:
17912 	    r = build_functional_cast (type, op, complain);
17913 	    break;
17914 	  case REINTERPRET_CAST_EXPR:
17915 	    r = build_reinterpret_cast (type, op, complain);
17916 	    break;
17917 	  case CONST_CAST_EXPR:
17918 	    r = build_const_cast (type, op, complain);
17919 	    break;
17920 	  case DYNAMIC_CAST_EXPR:
17921 	    r = build_dynamic_cast (type, op, complain);
17922 	    break;
17923 	  case STATIC_CAST_EXPR:
17924 	    r = build_static_cast (type, op, complain);
17925 	    break;
17926 	  default:
17927 	    gcc_unreachable ();
17928 	  }
17929 
17930 	RETURN (r);
17931       }
17932 
17933     case POSTDECREMENT_EXPR:
17934     case POSTINCREMENT_EXPR:
17935       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
17936 						args, complain, in_decl);
17937       RETURN (build_x_unary_op (input_location, TREE_CODE (t), op1,
17938 				complain|decltype_flag));
17939 
17940     case PREDECREMENT_EXPR:
17941     case PREINCREMENT_EXPR:
17942     case NEGATE_EXPR:
17943     case BIT_NOT_EXPR:
17944     case ABS_EXPR:
17945     case TRUTH_NOT_EXPR:
17946     case UNARY_PLUS_EXPR:  /* Unary + */
17947     case REALPART_EXPR:
17948     case IMAGPART_EXPR:
17949       RETURN (build_x_unary_op (input_location, TREE_CODE (t),
17950 				RECUR (TREE_OPERAND (t, 0)),
17951 				complain|decltype_flag));
17952 
17953     case FIX_TRUNC_EXPR:
17954       gcc_unreachable ();
17955 
17956     case ADDR_EXPR:
17957       op1 = TREE_OPERAND (t, 0);
17958       if (TREE_CODE (op1) == LABEL_DECL)
17959 	RETURN (finish_label_address_expr (DECL_NAME (op1),
17960 					  EXPR_LOCATION (op1)));
17961       if (TREE_CODE (op1) == SCOPE_REF)
17962 	op1 = tsubst_qualified_id (op1, args, complain, in_decl,
17963 				   /*done=*/true, /*address_p=*/true);
17964       else
17965 	op1 = tsubst_non_call_postfix_expression (op1, args, complain,
17966 						  in_decl);
17967       RETURN (build_x_unary_op (input_location, ADDR_EXPR, op1,
17968 				complain|decltype_flag));
17969 
17970     case PLUS_EXPR:
17971     case MINUS_EXPR:
17972     case MULT_EXPR:
17973     case TRUNC_DIV_EXPR:
17974     case CEIL_DIV_EXPR:
17975     case FLOOR_DIV_EXPR:
17976     case ROUND_DIV_EXPR:
17977     case EXACT_DIV_EXPR:
17978     case BIT_AND_EXPR:
17979     case BIT_IOR_EXPR:
17980     case BIT_XOR_EXPR:
17981     case TRUNC_MOD_EXPR:
17982     case FLOOR_MOD_EXPR:
17983     case TRUTH_ANDIF_EXPR:
17984     case TRUTH_ORIF_EXPR:
17985     case TRUTH_AND_EXPR:
17986     case TRUTH_OR_EXPR:
17987     case RSHIFT_EXPR:
17988     case LSHIFT_EXPR:
17989     case RROTATE_EXPR:
17990     case LROTATE_EXPR:
17991     case EQ_EXPR:
17992     case NE_EXPR:
17993     case MAX_EXPR:
17994     case MIN_EXPR:
17995     case LE_EXPR:
17996     case GE_EXPR:
17997     case LT_EXPR:
17998     case GT_EXPR:
17999     case MEMBER_REF:
18000     case DOTSTAR_EXPR:
18001       {
18002 	warning_sentinel s1(warn_type_limits);
18003 	warning_sentinel s2(warn_div_by_zero);
18004 	warning_sentinel s3(warn_logical_op);
18005 	warning_sentinel s4(warn_tautological_compare);
18006 	tree op0 = RECUR (TREE_OPERAND (t, 0));
18007 	tree op1 = RECUR (TREE_OPERAND (t, 1));
18008 	tree r = build_x_binary_op
18009 	  (input_location, TREE_CODE (t),
18010 	   op0,
18011 	   (TREE_NO_WARNING (TREE_OPERAND (t, 0))
18012 	    ? ERROR_MARK
18013 	    : TREE_CODE (TREE_OPERAND (t, 0))),
18014 	   op1,
18015 	   (TREE_NO_WARNING (TREE_OPERAND (t, 1))
18016 	    ? ERROR_MARK
18017 	    : TREE_CODE (TREE_OPERAND (t, 1))),
18018 	   /*overload=*/NULL,
18019 	   complain|decltype_flag);
18020 	if (EXPR_P (r) && TREE_NO_WARNING (t))
18021 	  TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
18022 
18023 	RETURN (r);
18024       }
18025 
18026     case POINTER_PLUS_EXPR:
18027       {
18028 	tree op0 = RECUR (TREE_OPERAND (t, 0));
18029 	tree op1 = RECUR (TREE_OPERAND (t, 1));
18030 	RETURN (fold_build_pointer_plus (op0, op1));
18031       }
18032 
18033     case SCOPE_REF:
18034       RETURN (tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
18035 				  /*address_p=*/false));
18036     case ARRAY_REF:
18037       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
18038 						args, complain, in_decl);
18039       RETURN (build_x_array_ref (EXPR_LOCATION (t), op1,
18040 				 RECUR (TREE_OPERAND (t, 1)),
18041 				 complain|decltype_flag));
18042 
18043     case SIZEOF_EXPR:
18044       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
18045 	  || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
18046 	RETURN (tsubst_copy (t, args, complain, in_decl));
18047       /* Fall through */
18048 
18049     case ALIGNOF_EXPR:
18050       {
18051 	tree r;
18052 
18053 	op1 = TREE_OPERAND (t, 0);
18054 	if (TREE_CODE (t) == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (t))
18055 	  op1 = TREE_TYPE (op1);
18056 	bool std_alignof = (TREE_CODE (t) == ALIGNOF_EXPR
18057 			    && ALIGNOF_EXPR_STD_P (t));
18058         if (!args)
18059 	  {
18060 	    /* When there are no ARGS, we are trying to evaluate a
18061 	       non-dependent expression from the parser.  Trying to do
18062 	       the substitutions may not work.  */
18063 	    if (!TYPE_P (op1))
18064 	      op1 = TREE_TYPE (op1);
18065 	  }
18066 	else
18067 	  {
18068 	    ++cp_unevaluated_operand;
18069 	    ++c_inhibit_evaluation_warnings;
18070 	    if (TYPE_P (op1))
18071 	      op1 = tsubst (op1, args, complain, in_decl);
18072 	    else
18073 	      op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
18074 					   /*function_p=*/false,
18075 					   /*integral_constant_expression_p=*/
18076 					   false);
18077 	    --cp_unevaluated_operand;
18078 	    --c_inhibit_evaluation_warnings;
18079 	  }
18080         if (TYPE_P (op1))
18081 	  r = cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), std_alignof,
18082 					  complain & tf_error);
18083 	else
18084 	  r = cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t),
18085 					  complain & tf_error);
18086 	if (TREE_CODE (t) == SIZEOF_EXPR && r != error_mark_node)
18087 	  {
18088 	    if (TREE_CODE (r) != SIZEOF_EXPR || TYPE_P (op1))
18089 	      {
18090 		if (!processing_template_decl && TYPE_P (op1))
18091 		  {
18092 		    r = build_min (SIZEOF_EXPR, size_type_node,
18093 				   build1 (NOP_EXPR, op1, error_mark_node));
18094 		    SIZEOF_EXPR_TYPE_P (r) = 1;
18095 		  }
18096 		else
18097 		  r = build_min (SIZEOF_EXPR, size_type_node, op1);
18098 		TREE_SIDE_EFFECTS (r) = 0;
18099 		TREE_READONLY (r) = 1;
18100 	      }
18101 	    SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
18102 	  }
18103 	RETURN (r);
18104       }
18105 
18106     case AT_ENCODE_EXPR:
18107       {
18108 	op1 = TREE_OPERAND (t, 0);
18109 	++cp_unevaluated_operand;
18110 	++c_inhibit_evaluation_warnings;
18111 	op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
18112 				     /*function_p=*/false,
18113 				     /*integral_constant_expression_p=*/false);
18114 	--cp_unevaluated_operand;
18115 	--c_inhibit_evaluation_warnings;
18116 	RETURN (objc_build_encode_expr (op1));
18117       }
18118 
18119     case NOEXCEPT_EXPR:
18120       op1 = TREE_OPERAND (t, 0);
18121       ++cp_unevaluated_operand;
18122       ++c_inhibit_evaluation_warnings;
18123       ++cp_noexcept_operand;
18124       op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
18125 				   /*function_p=*/false,
18126 				   /*integral_constant_expression_p=*/false);
18127       --cp_unevaluated_operand;
18128       --c_inhibit_evaluation_warnings;
18129       --cp_noexcept_operand;
18130       RETURN (finish_noexcept_expr (op1, complain));
18131 
18132     case MODOP_EXPR:
18133       {
18134 	warning_sentinel s(warn_div_by_zero);
18135 	tree lhs = RECUR (TREE_OPERAND (t, 0));
18136 	tree rhs = RECUR (TREE_OPERAND (t, 2));
18137 	tree r = build_x_modify_expr
18138 	  (EXPR_LOCATION (t), lhs, TREE_CODE (TREE_OPERAND (t, 1)), rhs,
18139 	   complain|decltype_flag);
18140 	/* TREE_NO_WARNING must be set if either the expression was
18141 	   parenthesized or it uses an operator such as >>= rather
18142 	   than plain assignment.  In the former case, it was already
18143 	   set and must be copied.  In the latter case,
18144 	   build_x_modify_expr sets it and it must not be reset
18145 	   here.  */
18146 	if (TREE_NO_WARNING (t))
18147 	  TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
18148 
18149 	RETURN (r);
18150       }
18151 
18152     case ARROW_EXPR:
18153       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
18154 						args, complain, in_decl);
18155       /* Remember that there was a reference to this entity.  */
18156       if (DECL_P (op1)
18157 	  && !mark_used (op1, complain) && !(complain & tf_error))
18158 	RETURN (error_mark_node);
18159       RETURN (build_x_arrow (input_location, op1, complain));
18160 
18161     case NEW_EXPR:
18162       {
18163 	tree placement = RECUR (TREE_OPERAND (t, 0));
18164 	tree init = RECUR (TREE_OPERAND (t, 3));
18165 	vec<tree, va_gc> *placement_vec;
18166 	vec<tree, va_gc> *init_vec;
18167 	tree ret;
18168 
18169 	if (placement == NULL_TREE)
18170 	  placement_vec = NULL;
18171 	else
18172 	  {
18173 	    placement_vec = make_tree_vector ();
18174 	    for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
18175 	      vec_safe_push (placement_vec, TREE_VALUE (placement));
18176 	  }
18177 
18178 	/* If there was an initializer in the original tree, but it
18179 	   instantiated to an empty list, then we should pass a
18180 	   non-NULL empty vector to tell build_new that it was an
18181 	   empty initializer() rather than no initializer.  This can
18182 	   only happen when the initializer is a pack expansion whose
18183 	   parameter packs are of length zero.  */
18184 	if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
18185 	  init_vec = NULL;
18186 	else
18187 	  {
18188 	    init_vec = make_tree_vector ();
18189 	    if (init == void_node)
18190 	      gcc_assert (init_vec != NULL);
18191 	    else
18192 	      {
18193 		for (; init != NULL_TREE; init = TREE_CHAIN (init))
18194 		  vec_safe_push (init_vec, TREE_VALUE (init));
18195 	      }
18196 	  }
18197 
18198 	tree op1 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
18199 	tree op2 = RECUR (TREE_OPERAND (t, 2));
18200 	ret = build_new (&placement_vec, op1, op2, &init_vec,
18201 			 NEW_EXPR_USE_GLOBAL (t),
18202 			 complain);
18203 
18204 	if (placement_vec != NULL)
18205 	  release_tree_vector (placement_vec);
18206 	if (init_vec != NULL)
18207 	  release_tree_vector (init_vec);
18208 
18209 	RETURN (ret);
18210       }
18211 
18212     case DELETE_EXPR:
18213       {
18214 	tree op0 = RECUR (TREE_OPERAND (t, 0));
18215 	tree op1 = RECUR (TREE_OPERAND (t, 1));
18216 	RETURN (delete_sanity (op0, op1,
18217 			       DELETE_EXPR_USE_VEC (t),
18218 			       DELETE_EXPR_USE_GLOBAL (t),
18219 			       complain));
18220       }
18221 
18222     case COMPOUND_EXPR:
18223       {
18224 	tree op0 = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
18225 					  complain & ~tf_decltype, in_decl,
18226 					  /*function_p=*/false,
18227 					  integral_constant_expression_p);
18228 	RETURN (build_x_compound_expr (EXPR_LOCATION (t),
18229 				       op0,
18230 				       RECUR (TREE_OPERAND (t, 1)),
18231 				       complain|decltype_flag));
18232       }
18233 
18234     case CALL_EXPR:
18235       {
18236 	tree function;
18237 	vec<tree, va_gc> *call_args;
18238 	unsigned int nargs, i;
18239 	bool qualified_p;
18240 	bool koenig_p;
18241 	tree ret;
18242 
18243 	function = CALL_EXPR_FN (t);
18244 	/* Internal function with no arguments.  */
18245 	if (function == NULL_TREE && call_expr_nargs (t) == 0)
18246 	  RETURN (t);
18247 
18248 	/* When we parsed the expression, we determined whether or
18249 	   not Koenig lookup should be performed.  */
18250 	koenig_p = KOENIG_LOOKUP_P (t);
18251 	if (function == NULL_TREE)
18252 	  {
18253 	    koenig_p = false;
18254 	    qualified_p = false;
18255 	  }
18256 	else if (TREE_CODE (function) == SCOPE_REF)
18257 	  {
18258 	    qualified_p = true;
18259 	    function = tsubst_qualified_id (function, args, complain, in_decl,
18260 					    /*done=*/false,
18261 					    /*address_p=*/false);
18262 	  }
18263 	else if (koenig_p && identifier_p (function))
18264 	  {
18265 	    /* Do nothing; calling tsubst_copy_and_build on an identifier
18266 	       would incorrectly perform unqualified lookup again.
18267 
18268 	       Note that we can also have an IDENTIFIER_NODE if the earlier
18269 	       unqualified lookup found a member function; in that case
18270 	       koenig_p will be false and we do want to do the lookup
18271 	       again to find the instantiated member function.
18272 
18273 	       FIXME but doing that causes c++/15272, so we need to stop
18274 	       using IDENTIFIER_NODE in that situation.  */
18275 	    qualified_p = false;
18276 	  }
18277 	else
18278 	  {
18279 	    if (TREE_CODE (function) == COMPONENT_REF)
18280 	      {
18281 		tree op = TREE_OPERAND (function, 1);
18282 
18283 		qualified_p = (TREE_CODE (op) == SCOPE_REF
18284 			       || (BASELINK_P (op)
18285 				   && BASELINK_QUALIFIED_P (op)));
18286 	      }
18287 	    else
18288 	      qualified_p = false;
18289 
18290 	    if (TREE_CODE (function) == ADDR_EXPR
18291 		&& TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL)
18292 	      /* Avoid error about taking the address of a constructor.  */
18293 	      function = TREE_OPERAND (function, 0);
18294 
18295 	    function = tsubst_copy_and_build (function, args, complain,
18296 					      in_decl,
18297 					      !qualified_p,
18298 					      integral_constant_expression_p);
18299 
18300 	    if (BASELINK_P (function))
18301 	      qualified_p = true;
18302 	  }
18303 
18304 	nargs = call_expr_nargs (t);
18305 	call_args = make_tree_vector ();
18306 	for (i = 0; i < nargs; ++i)
18307 	  {
18308 	    tree arg = CALL_EXPR_ARG (t, i);
18309 
18310 	    if (!PACK_EXPANSION_P (arg))
18311 	      vec_safe_push (call_args, RECUR (CALL_EXPR_ARG (t, i)));
18312 	    else
18313 	      {
18314 		/* Expand the pack expansion and push each entry onto
18315 		   CALL_ARGS.  */
18316 		arg = tsubst_pack_expansion (arg, args, complain, in_decl);
18317 		if (TREE_CODE (arg) == TREE_VEC)
18318 		  {
18319 		    unsigned int len, j;
18320 
18321 		    len = TREE_VEC_LENGTH (arg);
18322 		    for (j = 0; j < len; ++j)
18323 		      {
18324 			tree value = TREE_VEC_ELT (arg, j);
18325 			if (value != NULL_TREE)
18326 			  value = convert_from_reference (value);
18327 			vec_safe_push (call_args, value);
18328 		      }
18329 		  }
18330 		else
18331 		  {
18332 		    /* A partial substitution.  Add one entry.  */
18333 		    vec_safe_push (call_args, arg);
18334 		  }
18335 	      }
18336 	  }
18337 
18338 	/* We do not perform argument-dependent lookup if normal
18339 	   lookup finds a non-function, in accordance with the
18340 	   expected resolution of DR 218.  */
18341 	if (koenig_p
18342 	    && ((is_overloaded_fn (function)
18343 		 /* If lookup found a member function, the Koenig lookup is
18344 		    not appropriate, even if an unqualified-name was used
18345 		    to denote the function.  */
18346 		 && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
18347 		|| identifier_p (function))
18348 	    /* Only do this when substitution turns a dependent call
18349 	       into a non-dependent call.  */
18350 	    && type_dependent_expression_p_push (t)
18351 	    && !any_type_dependent_arguments_p (call_args))
18352 	  function = perform_koenig_lookup (function, call_args, tf_none);
18353 
18354 	if (function != NULL_TREE
18355 	    && identifier_p (function)
18356 	    && !any_type_dependent_arguments_p (call_args))
18357 	  {
18358 	    if (koenig_p && (complain & tf_warning_or_error))
18359 	      {
18360 		/* For backwards compatibility and good diagnostics, try
18361 		   the unqualified lookup again if we aren't in SFINAE
18362 		   context.  */
18363 		tree unq = (tsubst_copy_and_build
18364 			    (function, args, complain, in_decl, true,
18365 			     integral_constant_expression_p));
18366 		if (unq == error_mark_node)
18367 		  {
18368 		    release_tree_vector (call_args);
18369 		    RETURN (error_mark_node);
18370 		  }
18371 
18372 		if (unq != function)
18373 		  {
18374 		    /* In a lambda fn, we have to be careful to not
18375 		       introduce new this captures.  Legacy code can't
18376 		       be using lambdas anyway, so it's ok to be
18377 		       stricter.  */
18378 		    bool in_lambda = (current_class_type
18379 				      && LAMBDA_TYPE_P (current_class_type));
18380 		    char const *const msg
18381 		      = G_("%qD was not declared in this scope, "
18382 			   "and no declarations were found by "
18383 			   "argument-dependent lookup at the point "
18384 			   "of instantiation");
18385 
18386 		    bool diag = true;
18387 		    if (in_lambda)
18388 		      error_at (EXPR_LOC_OR_LOC (t, input_location),
18389 				msg, function);
18390 		    else
18391 		      diag = permerror (EXPR_LOC_OR_LOC (t, input_location),
18392 					msg, function);
18393 		    if (diag)
18394 		      {
18395 			tree fn = unq;
18396 
18397 			if (INDIRECT_REF_P (fn))
18398 			  fn = TREE_OPERAND (fn, 0);
18399 			if (is_overloaded_fn (fn))
18400 			  fn = get_first_fn (fn);
18401 
18402 			if (!DECL_P (fn))
18403 			  /* Can't say anything more.  */;
18404 			else if (DECL_CLASS_SCOPE_P (fn))
18405 			  {
18406 			    location_t loc = EXPR_LOC_OR_LOC (t,
18407 							      input_location);
18408 			    inform (loc,
18409 				    "declarations in dependent base %qT are "
18410 				    "not found by unqualified lookup",
18411 				    DECL_CLASS_CONTEXT (fn));
18412 			    if (current_class_ptr)
18413 			      inform (loc,
18414 				      "use %<this->%D%> instead", function);
18415 			    else
18416 			      inform (loc,
18417 				      "use %<%T::%D%> instead",
18418 				      current_class_name, function);
18419 			  }
18420 			else
18421 			  inform (DECL_SOURCE_LOCATION (fn),
18422 				  "%qD declared here, later in the "
18423 				  "translation unit", fn);
18424 			if (in_lambda)
18425 			  {
18426 			    release_tree_vector (call_args);
18427 			    RETURN (error_mark_node);
18428 			  }
18429 		      }
18430 
18431 		    function = unq;
18432 		  }
18433 	      }
18434 	    if (identifier_p (function))
18435 	      {
18436 		if (complain & tf_error)
18437 		  unqualified_name_lookup_error (function);
18438 		release_tree_vector (call_args);
18439 		RETURN (error_mark_node);
18440 	      }
18441 	  }
18442 
18443 	/* Remember that there was a reference to this entity.  */
18444 	if (function != NULL_TREE
18445 	    && DECL_P (function)
18446 	    && !mark_used (function, complain) && !(complain & tf_error))
18447 	  {
18448 	    release_tree_vector (call_args);
18449 	    RETURN (error_mark_node);
18450 	  }
18451 
18452 	/* Put back tf_decltype for the actual call.  */
18453 	complain |= decltype_flag;
18454 
18455 	if (function == NULL_TREE)
18456 	  switch (CALL_EXPR_IFN (t))
18457 	    {
18458 	    case IFN_LAUNDER:
18459 	      gcc_assert (nargs == 1);
18460 	      if (vec_safe_length (call_args) != 1)
18461 		{
18462 		  error_at (EXPR_LOC_OR_LOC (t, input_location),
18463 			    "wrong number of arguments to "
18464 			    "%<__builtin_launder%>");
18465 		  ret = error_mark_node;
18466 		}
18467 	      else
18468 		ret = finish_builtin_launder (EXPR_LOC_OR_LOC (t,
18469 							       input_location),
18470 					      (*call_args)[0], complain);
18471 	      break;
18472 
18473 	    default:
18474 	      /* Unsupported internal function with arguments.  */
18475 	      gcc_unreachable ();
18476 	    }
18477 	else if (TREE_CODE (function) == OFFSET_REF
18478 		 || TREE_CODE (function) == DOTSTAR_EXPR
18479 		 || TREE_CODE (function) == MEMBER_REF)
18480 	  ret = build_offset_ref_call_from_tree (function, &call_args,
18481 						 complain);
18482 	else if (TREE_CODE (function) == COMPONENT_REF)
18483 	  {
18484 	    tree instance = TREE_OPERAND (function, 0);
18485 	    tree fn = TREE_OPERAND (function, 1);
18486 
18487 	    if (processing_template_decl
18488 		&& (type_dependent_expression_p (instance)
18489 		    || (!BASELINK_P (fn)
18490 			&& TREE_CODE (fn) != FIELD_DECL)
18491 		    || type_dependent_expression_p (fn)
18492 		    || any_type_dependent_arguments_p (call_args)))
18493 	      ret = build_min_nt_call_vec (function, call_args);
18494 	    else if (!BASELINK_P (fn))
18495 	      ret = finish_call_expr (function, &call_args,
18496 				       /*disallow_virtual=*/false,
18497 				       /*koenig_p=*/false,
18498 				       complain);
18499 	    else
18500 	      ret = (build_new_method_call
18501 		      (instance, fn,
18502 		       &call_args, NULL_TREE,
18503 		       qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
18504 		       /*fn_p=*/NULL,
18505 		       complain));
18506 	  }
18507 	else
18508 	  ret = finish_call_expr (function, &call_args,
18509 				  /*disallow_virtual=*/qualified_p,
18510 				  koenig_p,
18511 				  complain);
18512 
18513 	release_tree_vector (call_args);
18514 
18515 	if (ret != error_mark_node)
18516 	  {
18517 	    bool op = CALL_EXPR_OPERATOR_SYNTAX (t);
18518 	    bool ord = CALL_EXPR_ORDERED_ARGS (t);
18519 	    bool rev = CALL_EXPR_REVERSE_ARGS (t);
18520 	    bool thk = CALL_FROM_THUNK_P (t);
18521 	    if (op || ord || rev || thk)
18522 	      {
18523 		function = extract_call_expr (ret);
18524 		CALL_EXPR_OPERATOR_SYNTAX (function) = op;
18525 		CALL_EXPR_ORDERED_ARGS (function) = ord;
18526 		CALL_EXPR_REVERSE_ARGS (function) = rev;
18527 		if (thk)
18528 		  {
18529 		    /* The thunk location is not interesting.  */
18530 		    SET_EXPR_LOCATION (function, UNKNOWN_LOCATION);
18531 		  }
18532 	      }
18533 	  }
18534 
18535 	RETURN (ret);
18536       }
18537 
18538     case COND_EXPR:
18539       {
18540 	tree cond = RECUR (TREE_OPERAND (t, 0));
18541 	cond = mark_rvalue_use (cond);
18542 	tree folded_cond = fold_non_dependent_expr (cond);
18543 	tree exp1, exp2;
18544 
18545 	if (TREE_CODE (folded_cond) == INTEGER_CST)
18546 	  {
18547 	    if (integer_zerop (folded_cond))
18548 	      {
18549 		++c_inhibit_evaluation_warnings;
18550 		exp1 = RECUR (TREE_OPERAND (t, 1));
18551 		--c_inhibit_evaluation_warnings;
18552 		exp2 = RECUR (TREE_OPERAND (t, 2));
18553 	      }
18554 	    else
18555 	      {
18556 		exp1 = RECUR (TREE_OPERAND (t, 1));
18557 		++c_inhibit_evaluation_warnings;
18558 		exp2 = RECUR (TREE_OPERAND (t, 2));
18559 		--c_inhibit_evaluation_warnings;
18560 	      }
18561 	    cond = folded_cond;
18562 	  }
18563 	else
18564 	  {
18565 	    exp1 = RECUR (TREE_OPERAND (t, 1));
18566 	    exp2 = RECUR (TREE_OPERAND (t, 2));
18567 	  }
18568 
18569 	warning_sentinel s(warn_duplicated_branches);
18570 	RETURN (build_x_conditional_expr (EXPR_LOCATION (t),
18571 					 cond, exp1, exp2, complain));
18572       }
18573 
18574     case PSEUDO_DTOR_EXPR:
18575       {
18576 	tree op0 = RECUR (TREE_OPERAND (t, 0));
18577 	tree op1 = RECUR (TREE_OPERAND (t, 1));
18578 	tree op2 = tsubst (TREE_OPERAND (t, 2), args, complain, in_decl);
18579 	RETURN (finish_pseudo_destructor_expr (op0, op1, op2,
18580 					       input_location));
18581       }
18582 
18583     case TREE_LIST:
18584       {
18585 	tree purpose, value, chain;
18586 
18587 	if (t == void_list_node)
18588 	  RETURN (t);
18589 
18590         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
18591             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
18592           {
18593             /* We have pack expansions, so expand those and
18594                create a new list out of it.  */
18595             tree purposevec = NULL_TREE;
18596             tree valuevec = NULL_TREE;
18597             tree chain;
18598             int i, len = -1;
18599 
18600             /* Expand the argument expressions.  */
18601             if (TREE_PURPOSE (t))
18602               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
18603                                                  complain, in_decl);
18604             if (TREE_VALUE (t))
18605               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
18606                                                complain, in_decl);
18607 
18608             /* Build the rest of the list.  */
18609             chain = TREE_CHAIN (t);
18610             if (chain && chain != void_type_node)
18611               chain = RECUR (chain);
18612 
18613             /* Determine the number of arguments.  */
18614             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
18615               {
18616                 len = TREE_VEC_LENGTH (purposevec);
18617                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
18618               }
18619             else if (TREE_CODE (valuevec) == TREE_VEC)
18620               len = TREE_VEC_LENGTH (valuevec);
18621             else
18622               {
18623                 /* Since we only performed a partial substitution into
18624                    the argument pack, we only RETURN (a single list
18625                    node.  */
18626                 if (purposevec == TREE_PURPOSE (t)
18627                     && valuevec == TREE_VALUE (t)
18628                     && chain == TREE_CHAIN (t))
18629                   RETURN (t);
18630 
18631                 RETURN (tree_cons (purposevec, valuevec, chain));
18632               }
18633 
18634             /* Convert the argument vectors into a TREE_LIST */
18635             i = len;
18636             while (i > 0)
18637               {
18638                 /* Grab the Ith values.  */
18639                 i--;
18640                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i)
18641 		                     : NULL_TREE;
18642                 value
18643 		  = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i))
18644                              : NULL_TREE;
18645 
18646                 /* Build the list (backwards).  */
18647                 chain = tree_cons (purpose, value, chain);
18648               }
18649 
18650             RETURN (chain);
18651           }
18652 
18653 	purpose = TREE_PURPOSE (t);
18654 	if (purpose)
18655 	  purpose = RECUR (purpose);
18656 	value = TREE_VALUE (t);
18657 	if (value)
18658 	  value = RECUR (value);
18659 	chain = TREE_CHAIN (t);
18660 	if (chain && chain != void_type_node)
18661 	  chain = RECUR (chain);
18662 	if (purpose == TREE_PURPOSE (t)
18663 	    && value == TREE_VALUE (t)
18664 	    && chain == TREE_CHAIN (t))
18665 	  RETURN (t);
18666 	RETURN (tree_cons (purpose, value, chain));
18667       }
18668 
18669     case COMPONENT_REF:
18670       {
18671 	tree object;
18672 	tree object_type;
18673 	tree member;
18674 	tree r;
18675 
18676 	object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
18677 						     args, complain, in_decl);
18678 	/* Remember that there was a reference to this entity.  */
18679 	if (DECL_P (object)
18680 	    && !mark_used (object, complain) && !(complain & tf_error))
18681 	  RETURN (error_mark_node);
18682 	object_type = TREE_TYPE (object);
18683 
18684 	member = TREE_OPERAND (t, 1);
18685 	if (BASELINK_P (member))
18686 	  member = tsubst_baselink (member,
18687 				    non_reference (TREE_TYPE (object)),
18688 				    args, complain, in_decl);
18689 	else
18690 	  member = tsubst_copy (member, args, complain, in_decl);
18691 	if (member == error_mark_node)
18692 	  RETURN (error_mark_node);
18693 
18694 	if (TREE_CODE (member) == FIELD_DECL)
18695 	  {
18696 	    r = finish_non_static_data_member (member, object, NULL_TREE);
18697 	    if (TREE_CODE (r) == COMPONENT_REF)
18698 	      REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
18699 	    RETURN (r);
18700 	  }
18701 	else if (type_dependent_expression_p (object))
18702 	  /* We can't do much here.  */;
18703 	else if (!CLASS_TYPE_P (object_type))
18704 	  {
18705 	    if (scalarish_type_p (object_type))
18706 	      {
18707 		tree s = NULL_TREE;
18708 		tree dtor = member;
18709 
18710 		if (TREE_CODE (dtor) == SCOPE_REF)
18711 		  {
18712 		    s = TREE_OPERAND (dtor, 0);
18713 		    dtor = TREE_OPERAND (dtor, 1);
18714 		  }
18715 		if (TREE_CODE (dtor) == BIT_NOT_EXPR)
18716 		  {
18717 		    dtor = TREE_OPERAND (dtor, 0);
18718 		    if (TYPE_P (dtor))
18719 		      RETURN (finish_pseudo_destructor_expr
18720 			      (object, s, dtor, input_location));
18721 		  }
18722 	      }
18723 	  }
18724 	else if (TREE_CODE (member) == SCOPE_REF
18725 		 && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
18726 	  {
18727 	    /* Lookup the template functions now that we know what the
18728 	       scope is.  */
18729 	    tree scope = TREE_OPERAND (member, 0);
18730 	    tree tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
18731 	    tree args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
18732 	    member = lookup_qualified_name (scope, tmpl,
18733 					    /*is_type_p=*/false,
18734 					    /*complain=*/false);
18735 	    if (BASELINK_P (member))
18736 	      {
18737 		BASELINK_FUNCTIONS (member)
18738 		  = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
18739 			      args);
18740 		member = (adjust_result_of_qualified_name_lookup
18741 			  (member, BINFO_TYPE (BASELINK_BINFO (member)),
18742 			   object_type));
18743 	      }
18744 	    else
18745 	      {
18746 		qualified_name_lookup_error (scope, tmpl, member,
18747 					     input_location);
18748 		RETURN (error_mark_node);
18749 	      }
18750 	  }
18751 	else if (TREE_CODE (member) == SCOPE_REF
18752 		 && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
18753 		 && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
18754 	  {
18755 	    if (complain & tf_error)
18756 	      {
18757 		if (TYPE_P (TREE_OPERAND (member, 0)))
18758 		  error ("%qT is not a class or namespace",
18759 			 TREE_OPERAND (member, 0));
18760 		else
18761 		  error ("%qD is not a class or namespace",
18762 			 TREE_OPERAND (member, 0));
18763 	      }
18764 	    RETURN (error_mark_node);
18765 	  }
18766 
18767 	r = finish_class_member_access_expr (object, member,
18768 					     /*template_p=*/false,
18769 					     complain);
18770 	if (TREE_CODE (r) == COMPONENT_REF)
18771 	  REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
18772 	RETURN (r);
18773       }
18774 
18775     case THROW_EXPR:
18776       RETURN (build_throw
18777 	(RECUR (TREE_OPERAND (t, 0))));
18778 
18779     case CONSTRUCTOR:
18780       {
18781 	vec<constructor_elt, va_gc> *n;
18782 	constructor_elt *ce;
18783 	unsigned HOST_WIDE_INT idx;
18784 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
18785 	bool process_index_p;
18786         int newlen;
18787         bool need_copy_p = false;
18788 	tree r;
18789 
18790 	if (type == error_mark_node)
18791 	  RETURN (error_mark_node);
18792 
18793 	/* We do not want to process the index of aggregate
18794 	   initializers as they are identifier nodes which will be
18795 	   looked up by digest_init.  */
18796 	process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
18797 
18798 	if (null_member_pointer_value_p (t))
18799 	  {
18800 	    gcc_assert (same_type_p (type, TREE_TYPE (t)));
18801 	    RETURN (t);
18802 	  }
18803 
18804 	n = vec_safe_copy (CONSTRUCTOR_ELTS (t));
18805         newlen = vec_safe_length (n);
18806 	FOR_EACH_VEC_SAFE_ELT (n, idx, ce)
18807 	  {
18808 	    if (ce->index && process_index_p
18809 		/* An identifier index is looked up in the type
18810 		   being initialized, not the current scope.  */
18811 		&& TREE_CODE (ce->index) != IDENTIFIER_NODE)
18812 	      ce->index = RECUR (ce->index);
18813 
18814             if (PACK_EXPANSION_P (ce->value))
18815               {
18816                 /* Substitute into the pack expansion.  */
18817                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
18818                                                   in_decl);
18819 
18820 		if (ce->value == error_mark_node
18821 		    || PACK_EXPANSION_P (ce->value))
18822 		  ;
18823 		else if (TREE_VEC_LENGTH (ce->value) == 1)
18824                   /* Just move the argument into place.  */
18825                   ce->value = TREE_VEC_ELT (ce->value, 0);
18826                 else
18827                   {
18828                     /* Update the length of the final CONSTRUCTOR
18829                        arguments vector, and note that we will need to
18830                        copy.*/
18831                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
18832                     need_copy_p = true;
18833                   }
18834               }
18835             else
18836               ce->value = RECUR (ce->value);
18837 	  }
18838 
18839         if (need_copy_p)
18840           {
18841             vec<constructor_elt, va_gc> *old_n = n;
18842 
18843             vec_alloc (n, newlen);
18844             FOR_EACH_VEC_ELT (*old_n, idx, ce)
18845               {
18846                 if (TREE_CODE (ce->value) == TREE_VEC)
18847                   {
18848                     int i, len = TREE_VEC_LENGTH (ce->value);
18849                     for (i = 0; i < len; ++i)
18850                       CONSTRUCTOR_APPEND_ELT (n, 0,
18851                                               TREE_VEC_ELT (ce->value, i));
18852                   }
18853                 else
18854                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
18855               }
18856           }
18857 
18858 	r = build_constructor (init_list_type_node, n);
18859 	CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
18860 
18861 	if (TREE_HAS_CONSTRUCTOR (t))
18862 	  {
18863 	    fcl_t cl = fcl_functional;
18864 	    if (CONSTRUCTOR_C99_COMPOUND_LITERAL (t))
18865 	      cl = fcl_c99;
18866 	    RETURN (finish_compound_literal (type, r, complain, cl));
18867 	  }
18868 
18869 	TREE_TYPE (r) = type;
18870 	RETURN (r);
18871       }
18872 
18873     case TYPEID_EXPR:
18874       {
18875 	tree operand_0 = TREE_OPERAND (t, 0);
18876 	if (TYPE_P (operand_0))
18877 	  {
18878 	    operand_0 = tsubst (operand_0, args, complain, in_decl);
18879 	    RETURN (get_typeid (operand_0, complain));
18880 	  }
18881 	else
18882 	  {
18883 	    operand_0 = RECUR (operand_0);
18884 	    RETURN (build_typeid (operand_0, complain));
18885 	  }
18886       }
18887 
18888     case VAR_DECL:
18889       if (!args)
18890 	RETURN (t);
18891       /* Fall through */
18892 
18893     case PARM_DECL:
18894       {
18895 	tree r = tsubst_copy (t, args, complain, in_decl);
18896 	/* ??? We're doing a subset of finish_id_expression here.  */
18897 	if (VAR_P (r)
18898 	    && !processing_template_decl
18899 	    && !cp_unevaluated_operand
18900 	    && (TREE_STATIC (r) || DECL_EXTERNAL (r))
18901 	    && CP_DECL_THREAD_LOCAL_P (r))
18902 	  {
18903 	    if (tree wrap = get_tls_wrapper_fn (r))
18904 	      /* Replace an evaluated use of the thread_local variable with
18905 		 a call to its wrapper.  */
18906 	      r = build_cxx_call (wrap, 0, NULL, tf_warning_or_error);
18907 	  }
18908 	else if (outer_automatic_var_p (r))
18909 	  r = process_outer_var_ref (r, complain);
18910 
18911 	if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
18912 	  /* If the original type was a reference, we'll be wrapped in
18913 	     the appropriate INDIRECT_REF.  */
18914 	  r = convert_from_reference (r);
18915 	RETURN (r);
18916       }
18917 
18918     case VA_ARG_EXPR:
18919       {
18920 	tree op0 = RECUR (TREE_OPERAND (t, 0));
18921 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
18922 	RETURN (build_x_va_arg (EXPR_LOCATION (t), op0, type));
18923       }
18924 
18925     case OFFSETOF_EXPR:
18926       {
18927 	tree object_ptr
18928 	  = tsubst_copy_and_build (TREE_OPERAND (t, 1), args, complain,
18929 				   in_decl, /*function_p=*/false,
18930 				   /*integral_constant_expression_p=*/false);
18931 	RETURN (finish_offsetof (object_ptr,
18932 				 RECUR (TREE_OPERAND (t, 0)),
18933 				 EXPR_LOCATION (t)));
18934       }
18935 
18936     case ADDRESSOF_EXPR:
18937       RETURN (cp_build_addressof (EXPR_LOCATION (t),
18938 				  RECUR (TREE_OPERAND (t, 0)), complain));
18939 
18940     case TRAIT_EXPR:
18941       {
18942 	tree type1 = tsubst (TRAIT_EXPR_TYPE1 (t), args,
18943 			     complain, in_decl);
18944 
18945 	tree type2 = TRAIT_EXPR_TYPE2 (t);
18946 	if (type2 && TREE_CODE (type2) == TREE_LIST)
18947 	  type2 = RECUR (type2);
18948 	else if (type2)
18949 	  type2 = tsubst (type2, args, complain, in_decl);
18950 
18951 	RETURN (finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2));
18952       }
18953 
18954     case STMT_EXPR:
18955       {
18956 	tree old_stmt_expr = cur_stmt_expr;
18957 	tree stmt_expr = begin_stmt_expr ();
18958 
18959 	cur_stmt_expr = stmt_expr;
18960 	tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
18961 		     integral_constant_expression_p);
18962 	stmt_expr = finish_stmt_expr (stmt_expr, false);
18963 	cur_stmt_expr = old_stmt_expr;
18964 
18965 	/* If the resulting list of expression statement is empty,
18966 	   fold it further into void_node.  */
18967 	if (empty_expr_stmt_p (stmt_expr))
18968 	  stmt_expr = void_node;
18969 
18970 	RETURN (stmt_expr);
18971       }
18972 
18973     case LAMBDA_EXPR:
18974       {
18975 	tree r = tsubst_lambda_expr (t, args, complain, in_decl);
18976 
18977 	RETURN (build_lambda_object (r));
18978       }
18979 
18980     case TARGET_EXPR:
18981       /* We can get here for a constant initializer of non-dependent type.
18982          FIXME stop folding in cp_parser_initializer_clause.  */
18983       {
18984 	tree r = get_target_expr_sfinae (RECUR (TARGET_EXPR_INITIAL (t)),
18985 					 complain);
18986 	RETURN (r);
18987       }
18988 
18989     case TRANSACTION_EXPR:
18990       RETURN (tsubst_expr(t, args, complain, in_decl,
18991 	     integral_constant_expression_p));
18992 
18993     case PAREN_EXPR:
18994       RETURN (finish_parenthesized_expr (RECUR (TREE_OPERAND (t, 0))));
18995 
18996     case VEC_PERM_EXPR:
18997       {
18998 	tree op0 = RECUR (TREE_OPERAND (t, 0));
18999 	tree op1 = RECUR (TREE_OPERAND (t, 1));
19000 	tree op2 = RECUR (TREE_OPERAND (t, 2));
19001 	RETURN (build_x_vec_perm_expr (input_location, op0, op1, op2,
19002 				       complain));
19003       }
19004 
19005     case REQUIRES_EXPR:
19006       RETURN (tsubst_requires_expr (t, args, complain, in_decl));
19007 
19008     case RANGE_EXPR:
19009       /* No need to substitute further, a RANGE_EXPR will always be built
19010 	 with constant operands.  */
19011       RETURN (t);
19012 
19013     case NON_LVALUE_EXPR:
19014     case VIEW_CONVERT_EXPR:
19015       /* We should only see these for location wrapper nodes, or within
19016 	 instantiate_non_dependent_expr (when args is NULL_TREE).  */
19017       gcc_assert (location_wrapper_p (t) || args == NULL_TREE);
19018       if (location_wrapper_p (t))
19019 	RETURN (maybe_wrap_with_location (RECUR (TREE_OPERAND (t, 0)),
19020 					  EXPR_LOCATION (t)));
19021       /* fallthrough.  */
19022 
19023     default:
19024       /* Handle Objective-C++ constructs, if appropriate.  */
19025       {
19026 	tree subst
19027 	  = objcp_tsubst_copy_and_build (t, args, complain,
19028 					 in_decl, /*function_p=*/false);
19029 	if (subst)
19030 	  RETURN (subst);
19031       }
19032       RETURN (tsubst_copy (t, args, complain, in_decl));
19033     }
19034 
19035 #undef RECUR
19036 #undef RETURN
19037  out:
19038   input_location = loc;
19039   return retval;
19040 }
19041 
19042 /* Verify that the instantiated ARGS are valid. For type arguments,
19043    make sure that the type's linkage is ok. For non-type arguments,
19044    make sure they are constants if they are integral or enumerations.
19045    Emit an error under control of COMPLAIN, and return TRUE on error.  */
19046 
19047 static bool
check_instantiated_arg(tree tmpl,tree t,tsubst_flags_t complain)19048 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
19049 {
19050   if (dependent_template_arg_p (t))
19051     return false;
19052   if (ARGUMENT_PACK_P (t))
19053     {
19054       tree vec = ARGUMENT_PACK_ARGS (t);
19055       int len = TREE_VEC_LENGTH (vec);
19056       bool result = false;
19057       int i;
19058 
19059       for (i = 0; i < len; ++i)
19060 	if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
19061 	  result = true;
19062       return result;
19063     }
19064   else if (TYPE_P (t))
19065     {
19066       /* [basic.link]: A name with no linkage (notably, the name
19067 	 of a class or enumeration declared in a local scope)
19068 	 shall not be used to declare an entity with linkage.
19069 	 This implies that names with no linkage cannot be used as
19070 	 template arguments
19071 
19072 	 DR 757 relaxes this restriction for C++0x.  */
19073       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
19074 		 : no_linkage_check (t, /*relaxed_p=*/false));
19075 
19076       if (nt)
19077 	{
19078 	  /* DR 488 makes use of a type with no linkage cause
19079 	     type deduction to fail.  */
19080 	  if (complain & tf_error)
19081 	    {
19082 	      if (TYPE_UNNAMED_P (nt))
19083 		error ("%qT is/uses unnamed type", t);
19084 	      else
19085 		error ("template argument for %qD uses local type %qT",
19086 		       tmpl, t);
19087 	    }
19088 	  return true;
19089 	}
19090       /* In order to avoid all sorts of complications, we do not
19091 	 allow variably-modified types as template arguments.  */
19092       else if (variably_modified_type_p (t, NULL_TREE))
19093 	{
19094 	  if (complain & tf_error)
19095 	    error ("%qT is a variably modified type", t);
19096 	  return true;
19097 	}
19098     }
19099   /* Class template and alias template arguments should be OK.  */
19100   else if (DECL_TYPE_TEMPLATE_P (t))
19101     ;
19102   /* A non-type argument of integral or enumerated type must be a
19103      constant.  */
19104   else if (TREE_TYPE (t)
19105 	   && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
19106 	   && !REFERENCE_REF_P (t)
19107 	   && !TREE_CONSTANT (t))
19108     {
19109       if (complain & tf_error)
19110 	error ("integral expression %qE is not constant", t);
19111       return true;
19112     }
19113   return false;
19114 }
19115 
19116 static bool
check_instantiated_args(tree tmpl,tree args,tsubst_flags_t complain)19117 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
19118 {
19119   int ix, len = DECL_NTPARMS (tmpl);
19120   bool result = false;
19121 
19122   for (ix = 0; ix != len; ix++)
19123     {
19124       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
19125 	result = true;
19126     }
19127   if (result && (complain & tf_error))
19128     error ("  trying to instantiate %qD", tmpl);
19129   return result;
19130 }
19131 
19132 /* We're out of SFINAE context now, so generate diagnostics for the access
19133    errors we saw earlier when instantiating D from TMPL and ARGS.  */
19134 
19135 static void
recheck_decl_substitution(tree d,tree tmpl,tree args)19136 recheck_decl_substitution (tree d, tree tmpl, tree args)
19137 {
19138   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
19139   tree type = TREE_TYPE (pattern);
19140   location_t loc = input_location;
19141 
19142   push_access_scope (d);
19143   push_deferring_access_checks (dk_no_deferred);
19144   input_location = DECL_SOURCE_LOCATION (pattern);
19145   tsubst (type, args, tf_warning_or_error, d);
19146   input_location = loc;
19147   pop_deferring_access_checks ();
19148   pop_access_scope (d);
19149 }
19150 
19151 /* Instantiate the indicated variable, function, or alias template TMPL with
19152    the template arguments in TARG_PTR.  */
19153 
19154 static tree
instantiate_template_1(tree tmpl,tree orig_args,tsubst_flags_t complain)19155 instantiate_template_1 (tree tmpl, tree orig_args, tsubst_flags_t complain)
19156 {
19157   tree targ_ptr = orig_args;
19158   tree fndecl;
19159   tree gen_tmpl;
19160   tree spec;
19161   bool access_ok = true;
19162 
19163   if (tmpl == error_mark_node)
19164     return error_mark_node;
19165 
19166   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
19167 
19168   /* If this function is a clone, handle it specially.  */
19169   if (DECL_CLONED_FUNCTION_P (tmpl))
19170     {
19171       tree spec;
19172       tree clone;
19173 
19174       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
19175 	 DECL_CLONED_FUNCTION.  */
19176       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
19177 				   targ_ptr, complain);
19178       if (spec == error_mark_node)
19179 	return error_mark_node;
19180 
19181       /* Look for the clone.  */
19182       FOR_EACH_CLONE (clone, spec)
19183 	if (DECL_NAME (clone) == DECL_NAME (tmpl))
19184 	  return clone;
19185       /* We should always have found the clone by now.  */
19186       gcc_unreachable ();
19187       return NULL_TREE;
19188     }
19189 
19190   if (targ_ptr == error_mark_node)
19191     return error_mark_node;
19192 
19193   /* Check to see if we already have this specialization.  */
19194   gen_tmpl = most_general_template (tmpl);
19195   if (TMPL_ARGS_DEPTH (targ_ptr)
19196       < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)))
19197     /* targ_ptr only has the innermost template args, so add the outer ones
19198        from tmpl, which could be either a partial instantiation or gen_tmpl (in
19199        the case of a non-dependent call within a template definition).  */
19200     targ_ptr = (add_outermost_template_args
19201 		(DECL_TI_ARGS (DECL_TEMPLATE_RESULT (tmpl)),
19202 		 targ_ptr));
19203 
19204   /* It would be nice to avoid hashing here and then again in tsubst_decl,
19205      but it doesn't seem to be on the hot path.  */
19206   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
19207 
19208   gcc_assert (tmpl == gen_tmpl
19209 	      || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
19210 		  == spec)
19211 	      || fndecl == NULL_TREE);
19212 
19213   if (spec != NULL_TREE)
19214     {
19215       if (FNDECL_HAS_ACCESS_ERRORS (spec))
19216 	{
19217 	  if (complain & tf_error)
19218 	    recheck_decl_substitution (spec, gen_tmpl, targ_ptr);
19219 	  return error_mark_node;
19220 	}
19221       return spec;
19222     }
19223 
19224   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
19225 			       complain))
19226     return error_mark_node;
19227 
19228   /* We are building a FUNCTION_DECL, during which the access of its
19229      parameters and return types have to be checked.  However this
19230      FUNCTION_DECL which is the desired context for access checking
19231      is not built yet.  We solve this chicken-and-egg problem by
19232      deferring all checks until we have the FUNCTION_DECL.  */
19233   push_deferring_access_checks (dk_deferred);
19234 
19235   /* Instantiation of the function happens in the context of the function
19236      template, not the context of the overload resolution we're doing.  */
19237   push_to_top_level ();
19238   /* If there are dependent arguments, e.g. because we're doing partial
19239      ordering, make sure processing_template_decl stays set.  */
19240   if (uses_template_parms (targ_ptr))
19241     ++processing_template_decl;
19242   if (DECL_CLASS_SCOPE_P (gen_tmpl))
19243     {
19244       tree ctx = tsubst_aggr_type (DECL_CONTEXT (gen_tmpl), targ_ptr,
19245 				   complain, gen_tmpl, true);
19246       push_nested_class (ctx);
19247     }
19248 
19249   tree pattern = DECL_TEMPLATE_RESULT (gen_tmpl);
19250 
19251   fndecl = NULL_TREE;
19252   if (VAR_P (pattern))
19253     {
19254       /* We need to determine if we're using a partial or explicit
19255 	 specialization now, because the type of the variable could be
19256 	 different.  */
19257       tree tid = lookup_template_variable (gen_tmpl, targ_ptr);
19258       tree elt = most_specialized_partial_spec (tid, complain);
19259       if (elt == error_mark_node)
19260 	pattern = error_mark_node;
19261       else if (elt)
19262 	{
19263 	  tree partial_tmpl = TREE_VALUE (elt);
19264 	  tree partial_args = TREE_PURPOSE (elt);
19265 	  tree partial_pat = DECL_TEMPLATE_RESULT (partial_tmpl);
19266 	  fndecl = tsubst (partial_pat, partial_args, complain, gen_tmpl);
19267 	}
19268     }
19269 
19270   /* Substitute template parameters to obtain the specialization.  */
19271   if (fndecl == NULL_TREE)
19272     fndecl = tsubst (pattern, targ_ptr, complain, gen_tmpl);
19273   if (DECL_CLASS_SCOPE_P (gen_tmpl))
19274     pop_nested_class ();
19275   pop_from_top_level ();
19276 
19277   if (fndecl == error_mark_node)
19278     {
19279       pop_deferring_access_checks ();
19280       return error_mark_node;
19281     }
19282 
19283   /* The DECL_TI_TEMPLATE should always be the immediate parent
19284      template, not the most general template.  */
19285   DECL_TI_TEMPLATE (fndecl) = tmpl;
19286   DECL_TI_ARGS (fndecl) = targ_ptr;
19287 
19288   /* Now we know the specialization, compute access previously
19289      deferred.  Do no access control for inheriting constructors,
19290      as we already checked access for the inherited constructor.  */
19291   if (!(flag_new_inheriting_ctors
19292 	&& DECL_INHERITED_CTOR (fndecl)))
19293     {
19294       push_access_scope (fndecl);
19295       if (!perform_deferred_access_checks (complain))
19296 	access_ok = false;
19297       pop_access_scope (fndecl);
19298     }
19299   pop_deferring_access_checks ();
19300 
19301   /* If we've just instantiated the main entry point for a function,
19302      instantiate all the alternate entry points as well.  We do this
19303      by cloning the instantiation of the main entry point, not by
19304      instantiating the template clones.  */
19305   if (DECL_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (DECL_CHAIN (gen_tmpl)))
19306     clone_function_decl (fndecl, /*update_methods=*/false);
19307 
19308   if (!access_ok)
19309     {
19310       if (!(complain & tf_error))
19311 	{
19312 	  /* Remember to reinstantiate when we're out of SFINAE so the user
19313 	     can see the errors.  */
19314 	  FNDECL_HAS_ACCESS_ERRORS (fndecl) = true;
19315 	}
19316       return error_mark_node;
19317     }
19318   return fndecl;
19319 }
19320 
19321 /* Wrapper for instantiate_template_1.  */
19322 
19323 tree
instantiate_template(tree tmpl,tree orig_args,tsubst_flags_t complain)19324 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
19325 {
19326   tree ret;
19327   timevar_push (TV_TEMPLATE_INST);
19328   ret = instantiate_template_1 (tmpl, orig_args,  complain);
19329   timevar_pop (TV_TEMPLATE_INST);
19330   return ret;
19331 }
19332 
19333 /* Instantiate the alias template TMPL with ARGS.  Also push a template
19334    instantiation level, which instantiate_template doesn't do because
19335    functions and variables have sufficient context established by the
19336    callers.  */
19337 
19338 static tree
instantiate_alias_template(tree tmpl,tree args,tsubst_flags_t complain)19339 instantiate_alias_template (tree tmpl, tree args, tsubst_flags_t complain)
19340 {
19341   if (tmpl == error_mark_node || args == error_mark_node)
19342     return error_mark_node;
19343   if (!push_tinst_level (tmpl, args))
19344     return error_mark_node;
19345 
19346   args =
19347     coerce_innermost_template_parms (DECL_TEMPLATE_PARMS (tmpl),
19348 				     args, tmpl, complain,
19349 				     /*require_all_args=*/true,
19350 				     /*use_default_args=*/true);
19351 
19352   tree r = instantiate_template (tmpl, args, complain);
19353   pop_tinst_level ();
19354 
19355   return r;
19356 }
19357 
19358 /* PARM is a template parameter pack for FN.  Returns true iff
19359    PARM is used in a deducible way in the argument list of FN.  */
19360 
19361 static bool
pack_deducible_p(tree parm,tree fn)19362 pack_deducible_p (tree parm, tree fn)
19363 {
19364   tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
19365   for (; t; t = TREE_CHAIN (t))
19366     {
19367       tree type = TREE_VALUE (t);
19368       tree packs;
19369       if (!PACK_EXPANSION_P (type))
19370 	continue;
19371       for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
19372 	   packs; packs = TREE_CHAIN (packs))
19373 	if (template_args_equal (TREE_VALUE (packs), parm))
19374 	  {
19375 	    /* The template parameter pack is used in a function parameter
19376 	       pack.  If this is the end of the parameter list, the
19377 	       template parameter pack is deducible.  */
19378 	    if (TREE_CHAIN (t) == void_list_node)
19379 	      return true;
19380 	    else
19381 	      /* Otherwise, not.  Well, it could be deduced from
19382 		 a non-pack parameter, but doing so would end up with
19383 		 a deduction mismatch, so don't bother.  */
19384 	      return false;
19385 	  }
19386     }
19387   /* The template parameter pack isn't used in any function parameter
19388      packs, but it might be used deeper, e.g. tuple<Args...>.  */
19389   return true;
19390 }
19391 
19392 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
19393    NARGS elements of the arguments that are being used when calling
19394    it.  TARGS is a vector into which the deduced template arguments
19395    are placed.
19396 
19397    Returns either a FUNCTION_DECL for the matching specialization of FN or
19398    NULL_TREE if no suitable specialization can be found.  If EXPLAIN_P is
19399    true, diagnostics will be printed to explain why it failed.
19400 
19401    If FN is a conversion operator, or we are trying to produce a specific
19402    specialization, RETURN_TYPE is the return type desired.
19403 
19404    The EXPLICIT_TARGS are explicit template arguments provided via a
19405    template-id.
19406 
19407    The parameter STRICT is one of:
19408 
19409    DEDUCE_CALL:
19410      We are deducing arguments for a function call, as in
19411      [temp.deduct.call].  If RETURN_TYPE is non-null, we are
19412      deducing arguments for a call to the result of a conversion
19413      function template, as in [over.call.object].
19414 
19415    DEDUCE_CONV:
19416      We are deducing arguments for a conversion function, as in
19417      [temp.deduct.conv].
19418 
19419    DEDUCE_EXACT:
19420      We are deducing arguments when doing an explicit instantiation
19421      as in [temp.explicit], when determining an explicit specialization
19422      as in [temp.expl.spec], or when taking the address of a function
19423      template, as in [temp.deduct.funcaddr].  */
19424 
19425 tree
fn_type_unification(tree fn,tree explicit_targs,tree targs,const tree * args,unsigned int nargs,tree return_type,unification_kind_t strict,int flags,bool explain_p,bool decltype_p)19426 fn_type_unification (tree fn,
19427 		     tree explicit_targs,
19428 		     tree targs,
19429 		     const tree *args,
19430 		     unsigned int nargs,
19431 		     tree return_type,
19432 		     unification_kind_t strict,
19433 		     int flags,
19434 		     bool explain_p,
19435 		     bool decltype_p)
19436 {
19437   tree parms;
19438   tree fntype;
19439   tree decl = NULL_TREE;
19440   tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
19441   bool ok;
19442   static int deduction_depth;
19443 
19444   tree orig_fn = fn;
19445   if (flag_new_inheriting_ctors)
19446     fn = strip_inheriting_ctors (fn);
19447 
19448   tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
19449   tree r = error_mark_node;
19450 
19451   tree full_targs = targs;
19452   if (TMPL_ARGS_DEPTH (targs)
19453       < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (fn)))
19454     full_targs = (add_outermost_template_args
19455 		  (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (fn)),
19456 		   targs));
19457 
19458   if (decltype_p)
19459     complain |= tf_decltype;
19460 
19461   /* In C++0x, it's possible to have a function template whose type depends
19462      on itself recursively.  This is most obvious with decltype, but can also
19463      occur with enumeration scope (c++/48969).  So we need to catch infinite
19464      recursion and reject the substitution at deduction time; this function
19465      will return error_mark_node for any repeated substitution.
19466 
19467      This also catches excessive recursion such as when f<N> depends on
19468      f<N-1> across all integers, and returns error_mark_node for all the
19469      substitutions back up to the initial one.
19470 
19471      This is, of course, not reentrant.  */
19472   if (excessive_deduction_depth)
19473     return error_mark_node;
19474   ++deduction_depth;
19475 
19476   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
19477 
19478   fntype = TREE_TYPE (fn);
19479   if (explicit_targs)
19480     {
19481       /* [temp.deduct]
19482 
19483 	 The specified template arguments must match the template
19484 	 parameters in kind (i.e., type, nontype, template), and there
19485 	 must not be more arguments than there are parameters;
19486 	 otherwise type deduction fails.
19487 
19488 	 Nontype arguments must match the types of the corresponding
19489 	 nontype template parameters, or must be convertible to the
19490 	 types of the corresponding nontype parameters as specified in
19491 	 _temp.arg.nontype_, otherwise type deduction fails.
19492 
19493 	 All references in the function type of the function template
19494 	 to the corresponding template parameters are replaced by the
19495 	 specified template argument values.  If a substitution in a
19496 	 template parameter or in the function type of the function
19497 	 template results in an invalid type, type deduction fails.  */
19498       int i, len = TREE_VEC_LENGTH (tparms);
19499       location_t loc = input_location;
19500       bool incomplete = false;
19501 
19502       if (explicit_targs == error_mark_node)
19503 	goto fail;
19504 
19505       if (TMPL_ARGS_DEPTH (explicit_targs)
19506 	  < TMPL_ARGS_DEPTH (full_targs))
19507 	explicit_targs = add_outermost_template_args (full_targs,
19508 						      explicit_targs);
19509 
19510       /* Adjust any explicit template arguments before entering the
19511 	 substitution context.  */
19512       explicit_targs
19513 	= (coerce_template_parms (tparms, explicit_targs, NULL_TREE,
19514 				  complain,
19515 				  /*require_all_args=*/false,
19516 				  /*use_default_args=*/false));
19517       if (explicit_targs == error_mark_node)
19518 	goto fail;
19519 
19520       /* Substitute the explicit args into the function type.  This is
19521 	 necessary so that, for instance, explicitly declared function
19522 	 arguments can match null pointed constants.  If we were given
19523 	 an incomplete set of explicit args, we must not do semantic
19524 	 processing during substitution as we could create partial
19525 	 instantiations.  */
19526       for (i = 0; i < len; i++)
19527         {
19528           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
19529           bool parameter_pack = false;
19530 	  tree targ = TREE_VEC_ELT (explicit_targs, i);
19531 
19532           /* Dig out the actual parm.  */
19533           if (TREE_CODE (parm) == TYPE_DECL
19534               || TREE_CODE (parm) == TEMPLATE_DECL)
19535             {
19536               parm = TREE_TYPE (parm);
19537               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
19538             }
19539           else if (TREE_CODE (parm) == PARM_DECL)
19540             {
19541               parm = DECL_INITIAL (parm);
19542               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
19543             }
19544 
19545 	  if (!parameter_pack && targ == NULL_TREE)
19546 	    /* No explicit argument for this template parameter.  */
19547 	    incomplete = true;
19548 
19549           if (parameter_pack && pack_deducible_p (parm, fn))
19550             {
19551               /* Mark the argument pack as "incomplete". We could
19552                  still deduce more arguments during unification.
19553 	         We remove this mark in type_unification_real.  */
19554               if (targ)
19555                 {
19556                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
19557                   ARGUMENT_PACK_EXPLICIT_ARGS (targ)
19558                     = ARGUMENT_PACK_ARGS (targ);
19559                 }
19560 
19561               /* We have some incomplete argument packs.  */
19562               incomplete = true;
19563             }
19564         }
19565 
19566       if (!push_tinst_level (fn, explicit_targs))
19567 	{
19568 	  excessive_deduction_depth = true;
19569 	  goto fail;
19570 	}
19571       processing_template_decl += incomplete;
19572       input_location = DECL_SOURCE_LOCATION (fn);
19573       /* Ignore any access checks; we'll see them again in
19574 	 instantiate_template and they might have the wrong
19575 	 access path at this point.  */
19576       push_deferring_access_checks (dk_deferred);
19577       fntype = tsubst (TREE_TYPE (fn), explicit_targs,
19578 		       complain | tf_partial | tf_fndecl_type, NULL_TREE);
19579       pop_deferring_access_checks ();
19580       input_location = loc;
19581       processing_template_decl -= incomplete;
19582       pop_tinst_level ();
19583 
19584       if (fntype == error_mark_node)
19585 	goto fail;
19586 
19587       /* Place the explicitly specified arguments in TARGS.  */
19588       explicit_targs = INNERMOST_TEMPLATE_ARGS (explicit_targs);
19589       for (i = NUM_TMPL_ARGS (explicit_targs); i--;)
19590 	TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (explicit_targs, i);
19591     }
19592 
19593   /* Never do unification on the 'this' parameter.  */
19594   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
19595 
19596   if (return_type && strict == DEDUCE_CALL)
19597     {
19598       /* We're deducing for a call to the result of a template conversion
19599          function.  The parms we really want are in return_type.  */
19600       if (POINTER_TYPE_P (return_type))
19601 	return_type = TREE_TYPE (return_type);
19602       parms = TYPE_ARG_TYPES (return_type);
19603     }
19604   else if (return_type)
19605     {
19606       tree *new_args;
19607 
19608       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
19609       new_args = XALLOCAVEC (tree, nargs + 1);
19610       new_args[0] = return_type;
19611       memcpy (new_args + 1, args, nargs * sizeof (tree));
19612       args = new_args;
19613       ++nargs;
19614     }
19615 
19616   /* We allow incomplete unification without an error message here
19617      because the standard doesn't seem to explicitly prohibit it.  Our
19618      callers must be ready to deal with unification failures in any
19619      event.  */
19620 
19621   /* If we aren't explaining yet, push tinst context so we can see where
19622      any errors (e.g. from class instantiations triggered by instantiation
19623      of default template arguments) come from.  If we are explaining, this
19624      context is redundant.  */
19625   if (!explain_p && !push_tinst_level (fn, targs))
19626     {
19627       excessive_deduction_depth = true;
19628       goto fail;
19629     }
19630 
19631   /* type_unification_real will pass back any access checks from default
19632      template argument substitution.  */
19633   vec<deferred_access_check, va_gc> *checks;
19634   checks = NULL;
19635 
19636   ok = !type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
19637 			       full_targs, parms, args, nargs, /*subr=*/0,
19638 			       strict, flags, &checks, explain_p);
19639   if (!explain_p)
19640     pop_tinst_level ();
19641   if (!ok)
19642     goto fail;
19643 
19644   /* Now that we have bindings for all of the template arguments,
19645      ensure that the arguments deduced for the template template
19646      parameters have compatible template parameter lists.  We cannot
19647      check this property before we have deduced all template
19648      arguments, because the template parameter types of a template
19649      template parameter might depend on prior template parameters
19650      deduced after the template template parameter.  The following
19651      ill-formed example illustrates this issue:
19652 
19653        template<typename T, template<T> class C> void f(C<5>, T);
19654 
19655        template<int N> struct X {};
19656 
19657        void g() {
19658          f(X<5>(), 5l); // error: template argument deduction fails
19659        }
19660 
19661      The template parameter list of 'C' depends on the template type
19662      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
19663      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
19664      time that we deduce 'C'.  */
19665   if (!template_template_parm_bindings_ok_p
19666            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
19667     {
19668       unify_inconsistent_template_template_parameters (explain_p);
19669       goto fail;
19670     }
19671 
19672   /* All is well so far.  Now, check:
19673 
19674      [temp.deduct]
19675 
19676      When all template arguments have been deduced, all uses of
19677      template parameters in nondeduced contexts are replaced with
19678      the corresponding deduced argument values.  If the
19679      substitution results in an invalid type, as described above,
19680      type deduction fails.  */
19681   if (!push_tinst_level (fn, targs))
19682     {
19683       excessive_deduction_depth = true;
19684       goto fail;
19685     }
19686 
19687   /* Also collect access checks from the instantiation.  */
19688   reopen_deferring_access_checks (checks);
19689 
19690   decl = instantiate_template (fn, targs, complain);
19691 
19692   checks = get_deferred_access_checks ();
19693   pop_deferring_access_checks ();
19694 
19695   pop_tinst_level ();
19696 
19697   if (decl == error_mark_node)
19698     goto fail;
19699 
19700   /* Now perform any access checks encountered during substitution.  */
19701   push_access_scope (decl);
19702   ok = perform_access_checks (checks, complain);
19703   pop_access_scope (decl);
19704   if (!ok)
19705     goto fail;
19706 
19707   /* If we're looking for an exact match, check that what we got
19708      is indeed an exact match.  It might not be if some template
19709      parameters are used in non-deduced contexts.  But don't check
19710      for an exact match if we have dependent template arguments;
19711      in that case we're doing partial ordering, and we already know
19712      that we have two candidates that will provide the actual type.  */
19713   if (strict == DEDUCE_EXACT && !any_dependent_template_arguments_p (targs))
19714     {
19715       tree substed = TREE_TYPE (decl);
19716       unsigned int i;
19717 
19718       tree sarg
19719 	= skip_artificial_parms_for (decl, TYPE_ARG_TYPES (substed));
19720       if (return_type)
19721 	sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
19722       for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
19723 	if (!same_type_p (args[i], TREE_VALUE (sarg)))
19724 	  {
19725 	    unify_type_mismatch (explain_p, args[i],
19726 				 TREE_VALUE (sarg));
19727 	    goto fail;
19728 	  }
19729     }
19730 
19731   /* After doing deduction with the inherited constructor, actually return an
19732      instantiation of the inheriting constructor.  */
19733   if (orig_fn != fn)
19734     decl = instantiate_template (orig_fn, targs, complain);
19735 
19736   r = decl;
19737 
19738  fail:
19739   --deduction_depth;
19740   if (excessive_deduction_depth)
19741     {
19742       if (deduction_depth == 0)
19743 	/* Reset once we're all the way out.  */
19744 	excessive_deduction_depth = false;
19745     }
19746 
19747   return r;
19748 }
19749 
19750 /* Adjust types before performing type deduction, as described in
19751    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
19752    sections are symmetric.  PARM is the type of a function parameter
19753    or the return type of the conversion function.  ARG is the type of
19754    the argument passed to the call, or the type of the value
19755    initialized with the result of the conversion function.
19756    ARG_EXPR is the original argument expression, which may be null.  */
19757 
19758 static int
maybe_adjust_types_for_deduction(unification_kind_t strict,tree * parm,tree * arg,tree arg_expr)19759 maybe_adjust_types_for_deduction (unification_kind_t strict,
19760 				  tree* parm,
19761 				  tree* arg,
19762 				  tree arg_expr)
19763 {
19764   int result = 0;
19765 
19766   switch (strict)
19767     {
19768     case DEDUCE_CALL:
19769       break;
19770 
19771     case DEDUCE_CONV:
19772       /* Swap PARM and ARG throughout the remainder of this
19773 	 function; the handling is precisely symmetric since PARM
19774 	 will initialize ARG rather than vice versa.  */
19775       std::swap (parm, arg);
19776       break;
19777 
19778     case DEDUCE_EXACT:
19779       /* Core issue #873: Do the DR606 thing (see below) for these cases,
19780 	 too, but here handle it by stripping the reference from PARM
19781 	 rather than by adding it to ARG.  */
19782       if (TREE_CODE (*parm) == REFERENCE_TYPE
19783 	  && TYPE_REF_IS_RVALUE (*parm)
19784 	  && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
19785 	  && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
19786 	  && TREE_CODE (*arg) == REFERENCE_TYPE
19787 	  && !TYPE_REF_IS_RVALUE (*arg))
19788 	*parm = TREE_TYPE (*parm);
19789       /* Nothing else to do in this case.  */
19790       return 0;
19791 
19792     default:
19793       gcc_unreachable ();
19794     }
19795 
19796   if (TREE_CODE (*parm) != REFERENCE_TYPE)
19797     {
19798       /* [temp.deduct.call]
19799 
19800 	 If P is not a reference type:
19801 
19802 	 --If A is an array type, the pointer type produced by the
19803 	 array-to-pointer standard conversion (_conv.array_) is
19804 	 used in place of A for type deduction; otherwise,
19805 
19806 	 --If A is a function type, the pointer type produced by
19807 	 the function-to-pointer standard conversion
19808 	 (_conv.func_) is used in place of A for type deduction;
19809 	 otherwise,
19810 
19811 	 --If A is a cv-qualified type, the top level
19812 	 cv-qualifiers of A's type are ignored for type
19813 	 deduction.  */
19814       if (TREE_CODE (*arg) == ARRAY_TYPE)
19815 	*arg = build_pointer_type (TREE_TYPE (*arg));
19816       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
19817 	*arg = build_pointer_type (*arg);
19818       else
19819 	*arg = TYPE_MAIN_VARIANT (*arg);
19820     }
19821 
19822   /* [14.8.2.1/3 temp.deduct.call], "A forwarding reference is an rvalue
19823      reference to a cv-unqualified template parameter that does not represent a
19824      template parameter of a class template (during class template argument
19825      deduction (13.3.1.8)). If P is a forwarding reference and the argument is
19826      an lvalue, the type "lvalue reference to A" is used in place of A for type
19827      deduction. */
19828   if (TREE_CODE (*parm) == REFERENCE_TYPE
19829       && TYPE_REF_IS_RVALUE (*parm)
19830       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
19831       && !TEMPLATE_TYPE_PARM_FOR_CLASS (TREE_TYPE (*parm))
19832       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
19833       && (arg_expr ? lvalue_p (arg_expr)
19834 	  /* try_one_overload doesn't provide an arg_expr, but
19835 	     functions are always lvalues.  */
19836 	  : TREE_CODE (*arg) == FUNCTION_TYPE))
19837     *arg = build_reference_type (*arg);
19838 
19839   /* [temp.deduct.call]
19840 
19841      If P is a cv-qualified type, the top level cv-qualifiers
19842      of P's type are ignored for type deduction.  If P is a
19843      reference type, the type referred to by P is used for
19844      type deduction.  */
19845   *parm = TYPE_MAIN_VARIANT (*parm);
19846   if (TREE_CODE (*parm) == REFERENCE_TYPE)
19847     {
19848       *parm = TREE_TYPE (*parm);
19849       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
19850     }
19851 
19852   /* DR 322. For conversion deduction, remove a reference type on parm
19853      too (which has been swapped into ARG).  */
19854   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
19855     *arg = TREE_TYPE (*arg);
19856 
19857   return result;
19858 }
19859 
19860 /* Subroutine of unify_one_argument.  PARM is a function parameter of a
19861    template which does contain any deducible template parameters; check if
19862    ARG is a suitable match for it.  STRICT, FLAGS and EXPLAIN_P are as in
19863    unify_one_argument.  */
19864 
19865 static int
check_non_deducible_conversion(tree parm,tree arg,int strict,int flags,bool explain_p)19866 check_non_deducible_conversion (tree parm, tree arg, int strict,
19867 				int flags, bool explain_p)
19868 {
19869   tree type;
19870 
19871   if (!TYPE_P (arg))
19872     type = TREE_TYPE (arg);
19873   else
19874     type = arg;
19875 
19876   if (same_type_p (parm, type))
19877     return unify_success (explain_p);
19878 
19879   if (strict == DEDUCE_CONV)
19880     {
19881       if (can_convert_arg (type, parm, NULL_TREE, flags,
19882 			   explain_p ? tf_warning_or_error : tf_none))
19883 	return unify_success (explain_p);
19884     }
19885   else if (strict != DEDUCE_EXACT)
19886     {
19887       if (can_convert_arg (parm, type,
19888 			   TYPE_P (arg) ? NULL_TREE : arg,
19889 			   flags, explain_p ? tf_warning_or_error : tf_none))
19890 	return unify_success (explain_p);
19891     }
19892 
19893   if (strict == DEDUCE_EXACT)
19894     return unify_type_mismatch (explain_p, parm, arg);
19895   else
19896     return unify_arg_conversion (explain_p, parm, type, arg);
19897 }
19898 
19899 static bool uses_deducible_template_parms (tree type);
19900 
19901 /* Returns true iff the expression EXPR is one from which a template
19902    argument can be deduced.  In other words, if it's an undecorated
19903    use of a template non-type parameter.  */
19904 
19905 static bool
deducible_expression(tree expr)19906 deducible_expression (tree expr)
19907 {
19908   /* Strip implicit conversions.  */
19909   while (CONVERT_EXPR_P (expr))
19910     expr = TREE_OPERAND (expr, 0);
19911   return (TREE_CODE (expr) == TEMPLATE_PARM_INDEX);
19912 }
19913 
19914 /* Returns true iff the array domain DOMAIN uses a template parameter in a
19915    deducible way; that is, if it has a max value of <PARM> - 1.  */
19916 
19917 static bool
deducible_array_bound(tree domain)19918 deducible_array_bound (tree domain)
19919 {
19920   if (domain == NULL_TREE)
19921     return false;
19922 
19923   tree max = TYPE_MAX_VALUE (domain);
19924   if (TREE_CODE (max) != MINUS_EXPR)
19925     return false;
19926 
19927   return deducible_expression (TREE_OPERAND (max, 0));
19928 }
19929 
19930 /* Returns true iff the template arguments ARGS use a template parameter
19931    in a deducible way.  */
19932 
19933 static bool
deducible_template_args(tree args)19934 deducible_template_args (tree args)
19935 {
19936   for (int i = 0; i < TREE_VEC_LENGTH (args); ++i)
19937     {
19938       bool deducible;
19939       tree elt = TREE_VEC_ELT (args, i);
19940       if (ARGUMENT_PACK_P (elt))
19941 	deducible = deducible_template_args (ARGUMENT_PACK_ARGS (elt));
19942       else
19943 	{
19944 	  if (PACK_EXPANSION_P (elt))
19945 	    elt = PACK_EXPANSION_PATTERN (elt);
19946 	  if (TREE_CODE (elt) == TEMPLATE_TEMPLATE_PARM)
19947 	    deducible = true;
19948 	  else if (TYPE_P (elt))
19949 	    deducible = uses_deducible_template_parms (elt);
19950 	  else
19951 	    deducible = deducible_expression (elt);
19952 	}
19953       if (deducible)
19954 	return true;
19955     }
19956   return false;
19957 }
19958 
19959 /* Returns true iff TYPE contains any deducible references to template
19960    parameters, as per 14.8.2.5.  */
19961 
19962 static bool
uses_deducible_template_parms(tree type)19963 uses_deducible_template_parms (tree type)
19964 {
19965   if (PACK_EXPANSION_P (type))
19966     type = PACK_EXPANSION_PATTERN (type);
19967 
19968   /* T
19969      cv-list T
19970      TT<T>
19971      TT<i>
19972      TT<> */
19973   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
19974       || TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
19975     return true;
19976 
19977   /* T*
19978      T&
19979      T&&  */
19980   if (POINTER_TYPE_P (type))
19981     return uses_deducible_template_parms (TREE_TYPE (type));
19982 
19983   /* T[integer-constant ]
19984      type [i]  */
19985   if (TREE_CODE (type) == ARRAY_TYPE)
19986     return (uses_deducible_template_parms (TREE_TYPE (type))
19987 	    || deducible_array_bound (TYPE_DOMAIN (type)));
19988 
19989   /* T type ::*
19990      type T::*
19991      T T::*
19992      T (type ::*)()
19993      type (T::*)()
19994      type (type ::*)(T)
19995      type (T::*)(T)
19996      T (type ::*)(T)
19997      T (T::*)()
19998      T (T::*)(T) */
19999   if (TYPE_PTRMEM_P (type))
20000     return (uses_deducible_template_parms (TYPE_PTRMEM_CLASS_TYPE (type))
20001 	    || (uses_deducible_template_parms
20002 		(TYPE_PTRMEM_POINTED_TO_TYPE (type))));
20003 
20004   /* template-name <T> (where template-name refers to a class template)
20005      template-name <i> (where template-name refers to a class template) */
20006   if (CLASS_TYPE_P (type)
20007       && CLASSTYPE_TEMPLATE_INFO (type)
20008       && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type)))
20009     return deducible_template_args (INNERMOST_TEMPLATE_ARGS
20010 				    (CLASSTYPE_TI_ARGS (type)));
20011 
20012   /* type (T)
20013      T()
20014      T(T)  */
20015   if (TREE_CODE (type) == FUNCTION_TYPE
20016       || TREE_CODE (type) == METHOD_TYPE)
20017     {
20018       if (uses_deducible_template_parms (TREE_TYPE (type)))
20019 	return true;
20020       tree parm = TYPE_ARG_TYPES (type);
20021       if (TREE_CODE (type) == METHOD_TYPE)
20022 	parm = TREE_CHAIN (parm);
20023       for (; parm; parm = TREE_CHAIN (parm))
20024 	if (uses_deducible_template_parms (TREE_VALUE (parm)))
20025 	  return true;
20026     }
20027 
20028   return false;
20029 }
20030 
20031 /* Subroutine of type_unification_real and unify_pack_expansion to
20032    handle unification of a single P/A pair.  Parameters are as
20033    for those functions.  */
20034 
20035 static int
unify_one_argument(tree tparms,tree targs,tree parm,tree arg,int subr,unification_kind_t strict,bool explain_p)20036 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
20037 		    int subr, unification_kind_t strict,
20038 		    bool explain_p)
20039 {
20040   tree arg_expr = NULL_TREE;
20041   int arg_strict;
20042 
20043   if (arg == error_mark_node || parm == error_mark_node)
20044     return unify_invalid (explain_p);
20045   if (arg == unknown_type_node)
20046     /* We can't deduce anything from this, but we might get all the
20047        template args from other function args.  */
20048     return unify_success (explain_p);
20049 
20050   /* Implicit conversions (Clause 4) will be performed on a function
20051      argument to convert it to the type of the corresponding function
20052      parameter if the parameter type contains no template-parameters that
20053      participate in template argument deduction.  */
20054   if (strict != DEDUCE_EXACT
20055       && TYPE_P (parm) && !uses_deducible_template_parms (parm))
20056     /* For function parameters with no deducible template parameters,
20057        just return.  We'll check non-dependent conversions later.  */
20058     return unify_success (explain_p);
20059 
20060   switch (strict)
20061     {
20062     case DEDUCE_CALL:
20063       arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
20064 		    | UNIFY_ALLOW_MORE_CV_QUAL
20065 		    | UNIFY_ALLOW_DERIVED);
20066       break;
20067 
20068     case DEDUCE_CONV:
20069       arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
20070       break;
20071 
20072     case DEDUCE_EXACT:
20073       arg_strict = UNIFY_ALLOW_NONE;
20074       break;
20075 
20076     default:
20077       gcc_unreachable ();
20078     }
20079 
20080   /* We only do these transformations if this is the top-level
20081      parameter_type_list in a call or declaration matching; in other
20082      situations (nested function declarators, template argument lists) we
20083      won't be comparing a type to an expression, and we don't do any type
20084      adjustments.  */
20085   if (!subr)
20086     {
20087       if (!TYPE_P (arg))
20088 	{
20089 	  gcc_assert (TREE_TYPE (arg) != NULL_TREE);
20090 	  if (type_unknown_p (arg))
20091 	    {
20092 	      /* [temp.deduct.type] A template-argument can be
20093 		 deduced from a pointer to function or pointer
20094 		 to member function argument if the set of
20095 		 overloaded functions does not contain function
20096 		 templates and at most one of a set of
20097 		 overloaded functions provides a unique
20098 		 match.  */
20099 	      resolve_overloaded_unification (tparms, targs, parm,
20100 					      arg, strict,
20101 					      arg_strict, explain_p);
20102 	      /* If a unique match was not found, this is a
20103 	         non-deduced context, so we still succeed. */
20104 	      return unify_success (explain_p);
20105 	    }
20106 
20107 	  arg_expr = arg;
20108 	  arg = unlowered_expr_type (arg);
20109 	  if (arg == error_mark_node)
20110 	    return unify_invalid (explain_p);
20111 	}
20112 
20113       arg_strict |=
20114 	maybe_adjust_types_for_deduction (strict, &parm, &arg, arg_expr);
20115     }
20116   else
20117     if ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
20118 	!= (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL))
20119       return unify_template_argument_mismatch (explain_p, parm, arg);
20120 
20121   /* For deduction from an init-list we need the actual list.  */
20122   if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
20123     arg = arg_expr;
20124   return unify (tparms, targs, parm, arg, arg_strict, explain_p);
20125 }
20126 
20127 /* for_each_template_parm callback that always returns 0.  */
20128 
20129 static int
zero_r(tree,void *)20130 zero_r (tree, void *)
20131 {
20132   return 0;
20133 }
20134 
20135 /* for_each_template_parm any_fn callback to handle deduction of a template
20136    type argument from the type of an array bound.  */
20137 
20138 static int
array_deduction_r(tree t,void * data)20139 array_deduction_r (tree t, void *data)
20140 {
20141   tree_pair_p d = (tree_pair_p)data;
20142   tree &tparms = d->purpose;
20143   tree &targs = d->value;
20144 
20145   if (TREE_CODE (t) == ARRAY_TYPE)
20146     if (tree dom = TYPE_DOMAIN (t))
20147       if (tree max = TYPE_MAX_VALUE (dom))
20148 	{
20149 	  if (TREE_CODE (max) == MINUS_EXPR)
20150 	    max = TREE_OPERAND (max, 0);
20151 	  if (TREE_CODE (max) == TEMPLATE_PARM_INDEX)
20152 	    unify (tparms, targs, TREE_TYPE (max), size_type_node,
20153 		   UNIFY_ALLOW_NONE, /*explain*/false);
20154 	}
20155 
20156   /* Keep walking.  */
20157   return 0;
20158 }
20159 
20160 /* Try to deduce any not-yet-deduced template type arguments from the type of
20161    an array bound.  This is handled separately from unify because 14.8.2.5 says
20162    "The type of a type parameter is only deduced from an array bound if it is
20163    not otherwise deduced."  */
20164 
20165 static void
try_array_deduction(tree tparms,tree targs,tree parm)20166 try_array_deduction (tree tparms, tree targs, tree parm)
20167 {
20168   tree_pair_s data = { tparms, targs };
20169   hash_set<tree> visited;
20170   for_each_template_parm (parm, zero_r, &data, &visited,
20171 			  /*nondeduced*/false, array_deduction_r);
20172 }
20173 
20174 /* Returns how many levels of { } INIT contains.  */
20175 
20176 static int
braced_init_depth(tree init)20177 braced_init_depth (tree init)
20178 {
20179   if (!init || !BRACE_ENCLOSED_INITIALIZER_P (init))
20180     return 0;
20181   unsigned i; tree val;
20182   unsigned max = 0;
20183   FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (init), i, val)
20184     {
20185       unsigned elt_d = braced_init_depth (val);
20186       if (elt_d > max)
20187 	max = elt_d;
20188     }
20189   return max + 1;
20190 }
20191 
20192 /* Most parms like fn_type_unification.
20193 
20194    If SUBR is 1, we're being called recursively (to unify the
20195    arguments of a function or method parameter of a function
20196    template).
20197 
20198    CHECKS is a pointer to a vector of access checks encountered while
20199    substituting default template arguments.  */
20200 
20201 static int
type_unification_real(tree tparms,tree full_targs,tree xparms,const tree * xargs,unsigned int xnargs,int subr,unification_kind_t strict,int flags,vec<deferred_access_check,va_gc> ** checks,bool explain_p)20202 type_unification_real (tree tparms,
20203 		       tree full_targs,
20204 		       tree xparms,
20205 		       const tree *xargs,
20206 		       unsigned int xnargs,
20207 		       int subr,
20208 		       unification_kind_t strict,
20209 		       int flags,
20210 		       vec<deferred_access_check, va_gc> **checks,
20211 		       bool explain_p)
20212 {
20213   tree parm, arg;
20214   int i;
20215   int ntparms = TREE_VEC_LENGTH (tparms);
20216   int saw_undeduced = 0;
20217   tree parms;
20218   const tree *args;
20219   unsigned int nargs;
20220   unsigned int ia;
20221 
20222   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
20223   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
20224   gcc_assert (ntparms > 0);
20225 
20226   tree targs = INNERMOST_TEMPLATE_ARGS (full_targs);
20227 
20228   /* Reset the number of non-defaulted template arguments contained
20229      in TARGS.  */
20230   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
20231 
20232  again:
20233   parms = xparms;
20234   args = xargs;
20235   nargs = xnargs;
20236 
20237   ia = 0;
20238   while (parms && parms != void_list_node
20239 	 && ia < nargs)
20240     {
20241       parm = TREE_VALUE (parms);
20242 
20243       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
20244 	  && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
20245 	/* For a function parameter pack that occurs at the end of the
20246 	   parameter-declaration-list, the type A of each remaining
20247 	   argument of the call is compared with the type P of the
20248 	   declarator-id of the function parameter pack.  */
20249 	break;
20250 
20251       parms = TREE_CHAIN (parms);
20252 
20253       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
20254 	/* For a function parameter pack that does not occur at the
20255 	   end of the parameter-declaration-list, the type of the
20256 	   parameter pack is a non-deduced context.  */
20257 	continue;
20258 
20259       arg = args[ia];
20260       ++ia;
20261 
20262       if (unify_one_argument (tparms, full_targs, parm, arg, subr, strict,
20263 			      explain_p))
20264 	return 1;
20265     }
20266 
20267   if (parms
20268       && parms != void_list_node
20269       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
20270     {
20271       /* Unify the remaining arguments with the pack expansion type.  */
20272       tree argvec;
20273       tree parmvec = make_tree_vec (1);
20274 
20275       /* Allocate a TREE_VEC and copy in all of the arguments */
20276       argvec = make_tree_vec (nargs - ia);
20277       for (i = 0; ia < nargs; ++ia, ++i)
20278 	TREE_VEC_ELT (argvec, i) = args[ia];
20279 
20280       /* Copy the parameter into parmvec.  */
20281       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
20282       if (unify_pack_expansion (tparms, full_targs, parmvec, argvec, strict,
20283                                 /*subr=*/subr, explain_p))
20284         return 1;
20285 
20286       /* Advance to the end of the list of parameters.  */
20287       parms = TREE_CHAIN (parms);
20288     }
20289 
20290   /* Fail if we've reached the end of the parm list, and more args
20291      are present, and the parm list isn't variadic.  */
20292   if (ia < nargs && parms == void_list_node)
20293     return unify_too_many_arguments (explain_p, nargs, ia);
20294   /* Fail if parms are left and they don't have default values and
20295      they aren't all deduced as empty packs (c++/57397).  This is
20296      consistent with sufficient_parms_p.  */
20297   if (parms && parms != void_list_node
20298       && TREE_PURPOSE (parms) == NULL_TREE)
20299     {
20300       unsigned int count = nargs;
20301       tree p = parms;
20302       bool type_pack_p;
20303       do
20304 	{
20305 	  type_pack_p = TREE_CODE (TREE_VALUE (p)) == TYPE_PACK_EXPANSION;
20306 	  if (!type_pack_p)
20307 	    count++;
20308 	  p = TREE_CHAIN (p);
20309 	}
20310       while (p && p != void_list_node);
20311       if (count != nargs)
20312 	return unify_too_few_arguments (explain_p, ia, count,
20313 					type_pack_p);
20314     }
20315 
20316   if (!subr)
20317     {
20318       tsubst_flags_t complain = (explain_p
20319 				 ? tf_warning_or_error
20320 				 : tf_none);
20321       bool tried_array_deduction = (cxx_dialect < cxx17);
20322 
20323       for (i = 0; i < ntparms; i++)
20324 	{
20325 	  tree targ = TREE_VEC_ELT (targs, i);
20326 	  tree tparm = TREE_VEC_ELT (tparms, i);
20327 
20328 	  /* Clear the "incomplete" flags on all argument packs now so that
20329 	     substituting them into later default arguments works.  */
20330 	  if (targ && ARGUMENT_PACK_P (targ))
20331             {
20332               ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
20333               ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
20334             }
20335 
20336 	  if (targ || tparm == error_mark_node)
20337 	    continue;
20338 	  tparm = TREE_VALUE (tparm);
20339 
20340 	  if (TREE_CODE (tparm) == TYPE_DECL
20341 	      && !tried_array_deduction)
20342 	    {
20343 	      try_array_deduction (tparms, targs, xparms);
20344 	      tried_array_deduction = true;
20345 	      if (TREE_VEC_ELT (targs, i))
20346 		continue;
20347 	    }
20348 
20349 	  /* If this is an undeduced nontype parameter that depends on
20350 	     a type parameter, try another pass; its type may have been
20351 	     deduced from a later argument than the one from which
20352 	     this parameter can be deduced.  */
20353 	  if (TREE_CODE (tparm) == PARM_DECL
20354 	      && uses_template_parms (TREE_TYPE (tparm))
20355 	      && saw_undeduced < 2)
20356 	    {
20357 	      saw_undeduced = 1;
20358 	      continue;
20359 	    }
20360 
20361 	  /* Core issue #226 (C++0x) [temp.deduct]:
20362 
20363 	     If a template argument has not been deduced, its
20364 	     default template argument, if any, is used.
20365 
20366 	     When we are in C++98 mode, TREE_PURPOSE will either
20367 	     be NULL_TREE or ERROR_MARK_NODE, so we do not need
20368 	     to explicitly check cxx_dialect here.  */
20369 	  if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
20370 	    /* OK, there is a default argument.  Wait until after the
20371 	       conversion check to do substitution.  */
20372 	    continue;
20373 
20374 	  /* If the type parameter is a parameter pack, then it will
20375 	     be deduced to an empty parameter pack.  */
20376 	  if (template_parameter_pack_p (tparm))
20377 	    {
20378 	      tree arg;
20379 
20380 	      if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
20381 		{
20382 		  arg = make_node (NONTYPE_ARGUMENT_PACK);
20383 		  TREE_CONSTANT (arg) = 1;
20384 		}
20385 	      else
20386 		arg = cxx_make_type (TYPE_ARGUMENT_PACK);
20387 
20388 	      SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
20389 
20390 	      TREE_VEC_ELT (targs, i) = arg;
20391 	      continue;
20392 	    }
20393 
20394 	  return unify_parameter_deduction_failure (explain_p, tparm);
20395 	}
20396 
20397       /* DR 1391: All parameters have args, now check non-dependent parms for
20398 	 convertibility.  */
20399       if (saw_undeduced < 2)
20400 	for (ia = 0, parms = xparms, args = xargs, nargs = xnargs;
20401 	     parms && parms != void_list_node && ia < nargs; )
20402 	  {
20403 	    parm = TREE_VALUE (parms);
20404 
20405 	    if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
20406 		&& (!TREE_CHAIN (parms)
20407 		    || TREE_CHAIN (parms) == void_list_node))
20408 	      /* For a function parameter pack that occurs at the end of the
20409 		 parameter-declaration-list, the type A of each remaining
20410 		 argument of the call is compared with the type P of the
20411 		 declarator-id of the function parameter pack.  */
20412 	      break;
20413 
20414 	    parms = TREE_CHAIN (parms);
20415 
20416 	    if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
20417 	      /* For a function parameter pack that does not occur at the
20418 		 end of the parameter-declaration-list, the type of the
20419 		 parameter pack is a non-deduced context.  */
20420 	      continue;
20421 
20422 	    arg = args[ia];
20423 	    ++ia;
20424 
20425 	    if (uses_template_parms (parm))
20426 	      continue;
20427 	    /* Workaround for c++/80290: avoid combinatorial explosion on
20428 	       deeply nested braced init-lists.  */
20429 	    if (braced_init_depth (arg) > 2)
20430 	      continue;
20431 	    if (check_non_deducible_conversion (parm, arg, strict, flags,
20432 						explain_p))
20433 	      return 1;
20434 	  }
20435 
20436       /* Now substitute into the default template arguments.  */
20437       for (i = 0; i < ntparms; i++)
20438 	{
20439 	  tree targ = TREE_VEC_ELT (targs, i);
20440 	  tree tparm = TREE_VEC_ELT (tparms, i);
20441 
20442 	  if (targ || tparm == error_mark_node)
20443 	    continue;
20444 	  tree parm = TREE_VALUE (tparm);
20445 	  tree arg = TREE_PURPOSE (tparm);
20446 	  reopen_deferring_access_checks (*checks);
20447 	  location_t save_loc = input_location;
20448 	  if (DECL_P (parm))
20449 	    input_location = DECL_SOURCE_LOCATION (parm);
20450 
20451 	  if (saw_undeduced == 1
20452 	      && TREE_CODE (parm) == PARM_DECL
20453 	      && uses_template_parms (TREE_TYPE (parm)))
20454 	    {
20455 	      /* The type of this non-type parameter depends on undeduced
20456 		 parameters.  Don't try to use its default argument yet,
20457 		 since we might deduce an argument for it on the next pass,
20458 		 but do check whether the arguments we already have cause
20459 		 substitution failure, so that that happens before we try
20460 		 later default arguments (78489).  */
20461 	      ++processing_template_decl;
20462 	      tree type = tsubst (TREE_TYPE (parm), full_targs, complain,
20463 				  NULL_TREE);
20464 	      --processing_template_decl;
20465 	      if (type == error_mark_node)
20466 		arg = error_mark_node;
20467 	      else
20468 		arg = NULL_TREE;
20469 	    }
20470 	  else
20471 	    {
20472 	      tree substed = NULL_TREE;
20473 	      if (saw_undeduced == 1 && processing_template_decl == 0)
20474 		{
20475 		  /* First instatiate in template context, in case we still
20476 		     depend on undeduced template parameters.  */
20477 		  ++processing_template_decl;
20478 		  substed = tsubst_template_arg (arg, full_targs, complain,
20479 						 NULL_TREE);
20480 		  --processing_template_decl;
20481 		  if (substed != error_mark_node
20482 		      && !uses_template_parms (substed))
20483 		    /* We replaced all the tparms, substitute again out of
20484 		       template context.  */
20485 		    substed = NULL_TREE;
20486 		}
20487 	      if (!substed)
20488 		substed = tsubst_template_arg (arg, full_targs, complain,
20489 					       NULL_TREE);
20490 
20491 	      if (!uses_template_parms (substed))
20492 		arg = convert_template_argument (parm, substed, full_targs,
20493 						 complain, i, NULL_TREE);
20494 	      else if (saw_undeduced == 1)
20495 		arg = NULL_TREE;
20496 	      else
20497 		arg = error_mark_node;
20498 	    }
20499 
20500 	  input_location = save_loc;
20501 	  *checks = get_deferred_access_checks ();
20502 	  pop_deferring_access_checks ();
20503 
20504 	  if (arg == error_mark_node)
20505 	    return 1;
20506 	  else if (arg)
20507 	    {
20508 	      TREE_VEC_ELT (targs, i) = arg;
20509 	      /* The position of the first default template argument,
20510 		 is also the number of non-defaulted arguments in TARGS.
20511 		 Record that.  */
20512 	      if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
20513 		SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
20514 	    }
20515 	}
20516 
20517       if (saw_undeduced++ == 1)
20518 	goto again;
20519     }
20520 
20521   if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
20522     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
20523 
20524   return unify_success (explain_p);
20525 }
20526 
20527 /* Subroutine of type_unification_real.  Args are like the variables
20528    at the call site.  ARG is an overloaded function (or template-id);
20529    we try deducing template args from each of the overloads, and if
20530    only one succeeds, we go with that.  Modifies TARGS and returns
20531    true on success.  */
20532 
20533 static bool
resolve_overloaded_unification(tree tparms,tree targs,tree parm,tree arg,unification_kind_t strict,int sub_strict,bool explain_p)20534 resolve_overloaded_unification (tree tparms,
20535 				tree targs,
20536 				tree parm,
20537 				tree arg,
20538 				unification_kind_t strict,
20539 				int sub_strict,
20540 			        bool explain_p)
20541 {
20542   tree tempargs = copy_node (targs);
20543   int good = 0;
20544   tree goodfn = NULL_TREE;
20545   bool addr_p;
20546 
20547   if (TREE_CODE (arg) == ADDR_EXPR)
20548     {
20549       arg = TREE_OPERAND (arg, 0);
20550       addr_p = true;
20551     }
20552   else
20553     addr_p = false;
20554 
20555   if (TREE_CODE (arg) == COMPONENT_REF)
20556     /* Handle `&x' where `x' is some static or non-static member
20557        function name.  */
20558     arg = TREE_OPERAND (arg, 1);
20559 
20560   if (TREE_CODE (arg) == OFFSET_REF)
20561     arg = TREE_OPERAND (arg, 1);
20562 
20563   /* Strip baselink information.  */
20564   if (BASELINK_P (arg))
20565     arg = BASELINK_FUNCTIONS (arg);
20566 
20567   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
20568     {
20569       /* If we got some explicit template args, we need to plug them into
20570 	 the affected templates before we try to unify, in case the
20571 	 explicit args will completely resolve the templates in question.  */
20572 
20573       int ok = 0;
20574       tree expl_subargs = TREE_OPERAND (arg, 1);
20575       arg = TREE_OPERAND (arg, 0);
20576 
20577       for (lkp_iterator iter (arg); iter; ++iter)
20578 	{
20579 	  tree fn = *iter;
20580 	  tree subargs, elem;
20581 
20582 	  if (TREE_CODE (fn) != TEMPLATE_DECL)
20583 	    continue;
20584 
20585 	  subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
20586 					   expl_subargs, NULL_TREE, tf_none,
20587 					   /*require_all_args=*/true,
20588 					   /*use_default_args=*/true);
20589 	  if (subargs != error_mark_node
20590 	      && !any_dependent_template_arguments_p (subargs))
20591 	    {
20592 	      elem = TREE_TYPE (instantiate_template (fn, subargs, tf_none));
20593 	      if (try_one_overload (tparms, targs, tempargs, parm,
20594 				    elem, strict, sub_strict, addr_p, explain_p)
20595 		  && (!goodfn || !same_type_p (goodfn, elem)))
20596 		{
20597 		  goodfn = elem;
20598 		  ++good;
20599 		}
20600 	    }
20601 	  else if (subargs)
20602 	    ++ok;
20603 	}
20604       /* If no templates (or more than one) are fully resolved by the
20605 	 explicit arguments, this template-id is a non-deduced context; it
20606 	 could still be OK if we deduce all template arguments for the
20607 	 enclosing call through other arguments.  */
20608       if (good != 1)
20609 	good = ok;
20610     }
20611   else if (TREE_CODE (arg) != OVERLOAD
20612 	   && TREE_CODE (arg) != FUNCTION_DECL)
20613     /* If ARG is, for example, "(0, &f)" then its type will be unknown
20614        -- but the deduction does not succeed because the expression is
20615        not just the function on its own.  */
20616     return false;
20617   else
20618     for (lkp_iterator iter (arg); iter; ++iter)
20619       {
20620 	tree fn = *iter;
20621 	if (try_one_overload (tparms, targs, tempargs, parm, TREE_TYPE (fn),
20622 			      strict, sub_strict, addr_p, explain_p)
20623 	    && (!goodfn || !decls_match (goodfn, fn)))
20624 	  {
20625 	    goodfn = fn;
20626 	    ++good;
20627 	  }
20628       }
20629 
20630   /* [temp.deduct.type] A template-argument can be deduced from a pointer
20631      to function or pointer to member function argument if the set of
20632      overloaded functions does not contain function templates and at most
20633      one of a set of overloaded functions provides a unique match.
20634 
20635      So if we found multiple possibilities, we return success but don't
20636      deduce anything.  */
20637 
20638   if (good == 1)
20639     {
20640       int i = TREE_VEC_LENGTH (targs);
20641       for (; i--; )
20642 	if (TREE_VEC_ELT (tempargs, i))
20643 	  {
20644 	    tree old = TREE_VEC_ELT (targs, i);
20645 	    tree new_ = TREE_VEC_ELT (tempargs, i);
20646 	    if (new_ && old && ARGUMENT_PACK_P (old)
20647 		&& ARGUMENT_PACK_EXPLICIT_ARGS (old))
20648 	      /* Don't forget explicit template arguments in a pack.  */
20649 	      ARGUMENT_PACK_EXPLICIT_ARGS (new_)
20650 		= ARGUMENT_PACK_EXPLICIT_ARGS (old);
20651 	    TREE_VEC_ELT (targs, i) = new_;
20652 	  }
20653     }
20654   if (good)
20655     return true;
20656 
20657   return false;
20658 }
20659 
20660 /* Core DR 115: In contexts where deduction is done and fails, or in
20661    contexts where deduction is not done, if a template argument list is
20662    specified and it, along with any default template arguments, identifies
20663    a single function template specialization, then the template-id is an
20664    lvalue for the function template specialization.  */
20665 
20666 tree
resolve_nondeduced_context(tree orig_expr,tsubst_flags_t complain)20667 resolve_nondeduced_context (tree orig_expr, tsubst_flags_t complain)
20668 {
20669   tree expr, offset, baselink;
20670   bool addr;
20671 
20672   if (!type_unknown_p (orig_expr))
20673     return orig_expr;
20674 
20675   expr = orig_expr;
20676   addr = false;
20677   offset = NULL_TREE;
20678   baselink = NULL_TREE;
20679 
20680   if (TREE_CODE (expr) == ADDR_EXPR)
20681     {
20682       expr = TREE_OPERAND (expr, 0);
20683       addr = true;
20684     }
20685   if (TREE_CODE (expr) == OFFSET_REF)
20686     {
20687       offset = expr;
20688       expr = TREE_OPERAND (expr, 1);
20689     }
20690   if (BASELINK_P (expr))
20691     {
20692       baselink = expr;
20693       expr = BASELINK_FUNCTIONS (expr);
20694     }
20695 
20696   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
20697     {
20698       int good = 0;
20699       tree goodfn = NULL_TREE;
20700 
20701       /* If we got some explicit template args, we need to plug them into
20702 	 the affected templates before we try to unify, in case the
20703 	 explicit args will completely resolve the templates in question.  */
20704 
20705       tree expl_subargs = TREE_OPERAND (expr, 1);
20706       tree arg = TREE_OPERAND (expr, 0);
20707       tree badfn = NULL_TREE;
20708       tree badargs = NULL_TREE;
20709 
20710       for (lkp_iterator iter (arg); iter; ++iter)
20711 	{
20712 	  tree fn = *iter;
20713 	  tree subargs, elem;
20714 
20715 	  if (TREE_CODE (fn) != TEMPLATE_DECL)
20716 	    continue;
20717 
20718 	  subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
20719 					   expl_subargs, NULL_TREE, tf_none,
20720 					   /*require_all_args=*/true,
20721 					   /*use_default_args=*/true);
20722 	  if (subargs != error_mark_node
20723 	      && !any_dependent_template_arguments_p (subargs))
20724 	    {
20725 	      elem = instantiate_template (fn, subargs, tf_none);
20726 	      if (elem == error_mark_node)
20727 		{
20728 		  badfn = fn;
20729 		  badargs = subargs;
20730 		}
20731 	      else if (elem && (!goodfn || !decls_match (goodfn, elem)))
20732 		{
20733 		  goodfn = elem;
20734 		  ++good;
20735 		}
20736 	    }
20737 	}
20738       if (good == 1)
20739 	{
20740 	  mark_used (goodfn);
20741 	  expr = goodfn;
20742 	  if (baselink)
20743 	    expr = build_baselink (BASELINK_BINFO (baselink),
20744 				   BASELINK_ACCESS_BINFO (baselink),
20745 				   expr, BASELINK_OPTYPE (baselink));
20746 	  if (offset)
20747 	    {
20748 	      tree base
20749 		= TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
20750 	      expr = build_offset_ref (base, expr, addr, complain);
20751 	    }
20752 	  if (addr)
20753 	    expr = cp_build_addr_expr (expr, complain);
20754 	  return expr;
20755 	}
20756       else if (good == 0 && badargs && (complain & tf_error))
20757 	/* There were no good options and at least one bad one, so let the
20758 	   user know what the problem is.  */
20759 	instantiate_template (badfn, badargs, complain);
20760     }
20761   return orig_expr;
20762 }
20763 
20764 /* Subroutine of resolve_overloaded_unification; does deduction for a single
20765    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
20766    different overloads deduce different arguments for a given parm.
20767    ADDR_P is true if the expression for which deduction is being
20768    performed was of the form "& fn" rather than simply "fn".
20769 
20770    Returns 1 on success.  */
20771 
20772 static int
try_one_overload(tree tparms,tree orig_targs,tree targs,tree parm,tree arg,unification_kind_t strict,int sub_strict,bool addr_p,bool explain_p)20773 try_one_overload (tree tparms,
20774 		  tree orig_targs,
20775 		  tree targs,
20776 		  tree parm,
20777 		  tree arg,
20778 		  unification_kind_t strict,
20779 		  int sub_strict,
20780 		  bool addr_p,
20781 		  bool explain_p)
20782 {
20783   int nargs;
20784   tree tempargs;
20785   int i;
20786 
20787   if (arg == error_mark_node)
20788     return 0;
20789 
20790   /* [temp.deduct.type] A template-argument can be deduced from a pointer
20791      to function or pointer to member function argument if the set of
20792      overloaded functions does not contain function templates and at most
20793      one of a set of overloaded functions provides a unique match.
20794 
20795      So if this is a template, just return success.  */
20796 
20797   if (uses_template_parms (arg))
20798     return 1;
20799 
20800   if (TREE_CODE (arg) == METHOD_TYPE)
20801     arg = build_ptrmemfunc_type (build_pointer_type (arg));
20802   else if (addr_p)
20803     arg = build_pointer_type (arg);
20804 
20805   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
20806 
20807   /* We don't copy orig_targs for this because if we have already deduced
20808      some template args from previous args, unify would complain when we
20809      try to deduce a template parameter for the same argument, even though
20810      there isn't really a conflict.  */
20811   nargs = TREE_VEC_LENGTH (targs);
20812   tempargs = make_tree_vec (nargs);
20813 
20814   if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
20815     return 0;
20816 
20817   /* First make sure we didn't deduce anything that conflicts with
20818      explicitly specified args.  */
20819   for (i = nargs; i--; )
20820     {
20821       tree elt = TREE_VEC_ELT (tempargs, i);
20822       tree oldelt = TREE_VEC_ELT (orig_targs, i);
20823 
20824       if (!elt)
20825 	/*NOP*/;
20826       else if (uses_template_parms (elt))
20827 	/* Since we're unifying against ourselves, we will fill in
20828 	   template args used in the function parm list with our own
20829 	   template parms.  Discard them.  */
20830 	TREE_VEC_ELT (tempargs, i) = NULL_TREE;
20831       else if (oldelt && ARGUMENT_PACK_P (oldelt))
20832 	{
20833 	  /* Check that the argument at each index of the deduced argument pack
20834 	     is equivalent to the corresponding explicitly specified argument.
20835 	     We may have deduced more arguments than were explicitly specified,
20836 	     and that's OK.  */
20837 
20838 	  /* We used to assert ARGUMENT_PACK_INCOMPLETE_P (oldelt) here, but
20839 	     that's wrong if we deduce the same argument pack from multiple
20840 	     function arguments: it's only incomplete the first time.  */
20841 
20842 	  tree explicit_pack = ARGUMENT_PACK_ARGS (oldelt);
20843 	  tree deduced_pack = ARGUMENT_PACK_ARGS (elt);
20844 
20845 	  if (TREE_VEC_LENGTH (deduced_pack)
20846 	      < TREE_VEC_LENGTH (explicit_pack))
20847 	    return 0;
20848 
20849 	  for (int j = 0; j < TREE_VEC_LENGTH (explicit_pack); j++)
20850 	    if (!template_args_equal (TREE_VEC_ELT (explicit_pack, j),
20851 				      TREE_VEC_ELT (deduced_pack, j)))
20852 	      return 0;
20853 	}
20854       else if (oldelt && !template_args_equal (oldelt, elt))
20855 	return 0;
20856     }
20857 
20858   for (i = nargs; i--; )
20859     {
20860       tree elt = TREE_VEC_ELT (tempargs, i);
20861 
20862       if (elt)
20863 	TREE_VEC_ELT (targs, i) = elt;
20864     }
20865 
20866   return 1;
20867 }
20868 
20869 /* PARM is a template class (perhaps with unbound template
20870    parameters).  ARG is a fully instantiated type.  If ARG can be
20871    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
20872    TARGS are as for unify.  */
20873 
20874 static tree
try_class_unification(tree tparms,tree targs,tree parm,tree arg,bool explain_p)20875 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
20876 		       bool explain_p)
20877 {
20878   tree copy_of_targs;
20879 
20880   if (!CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
20881     return NULL_TREE;
20882   else if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
20883     /* Matches anything.  */;
20884   else if (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
20885 	   != most_general_template (CLASSTYPE_TI_TEMPLATE (parm)))
20886     return NULL_TREE;
20887 
20888   /* We need to make a new template argument vector for the call to
20889      unify.  If we used TARGS, we'd clutter it up with the result of
20890      the attempted unification, even if this class didn't work out.
20891      We also don't want to commit ourselves to all the unifications
20892      we've already done, since unification is supposed to be done on
20893      an argument-by-argument basis.  In other words, consider the
20894      following pathological case:
20895 
20896        template <int I, int J, int K>
20897        struct S {};
20898 
20899        template <int I, int J>
20900        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
20901 
20902        template <int I, int J, int K>
20903        void f(S<I, J, K>, S<I, I, I>);
20904 
20905        void g() {
20906 	 S<0, 0, 0> s0;
20907 	 S<0, 1, 2> s2;
20908 
20909 	 f(s0, s2);
20910        }
20911 
20912      Now, by the time we consider the unification involving `s2', we
20913      already know that we must have `f<0, 0, 0>'.  But, even though
20914      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
20915      because there are two ways to unify base classes of S<0, 1, 2>
20916      with S<I, I, I>.  If we kept the already deduced knowledge, we
20917      would reject the possibility I=1.  */
20918   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
20919 
20920   if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
20921     {
20922       if (unify_bound_ttp_args (tparms, copy_of_targs, parm, arg, explain_p))
20923 	return NULL_TREE;
20924       return arg;
20925     }
20926 
20927   /* If unification failed, we're done.  */
20928   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
20929 	     CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE, explain_p))
20930     return NULL_TREE;
20931 
20932   return arg;
20933 }
20934 
20935 /* Given a template type PARM and a class type ARG, find the unique
20936    base type in ARG that is an instance of PARM.  We do not examine
20937    ARG itself; only its base-classes.  If there is not exactly one
20938    appropriate base class, return NULL_TREE.  PARM may be the type of
20939    a partial specialization, as well as a plain template type.  Used
20940    by unify.  */
20941 
20942 static enum template_base_result
get_template_base(tree tparms,tree targs,tree parm,tree arg,bool explain_p,tree * result)20943 get_template_base (tree tparms, tree targs, tree parm, tree arg,
20944 		   bool explain_p, tree *result)
20945 {
20946   tree rval = NULL_TREE;
20947   tree binfo;
20948 
20949   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
20950 
20951   binfo = TYPE_BINFO (complete_type (arg));
20952   if (!binfo)
20953     {
20954       /* The type could not be completed.  */
20955       *result = NULL_TREE;
20956       return tbr_incomplete_type;
20957     }
20958 
20959   /* Walk in inheritance graph order.  The search order is not
20960      important, and this avoids multiple walks of virtual bases.  */
20961   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
20962     {
20963       tree r = try_class_unification (tparms, targs, parm,
20964 				      BINFO_TYPE (binfo), explain_p);
20965 
20966       if (r)
20967 	{
20968 	  /* If there is more than one satisfactory baseclass, then:
20969 
20970 	       [temp.deduct.call]
20971 
20972 	      If they yield more than one possible deduced A, the type
20973 	      deduction fails.
20974 
20975 	     applies.  */
20976 	  if (rval && !same_type_p (r, rval))
20977 	    {
20978 	      *result = NULL_TREE;
20979 	      return tbr_ambiguous_baseclass;
20980 	    }
20981 
20982 	  rval = r;
20983 	}
20984     }
20985 
20986   *result = rval;
20987   return tbr_success;
20988 }
20989 
20990 /* Returns the level of DECL, which declares a template parameter.  */
20991 
20992 static int
template_decl_level(tree decl)20993 template_decl_level (tree decl)
20994 {
20995   switch (TREE_CODE (decl))
20996     {
20997     case TYPE_DECL:
20998     case TEMPLATE_DECL:
20999       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
21000 
21001     case PARM_DECL:
21002       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
21003 
21004     default:
21005       gcc_unreachable ();
21006     }
21007   return 0;
21008 }
21009 
21010 /* Decide whether ARG can be unified with PARM, considering only the
21011    cv-qualifiers of each type, given STRICT as documented for unify.
21012    Returns nonzero iff the unification is OK on that basis.  */
21013 
21014 static int
check_cv_quals_for_unify(int strict,tree arg,tree parm)21015 check_cv_quals_for_unify (int strict, tree arg, tree parm)
21016 {
21017   int arg_quals = cp_type_quals (arg);
21018   int parm_quals = cp_type_quals (parm);
21019 
21020   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
21021       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
21022     {
21023       /*  Although a CVR qualifier is ignored when being applied to a
21024 	  substituted template parameter ([8.3.2]/1 for example), that
21025 	  does not allow us to unify "const T" with "int&" because both
21026 	  types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
21027 	  It is ok when we're allowing additional CV qualifiers
21028 	  at the outer level [14.8.2.1]/3,1st bullet.  */
21029       if ((TREE_CODE (arg) == REFERENCE_TYPE
21030 	   || TREE_CODE (arg) == FUNCTION_TYPE
21031 	   || TREE_CODE (arg) == METHOD_TYPE)
21032 	  && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
21033 	return 0;
21034 
21035       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
21036 	  && (parm_quals & TYPE_QUAL_RESTRICT))
21037 	return 0;
21038     }
21039 
21040   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
21041       && (arg_quals & parm_quals) != parm_quals)
21042     return 0;
21043 
21044   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
21045       && (parm_quals & arg_quals) != arg_quals)
21046     return 0;
21047 
21048   return 1;
21049 }
21050 
21051 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
21052 void
template_parm_level_and_index(tree parm,int * level,int * index)21053 template_parm_level_and_index (tree parm, int* level, int* index)
21054 {
21055   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
21056       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
21057       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
21058     {
21059       *index = TEMPLATE_TYPE_IDX (parm);
21060       *level = TEMPLATE_TYPE_LEVEL (parm);
21061     }
21062   else
21063     {
21064       *index = TEMPLATE_PARM_IDX (parm);
21065       *level = TEMPLATE_PARM_LEVEL (parm);
21066     }
21067 }
21068 
21069 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP)			\
21070   do {									\
21071     if (unify (TP, TA, P, A, S, EP))					\
21072       return 1;								\
21073   } while (0)
21074 
21075 /* Unifies the remaining arguments in PACKED_ARGS with the pack
21076    expansion at the end of PACKED_PARMS. Returns 0 if the type
21077    deduction succeeds, 1 otherwise. STRICT is the same as in
21078    fn_type_unification. CALL_ARGS_P is true iff PACKED_ARGS is actually a
21079    function call argument list. We'll need to adjust the arguments to make them
21080    types. SUBR tells us if this is from a recursive call to
21081    type_unification_real, or for comparing two template argument
21082    lists. */
21083 
21084 static int
unify_pack_expansion(tree tparms,tree targs,tree packed_parms,tree packed_args,unification_kind_t strict,bool subr,bool explain_p)21085 unify_pack_expansion (tree tparms, tree targs, tree packed_parms,
21086                       tree packed_args, unification_kind_t strict,
21087                       bool subr, bool explain_p)
21088 {
21089   tree parm
21090     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
21091   tree pattern = PACK_EXPANSION_PATTERN (parm);
21092   tree pack, packs = NULL_TREE;
21093   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
21094 
21095   /* Add in any args remembered from an earlier partial instantiation.  */
21096   targs = add_to_template_args (PACK_EXPANSION_EXTRA_ARGS (parm), targs);
21097   int levels = TMPL_ARGS_DEPTH (targs);
21098 
21099   packed_args = expand_template_argument_pack (packed_args);
21100 
21101   int len = TREE_VEC_LENGTH (packed_args);
21102 
21103   /* Determine the parameter packs we will be deducing from the
21104      pattern, and record their current deductions.  */
21105   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm);
21106        pack; pack = TREE_CHAIN (pack))
21107     {
21108       tree parm_pack = TREE_VALUE (pack);
21109       int idx, level;
21110 
21111       /* Only template parameter packs can be deduced, not e.g. function
21112 	 parameter packs or __bases or __integer_pack.  */
21113       if (!TEMPLATE_PARM_P (parm_pack))
21114 	continue;
21115 
21116       /* Determine the index and level of this parameter pack.  */
21117       template_parm_level_and_index (parm_pack, &level, &idx);
21118       if (level < levels)
21119 	continue;
21120 
21121       /* Keep track of the parameter packs and their corresponding
21122          argument packs.  */
21123       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
21124       TREE_TYPE (packs) = make_tree_vec (len - start);
21125     }
21126 
21127   /* Loop through all of the arguments that have not yet been
21128      unified and unify each with the pattern.  */
21129   for (i = start; i < len; i++)
21130     {
21131       tree parm;
21132       bool any_explicit = false;
21133       tree arg = TREE_VEC_ELT (packed_args, i);
21134 
21135       /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
21136 	 or the element of its argument pack at the current index if
21137 	 this argument was explicitly specified.  */
21138       for (pack = packs; pack; pack = TREE_CHAIN (pack))
21139         {
21140           int idx, level;
21141           tree arg, pargs;
21142           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
21143 
21144           arg = NULL_TREE;
21145           if (TREE_VALUE (pack)
21146               && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
21147               && (i - start < TREE_VEC_LENGTH (pargs)))
21148             {
21149               any_explicit = true;
21150               arg = TREE_VEC_ELT (pargs, i - start);
21151             }
21152           TMPL_ARG (targs, level, idx) = arg;
21153         }
21154 
21155       /* If we had explicit template arguments, substitute them into the
21156 	 pattern before deduction.  */
21157       if (any_explicit)
21158 	{
21159 	  /* Some arguments might still be unspecified or dependent.  */
21160 	  bool dependent;
21161 	  ++processing_template_decl;
21162 	  dependent = any_dependent_template_arguments_p (targs);
21163 	  if (!dependent)
21164 	    --processing_template_decl;
21165 	  parm = tsubst (pattern, targs,
21166 			 explain_p ? tf_warning_or_error : tf_none,
21167 			 NULL_TREE);
21168 	  if (dependent)
21169 	    --processing_template_decl;
21170 	  if (parm == error_mark_node)
21171 	    return 1;
21172 	}
21173       else
21174 	parm = pattern;
21175 
21176       /* Unify the pattern with the current argument.  */
21177       if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
21178 			      explain_p))
21179 	return 1;
21180 
21181       /* For each parameter pack, collect the deduced value.  */
21182       for (pack = packs; pack; pack = TREE_CHAIN (pack))
21183         {
21184           int idx, level;
21185           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
21186 
21187           TREE_VEC_ELT (TREE_TYPE (pack), i - start) =
21188             TMPL_ARG (targs, level, idx);
21189         }
21190     }
21191 
21192   /* Verify that the results of unification with the parameter packs
21193      produce results consistent with what we've seen before, and make
21194      the deduced argument packs available.  */
21195   for (pack = packs; pack; pack = TREE_CHAIN (pack))
21196     {
21197       tree old_pack = TREE_VALUE (pack);
21198       tree new_args = TREE_TYPE (pack);
21199       int i, len = TREE_VEC_LENGTH (new_args);
21200       int idx, level;
21201       bool nondeduced_p = false;
21202 
21203       /* By default keep the original deduced argument pack.
21204 	 If necessary, more specific code is going to update the
21205 	 resulting deduced argument later down in this function.  */
21206       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
21207       TMPL_ARG (targs, level, idx) = old_pack;
21208 
21209       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
21210 	 actually deduce anything.  */
21211       for (i = 0; i < len && !nondeduced_p; ++i)
21212 	if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
21213 	  nondeduced_p = true;
21214       if (nondeduced_p)
21215 	continue;
21216 
21217       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
21218         {
21219           /* If we had fewer function args than explicit template args,
21220              just use the explicits.  */
21221           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
21222           int explicit_len = TREE_VEC_LENGTH (explicit_args);
21223           if (len < explicit_len)
21224             new_args = explicit_args;
21225         }
21226 
21227       if (!old_pack)
21228         {
21229           tree result;
21230           /* Build the deduced *_ARGUMENT_PACK.  */
21231           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
21232             {
21233               result = make_node (NONTYPE_ARGUMENT_PACK);
21234               TREE_CONSTANT (result) = 1;
21235             }
21236           else
21237             result = cxx_make_type (TYPE_ARGUMENT_PACK);
21238 
21239           SET_ARGUMENT_PACK_ARGS (result, new_args);
21240 
21241           /* Note the deduced argument packs for this parameter
21242              pack.  */
21243           TMPL_ARG (targs, level, idx) = result;
21244         }
21245       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
21246                && (ARGUMENT_PACK_ARGS (old_pack)
21247                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
21248         {
21249           /* We only had the explicitly-provided arguments before, but
21250              now we have a complete set of arguments.  */
21251           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
21252 
21253           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
21254           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
21255           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
21256         }
21257       else
21258 	{
21259 	  tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
21260 	  tree old_args = ARGUMENT_PACK_ARGS (old_pack);
21261 
21262 	  if (!comp_template_args (old_args, new_args,
21263 				   &bad_old_arg, &bad_new_arg))
21264 	    /* Inconsistent unification of this parameter pack.  */
21265 	    return unify_parameter_pack_inconsistent (explain_p,
21266 						      bad_old_arg,
21267 						      bad_new_arg);
21268 	}
21269     }
21270 
21271   return unify_success (explain_p);
21272 }
21273 
21274 /* Handle unification of the domain of an array.  PARM_DOM and ARG_DOM are
21275    INTEGER_TYPEs representing the TYPE_DOMAIN of ARRAY_TYPEs.  The other
21276    parameters and return value are as for unify.  */
21277 
21278 static int
unify_array_domain(tree tparms,tree targs,tree parm_dom,tree arg_dom,bool explain_p)21279 unify_array_domain (tree tparms, tree targs,
21280 		    tree parm_dom, tree arg_dom,
21281 		    bool explain_p)
21282 {
21283   tree parm_max;
21284   tree arg_max;
21285   bool parm_cst;
21286   bool arg_cst;
21287 
21288   /* Our representation of array types uses "N - 1" as the
21289      TYPE_MAX_VALUE for an array with "N" elements, if "N" is
21290      not an integer constant.  We cannot unify arbitrarily
21291      complex expressions, so we eliminate the MINUS_EXPRs
21292      here.  */
21293   parm_max = TYPE_MAX_VALUE (parm_dom);
21294   parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
21295   if (!parm_cst)
21296     {
21297       gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
21298       parm_max = TREE_OPERAND (parm_max, 0);
21299     }
21300   arg_max = TYPE_MAX_VALUE (arg_dom);
21301   arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
21302   if (!arg_cst)
21303     {
21304       /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
21305 	 trying to unify the type of a variable with the type
21306 	 of a template parameter.  For example:
21307 
21308 	   template <unsigned int N>
21309 	   void f (char (&) [N]);
21310 	   int g();
21311 	   void h(int i) {
21312 	     char a[g(i)];
21313 	     f(a);
21314 	   }
21315 
21316 	 Here, the type of the ARG will be "int [g(i)]", and
21317 	 may be a SAVE_EXPR, etc.  */
21318       if (TREE_CODE (arg_max) != MINUS_EXPR)
21319 	return unify_vla_arg (explain_p, arg_dom);
21320       arg_max = TREE_OPERAND (arg_max, 0);
21321     }
21322 
21323   /* If only one of the bounds used a MINUS_EXPR, compensate
21324      by adding one to the other bound.  */
21325   if (parm_cst && !arg_cst)
21326     parm_max = fold_build2_loc (input_location, PLUS_EXPR,
21327 				integer_type_node,
21328 				parm_max,
21329 				integer_one_node);
21330   else if (arg_cst && !parm_cst)
21331     arg_max = fold_build2_loc (input_location, PLUS_EXPR,
21332 			       integer_type_node,
21333 			       arg_max,
21334 			       integer_one_node);
21335 
21336   return unify (tparms, targs, parm_max, arg_max,
21337 		UNIFY_ALLOW_INTEGER, explain_p);
21338 }
21339 
21340 /* Returns whether T, a P or A in unify, is a type, template or expression.  */
21341 
21342 enum pa_kind_t { pa_type, pa_tmpl, pa_expr };
21343 
21344 static pa_kind_t
pa_kind(tree t)21345 pa_kind (tree t)
21346 {
21347   if (PACK_EXPANSION_P (t))
21348     t = PACK_EXPANSION_PATTERN (t);
21349   if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM
21350       || TREE_CODE (t) == UNBOUND_CLASS_TEMPLATE
21351       || DECL_TYPE_TEMPLATE_P (t))
21352     return pa_tmpl;
21353   else if (TYPE_P (t))
21354     return pa_type;
21355   else
21356     return pa_expr;
21357 }
21358 
21359 /* Deduce the value of template parameters.  TPARMS is the (innermost)
21360    set of template parameters to a template.  TARGS is the bindings
21361    for those template parameters, as determined thus far; TARGS may
21362    include template arguments for outer levels of template parameters
21363    as well.  PARM is a parameter to a template function, or a
21364    subcomponent of that parameter; ARG is the corresponding argument.
21365    This function attempts to match PARM with ARG in a manner
21366    consistent with the existing assignments in TARGS.  If more values
21367    are deduced, then TARGS is updated.
21368 
21369    Returns 0 if the type deduction succeeds, 1 otherwise.  The
21370    parameter STRICT is a bitwise or of the following flags:
21371 
21372      UNIFY_ALLOW_NONE:
21373        Require an exact match between PARM and ARG.
21374      UNIFY_ALLOW_MORE_CV_QUAL:
21375        Allow the deduced ARG to be more cv-qualified (by qualification
21376        conversion) than ARG.
21377      UNIFY_ALLOW_LESS_CV_QUAL:
21378        Allow the deduced ARG to be less cv-qualified than ARG.
21379      UNIFY_ALLOW_DERIVED:
21380        Allow the deduced ARG to be a template base class of ARG,
21381        or a pointer to a template base class of the type pointed to by
21382        ARG.
21383      UNIFY_ALLOW_INTEGER:
21384        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
21385        case for more information.
21386      UNIFY_ALLOW_OUTER_LEVEL:
21387        This is the outermost level of a deduction. Used to determine validity
21388        of qualification conversions. A valid qualification conversion must
21389        have const qualified pointers leading up to the inner type which
21390        requires additional CV quals, except at the outer level, where const
21391        is not required [conv.qual]. It would be normal to set this flag in
21392        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
21393      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
21394        This is the outermost level of a deduction, and PARM can be more CV
21395        qualified at this point.
21396      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
21397        This is the outermost level of a deduction, and PARM can be less CV
21398        qualified at this point.  */
21399 
21400 static int
unify(tree tparms,tree targs,tree parm,tree arg,int strict,bool explain_p)21401 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
21402        bool explain_p)
21403 {
21404   int idx;
21405   tree targ;
21406   tree tparm;
21407   int strict_in = strict;
21408   tsubst_flags_t complain = (explain_p
21409 			     ? tf_warning_or_error
21410 			     : tf_none);
21411 
21412   /* I don't think this will do the right thing with respect to types.
21413      But the only case I've seen it in so far has been array bounds, where
21414      signedness is the only information lost, and I think that will be
21415      okay.  */
21416   while (CONVERT_EXPR_P (parm))
21417     parm = TREE_OPERAND (parm, 0);
21418 
21419   if (arg == error_mark_node)
21420     return unify_invalid (explain_p);
21421   if (arg == unknown_type_node
21422       || arg == init_list_type_node)
21423     /* We can't deduce anything from this, but we might get all the
21424        template args from other function args.  */
21425     return unify_success (explain_p);
21426 
21427   if (parm == any_targ_node || arg == any_targ_node)
21428     return unify_success (explain_p);
21429 
21430   /* If PARM uses template parameters, then we can't bail out here,
21431      even if ARG == PARM, since we won't record unifications for the
21432      template parameters.  We might need them if we're trying to
21433      figure out which of two things is more specialized.  */
21434   if (arg == parm && !uses_template_parms (parm))
21435     return unify_success (explain_p);
21436 
21437   /* Handle init lists early, so the rest of the function can assume
21438      we're dealing with a type. */
21439   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
21440     {
21441       tree elt, elttype;
21442       unsigned i;
21443       tree orig_parm = parm;
21444 
21445       /* Replace T with std::initializer_list<T> for deduction.  */
21446       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
21447 	  && flag_deduce_init_list)
21448 	parm = listify (parm);
21449 
21450       if (!is_std_init_list (parm)
21451 	  && TREE_CODE (parm) != ARRAY_TYPE)
21452 	/* We can only deduce from an initializer list argument if the
21453 	   parameter is std::initializer_list or an array; otherwise this
21454 	   is a non-deduced context. */
21455 	return unify_success (explain_p);
21456 
21457       if (TREE_CODE (parm) == ARRAY_TYPE)
21458 	elttype = TREE_TYPE (parm);
21459       else
21460 	{
21461 	  elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
21462 	  /* Deduction is defined in terms of a single type, so just punt
21463 	     on the (bizarre) std::initializer_list<T...>.  */
21464 	  if (PACK_EXPANSION_P (elttype))
21465 	    return unify_success (explain_p);
21466 	}
21467 
21468       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
21469 	{
21470 	  int elt_strict = strict;
21471 
21472 	  if (elt == error_mark_node)
21473 	    return unify_invalid (explain_p);
21474 
21475 	  if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
21476 	    {
21477 	      tree type = TREE_TYPE (elt);
21478 	      if (type == error_mark_node)
21479 		return unify_invalid (explain_p);
21480 	      /* It should only be possible to get here for a call.  */
21481 	      gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
21482 	      elt_strict |= maybe_adjust_types_for_deduction
21483 		(DEDUCE_CALL, &elttype, &type, elt);
21484 	      elt = type;
21485 	    }
21486 
21487 	  RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
21488 				   explain_p);
21489 	}
21490 
21491       if (TREE_CODE (parm) == ARRAY_TYPE
21492 	  && deducible_array_bound (TYPE_DOMAIN (parm)))
21493 	{
21494 	  /* Also deduce from the length of the initializer list.  */
21495 	  tree max = size_int (CONSTRUCTOR_NELTS (arg));
21496 	  tree idx = compute_array_index_type (NULL_TREE, max, tf_none);
21497 	  if (idx == error_mark_node)
21498 	    return unify_invalid (explain_p);
21499 	  return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
21500 				     idx, explain_p);
21501 	}
21502 
21503       /* If the std::initializer_list<T> deduction worked, replace the
21504 	 deduced A with std::initializer_list<A>.  */
21505       if (orig_parm != parm)
21506 	{
21507 	  idx = TEMPLATE_TYPE_IDX (orig_parm);
21508 	  targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
21509 	  targ = listify (targ);
21510 	  TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
21511 	}
21512       return unify_success (explain_p);
21513     }
21514 
21515   /* If parm and arg aren't the same kind of thing (template, type, or
21516      expression), fail early.  */
21517   if (pa_kind (parm) != pa_kind (arg))
21518     return unify_invalid (explain_p);
21519 
21520   /* Immediately reject some pairs that won't unify because of
21521      cv-qualification mismatches.  */
21522   if (TREE_CODE (arg) == TREE_CODE (parm)
21523       && TYPE_P (arg)
21524       /* It is the elements of the array which hold the cv quals of an array
21525 	 type, and the elements might be template type parms. We'll check
21526 	 when we recurse.  */
21527       && TREE_CODE (arg) != ARRAY_TYPE
21528       /* We check the cv-qualifiers when unifying with template type
21529 	 parameters below.  We want to allow ARG `const T' to unify with
21530 	 PARM `T' for example, when computing which of two templates
21531 	 is more specialized, for example.  */
21532       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
21533       && !check_cv_quals_for_unify (strict_in, arg, parm))
21534     return unify_cv_qual_mismatch (explain_p, parm, arg);
21535 
21536   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
21537       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
21538     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
21539   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
21540   strict &= ~UNIFY_ALLOW_DERIVED;
21541   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
21542   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
21543 
21544   switch (TREE_CODE (parm))
21545     {
21546     case TYPENAME_TYPE:
21547     case SCOPE_REF:
21548     case UNBOUND_CLASS_TEMPLATE:
21549       /* In a type which contains a nested-name-specifier, template
21550 	 argument values cannot be deduced for template parameters used
21551 	 within the nested-name-specifier.  */
21552       return unify_success (explain_p);
21553 
21554     case TEMPLATE_TYPE_PARM:
21555     case TEMPLATE_TEMPLATE_PARM:
21556     case BOUND_TEMPLATE_TEMPLATE_PARM:
21557       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
21558       if (error_operand_p (tparm))
21559 	return unify_invalid (explain_p);
21560 
21561       if (TEMPLATE_TYPE_LEVEL (parm)
21562 	  != template_decl_level (tparm))
21563 	/* The PARM is not one we're trying to unify.  Just check
21564 	   to see if it matches ARG.  */
21565 	{
21566 	  if (TREE_CODE (arg) == TREE_CODE (parm)
21567 	      && (is_auto (parm) ? is_auto (arg)
21568 		  : same_type_p (parm, arg)))
21569 	    return unify_success (explain_p);
21570 	  else
21571 	    return unify_type_mismatch (explain_p, parm, arg);
21572 	}
21573       idx = TEMPLATE_TYPE_IDX (parm);
21574       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
21575       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
21576       if (error_operand_p (tparm))
21577 	return unify_invalid (explain_p);
21578 
21579       /* Check for mixed types and values.  */
21580       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
21581 	   && TREE_CODE (tparm) != TYPE_DECL)
21582 	  || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
21583 	      && TREE_CODE (tparm) != TEMPLATE_DECL))
21584 	gcc_unreachable ();
21585 
21586       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
21587 	{
21588 	  if ((strict_in & UNIFY_ALLOW_DERIVED)
21589 	      && CLASS_TYPE_P (arg))
21590 	    {
21591 	      /* First try to match ARG directly.  */
21592 	      tree t = try_class_unification (tparms, targs, parm, arg,
21593 					      explain_p);
21594 	      if (!t)
21595 		{
21596 		  /* Otherwise, look for a suitable base of ARG, as below.  */
21597 		  enum template_base_result r;
21598 		  r = get_template_base (tparms, targs, parm, arg,
21599 					 explain_p, &t);
21600 		  if (!t)
21601 		    return unify_no_common_base (explain_p, r, parm, arg);
21602 		  arg = t;
21603 		}
21604 	    }
21605 	  /* ARG must be constructed from a template class or a template
21606 	     template parameter.  */
21607 	  else if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
21608 		   && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
21609 	    return unify_template_deduction_failure (explain_p, parm, arg);
21610 
21611 	  /* Deduce arguments T, i from TT<T> or TT<i>.  */
21612 	  if (unify_bound_ttp_args (tparms, targs, parm, arg, explain_p))
21613 	    return 1;
21614 
21615 	  arg = TYPE_TI_TEMPLATE (arg);
21616 
21617 	  /* Fall through to deduce template name.  */
21618 	}
21619 
21620       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
21621 	  || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
21622 	{
21623 	  /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
21624 
21625 	  /* Simple cases: Value already set, does match or doesn't.  */
21626 	  if (targ != NULL_TREE && template_args_equal (targ, arg))
21627 	    return unify_success (explain_p);
21628 	  else if (targ)
21629 	    return unify_inconsistency (explain_p, parm, targ, arg);
21630 	}
21631       else
21632 	{
21633 	  /* If PARM is `const T' and ARG is only `int', we don't have
21634 	     a match unless we are allowing additional qualification.
21635 	     If ARG is `const int' and PARM is just `T' that's OK;
21636 	     that binds `const int' to `T'.  */
21637 	  if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
21638 					 arg, parm))
21639 	    return unify_cv_qual_mismatch (explain_p, parm, arg);
21640 
21641 	  /* Consider the case where ARG is `const volatile int' and
21642 	     PARM is `const T'.  Then, T should be `volatile int'.  */
21643 	  arg = cp_build_qualified_type_real
21644 	    (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
21645 	  if (arg == error_mark_node)
21646 	    return unify_invalid (explain_p);
21647 
21648 	  /* Simple cases: Value already set, does match or doesn't.  */
21649 	  if (targ != NULL_TREE && same_type_p (targ, arg))
21650 	    return unify_success (explain_p);
21651 	  else if (targ)
21652 	    return unify_inconsistency (explain_p, parm, targ, arg);
21653 
21654 	  /* Make sure that ARG is not a variable-sized array.  (Note
21655 	     that were talking about variable-sized arrays (like
21656 	     `int[n]'), rather than arrays of unknown size (like
21657 	     `int[]').)  We'll get very confused by such a type since
21658 	     the bound of the array is not constant, and therefore
21659 	     not mangleable.  Besides, such types are not allowed in
21660 	     ISO C++, so we can do as we please here.  We do allow
21661 	     them for 'auto' deduction, since that isn't ABI-exposed.  */
21662 	  if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
21663 	    return unify_vla_arg (explain_p, arg);
21664 
21665 	  /* Strip typedefs as in convert_template_argument.  */
21666 	  arg = canonicalize_type_argument (arg, tf_none);
21667 	}
21668 
21669       /* If ARG is a parameter pack or an expansion, we cannot unify
21670 	 against it unless PARM is also a parameter pack.  */
21671       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
21672 	  && !template_parameter_pack_p (parm))
21673 	return unify_parameter_pack_mismatch (explain_p, parm, arg);
21674 
21675       /* If the argument deduction results is a METHOD_TYPE,
21676          then there is a problem.
21677          METHOD_TYPE doesn't map to any real C++ type the result of
21678 	 the deduction can not be of that type.  */
21679       if (TREE_CODE (arg) == METHOD_TYPE)
21680 	return unify_method_type_error (explain_p, arg);
21681 
21682       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
21683       return unify_success (explain_p);
21684 
21685     case TEMPLATE_PARM_INDEX:
21686       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
21687       if (error_operand_p (tparm))
21688 	return unify_invalid (explain_p);
21689 
21690       if (TEMPLATE_PARM_LEVEL (parm)
21691 	  != template_decl_level (tparm))
21692 	{
21693 	  /* The PARM is not one we're trying to unify.  Just check
21694 	     to see if it matches ARG.  */
21695 	  int result = !(TREE_CODE (arg) == TREE_CODE (parm)
21696 			 && cp_tree_equal (parm, arg));
21697 	  if (result)
21698 	    unify_expression_unequal (explain_p, parm, arg);
21699 	  return result;
21700 	}
21701 
21702       idx = TEMPLATE_PARM_IDX (parm);
21703       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
21704 
21705       if (targ)
21706 	{
21707 	  if ((strict & UNIFY_ALLOW_INTEGER)
21708 	      && TREE_TYPE (targ) && TREE_TYPE (arg)
21709 	      && CP_INTEGRAL_TYPE_P (TREE_TYPE (targ)))
21710 	    /* We're deducing from an array bound, the type doesn't matter.  */
21711 	    arg = fold_convert (TREE_TYPE (targ), arg);
21712 	  int x = !cp_tree_equal (targ, arg);
21713 	  if (x)
21714 	    unify_inconsistency (explain_p, parm, targ, arg);
21715 	  return x;
21716 	}
21717 
21718       /* [temp.deduct.type] If, in the declaration of a function template
21719 	 with a non-type template-parameter, the non-type
21720 	 template-parameter is used in an expression in the function
21721 	 parameter-list and, if the corresponding template-argument is
21722 	 deduced, the template-argument type shall match the type of the
21723 	 template-parameter exactly, except that a template-argument
21724 	 deduced from an array bound may be of any integral type.
21725 	 The non-type parameter might use already deduced type parameters.  */
21726       tparm = TREE_TYPE (parm);
21727       if (TEMPLATE_PARM_LEVEL (parm) > TMPL_ARGS_DEPTH (targs))
21728 	/* We don't have enough levels of args to do any substitution.  This
21729 	   can happen in the context of -fnew-ttp-matching.  */;
21730       else
21731 	{
21732 	  ++processing_template_decl;
21733 	  tparm = tsubst (tparm, targs, tf_none, NULL_TREE);
21734 	  --processing_template_decl;
21735 
21736 	  if (tree a = type_uses_auto (tparm))
21737 	    {
21738 	      tparm = do_auto_deduction (tparm, arg, a, complain, adc_unify);
21739 	      if (tparm == error_mark_node)
21740 		return 1;
21741 	    }
21742 	}
21743 
21744       if (!TREE_TYPE (arg))
21745 	/* Template-parameter dependent expression.  Just accept it for now.
21746 	   It will later be processed in convert_template_argument.  */
21747 	;
21748       else if (same_type_p (non_reference (TREE_TYPE (arg)),
21749 			    non_reference (tparm)))
21750 	/* OK */;
21751       else if ((strict & UNIFY_ALLOW_INTEGER)
21752 	       && CP_INTEGRAL_TYPE_P (tparm))
21753 	/* Convert the ARG to the type of PARM; the deduced non-type
21754 	   template argument must exactly match the types of the
21755 	   corresponding parameter.  */
21756 	arg = fold (build_nop (tparm, arg));
21757       else if (uses_template_parms (tparm))
21758 	{
21759 	  /* We haven't deduced the type of this parameter yet.  */
21760 	  if (cxx_dialect >= cxx17
21761 	      /* We deduce from array bounds in try_array_deduction.  */
21762 	      && !(strict & UNIFY_ALLOW_INTEGER))
21763 	    {
21764 	      /* Deduce it from the non-type argument.  */
21765 	      tree atype = TREE_TYPE (arg);
21766 	      RECUR_AND_CHECK_FAILURE (tparms, targs,
21767 				       tparm, atype,
21768 				       UNIFY_ALLOW_NONE, explain_p);
21769 	    }
21770 	  else
21771 	    /* Try again later.  */
21772 	    return unify_success (explain_p);
21773 	}
21774       else
21775 	return unify_type_mismatch (explain_p, tparm, TREE_TYPE (arg));
21776 
21777       /* If ARG is a parameter pack or an expansion, we cannot unify
21778 	 against it unless PARM is also a parameter pack.  */
21779       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
21780 	  && !TEMPLATE_PARM_PARAMETER_PACK (parm))
21781 	return unify_parameter_pack_mismatch (explain_p, parm, arg);
21782 
21783       {
21784 	bool removed_attr = false;
21785 	arg = strip_typedefs_expr (arg, &removed_attr);
21786       }
21787       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
21788       return unify_success (explain_p);
21789 
21790     case PTRMEM_CST:
21791      {
21792 	/* A pointer-to-member constant can be unified only with
21793 	 another constant.  */
21794       if (TREE_CODE (arg) != PTRMEM_CST)
21795 	return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
21796 
21797       /* Just unify the class member. It would be useless (and possibly
21798 	 wrong, depending on the strict flags) to unify also
21799 	 PTRMEM_CST_CLASS, because we want to be sure that both parm and
21800 	 arg refer to the same variable, even if through different
21801 	 classes. For instance:
21802 
21803 	 struct A { int x; };
21804 	 struct B : A { };
21805 
21806 	 Unification of &A::x and &B::x must succeed.  */
21807       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
21808 		    PTRMEM_CST_MEMBER (arg), strict, explain_p);
21809      }
21810 
21811     case POINTER_TYPE:
21812       {
21813 	if (!TYPE_PTR_P (arg))
21814 	  return unify_type_mismatch (explain_p, parm, arg);
21815 
21816 	/* [temp.deduct.call]
21817 
21818 	   A can be another pointer or pointer to member type that can
21819 	   be converted to the deduced A via a qualification
21820 	   conversion (_conv.qual_).
21821 
21822 	   We pass down STRICT here rather than UNIFY_ALLOW_NONE.
21823 	   This will allow for additional cv-qualification of the
21824 	   pointed-to types if appropriate.  */
21825 
21826 	if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
21827 	  /* The derived-to-base conversion only persists through one
21828 	     level of pointers.  */
21829 	  strict |= (strict_in & UNIFY_ALLOW_DERIVED);
21830 
21831 	return unify (tparms, targs, TREE_TYPE (parm),
21832 		      TREE_TYPE (arg), strict, explain_p);
21833       }
21834 
21835     case REFERENCE_TYPE:
21836       if (TREE_CODE (arg) != REFERENCE_TYPE)
21837 	return unify_type_mismatch (explain_p, parm, arg);
21838       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
21839 		    strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
21840 
21841     case ARRAY_TYPE:
21842       if (TREE_CODE (arg) != ARRAY_TYPE)
21843 	return unify_type_mismatch (explain_p, parm, arg);
21844       if ((TYPE_DOMAIN (parm) == NULL_TREE)
21845 	  != (TYPE_DOMAIN (arg) == NULL_TREE))
21846 	return unify_type_mismatch (explain_p, parm, arg);
21847       RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
21848 			       strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
21849       if (TYPE_DOMAIN (parm) != NULL_TREE)
21850 	return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
21851 				   TYPE_DOMAIN (arg), explain_p);
21852       return unify_success (explain_p);
21853 
21854     case REAL_TYPE:
21855     case COMPLEX_TYPE:
21856     case VECTOR_TYPE:
21857     case INTEGER_TYPE:
21858     case BOOLEAN_TYPE:
21859     case ENUMERAL_TYPE:
21860     case VOID_TYPE:
21861     case NULLPTR_TYPE:
21862       if (TREE_CODE (arg) != TREE_CODE (parm))
21863 	return unify_type_mismatch (explain_p, parm, arg);
21864 
21865       /* We have already checked cv-qualification at the top of the
21866 	 function.  */
21867       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
21868 	return unify_type_mismatch (explain_p, parm, arg);
21869 
21870       /* As far as unification is concerned, this wins.	 Later checks
21871 	 will invalidate it if necessary.  */
21872       return unify_success (explain_p);
21873 
21874       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
21875       /* Type INTEGER_CST can come from ordinary constant template args.  */
21876     case INTEGER_CST:
21877       while (CONVERT_EXPR_P (arg))
21878 	arg = TREE_OPERAND (arg, 0);
21879 
21880       if (TREE_CODE (arg) != INTEGER_CST)
21881 	return unify_template_argument_mismatch (explain_p, parm, arg);
21882       return (tree_int_cst_equal (parm, arg)
21883 	      ? unify_success (explain_p)
21884 	      : unify_template_argument_mismatch (explain_p, parm, arg));
21885 
21886     case TREE_VEC:
21887       {
21888 	int i, len, argslen;
21889 	int parm_variadic_p = 0;
21890 
21891 	if (TREE_CODE (arg) != TREE_VEC)
21892 	  return unify_template_argument_mismatch (explain_p, parm, arg);
21893 
21894 	len = TREE_VEC_LENGTH (parm);
21895 	argslen = TREE_VEC_LENGTH (arg);
21896 
21897 	/* Check for pack expansions in the parameters.  */
21898 	for (i = 0; i < len; ++i)
21899 	  {
21900 	    if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
21901 	      {
21902 		if (i == len - 1)
21903 		  /* We can unify against something with a trailing
21904 		     parameter pack.  */
21905 		  parm_variadic_p = 1;
21906 		else
21907 		  /* [temp.deduct.type]/9: If the template argument list of
21908 		     P contains a pack expansion that is not the last
21909 		     template argument, the entire template argument list
21910 		     is a non-deduced context.  */
21911 		  return unify_success (explain_p);
21912 	      }
21913 	  }
21914 
21915         /* If we don't have enough arguments to satisfy the parameters
21916            (not counting the pack expression at the end), or we have
21917            too many arguments for a parameter list that doesn't end in
21918            a pack expression, we can't unify.  */
21919 	if (parm_variadic_p
21920 	    ? argslen < len - parm_variadic_p
21921 	    : argslen != len)
21922 	  return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
21923 
21924 	/* Unify all of the parameters that precede the (optional)
21925 	   pack expression.  */
21926 	for (i = 0; i < len - parm_variadic_p; ++i)
21927 	  {
21928 	    RECUR_AND_CHECK_FAILURE (tparms, targs,
21929 				     TREE_VEC_ELT (parm, i),
21930 				     TREE_VEC_ELT (arg, i),
21931 				     UNIFY_ALLOW_NONE, explain_p);
21932 	  }
21933 	if (parm_variadic_p)
21934 	  return unify_pack_expansion (tparms, targs, parm, arg,
21935 				       DEDUCE_EXACT,
21936 				       /*subr=*/true, explain_p);
21937 	return unify_success (explain_p);
21938       }
21939 
21940     case RECORD_TYPE:
21941     case UNION_TYPE:
21942       if (TREE_CODE (arg) != TREE_CODE (parm))
21943 	return unify_type_mismatch (explain_p, parm, arg);
21944 
21945       if (TYPE_PTRMEMFUNC_P (parm))
21946 	{
21947 	  if (!TYPE_PTRMEMFUNC_P (arg))
21948 	    return unify_type_mismatch (explain_p, parm, arg);
21949 
21950 	  return unify (tparms, targs,
21951 			TYPE_PTRMEMFUNC_FN_TYPE (parm),
21952 			TYPE_PTRMEMFUNC_FN_TYPE (arg),
21953 			strict, explain_p);
21954 	}
21955       else if (TYPE_PTRMEMFUNC_P (arg))
21956 	return unify_type_mismatch (explain_p, parm, arg);
21957 
21958       if (CLASSTYPE_TEMPLATE_INFO (parm))
21959 	{
21960 	  tree t = NULL_TREE;
21961 
21962 	  if (strict_in & UNIFY_ALLOW_DERIVED)
21963 	    {
21964 	      /* First, we try to unify the PARM and ARG directly.  */
21965 	      t = try_class_unification (tparms, targs,
21966 					 parm, arg, explain_p);
21967 
21968 	      if (!t)
21969 		{
21970 		  /* Fallback to the special case allowed in
21971 		     [temp.deduct.call]:
21972 
21973 		       If P is a class, and P has the form
21974 		       template-id, then A can be a derived class of
21975 		       the deduced A.  Likewise, if P is a pointer to
21976 		       a class of the form template-id, A can be a
21977 		       pointer to a derived class pointed to by the
21978 		       deduced A.  */
21979 		  enum template_base_result r;
21980 		  r = get_template_base (tparms, targs, parm, arg,
21981 					 explain_p, &t);
21982 
21983 		  if (!t)
21984 		    {
21985 		      /* Don't give the derived diagnostic if we're
21986 			 already dealing with the same template.  */
21987 		      bool same_template
21988 			= (CLASSTYPE_TEMPLATE_INFO (arg)
21989 			   && (CLASSTYPE_TI_TEMPLATE (parm)
21990 			       == CLASSTYPE_TI_TEMPLATE (arg)));
21991 		      return unify_no_common_base (explain_p && !same_template,
21992 						   r, parm, arg);
21993 		    }
21994 		}
21995 	    }
21996 	  else if (CLASSTYPE_TEMPLATE_INFO (arg)
21997 		   && (CLASSTYPE_TI_TEMPLATE (parm)
21998 		       == CLASSTYPE_TI_TEMPLATE (arg)))
21999 	    /* Perhaps PARM is something like S<U> and ARG is S<int>.
22000 	       Then, we should unify `int' and `U'.  */
22001 	    t = arg;
22002 	  else
22003 	    /* There's no chance of unification succeeding.  */
22004 	    return unify_type_mismatch (explain_p, parm, arg);
22005 
22006 	  return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
22007 			CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE, explain_p);
22008 	}
22009       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
22010 	return unify_type_mismatch (explain_p, parm, arg);
22011       return unify_success (explain_p);
22012 
22013     case METHOD_TYPE:
22014     case FUNCTION_TYPE:
22015       {
22016 	unsigned int nargs;
22017 	tree *args;
22018 	tree a;
22019 	unsigned int i;
22020 
22021 	if (TREE_CODE (arg) != TREE_CODE (parm))
22022 	  return unify_type_mismatch (explain_p, parm, arg);
22023 
22024 	/* CV qualifications for methods can never be deduced, they must
22025 	   match exactly.  We need to check them explicitly here,
22026 	   because type_unification_real treats them as any other
22027 	   cv-qualified parameter.  */
22028 	if (TREE_CODE (parm) == METHOD_TYPE
22029 	    && (!check_cv_quals_for_unify
22030 		(UNIFY_ALLOW_NONE,
22031 		 class_of_this_parm (arg),
22032 		 class_of_this_parm (parm))))
22033 	  return unify_cv_qual_mismatch (explain_p, parm, arg);
22034 	if (TREE_CODE (arg) == FUNCTION_TYPE
22035 	    && type_memfn_quals (parm) != type_memfn_quals (arg))
22036 	  return unify_cv_qual_mismatch (explain_p, parm, arg);
22037 	if (type_memfn_rqual (parm) != type_memfn_rqual (arg))
22038 	  return unify_type_mismatch (explain_p, parm, arg);
22039 
22040 	RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
22041 				 TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
22042 
22043 	nargs = list_length (TYPE_ARG_TYPES (arg));
22044 	args = XALLOCAVEC (tree, nargs);
22045 	for (a = TYPE_ARG_TYPES (arg), i = 0;
22046 	     a != NULL_TREE && a != void_list_node;
22047 	     a = TREE_CHAIN (a), ++i)
22048 	  args[i] = TREE_VALUE (a);
22049 	nargs = i;
22050 
22051 	if (type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
22052 				   args, nargs, 1, DEDUCE_EXACT,
22053 				   LOOKUP_NORMAL, NULL, explain_p))
22054 	  return 1;
22055 
22056 	if (flag_noexcept_type)
22057 	  {
22058 	    tree pspec = TYPE_RAISES_EXCEPTIONS (parm);
22059 	    tree aspec = canonical_eh_spec (TYPE_RAISES_EXCEPTIONS (arg));
22060 	    if (pspec == NULL_TREE) pspec = noexcept_false_spec;
22061 	    if (aspec == NULL_TREE) aspec = noexcept_false_spec;
22062 	    if (TREE_PURPOSE (pspec) && TREE_PURPOSE (aspec)
22063 		&& uses_template_parms (TREE_PURPOSE (pspec)))
22064 	      RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_PURPOSE (pspec),
22065 				       TREE_PURPOSE (aspec),
22066 				       UNIFY_ALLOW_NONE, explain_p);
22067 	    else if (nothrow_spec_p (pspec) && !nothrow_spec_p (aspec))
22068 	      return unify_type_mismatch (explain_p, parm, arg);
22069 	  }
22070 
22071 	return 0;
22072       }
22073 
22074     case OFFSET_TYPE:
22075       /* Unify a pointer to member with a pointer to member function, which
22076 	 deduces the type of the member as a function type. */
22077       if (TYPE_PTRMEMFUNC_P (arg))
22078 	{
22079 	  /* Check top-level cv qualifiers */
22080 	  if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
22081 	    return unify_cv_qual_mismatch (explain_p, parm, arg);
22082 
22083 	  RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
22084 				   TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
22085 				   UNIFY_ALLOW_NONE, explain_p);
22086 
22087 	  /* Determine the type of the function we are unifying against. */
22088 	  tree fntype = static_fn_type (arg);
22089 
22090 	  return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
22091 	}
22092 
22093       if (TREE_CODE (arg) != OFFSET_TYPE)
22094 	return unify_type_mismatch (explain_p, parm, arg);
22095       RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
22096 			       TYPE_OFFSET_BASETYPE (arg),
22097 			       UNIFY_ALLOW_NONE, explain_p);
22098       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
22099 		    strict, explain_p);
22100 
22101     case CONST_DECL:
22102       if (DECL_TEMPLATE_PARM_P (parm))
22103 	return unify (tparms, targs, DECL_INITIAL (parm), arg, strict, explain_p);
22104       if (arg != scalar_constant_value (parm))
22105 	return unify_template_argument_mismatch (explain_p, parm, arg);
22106       return unify_success (explain_p);
22107 
22108     case FIELD_DECL:
22109     case TEMPLATE_DECL:
22110       /* Matched cases are handled by the ARG == PARM test above.  */
22111       return unify_template_argument_mismatch (explain_p, parm, arg);
22112 
22113     case VAR_DECL:
22114       /* We might get a variable as a non-type template argument in parm if the
22115 	 corresponding parameter is type-dependent.  Make any necessary
22116 	 adjustments based on whether arg is a reference.  */
22117       if (CONSTANT_CLASS_P (arg))
22118 	parm = fold_non_dependent_expr (parm);
22119       else if (REFERENCE_REF_P (arg))
22120 	{
22121 	  tree sub = TREE_OPERAND (arg, 0);
22122 	  STRIP_NOPS (sub);
22123 	  if (TREE_CODE (sub) == ADDR_EXPR)
22124 	    arg = TREE_OPERAND (sub, 0);
22125 	}
22126       /* Now use the normal expression code to check whether they match.  */
22127       goto expr;
22128 
22129     case TYPE_ARGUMENT_PACK:
22130     case NONTYPE_ARGUMENT_PACK:
22131       return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
22132 		    ARGUMENT_PACK_ARGS (arg), strict, explain_p);
22133 
22134     case TYPEOF_TYPE:
22135     case DECLTYPE_TYPE:
22136     case UNDERLYING_TYPE:
22137       /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
22138 	 or UNDERLYING_TYPE nodes.  */
22139       return unify_success (explain_p);
22140 
22141     case ERROR_MARK:
22142       /* Unification fails if we hit an error node.  */
22143       return unify_invalid (explain_p);
22144 
22145     case INDIRECT_REF:
22146       if (REFERENCE_REF_P (parm))
22147 	{
22148 	  bool pexp = PACK_EXPANSION_P (arg);
22149 	  if (pexp)
22150 	    arg = PACK_EXPANSION_PATTERN (arg);
22151 	  if (REFERENCE_REF_P (arg))
22152 	    arg = TREE_OPERAND (arg, 0);
22153 	  if (pexp)
22154 	    arg = make_pack_expansion (arg, complain);
22155 	  return unify (tparms, targs, TREE_OPERAND (parm, 0), arg,
22156 			strict, explain_p);
22157 	}
22158       /* FALLTHRU */
22159 
22160     default:
22161       /* An unresolved overload is a nondeduced context.  */
22162       if (is_overloaded_fn (parm) || type_unknown_p (parm))
22163 	return unify_success (explain_p);
22164       gcc_assert (EXPR_P (parm) || TREE_CODE (parm) == TRAIT_EXPR);
22165     expr:
22166       /* We must be looking at an expression.  This can happen with
22167 	 something like:
22168 
22169 	   template <int I>
22170 	   void foo(S<I>, S<I + 2>);
22171 
22172 	 This is a "nondeduced context":
22173 
22174 	   [deduct.type]
22175 
22176 	   The nondeduced contexts are:
22177 
22178 	   --A type that is a template-id in which one or more of
22179 	     the template-arguments is an expression that references
22180 	     a template-parameter.
22181 
22182 	 In these cases, we assume deduction succeeded, but don't
22183 	 actually infer any unifications.  */
22184 
22185       if (!uses_template_parms (parm)
22186 	  && !template_args_equal (parm, arg))
22187 	return unify_expression_unequal (explain_p, parm, arg);
22188       else
22189 	return unify_success (explain_p);
22190     }
22191 }
22192 #undef RECUR_AND_CHECK_FAILURE
22193 
22194 /* Note that DECL can be defined in this translation unit, if
22195    required.  */
22196 
22197 static void
mark_definable(tree decl)22198 mark_definable (tree decl)
22199 {
22200   tree clone;
22201   DECL_NOT_REALLY_EXTERN (decl) = 1;
22202   FOR_EACH_CLONE (clone, decl)
22203     DECL_NOT_REALLY_EXTERN (clone) = 1;
22204 }
22205 
22206 /* Called if RESULT is explicitly instantiated, or is a member of an
22207    explicitly instantiated class.  */
22208 
22209 void
mark_decl_instantiated(tree result,int extern_p)22210 mark_decl_instantiated (tree result, int extern_p)
22211 {
22212   SET_DECL_EXPLICIT_INSTANTIATION (result);
22213 
22214   /* If this entity has already been written out, it's too late to
22215      make any modifications.  */
22216   if (TREE_ASM_WRITTEN (result))
22217     return;
22218 
22219   /* For anonymous namespace we don't need to do anything.  */
22220   if (decl_anon_ns_mem_p (result))
22221     {
22222       gcc_assert (!TREE_PUBLIC (result));
22223       return;
22224     }
22225 
22226   if (TREE_CODE (result) != FUNCTION_DECL)
22227     /* The TREE_PUBLIC flag for function declarations will have been
22228        set correctly by tsubst.  */
22229     TREE_PUBLIC (result) = 1;
22230 
22231   /* This might have been set by an earlier implicit instantiation.  */
22232   DECL_COMDAT (result) = 0;
22233 
22234   if (extern_p)
22235     DECL_NOT_REALLY_EXTERN (result) = 0;
22236   else
22237     {
22238       mark_definable (result);
22239       mark_needed (result);
22240       /* Always make artificials weak.  */
22241       if (DECL_ARTIFICIAL (result) && flag_weak)
22242 	comdat_linkage (result);
22243       /* For WIN32 we also want to put explicit instantiations in
22244 	 linkonce sections.  */
22245       else if (TREE_PUBLIC (result))
22246 	maybe_make_one_only (result);
22247     }
22248 
22249   /* If EXTERN_P, then this function will not be emitted -- unless
22250      followed by an explicit instantiation, at which point its linkage
22251      will be adjusted.  If !EXTERN_P, then this function will be
22252      emitted here.  In neither circumstance do we want
22253      import_export_decl to adjust the linkage.  */
22254   DECL_INTERFACE_KNOWN (result) = 1;
22255 }
22256 
22257 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
22258    important template arguments.  If any are missing, we check whether
22259    they're important by using error_mark_node for substituting into any
22260    args that were used for partial ordering (the ones between ARGS and END)
22261    and seeing if it bubbles up.  */
22262 
22263 static bool
check_undeduced_parms(tree targs,tree args,tree end)22264 check_undeduced_parms (tree targs, tree args, tree end)
22265 {
22266   bool found = false;
22267   int i;
22268   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
22269     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
22270       {
22271 	found = true;
22272 	TREE_VEC_ELT (targs, i) = error_mark_node;
22273       }
22274   if (found)
22275     {
22276       tree substed = tsubst_arg_types (args, targs, end, tf_none, NULL_TREE);
22277       if (substed == error_mark_node)
22278 	return true;
22279     }
22280   return false;
22281 }
22282 
22283 /* Given two function templates PAT1 and PAT2, return:
22284 
22285    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
22286    -1 if PAT2 is more specialized than PAT1.
22287    0 if neither is more specialized.
22288 
22289    LEN indicates the number of parameters we should consider
22290    (defaulted parameters should not be considered).
22291 
22292    The 1998 std underspecified function template partial ordering, and
22293    DR214 addresses the issue.  We take pairs of arguments, one from
22294    each of the templates, and deduce them against each other.  One of
22295    the templates will be more specialized if all the *other*
22296    template's arguments deduce against its arguments and at least one
22297    of its arguments *does* *not* deduce against the other template's
22298    corresponding argument.  Deduction is done as for class templates.
22299    The arguments used in deduction have reference and top level cv
22300    qualifiers removed.  Iff both arguments were originally reference
22301    types *and* deduction succeeds in both directions, an lvalue reference
22302    wins against an rvalue reference and otherwise the template
22303    with the more cv-qualified argument wins for that pairing (if
22304    neither is more cv-qualified, they both are equal).  Unlike regular
22305    deduction, after all the arguments have been deduced in this way,
22306    we do *not* verify the deduced template argument values can be
22307    substituted into non-deduced contexts.
22308 
22309    The logic can be a bit confusing here, because we look at deduce1 and
22310    targs1 to see if pat2 is at least as specialized, and vice versa; if we
22311    can find template arguments for pat1 to make arg1 look like arg2, that
22312    means that arg2 is at least as specialized as arg1.  */
22313 
22314 int
more_specialized_fn(tree pat1,tree pat2,int len)22315 more_specialized_fn (tree pat1, tree pat2, int len)
22316 {
22317   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
22318   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
22319   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
22320   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
22321   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
22322   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
22323   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
22324   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
22325   tree origs1, origs2;
22326   bool lose1 = false;
22327   bool lose2 = false;
22328 
22329   /* Remove the this parameter from non-static member functions.  If
22330      one is a non-static member function and the other is not a static
22331      member function, remove the first parameter from that function
22332      also.  This situation occurs for operator functions where we
22333      locate both a member function (with this pointer) and non-member
22334      operator (with explicit first operand).  */
22335   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
22336     {
22337       len--; /* LEN is the number of significant arguments for DECL1 */
22338       args1 = TREE_CHAIN (args1);
22339       if (!DECL_STATIC_FUNCTION_P (decl2))
22340 	args2 = TREE_CHAIN (args2);
22341     }
22342   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
22343     {
22344       args2 = TREE_CHAIN (args2);
22345       if (!DECL_STATIC_FUNCTION_P (decl1))
22346 	{
22347 	  len--;
22348 	  args1 = TREE_CHAIN (args1);
22349 	}
22350     }
22351 
22352   /* If only one is a conversion operator, they are unordered.  */
22353   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
22354     return 0;
22355 
22356   /* Consider the return type for a conversion function */
22357   if (DECL_CONV_FN_P (decl1))
22358     {
22359       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
22360       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
22361       len++;
22362     }
22363 
22364   processing_template_decl++;
22365 
22366   origs1 = args1;
22367   origs2 = args2;
22368 
22369   while (len--
22370 	 /* Stop when an ellipsis is seen.  */
22371 	 && args1 != NULL_TREE && args2 != NULL_TREE)
22372     {
22373       tree arg1 = TREE_VALUE (args1);
22374       tree arg2 = TREE_VALUE (args2);
22375       int deduce1, deduce2;
22376       int quals1 = -1;
22377       int quals2 = -1;
22378       int ref1 = 0;
22379       int ref2 = 0;
22380 
22381       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
22382           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
22383         {
22384           /* When both arguments are pack expansions, we need only
22385              unify the patterns themselves.  */
22386           arg1 = PACK_EXPANSION_PATTERN (arg1);
22387           arg2 = PACK_EXPANSION_PATTERN (arg2);
22388 
22389           /* This is the last comparison we need to do.  */
22390           len = 0;
22391         }
22392 
22393       /* DR 1847: If a particular P contains no template-parameters that
22394 	 participate in template argument deduction, that P is not used to
22395 	 determine the ordering.  */
22396       if (!uses_deducible_template_parms (arg1)
22397 	  && !uses_deducible_template_parms (arg2))
22398 	goto next;
22399 
22400       if (TREE_CODE (arg1) == REFERENCE_TYPE)
22401 	{
22402 	  ref1 = TYPE_REF_IS_RVALUE (arg1) + 1;
22403 	  arg1 = TREE_TYPE (arg1);
22404 	  quals1 = cp_type_quals (arg1);
22405 	}
22406 
22407       if (TREE_CODE (arg2) == REFERENCE_TYPE)
22408 	{
22409 	  ref2 = TYPE_REF_IS_RVALUE (arg2) + 1;
22410 	  arg2 = TREE_TYPE (arg2);
22411 	  quals2 = cp_type_quals (arg2);
22412 	}
22413 
22414       arg1 = TYPE_MAIN_VARIANT (arg1);
22415       arg2 = TYPE_MAIN_VARIANT (arg2);
22416 
22417       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
22418         {
22419           int i, len2 = remaining_arguments (args2);
22420           tree parmvec = make_tree_vec (1);
22421           tree argvec = make_tree_vec (len2);
22422           tree ta = args2;
22423 
22424           /* Setup the parameter vector, which contains only ARG1.  */
22425           TREE_VEC_ELT (parmvec, 0) = arg1;
22426 
22427           /* Setup the argument vector, which contains the remaining
22428              arguments.  */
22429           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
22430             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
22431 
22432           deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
22433 					   argvec, DEDUCE_EXACT,
22434 					   /*subr=*/true, /*explain_p=*/false)
22435 		     == 0);
22436 
22437           /* We cannot deduce in the other direction, because ARG1 is
22438              a pack expansion but ARG2 is not.  */
22439           deduce2 = 0;
22440         }
22441       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
22442         {
22443           int i, len1 = remaining_arguments (args1);
22444           tree parmvec = make_tree_vec (1);
22445           tree argvec = make_tree_vec (len1);
22446           tree ta = args1;
22447 
22448           /* Setup the parameter vector, which contains only ARG1.  */
22449           TREE_VEC_ELT (parmvec, 0) = arg2;
22450 
22451           /* Setup the argument vector, which contains the remaining
22452              arguments.  */
22453           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
22454             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
22455 
22456           deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
22457 					   argvec, DEDUCE_EXACT,
22458 					   /*subr=*/true, /*explain_p=*/false)
22459 		     == 0);
22460 
22461           /* We cannot deduce in the other direction, because ARG2 is
22462              a pack expansion but ARG1 is not.*/
22463           deduce1 = 0;
22464         }
22465 
22466       else
22467         {
22468           /* The normal case, where neither argument is a pack
22469              expansion.  */
22470           deduce1 = (unify (tparms1, targs1, arg1, arg2,
22471 			    UNIFY_ALLOW_NONE, /*explain_p=*/false)
22472 		     == 0);
22473           deduce2 = (unify (tparms2, targs2, arg2, arg1,
22474 			    UNIFY_ALLOW_NONE, /*explain_p=*/false)
22475 		     == 0);
22476         }
22477 
22478       /* If we couldn't deduce arguments for tparms1 to make arg1 match
22479 	 arg2, then arg2 is not as specialized as arg1.  */
22480       if (!deduce1)
22481 	lose2 = true;
22482       if (!deduce2)
22483 	lose1 = true;
22484 
22485       /* "If, for a given type, deduction succeeds in both directions
22486 	 (i.e., the types are identical after the transformations above)
22487 	 and both P and A were reference types (before being replaced with
22488 	 the type referred to above):
22489 	 - if the type from the argument template was an lvalue reference and
22490 	 the type from the parameter template was not, the argument type is
22491 	 considered to be more specialized than the other; otherwise,
22492 	 - if the type from the argument template is more cv-qualified
22493 	 than the type from the parameter template (as described above),
22494 	 the argument type is considered to be more specialized than the other;
22495 	 otherwise,
22496 	 - neither type is more specialized than the other."  */
22497 
22498       if (deduce1 && deduce2)
22499 	{
22500 	  if (ref1 && ref2 && ref1 != ref2)
22501 	    {
22502 	      if (ref1 > ref2)
22503 		lose1 = true;
22504 	      else
22505 		lose2 = true;
22506 	    }
22507 	  else if (quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
22508 	    {
22509 	      if ((quals1 & quals2) == quals2)
22510 		lose2 = true;
22511 	      if ((quals1 & quals2) == quals1)
22512 		lose1 = true;
22513 	    }
22514 	}
22515 
22516       if (lose1 && lose2)
22517 	/* We've failed to deduce something in either direction.
22518 	   These must be unordered.  */
22519 	break;
22520 
22521     next:
22522 
22523       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
22524           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
22525         /* We have already processed all of the arguments in our
22526            handing of the pack expansion type.  */
22527         len = 0;
22528 
22529       args1 = TREE_CHAIN (args1);
22530       args2 = TREE_CHAIN (args2);
22531     }
22532 
22533   /* "In most cases, all template parameters must have values in order for
22534      deduction to succeed, but for partial ordering purposes a template
22535      parameter may remain without a value provided it is not used in the
22536      types being used for partial ordering."
22537 
22538      Thus, if we are missing any of the targs1 we need to substitute into
22539      origs1, then pat2 is not as specialized as pat1.  This can happen when
22540      there is a nondeduced context.  */
22541   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
22542     lose2 = true;
22543   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
22544     lose1 = true;
22545 
22546   processing_template_decl--;
22547 
22548   /* If both deductions succeed, the partial ordering selects the more
22549      constrained template.  */
22550   if (!lose1 && !lose2)
22551     {
22552       tree c1 = get_constraints (DECL_TEMPLATE_RESULT (pat1));
22553       tree c2 = get_constraints (DECL_TEMPLATE_RESULT (pat2));
22554       lose1 = !subsumes_constraints (c1, c2);
22555       lose2 = !subsumes_constraints (c2, c1);
22556     }
22557 
22558   /* All things being equal, if the next argument is a pack expansion
22559      for one function but not for the other, prefer the
22560      non-variadic function.  FIXME this is bogus; see c++/41958.  */
22561   if (lose1 == lose2
22562       && args1 && TREE_VALUE (args1)
22563       && args2 && TREE_VALUE (args2))
22564     {
22565       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
22566       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
22567     }
22568 
22569   if (lose1 == lose2)
22570     return 0;
22571   else if (!lose1)
22572     return 1;
22573   else
22574     return -1;
22575 }
22576 
22577 /* Determine which of two partial specializations of TMPL is more
22578    specialized.
22579 
22580    PAT1 is a TREE_LIST whose TREE_VALUE is the TEMPLATE_DECL corresponding
22581    to the first partial specialization.  The TREE_PURPOSE is the
22582    innermost set of template parameters for the partial
22583    specialization.  PAT2 is similar, but for the second template.
22584 
22585    Return 1 if the first partial specialization is more specialized;
22586    -1 if the second is more specialized; 0 if neither is more
22587    specialized.
22588 
22589    See [temp.class.order] for information about determining which of
22590    two templates is more specialized.  */
22591 
22592 static int
more_specialized_partial_spec(tree tmpl,tree pat1,tree pat2)22593 more_specialized_partial_spec (tree tmpl, tree pat1, tree pat2)
22594 {
22595   tree targs;
22596   int winner = 0;
22597   bool any_deductions = false;
22598 
22599   tree tmpl1 = TREE_VALUE (pat1);
22600   tree tmpl2 = TREE_VALUE (pat2);
22601   tree specargs1 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl1)));
22602   tree specargs2 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl2)));
22603 
22604   /* Just like what happens for functions, if we are ordering between
22605      different template specializations, we may encounter dependent
22606      types in the arguments, and we need our dependency check functions
22607      to behave correctly.  */
22608   ++processing_template_decl;
22609   targs = get_partial_spec_bindings (tmpl, tmpl1, specargs2);
22610   if (targs)
22611     {
22612       --winner;
22613       any_deductions = true;
22614     }
22615 
22616   targs = get_partial_spec_bindings (tmpl, tmpl2, specargs1);
22617   if (targs)
22618     {
22619       ++winner;
22620       any_deductions = true;
22621     }
22622   --processing_template_decl;
22623 
22624   /* If both deductions succeed, the partial ordering selects the more
22625      constrained template.  */
22626   if (!winner && any_deductions)
22627     return more_constrained (tmpl1, tmpl2);
22628 
22629   /* In the case of a tie where at least one of the templates
22630      has a parameter pack at the end, the template with the most
22631      non-packed parameters wins.  */
22632   if (winner == 0
22633       && any_deductions
22634       && (template_args_variadic_p (TREE_PURPOSE (pat1))
22635           || template_args_variadic_p (TREE_PURPOSE (pat2))))
22636     {
22637       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
22638       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
22639       int len1 = TREE_VEC_LENGTH (args1);
22640       int len2 = TREE_VEC_LENGTH (args2);
22641 
22642       /* We don't count the pack expansion at the end.  */
22643       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
22644         --len1;
22645       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
22646         --len2;
22647 
22648       if (len1 > len2)
22649         return 1;
22650       else if (len1 < len2)
22651         return -1;
22652     }
22653 
22654   return winner;
22655 }
22656 
22657 /* Return the template arguments that will produce the function signature
22658    DECL from the function template FN, with the explicit template
22659    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
22660    also match.  Return NULL_TREE if no satisfactory arguments could be
22661    found.  */
22662 
22663 static tree
get_bindings(tree fn,tree decl,tree explicit_args,bool check_rettype)22664 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
22665 {
22666   int ntparms = DECL_NTPARMS (fn);
22667   tree targs = make_tree_vec (ntparms);
22668   tree decl_type = TREE_TYPE (decl);
22669   tree decl_arg_types;
22670   tree *args;
22671   unsigned int nargs, ix;
22672   tree arg;
22673 
22674   gcc_assert (decl != DECL_TEMPLATE_RESULT (fn));
22675 
22676   /* Never do unification on the 'this' parameter.  */
22677   decl_arg_types = skip_artificial_parms_for (decl,
22678 					      TYPE_ARG_TYPES (decl_type));
22679 
22680   nargs = list_length (decl_arg_types);
22681   args = XALLOCAVEC (tree, nargs);
22682   for (arg = decl_arg_types, ix = 0;
22683        arg != NULL_TREE && arg != void_list_node;
22684        arg = TREE_CHAIN (arg), ++ix)
22685     args[ix] = TREE_VALUE (arg);
22686 
22687   if (fn_type_unification (fn, explicit_args, targs,
22688 			   args, ix,
22689 			   (check_rettype || DECL_CONV_FN_P (fn)
22690 			    ? TREE_TYPE (decl_type) : NULL_TREE),
22691 			   DEDUCE_EXACT, LOOKUP_NORMAL, /*explain_p=*/false,
22692 			   /*decltype*/false)
22693       == error_mark_node)
22694     return NULL_TREE;
22695 
22696   return targs;
22697 }
22698 
22699 /* Return the innermost template arguments that, when applied to a partial
22700    specialization SPEC_TMPL of TMPL, yield the ARGS.
22701 
22702    For example, suppose we have:
22703 
22704      template <class T, class U> struct S {};
22705      template <class T> struct S<T*, int> {};
22706 
22707    Then, suppose we want to get `S<double*, int>'.  SPEC_TMPL will be the
22708    partial specialization and the ARGS will be {double*, int}.  The resulting
22709    vector will be {double}, indicating that `T' is bound to `double'.  */
22710 
22711 static tree
get_partial_spec_bindings(tree tmpl,tree spec_tmpl,tree args)22712 get_partial_spec_bindings (tree tmpl, tree spec_tmpl, tree args)
22713 {
22714   tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (spec_tmpl);
22715   tree spec_args
22716     = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (spec_tmpl)));
22717   int i, ntparms = TREE_VEC_LENGTH (tparms);
22718   tree deduced_args;
22719   tree innermost_deduced_args;
22720 
22721   innermost_deduced_args = make_tree_vec (ntparms);
22722   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
22723     {
22724       deduced_args = copy_node (args);
22725       SET_TMPL_ARGS_LEVEL (deduced_args,
22726 			   TMPL_ARGS_DEPTH (deduced_args),
22727 			   innermost_deduced_args);
22728     }
22729   else
22730     deduced_args = innermost_deduced_args;
22731 
22732   bool tried_array_deduction = (cxx_dialect < cxx17);
22733  again:
22734   if (unify (tparms, deduced_args,
22735 	     INNERMOST_TEMPLATE_ARGS (spec_args),
22736 	     INNERMOST_TEMPLATE_ARGS (args),
22737 	     UNIFY_ALLOW_NONE, /*explain_p=*/false))
22738     return NULL_TREE;
22739 
22740   for (i =  0; i < ntparms; ++i)
22741     if (! TREE_VEC_ELT (innermost_deduced_args, i))
22742       {
22743 	if (!tried_array_deduction)
22744 	  {
22745 	    try_array_deduction (tparms, innermost_deduced_args,
22746 				 INNERMOST_TEMPLATE_ARGS (spec_args));
22747 	    tried_array_deduction = true;
22748 	    if (TREE_VEC_ELT (innermost_deduced_args, i))
22749 	      goto again;
22750 	  }
22751 	return NULL_TREE;
22752       }
22753 
22754   if (!push_tinst_level (spec_tmpl, deduced_args))
22755     {
22756       excessive_deduction_depth = true;
22757       return NULL_TREE;
22758     }
22759 
22760   /* Verify that nondeduced template arguments agree with the type
22761      obtained from argument deduction.
22762 
22763      For example:
22764 
22765        struct A { typedef int X; };
22766        template <class T, class U> struct C {};
22767        template <class T> struct C<T, typename T::X> {};
22768 
22769      Then with the instantiation `C<A, int>', we can deduce that
22770      `T' is `A' but unify () does not check whether `typename T::X'
22771      is `int'.  */
22772   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
22773 
22774   if (spec_args != error_mark_node)
22775     spec_args = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
22776 				       INNERMOST_TEMPLATE_ARGS (spec_args),
22777 				       tmpl, tf_none, false, false);
22778 
22779   pop_tinst_level ();
22780 
22781   if (spec_args == error_mark_node
22782       /* We only need to check the innermost arguments; the other
22783 	 arguments will always agree.  */
22784       || !comp_template_args_porder (INNERMOST_TEMPLATE_ARGS (spec_args),
22785 				     INNERMOST_TEMPLATE_ARGS (args)))
22786     return NULL_TREE;
22787 
22788   /* Now that we have bindings for all of the template arguments,
22789      ensure that the arguments deduced for the template template
22790      parameters have compatible template parameter lists.  See the use
22791      of template_template_parm_bindings_ok_p in fn_type_unification
22792      for more information.  */
22793   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
22794     return NULL_TREE;
22795 
22796   return deduced_args;
22797 }
22798 
22799 // Compare two function templates T1 and T2 by deducing bindings
22800 // from one against the other. If both deductions succeed, compare
22801 // constraints to see which is more constrained.
22802 static int
more_specialized_inst(tree t1,tree t2)22803 more_specialized_inst (tree t1, tree t2)
22804 {
22805   int fate = 0;
22806   int count = 0;
22807 
22808   if (get_bindings (t1, DECL_TEMPLATE_RESULT (t2), NULL_TREE, true))
22809     {
22810       --fate;
22811       ++count;
22812     }
22813 
22814   if (get_bindings (t2, DECL_TEMPLATE_RESULT (t1), NULL_TREE, true))
22815     {
22816       ++fate;
22817       ++count;
22818     }
22819 
22820   // If both deductions succeed, then one may be more constrained.
22821   if (count == 2 && fate == 0)
22822     fate = more_constrained (t1, t2);
22823 
22824   return fate;
22825 }
22826 
22827 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
22828    Return the TREE_LIST node with the most specialized template, if
22829    any.  If there is no most specialized template, the error_mark_node
22830    is returned.
22831 
22832    Note that this function does not look at, or modify, the
22833    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
22834    returned is one of the elements of INSTANTIATIONS, callers may
22835    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
22836    and retrieve it from the value returned.  */
22837 
22838 tree
most_specialized_instantiation(tree templates)22839 most_specialized_instantiation (tree templates)
22840 {
22841   tree fn, champ;
22842 
22843   ++processing_template_decl;
22844 
22845   champ = templates;
22846   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
22847     {
22848       gcc_assert (TREE_VALUE (champ) != TREE_VALUE (fn));
22849       int fate = more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn));
22850       if (fate == -1)
22851 	champ = fn;
22852       else if (!fate)
22853 	{
22854 	  /* Equally specialized, move to next function.  If there
22855 	     is no next function, nothing's most specialized.  */
22856 	  fn = TREE_CHAIN (fn);
22857 	  champ = fn;
22858 	  if (!fn)
22859 	    break;
22860 	}
22861     }
22862 
22863   if (champ)
22864     /* Now verify that champ is better than everything earlier in the
22865        instantiation list.  */
22866     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn)) {
22867       if (more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn)) != 1)
22868       {
22869         champ = NULL_TREE;
22870         break;
22871       }
22872     }
22873 
22874   processing_template_decl--;
22875 
22876   if (!champ)
22877     return error_mark_node;
22878 
22879   return champ;
22880 }
22881 
22882 /* If DECL is a specialization of some template, return the most
22883    general such template.  Otherwise, returns NULL_TREE.
22884 
22885    For example, given:
22886 
22887      template <class T> struct S { template <class U> void f(U); };
22888 
22889    if TMPL is `template <class U> void S<int>::f(U)' this will return
22890    the full template.  This function will not trace past partial
22891    specializations, however.  For example, given in addition:
22892 
22893      template <class T> struct S<T*> { template <class U> void f(U); };
22894 
22895    if TMPL is `template <class U> void S<int*>::f(U)' this will return
22896    `template <class T> template <class U> S<T*>::f(U)'.  */
22897 
22898 tree
most_general_template(tree decl)22899 most_general_template (tree decl)
22900 {
22901   if (TREE_CODE (decl) != TEMPLATE_DECL)
22902     {
22903       if (tree tinfo = get_template_info (decl))
22904 	decl = TI_TEMPLATE (tinfo);
22905       /* The TI_TEMPLATE can be an IDENTIFIER_NODE for a
22906 	 template friend, or a FIELD_DECL for a capture pack.  */
22907       if (TREE_CODE (decl) != TEMPLATE_DECL)
22908 	return NULL_TREE;
22909     }
22910 
22911   /* Look for more and more general templates.  */
22912   while (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
22913     {
22914       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
22915 	 (See cp-tree.h for details.)  */
22916       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
22917 	break;
22918 
22919       if (CLASS_TYPE_P (TREE_TYPE (decl))
22920 	  && !TYPE_DECL_ALIAS_P (TYPE_NAME (TREE_TYPE (decl)))
22921 	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
22922 	break;
22923 
22924       /* Stop if we run into an explicitly specialized class template.  */
22925       if (!DECL_NAMESPACE_SCOPE_P (decl)
22926 	  && DECL_CONTEXT (decl)
22927 	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
22928 	break;
22929 
22930       decl = DECL_TI_TEMPLATE (decl);
22931     }
22932 
22933   return decl;
22934 }
22935 
22936 /* Return the most specialized of the template partial specializations
22937    which can produce TARGET, a specialization of some class or variable
22938    template.  The value returned is actually a TREE_LIST; the TREE_VALUE is
22939    a TEMPLATE_DECL node corresponding to the partial specialization, while
22940    the TREE_PURPOSE is the set of template arguments that must be
22941    substituted into the template pattern in order to generate TARGET.
22942 
22943    If the choice of partial specialization is ambiguous, a diagnostic
22944    is issued, and the error_mark_node is returned.  If there are no
22945    partial specializations matching TARGET, then NULL_TREE is
22946    returned, indicating that the primary template should be used.  */
22947 
22948 static tree
most_specialized_partial_spec(tree target,tsubst_flags_t complain)22949 most_specialized_partial_spec (tree target, tsubst_flags_t complain)
22950 {
22951   tree list = NULL_TREE;
22952   tree t;
22953   tree champ;
22954   int fate;
22955   bool ambiguous_p;
22956   tree outer_args = NULL_TREE;
22957   tree tmpl, args;
22958 
22959   if (TYPE_P (target))
22960     {
22961       tree tinfo = CLASSTYPE_TEMPLATE_INFO (target);
22962       tmpl = TI_TEMPLATE (tinfo);
22963       args = TI_ARGS (tinfo);
22964     }
22965   else if (TREE_CODE (target) == TEMPLATE_ID_EXPR)
22966     {
22967       tmpl = TREE_OPERAND (target, 0);
22968       args = TREE_OPERAND (target, 1);
22969     }
22970   else if (VAR_P (target))
22971     {
22972       tree tinfo = DECL_TEMPLATE_INFO (target);
22973       tmpl = TI_TEMPLATE (tinfo);
22974       args = TI_ARGS (tinfo);
22975     }
22976   else
22977     gcc_unreachable ();
22978 
22979   tree main_tmpl = most_general_template (tmpl);
22980 
22981   /* For determining which partial specialization to use, only the
22982      innermost args are interesting.  */
22983   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
22984     {
22985       outer_args = strip_innermost_template_args (args, 1);
22986       args = INNERMOST_TEMPLATE_ARGS (args);
22987     }
22988 
22989   for (t = DECL_TEMPLATE_SPECIALIZATIONS (main_tmpl); t; t = TREE_CHAIN (t))
22990     {
22991       tree spec_args;
22992       tree spec_tmpl = TREE_VALUE (t);
22993 
22994       if (outer_args)
22995 	{
22996 	  /* Substitute in the template args from the enclosing class.  */
22997 	  ++processing_template_decl;
22998 	  spec_tmpl = tsubst (spec_tmpl, outer_args, tf_none, NULL_TREE);
22999 	  --processing_template_decl;
23000 	}
23001 
23002       if (spec_tmpl == error_mark_node)
23003 	return error_mark_node;
23004 
23005       spec_args = get_partial_spec_bindings (tmpl, spec_tmpl, args);
23006       if (spec_args)
23007 	{
23008 	  if (outer_args)
23009 	    spec_args = add_to_template_args (outer_args, spec_args);
23010 
23011           /* Keep the candidate only if the constraints are satisfied,
23012              or if we're not compiling with concepts.  */
23013           if (!flag_concepts
23014               || constraints_satisfied_p (spec_tmpl, spec_args))
23015             {
23016               list = tree_cons (spec_args, TREE_VALUE (t), list);
23017               TREE_TYPE (list) = TREE_TYPE (t);
23018             }
23019 	}
23020     }
23021 
23022   if (! list)
23023     return NULL_TREE;
23024 
23025   ambiguous_p = false;
23026   t = list;
23027   champ = t;
23028   t = TREE_CHAIN (t);
23029   for (; t; t = TREE_CHAIN (t))
23030     {
23031       fate = more_specialized_partial_spec (tmpl, champ, t);
23032       if (fate == 1)
23033 	;
23034       else
23035 	{
23036 	  if (fate == 0)
23037 	    {
23038 	      t = TREE_CHAIN (t);
23039 	      if (! t)
23040 		{
23041 		  ambiguous_p = true;
23042 		  break;
23043 		}
23044 	    }
23045 	  champ = t;
23046 	}
23047     }
23048 
23049   if (!ambiguous_p)
23050     for (t = list; t && t != champ; t = TREE_CHAIN (t))
23051       {
23052 	fate = more_specialized_partial_spec (tmpl, champ, t);
23053 	if (fate != 1)
23054 	  {
23055 	    ambiguous_p = true;
23056 	    break;
23057 	  }
23058       }
23059 
23060   if (ambiguous_p)
23061     {
23062       const char *str;
23063       char *spaces = NULL;
23064       if (!(complain & tf_error))
23065 	return error_mark_node;
23066       if (TYPE_P (target))
23067 	error ("ambiguous template instantiation for %q#T", target);
23068       else
23069 	error ("ambiguous template instantiation for %q#D", target);
23070       str = ngettext ("candidate is:", "candidates are:", list_length (list));
23071       for (t = list; t; t = TREE_CHAIN (t))
23072         {
23073 	  tree subst = build_tree_list (TREE_VALUE (t), TREE_PURPOSE (t));
23074           inform (DECL_SOURCE_LOCATION (TREE_VALUE (t)),
23075 		  "%s %#qS", spaces ? spaces : str, subst);
23076           spaces = spaces ? spaces : get_spaces (str);
23077         }
23078       free (spaces);
23079       return error_mark_node;
23080     }
23081 
23082   return champ;
23083 }
23084 
23085 /* Explicitly instantiate DECL.  */
23086 
23087 void
do_decl_instantiation(tree decl,tree storage)23088 do_decl_instantiation (tree decl, tree storage)
23089 {
23090   tree result = NULL_TREE;
23091   int extern_p = 0;
23092 
23093   if (!decl || decl == error_mark_node)
23094     /* An error occurred, for which grokdeclarator has already issued
23095        an appropriate message.  */
23096     return;
23097   else if (! DECL_LANG_SPECIFIC (decl))
23098     {
23099       error ("explicit instantiation of non-template %q#D", decl);
23100       return;
23101     }
23102 
23103   bool var_templ = (DECL_TEMPLATE_INFO (decl)
23104                     && variable_template_p (DECL_TI_TEMPLATE (decl)));
23105 
23106   if (VAR_P (decl) && !var_templ)
23107     {
23108       /* There is an asymmetry here in the way VAR_DECLs and
23109 	 FUNCTION_DECLs are handled by grokdeclarator.  In the case of
23110 	 the latter, the DECL we get back will be marked as a
23111 	 template instantiation, and the appropriate
23112 	 DECL_TEMPLATE_INFO will be set up.  This does not happen for
23113 	 VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
23114 	 should handle VAR_DECLs as it currently handles
23115 	 FUNCTION_DECLs.  */
23116       if (!DECL_CLASS_SCOPE_P (decl))
23117 	{
23118 	  error ("%qD is not a static data member of a class template", decl);
23119 	  return;
23120 	}
23121       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
23122       if (!result || !VAR_P (result))
23123 	{
23124 	  error ("no matching template for %qD found", decl);
23125 	  return;
23126 	}
23127       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
23128 	{
23129 	  error ("type %qT for explicit instantiation %qD does not match "
23130 		 "declared type %qT", TREE_TYPE (result), decl,
23131 		 TREE_TYPE (decl));
23132 	  return;
23133 	}
23134     }
23135   else if (TREE_CODE (decl) != FUNCTION_DECL && !var_templ)
23136     {
23137       error ("explicit instantiation of %q#D", decl);
23138       return;
23139     }
23140   else
23141     result = decl;
23142 
23143   /* Check for various error cases.  Note that if the explicit
23144      instantiation is valid the RESULT will currently be marked as an
23145      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
23146      until we get here.  */
23147 
23148   if (DECL_TEMPLATE_SPECIALIZATION (result))
23149     {
23150       /* DR 259 [temp.spec].
23151 
23152 	 Both an explicit instantiation and a declaration of an explicit
23153 	 specialization shall not appear in a program unless the explicit
23154 	 instantiation follows a declaration of the explicit specialization.
23155 
23156 	 For a given set of template parameters, if an explicit
23157 	 instantiation of a template appears after a declaration of an
23158 	 explicit specialization for that template, the explicit
23159 	 instantiation has no effect.  */
23160       return;
23161     }
23162   else if (DECL_EXPLICIT_INSTANTIATION (result))
23163     {
23164       /* [temp.spec]
23165 
23166 	 No program shall explicitly instantiate any template more
23167 	 than once.
23168 
23169 	 We check DECL_NOT_REALLY_EXTERN so as not to complain when
23170 	 the first instantiation was `extern' and the second is not,
23171 	 and EXTERN_P for the opposite case.  */
23172       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
23173 	permerror (input_location, "duplicate explicit instantiation of %q#D", result);
23174       /* If an "extern" explicit instantiation follows an ordinary
23175 	 explicit instantiation, the template is instantiated.  */
23176       if (extern_p)
23177 	return;
23178     }
23179   else if (!DECL_IMPLICIT_INSTANTIATION (result))
23180     {
23181       error ("no matching template for %qD found", result);
23182       return;
23183     }
23184   else if (!DECL_TEMPLATE_INFO (result))
23185     {
23186       permerror (input_location, "explicit instantiation of non-template %q#D", result);
23187       return;
23188     }
23189 
23190   if (storage == NULL_TREE)
23191     ;
23192   else if (storage == ridpointers[(int) RID_EXTERN])
23193     {
23194       if (!in_system_header_at (input_location) && (cxx_dialect == cxx98))
23195 	pedwarn (input_location, OPT_Wpedantic,
23196 		 "ISO C++ 1998 forbids the use of %<extern%> on explicit "
23197 		 "instantiations");
23198       extern_p = 1;
23199     }
23200   else
23201     error ("storage class %qD applied to template instantiation", storage);
23202 
23203   check_explicit_instantiation_namespace (result);
23204   mark_decl_instantiated (result, extern_p);
23205   if (! extern_p)
23206     instantiate_decl (result, /*defer_ok=*/true,
23207 		      /*expl_inst_class_mem_p=*/false);
23208 }
23209 
23210 static void
mark_class_instantiated(tree t,int extern_p)23211 mark_class_instantiated (tree t, int extern_p)
23212 {
23213   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
23214   SET_CLASSTYPE_INTERFACE_KNOWN (t);
23215   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
23216   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
23217   if (! extern_p)
23218     {
23219       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
23220       rest_of_type_compilation (t, 1);
23221     }
23222 }
23223 
23224 /* Called from do_type_instantiation through binding_table_foreach to
23225    do recursive instantiation for the type bound in ENTRY.  */
23226 static void
bt_instantiate_type_proc(binding_entry entry,void * data)23227 bt_instantiate_type_proc (binding_entry entry, void *data)
23228 {
23229   tree storage = *(tree *) data;
23230 
23231   if (MAYBE_CLASS_TYPE_P (entry->type)
23232       && CLASSTYPE_TEMPLATE_INFO (entry->type)
23233       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
23234     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
23235 }
23236 
23237 /* Perform an explicit instantiation of template class T.  STORAGE, if
23238    non-null, is the RID for extern, inline or static.  COMPLAIN is
23239    nonzero if this is called from the parser, zero if called recursively,
23240    since the standard is unclear (as detailed below).  */
23241 
23242 void
do_type_instantiation(tree t,tree storage,tsubst_flags_t complain)23243 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
23244 {
23245   int extern_p = 0;
23246   int nomem_p = 0;
23247   int static_p = 0;
23248   int previous_instantiation_extern_p = 0;
23249 
23250   if (TREE_CODE (t) == TYPE_DECL)
23251     t = TREE_TYPE (t);
23252 
23253   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
23254     {
23255       tree tmpl =
23256 	(TYPE_TEMPLATE_INFO (t)) ? TYPE_TI_TEMPLATE (t) : NULL;
23257       if (tmpl)
23258 	error ("explicit instantiation of non-class template %qD", tmpl);
23259       else
23260 	error ("explicit instantiation of non-template type %qT", t);
23261       return;
23262     }
23263 
23264   complete_type (t);
23265 
23266   if (!COMPLETE_TYPE_P (t))
23267     {
23268       if (complain & tf_error)
23269 	error ("explicit instantiation of %q#T before definition of template",
23270 	       t);
23271       return;
23272     }
23273 
23274   if (storage != NULL_TREE)
23275     {
23276       if (!in_system_header_at (input_location))
23277 	{
23278 	  if (storage == ridpointers[(int) RID_EXTERN])
23279 	    {
23280 	      if (cxx_dialect == cxx98)
23281 		pedwarn (input_location, OPT_Wpedantic,
23282 			 "ISO C++ 1998 forbids the use of %<extern%> on "
23283 			 "explicit instantiations");
23284 	    }
23285 	  else
23286 	    pedwarn (input_location, OPT_Wpedantic,
23287 		     "ISO C++ forbids the use of %qE"
23288 		     " on explicit instantiations", storage);
23289 	}
23290 
23291       if (storage == ridpointers[(int) RID_INLINE])
23292 	nomem_p = 1;
23293       else if (storage == ridpointers[(int) RID_EXTERN])
23294 	extern_p = 1;
23295       else if (storage == ridpointers[(int) RID_STATIC])
23296 	static_p = 1;
23297       else
23298 	{
23299 	  error ("storage class %qD applied to template instantiation",
23300 		 storage);
23301 	  extern_p = 0;
23302 	}
23303     }
23304 
23305   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
23306     {
23307       /* DR 259 [temp.spec].
23308 
23309 	 Both an explicit instantiation and a declaration of an explicit
23310 	 specialization shall not appear in a program unless the explicit
23311 	 instantiation follows a declaration of the explicit specialization.
23312 
23313 	 For a given set of template parameters, if an explicit
23314 	 instantiation of a template appears after a declaration of an
23315 	 explicit specialization for that template, the explicit
23316 	 instantiation has no effect.  */
23317       return;
23318     }
23319   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
23320     {
23321       /* [temp.spec]
23322 
23323 	 No program shall explicitly instantiate any template more
23324 	 than once.
23325 
23326 	 If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
23327 	 instantiation was `extern'.  If EXTERN_P then the second is.
23328 	 These cases are OK.  */
23329       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
23330 
23331       if (!previous_instantiation_extern_p && !extern_p
23332 	  && (complain & tf_error))
23333 	permerror (input_location, "duplicate explicit instantiation of %q#T", t);
23334 
23335       /* If we've already instantiated the template, just return now.  */
23336       if (!CLASSTYPE_INTERFACE_ONLY (t))
23337 	return;
23338     }
23339 
23340   check_explicit_instantiation_namespace (TYPE_NAME (t));
23341   mark_class_instantiated (t, extern_p);
23342 
23343   if (nomem_p)
23344     return;
23345 
23346   /* In contrast to implicit instantiation, where only the
23347      declarations, and not the definitions, of members are
23348      instantiated, we have here:
23349 
23350 	 [temp.explicit]
23351 
23352 	 The explicit instantiation of a class template specialization
23353 	 implies the instantiation of all of its members not
23354 	 previously explicitly specialized in the translation unit
23355 	 containing the explicit instantiation.
23356 
23357      Of course, we can't instantiate member template classes, since we
23358      don't have any arguments for them.  Note that the standard is
23359      unclear on whether the instantiation of the members are
23360      *explicit* instantiations or not.  However, the most natural
23361      interpretation is that it should be an explicit
23362      instantiation.  */
23363   for (tree fld = TYPE_FIELDS (t); fld; fld = DECL_CHAIN (fld))
23364     if ((VAR_P (fld)
23365 	 || (TREE_CODE (fld) == FUNCTION_DECL
23366 	     && !static_p
23367 	     && user_provided_p (fld)))
23368 	&& DECL_TEMPLATE_INSTANTIATION (fld))
23369       {
23370 	mark_decl_instantiated (fld, extern_p);
23371 	if (! extern_p)
23372 	  instantiate_decl (fld, /*defer_ok=*/true,
23373 			    /*expl_inst_class_mem_p=*/true);
23374       }
23375 
23376   if (CLASSTYPE_NESTED_UTDS (t))
23377     binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
23378 			   bt_instantiate_type_proc, &storage);
23379 }
23380 
23381 /* Given a function DECL, which is a specialization of TMPL, modify
23382    DECL to be a re-instantiation of TMPL with the same template
23383    arguments.  TMPL should be the template into which tsubst'ing
23384    should occur for DECL, not the most general template.
23385 
23386    One reason for doing this is a scenario like this:
23387 
23388      template <class T>
23389      void f(const T&, int i);
23390 
23391      void g() { f(3, 7); }
23392 
23393      template <class T>
23394      void f(const T& t, const int i) { }
23395 
23396    Note that when the template is first instantiated, with
23397    instantiate_template, the resulting DECL will have no name for the
23398    first parameter, and the wrong type for the second.  So, when we go
23399    to instantiate the DECL, we regenerate it.  */
23400 
23401 static void
regenerate_decl_from_template(tree decl,tree tmpl,tree args)23402 regenerate_decl_from_template (tree decl, tree tmpl, tree args)
23403 {
23404   /* The arguments used to instantiate DECL, from the most general
23405      template.  */
23406   tree code_pattern;
23407 
23408   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
23409 
23410   /* Make sure that we can see identifiers, and compute access
23411      correctly.  */
23412   push_access_scope (decl);
23413 
23414   if (TREE_CODE (decl) == FUNCTION_DECL)
23415     {
23416       tree decl_parm;
23417       tree pattern_parm;
23418       tree specs;
23419       int args_depth;
23420       int parms_depth;
23421 
23422       args_depth = TMPL_ARGS_DEPTH (args);
23423       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
23424       if (args_depth > parms_depth)
23425 	args = get_innermost_template_args (args, parms_depth);
23426 
23427       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
23428 					      args, tf_error, NULL_TREE,
23429 					      /*defer_ok*/false);
23430       if (specs && specs != error_mark_node)
23431 	TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
23432 						    specs);
23433 
23434       /* Merge parameter declarations.  */
23435       decl_parm = skip_artificial_parms_for (decl,
23436 					     DECL_ARGUMENTS (decl));
23437       pattern_parm
23438 	= skip_artificial_parms_for (code_pattern,
23439 				     DECL_ARGUMENTS (code_pattern));
23440       while (decl_parm && !DECL_PACK_P (pattern_parm))
23441 	{
23442 	  tree parm_type;
23443 	  tree attributes;
23444 
23445 	  if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
23446 	    DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
23447 	  parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
23448 			      NULL_TREE);
23449 	  parm_type = type_decays_to (parm_type);
23450 	  if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
23451 	    TREE_TYPE (decl_parm) = parm_type;
23452 	  attributes = DECL_ATTRIBUTES (pattern_parm);
23453 	  if (DECL_ATTRIBUTES (decl_parm) != attributes)
23454 	    {
23455 	      DECL_ATTRIBUTES (decl_parm) = attributes;
23456 	      cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
23457 	    }
23458 	  decl_parm = DECL_CHAIN (decl_parm);
23459 	  pattern_parm = DECL_CHAIN (pattern_parm);
23460 	}
23461       /* Merge any parameters that match with the function parameter
23462          pack.  */
23463       if (pattern_parm && DECL_PACK_P (pattern_parm))
23464         {
23465           int i, len;
23466           tree expanded_types;
23467           /* Expand the TYPE_PACK_EXPANSION that provides the types for
23468              the parameters in this function parameter pack.  */
23469           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm),
23470                                                  args, tf_error, NULL_TREE);
23471           len = TREE_VEC_LENGTH (expanded_types);
23472           for (i = 0; i < len; i++)
23473             {
23474               tree parm_type;
23475               tree attributes;
23476 
23477               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
23478                 /* Rename the parameter to include the index.  */
23479                 DECL_NAME (decl_parm) =
23480                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
23481               parm_type = TREE_VEC_ELT (expanded_types, i);
23482               parm_type = type_decays_to (parm_type);
23483               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
23484                 TREE_TYPE (decl_parm) = parm_type;
23485               attributes = DECL_ATTRIBUTES (pattern_parm);
23486               if (DECL_ATTRIBUTES (decl_parm) != attributes)
23487                 {
23488                   DECL_ATTRIBUTES (decl_parm) = attributes;
23489                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
23490                 }
23491               decl_parm = DECL_CHAIN (decl_parm);
23492             }
23493         }
23494       /* Merge additional specifiers from the CODE_PATTERN.  */
23495       if (DECL_DECLARED_INLINE_P (code_pattern)
23496 	  && !DECL_DECLARED_INLINE_P (decl))
23497 	DECL_DECLARED_INLINE_P (decl) = 1;
23498     }
23499   else if (VAR_P (decl))
23500     {
23501       start_lambda_scope (decl);
23502       DECL_INITIAL (decl) =
23503 	tsubst_expr (DECL_INITIAL (code_pattern), args,
23504 		     tf_error, DECL_TI_TEMPLATE (decl),
23505 		     /*integral_constant_expression_p=*/false);
23506       finish_lambda_scope ();
23507       if (VAR_HAD_UNKNOWN_BOUND (decl))
23508 	TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
23509 				   tf_error, DECL_TI_TEMPLATE (decl));
23510     }
23511   else
23512     gcc_unreachable ();
23513 
23514   pop_access_scope (decl);
23515 }
23516 
23517 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
23518    substituted to get DECL.  */
23519 
23520 tree
template_for_substitution(tree decl)23521 template_for_substitution (tree decl)
23522 {
23523   tree tmpl = DECL_TI_TEMPLATE (decl);
23524 
23525   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
23526      for the instantiation.  This is not always the most general
23527      template.  Consider, for example:
23528 
23529 	template <class T>
23530 	struct S { template <class U> void f();
23531 		   template <> void f<int>(); };
23532 
23533      and an instantiation of S<double>::f<int>.  We want TD to be the
23534      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
23535   while (/* An instantiation cannot have a definition, so we need a
23536 	    more general template.  */
23537 	 DECL_TEMPLATE_INSTANTIATION (tmpl)
23538 	   /* We must also deal with friend templates.  Given:
23539 
23540 		template <class T> struct S {
23541 		  template <class U> friend void f() {};
23542 		};
23543 
23544 	      S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
23545 	      so far as the language is concerned, but that's still
23546 	      where we get the pattern for the instantiation from.  On
23547 	      other hand, if the definition comes outside the class, say:
23548 
23549 		template <class T> struct S {
23550 		  template <class U> friend void f();
23551 		};
23552 		template <class U> friend void f() {}
23553 
23554 	      we don't need to look any further.  That's what the check for
23555 	      DECL_INITIAL is for.  */
23556 	  || (TREE_CODE (decl) == FUNCTION_DECL
23557 	      && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
23558 	      && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
23559     {
23560       /* The present template, TD, should not be a definition.  If it
23561 	 were a definition, we should be using it!  Note that we
23562 	 cannot restructure the loop to just keep going until we find
23563 	 a template with a definition, since that might go too far if
23564 	 a specialization was declared, but not defined.  */
23565 
23566       /* Fetch the more general template.  */
23567       tmpl = DECL_TI_TEMPLATE (tmpl);
23568     }
23569 
23570   return tmpl;
23571 }
23572 
23573 /* Returns true if we need to instantiate this template instance even if we
23574    know we aren't going to emit it.  */
23575 
23576 bool
always_instantiate_p(tree decl)23577 always_instantiate_p (tree decl)
23578 {
23579   /* We always instantiate inline functions so that we can inline them.  An
23580      explicit instantiation declaration prohibits implicit instantiation of
23581      non-inline functions.  With high levels of optimization, we would
23582      normally inline non-inline functions -- but we're not allowed to do
23583      that for "extern template" functions.  Therefore, we check
23584      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
23585   return ((TREE_CODE (decl) == FUNCTION_DECL
23586 	   && (DECL_DECLARED_INLINE_P (decl)
23587 	       || type_uses_auto (TREE_TYPE (TREE_TYPE (decl)))))
23588 	  /* And we need to instantiate static data members so that
23589 	     their initializers are available in integral constant
23590 	     expressions.  */
23591 	  || (VAR_P (decl)
23592 	      && decl_maybe_constant_var_p (decl)));
23593 }
23594 
23595 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
23596    instantiate it now, modifying TREE_TYPE (fn).  Returns false on
23597    error, true otherwise.  */
23598 
23599 bool
maybe_instantiate_noexcept(tree fn,tsubst_flags_t complain)23600 maybe_instantiate_noexcept (tree fn, tsubst_flags_t complain)
23601 {
23602   tree fntype, spec, noex, clone;
23603 
23604   /* Don't instantiate a noexcept-specification from template context.  */
23605   if (processing_template_decl
23606       && (!flag_noexcept_type || type_dependent_expression_p (fn)))
23607     return true;
23608 
23609   if (DECL_CLONED_FUNCTION_P (fn))
23610     fn = DECL_CLONED_FUNCTION (fn);
23611   fntype = TREE_TYPE (fn);
23612   spec = TYPE_RAISES_EXCEPTIONS (fntype);
23613 
23614   if (!spec || !TREE_PURPOSE (spec))
23615     return true;
23616 
23617   noex = TREE_PURPOSE (spec);
23618 
23619   if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
23620     {
23621       static hash_set<tree>* fns = new hash_set<tree>;
23622       bool added = false;
23623       if (DEFERRED_NOEXCEPT_PATTERN (noex) == NULL_TREE)
23624 	spec = get_defaulted_eh_spec (fn, complain);
23625       else if (!(added = !fns->add (fn)))
23626 	{
23627 	  /* If hash_set::add returns true, the element was already there.  */
23628 	  location_t loc = EXPR_LOC_OR_LOC (DEFERRED_NOEXCEPT_PATTERN (noex),
23629 					    DECL_SOURCE_LOCATION (fn));
23630 	  error_at (loc,
23631 		    "exception specification of %qD depends on itself",
23632 		    fn);
23633 	  spec = noexcept_false_spec;
23634 	}
23635       else if (push_tinst_level (fn))
23636 	{
23637 	  push_access_scope (fn);
23638 	  push_deferring_access_checks (dk_no_deferred);
23639 	  input_location = DECL_SOURCE_LOCATION (fn);
23640 	  noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
23641 					DEFERRED_NOEXCEPT_ARGS (noex),
23642 					tf_warning_or_error, fn,
23643 					/*function_p=*/false,
23644 					/*integral_constant_expression_p=*/true);
23645 	  spec = build_noexcept_spec (noex, tf_warning_or_error);
23646 	  pop_deferring_access_checks ();
23647 	  pop_access_scope (fn);
23648 	  pop_tinst_level ();
23649 	  if (spec == error_mark_node)
23650 	    spec = noexcept_false_spec;
23651 	}
23652       else
23653 	spec = noexcept_false_spec;
23654 
23655       if (added)
23656 	fns->remove (fn);
23657 
23658       if (spec == error_mark_node)
23659 	return false;
23660 
23661       TREE_TYPE (fn) = build_exception_variant (fntype, spec);
23662     }
23663 
23664   FOR_EACH_CLONE (clone, fn)
23665     {
23666       if (TREE_TYPE (clone) == fntype)
23667 	TREE_TYPE (clone) = TREE_TYPE (fn);
23668       else
23669 	TREE_TYPE (clone) = build_exception_variant (TREE_TYPE (clone), spec);
23670     }
23671 
23672   return true;
23673 }
23674 
23675 /* We're starting to process the function INST, an instantiation of PATTERN;
23676    add their parameters to local_specializations.  */
23677 
23678 static void
register_parameter_specializations(tree pattern,tree inst)23679 register_parameter_specializations (tree pattern, tree inst)
23680 {
23681   tree tmpl_parm = DECL_ARGUMENTS (pattern);
23682   tree spec_parm = DECL_ARGUMENTS (inst);
23683   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (inst))
23684     {
23685       register_local_specialization (spec_parm, tmpl_parm);
23686       spec_parm = skip_artificial_parms_for (inst, spec_parm);
23687       tmpl_parm = skip_artificial_parms_for (pattern, tmpl_parm);
23688     }
23689   for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
23690     {
23691       if (!DECL_PACK_P (tmpl_parm))
23692 	{
23693 	  register_local_specialization (spec_parm, tmpl_parm);
23694 	  spec_parm = DECL_CHAIN (spec_parm);
23695 	}
23696       else
23697 	{
23698 	  /* Register the (value) argument pack as a specialization of
23699 	     TMPL_PARM, then move on.  */
23700 	  tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
23701 	  register_local_specialization (argpack, tmpl_parm);
23702 	}
23703     }
23704   gcc_assert (!spec_parm);
23705 }
23706 
23707 /* Produce the definition of D, a _DECL generated from a template.  If
23708    DEFER_OK is true, then we don't have to actually do the
23709    instantiation now; we just have to do it sometime.  Normally it is
23710    an error if this is an explicit instantiation but D is undefined.
23711    EXPL_INST_CLASS_MEM_P is true iff D is a member of an explicitly
23712    instantiated class template.  */
23713 
23714 tree
instantiate_decl(tree d,bool defer_ok,bool expl_inst_class_mem_p)23715 instantiate_decl (tree d, bool defer_ok, bool expl_inst_class_mem_p)
23716 {
23717   tree tmpl = DECL_TI_TEMPLATE (d);
23718   tree gen_args;
23719   tree args;
23720   tree td;
23721   tree code_pattern;
23722   tree spec;
23723   tree gen_tmpl;
23724   bool pattern_defined;
23725   location_t saved_loc = input_location;
23726   int saved_unevaluated_operand = cp_unevaluated_operand;
23727   int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
23728   bool external_p;
23729   bool deleted_p;
23730 
23731   /* This function should only be used to instantiate templates for
23732      functions and static member variables.  */
23733   gcc_assert (VAR_OR_FUNCTION_DECL_P (d));
23734 
23735   /* A concept is never instantiated. */
23736   gcc_assert (!DECL_DECLARED_CONCEPT_P (d));
23737 
23738   /* Variables are never deferred; if instantiation is required, they
23739      are instantiated right away.  That allows for better code in the
23740      case that an expression refers to the value of the variable --
23741      if the variable has a constant value the referring expression can
23742      take advantage of that fact.  */
23743   if (VAR_P (d))
23744     defer_ok = false;
23745 
23746   /* Don't instantiate cloned functions.  Instead, instantiate the
23747      functions they cloned.  */
23748   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
23749     d = DECL_CLONED_FUNCTION (d);
23750 
23751   if (DECL_TEMPLATE_INSTANTIATED (d)
23752       || (TREE_CODE (d) == FUNCTION_DECL
23753 	  && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
23754       || DECL_TEMPLATE_SPECIALIZATION (d))
23755     /* D has already been instantiated or explicitly specialized, so
23756        there's nothing for us to do here.
23757 
23758        It might seem reasonable to check whether or not D is an explicit
23759        instantiation, and, if so, stop here.  But when an explicit
23760        instantiation is deferred until the end of the compilation,
23761        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
23762        the instantiation.  */
23763     return d;
23764 
23765   /* Check to see whether we know that this template will be
23766      instantiated in some other file, as with "extern template"
23767      extension.  */
23768   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
23769 
23770   /* In general, we do not instantiate such templates.  */
23771   if (external_p && !always_instantiate_p (d))
23772     return d;
23773 
23774   gen_tmpl = most_general_template (tmpl);
23775   gen_args = DECL_TI_ARGS (d);
23776 
23777   if (tmpl != gen_tmpl)
23778     /* We should already have the extra args.  */
23779     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
23780 		== TMPL_ARGS_DEPTH (gen_args));
23781   /* And what's in the hash table should match D.  */
23782   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
23783 	      || spec == NULL_TREE);
23784 
23785   /* This needs to happen before any tsubsting.  */
23786   if (! push_tinst_level (d))
23787     return d;
23788 
23789   timevar_push (TV_TEMPLATE_INST);
23790 
23791   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
23792      for the instantiation.  */
23793   td = template_for_substitution (d);
23794   args = gen_args;
23795 
23796   if (VAR_P (d))
23797     {
23798       /* Look up an explicit specialization, if any.  */
23799       tree tid = lookup_template_variable (gen_tmpl, gen_args);
23800       tree elt = most_specialized_partial_spec (tid, tf_warning_or_error);
23801       if (elt && elt != error_mark_node)
23802 	{
23803 	  td = TREE_VALUE (elt);
23804 	  args = TREE_PURPOSE (elt);
23805 	}
23806     }
23807 
23808   code_pattern = DECL_TEMPLATE_RESULT (td);
23809 
23810   /* We should never be trying to instantiate a member of a class
23811      template or partial specialization.  */
23812   gcc_assert (d != code_pattern);
23813 
23814   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
23815       || DECL_TEMPLATE_SPECIALIZATION (td))
23816     /* In the case of a friend template whose definition is provided
23817        outside the class, we may have too many arguments.  Drop the
23818        ones we don't need.  The same is true for specializations.  */
23819     args = get_innermost_template_args
23820       (args, TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (td)));
23821 
23822   if (TREE_CODE (d) == FUNCTION_DECL)
23823     {
23824       deleted_p = DECL_DELETED_FN (code_pattern);
23825       pattern_defined = ((DECL_SAVED_TREE (code_pattern) != NULL_TREE
23826 			  && DECL_INITIAL (code_pattern) != error_mark_node)
23827 			 || DECL_DEFAULTED_OUTSIDE_CLASS_P (code_pattern)
23828 			 || deleted_p);
23829     }
23830   else
23831     {
23832       deleted_p = false;
23833       if (DECL_CLASS_SCOPE_P (code_pattern))
23834 	pattern_defined = (! DECL_IN_AGGR_P (code_pattern)
23835 			   || DECL_INLINE_VAR_P (code_pattern));
23836       else
23837 	pattern_defined = ! DECL_EXTERNAL (code_pattern);
23838     }
23839 
23840   /* We may be in the middle of deferred access check.  Disable it now.  */
23841   push_deferring_access_checks (dk_no_deferred);
23842 
23843   /* Unless an explicit instantiation directive has already determined
23844      the linkage of D, remember that a definition is available for
23845      this entity.  */
23846   if (pattern_defined
23847       && !DECL_INTERFACE_KNOWN (d)
23848       && !DECL_NOT_REALLY_EXTERN (d))
23849     mark_definable (d);
23850 
23851   DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
23852   DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
23853   input_location = DECL_SOURCE_LOCATION (d);
23854 
23855   /* If D is a member of an explicitly instantiated class template,
23856      and no definition is available, treat it like an implicit
23857      instantiation.  */
23858   if (!pattern_defined && expl_inst_class_mem_p
23859       && DECL_EXPLICIT_INSTANTIATION (d))
23860     {
23861       /* Leave linkage flags alone on instantiations with anonymous
23862 	 visibility.  */
23863       if (TREE_PUBLIC (d))
23864 	{
23865 	  DECL_NOT_REALLY_EXTERN (d) = 0;
23866 	  DECL_INTERFACE_KNOWN (d) = 0;
23867 	}
23868       SET_DECL_IMPLICIT_INSTANTIATION (d);
23869     }
23870 
23871   /* Defer all other templates, unless we have been explicitly
23872      forbidden from doing so.  */
23873   if (/* If there is no definition, we cannot instantiate the
23874 	 template.  */
23875       ! pattern_defined
23876       /* If it's OK to postpone instantiation, do so.  */
23877       || defer_ok
23878       /* If this is a static data member that will be defined
23879 	 elsewhere, we don't want to instantiate the entire data
23880 	 member, but we do want to instantiate the initializer so that
23881 	 we can substitute that elsewhere.  */
23882       || (external_p && VAR_P (d))
23883       /* Handle here a deleted function too, avoid generating
23884 	 its body (c++/61080).  */
23885       || deleted_p)
23886     {
23887       /* The definition of the static data member is now required so
23888 	 we must substitute the initializer.  */
23889       if (VAR_P (d)
23890 	  && !DECL_INITIAL (d)
23891 	  && DECL_INITIAL (code_pattern))
23892 	{
23893 	  tree ns;
23894 	  tree init;
23895 	  bool const_init = false;
23896 	  bool enter_context = DECL_CLASS_SCOPE_P (d);
23897 
23898 	  ns = decl_namespace_context (d);
23899 	  push_nested_namespace (ns);
23900 	  if (enter_context)
23901 	    push_nested_class (DECL_CONTEXT (d));
23902 	  init = tsubst_expr (DECL_INITIAL (code_pattern),
23903 			      args,
23904 			      tf_warning_or_error, NULL_TREE,
23905 			      /*integral_constant_expression_p=*/false);
23906 	  /* If instantiating the initializer involved instantiating this
23907 	     again, don't call cp_finish_decl twice.  */
23908 	  if (!DECL_INITIAL (d))
23909 	    {
23910 	      /* Make sure the initializer is still constant, in case of
23911 		 circular dependency (template/instantiate6.C). */
23912 	      const_init
23913 		= DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
23914 	      cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
23915 			      /*asmspec_tree=*/NULL_TREE,
23916 			      LOOKUP_ONLYCONVERTING);
23917 	    }
23918 	  if (enter_context)
23919 	    pop_nested_class ();
23920 	  pop_nested_namespace (ns);
23921 	}
23922 
23923       /* We restore the source position here because it's used by
23924 	 add_pending_template.  */
23925       input_location = saved_loc;
23926 
23927       if (at_eof && !pattern_defined
23928 	  && DECL_EXPLICIT_INSTANTIATION (d)
23929 	  && DECL_NOT_REALLY_EXTERN (d))
23930 	/* [temp.explicit]
23931 
23932 	   The definition of a non-exported function template, a
23933 	   non-exported member function template, or a non-exported
23934 	   member function or static data member of a class template
23935 	   shall be present in every translation unit in which it is
23936 	   explicitly instantiated.  */
23937 	permerror (input_location,  "explicit instantiation of %qD "
23938 		   "but no definition available", d);
23939 
23940       /* If we're in unevaluated context, we just wanted to get the
23941 	 constant value; this isn't an odr use, so don't queue
23942 	 a full instantiation.  */
23943       if (cp_unevaluated_operand != 0)
23944 	goto out;
23945       /* ??? Historically, we have instantiated inline functions, even
23946 	 when marked as "extern template".  */
23947       if (!(external_p && VAR_P (d)))
23948 	add_pending_template (d);
23949       goto out;
23950     }
23951   /* Tell the repository that D is available in this translation unit
23952      -- and see if it is supposed to be instantiated here.  */
23953   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
23954     {
23955       /* In a PCH file, despite the fact that the repository hasn't
23956 	 requested instantiation in the PCH it is still possible that
23957 	 an instantiation will be required in a file that includes the
23958 	 PCH.  */
23959       if (pch_file)
23960 	add_pending_template (d);
23961       /* Instantiate inline functions so that the inliner can do its
23962 	 job, even though we'll not be emitting a copy of this
23963 	 function.  */
23964       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
23965 	goto out;
23966     }
23967 
23968   bool push_to_top, nested;
23969   tree fn_context;
23970   fn_context = decl_function_context (d);
23971   if (LAMBDA_FUNCTION_P (d))
23972     /* tsubst_lambda_expr resolved any references to enclosing functions.  */
23973     fn_context = NULL_TREE;
23974   nested = current_function_decl != NULL_TREE;
23975   push_to_top = !(nested && fn_context == current_function_decl);
23976 
23977   vec<tree> omp_privatization_save;
23978   if (nested)
23979     save_omp_privatization_clauses (omp_privatization_save);
23980 
23981   if (push_to_top)
23982     push_to_top_level ();
23983   else
23984     {
23985       push_function_context ();
23986       cp_unevaluated_operand = 0;
23987       c_inhibit_evaluation_warnings = 0;
23988     }
23989 
23990   /* Mark D as instantiated so that recursive calls to
23991      instantiate_decl do not try to instantiate it again.  */
23992   DECL_TEMPLATE_INSTANTIATED (d) = 1;
23993 
23994   /* Regenerate the declaration in case the template has been modified
23995      by a subsequent redeclaration.  */
23996   regenerate_decl_from_template (d, td, args);
23997 
23998   /* We already set the file and line above.  Reset them now in case
23999      they changed as a result of calling regenerate_decl_from_template.  */
24000   input_location = DECL_SOURCE_LOCATION (d);
24001 
24002   if (VAR_P (d))
24003     {
24004       tree init;
24005       bool const_init = false;
24006 
24007       /* Clear out DECL_RTL; whatever was there before may not be right
24008 	 since we've reset the type of the declaration.  */
24009       SET_DECL_RTL (d, NULL);
24010       DECL_IN_AGGR_P (d) = 0;
24011 
24012       /* The initializer is placed in DECL_INITIAL by
24013 	 regenerate_decl_from_template so we don't need to
24014 	 push/pop_access_scope again here.  Pull it out so that
24015 	 cp_finish_decl can process it.  */
24016       init = DECL_INITIAL (d);
24017       DECL_INITIAL (d) = NULL_TREE;
24018       DECL_INITIALIZED_P (d) = 0;
24019 
24020       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
24021 	 initializer.  That function will defer actual emission until
24022 	 we have a chance to determine linkage.  */
24023       DECL_EXTERNAL (d) = 0;
24024 
24025       /* Enter the scope of D so that access-checking works correctly.  */
24026       bool enter_context = DECL_CLASS_SCOPE_P (d);
24027       if (enter_context)
24028         push_nested_class (DECL_CONTEXT (d));
24029 
24030       const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
24031       cp_finish_decl (d, init, const_init, NULL_TREE, 0);
24032 
24033       if (enter_context)
24034         pop_nested_class ();
24035 
24036       if (variable_template_p (gen_tmpl))
24037 	note_variable_template_instantiation (d);
24038     }
24039   else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
24040     synthesize_method (d);
24041   else if (TREE_CODE (d) == FUNCTION_DECL)
24042     {
24043       /* Set up the list of local specializations.  */
24044       local_specialization_stack lss (push_to_top ? lss_blank : lss_copy);
24045       tree block = NULL_TREE;
24046 
24047       /* Set up context.  */
24048       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern)
24049 	  && TREE_CODE (DECL_CONTEXT (code_pattern)) == FUNCTION_DECL)
24050 	block = push_stmt_list ();
24051       else
24052 	start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
24053 
24054       /* Some typedefs referenced from within the template code need to be
24055 	 access checked at template instantiation time, i.e now. These
24056 	 types were added to the template at parsing time. Let's get those
24057 	 and perform the access checks then.  */
24058       perform_typedefs_access_check (DECL_TEMPLATE_RESULT (td),
24059 				     args);
24060 
24061       /* Create substitution entries for the parameters.  */
24062       register_parameter_specializations (code_pattern, d);
24063 
24064       /* Substitute into the body of the function.  */
24065       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
24066 	tsubst_omp_udr (DECL_SAVED_TREE (code_pattern), args,
24067 			tf_warning_or_error, tmpl);
24068       else
24069 	{
24070 	  tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
24071 		       tf_warning_or_error, tmpl,
24072 		       /*integral_constant_expression_p=*/false);
24073 
24074 	  /* Set the current input_location to the end of the function
24075 	     so that finish_function knows where we are.  */
24076 	  input_location
24077 	    = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
24078 
24079 	  /* Remember if we saw an infinite loop in the template.  */
24080 	  current_function_infinite_loop
24081 	    = DECL_STRUCT_FUNCTION (code_pattern)->language->infinite_loop;
24082 	}
24083 
24084       /* Finish the function.  */
24085       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern)
24086 	  && TREE_CODE (DECL_CONTEXT (code_pattern)) == FUNCTION_DECL)
24087 	DECL_SAVED_TREE (d) = pop_stmt_list (block);
24088       else
24089 	{
24090 	  d = finish_function (/*inline_p=*/false);
24091 	  expand_or_defer_fn (d);
24092 	}
24093 
24094       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
24095 	cp_check_omp_declare_reduction (d);
24096     }
24097 
24098   /* We're not deferring instantiation any more.  */
24099   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
24100 
24101   if (push_to_top)
24102     pop_from_top_level ();
24103   else
24104     pop_function_context ();
24105 
24106   if (nested)
24107     restore_omp_privatization_clauses (omp_privatization_save);
24108 
24109 out:
24110   pop_deferring_access_checks ();
24111   timevar_pop (TV_TEMPLATE_INST);
24112   pop_tinst_level ();
24113   input_location = saved_loc;
24114   cp_unevaluated_operand = saved_unevaluated_operand;
24115   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
24116 
24117   return d;
24118 }
24119 
24120 /* Run through the list of templates that we wish we could
24121    instantiate, and instantiate any we can.  RETRIES is the
24122    number of times we retry pending template instantiation.  */
24123 
24124 void
instantiate_pending_templates(int retries)24125 instantiate_pending_templates (int retries)
24126 {
24127   int reconsider;
24128   location_t saved_loc = input_location;
24129 
24130   /* Instantiating templates may trigger vtable generation.  This in turn
24131      may require further template instantiations.  We place a limit here
24132      to avoid infinite loop.  */
24133   if (pending_templates && retries >= max_tinst_depth)
24134     {
24135       tree decl = pending_templates->tinst->maybe_get_node ();
24136 
24137       fatal_error (input_location,
24138 		   "template instantiation depth exceeds maximum of %d"
24139                    " instantiating %q+D, possibly from virtual table generation"
24140                    " (use -ftemplate-depth= to increase the maximum)",
24141                    max_tinst_depth, decl);
24142       if (TREE_CODE (decl) == FUNCTION_DECL)
24143 	/* Pretend that we defined it.  */
24144 	DECL_INITIAL (decl) = error_mark_node;
24145       return;
24146     }
24147 
24148   do
24149     {
24150       struct pending_template **t = &pending_templates;
24151       struct pending_template *last = NULL;
24152       reconsider = 0;
24153       while (*t)
24154 	{
24155 	  tree instantiation = reopen_tinst_level ((*t)->tinst);
24156 	  bool complete = false;
24157 
24158 	  if (TYPE_P (instantiation))
24159 	    {
24160 	      if (!COMPLETE_TYPE_P (instantiation))
24161 		{
24162 		  instantiate_class_template (instantiation);
24163 		  if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
24164 		    for (tree fld = TYPE_FIELDS (instantiation);
24165 			 fld; fld = TREE_CHAIN (fld))
24166 		      if ((VAR_P (fld)
24167 			   || (TREE_CODE (fld) == FUNCTION_DECL
24168 			       && !DECL_ARTIFICIAL (fld)))
24169 			  && DECL_TEMPLATE_INSTANTIATION (fld))
24170 			instantiate_decl (fld,
24171 					  /*defer_ok=*/false,
24172 					  /*expl_inst_class_mem_p=*/false);
24173 
24174 		  if (COMPLETE_TYPE_P (instantiation))
24175 		    reconsider = 1;
24176 		}
24177 
24178 	      complete = COMPLETE_TYPE_P (instantiation);
24179 	    }
24180 	  else
24181 	    {
24182 	      if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
24183 		  && !DECL_TEMPLATE_INSTANTIATED (instantiation))
24184 		{
24185 		  instantiation
24186 		    = instantiate_decl (instantiation,
24187 					/*defer_ok=*/false,
24188 					/*expl_inst_class_mem_p=*/false);
24189 		  if (DECL_TEMPLATE_INSTANTIATED (instantiation))
24190 		    reconsider = 1;
24191 		}
24192 
24193 	      complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
24194 			  || DECL_TEMPLATE_INSTANTIATED (instantiation));
24195 	    }
24196 
24197 	  if (complete)
24198 	    {
24199 	      /* If INSTANTIATION has been instantiated, then we don't
24200 		 need to consider it again in the future.  */
24201 	      struct pending_template *drop = *t;
24202 	      *t = (*t)->next;
24203 	      set_refcount_ptr (drop->tinst);
24204 	      pending_template_freelist ().free (drop);
24205 	    }
24206 	  else
24207 	    {
24208 	      last = *t;
24209 	      t = &(*t)->next;
24210 	    }
24211 	  tinst_depth = 0;
24212 	  set_refcount_ptr (current_tinst_level);
24213 	}
24214       last_pending_template = last;
24215     }
24216   while (reconsider);
24217 
24218   input_location = saved_loc;
24219 }
24220 
24221 /* Substitute ARGVEC into T, which is a list of initializers for
24222    either base class or a non-static data member.  The TREE_PURPOSEs
24223    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
24224    instantiate_decl.  */
24225 
24226 static tree
tsubst_initializer_list(tree t,tree argvec)24227 tsubst_initializer_list (tree t, tree argvec)
24228 {
24229   tree inits = NULL_TREE;
24230   tree target_ctor = error_mark_node;
24231 
24232   for (; t; t = TREE_CHAIN (t))
24233     {
24234       tree decl;
24235       tree init;
24236       tree expanded_bases = NULL_TREE;
24237       tree expanded_arguments = NULL_TREE;
24238       int i, len = 1;
24239 
24240       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
24241         {
24242           tree expr;
24243           tree arg;
24244 
24245           /* Expand the base class expansion type into separate base
24246              classes.  */
24247           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
24248                                                  tf_warning_or_error,
24249                                                  NULL_TREE);
24250           if (expanded_bases == error_mark_node)
24251             continue;
24252 
24253           /* We'll be building separate TREE_LISTs of arguments for
24254              each base.  */
24255           len = TREE_VEC_LENGTH (expanded_bases);
24256           expanded_arguments = make_tree_vec (len);
24257           for (i = 0; i < len; i++)
24258             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
24259 
24260           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
24261              expand each argument in the TREE_VALUE of t.  */
24262           expr = make_node (EXPR_PACK_EXPANSION);
24263 	  PACK_EXPANSION_LOCAL_P (expr) = true;
24264           PACK_EXPANSION_PARAMETER_PACKS (expr) =
24265             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
24266 
24267 	  if (TREE_VALUE (t) == void_type_node)
24268 	    /* VOID_TYPE_NODE is used to indicate
24269 	       value-initialization.  */
24270 	    {
24271 	      for (i = 0; i < len; i++)
24272 		TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
24273 	    }
24274 	  else
24275 	    {
24276 	      /* Substitute parameter packs into each argument in the
24277 		 TREE_LIST.  */
24278 	      in_base_initializer = 1;
24279 	      for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
24280 		{
24281 		  tree expanded_exprs;
24282 
24283 		  /* Expand the argument.  */
24284 		  SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
24285 		  expanded_exprs
24286 		    = tsubst_pack_expansion (expr, argvec,
24287 					     tf_warning_or_error,
24288 					     NULL_TREE);
24289 		  if (expanded_exprs == error_mark_node)
24290 		    continue;
24291 
24292 		  /* Prepend each of the expanded expressions to the
24293 		     corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
24294 		  for (i = 0; i < len; i++)
24295 		    {
24296 		      TREE_VEC_ELT (expanded_arguments, i) =
24297 			tree_cons (NULL_TREE,
24298 				   TREE_VEC_ELT (expanded_exprs, i),
24299 				   TREE_VEC_ELT (expanded_arguments, i));
24300 		    }
24301 		}
24302 	      in_base_initializer = 0;
24303 
24304 	      /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
24305 		 since we built them backwards.  */
24306 	      for (i = 0; i < len; i++)
24307 		{
24308 		  TREE_VEC_ELT (expanded_arguments, i) =
24309 		    nreverse (TREE_VEC_ELT (expanded_arguments, i));
24310 		}
24311 	    }
24312         }
24313 
24314       for (i = 0; i < len; ++i)
24315         {
24316           if (expanded_bases)
24317             {
24318               decl = TREE_VEC_ELT (expanded_bases, i);
24319               decl = expand_member_init (decl);
24320               init = TREE_VEC_ELT (expanded_arguments, i);
24321             }
24322           else
24323             {
24324 	      tree tmp;
24325               decl = tsubst_copy (TREE_PURPOSE (t), argvec,
24326                                   tf_warning_or_error, NULL_TREE);
24327 
24328               decl = expand_member_init (decl);
24329               if (decl && !DECL_P (decl))
24330                 in_base_initializer = 1;
24331 
24332 	      init = TREE_VALUE (t);
24333 	      tmp = init;
24334 	      if (init != void_type_node)
24335 		init = tsubst_expr (init, argvec,
24336 				    tf_warning_or_error, NULL_TREE,
24337 				    /*integral_constant_expression_p=*/false);
24338 	      if (init == NULL_TREE && tmp != NULL_TREE)
24339 		/* If we had an initializer but it instantiated to nothing,
24340 		   value-initialize the object.  This will only occur when
24341 		   the initializer was a pack expansion where the parameter
24342 		   packs used in that expansion were of length zero.  */
24343 		init = void_type_node;
24344               in_base_initializer = 0;
24345             }
24346 
24347 	  if (target_ctor != error_mark_node
24348 	      && init != error_mark_node)
24349 	    {
24350 	      error ("mem-initializer for %qD follows constructor delegation",
24351 		     decl);
24352 	      return inits;
24353 	    }
24354 	  /* Look for a target constructor. */
24355 	  if (init != error_mark_node
24356 	      && decl && CLASS_TYPE_P (decl)
24357 	      && same_type_p (decl, current_class_type))
24358 	    {
24359 	      maybe_warn_cpp0x (CPP0X_DELEGATING_CTORS);
24360 	      if (inits)
24361 		{
24362 		  error ("constructor delegation follows mem-initializer for %qD",
24363 			 TREE_PURPOSE (inits));
24364 		  continue;
24365 		}
24366 	      target_ctor = init;
24367 	    }
24368 
24369           if (decl)
24370             {
24371               init = build_tree_list (decl, init);
24372               TREE_CHAIN (init) = inits;
24373               inits = init;
24374             }
24375         }
24376     }
24377   return inits;
24378 }
24379 
24380 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
24381 
24382 static void
set_current_access_from_decl(tree decl)24383 set_current_access_from_decl (tree decl)
24384 {
24385   if (TREE_PRIVATE (decl))
24386     current_access_specifier = access_private_node;
24387   else if (TREE_PROTECTED (decl))
24388     current_access_specifier = access_protected_node;
24389   else
24390     current_access_specifier = access_public_node;
24391 }
24392 
24393 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
24394    is the instantiation (which should have been created with
24395    start_enum) and ARGS are the template arguments to use.  */
24396 
24397 static void
tsubst_enum(tree tag,tree newtag,tree args)24398 tsubst_enum (tree tag, tree newtag, tree args)
24399 {
24400   tree e;
24401 
24402   if (SCOPED_ENUM_P (newtag))
24403     begin_scope (sk_scoped_enum, newtag);
24404 
24405   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
24406     {
24407       tree value;
24408       tree decl;
24409 
24410       decl = TREE_VALUE (e);
24411       /* Note that in a template enum, the TREE_VALUE is the
24412 	 CONST_DECL, not the corresponding INTEGER_CST.  */
24413       value = tsubst_expr (DECL_INITIAL (decl),
24414 			   args, tf_warning_or_error, NULL_TREE,
24415 			   /*integral_constant_expression_p=*/true);
24416 
24417       /* Give this enumeration constant the correct access.  */
24418       set_current_access_from_decl (decl);
24419 
24420       /* Actually build the enumerator itself.  Here we're assuming that
24421 	 enumerators can't have dependent attributes.  */
24422       build_enumerator (DECL_NAME (decl), value, newtag,
24423 			DECL_ATTRIBUTES (decl), DECL_SOURCE_LOCATION (decl));
24424     }
24425 
24426   if (SCOPED_ENUM_P (newtag))
24427     finish_scope ();
24428 
24429   finish_enum_value_list (newtag);
24430   finish_enum (newtag);
24431 
24432   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
24433     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
24434 }
24435 
24436 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
24437    its type -- but without substituting the innermost set of template
24438    arguments.  So, innermost set of template parameters will appear in
24439    the type.  */
24440 
24441 tree
get_mostly_instantiated_function_type(tree decl)24442 get_mostly_instantiated_function_type (tree decl)
24443 {
24444   /* For a function, DECL_TI_TEMPLATE is partially instantiated.  */
24445   return TREE_TYPE (DECL_TI_TEMPLATE (decl));
24446 }
24447 
24448 /* Return truthvalue if we're processing a template different from
24449    the last one involved in diagnostics.  */
24450 bool
problematic_instantiation_changed(void)24451 problematic_instantiation_changed (void)
24452 {
24453   return current_tinst_level != last_error_tinst_level;
24454 }
24455 
24456 /* Remember current template involved in diagnostics.  */
24457 void
record_last_problematic_instantiation(void)24458 record_last_problematic_instantiation (void)
24459 {
24460   set_refcount_ptr (last_error_tinst_level, current_tinst_level);
24461 }
24462 
24463 struct tinst_level *
current_instantiation(void)24464 current_instantiation (void)
24465 {
24466   return current_tinst_level;
24467 }
24468 
24469 /* Return TRUE if current_function_decl is being instantiated, false
24470    otherwise.  */
24471 
24472 bool
instantiating_current_function_p(void)24473 instantiating_current_function_p (void)
24474 {
24475   return (current_instantiation ()
24476 	  && (current_instantiation ()->maybe_get_node ()
24477 	      == current_function_decl));
24478 }
24479 
24480 /* [temp.param] Check that template non-type parm TYPE is of an allowable
24481    type.  Return false for ok, true for disallowed.  Issue error and
24482    inform messages under control of COMPLAIN.  */
24483 
24484 static bool
invalid_nontype_parm_type_p(tree type,tsubst_flags_t complain)24485 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
24486 {
24487   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
24488     return false;
24489   else if (TYPE_PTR_P (type))
24490     return false;
24491   else if (TREE_CODE (type) == REFERENCE_TYPE
24492 	   && !TYPE_REF_IS_RVALUE (type))
24493     return false;
24494   else if (TYPE_PTRMEM_P (type))
24495     return false;
24496   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
24497     return false;
24498   else if (TREE_CODE (type) == TYPENAME_TYPE)
24499     return false;
24500   else if (TREE_CODE (type) == DECLTYPE_TYPE)
24501     return false;
24502   else if (TREE_CODE (type) == NULLPTR_TYPE)
24503     return false;
24504   /* A bound template template parm could later be instantiated to have a valid
24505      nontype parm type via an alias template.  */
24506   else if (cxx_dialect >= cxx11
24507 	   && TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
24508     return false;
24509 
24510   if (complain & tf_error)
24511     {
24512       if (type == error_mark_node)
24513 	inform (input_location, "invalid template non-type parameter");
24514       else
24515 	error ("%q#T is not a valid type for a template non-type parameter",
24516 	       type);
24517     }
24518   return true;
24519 }
24520 
24521 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
24522    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
24523 
24524 static bool
dependent_type_p_r(tree type)24525 dependent_type_p_r (tree type)
24526 {
24527   tree scope;
24528 
24529   /* [temp.dep.type]
24530 
24531      A type is dependent if it is:
24532 
24533      -- a template parameter. Template template parameters are types
24534 	for us (since TYPE_P holds true for them) so we handle
24535 	them here.  */
24536   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
24537       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
24538     return true;
24539   /* -- a qualified-id with a nested-name-specifier which contains a
24540 	class-name that names a dependent type or whose unqualified-id
24541 	names a dependent type.  */
24542   if (TREE_CODE (type) == TYPENAME_TYPE)
24543     return true;
24544 
24545   /* An alias template specialization can be dependent even if the
24546      resulting type is not.  */
24547   if (dependent_alias_template_spec_p (type))
24548     return true;
24549 
24550   /* -- a cv-qualified type where the cv-unqualified type is
24551 	dependent.
24552      No code is necessary for this bullet; the code below handles
24553      cv-qualified types, and we don't want to strip aliases with
24554      TYPE_MAIN_VARIANT because of DR 1558.  */
24555   /* -- a compound type constructed from any dependent type.  */
24556   if (TYPE_PTRMEM_P (type))
24557     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
24558 	    || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
24559 					   (type)));
24560   else if (TYPE_PTR_P (type)
24561 	   || TREE_CODE (type) == REFERENCE_TYPE)
24562     return dependent_type_p (TREE_TYPE (type));
24563   else if (TREE_CODE (type) == FUNCTION_TYPE
24564 	   || TREE_CODE (type) == METHOD_TYPE)
24565     {
24566       tree arg_type;
24567 
24568       if (dependent_type_p (TREE_TYPE (type)))
24569 	return true;
24570       for (arg_type = TYPE_ARG_TYPES (type);
24571 	   arg_type;
24572 	   arg_type = TREE_CHAIN (arg_type))
24573 	if (dependent_type_p (TREE_VALUE (arg_type)))
24574 	  return true;
24575       if (cxx_dialect >= cxx17)
24576 	/* A value-dependent noexcept-specifier makes the type dependent.  */
24577 	if (tree spec = TYPE_RAISES_EXCEPTIONS (type))
24578 	  if (tree noex = TREE_PURPOSE (spec))
24579 	    /* Treat DEFERRED_NOEXCEPT as non-dependent, since it doesn't
24580 	       affect overload resolution and treating it as dependent breaks
24581 	       things.  */
24582 	    if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
24583 		&& value_dependent_expression_p (noex))
24584 	      return true;
24585       return false;
24586     }
24587   /* -- an array type constructed from any dependent type or whose
24588 	size is specified by a constant expression that is
24589 	value-dependent.
24590 
24591         We checked for type- and value-dependence of the bounds in
24592         compute_array_index_type, so TYPE_DEPENDENT_P is already set.  */
24593   if (TREE_CODE (type) == ARRAY_TYPE)
24594     {
24595       if (TYPE_DOMAIN (type)
24596 	  && dependent_type_p (TYPE_DOMAIN (type)))
24597 	return true;
24598       return dependent_type_p (TREE_TYPE (type));
24599     }
24600 
24601   /* -- a template-id in which either the template name is a template
24602      parameter ...  */
24603   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
24604     return true;
24605   /* ... or any of the template arguments is a dependent type or
24606 	an expression that is type-dependent or value-dependent.  */
24607   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
24608 	   && (any_dependent_template_arguments_p
24609 	       (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
24610     return true;
24611 
24612   /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and UNDERLYING_TYPEs are
24613      dependent; if the argument of the `typeof' expression is not
24614      type-dependent, then it should already been have resolved.  */
24615   if (TREE_CODE (type) == TYPEOF_TYPE
24616       || TREE_CODE (type) == DECLTYPE_TYPE
24617       || TREE_CODE (type) == UNDERLYING_TYPE)
24618     return true;
24619 
24620   /* A template argument pack is dependent if any of its packed
24621      arguments are.  */
24622   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
24623     {
24624       tree args = ARGUMENT_PACK_ARGS (type);
24625       int i, len = TREE_VEC_LENGTH (args);
24626       for (i = 0; i < len; ++i)
24627         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
24628           return true;
24629     }
24630 
24631   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
24632      be template parameters.  */
24633   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
24634     return true;
24635 
24636   if (any_dependent_type_attributes_p (TYPE_ATTRIBUTES (type)))
24637     return true;
24638 
24639   /* The standard does not specifically mention types that are local
24640      to template functions or local classes, but they should be
24641      considered dependent too.  For example:
24642 
24643        template <int I> void f() {
24644 	 enum E { a = I };
24645 	 S<sizeof (E)> s;
24646        }
24647 
24648      The size of `E' cannot be known until the value of `I' has been
24649      determined.  Therefore, `E' must be considered dependent.  */
24650   scope = TYPE_CONTEXT (type);
24651   if (scope && TYPE_P (scope))
24652     return dependent_type_p (scope);
24653   /* Don't use type_dependent_expression_p here, as it can lead
24654      to infinite recursion trying to determine whether a lambda
24655      nested in a lambda is dependent (c++/47687).  */
24656   else if (scope && TREE_CODE (scope) == FUNCTION_DECL
24657 	   && DECL_LANG_SPECIFIC (scope)
24658 	   && DECL_TEMPLATE_INFO (scope)
24659 	   && (any_dependent_template_arguments_p
24660 	       (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
24661     return true;
24662 
24663   /* Other types are non-dependent.  */
24664   return false;
24665 }
24666 
24667 /* Returns TRUE if TYPE is dependent, in the sense of
24668    [temp.dep.type].  Note that a NULL type is considered dependent.  */
24669 
24670 bool
dependent_type_p(tree type)24671 dependent_type_p (tree type)
24672 {
24673   /* If there are no template parameters in scope, then there can't be
24674      any dependent types.  */
24675   if (!processing_template_decl)
24676     {
24677       /* If we are not processing a template, then nobody should be
24678 	 providing us with a dependent type.  */
24679       gcc_assert (type);
24680       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
24681       return false;
24682     }
24683 
24684   /* If the type is NULL, we have not computed a type for the entity
24685      in question; in that case, the type is dependent.  */
24686   if (!type)
24687     return true;
24688 
24689   /* Erroneous types can be considered non-dependent.  */
24690   if (type == error_mark_node)
24691     return false;
24692 
24693   /* Getting here with global_type_node means we improperly called this
24694      function on the TREE_TYPE of an IDENTIFIER_NODE.  */
24695   gcc_checking_assert (type != global_type_node);
24696 
24697   /* If we have not already computed the appropriate value for TYPE,
24698      do so now.  */
24699   if (!TYPE_DEPENDENT_P_VALID (type))
24700     {
24701       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
24702       TYPE_DEPENDENT_P_VALID (type) = 1;
24703     }
24704 
24705   return TYPE_DEPENDENT_P (type);
24706 }
24707 
24708 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
24709    lookup.  In other words, a dependent type that is not the current
24710    instantiation.  */
24711 
24712 bool
dependent_scope_p(tree scope)24713 dependent_scope_p (tree scope)
24714 {
24715   return (scope && TYPE_P (scope) && dependent_type_p (scope)
24716 	  && !currently_open_class (scope));
24717 }
24718 
24719 /* T is a SCOPE_REF.  Return whether it represents a non-static member of
24720    an unknown base of 'this' (and is therefore instantiation-dependent).  */
24721 
24722 static bool
unknown_base_ref_p(tree t)24723 unknown_base_ref_p (tree t)
24724 {
24725   if (!current_class_ptr)
24726     return false;
24727 
24728   tree mem = TREE_OPERAND (t, 1);
24729   if (shared_member_p (mem))
24730     return false;
24731 
24732   tree cur = current_nonlambda_class_type ();
24733   if (!any_dependent_bases_p (cur))
24734     return false;
24735 
24736   tree ctx = TREE_OPERAND (t, 0);
24737   if (DERIVED_FROM_P (ctx, cur))
24738     return false;
24739 
24740   return true;
24741 }
24742 
24743 /* T is a SCOPE_REF; return whether we need to consider it
24744     instantiation-dependent so that we can check access at instantiation
24745     time even though we know which member it resolves to.  */
24746 
24747 static bool
instantiation_dependent_scope_ref_p(tree t)24748 instantiation_dependent_scope_ref_p (tree t)
24749 {
24750   if (DECL_P (TREE_OPERAND (t, 1))
24751       && CLASS_TYPE_P (TREE_OPERAND (t, 0))
24752       && !unknown_base_ref_p (t)
24753       && accessible_in_template_p (TREE_OPERAND (t, 0),
24754 				   TREE_OPERAND (t, 1)))
24755     return false;
24756   else
24757     return true;
24758 }
24759 
24760 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
24761    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
24762    expression.  */
24763 
24764 /* Note that this predicate is not appropriate for general expressions;
24765    only constant expressions (that satisfy potential_constant_expression)
24766    can be tested for value dependence.  */
24767 
24768 bool
value_dependent_expression_p(tree expression)24769 value_dependent_expression_p (tree expression)
24770 {
24771   if (!processing_template_decl || expression == NULL_TREE)
24772     return false;
24773 
24774   /* A type-dependent expression is also value-dependent.  */
24775   if (type_dependent_expression_p (expression))
24776     return true;
24777 
24778   switch (TREE_CODE (expression))
24779     {
24780     case BASELINK:
24781       /* A dependent member function of the current instantiation.  */
24782       return dependent_type_p (BINFO_TYPE (BASELINK_BINFO (expression)));
24783 
24784     case FUNCTION_DECL:
24785       /* A dependent member function of the current instantiation.  */
24786       if (DECL_CLASS_SCOPE_P (expression)
24787 	  && dependent_type_p (DECL_CONTEXT (expression)))
24788 	return true;
24789       break;
24790 
24791     case IDENTIFIER_NODE:
24792       /* A name that has not been looked up -- must be dependent.  */
24793       return true;
24794 
24795     case TEMPLATE_PARM_INDEX:
24796       /* A non-type template parm.  */
24797       return true;
24798 
24799     case CONST_DECL:
24800       /* A non-type template parm.  */
24801       if (DECL_TEMPLATE_PARM_P (expression))
24802 	return true;
24803       return value_dependent_expression_p (DECL_INITIAL (expression));
24804 
24805     case VAR_DECL:
24806        /* A constant with literal type and is initialized
24807 	  with an expression that is value-dependent.  */
24808       if (DECL_DEPENDENT_INIT_P (expression)
24809 	  /* FIXME cp_finish_decl doesn't fold reference initializers.  */
24810 	  || TREE_CODE (TREE_TYPE (expression)) == REFERENCE_TYPE)
24811 	return true;
24812       if (DECL_HAS_VALUE_EXPR_P (expression))
24813 	{
24814 	  tree value_expr = DECL_VALUE_EXPR (expression);
24815 	  if (value_dependent_expression_p (value_expr))
24816 	    return true;
24817 	}
24818       return false;
24819 
24820     case DYNAMIC_CAST_EXPR:
24821     case STATIC_CAST_EXPR:
24822     case CONST_CAST_EXPR:
24823     case REINTERPRET_CAST_EXPR:
24824     case CAST_EXPR:
24825     case IMPLICIT_CONV_EXPR:
24826       /* These expressions are value-dependent if the type to which
24827 	 the cast occurs is dependent or the expression being casted
24828 	 is value-dependent.  */
24829       {
24830 	tree type = TREE_TYPE (expression);
24831 
24832 	if (dependent_type_p (type))
24833 	  return true;
24834 
24835 	/* A functional cast has a list of operands.  */
24836 	expression = TREE_OPERAND (expression, 0);
24837 	if (!expression)
24838 	  {
24839 	    /* If there are no operands, it must be an expression such
24840 	       as "int()". This should not happen for aggregate types
24841 	       because it would form non-constant expressions.  */
24842 	    gcc_assert (cxx_dialect >= cxx11
24843 			|| INTEGRAL_OR_ENUMERATION_TYPE_P (type));
24844 
24845 	    return false;
24846 	  }
24847 
24848 	if (TREE_CODE (expression) == TREE_LIST)
24849 	  return any_value_dependent_elements_p (expression);
24850 
24851 	return value_dependent_expression_p (expression);
24852       }
24853 
24854     case SIZEOF_EXPR:
24855       if (SIZEOF_EXPR_TYPE_P (expression))
24856 	return dependent_type_p (TREE_TYPE (TREE_OPERAND (expression, 0)));
24857       /* FALLTHRU */
24858     case ALIGNOF_EXPR:
24859     case TYPEID_EXPR:
24860       /* A `sizeof' expression is value-dependent if the operand is
24861 	 type-dependent or is a pack expansion.  */
24862       expression = TREE_OPERAND (expression, 0);
24863       if (PACK_EXPANSION_P (expression))
24864         return true;
24865       else if (TYPE_P (expression))
24866 	return dependent_type_p (expression);
24867       return instantiation_dependent_uneval_expression_p (expression);
24868 
24869     case AT_ENCODE_EXPR:
24870       /* An 'encode' expression is value-dependent if the operand is
24871 	 type-dependent.  */
24872       expression = TREE_OPERAND (expression, 0);
24873       return dependent_type_p (expression);
24874 
24875     case NOEXCEPT_EXPR:
24876       expression = TREE_OPERAND (expression, 0);
24877       return instantiation_dependent_uneval_expression_p (expression);
24878 
24879     case SCOPE_REF:
24880       /* All instantiation-dependent expressions should also be considered
24881 	 value-dependent.  */
24882       return instantiation_dependent_scope_ref_p (expression);
24883 
24884     case COMPONENT_REF:
24885       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
24886 	      || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
24887 
24888     case NONTYPE_ARGUMENT_PACK:
24889       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
24890          is value-dependent.  */
24891       {
24892         tree values = ARGUMENT_PACK_ARGS (expression);
24893         int i, len = TREE_VEC_LENGTH (values);
24894 
24895         for (i = 0; i < len; ++i)
24896           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
24897             return true;
24898 
24899         return false;
24900       }
24901 
24902     case TRAIT_EXPR:
24903       {
24904 	tree type2 = TRAIT_EXPR_TYPE2 (expression);
24905 
24906 	if (dependent_type_p (TRAIT_EXPR_TYPE1 (expression)))
24907 	  return true;
24908 
24909 	if (!type2)
24910 	  return false;
24911 
24912 	if (TREE_CODE (type2) != TREE_LIST)
24913 	  return dependent_type_p (type2);
24914 
24915 	for (; type2; type2 = TREE_CHAIN (type2))
24916 	  if (dependent_type_p (TREE_VALUE (type2)))
24917 	    return true;
24918 
24919 	return false;
24920       }
24921 
24922     case MODOP_EXPR:
24923       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
24924 	      || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
24925 
24926     case ARRAY_REF:
24927       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
24928 	      || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
24929 
24930     case ADDR_EXPR:
24931       {
24932 	tree op = TREE_OPERAND (expression, 0);
24933 	return (value_dependent_expression_p (op)
24934 		|| has_value_dependent_address (op));
24935       }
24936 
24937     case REQUIRES_EXPR:
24938       /* Treat all requires-expressions as value-dependent so
24939          we don't try to fold them.  */
24940       return true;
24941 
24942     case TYPE_REQ:
24943       return dependent_type_p (TREE_OPERAND (expression, 0));
24944 
24945     case CALL_EXPR:
24946       {
24947 	if (value_dependent_expression_p (CALL_EXPR_FN (expression)))
24948 	  return true;
24949 	tree fn = get_callee_fndecl (expression);
24950 	int i, nargs;
24951 	nargs = call_expr_nargs (expression);
24952 	for (i = 0; i < nargs; ++i)
24953 	  {
24954 	    tree op = CALL_EXPR_ARG (expression, i);
24955 	    /* In a call to a constexpr member function, look through the
24956 	       implicit ADDR_EXPR on the object argument so that it doesn't
24957 	       cause the call to be considered value-dependent.  We also
24958 	       look through it in potential_constant_expression.  */
24959 	    if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
24960 		&& DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
24961 		&& TREE_CODE (op) == ADDR_EXPR)
24962 	      op = TREE_OPERAND (op, 0);
24963 	    if (value_dependent_expression_p (op))
24964 	      return true;
24965 	  }
24966 	return false;
24967       }
24968 
24969     case TEMPLATE_ID_EXPR:
24970       return variable_concept_p (TREE_OPERAND (expression, 0));
24971 
24972     case CONSTRUCTOR:
24973       {
24974 	unsigned ix;
24975 	tree val;
24976 	if (dependent_type_p (TREE_TYPE (expression)))
24977 	  return true;
24978 	FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
24979 	  if (value_dependent_expression_p (val))
24980 	    return true;
24981 	return false;
24982       }
24983 
24984     case STMT_EXPR:
24985       /* Treat a GNU statement expression as dependent to avoid crashing
24986 	 under instantiate_non_dependent_expr; it can't be constant.  */
24987       return true;
24988 
24989     default:
24990       /* A constant expression is value-dependent if any subexpression is
24991 	 value-dependent.  */
24992       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
24993 	{
24994 	case tcc_reference:
24995 	case tcc_unary:
24996 	case tcc_comparison:
24997 	case tcc_binary:
24998 	case tcc_expression:
24999 	case tcc_vl_exp:
25000 	  {
25001 	    int i, len = cp_tree_operand_length (expression);
25002 
25003 	    for (i = 0; i < len; i++)
25004 	      {
25005 		tree t = TREE_OPERAND (expression, i);
25006 
25007 		/* In some cases, some of the operands may be missing.
25008 		   (For example, in the case of PREDECREMENT_EXPR, the
25009 		   amount to increment by may be missing.)  That doesn't
25010 		   make the expression dependent.  */
25011 		if (t && value_dependent_expression_p (t))
25012 		  return true;
25013 	      }
25014 	  }
25015 	  break;
25016 	default:
25017 	  break;
25018 	}
25019       break;
25020     }
25021 
25022   /* The expression is not value-dependent.  */
25023   return false;
25024 }
25025 
25026 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
25027    [temp.dep.expr].  Note that an expression with no type is
25028    considered dependent.  Other parts of the compiler arrange for an
25029    expression with type-dependent subexpressions to have no type, so
25030    this function doesn't have to be fully recursive.  */
25031 
25032 bool
type_dependent_expression_p(tree expression)25033 type_dependent_expression_p (tree expression)
25034 {
25035   if (!processing_template_decl)
25036     return false;
25037 
25038   if (expression == NULL_TREE || expression == error_mark_node)
25039     return false;
25040 
25041   STRIP_ANY_LOCATION_WRAPPER (expression);
25042 
25043   /* An unresolved name is always dependent.  */
25044   if (identifier_p (expression)
25045       || TREE_CODE (expression) == USING_DECL
25046       || TREE_CODE (expression) == WILDCARD_DECL)
25047     return true;
25048 
25049   /* A fold expression is type-dependent. */
25050   if (TREE_CODE (expression) == UNARY_LEFT_FOLD_EXPR
25051       || TREE_CODE (expression) == UNARY_RIGHT_FOLD_EXPR
25052       || TREE_CODE (expression) == BINARY_LEFT_FOLD_EXPR
25053       || TREE_CODE (expression) == BINARY_RIGHT_FOLD_EXPR)
25054     return true;
25055 
25056   /* Some expression forms are never type-dependent.  */
25057   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
25058       || TREE_CODE (expression) == SIZEOF_EXPR
25059       || TREE_CODE (expression) == ALIGNOF_EXPR
25060       || TREE_CODE (expression) == AT_ENCODE_EXPR
25061       || TREE_CODE (expression) == NOEXCEPT_EXPR
25062       || TREE_CODE (expression) == TRAIT_EXPR
25063       || TREE_CODE (expression) == TYPEID_EXPR
25064       || TREE_CODE (expression) == DELETE_EXPR
25065       || TREE_CODE (expression) == VEC_DELETE_EXPR
25066       || TREE_CODE (expression) == THROW_EXPR
25067       || TREE_CODE (expression) == REQUIRES_EXPR)
25068     return false;
25069 
25070   /* The types of these expressions depends only on the type to which
25071      the cast occurs.  */
25072   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
25073       || TREE_CODE (expression) == STATIC_CAST_EXPR
25074       || TREE_CODE (expression) == CONST_CAST_EXPR
25075       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
25076       || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
25077       || TREE_CODE (expression) == CAST_EXPR)
25078     return dependent_type_p (TREE_TYPE (expression));
25079 
25080   /* The types of these expressions depends only on the type created
25081      by the expression.  */
25082   if (TREE_CODE (expression) == NEW_EXPR
25083       || TREE_CODE (expression) == VEC_NEW_EXPR)
25084     {
25085       /* For NEW_EXPR tree nodes created inside a template, either
25086 	 the object type itself or a TREE_LIST may appear as the
25087 	 operand 1.  */
25088       tree type = TREE_OPERAND (expression, 1);
25089       if (TREE_CODE (type) == TREE_LIST)
25090 	/* This is an array type.  We need to check array dimensions
25091 	   as well.  */
25092 	return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
25093 	       || value_dependent_expression_p
25094 		    (TREE_OPERAND (TREE_VALUE (type), 1));
25095       else
25096 	return dependent_type_p (type);
25097     }
25098 
25099   if (TREE_CODE (expression) == SCOPE_REF)
25100     {
25101       tree scope = TREE_OPERAND (expression, 0);
25102       tree name = TREE_OPERAND (expression, 1);
25103 
25104       /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
25105 	 contains an identifier associated by name lookup with one or more
25106 	 declarations declared with a dependent type, or...a
25107 	 nested-name-specifier or qualified-id that names a member of an
25108 	 unknown specialization.  */
25109       return (type_dependent_expression_p (name)
25110 	      || dependent_scope_p (scope));
25111     }
25112 
25113   if (TREE_CODE (expression) == TEMPLATE_DECL
25114       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
25115     return uses_outer_template_parms (expression);
25116 
25117   if (TREE_CODE (expression) == STMT_EXPR)
25118     expression = stmt_expr_value_expr (expression);
25119 
25120   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
25121     {
25122       tree elt;
25123       unsigned i;
25124 
25125       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
25126 	{
25127 	  if (type_dependent_expression_p (elt))
25128 	    return true;
25129 	}
25130       return false;
25131     }
25132 
25133   /* A static data member of the current instantiation with incomplete
25134      array type is type-dependent, as the definition and specializations
25135      can have different bounds.  */
25136   if (VAR_P (expression)
25137       && DECL_CLASS_SCOPE_P (expression)
25138       && dependent_type_p (DECL_CONTEXT (expression))
25139       && VAR_HAD_UNKNOWN_BOUND (expression))
25140     return true;
25141 
25142   /* An array of unknown bound depending on a variadic parameter, eg:
25143 
25144      template<typename... Args>
25145        void foo (Args... args)
25146        {
25147          int arr[] = { args... };
25148        }
25149 
25150      template<int... vals>
25151        void bar ()
25152        {
25153          int arr[] = { vals... };
25154        }
25155 
25156      If the array has no length and has an initializer, it must be that
25157      we couldn't determine its length in cp_complete_array_type because
25158      it is dependent.  */
25159   if (VAR_P (expression)
25160       && TREE_TYPE (expression) != NULL_TREE
25161       && TREE_CODE (TREE_TYPE (expression)) == ARRAY_TYPE
25162       && !TYPE_DOMAIN (TREE_TYPE (expression))
25163       && DECL_INITIAL (expression))
25164    return true;
25165 
25166   /* A function or variable template-id is type-dependent if it has any
25167      dependent template arguments.  */
25168   if (VAR_OR_FUNCTION_DECL_P (expression)
25169       && DECL_LANG_SPECIFIC (expression)
25170       && DECL_TEMPLATE_INFO (expression))
25171     {
25172       /* Consider the innermost template arguments, since those are the ones
25173 	 that come from the template-id; the template arguments for the
25174 	 enclosing class do not make it type-dependent unless they are used in
25175 	 the type of the decl.  */
25176       if (PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (expression))
25177 	  && (any_dependent_template_arguments_p
25178 	      (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
25179 	return true;
25180     }
25181 
25182   /* Otherwise, if the function decl isn't from a dependent scope, it can't be
25183      type-dependent.  Checking this is important for functions with auto return
25184      type, which looks like a dependent type.  */
25185   if (TREE_CODE (expression) == FUNCTION_DECL
25186       && !(DECL_CLASS_SCOPE_P (expression)
25187 	   && dependent_type_p (DECL_CONTEXT (expression)))
25188       && !(DECL_LANG_SPECIFIC (expression)
25189 	   && DECL_FRIEND_P (expression)
25190 	   && (!DECL_FRIEND_CONTEXT (expression)
25191 	       || dependent_type_p (DECL_FRIEND_CONTEXT (expression))))
25192       && !DECL_LOCAL_FUNCTION_P (expression))
25193     {
25194       gcc_assert (!dependent_type_p (TREE_TYPE (expression))
25195 		  || undeduced_auto_decl (expression));
25196       return false;
25197     }
25198 
25199   /* Always dependent, on the number of arguments if nothing else.  */
25200   if (TREE_CODE (expression) == EXPR_PACK_EXPANSION)
25201     return true;
25202 
25203   if (TREE_TYPE (expression) == unknown_type_node)
25204     {
25205       if (TREE_CODE (expression) == ADDR_EXPR)
25206 	return type_dependent_expression_p (TREE_OPERAND (expression, 0));
25207       if (TREE_CODE (expression) == COMPONENT_REF
25208 	  || TREE_CODE (expression) == OFFSET_REF)
25209 	{
25210 	  if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
25211 	    return true;
25212 	  expression = TREE_OPERAND (expression, 1);
25213 	  if (identifier_p (expression))
25214 	    return false;
25215 	}
25216       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
25217       if (TREE_CODE (expression) == SCOPE_REF)
25218 	return false;
25219 
25220       if (BASELINK_P (expression))
25221 	{
25222 	  if (BASELINK_OPTYPE (expression)
25223 	      && dependent_type_p (BASELINK_OPTYPE (expression)))
25224 	    return true;
25225 	  expression = BASELINK_FUNCTIONS (expression);
25226 	}
25227 
25228       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
25229 	{
25230 	  if (any_dependent_template_arguments_p
25231 	      (TREE_OPERAND (expression, 1)))
25232 	    return true;
25233 	  expression = TREE_OPERAND (expression, 0);
25234 	  if (identifier_p (expression))
25235 	    return true;
25236 	}
25237 
25238       gcc_assert (TREE_CODE (expression) == OVERLOAD
25239 		  || TREE_CODE (expression) == FUNCTION_DECL);
25240 
25241       for (lkp_iterator iter (expression); iter; ++iter)
25242 	if (type_dependent_expression_p (*iter))
25243 	  return true;
25244 
25245       return false;
25246     }
25247 
25248   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
25249 
25250   /* Dependent type attributes might not have made it from the decl to
25251      the type yet.  */
25252   if (DECL_P (expression)
25253       && any_dependent_type_attributes_p (DECL_ATTRIBUTES (expression)))
25254     return true;
25255 
25256   return (dependent_type_p (TREE_TYPE (expression)));
25257 }
25258 
25259 /* [temp.dep.expr]/5: A class member access expression (5.2.5) is
25260    type-dependent if the expression refers to a member of the current
25261    instantiation and the type of the referenced member is dependent, or the
25262    class member access expression refers to a member of an unknown
25263    specialization.
25264 
25265    This function returns true if the OBJECT in such a class member access
25266    expression is of an unknown specialization.  */
25267 
25268 bool
type_dependent_object_expression_p(tree object)25269 type_dependent_object_expression_p (tree object)
25270 {
25271   /* An IDENTIFIER_NODE can sometimes have a TREE_TYPE, but it's still
25272      dependent.  */
25273   if (TREE_CODE (object) == IDENTIFIER_NODE)
25274     return true;
25275   tree scope = TREE_TYPE (object);
25276   return (!scope || dependent_scope_p (scope));
25277 }
25278 
25279 /* walk_tree callback function for instantiation_dependent_expression_p,
25280    below.  Returns non-zero if a dependent subexpression is found.  */
25281 
25282 static tree
instantiation_dependent_r(tree * tp,int * walk_subtrees,void *)25283 instantiation_dependent_r (tree *tp, int *walk_subtrees,
25284 			   void * /*data*/)
25285 {
25286   if (TYPE_P (*tp))
25287     {
25288       /* We don't have to worry about decltype currently because decltype
25289 	 of an instantiation-dependent expr is a dependent type.  This
25290 	 might change depending on the resolution of DR 1172.  */
25291       *walk_subtrees = false;
25292       return NULL_TREE;
25293     }
25294   enum tree_code code = TREE_CODE (*tp);
25295   switch (code)
25296     {
25297       /* Don't treat an argument list as dependent just because it has no
25298 	 TREE_TYPE.  */
25299     case TREE_LIST:
25300     case TREE_VEC:
25301     case NONTYPE_ARGUMENT_PACK:
25302       return NULL_TREE;
25303 
25304     case TEMPLATE_PARM_INDEX:
25305       return *tp;
25306 
25307       /* Handle expressions with type operands.  */
25308     case SIZEOF_EXPR:
25309     case ALIGNOF_EXPR:
25310     case TYPEID_EXPR:
25311     case AT_ENCODE_EXPR:
25312       {
25313 	tree op = TREE_OPERAND (*tp, 0);
25314 	if (code == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (*tp))
25315 	  op = TREE_TYPE (op);
25316 	if (TYPE_P (op))
25317 	  {
25318 	    if (dependent_type_p (op))
25319 	      return *tp;
25320 	    else
25321 	      {
25322 		*walk_subtrees = false;
25323 		return NULL_TREE;
25324 	      }
25325 	  }
25326 	break;
25327       }
25328 
25329     case COMPONENT_REF:
25330       if (identifier_p (TREE_OPERAND (*tp, 1)))
25331 	/* In a template, finish_class_member_access_expr creates a
25332 	   COMPONENT_REF with an IDENTIFIER_NODE for op1 even if it isn't
25333 	   type-dependent, so that we can check access control at
25334 	   instantiation time (PR 42277).  See also Core issue 1273.  */
25335 	return *tp;
25336       break;
25337 
25338     case SCOPE_REF:
25339       if (instantiation_dependent_scope_ref_p (*tp))
25340 	return *tp;
25341       else
25342 	break;
25343 
25344       /* Treat statement-expressions as dependent.  */
25345     case BIND_EXPR:
25346       return *tp;
25347 
25348       /* Treat requires-expressions as dependent. */
25349     case REQUIRES_EXPR:
25350       return *tp;
25351 
25352     case CALL_EXPR:
25353       /* Treat calls to function concepts as dependent. */
25354       if (function_concept_check_p (*tp))
25355         return *tp;
25356       break;
25357 
25358     case TEMPLATE_ID_EXPR:
25359       /* And variable concepts.  */
25360       if (variable_concept_p (TREE_OPERAND (*tp, 0)))
25361 	return *tp;
25362       break;
25363 
25364     default:
25365       break;
25366     }
25367 
25368   if (type_dependent_expression_p (*tp))
25369     return *tp;
25370   else
25371     return NULL_TREE;
25372 }
25373 
25374 /* Returns TRUE if the EXPRESSION is instantiation-dependent, in the
25375    sense defined by the ABI:
25376 
25377    "An expression is instantiation-dependent if it is type-dependent
25378    or value-dependent, or it has a subexpression that is type-dependent
25379    or value-dependent."
25380 
25381    Except don't actually check value-dependence for unevaluated expressions,
25382    because in sizeof(i) we don't care about the value of i.  Checking
25383    type-dependence will in turn check value-dependence of array bounds/template
25384    arguments as needed.  */
25385 
25386 bool
instantiation_dependent_uneval_expression_p(tree expression)25387 instantiation_dependent_uneval_expression_p (tree expression)
25388 {
25389   tree result;
25390 
25391   if (!processing_template_decl)
25392     return false;
25393 
25394   if (expression == error_mark_node)
25395     return false;
25396 
25397   result = cp_walk_tree_without_duplicates (&expression,
25398 					    instantiation_dependent_r, NULL);
25399   return result != NULL_TREE;
25400 }
25401 
25402 /* As above, but also check value-dependence of the expression as a whole.  */
25403 
25404 bool
instantiation_dependent_expression_p(tree expression)25405 instantiation_dependent_expression_p (tree expression)
25406 {
25407   return (instantiation_dependent_uneval_expression_p (expression)
25408 	  || value_dependent_expression_p (expression));
25409 }
25410 
25411 /* Like type_dependent_expression_p, but it also works while not processing
25412    a template definition, i.e. during substitution or mangling.  */
25413 
25414 bool
type_dependent_expression_p_push(tree expr)25415 type_dependent_expression_p_push (tree expr)
25416 {
25417   bool b;
25418   ++processing_template_decl;
25419   b = type_dependent_expression_p (expr);
25420   --processing_template_decl;
25421   return b;
25422 }
25423 
25424 /* Returns TRUE if ARGS contains a type-dependent expression.  */
25425 
25426 bool
any_type_dependent_arguments_p(const vec<tree,va_gc> * args)25427 any_type_dependent_arguments_p (const vec<tree, va_gc> *args)
25428 {
25429   unsigned int i;
25430   tree arg;
25431 
25432   FOR_EACH_VEC_SAFE_ELT (args, i, arg)
25433     {
25434       if (type_dependent_expression_p (arg))
25435 	return true;
25436     }
25437   return false;
25438 }
25439 
25440 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
25441    expressions) contains any type-dependent expressions.  */
25442 
25443 bool
any_type_dependent_elements_p(const_tree list)25444 any_type_dependent_elements_p (const_tree list)
25445 {
25446   for (; list; list = TREE_CHAIN (list))
25447     if (type_dependent_expression_p (TREE_VALUE (list)))
25448       return true;
25449 
25450   return false;
25451 }
25452 
25453 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
25454    expressions) contains any value-dependent expressions.  */
25455 
25456 bool
any_value_dependent_elements_p(const_tree list)25457 any_value_dependent_elements_p (const_tree list)
25458 {
25459   for (; list; list = TREE_CHAIN (list))
25460     if (value_dependent_expression_p (TREE_VALUE (list)))
25461       return true;
25462 
25463   return false;
25464 }
25465 
25466 /* Returns TRUE if the ARG (a template argument) is dependent.  */
25467 
25468 bool
dependent_template_arg_p(tree arg)25469 dependent_template_arg_p (tree arg)
25470 {
25471   if (!processing_template_decl)
25472     return false;
25473 
25474   /* Assume a template argument that was wrongly written by the user
25475      is dependent. This is consistent with what
25476      any_dependent_template_arguments_p [that calls this function]
25477      does.  */
25478   if (!arg || arg == error_mark_node)
25479     return true;
25480 
25481   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
25482     arg = argument_pack_select_arg (arg);
25483 
25484   if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
25485     return true;
25486   if (TREE_CODE (arg) == TEMPLATE_DECL)
25487     {
25488       if (DECL_TEMPLATE_PARM_P (arg))
25489 	return true;
25490       /* A member template of a dependent class is not necessarily
25491 	 type-dependent, but it is a dependent template argument because it
25492 	 will be a member of an unknown specialization to that template.  */
25493       tree scope = CP_DECL_CONTEXT (arg);
25494       return TYPE_P (scope) && dependent_type_p (scope);
25495     }
25496   else if (ARGUMENT_PACK_P (arg))
25497     {
25498       tree args = ARGUMENT_PACK_ARGS (arg);
25499       int i, len = TREE_VEC_LENGTH (args);
25500       for (i = 0; i < len; ++i)
25501         {
25502           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
25503             return true;
25504         }
25505 
25506       return false;
25507     }
25508   else if (TYPE_P (arg))
25509     return dependent_type_p (arg);
25510   else
25511     return (type_dependent_expression_p (arg)
25512 	    || value_dependent_expression_p (arg));
25513 }
25514 
25515 /* Returns true if ARGS (a collection of template arguments) contains
25516    any types that require structural equality testing.  */
25517 
25518 bool
any_template_arguments_need_structural_equality_p(tree args)25519 any_template_arguments_need_structural_equality_p (tree args)
25520 {
25521   int i;
25522   int j;
25523 
25524   if (!args)
25525     return false;
25526   if (args == error_mark_node)
25527     return true;
25528 
25529   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
25530     {
25531       tree level = TMPL_ARGS_LEVEL (args, i + 1);
25532       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
25533 	{
25534 	  tree arg = TREE_VEC_ELT (level, j);
25535 	  tree packed_args = NULL_TREE;
25536 	  int k, len = 1;
25537 
25538 	  if (ARGUMENT_PACK_P (arg))
25539 	    {
25540 	      /* Look inside the argument pack.  */
25541 	      packed_args = ARGUMENT_PACK_ARGS (arg);
25542 	      len = TREE_VEC_LENGTH (packed_args);
25543 	    }
25544 
25545 	  for (k = 0; k < len; ++k)
25546 	    {
25547 	      if (packed_args)
25548 		arg = TREE_VEC_ELT (packed_args, k);
25549 
25550 	      if (error_operand_p (arg))
25551 		return true;
25552 	      else if (TREE_CODE (arg) == TEMPLATE_DECL)
25553 		continue;
25554 	      else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
25555 		return true;
25556 	      else if (!TYPE_P (arg) && TREE_TYPE (arg)
25557 		       && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
25558 		return true;
25559 	    }
25560 	}
25561     }
25562 
25563   return false;
25564 }
25565 
25566 /* Returns true if ARGS (a collection of template arguments) contains
25567    any dependent arguments.  */
25568 
25569 bool
any_dependent_template_arguments_p(const_tree args)25570 any_dependent_template_arguments_p (const_tree args)
25571 {
25572   int i;
25573   int j;
25574 
25575   if (!args)
25576     return false;
25577   if (args == error_mark_node)
25578     return true;
25579 
25580   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
25581     {
25582       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
25583       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
25584 	if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
25585 	  return true;
25586     }
25587 
25588   return false;
25589 }
25590 
25591 /* Returns true if ARGS contains any errors.  */
25592 
25593 bool
any_erroneous_template_args_p(const_tree args)25594 any_erroneous_template_args_p (const_tree args)
25595 {
25596   int i;
25597   int j;
25598 
25599   if (args == error_mark_node)
25600     return true;
25601 
25602   if (args && TREE_CODE (args) != TREE_VEC)
25603     {
25604       if (tree ti = get_template_info (args))
25605 	args = TI_ARGS (ti);
25606       else
25607 	args = NULL_TREE;
25608     }
25609 
25610   if (!args)
25611     return false;
25612 
25613   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
25614     {
25615       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
25616       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
25617 	if (error_operand_p (TREE_VEC_ELT (level, j)))
25618 	  return true;
25619     }
25620 
25621   return false;
25622 }
25623 
25624 /* Returns TRUE if the template TMPL is type-dependent.  */
25625 
25626 bool
dependent_template_p(tree tmpl)25627 dependent_template_p (tree tmpl)
25628 {
25629   if (TREE_CODE (tmpl) == OVERLOAD)
25630     {
25631       for (lkp_iterator iter (tmpl); iter; ++iter)
25632 	if (dependent_template_p (*iter))
25633 	  return true;
25634       return false;
25635     }
25636 
25637   /* Template template parameters are dependent.  */
25638   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
25639       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
25640     return true;
25641   /* So are names that have not been looked up.  */
25642   if (TREE_CODE (tmpl) == SCOPE_REF || identifier_p (tmpl))
25643     return true;
25644   return false;
25645 }
25646 
25647 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
25648 
25649 bool
dependent_template_id_p(tree tmpl,tree args)25650 dependent_template_id_p (tree tmpl, tree args)
25651 {
25652   return (dependent_template_p (tmpl)
25653 	  || any_dependent_template_arguments_p (args));
25654 }
25655 
25656 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
25657    are dependent.  */
25658 
25659 bool
dependent_omp_for_p(tree declv,tree initv,tree condv,tree incrv)25660 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
25661 {
25662   int i;
25663 
25664   if (!processing_template_decl)
25665     return false;
25666 
25667   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
25668     {
25669       tree decl = TREE_VEC_ELT (declv, i);
25670       tree init = TREE_VEC_ELT (initv, i);
25671       tree cond = TREE_VEC_ELT (condv, i);
25672       tree incr = TREE_VEC_ELT (incrv, i);
25673 
25674       if (type_dependent_expression_p (decl)
25675 	  || TREE_CODE (decl) == SCOPE_REF)
25676 	return true;
25677 
25678       if (init && type_dependent_expression_p (init))
25679 	return true;
25680 
25681       if (type_dependent_expression_p (cond))
25682 	return true;
25683 
25684       if (COMPARISON_CLASS_P (cond)
25685 	  && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
25686 	      || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
25687 	return true;
25688 
25689       if (TREE_CODE (incr) == MODOP_EXPR)
25690 	{
25691 	  if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
25692 	      || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
25693 	    return true;
25694 	}
25695       else if (type_dependent_expression_p (incr))
25696 	return true;
25697       else if (TREE_CODE (incr) == MODIFY_EXPR)
25698 	{
25699 	  if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
25700 	    return true;
25701 	  else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
25702 	    {
25703 	      tree t = TREE_OPERAND (incr, 1);
25704 	      if (type_dependent_expression_p (TREE_OPERAND (t, 0))
25705 		  || type_dependent_expression_p (TREE_OPERAND (t, 1)))
25706 		return true;
25707 	    }
25708 	}
25709     }
25710 
25711   return false;
25712 }
25713 
25714 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
25715    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
25716    no such TYPE can be found.  Note that this function peers inside
25717    uninstantiated templates and therefore should be used only in
25718    extremely limited situations.  ONLY_CURRENT_P restricts this
25719    peering to the currently open classes hierarchy (which is required
25720    when comparing types).  */
25721 
25722 tree
resolve_typename_type(tree type,bool only_current_p)25723 resolve_typename_type (tree type, bool only_current_p)
25724 {
25725   tree scope;
25726   tree name;
25727   tree decl;
25728   int quals;
25729   tree pushed_scope;
25730   tree result;
25731 
25732   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
25733 
25734   scope = TYPE_CONTEXT (type);
25735   /* We shouldn't have built a TYPENAME_TYPE with a non-dependent scope.  */
25736   gcc_checking_assert (uses_template_parms (scope));
25737 
25738   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
25739      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
25740      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
25741      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
25742      identifier  of the TYPENAME_TYPE anymore.
25743      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
25744      TYPENAME_TYPE instead, we avoid messing up with a possible
25745      typedef variant case.  */
25746   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
25747 
25748   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
25749      it first before we can figure out what NAME refers to.  */
25750   if (TREE_CODE (scope) == TYPENAME_TYPE)
25751     {
25752       if (TYPENAME_IS_RESOLVING_P (scope))
25753 	/* Given a class template A with a dependent base with nested type C,
25754 	   typedef typename A::C::C C will land us here, as trying to resolve
25755 	   the initial A::C leads to the local C typedef, which leads back to
25756 	   A::C::C.  So we break the recursion now.  */
25757 	return type;
25758       else
25759 	scope = resolve_typename_type (scope, only_current_p);
25760     }
25761   /* If we don't know what SCOPE refers to, then we cannot resolve the
25762      TYPENAME_TYPE.  */
25763   if (!CLASS_TYPE_P (scope))
25764     return type;
25765   /* If this is a typedef, we don't want to look inside (c++/11987).  */
25766   if (typedef_variant_p (type))
25767     return type;
25768   /* If SCOPE isn't the template itself, it will not have a valid
25769      TYPE_FIELDS list.  */
25770   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
25771     /* scope is either the template itself or a compatible instantiation
25772        like X<T>, so look up the name in the original template.  */
25773     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
25774   /* If scope has no fields, it can't be a current instantiation.  Check this
25775      before currently_open_class to avoid infinite recursion (71515).  */
25776   if (!TYPE_FIELDS (scope))
25777     return type;
25778   /* If the SCOPE is not the current instantiation, there's no reason
25779      to look inside it.  */
25780   if (only_current_p && !currently_open_class (scope))
25781     return type;
25782   /* Enter the SCOPE so that name lookup will be resolved as if we
25783      were in the class definition.  In particular, SCOPE will no
25784      longer be considered a dependent type.  */
25785   pushed_scope = push_scope (scope);
25786   /* Look up the declaration.  */
25787   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true,
25788 			tf_warning_or_error);
25789 
25790   result = NULL_TREE;
25791 
25792   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
25793      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
25794   tree fullname = TYPENAME_TYPE_FULLNAME (type);
25795   if (!decl)
25796     /*nop*/;
25797   else if (identifier_p (fullname)
25798 	   && TREE_CODE (decl) == TYPE_DECL)
25799     {
25800       result = TREE_TYPE (decl);
25801       if (result == error_mark_node)
25802 	result = NULL_TREE;
25803     }
25804   else if (TREE_CODE (fullname) == TEMPLATE_ID_EXPR
25805 	   && DECL_CLASS_TEMPLATE_P (decl))
25806     {
25807       /* Obtain the template and the arguments.  */
25808       tree tmpl = TREE_OPERAND (fullname, 0);
25809       if (TREE_CODE (tmpl) == IDENTIFIER_NODE)
25810 	{
25811 	  /* We get here with a plain identifier because a previous tentative
25812 	     parse of the nested-name-specifier as part of a ptr-operator saw
25813 	     ::template X<A>.  The use of ::template is necessary in a
25814 	     ptr-operator, but wrong in a declarator-id.
25815 
25816 	     [temp.names]: In a qualified-id of a declarator-id, the keyword
25817 	     template shall not appear at the top level.  */
25818 	  pedwarn (EXPR_LOC_OR_LOC (fullname, input_location), OPT_Wpedantic,
25819 		   "keyword %<template%> not allowed in declarator-id");
25820 	  tmpl = decl;
25821 	}
25822       tree args = TREE_OPERAND (fullname, 1);
25823       /* Instantiate the template.  */
25824       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
25825 				      /*entering_scope=*/true,
25826 				      tf_error | tf_user);
25827       if (result == error_mark_node)
25828 	result = NULL_TREE;
25829     }
25830 
25831   /* Leave the SCOPE.  */
25832   if (pushed_scope)
25833     pop_scope (pushed_scope);
25834 
25835   /* If we failed to resolve it, return the original typename.  */
25836   if (!result)
25837     return type;
25838 
25839   /* If lookup found a typename type, resolve that too.  */
25840   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
25841     {
25842       /* Ill-formed programs can cause infinite recursion here, so we
25843 	 must catch that.  */
25844       TYPENAME_IS_RESOLVING_P (result) = 1;
25845       result = resolve_typename_type (result, only_current_p);
25846       TYPENAME_IS_RESOLVING_P (result) = 0;
25847     }
25848 
25849   /* Qualify the resulting type.  */
25850   quals = cp_type_quals (type);
25851   if (quals)
25852     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
25853 
25854   return result;
25855 }
25856 
25857 /* EXPR is an expression which is not type-dependent.  Return a proxy
25858    for EXPR that can be used to compute the types of larger
25859    expressions containing EXPR.  */
25860 
25861 tree
build_non_dependent_expr(tree expr)25862 build_non_dependent_expr (tree expr)
25863 {
25864   tree orig_expr = expr;
25865   tree inner_expr;
25866 
25867   /* When checking, try to get a constant value for all non-dependent
25868      expressions in order to expose bugs in *_dependent_expression_p
25869      and constexpr.  This can affect code generation, see PR70704, so
25870      only do this for -fchecking=2.  */
25871   if (flag_checking > 1
25872       && cxx_dialect >= cxx11
25873       /* Don't do this during nsdmi parsing as it can lead to
25874 	 unexpected recursive instantiations.  */
25875       && !parsing_nsdmi ()
25876       /* Don't do this during concept expansion either and for
25877          the same reason.  */
25878       && !expanding_concept ())
25879     fold_non_dependent_expr (expr);
25880 
25881   STRIP_ANY_LOCATION_WRAPPER (expr);
25882 
25883   /* Preserve OVERLOADs; the functions must be available to resolve
25884      types.  */
25885   inner_expr = expr;
25886   if (TREE_CODE (inner_expr) == STMT_EXPR)
25887     inner_expr = stmt_expr_value_expr (inner_expr);
25888   if (TREE_CODE (inner_expr) == ADDR_EXPR)
25889     inner_expr = TREE_OPERAND (inner_expr, 0);
25890   if (TREE_CODE (inner_expr) == COMPONENT_REF)
25891     inner_expr = TREE_OPERAND (inner_expr, 1);
25892   if (is_overloaded_fn (inner_expr)
25893       || TREE_CODE (inner_expr) == OFFSET_REF)
25894     return orig_expr;
25895   /* There is no need to return a proxy for a variable.  */
25896   if (VAR_P (expr))
25897     return orig_expr;
25898   /* Preserve string constants; conversions from string constants to
25899      "char *" are allowed, even though normally a "const char *"
25900      cannot be used to initialize a "char *".  */
25901   if (TREE_CODE (expr) == STRING_CST)
25902     return orig_expr;
25903   /* Preserve void and arithmetic constants, as an optimization -- there is no
25904      reason to create a new node.  */
25905   if (TREE_CODE (expr) == VOID_CST
25906       || TREE_CODE (expr) == INTEGER_CST
25907       || TREE_CODE (expr) == REAL_CST)
25908     return orig_expr;
25909   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
25910      There is at least one place where we want to know that a
25911      particular expression is a throw-expression: when checking a ?:
25912      expression, there are special rules if the second or third
25913      argument is a throw-expression.  */
25914   if (TREE_CODE (expr) == THROW_EXPR)
25915     return orig_expr;
25916 
25917   /* Don't wrap an initializer list, we need to be able to look inside.  */
25918   if (BRACE_ENCLOSED_INITIALIZER_P (expr))
25919     return orig_expr;
25920 
25921   /* Don't wrap a dummy object, we need to be able to test for it.  */
25922   if (is_dummy_object (expr))
25923     return orig_expr;
25924 
25925   if (TREE_CODE (expr) == COND_EXPR)
25926     return build3 (COND_EXPR,
25927 		   TREE_TYPE (expr),
25928 		   TREE_OPERAND (expr, 0),
25929 		   (TREE_OPERAND (expr, 1)
25930 		    ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
25931 		    : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
25932 		   build_non_dependent_expr (TREE_OPERAND (expr, 2)));
25933   if (TREE_CODE (expr) == COMPOUND_EXPR
25934       && !COMPOUND_EXPR_OVERLOADED (expr))
25935     return build2 (COMPOUND_EXPR,
25936 		   TREE_TYPE (expr),
25937 		   TREE_OPERAND (expr, 0),
25938 		   build_non_dependent_expr (TREE_OPERAND (expr, 1)));
25939 
25940   /* If the type is unknown, it can't really be non-dependent */
25941   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
25942 
25943   /* Otherwise, build a NON_DEPENDENT_EXPR.  */
25944   return build1_loc (EXPR_LOCATION (orig_expr), NON_DEPENDENT_EXPR,
25945 		     TREE_TYPE (expr), expr);
25946 }
25947 
25948 /* ARGS is a vector of expressions as arguments to a function call.
25949    Replace the arguments with equivalent non-dependent expressions.
25950    This modifies ARGS in place.  */
25951 
25952 void
make_args_non_dependent(vec<tree,va_gc> * args)25953 make_args_non_dependent (vec<tree, va_gc> *args)
25954 {
25955   unsigned int ix;
25956   tree arg;
25957 
25958   FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
25959     {
25960       tree newarg = build_non_dependent_expr (arg);
25961       if (newarg != arg)
25962 	(*args)[ix] = newarg;
25963     }
25964 }
25965 
25966 /* Returns a type which represents 'auto' or 'decltype(auto)'.  We use a
25967    TEMPLATE_TYPE_PARM with a level one deeper than the actual template
25968    parms.  If set_canonical is true, we set TYPE_CANONICAL on it.  */
25969 
25970 static tree
make_auto_1(tree name,bool set_canonical)25971 make_auto_1 (tree name, bool set_canonical)
25972 {
25973   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
25974   TYPE_NAME (au) = build_decl (input_location,
25975 			       TYPE_DECL, name, au);
25976   TYPE_STUB_DECL (au) = TYPE_NAME (au);
25977   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
25978     (0, processing_template_decl + 1, processing_template_decl + 1,
25979      TYPE_NAME (au), NULL_TREE);
25980   if (set_canonical)
25981     TYPE_CANONICAL (au) = canonical_type_parameter (au);
25982   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
25983   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
25984 
25985   return au;
25986 }
25987 
25988 tree
make_decltype_auto(void)25989 make_decltype_auto (void)
25990 {
25991   return make_auto_1 (decltype_auto_identifier, true);
25992 }
25993 
25994 tree
make_auto(void)25995 make_auto (void)
25996 {
25997   return make_auto_1 (auto_identifier, true);
25998 }
25999 
26000 /* Return a C++17 deduction placeholder for class template TMPL.  */
26001 
26002 tree
make_template_placeholder(tree tmpl)26003 make_template_placeholder (tree tmpl)
26004 {
26005   tree t = make_auto_1 (DECL_NAME (tmpl), false);
26006   CLASS_PLACEHOLDER_TEMPLATE (t) = tmpl;
26007   /* Our canonical type depends on the placeholder.  */
26008   TYPE_CANONICAL (t) = canonical_type_parameter (t);
26009   return t;
26010 }
26011 
26012 /* True iff T is a C++17 class template deduction placeholder.  */
26013 
26014 bool
template_placeholder_p(tree t)26015 template_placeholder_p (tree t)
26016 {
26017   return is_auto (t) && CLASS_PLACEHOLDER_TEMPLATE (t);
26018 }
26019 
26020 /* Make a "constrained auto" type-specifier. This is an
26021    auto type with constraints that must be associated after
26022    deduction.  The constraint is formed from the given
26023    CONC and its optional sequence of arguments, which are
26024    non-null if written as partial-concept-id.  */
26025 
26026 tree
make_constrained_auto(tree con,tree args)26027 make_constrained_auto (tree con, tree args)
26028 {
26029   tree type = make_auto_1 (auto_identifier, false);
26030 
26031   /* Build the constraint. */
26032   tree tmpl = DECL_TI_TEMPLATE (con);
26033   tree expr = VAR_P (con) ? tmpl : ovl_make (tmpl);
26034   expr = build_concept_check (expr, type, args);
26035 
26036   tree constr = normalize_expression (expr);
26037   PLACEHOLDER_TYPE_CONSTRAINTS (type) = constr;
26038 
26039   /* Our canonical type depends on the constraint.  */
26040   TYPE_CANONICAL (type) = canonical_type_parameter (type);
26041 
26042   /* Attach the constraint to the type declaration. */
26043   tree decl = TYPE_NAME (type);
26044   return decl;
26045 }
26046 
26047 /* Given type ARG, return std::initializer_list<ARG>.  */
26048 
26049 static tree
listify(tree arg)26050 listify (tree arg)
26051 {
26052   tree std_init_list = get_namespace_binding (std_node, init_list_identifier);
26053 
26054   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
26055     {
26056       gcc_rich_location richloc (input_location);
26057       maybe_add_include_fixit (&richloc, "<initializer_list>");
26058       error_at (&richloc,
26059 		"deducing from brace-enclosed initializer list"
26060 		" requires %<#include <initializer_list>%>");
26061 
26062       return error_mark_node;
26063     }
26064   tree argvec = make_tree_vec (1);
26065   TREE_VEC_ELT (argvec, 0) = arg;
26066 
26067   return lookup_template_class (std_init_list, argvec, NULL_TREE,
26068 				NULL_TREE, 0, tf_warning_or_error);
26069 }
26070 
26071 /* Replace auto in TYPE with std::initializer_list<auto>.  */
26072 
26073 static tree
listify_autos(tree type,tree auto_node)26074 listify_autos (tree type, tree auto_node)
26075 {
26076   tree init_auto = listify (auto_node);
26077   tree argvec = make_tree_vec (1);
26078   TREE_VEC_ELT (argvec, 0) = init_auto;
26079   if (processing_template_decl)
26080     argvec = add_to_template_args (current_template_args (), argvec);
26081   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
26082 }
26083 
26084 /* Hash traits for hashing possibly constrained 'auto'
26085    TEMPLATE_TYPE_PARMs for use by do_auto_deduction.  */
26086 
26087 struct auto_hash : default_hash_traits<tree>
26088 {
26089   static inline hashval_t hash (tree);
26090   static inline bool equal (tree, tree);
26091 };
26092 
26093 /* Hash the 'auto' T.  */
26094 
26095 inline hashval_t
hash(tree t)26096 auto_hash::hash (tree t)
26097 {
26098   if (tree c = PLACEHOLDER_TYPE_CONSTRAINTS (t))
26099     /* Matching constrained-type-specifiers denote the same template
26100        parameter, so hash the constraint.  */
26101     return hash_placeholder_constraint (c);
26102   else
26103     /* But unconstrained autos are all separate, so just hash the pointer.  */
26104     return iterative_hash_object (t, 0);
26105 }
26106 
26107 /* Compare two 'auto's.  */
26108 
26109 inline bool
equal(tree t1,tree t2)26110 auto_hash::equal (tree t1, tree t2)
26111 {
26112   if (t1 == t2)
26113     return true;
26114 
26115   tree c1 = PLACEHOLDER_TYPE_CONSTRAINTS (t1);
26116   tree c2 = PLACEHOLDER_TYPE_CONSTRAINTS (t2);
26117 
26118   /* Two unconstrained autos are distinct.  */
26119   if (!c1 || !c2)
26120     return false;
26121 
26122   return equivalent_placeholder_constraints (c1, c2);
26123 }
26124 
26125 /* for_each_template_parm callback for extract_autos: if t is a (possibly
26126    constrained) auto, add it to the vector.  */
26127 
26128 static int
extract_autos_r(tree t,void * data)26129 extract_autos_r (tree t, void *data)
26130 {
26131   hash_table<auto_hash> &hash = *(hash_table<auto_hash>*)data;
26132   if (is_auto (t))
26133     {
26134       /* All the autos were built with index 0; fix that up now.  */
26135       tree *p = hash.find_slot (t, INSERT);
26136       unsigned idx;
26137       if (*p)
26138 	/* If this is a repeated constrained-type-specifier, use the index we
26139 	   chose before.  */
26140 	idx = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (*p));
26141       else
26142 	{
26143 	  /* Otherwise this is new, so use the current count.  */
26144 	  *p = t;
26145 	  idx = hash.elements () - 1;
26146 	}
26147       TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (t)) = idx;
26148     }
26149 
26150   /* Always keep walking.  */
26151   return 0;
26152 }
26153 
26154 /* Return a TREE_VEC of the 'auto's used in type under the Concepts TS, which
26155    says they can appear anywhere in the type.  */
26156 
26157 static tree
extract_autos(tree type)26158 extract_autos (tree type)
26159 {
26160   hash_set<tree> visited;
26161   hash_table<auto_hash> hash (2);
26162 
26163   for_each_template_parm (type, extract_autos_r, &hash, &visited, true);
26164 
26165   tree tree_vec = make_tree_vec (hash.elements());
26166   for (hash_table<auto_hash>::iterator iter = hash.begin();
26167        iter != hash.end(); ++iter)
26168     {
26169       tree elt = *iter;
26170       unsigned i = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (elt));
26171       TREE_VEC_ELT (tree_vec, i)
26172 	= build_tree_list (NULL_TREE, TYPE_NAME (elt));
26173     }
26174 
26175   return tree_vec;
26176 }
26177 
26178 /* The stem for deduction guide names.  */
26179 const char *const dguide_base = "__dguide_";
26180 
26181 /* Return the name for a deduction guide for class template TMPL.  */
26182 
26183 tree
dguide_name(tree tmpl)26184 dguide_name (tree tmpl)
26185 {
26186   tree type = (TYPE_P (tmpl) ? tmpl : TREE_TYPE (tmpl));
26187   tree tname = TYPE_IDENTIFIER (type);
26188   char *buf = (char *) alloca (1 + strlen (dguide_base)
26189 			       + IDENTIFIER_LENGTH (tname));
26190   memcpy (buf, dguide_base, strlen (dguide_base));
26191   memcpy (buf + strlen (dguide_base), IDENTIFIER_POINTER (tname),
26192 	  IDENTIFIER_LENGTH (tname) + 1);
26193   tree dname = get_identifier (buf);
26194   TREE_TYPE (dname) = type;
26195   return dname;
26196 }
26197 
26198 /* True if NAME is the name of a deduction guide.  */
26199 
26200 bool
dguide_name_p(tree name)26201 dguide_name_p (tree name)
26202 {
26203   return (TREE_CODE (name) == IDENTIFIER_NODE
26204 	  && TREE_TYPE (name)
26205 	  && !strncmp (IDENTIFIER_POINTER (name), dguide_base,
26206 		       strlen (dguide_base)));
26207 }
26208 
26209 /* True if FN is a deduction guide.  */
26210 
26211 bool
deduction_guide_p(const_tree fn)26212 deduction_guide_p (const_tree fn)
26213 {
26214   if (DECL_P (fn))
26215     if (tree name = DECL_NAME (fn))
26216       return dguide_name_p (name);
26217   return false;
26218 }
26219 
26220 /* True if FN is the copy deduction guide, i.e. A(A)->A.  */
26221 
26222 bool
copy_guide_p(const_tree fn)26223 copy_guide_p (const_tree fn)
26224 {
26225   gcc_assert (deduction_guide_p (fn));
26226   if (!DECL_ARTIFICIAL (fn))
26227     return false;
26228   tree parms = FUNCTION_FIRST_USER_PARMTYPE (DECL_TI_TEMPLATE (fn));
26229   return (TREE_CHAIN (parms) == void_list_node
26230 	  && same_type_p (TREE_VALUE (parms), TREE_TYPE (DECL_NAME (fn))));
26231 }
26232 
26233 /* True if FN is a guide generated from a constructor template.  */
26234 
26235 bool
template_guide_p(const_tree fn)26236 template_guide_p (const_tree fn)
26237 {
26238   gcc_assert (deduction_guide_p (fn));
26239   if (!DECL_ARTIFICIAL (fn))
26240     return false;
26241   tree tmpl = DECL_TI_TEMPLATE (fn);
26242   if (tree org = DECL_ABSTRACT_ORIGIN (tmpl))
26243     return PRIMARY_TEMPLATE_P (org);
26244   return false;
26245 }
26246 
26247 /* OLDDECL is a _DECL for a template parameter.  Return a similar parameter at
26248    LEVEL:INDEX, using tsubst_args and complain for substitution into non-type
26249    template parameter types.  Note that the handling of template template
26250    parameters relies on current_template_parms being set appropriately for the
26251    new template.  */
26252 
26253 static tree
rewrite_template_parm(tree olddecl,unsigned index,unsigned level,tree tsubst_args,tsubst_flags_t complain)26254 rewrite_template_parm (tree olddecl, unsigned index, unsigned level,
26255 		       tree tsubst_args, tsubst_flags_t complain)
26256 {
26257   if (olddecl == error_mark_node)
26258     return error_mark_node;
26259 
26260   tree oldidx = get_template_parm_index (olddecl);
26261 
26262   tree newtype;
26263   if (TREE_CODE (olddecl) == TYPE_DECL
26264       || TREE_CODE (olddecl) == TEMPLATE_DECL)
26265     {
26266       tree oldtype = TREE_TYPE (olddecl);
26267       newtype = cxx_make_type (TREE_CODE (oldtype));
26268       TYPE_MAIN_VARIANT (newtype) = newtype;
26269       if (TREE_CODE (oldtype) == TEMPLATE_TYPE_PARM)
26270 	TEMPLATE_TYPE_PARM_FOR_CLASS (newtype)
26271 	  = TEMPLATE_TYPE_PARM_FOR_CLASS (oldtype);
26272     }
26273   else
26274     {
26275       newtype = TREE_TYPE (olddecl);
26276       if (type_uses_auto (newtype))
26277 	{
26278 	  // Substitute once to fix references to other template parameters.
26279 	  newtype = tsubst (newtype, tsubst_args,
26280 			    complain|tf_partial, NULL_TREE);
26281 	  // Now substitute again to reduce the level of the auto.
26282 	  newtype = tsubst (newtype, current_template_args (),
26283 			    complain, NULL_TREE);
26284 	}
26285       else
26286 	newtype = tsubst (newtype, tsubst_args,
26287 			  complain, NULL_TREE);
26288     }
26289 
26290   tree newdecl
26291     = build_decl (DECL_SOURCE_LOCATION (olddecl), TREE_CODE (olddecl),
26292 		  DECL_NAME (olddecl), newtype);
26293   SET_DECL_TEMPLATE_PARM_P (newdecl);
26294 
26295   tree newidx;
26296   if (TREE_CODE (olddecl) == TYPE_DECL
26297       || TREE_CODE (olddecl) == TEMPLATE_DECL)
26298     {
26299       newidx = TEMPLATE_TYPE_PARM_INDEX (newtype)
26300 	= build_template_parm_index (index, level, level,
26301 				     newdecl, newtype);
26302       TEMPLATE_PARM_PARAMETER_PACK (newidx)
26303 	= TEMPLATE_PARM_PARAMETER_PACK (oldidx);
26304       TYPE_STUB_DECL (newtype) = TYPE_NAME (newtype) = newdecl;
26305       TYPE_CANONICAL (newtype) = canonical_type_parameter (newtype);
26306 
26307       if (TREE_CODE (olddecl) == TEMPLATE_DECL)
26308 	{
26309 	  DECL_TEMPLATE_RESULT (newdecl)
26310 	    = build_decl (DECL_SOURCE_LOCATION (olddecl), TYPE_DECL,
26311 			  DECL_NAME (olddecl), newtype);
26312 	  DECL_ARTIFICIAL (DECL_TEMPLATE_RESULT (newdecl)) = true;
26313 	  // First create a copy (ttargs) of tsubst_args with an
26314 	  // additional level for the template template parameter's own
26315 	  // template parameters (ttparms).
26316 	  tree ttparms = (INNERMOST_TEMPLATE_PARMS
26317 			  (DECL_TEMPLATE_PARMS (olddecl)));
26318 	  const int depth = TMPL_ARGS_DEPTH (tsubst_args);
26319 	  tree ttargs = make_tree_vec (depth + 1);
26320 	  for (int i = 0; i < depth; ++i)
26321 	    TREE_VEC_ELT (ttargs, i) = TREE_VEC_ELT (tsubst_args, i);
26322 	  TREE_VEC_ELT (ttargs, depth)
26323 	    = template_parms_level_to_args (ttparms);
26324 	  // Substitute ttargs into ttparms to fix references to
26325 	  // other template parameters.
26326 	  ttparms = tsubst_template_parms_level (ttparms, ttargs,
26327 						 complain|tf_partial);
26328 	  // Now substitute again with args based on tparms, to reduce
26329 	  // the level of the ttparms.
26330 	  ttargs = current_template_args ();
26331 	  ttparms = tsubst_template_parms_level (ttparms, ttargs,
26332 						 complain);
26333 	  // Finally, tack the adjusted parms onto tparms.
26334 	  ttparms = tree_cons (size_int (depth), ttparms,
26335 			       current_template_parms);
26336 	  DECL_TEMPLATE_PARMS (newdecl) = ttparms;
26337 	}
26338     }
26339   else
26340     {
26341       tree oldconst = TEMPLATE_PARM_DECL (oldidx);
26342       tree newconst
26343 	= build_decl (DECL_SOURCE_LOCATION (oldconst),
26344 		      TREE_CODE (oldconst),
26345 		      DECL_NAME (oldconst), newtype);
26346       TREE_CONSTANT (newconst) = TREE_CONSTANT (newdecl)
26347 	= TREE_READONLY (newconst) = TREE_READONLY (newdecl) = true;
26348       SET_DECL_TEMPLATE_PARM_P (newconst);
26349       newidx = build_template_parm_index (index, level, level,
26350 					  newconst, newtype);
26351       TEMPLATE_PARM_PARAMETER_PACK (newidx)
26352 	= TEMPLATE_PARM_PARAMETER_PACK (oldidx);
26353       DECL_INITIAL (newdecl) = DECL_INITIAL (newconst) = newidx;
26354     }
26355 
26356   return newdecl;
26357 }
26358 
26359 /* Returns a C++17 class deduction guide template based on the constructor
26360    CTOR.  As a special case, CTOR can be a RECORD_TYPE for an implicit default
26361    guide, or REFERENCE_TYPE for an implicit copy/move guide.  */
26362 
26363 static tree
build_deduction_guide(tree ctor,tree outer_args,tsubst_flags_t complain)26364 build_deduction_guide (tree ctor, tree outer_args, tsubst_flags_t complain)
26365 {
26366   tree type, tparms, targs, fparms, fargs, ci;
26367   bool memtmpl = false;
26368   bool explicit_p;
26369   location_t loc;
26370   tree fn_tmpl = NULL_TREE;
26371 
26372   if (TYPE_P (ctor))
26373     {
26374       type = ctor;
26375       bool copy_p = TREE_CODE (type) == REFERENCE_TYPE;
26376       if (copy_p)
26377 	{
26378 	  type = TREE_TYPE (type);
26379 	  fparms = tree_cons (NULL_TREE, type, void_list_node);
26380 	}
26381       else
26382 	fparms = void_list_node;
26383 
26384       tree ctmpl = CLASSTYPE_TI_TEMPLATE (type);
26385       tparms = DECL_TEMPLATE_PARMS (ctmpl);
26386       targs = CLASSTYPE_TI_ARGS (type);
26387       ci = NULL_TREE;
26388       fargs = NULL_TREE;
26389       loc = DECL_SOURCE_LOCATION (ctmpl);
26390       explicit_p = false;
26391     }
26392   else
26393     {
26394       ++processing_template_decl;
26395       bool ok = true;
26396 
26397       fn_tmpl
26398 	= (TREE_CODE (ctor) == TEMPLATE_DECL ? ctor
26399 	   : DECL_TI_TEMPLATE (ctor));
26400       if (outer_args)
26401 	fn_tmpl = tsubst (fn_tmpl, outer_args, complain, ctor);
26402       ctor = DECL_TEMPLATE_RESULT (fn_tmpl);
26403 
26404       type = DECL_CONTEXT (ctor);
26405 
26406       tparms = DECL_TEMPLATE_PARMS (fn_tmpl);
26407       /* If type is a member class template, DECL_TI_ARGS (ctor) will have
26408 	 fully specialized args for the enclosing class.  Strip those off, as
26409 	 the deduction guide won't have those template parameters.  */
26410       targs = get_innermost_template_args (DECL_TI_ARGS (ctor),
26411 						TMPL_PARMS_DEPTH (tparms));
26412       /* Discard the 'this' parameter.  */
26413       fparms = FUNCTION_ARG_CHAIN (ctor);
26414       fargs = TREE_CHAIN (DECL_ARGUMENTS (ctor));
26415       ci = get_constraints (ctor);
26416       loc = DECL_SOURCE_LOCATION (ctor);
26417       explicit_p = DECL_NONCONVERTING_P (ctor);
26418 
26419       if (PRIMARY_TEMPLATE_P (fn_tmpl))
26420 	{
26421 	  memtmpl = true;
26422 
26423 	  /* For a member template constructor, we need to flatten the two
26424 	     template parameter lists into one, and then adjust the function
26425 	     signature accordingly.  This gets...complicated.  */
26426 	  tree save_parms = current_template_parms;
26427 
26428 	  /* For a member template we should have two levels of parms/args, one
26429 	     for the class and one for the constructor.  We stripped
26430 	     specialized args for further enclosing classes above.  */
26431 	  const int depth = 2;
26432 	  gcc_assert (TMPL_ARGS_DEPTH (targs) == depth);
26433 
26434 	  /* Template args for translating references to the two-level template
26435 	     parameters into references to the one-level template parameters we
26436 	     are creating.  */
26437 	  tree tsubst_args = copy_node (targs);
26438 	  TMPL_ARGS_LEVEL (tsubst_args, depth)
26439 	    = copy_node (TMPL_ARGS_LEVEL (tsubst_args, depth));
26440 
26441 	  /* Template parms for the constructor template.  */
26442 	  tree ftparms = TREE_VALUE (tparms);
26443 	  unsigned flen = TREE_VEC_LENGTH (ftparms);
26444 	  /* Template parms for the class template.  */
26445 	  tparms = TREE_CHAIN (tparms);
26446 	  tree ctparms = TREE_VALUE (tparms);
26447 	  unsigned clen = TREE_VEC_LENGTH (ctparms);
26448 	  /* Template parms for the deduction guide start as a copy of the
26449 	     template parms for the class.  We set current_template_parms for
26450 	     lookup_template_class_1.  */
26451 	  current_template_parms = tparms = copy_node (tparms);
26452 	  tree new_vec = TREE_VALUE (tparms) = make_tree_vec (flen + clen);
26453 	  for (unsigned i = 0; i < clen; ++i)
26454 	    TREE_VEC_ELT (new_vec, i) = TREE_VEC_ELT (ctparms, i);
26455 
26456 	  /* Now we need to rewrite the constructor parms to append them to the
26457 	     class parms.  */
26458 	  for (unsigned i = 0; i < flen; ++i)
26459 	    {
26460 	      unsigned index = i + clen;
26461 	      unsigned level = 1;
26462 	      tree oldelt = TREE_VEC_ELT (ftparms, i);
26463 	      tree olddecl = TREE_VALUE (oldelt);
26464 	      tree newdecl = rewrite_template_parm (olddecl, index, level,
26465 						    tsubst_args, complain);
26466 	      if (newdecl == error_mark_node)
26467 		ok = false;
26468 	      tree newdef = tsubst_template_arg (TREE_PURPOSE (oldelt),
26469 						 tsubst_args, complain, ctor);
26470 	      tree list = build_tree_list (newdef, newdecl);
26471 	      TEMPLATE_PARM_CONSTRAINTS (list)
26472 		= tsubst_constraint_info (TEMPLATE_PARM_CONSTRAINTS (oldelt),
26473 					  tsubst_args, complain, ctor);
26474 	      TREE_VEC_ELT (new_vec, index) = list;
26475 	      TMPL_ARG (tsubst_args, depth, i) = template_parm_to_arg (list);
26476 	    }
26477 
26478 	  /* Now we have a final set of template parms to substitute into the
26479 	     function signature.  */
26480 	  targs = template_parms_to_args (tparms);
26481 	  fparms = tsubst_arg_types (fparms, tsubst_args, NULL_TREE,
26482 				     complain, ctor);
26483 	  if (fparms == error_mark_node)
26484 	    ok = false;
26485 	  fargs = tsubst (fargs, tsubst_args, complain, ctor);
26486 	  if (ci)
26487 	    ci = tsubst_constraint_info (ci, tsubst_args, complain, ctor);
26488 
26489 	  current_template_parms = save_parms;
26490 	}
26491 
26492       --processing_template_decl;
26493       if (!ok)
26494 	return error_mark_node;
26495     }
26496 
26497   if (!memtmpl)
26498     {
26499       /* Copy the parms so we can set DECL_PRIMARY_TEMPLATE.  */
26500       tparms = copy_node (tparms);
26501       INNERMOST_TEMPLATE_PARMS (tparms)
26502 	= copy_node (INNERMOST_TEMPLATE_PARMS (tparms));
26503     }
26504 
26505   tree fntype = build_function_type (type, fparms);
26506   tree ded_fn = build_lang_decl_loc (loc,
26507 				     FUNCTION_DECL,
26508 				     dguide_name (type), fntype);
26509   DECL_ARGUMENTS (ded_fn) = fargs;
26510   DECL_ARTIFICIAL (ded_fn) = true;
26511   DECL_NONCONVERTING_P (ded_fn) = explicit_p;
26512   tree ded_tmpl = build_template_decl (ded_fn, tparms, /*member*/false);
26513   DECL_ARTIFICIAL (ded_tmpl) = true;
26514   DECL_TEMPLATE_RESULT (ded_tmpl) = ded_fn;
26515   TREE_TYPE (ded_tmpl) = TREE_TYPE (ded_fn);
26516   DECL_TEMPLATE_INFO (ded_fn) = build_template_info (ded_tmpl, targs);
26517   DECL_PRIMARY_TEMPLATE (ded_tmpl) = ded_tmpl;
26518   if (DECL_P (ctor))
26519     DECL_ABSTRACT_ORIGIN (ded_tmpl) = fn_tmpl;
26520   if (ci)
26521     set_constraints (ded_tmpl, ci);
26522 
26523   return ded_tmpl;
26524 }
26525 
26526 /* Deduce template arguments for the class template placeholder PTYPE for
26527    template TMPL based on the initializer INIT, and return the resulting
26528    type.  */
26529 
26530 static tree
do_class_deduction(tree ptype,tree tmpl,tree init,int flags,tsubst_flags_t complain)26531 do_class_deduction (tree ptype, tree tmpl, tree init, int flags,
26532 		    tsubst_flags_t complain)
26533 {
26534   if (!DECL_CLASS_TEMPLATE_P (tmpl))
26535     {
26536       /* We should have handled this in the caller.  */
26537       if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
26538 	return ptype;
26539       if (complain & tf_error)
26540 	error ("non-class template %qT used without template arguments", tmpl);
26541       return error_mark_node;
26542     }
26543   if (init && TREE_TYPE (init) == ptype)
26544     /* Using the template parm as its own argument.  */
26545     return ptype;
26546 
26547   tree type = TREE_TYPE (tmpl);
26548 
26549   bool try_list_ctor = false;
26550 
26551   vec<tree,va_gc> *args;
26552   if (init == NULL_TREE
26553       || TREE_CODE (init) == TREE_LIST)
26554     args = make_tree_vector_from_list (init);
26555   else if (BRACE_ENCLOSED_INITIALIZER_P (init))
26556     {
26557       try_list_ctor = TYPE_HAS_LIST_CTOR (type);
26558       if (try_list_ctor && CONSTRUCTOR_NELTS (init) == 1)
26559 	{
26560 	  /* As an exception, the first phase in 16.3.1.7 (considering the
26561 	     initializer list as a single argument) is omitted if the
26562 	     initializer list consists of a single expression of type cv U,
26563 	     where U is a specialization of C or a class derived from a
26564 	     specialization of C.  */
26565 	  tree elt = CONSTRUCTOR_ELT (init, 0)->value;
26566 	  tree etype = TREE_TYPE (elt);
26567 
26568 	  tree tparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
26569 	  tree targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
26570 	  int err = unify (tparms, targs, type, etype,
26571 			   UNIFY_ALLOW_DERIVED, /*explain*/false);
26572 	  if (err == 0)
26573 	    try_list_ctor = false;
26574 	  ggc_free (targs);
26575 	}
26576       if (try_list_ctor || is_std_init_list (type))
26577 	args = make_tree_vector_single (init);
26578       else
26579 	args = make_tree_vector_from_ctor (init);
26580     }
26581   else
26582     args = make_tree_vector_single (init);
26583 
26584   tree dname = dguide_name (tmpl);
26585   tree cands = lookup_qualified_name (CP_DECL_CONTEXT (tmpl), dname,
26586 				      /*type*/false, /*complain*/false,
26587 				      /*hidden*/false);
26588   bool elided = false;
26589   if (cands == error_mark_node)
26590     cands = NULL_TREE;
26591 
26592   /* Prune explicit deduction guides in copy-initialization context.  */
26593   if (flags & LOOKUP_ONLYCONVERTING)
26594     {
26595       for (lkp_iterator iter (cands); !elided && iter; ++iter)
26596 	if (DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
26597 	  elided = true;
26598 
26599       if (elided)
26600 	{
26601 	  /* Found a nonconverting guide, prune the candidates.  */
26602 	  tree pruned = NULL_TREE;
26603 	  for (lkp_iterator iter (cands); iter; ++iter)
26604 	    if (!DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
26605 	      pruned = lookup_add (*iter, pruned);
26606 
26607 	  cands = pruned;
26608 	}
26609     }
26610 
26611   tree outer_args = NULL_TREE;
26612   if (DECL_CLASS_SCOPE_P (tmpl)
26613       && CLASSTYPE_TEMPLATE_INSTANTIATION (DECL_CONTEXT (tmpl)))
26614     {
26615       outer_args = CLASSTYPE_TI_ARGS (DECL_CONTEXT (tmpl));
26616       type = TREE_TYPE (most_general_template (tmpl));
26617     }
26618 
26619   bool saw_ctor = false;
26620   // FIXME cache artificial deduction guides
26621   for (ovl_iterator iter (CLASSTYPE_CONSTRUCTORS (type)); iter; ++iter)
26622     {
26623       /* Skip inherited constructors.  */
26624       if (iter.using_p ())
26625 	continue;
26626 
26627       tree guide = build_deduction_guide (*iter, outer_args, complain);
26628       if (guide == error_mark_node)
26629 	return error_mark_node;
26630       if ((flags & LOOKUP_ONLYCONVERTING)
26631 	  && DECL_NONCONVERTING_P (STRIP_TEMPLATE (guide)))
26632 	elided = true;
26633       else
26634 	cands = lookup_add (guide, cands);
26635 
26636       saw_ctor = true;
26637     }
26638 
26639   tree call = error_mark_node;
26640 
26641   /* If this is list-initialization and the class has a list constructor, first
26642      try deducing from the list as a single argument, as [over.match.list].  */
26643   tree list_cands = NULL_TREE;
26644   if (try_list_ctor && cands)
26645     for (lkp_iterator iter (cands); iter; ++iter)
26646       {
26647 	tree dg = *iter;
26648 	if (is_list_ctor (dg))
26649 	  list_cands = lookup_add (dg, list_cands);
26650       }
26651   if (list_cands)
26652     {
26653       ++cp_unevaluated_operand;
26654       call = build_new_function_call (list_cands, &args, tf_decltype);
26655       --cp_unevaluated_operand;
26656 
26657       if (call == error_mark_node)
26658 	{
26659 	  /* That didn't work, now try treating the list as a sequence of
26660 	     arguments.  */
26661 	  release_tree_vector (args);
26662 	  args = make_tree_vector_from_ctor (init);
26663 	}
26664     }
26665 
26666   /* Maybe generate an implicit deduction guide.  */
26667   if (call == error_mark_node && args->length () < 2)
26668     {
26669       tree gtype = NULL_TREE;
26670 
26671       if (args->length () == 1)
26672 	/* Generate a copy guide.  */
26673 	gtype = build_reference_type (type);
26674       else if (!saw_ctor)
26675 	/* Generate a default guide.  */
26676 	gtype = type;
26677 
26678       if (gtype)
26679 	{
26680 	  tree guide = build_deduction_guide (gtype, outer_args, complain);
26681 	  if (guide == error_mark_node)
26682 	    return error_mark_node;
26683 	  cands = lookup_add (guide, cands);
26684 	}
26685     }
26686 
26687   if (elided && !cands)
26688     {
26689       error ("cannot deduce template arguments for copy-initialization"
26690 	     " of %qT, as it has no non-explicit deduction guides or "
26691 	     "user-declared constructors", type);
26692       return error_mark_node;
26693     }
26694   else if (!cands && call == error_mark_node)
26695     {
26696       error ("cannot deduce template arguments of %qT, as it has no viable "
26697 	     "deduction guides", type);
26698       return error_mark_node;
26699     }
26700 
26701   if (call == error_mark_node)
26702     {
26703       ++cp_unevaluated_operand;
26704       call = build_new_function_call (cands, &args, tf_decltype);
26705       --cp_unevaluated_operand;
26706     }
26707 
26708   if (call == error_mark_node && (complain & tf_warning_or_error))
26709     {
26710       error ("class template argument deduction failed:");
26711 
26712       ++cp_unevaluated_operand;
26713       call = build_new_function_call (cands, &args, complain | tf_decltype);
26714       --cp_unevaluated_operand;
26715 
26716       if (elided)
26717 	inform (input_location, "explicit deduction guides not considered "
26718 		"for copy-initialization");
26719     }
26720 
26721   release_tree_vector (args);
26722 
26723   return cp_build_qualified_type (TREE_TYPE (call), cp_type_quals (ptype));
26724 }
26725 
26726 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
26727    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.
26728    The CONTEXT determines the context in which auto deduction is performed
26729    and is used to control error diagnostics.  FLAGS are the LOOKUP_* flags.
26730    OUTER_TARGS are used during template argument deduction
26731    (context == adc_unify) to properly substitute the result, and is ignored
26732    in other contexts.
26733 
26734    For partial-concept-ids, extra args may be appended to the list of deduced
26735    template arguments prior to determining constraint satisfaction.  */
26736 
26737 tree
do_auto_deduction(tree type,tree init,tree auto_node,tsubst_flags_t complain,auto_deduction_context context,tree outer_targs,int flags)26738 do_auto_deduction (tree type, tree init, tree auto_node,
26739                    tsubst_flags_t complain, auto_deduction_context context,
26740 		   tree outer_targs, int flags)
26741 {
26742   tree targs;
26743 
26744   if (init == error_mark_node)
26745     return error_mark_node;
26746 
26747   if (init && type_dependent_expression_p (init)
26748       && context != adc_unify)
26749     /* Defining a subset of type-dependent expressions that we can deduce
26750        from ahead of time isn't worth the trouble.  */
26751     return type;
26752 
26753   /* Similarly, we can't deduce from another undeduced decl.  */
26754   if (init && undeduced_auto_decl (init))
26755     return type;
26756 
26757   if (tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
26758     /* C++17 class template argument deduction.  */
26759     return do_class_deduction (type, tmpl, init, flags, complain);
26760 
26761   if (init == NULL_TREE || TREE_TYPE (init) == NULL_TREE)
26762     /* Nothing we can do with this, even in deduction context.  */
26763     return type;
26764 
26765   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
26766      with either a new invented type template parameter U or, if the
26767      initializer is a braced-init-list (8.5.4), with
26768      std::initializer_list<U>.  */
26769   if (BRACE_ENCLOSED_INITIALIZER_P (init))
26770     {
26771       if (!DIRECT_LIST_INIT_P (init))
26772 	type = listify_autos (type, auto_node);
26773       else if (CONSTRUCTOR_NELTS (init) == 1)
26774 	init = CONSTRUCTOR_ELT (init, 0)->value;
26775       else
26776 	{
26777           if (complain & tf_warning_or_error)
26778             {
26779 	      if (permerror (input_location, "direct-list-initialization of "
26780 			     "%<auto%> requires exactly one element"))
26781 	        inform (input_location,
26782 		        "for deduction to %<std::initializer_list%>, use copy-"
26783 		        "list-initialization (i.e. add %<=%> before the %<{%>)");
26784             }
26785 	  type = listify_autos (type, auto_node);
26786 	}
26787     }
26788 
26789   if (type == error_mark_node)
26790     return error_mark_node;
26791 
26792   init = resolve_nondeduced_context (init, complain);
26793 
26794   if (context == adc_decomp_type
26795       && auto_node == type
26796       && init != error_mark_node
26797       && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
26798     /* [dcl.decomp]/1 - if decomposition declaration has no ref-qualifiers
26799        and initializer has array type, deduce cv-qualified array type.  */
26800     return cp_build_qualified_type_real (TREE_TYPE (init), TYPE_QUALS (type),
26801 					 complain);
26802   else if (AUTO_IS_DECLTYPE (auto_node))
26803     {
26804       bool id = (DECL_P (init)
26805 		 || ((TREE_CODE (init) == COMPONENT_REF
26806 		      || TREE_CODE (init) == SCOPE_REF)
26807 		     && !REF_PARENTHESIZED_P (init)));
26808       targs = make_tree_vec (1);
26809       TREE_VEC_ELT (targs, 0)
26810 	= finish_decltype_type (init, id, tf_warning_or_error);
26811       if (type != auto_node)
26812 	{
26813           if (complain & tf_error)
26814 	    error ("%qT as type rather than plain %<decltype(auto)%>", type);
26815 	  return error_mark_node;
26816 	}
26817     }
26818   else
26819     {
26820       tree parms = build_tree_list (NULL_TREE, type);
26821       tree tparms;
26822 
26823       if (flag_concepts)
26824 	tparms = extract_autos (type);
26825       else
26826 	{
26827 	  tparms = make_tree_vec (1);
26828 	  TREE_VEC_ELT (tparms, 0)
26829 	    = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
26830 	}
26831 
26832       targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
26833       int val = type_unification_real (tparms, targs, parms, &init, 1, 0,
26834 				       DEDUCE_CALL, LOOKUP_NORMAL,
26835 				       NULL, /*explain_p=*/false);
26836       if (val > 0)
26837 	{
26838 	  if (processing_template_decl)
26839 	    /* Try again at instantiation time.  */
26840 	    return type;
26841 	  if (type && type != error_mark_node
26842 	      && (complain & tf_error))
26843 	    /* If type is error_mark_node a diagnostic must have been
26844 	       emitted by now.  Also, having a mention to '<type error>'
26845 	       in the diagnostic is not really useful to the user.  */
26846 	    {
26847 	      if (cfun && auto_node == current_function_auto_return_pattern
26848 		  && LAMBDA_FUNCTION_P (current_function_decl))
26849 		error ("unable to deduce lambda return type from %qE", init);
26850 	      else
26851 		error ("unable to deduce %qT from %qE", type, init);
26852 	      type_unification_real (tparms, targs, parms, &init, 1, 0,
26853 				     DEDUCE_CALL, LOOKUP_NORMAL,
26854 				     NULL, /*explain_p=*/true);
26855 	    }
26856 	  return error_mark_node;
26857 	}
26858     }
26859 
26860   /* Check any placeholder constraints against the deduced type. */
26861   if (flag_concepts && !processing_template_decl)
26862     if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (auto_node))
26863       {
26864         /* Use the deduced type to check the associated constraints. If we
26865            have a partial-concept-id, rebuild the argument list so that
26866            we check using the extra arguments. */
26867         gcc_assert (TREE_CODE (constr) == CHECK_CONSTR);
26868         tree cargs = CHECK_CONSTR_ARGS (constr);
26869         if (TREE_VEC_LENGTH (cargs) > 1)
26870           {
26871             cargs = copy_node (cargs);
26872             TREE_VEC_ELT (cargs, 0) = TREE_VEC_ELT (targs, 0);
26873           }
26874         else
26875           cargs = targs;
26876         if (!constraints_satisfied_p (constr, cargs))
26877           {
26878             if (complain & tf_warning_or_error)
26879               {
26880                 switch (context)
26881                   {
26882                   case adc_unspecified:
26883 		  case adc_unify:
26884                     error("placeholder constraints not satisfied");
26885                     break;
26886                   case adc_variable_type:
26887 		  case adc_decomp_type:
26888                     error ("deduced initializer does not satisfy "
26889                            "placeholder constraints");
26890                     break;
26891                   case adc_return_type:
26892                     error ("deduced return type does not satisfy "
26893                            "placeholder constraints");
26894                     break;
26895                   case adc_requirement:
26896 		    error ("deduced expression type does not satisfy "
26897                            "placeholder constraints");
26898                     break;
26899                   }
26900                 diagnose_constraints (input_location, constr, targs);
26901               }
26902             return error_mark_node;
26903           }
26904       }
26905 
26906   if (processing_template_decl && context != adc_unify)
26907     outer_targs = current_template_args ();
26908   targs = add_to_template_args (outer_targs, targs);
26909   return tsubst (type, targs, complain, NULL_TREE);
26910 }
26911 
26912 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
26913    result.  */
26914 
26915 tree
splice_late_return_type(tree type,tree late_return_type)26916 splice_late_return_type (tree type, tree late_return_type)
26917 {
26918   if (is_auto (type))
26919     {
26920       if (late_return_type)
26921 	return late_return_type;
26922 
26923       tree idx = get_template_parm_index (type);
26924       if (TEMPLATE_PARM_LEVEL (idx) <= processing_template_decl)
26925 	/* In an abbreviated function template we didn't know we were dealing
26926 	   with a function template when we saw the auto return type, so update
26927 	   it to have the correct level.  */
26928 	return make_auto_1 (TYPE_IDENTIFIER (type), true);
26929     }
26930   return type;
26931 }
26932 
26933 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto' or
26934    'decltype(auto)' or a deduced class template.  */
26935 
26936 bool
is_auto(const_tree type)26937 is_auto (const_tree type)
26938 {
26939   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
26940       && (TYPE_IDENTIFIER (type) == auto_identifier
26941 	  || TYPE_IDENTIFIER (type) == decltype_auto_identifier
26942 	  || CLASS_PLACEHOLDER_TEMPLATE (type)))
26943     return true;
26944   else
26945     return false;
26946 }
26947 
26948 /* for_each_template_parm callback for type_uses_auto.  */
26949 
26950 int
is_auto_r(tree tp,void *)26951 is_auto_r (tree tp, void */*data*/)
26952 {
26953   return is_auto (tp);
26954 }
26955 
26956 /* Returns the TEMPLATE_TYPE_PARM in TYPE representing `auto' iff TYPE contains
26957    a use of `auto'.  Returns NULL_TREE otherwise.  */
26958 
26959 tree
type_uses_auto(tree type)26960 type_uses_auto (tree type)
26961 {
26962   if (type == NULL_TREE)
26963     return NULL_TREE;
26964   else if (flag_concepts)
26965     {
26966       /* The Concepts TS allows multiple autos in one type-specifier; just
26967 	 return the first one we find, do_auto_deduction will collect all of
26968 	 them.  */
26969       if (uses_template_parms (type))
26970 	return for_each_template_parm (type, is_auto_r, /*data*/NULL,
26971 				       /*visited*/NULL, /*nondeduced*/false);
26972       else
26973 	return NULL_TREE;
26974     }
26975   else
26976     return find_type_usage (type, is_auto);
26977 }
26978 
26979 /* Report ill-formed occurrences of auto types in ARGUMENTS.  If
26980    concepts are enabled, auto is acceptable in template arguments, but
26981    only when TEMPL identifies a template class.  Return TRUE if any
26982    such errors were reported.  */
26983 
26984 bool
check_auto_in_tmpl_args(tree tmpl,tree args)26985 check_auto_in_tmpl_args (tree tmpl, tree args)
26986 {
26987   /* If there were previous errors, nevermind.  */
26988   if (!args || TREE_CODE (args) != TREE_VEC)
26989     return false;
26990 
26991   /* If TMPL is an identifier, we're parsing and we can't tell yet
26992      whether TMPL is supposed to be a type, a function or a variable.
26993      We'll only be able to tell during template substitution, so we
26994      expect to be called again then.  If concepts are enabled and we
26995      know we have a type, we're ok.  */
26996   if (flag_concepts
26997       && (identifier_p (tmpl)
26998 	  || (DECL_P (tmpl)
26999 	      &&  (DECL_TYPE_TEMPLATE_P (tmpl)
27000 		   || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)))))
27001     return false;
27002 
27003   /* Quickly search for any occurrences of auto; usually there won't
27004      be any, and then we'll avoid allocating the vector.  */
27005   if (!type_uses_auto (args))
27006     return false;
27007 
27008   bool errors = false;
27009 
27010   tree vec = extract_autos (args);
27011   for (int i = 0; i < TREE_VEC_LENGTH (vec); i++)
27012     {
27013       tree xauto = TREE_VALUE (TREE_VEC_ELT (vec, i));
27014       error_at (DECL_SOURCE_LOCATION (xauto),
27015 		"invalid use of %qT in template argument", xauto);
27016       errors = true;
27017     }
27018 
27019   return errors;
27020 }
27021 
27022 /* For a given template T, return the vector of typedefs referenced
27023    in T for which access check is needed at T instantiation time.
27024    T is either  a FUNCTION_DECL or a RECORD_TYPE.
27025    Those typedefs were added to T by the function
27026    append_type_to_template_for_access_check.  */
27027 
27028 vec<qualified_typedef_usage_t, va_gc> *
get_types_needing_access_check(tree t)27029 get_types_needing_access_check (tree t)
27030 {
27031   tree ti;
27032   vec<qualified_typedef_usage_t, va_gc> *result = NULL;
27033 
27034   if (!t || t == error_mark_node)
27035     return NULL;
27036 
27037   if (!(ti = get_template_info (t)))
27038     return NULL;
27039 
27040   if (CLASS_TYPE_P (t)
27041       || TREE_CODE (t) == FUNCTION_DECL)
27042     {
27043       if (!TI_TEMPLATE (ti))
27044 	return NULL;
27045 
27046       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
27047     }
27048 
27049   return result;
27050 }
27051 
27052 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
27053    tied to T. That list of typedefs will be access checked at
27054    T instantiation time.
27055    T is either a FUNCTION_DECL or a RECORD_TYPE.
27056    TYPE_DECL is a TYPE_DECL node representing a typedef.
27057    SCOPE is the scope through which TYPE_DECL is accessed.
27058    LOCATION is the location of the usage point of TYPE_DECL.
27059 
27060    This function is a subroutine of
27061    append_type_to_template_for_access_check.  */
27062 
27063 static void
append_type_to_template_for_access_check_1(tree t,tree type_decl,tree scope,location_t location)27064 append_type_to_template_for_access_check_1 (tree t,
27065 					    tree type_decl,
27066 					    tree scope,
27067 					    location_t location)
27068 {
27069   qualified_typedef_usage_t typedef_usage;
27070   tree ti;
27071 
27072   if (!t || t == error_mark_node)
27073     return;
27074 
27075   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
27076 	       || CLASS_TYPE_P (t))
27077 	      && type_decl
27078 	      && TREE_CODE (type_decl) == TYPE_DECL
27079 	      && scope);
27080 
27081   if (!(ti = get_template_info (t)))
27082     return;
27083 
27084   gcc_assert (TI_TEMPLATE (ti));
27085 
27086   typedef_usage.typedef_decl = type_decl;
27087   typedef_usage.context = scope;
27088   typedef_usage.locus = location;
27089 
27090   vec_safe_push (TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti), typedef_usage);
27091 }
27092 
27093 /* Append TYPE_DECL to the template TEMPL.
27094    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
27095    At TEMPL instanciation time, TYPE_DECL will be checked to see
27096    if it can be accessed through SCOPE.
27097    LOCATION is the location of the usage point of TYPE_DECL.
27098 
27099    e.g. consider the following code snippet:
27100 
27101      class C
27102      {
27103        typedef int myint;
27104      };
27105 
27106      template<class U> struct S
27107      {
27108        C::myint mi; // <-- usage point of the typedef C::myint
27109      };
27110 
27111      S<char> s;
27112 
27113    At S<char> instantiation time, we need to check the access of C::myint
27114    In other words, we need to check the access of the myint typedef through
27115    the C scope. For that purpose, this function will add the myint typedef
27116    and the scope C through which its being accessed to a list of typedefs
27117    tied to the template S. That list will be walked at template instantiation
27118    time and access check performed on each typedefs it contains.
27119    Note that this particular code snippet should yield an error because
27120    myint is private to C.  */
27121 
27122 void
append_type_to_template_for_access_check(tree templ,tree type_decl,tree scope,location_t location)27123 append_type_to_template_for_access_check (tree templ,
27124                                           tree type_decl,
27125 					  tree scope,
27126 					  location_t location)
27127 {
27128   qualified_typedef_usage_t *iter;
27129   unsigned i;
27130 
27131   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
27132 
27133   /* Make sure we don't append the type to the template twice.  */
27134   FOR_EACH_VEC_SAFE_ELT (get_types_needing_access_check (templ), i, iter)
27135     if (iter->typedef_decl == type_decl && scope == iter->context)
27136       return;
27137 
27138   append_type_to_template_for_access_check_1 (templ, type_decl,
27139 					      scope, location);
27140 }
27141 
27142 /* Convert the generic type parameters in PARM that match the types given in the
27143    range [START_IDX, END_IDX) from the current_template_parms into generic type
27144    packs.  */
27145 
27146 tree
convert_generic_types_to_packs(tree parm,int start_idx,int end_idx)27147 convert_generic_types_to_packs (tree parm, int start_idx, int end_idx)
27148 {
27149   tree current = current_template_parms;
27150   int depth = TMPL_PARMS_DEPTH (current);
27151   current = INNERMOST_TEMPLATE_PARMS (current);
27152   tree replacement = make_tree_vec (TREE_VEC_LENGTH (current));
27153 
27154   for (int i = 0; i < start_idx; ++i)
27155     TREE_VEC_ELT (replacement, i)
27156       = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
27157 
27158   for (int i = start_idx; i < end_idx; ++i)
27159     {
27160       /* Create a distinct parameter pack type from the current parm and add it
27161 	 to the replacement args to tsubst below into the generic function
27162 	 parameter.  */
27163 
27164       tree o = TREE_TYPE (TREE_VALUE
27165 			  (TREE_VEC_ELT (current, i)));
27166       tree t = copy_type (o);
27167       TEMPLATE_TYPE_PARM_INDEX (t)
27168 	= reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (o),
27169 				      o, 0, 0, tf_none);
27170       TREE_TYPE (TEMPLATE_TYPE_DECL (t)) = t;
27171       TYPE_STUB_DECL (t) = TYPE_NAME (t) = TEMPLATE_TYPE_DECL (t);
27172       TYPE_MAIN_VARIANT (t) = t;
27173       TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
27174       TYPE_CANONICAL (t) = canonical_type_parameter (t);
27175       TREE_VEC_ELT (replacement, i) = t;
27176       TREE_VALUE (TREE_VEC_ELT (current, i)) = TREE_CHAIN (t);
27177     }
27178 
27179   for (int i = end_idx, e = TREE_VEC_LENGTH (current); i < e; ++i)
27180     TREE_VEC_ELT (replacement, i)
27181       = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
27182 
27183   /* If there are more levels then build up the replacement with the outer
27184      template parms.  */
27185   if (depth > 1)
27186     replacement = add_to_template_args (template_parms_to_args
27187 					(TREE_CHAIN (current_template_parms)),
27188 					replacement);
27189 
27190   return tsubst (parm, replacement, tf_none, NULL_TREE);
27191 }
27192 
27193 /* Entries in the decl_constraint hash table. */
27194 struct GTY((for_user)) constr_entry
27195 {
27196   tree decl;
27197   tree ci;
27198 };
27199 
27200 /* Hashing function and equality for constraint entries. */
27201 struct constr_hasher : ggc_ptr_hash<constr_entry>
27202 {
hashconstr_hasher27203   static hashval_t hash (constr_entry *e)
27204   {
27205     return (hashval_t)DECL_UID (e->decl);
27206   }
27207 
equalconstr_hasher27208   static bool equal (constr_entry *e1, constr_entry *e2)
27209   {
27210     return e1->decl == e2->decl;
27211   }
27212 };
27213 
27214 /* A mapping from declarations to constraint information. Note that
27215    both templates and their underlying declarations are mapped to the
27216    same constraint information.
27217 
27218    FIXME: This is defined in pt.c because garbage collection
27219    code is not being generated for constraint.cc. */
27220 
27221 static GTY (()) hash_table<constr_hasher> *decl_constraints;
27222 
27223 /* Returns the template constraints of declaration T. If T is not
27224    constrained, return NULL_TREE. Note that T must be non-null. */
27225 
27226 tree
get_constraints(tree t)27227 get_constraints (tree t)
27228 {
27229   if (!flag_concepts)
27230     return NULL_TREE;
27231 
27232   gcc_assert (DECL_P (t));
27233   if (TREE_CODE (t) == TEMPLATE_DECL)
27234     t = DECL_TEMPLATE_RESULT (t);
27235   constr_entry elt = { t, NULL_TREE };
27236   constr_entry* found = decl_constraints->find (&elt);
27237   if (found)
27238     return found->ci;
27239   else
27240     return NULL_TREE;
27241 }
27242 
27243 /* Associate the given constraint information CI with the declaration
27244    T. If T is a template, then the constraints are associated with
27245    its underlying declaration. Don't build associations if CI is
27246    NULL_TREE.  */
27247 
27248 void
set_constraints(tree t,tree ci)27249 set_constraints (tree t, tree ci)
27250 {
27251   if (!ci)
27252     return;
27253   gcc_assert (t && flag_concepts);
27254   if (TREE_CODE (t) == TEMPLATE_DECL)
27255     t = DECL_TEMPLATE_RESULT (t);
27256   gcc_assert (!get_constraints (t));
27257   constr_entry elt = {t, ci};
27258   constr_entry** slot = decl_constraints->find_slot (&elt, INSERT);
27259   constr_entry* entry = ggc_alloc<constr_entry> ();
27260   *entry = elt;
27261   *slot = entry;
27262 }
27263 
27264 /* Remove the associated constraints of the declaration T.  */
27265 
27266 void
remove_constraints(tree t)27267 remove_constraints (tree t)
27268 {
27269   gcc_assert (DECL_P (t));
27270   if (TREE_CODE (t) == TEMPLATE_DECL)
27271     t = DECL_TEMPLATE_RESULT (t);
27272 
27273   constr_entry elt = {t, NULL_TREE};
27274   constr_entry** slot = decl_constraints->find_slot (&elt, NO_INSERT);
27275   if (slot)
27276     decl_constraints->clear_slot (slot);
27277 }
27278 
27279 /* Memoized satisfaction results for declarations. This
27280    maps the pair (constraint_info, arguments) to the result computed
27281    by constraints_satisfied_p.  */
27282 
27283 struct GTY((for_user)) constraint_sat_entry
27284 {
27285   tree ci;
27286   tree args;
27287   tree result;
27288 };
27289 
27290 /* Hashing function and equality for constraint entries. */
27291 
27292 struct constraint_sat_hasher : ggc_ptr_hash<constraint_sat_entry>
27293 {
hashconstraint_sat_hasher27294   static hashval_t hash (constraint_sat_entry *e)
27295   {
27296     hashval_t val = iterative_hash_object(e->ci, 0);
27297     return iterative_hash_template_arg (e->args, val);
27298   }
27299 
equalconstraint_sat_hasher27300   static bool equal (constraint_sat_entry *e1, constraint_sat_entry *e2)
27301   {
27302     return e1->ci == e2->ci && comp_template_args (e1->args, e2->args);
27303   }
27304 };
27305 
27306 /* Memoized satisfaction results for concept checks. */
27307 
27308 struct GTY((for_user)) concept_spec_entry
27309 {
27310   tree tmpl;
27311   tree args;
27312   tree result;
27313 };
27314 
27315 /* Hashing function and equality for constraint entries.  */
27316 
27317 struct concept_spec_hasher : ggc_ptr_hash<concept_spec_entry>
27318 {
hashconcept_spec_hasher27319   static hashval_t hash (concept_spec_entry *e)
27320   {
27321     return hash_tmpl_and_args (e->tmpl, e->args);
27322   }
27323 
equalconcept_spec_hasher27324   static bool equal (concept_spec_entry *e1, concept_spec_entry *e2)
27325   {
27326     ++comparing_specializations;
27327     bool eq = e1->tmpl == e2->tmpl && comp_template_args (e1->args, e2->args);
27328     --comparing_specializations;
27329     return eq;
27330   }
27331 };
27332 
27333 static GTY (()) hash_table<constraint_sat_hasher> *constraint_memos;
27334 static GTY (()) hash_table<concept_spec_hasher> *concept_memos;
27335 
27336 /* Search for a memoized satisfaction result. Returns one of the
27337    truth value nodes if previously memoized, or NULL_TREE otherwise.   */
27338 
27339 tree
lookup_constraint_satisfaction(tree ci,tree args)27340 lookup_constraint_satisfaction (tree ci, tree args)
27341 {
27342   constraint_sat_entry elt = { ci, args, NULL_TREE };
27343   constraint_sat_entry* found = constraint_memos->find (&elt);
27344   if (found)
27345     return found->result;
27346   else
27347     return NULL_TREE;
27348 }
27349 
27350 /* Memoize the result of a satisfication test. Returns the saved result.  */
27351 
27352 tree
memoize_constraint_satisfaction(tree ci,tree args,tree result)27353 memoize_constraint_satisfaction (tree ci, tree args, tree result)
27354 {
27355   constraint_sat_entry elt = {ci, args, result};
27356   constraint_sat_entry** slot = constraint_memos->find_slot (&elt, INSERT);
27357   constraint_sat_entry* entry = ggc_alloc<constraint_sat_entry> ();
27358   *entry = elt;
27359   *slot = entry;
27360   return result;
27361 }
27362 
27363 /* Search for a memoized satisfaction result for a concept. */
27364 
27365 tree
lookup_concept_satisfaction(tree tmpl,tree args)27366 lookup_concept_satisfaction (tree tmpl, tree args)
27367 {
27368   concept_spec_entry elt = { tmpl, args, NULL_TREE };
27369   concept_spec_entry* found = concept_memos->find (&elt);
27370   if (found)
27371     return found->result;
27372   else
27373     return NULL_TREE;
27374 }
27375 
27376 /* Memoize the result of a concept check. Returns the saved result.  */
27377 
27378 tree
memoize_concept_satisfaction(tree tmpl,tree args,tree result)27379 memoize_concept_satisfaction (tree tmpl, tree args, tree result)
27380 {
27381   concept_spec_entry elt = {tmpl, args, result};
27382   concept_spec_entry** slot = concept_memos->find_slot (&elt, INSERT);
27383   concept_spec_entry* entry = ggc_alloc<concept_spec_entry> ();
27384   *entry = elt;
27385   *slot = entry;
27386   return result;
27387 }
27388 
27389 static GTY (()) hash_table<concept_spec_hasher> *concept_expansions;
27390 
27391 /* Returns a prior concept specialization. This returns the substituted
27392    and normalized constraints defined by the concept.  */
27393 
27394 tree
get_concept_expansion(tree tmpl,tree args)27395 get_concept_expansion (tree tmpl, tree args)
27396 {
27397   concept_spec_entry elt = { tmpl, args, NULL_TREE };
27398   concept_spec_entry* found = concept_expansions->find (&elt);
27399   if (found)
27400     return found->result;
27401   else
27402     return NULL_TREE;
27403 }
27404 
27405 /* Save a concept expansion for later.  */
27406 
27407 tree
save_concept_expansion(tree tmpl,tree args,tree def)27408 save_concept_expansion (tree tmpl, tree args, tree def)
27409 {
27410   concept_spec_entry elt = {tmpl, args, def};
27411   concept_spec_entry** slot = concept_expansions->find_slot (&elt, INSERT);
27412   concept_spec_entry* entry = ggc_alloc<concept_spec_entry> ();
27413   *entry = elt;
27414   *slot = entry;
27415   return def;
27416 }
27417 
27418 static hashval_t
hash_subsumption_args(tree t1,tree t2)27419 hash_subsumption_args (tree t1, tree t2)
27420 {
27421   gcc_assert (TREE_CODE (t1) == CHECK_CONSTR);
27422   gcc_assert (TREE_CODE (t2) == CHECK_CONSTR);
27423   int val = 0;
27424   val = iterative_hash_object (CHECK_CONSTR_CONCEPT (t1), val);
27425   val = iterative_hash_template_arg (CHECK_CONSTR_ARGS (t1), val);
27426   val = iterative_hash_object (CHECK_CONSTR_CONCEPT (t2), val);
27427   val = iterative_hash_template_arg (CHECK_CONSTR_ARGS (t2), val);
27428   return val;
27429 }
27430 
27431 /* Compare the constraints of two subsumption entries.  The LEFT1 and
27432    LEFT2 arguments comprise the first subsumption pair and the RIGHT1
27433    and RIGHT2 arguments comprise the second. These are all CHECK_CONSTRs. */
27434 
27435 static bool
comp_subsumption_args(tree left1,tree left2,tree right1,tree right2)27436 comp_subsumption_args (tree left1, tree left2, tree right1, tree right2)
27437 {
27438   if (CHECK_CONSTR_CONCEPT (left1) == CHECK_CONSTR_CONCEPT (right1))
27439     if (CHECK_CONSTR_CONCEPT (left2) == CHECK_CONSTR_CONCEPT (right2))
27440       if (comp_template_args (CHECK_CONSTR_ARGS (left1),
27441                              CHECK_CONSTR_ARGS (right1)))
27442         return comp_template_args (CHECK_CONSTR_ARGS (left2),
27443                                   CHECK_CONSTR_ARGS (right2));
27444   return false;
27445 }
27446 
27447 /* Key/value pair for learning and memoizing subsumption results. This
27448    associates a pair of check constraints (including arguments) with
27449    a boolean value indicating the result.  */
27450 
27451 struct GTY((for_user)) subsumption_entry
27452 {
27453   tree t1;
27454   tree t2;
27455   bool result;
27456 };
27457 
27458 /* Hashing function and equality for constraint entries.  */
27459 
27460 struct subsumption_hasher : ggc_ptr_hash<subsumption_entry>
27461 {
hashsubsumption_hasher27462   static hashval_t hash (subsumption_entry *e)
27463   {
27464     return hash_subsumption_args (e->t1, e->t2);
27465   }
27466 
equalsubsumption_hasher27467   static bool equal (subsumption_entry *e1, subsumption_entry *e2)
27468   {
27469     ++comparing_specializations;
27470     bool eq = comp_subsumption_args(e1->t1, e1->t2, e2->t1, e2->t2);
27471     --comparing_specializations;
27472     return eq;
27473   }
27474 };
27475 
27476 static GTY (()) hash_table<subsumption_hasher> *subsumption_table;
27477 
27478 /* Search for a previously cached subsumption result. */
27479 
27480 bool*
lookup_subsumption_result(tree t1,tree t2)27481 lookup_subsumption_result (tree t1, tree t2)
27482 {
27483   subsumption_entry elt = { t1, t2, false };
27484   subsumption_entry* found = subsumption_table->find (&elt);
27485   if (found)
27486     return &found->result;
27487   else
27488     return 0;
27489 }
27490 
27491 /* Save a subsumption result. */
27492 
27493 bool
save_subsumption_result(tree t1,tree t2,bool result)27494 save_subsumption_result (tree t1, tree t2, bool result)
27495 {
27496   subsumption_entry elt = {t1, t2, result};
27497   subsumption_entry** slot = subsumption_table->find_slot (&elt, INSERT);
27498   subsumption_entry* entry = ggc_alloc<subsumption_entry> ();
27499   *entry = elt;
27500   *slot = entry;
27501   return result;
27502 }
27503 
27504 /* Set up the hash table for constraint association. */
27505 
27506 void
init_constraint_processing(void)27507 init_constraint_processing (void)
27508 {
27509   if (!flag_concepts)
27510     return;
27511 
27512   decl_constraints = hash_table<constr_hasher>::create_ggc(37);
27513   constraint_memos = hash_table<constraint_sat_hasher>::create_ggc(37);
27514   concept_memos = hash_table<concept_spec_hasher>::create_ggc(37);
27515   concept_expansions = hash_table<concept_spec_hasher>::create_ggc(37);
27516   subsumption_table = hash_table<subsumption_hasher>::create_ggc(37);
27517 }
27518 
27519 /* __integer_pack(N) in a pack expansion expands to a sequence of numbers from
27520    0..N-1.  */
27521 
27522 void
declare_integer_pack(void)27523 declare_integer_pack (void)
27524 {
27525   tree ipfn = push_library_fn (get_identifier ("__integer_pack"),
27526 			       build_function_type_list (integer_type_node,
27527 							 integer_type_node,
27528 							 NULL_TREE),
27529 			       NULL_TREE, ECF_CONST);
27530   DECL_DECLARED_CONSTEXPR_P (ipfn) = true;
27531   DECL_BUILT_IN_CLASS (ipfn) = BUILT_IN_FRONTEND;
27532 }
27533 
27534 /* Set up the hash tables for template instantiations.  */
27535 
27536 void
init_template_processing(void)27537 init_template_processing (void)
27538 {
27539   decl_specializations = hash_table<spec_hasher>::create_ggc (37);
27540   type_specializations = hash_table<spec_hasher>::create_ggc (37);
27541 
27542   if (cxx_dialect >= cxx11)
27543     declare_integer_pack ();
27544 }
27545 
27546 /* Print stats about the template hash tables for -fstats.  */
27547 
27548 void
print_template_statistics(void)27549 print_template_statistics (void)
27550 {
27551   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
27552 	   "%f collisions\n", (long) decl_specializations->size (),
27553 	   (long) decl_specializations->elements (),
27554 	   decl_specializations->collisions ());
27555   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
27556 	   "%f collisions\n", (long) type_specializations->size (),
27557 	   (long) type_specializations->elements (),
27558 	   type_specializations->collisions ());
27559 }
27560 
27561 #if CHECKING_P
27562 
27563 namespace selftest {
27564 
27565 /* Verify that build_non_dependent_expr () works, for various expressions,
27566    and that location wrappers don't affect the results.  */
27567 
27568 static void
test_build_non_dependent_expr()27569 test_build_non_dependent_expr ()
27570 {
27571   location_t loc = BUILTINS_LOCATION;
27572 
27573   /* Verify constants, without and with location wrappers.  */
27574   tree int_cst = build_int_cst (integer_type_node, 42);
27575   ASSERT_EQ (int_cst, build_non_dependent_expr (int_cst));
27576 
27577   tree wrapped_int_cst = maybe_wrap_with_location (int_cst, loc);
27578   ASSERT_TRUE (location_wrapper_p (wrapped_int_cst));
27579   ASSERT_EQ (wrapped_int_cst, build_non_dependent_expr (wrapped_int_cst));
27580 
27581   tree string_lit = build_string (4, "foo");
27582   TREE_TYPE (string_lit) = char_array_type_node;
27583   string_lit = fix_string_type (string_lit);
27584   ASSERT_EQ (string_lit, build_non_dependent_expr (string_lit));
27585 
27586   tree wrapped_string_lit = maybe_wrap_with_location (string_lit, loc);
27587   ASSERT_TRUE (location_wrapper_p (wrapped_string_lit));
27588   ASSERT_EQ (wrapped_string_lit,
27589 	     build_non_dependent_expr (wrapped_string_lit));
27590 }
27591 
27592 /* Verify that type_dependent_expression_p () works correctly, even
27593    in the presence of location wrapper nodes.  */
27594 
27595 static void
test_type_dependent_expression_p()27596 test_type_dependent_expression_p ()
27597 {
27598   location_t loc = BUILTINS_LOCATION;
27599 
27600   tree name = get_identifier ("foo");
27601 
27602   /* If no templates are involved, nothing is type-dependent.  */
27603   gcc_assert (!processing_template_decl);
27604   ASSERT_FALSE (type_dependent_expression_p (name));
27605 
27606   ++processing_template_decl;
27607 
27608   /* Within a template, an unresolved name is always type-dependent.  */
27609   ASSERT_TRUE (type_dependent_expression_p (name));
27610 
27611   /* Ensure it copes with NULL_TREE and errors.  */
27612   ASSERT_FALSE (type_dependent_expression_p (NULL_TREE));
27613   ASSERT_FALSE (type_dependent_expression_p (error_mark_node));
27614 
27615   /* A USING_DECL in a template should be type-dependent, even if wrapped
27616      with a location wrapper (PR c++/83799).  */
27617   tree using_decl = build_lang_decl (USING_DECL, name, NULL_TREE);
27618   TREE_TYPE (using_decl) = integer_type_node;
27619   ASSERT_TRUE (type_dependent_expression_p (using_decl));
27620   tree wrapped_using_decl = maybe_wrap_with_location (using_decl, loc);
27621   ASSERT_TRUE (location_wrapper_p (wrapped_using_decl));
27622   ASSERT_TRUE (type_dependent_expression_p (wrapped_using_decl));
27623 
27624   --processing_template_decl;
27625 }
27626 
27627 /* Run all of the selftests within this file.  */
27628 
27629 void
cp_pt_c_tests()27630 cp_pt_c_tests ()
27631 {
27632   test_build_non_dependent_expr ();
27633   test_type_dependent_expression_p ();
27634 }
27635 
27636 } // namespace selftest
27637 
27638 #endif /* #if CHECKING_P */
27639 
27640 #include "gt-cp-pt.h"
27641