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     case DOTSTAR_EXPR:
11736       return build_m_component_ref (left, right, complain);
11737     default:
11738       return build_x_binary_op (input_location, code,
11739                                 left, TREE_CODE (left),
11740                                 right, TREE_CODE (right),
11741                                 /*overload=*/NULL,
11742                                 complain);
11743     }
11744 }
11745 
11746 /* Substitute ARGS into the pack of a fold expression T. */
11747 
11748 static inline tree
tsubst_fold_expr_pack(tree t,tree args,tsubst_flags_t complain,tree in_decl)11749 tsubst_fold_expr_pack (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11750 {
11751   return tsubst_pack_expansion (FOLD_EXPR_PACK (t), args, complain, in_decl);
11752 }
11753 
11754 /* Substitute ARGS into the pack of a fold expression T. */
11755 
11756 static inline tree
tsubst_fold_expr_init(tree t,tree args,tsubst_flags_t complain,tree in_decl)11757 tsubst_fold_expr_init (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11758 {
11759   return tsubst_expr (FOLD_EXPR_INIT (t), args, complain, in_decl, false);
11760 }
11761 
11762 /* Expand a PACK of arguments into a grouped as left fold.
11763    Given a pack containing elements A0, A1, ..., An and an
11764    operator @, this builds the expression:
11765 
11766       ((A0 @ A1) @ A2) ... @ An
11767 
11768    Note that PACK must not be empty.
11769 
11770    The operator is defined by the original fold expression T. */
11771 
11772 static tree
expand_left_fold(tree t,tree pack,tsubst_flags_t complain)11773 expand_left_fold (tree t, tree pack, tsubst_flags_t complain)
11774 {
11775   tree left = TREE_VEC_ELT (pack, 0);
11776   for (int i = 1; i < TREE_VEC_LENGTH (pack); ++i)
11777     {
11778       tree right = TREE_VEC_ELT (pack, i);
11779       left = fold_expression (t, left, right, complain);
11780     }
11781   return left;
11782 }
11783 
11784 /* Substitute into a unary left fold expression. */
11785 
11786 static tree
tsubst_unary_left_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)11787 tsubst_unary_left_fold (tree t, tree args, tsubst_flags_t complain,
11788                         tree in_decl)
11789 {
11790   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
11791   if (pack == error_mark_node)
11792     return error_mark_node;
11793   if (PACK_EXPANSION_P (pack))
11794     {
11795       tree r = copy_node (t);
11796       FOLD_EXPR_PACK (r) = pack;
11797       return r;
11798     }
11799   if (TREE_VEC_LENGTH (pack) == 0)
11800     return expand_empty_fold (t, complain);
11801   else
11802     return expand_left_fold (t, pack, complain);
11803 }
11804 
11805 /* Substitute into a binary left fold expression.
11806 
11807    Do ths by building a single (non-empty) vector of argumnts and
11808    building the expression from those elements. */
11809 
11810 static tree
tsubst_binary_left_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)11811 tsubst_binary_left_fold (tree t, tree args, tsubst_flags_t complain,
11812                          tree in_decl)
11813 {
11814   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
11815   if (pack == error_mark_node)
11816     return error_mark_node;
11817   tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
11818   if (init == error_mark_node)
11819     return error_mark_node;
11820 
11821   if (PACK_EXPANSION_P (pack))
11822     {
11823       tree r = copy_node (t);
11824       FOLD_EXPR_PACK (r) = pack;
11825       FOLD_EXPR_INIT (r) = init;
11826       return r;
11827     }
11828 
11829   tree vec = make_tree_vec (TREE_VEC_LENGTH (pack) + 1);
11830   TREE_VEC_ELT (vec, 0) = init;
11831   for (int i = 0; i < TREE_VEC_LENGTH (pack); ++i)
11832     TREE_VEC_ELT (vec, i + 1) = TREE_VEC_ELT (pack, i);
11833 
11834   return expand_left_fold (t, vec, complain);
11835 }
11836 
11837 /* Expand a PACK of arguments into a grouped as right fold.
11838    Given a pack containing elementns A0, A1, ..., and an
11839    operator @, this builds the expression:
11840 
11841       A0@ ... (An-2 @ (An-1 @ An))
11842 
11843    Note that PACK must not be empty.
11844 
11845    The operator is defined by the original fold expression T. */
11846 
11847 tree
expand_right_fold(tree t,tree pack,tsubst_flags_t complain)11848 expand_right_fold (tree t, tree pack, tsubst_flags_t complain)
11849 {
11850   // Build the expression.
11851   int n = TREE_VEC_LENGTH (pack);
11852   tree right = TREE_VEC_ELT (pack, n - 1);
11853   for (--n; n != 0; --n)
11854     {
11855       tree left = TREE_VEC_ELT (pack, n - 1);
11856       right = fold_expression (t, left, right, complain);
11857     }
11858   return right;
11859 }
11860 
11861 /* Substitute into a unary right fold expression. */
11862 
11863 static tree
tsubst_unary_right_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)11864 tsubst_unary_right_fold (tree t, tree args, tsubst_flags_t complain,
11865                          tree in_decl)
11866 {
11867   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
11868   if (pack == error_mark_node)
11869     return error_mark_node;
11870   if (PACK_EXPANSION_P (pack))
11871     {
11872       tree r = copy_node (t);
11873       FOLD_EXPR_PACK (r) = pack;
11874       return r;
11875     }
11876   if (TREE_VEC_LENGTH (pack) == 0)
11877     return expand_empty_fold (t, complain);
11878   else
11879     return expand_right_fold (t, pack, complain);
11880 }
11881 
11882 /* Substitute into a binary right fold expression.
11883 
11884    Do ths by building a single (non-empty) vector of arguments and
11885    building the expression from those elements. */
11886 
11887 static tree
tsubst_binary_right_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)11888 tsubst_binary_right_fold (tree t, tree args, tsubst_flags_t complain,
11889                          tree in_decl)
11890 {
11891   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
11892   if (pack == error_mark_node)
11893     return error_mark_node;
11894   tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
11895   if (init == error_mark_node)
11896     return error_mark_node;
11897 
11898   if (PACK_EXPANSION_P (pack))
11899     {
11900       tree r = copy_node (t);
11901       FOLD_EXPR_PACK (r) = pack;
11902       FOLD_EXPR_INIT (r) = init;
11903       return r;
11904     }
11905 
11906   int n = TREE_VEC_LENGTH (pack);
11907   tree vec = make_tree_vec (n + 1);
11908   for (int i = 0; i < n; ++i)
11909     TREE_VEC_ELT (vec, i) = TREE_VEC_ELT (pack, i);
11910   TREE_VEC_ELT (vec, n) = init;
11911 
11912   return expand_right_fold (t, vec, complain);
11913 }
11914 
11915 /* Walk through the pattern of a pack expansion, adding everything in
11916    local_specializations to a list.  */
11917 
11918 struct el_data
11919 {
11920   hash_set<tree> internal;
11921   tree extra;
11922   tsubst_flags_t complain;
11923 
el_datael_data11924   el_data (tsubst_flags_t c)
11925     : extra (NULL_TREE), complain (c) {}
11926 };
11927 static tree
extract_locals_r(tree * tp,int *,void * data_)11928 extract_locals_r (tree *tp, int */*walk_subtrees*/, void *data_)
11929 {
11930   el_data &data = *reinterpret_cast<el_data*>(data_);
11931   tree *extra = &data.extra;
11932   tsubst_flags_t complain = data.complain;
11933 
11934   if (TYPE_P (*tp) && typedef_variant_p (*tp))
11935     /* Remember local typedefs (85214).  */
11936     tp = &TYPE_NAME (*tp);
11937 
11938   if (TREE_CODE (*tp) == DECL_EXPR)
11939     data.internal.add (DECL_EXPR_DECL (*tp));
11940   else if (tree spec = retrieve_local_specialization (*tp))
11941     {
11942       if (data.internal.contains (*tp))
11943 	/* Don't mess with variables declared within the pattern.  */
11944 	return NULL_TREE;
11945       if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
11946 	{
11947 	  /* Maybe pull out the PARM_DECL for a partial instantiation.  */
11948 	  tree args = ARGUMENT_PACK_ARGS (spec);
11949 	  if (TREE_VEC_LENGTH (args) == 1)
11950 	    {
11951 	      tree elt = TREE_VEC_ELT (args, 0);
11952 	      if (PACK_EXPANSION_P (elt))
11953 		elt = PACK_EXPANSION_PATTERN (elt);
11954 	      if (DECL_PACK_P (elt))
11955 		spec = elt;
11956 	    }
11957 	  if (TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK)
11958 	    {
11959 	      /* Handle lambda capture here, since we aren't doing any
11960 		 substitution now, and so tsubst_copy won't call
11961 		 process_outer_var_ref.  */
11962 	      tree args = ARGUMENT_PACK_ARGS (spec);
11963 	      int len = TREE_VEC_LENGTH (args);
11964 	      for (int i = 0; i < len; ++i)
11965 		{
11966 		  tree arg = TREE_VEC_ELT (args, i);
11967 		  tree carg = arg;
11968 		  if (outer_automatic_var_p (arg))
11969 		    carg = process_outer_var_ref (arg, complain);
11970 		  if (carg != arg)
11971 		    {
11972 		      /* Make a new NONTYPE_ARGUMENT_PACK of the capture
11973 			 proxies.  */
11974 		      if (i == 0)
11975 			{
11976 			  spec = copy_node (spec);
11977 			  args = copy_node (args);
11978 			  SET_ARGUMENT_PACK_ARGS (spec, args);
11979 			  register_local_specialization (spec, *tp);
11980 			}
11981 		      TREE_VEC_ELT (args, i) = carg;
11982 		    }
11983 		}
11984 	    }
11985 	}
11986       if (outer_automatic_var_p (spec))
11987 	spec = process_outer_var_ref (spec, complain);
11988       *extra = tree_cons (*tp, spec, *extra);
11989     }
11990   return NULL_TREE;
11991 }
11992 static tree
extract_local_specs(tree pattern,tsubst_flags_t complain)11993 extract_local_specs (tree pattern, tsubst_flags_t complain)
11994 {
11995   el_data data (complain);
11996   cp_walk_tree_without_duplicates (&pattern, extract_locals_r, &data);
11997   return data.extra;
11998 }
11999 
12000 /* Extract any uses of local_specializations from PATTERN and add them to ARGS
12001    for use in PACK_EXPANSION_EXTRA_ARGS.  */
12002 
12003 tree
build_extra_args(tree pattern,tree args,tsubst_flags_t complain)12004 build_extra_args (tree pattern, tree args, tsubst_flags_t complain)
12005 {
12006   tree extra = args;
12007   if (local_specializations)
12008     if (tree locals = extract_local_specs (pattern, complain))
12009       extra = tree_cons (NULL_TREE, extra, locals);
12010   return extra;
12011 }
12012 
12013 /* Apply any local specializations from PACK_EXPANSION_EXTRA_ARGS and add the
12014    normal template args to ARGS.  */
12015 
12016 tree
add_extra_args(tree extra,tree args)12017 add_extra_args (tree extra, tree args)
12018 {
12019   if (extra && TREE_CODE (extra) == TREE_LIST)
12020     {
12021       for (tree elt = TREE_CHAIN (extra); elt; elt = TREE_CHAIN (elt))
12022 	{
12023 	  /* The partial instantiation involved local declarations collected in
12024 	     extract_local_specs; map from the general template to our local
12025 	     context.  */
12026 	  tree gen = TREE_PURPOSE (elt);
12027 	  tree inst = TREE_VALUE (elt);
12028 	  if (DECL_P (inst))
12029 	    if (tree local = retrieve_local_specialization (inst))
12030 	      inst = local;
12031 	  /* else inst is already a full instantiation of the pack.  */
12032 	  register_local_specialization (inst, gen);
12033 	}
12034       gcc_assert (!TREE_PURPOSE (extra));
12035       extra = TREE_VALUE (extra);
12036     }
12037   return add_to_template_args (extra, args);
12038 }
12039 
12040 /* Substitute ARGS into T, which is an pack expansion
12041    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
12042    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
12043    (if only a partial substitution could be performed) or
12044    ERROR_MARK_NODE if there was an error.  */
12045 tree
tsubst_pack_expansion(tree t,tree args,tsubst_flags_t complain,tree in_decl)12046 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
12047 		       tree in_decl)
12048 {
12049   tree pattern;
12050   tree pack, packs = NULL_TREE;
12051   bool unsubstituted_packs = false;
12052   bool unsubstituted_fn_pack = false;
12053   int i, len = -1;
12054   tree result;
12055   hash_map<tree, tree> *saved_local_specializations = NULL;
12056   bool need_local_specializations = false;
12057   int levels;
12058 
12059   gcc_assert (PACK_EXPANSION_P (t));
12060   pattern = PACK_EXPANSION_PATTERN (t);
12061 
12062   /* Add in any args remembered from an earlier partial instantiation.  */
12063   args = add_extra_args (PACK_EXPANSION_EXTRA_ARGS (t), args);
12064 
12065   levels = TMPL_ARGS_DEPTH (args);
12066 
12067   /* Determine the argument packs that will instantiate the parameter
12068      packs used in the expansion expression. While we're at it,
12069      compute the number of arguments to be expanded and make sure it
12070      is consistent.  */
12071   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
12072        pack = TREE_CHAIN (pack))
12073     {
12074       tree parm_pack = TREE_VALUE (pack);
12075       tree arg_pack = NULL_TREE;
12076       tree orig_arg = NULL_TREE;
12077       int level = 0;
12078 
12079       if (TREE_CODE (parm_pack) == BASES)
12080 	{
12081 	  gcc_assert (parm_pack == pattern);
12082 	  if (BASES_DIRECT (parm_pack))
12083 	    return calculate_direct_bases (tsubst_expr (BASES_TYPE (parm_pack),
12084 							args, complain,
12085 							in_decl, false),
12086 					   complain);
12087 	  else
12088 	    return calculate_bases (tsubst_expr (BASES_TYPE (parm_pack),
12089 						 args, complain, in_decl,
12090 						 false), complain);
12091 	}
12092       else if (builtin_pack_call_p (parm_pack))
12093 	{
12094 	  /* ??? Support use in other patterns.  */
12095 	  gcc_assert (parm_pack == pattern);
12096 	  return expand_builtin_pack_call (parm_pack, args,
12097 					   complain, in_decl);
12098 	}
12099       else if (TREE_CODE (parm_pack) == PARM_DECL)
12100 	{
12101 	  /* We know we have correct local_specializations if this
12102 	     expansion is at function scope, or if we're dealing with a
12103 	     local parameter in a requires expression; for the latter,
12104 	     tsubst_requires_expr set it up appropriately.  */
12105 	  if (PACK_EXPANSION_LOCAL_P (t) || CONSTRAINT_VAR_P (parm_pack))
12106 	    arg_pack = retrieve_local_specialization (parm_pack);
12107 	  else
12108 	    /* We can't rely on local_specializations for a parameter
12109 	       name used later in a function declaration (such as in a
12110 	       late-specified return type).  Even if it exists, it might
12111 	       have the wrong value for a recursive call.  */
12112 	    need_local_specializations = true;
12113 
12114 	  if (!arg_pack)
12115 	    {
12116 	      /* This parameter pack was used in an unevaluated context.  Just
12117 		 make a dummy decl, since it's only used for its type.  */
12118 	      ++cp_unevaluated_operand;
12119 	      arg_pack = tsubst_decl (parm_pack, args, complain);
12120 	      --cp_unevaluated_operand;
12121 	      if (arg_pack && DECL_PACK_P (arg_pack))
12122 		/* Partial instantiation of the parm_pack, we can't build
12123 		   up an argument pack yet.  */
12124 		arg_pack = NULL_TREE;
12125 	      else
12126 		arg_pack = make_fnparm_pack (arg_pack);
12127 	    }
12128 	  else if (argument_pack_element_is_expansion_p (arg_pack, 0))
12129 	    /* This argument pack isn't fully instantiated yet.  We set this
12130 	       flag rather than clear arg_pack because we do want to do the
12131 	       optimization below, and we don't want to substitute directly
12132 	       into the pattern (as that would expose a NONTYPE_ARGUMENT_PACK
12133 	       where it isn't expected).  */
12134 	    unsubstituted_fn_pack = true;
12135 	}
12136       else if (is_normal_capture_proxy (parm_pack))
12137 	{
12138 	  arg_pack = retrieve_local_specialization (parm_pack);
12139 	  if (argument_pack_element_is_expansion_p (arg_pack, 0))
12140 	    unsubstituted_fn_pack = true;
12141 	}
12142       else
12143         {
12144 	  int idx;
12145           template_parm_level_and_index (parm_pack, &level, &idx);
12146 
12147           if (level <= levels)
12148             arg_pack = TMPL_ARG (args, level, idx);
12149         }
12150 
12151       orig_arg = arg_pack;
12152       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
12153 	arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
12154 
12155       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
12156 	/* This can only happen if we forget to expand an argument
12157 	   pack somewhere else. Just return an error, silently.  */
12158 	{
12159 	  result = make_tree_vec (1);
12160 	  TREE_VEC_ELT (result, 0) = error_mark_node;
12161 	  return result;
12162 	}
12163 
12164       if (arg_pack)
12165         {
12166           int my_len =
12167             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
12168 
12169 	  /* Don't bother trying to do a partial substitution with
12170 	     incomplete packs; we'll try again after deduction.  */
12171           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
12172             return t;
12173 
12174           if (len < 0)
12175 	    len = my_len;
12176           else if (len != my_len
12177 		   && !unsubstituted_fn_pack)
12178             {
12179 	      if (!(complain & tf_error))
12180 		/* Fail quietly.  */;
12181               else if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
12182                 error ("mismatched argument pack lengths while expanding %qT",
12183                        pattern);
12184               else
12185                 error ("mismatched argument pack lengths while expanding %qE",
12186                        pattern);
12187               return error_mark_node;
12188             }
12189 
12190           /* Keep track of the parameter packs and their corresponding
12191              argument packs.  */
12192           packs = tree_cons (parm_pack, arg_pack, packs);
12193           TREE_TYPE (packs) = orig_arg;
12194         }
12195       else
12196 	{
12197 	  /* We can't substitute for this parameter pack.  We use a flag as
12198 	     well as the missing_level counter because function parameter
12199 	     packs don't have a level.  */
12200 	  gcc_assert (processing_template_decl || is_auto (parm_pack));
12201 	  unsubstituted_packs = true;
12202 	}
12203     }
12204 
12205   /* If the expansion is just T..., return the matching argument pack, unless
12206      we need to call convert_from_reference on all the elements.  This is an
12207      important optimization; see c++/68422.  */
12208   if (!unsubstituted_packs
12209       && TREE_PURPOSE (packs) == pattern)
12210     {
12211       tree args = ARGUMENT_PACK_ARGS (TREE_VALUE (packs));
12212 
12213       /* If the argument pack is a single pack expansion, pull it out.  */
12214       if (TREE_VEC_LENGTH (args) == 1
12215 	  && pack_expansion_args_count (args))
12216 	return TREE_VEC_ELT (args, 0);
12217 
12218       /* Types need no adjustment, nor does sizeof..., and if we still have
12219 	 some pack expansion args we won't do anything yet.  */
12220       if (TREE_CODE (t) == TYPE_PACK_EXPANSION
12221 	  || PACK_EXPANSION_SIZEOF_P (t)
12222 	  || pack_expansion_args_count (args))
12223 	return args;
12224       /* Also optimize expression pack expansions if we can tell that the
12225 	 elements won't have reference type.  */
12226       tree type = TREE_TYPE (pattern);
12227       if (type && TREE_CODE (type) != REFERENCE_TYPE
12228 	  && !PACK_EXPANSION_P (type)
12229 	  && !WILDCARD_TYPE_P (type))
12230 	return args;
12231       /* Otherwise use the normal path so we get convert_from_reference.  */
12232     }
12233 
12234   /* We cannot expand this expansion expression, because we don't have
12235      all of the argument packs we need.  */
12236   if (use_pack_expansion_extra_args_p (packs, len, unsubstituted_packs))
12237     {
12238       /* We got some full packs, but we can't substitute them in until we
12239 	 have values for all the packs.  So remember these until then.  */
12240 
12241       t = make_pack_expansion (pattern, complain);
12242       PACK_EXPANSION_EXTRA_ARGS (t)
12243 	= build_extra_args (pattern, args, complain);
12244       return t;
12245     }
12246   else if (unsubstituted_packs)
12247     {
12248       /* There were no real arguments, we're just replacing a parameter
12249 	 pack with another version of itself. Substitute into the
12250 	 pattern and return a PACK_EXPANSION_*. The caller will need to
12251 	 deal with that.  */
12252       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
12253 	t = tsubst_expr (pattern, args, complain, in_decl,
12254 			 /*integral_constant_expression_p=*/false);
12255       else
12256 	t = tsubst (pattern, args, complain, in_decl);
12257       t = make_pack_expansion (t, complain);
12258       return t;
12259     }
12260 
12261   gcc_assert (len >= 0);
12262 
12263   if (need_local_specializations)
12264     {
12265       /* We're in a late-specified return type, so create our own local
12266 	 specializations map; the current map is either NULL or (in the
12267 	 case of recursive unification) might have bindings that we don't
12268 	 want to use or alter.  */
12269       saved_local_specializations = local_specializations;
12270       local_specializations = new hash_map<tree, tree>;
12271     }
12272 
12273   /* For each argument in each argument pack, substitute into the
12274      pattern.  */
12275   result = make_tree_vec (len);
12276   tree elem_args = copy_template_args (args);
12277   for (i = 0; i < len; ++i)
12278     {
12279       t = gen_elem_of_pack_expansion_instantiation (pattern, packs,
12280 						    i,
12281 						    elem_args, complain,
12282 						    in_decl);
12283       TREE_VEC_ELT (result, i) = t;
12284       if (t == error_mark_node)
12285 	{
12286 	  result = error_mark_node;
12287 	  break;
12288 	}
12289     }
12290 
12291   /* Update ARGS to restore the substitution from parameter packs to
12292      their argument packs.  */
12293   for (pack = packs; pack; pack = TREE_CHAIN (pack))
12294     {
12295       tree parm = TREE_PURPOSE (pack);
12296 
12297       if (TREE_CODE (parm) == PARM_DECL
12298 	  || VAR_P (parm)
12299 	  || TREE_CODE (parm) == FIELD_DECL)
12300         register_local_specialization (TREE_TYPE (pack), parm);
12301       else
12302         {
12303           int idx, level;
12304 
12305 	  if (TREE_VALUE (pack) == NULL_TREE)
12306 	    continue;
12307 
12308           template_parm_level_and_index (parm, &level, &idx);
12309 
12310           /* Update the corresponding argument.  */
12311           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
12312             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
12313               TREE_TYPE (pack);
12314           else
12315             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
12316         }
12317     }
12318 
12319   if (need_local_specializations)
12320     {
12321       delete local_specializations;
12322       local_specializations = saved_local_specializations;
12323     }
12324 
12325   /* If the dependent pack arguments were such that we end up with only a
12326      single pack expansion again, there's no need to keep it in a TREE_VEC.  */
12327   if (len == 1 && TREE_CODE (result) == TREE_VEC
12328       && PACK_EXPANSION_P (TREE_VEC_ELT (result, 0)))
12329     return TREE_VEC_ELT (result, 0);
12330 
12331   return result;
12332 }
12333 
12334 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
12335    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
12336    parameter packs; all parms generated from a function parameter pack will
12337    have the same DECL_PARM_INDEX.  */
12338 
12339 tree
get_pattern_parm(tree parm,tree tmpl)12340 get_pattern_parm (tree parm, tree tmpl)
12341 {
12342   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
12343   tree patparm;
12344 
12345   if (DECL_ARTIFICIAL (parm))
12346     {
12347       for (patparm = DECL_ARGUMENTS (pattern);
12348 	   patparm; patparm = DECL_CHAIN (patparm))
12349 	if (DECL_ARTIFICIAL (patparm)
12350 	    && DECL_NAME (parm) == DECL_NAME (patparm))
12351 	  break;
12352     }
12353   else
12354     {
12355       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
12356       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
12357       gcc_assert (DECL_PARM_INDEX (patparm)
12358 		  == DECL_PARM_INDEX (parm));
12359     }
12360 
12361   return patparm;
12362 }
12363 
12364 /* Make an argument pack out of the TREE_VEC VEC.  */
12365 
12366 static tree
make_argument_pack(tree vec)12367 make_argument_pack (tree vec)
12368 {
12369   tree pack;
12370   tree elt = TREE_VEC_ELT (vec, 0);
12371   if (TYPE_P (elt))
12372     pack = cxx_make_type (TYPE_ARGUMENT_PACK);
12373   else
12374     {
12375       pack = make_node (NONTYPE_ARGUMENT_PACK);
12376       TREE_CONSTANT (pack) = 1;
12377     }
12378   SET_ARGUMENT_PACK_ARGS (pack, vec);
12379   return pack;
12380 }
12381 
12382 /* Return an exact copy of template args T that can be modified
12383    independently.  */
12384 
12385 static tree
copy_template_args(tree t)12386 copy_template_args (tree t)
12387 {
12388   if (t == error_mark_node)
12389     return t;
12390 
12391   int len = TREE_VEC_LENGTH (t);
12392   tree new_vec = make_tree_vec (len);
12393 
12394   for (int i = 0; i < len; ++i)
12395     {
12396       tree elt = TREE_VEC_ELT (t, i);
12397       if (elt && TREE_CODE (elt) == TREE_VEC)
12398 	elt = copy_template_args (elt);
12399       TREE_VEC_ELT (new_vec, i) = elt;
12400     }
12401 
12402   NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_vec)
12403     = NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
12404 
12405   return new_vec;
12406 }
12407 
12408 /* Substitute ARGS into the vector or list of template arguments T.  */
12409 
12410 static tree
tsubst_template_args(tree t,tree args,tsubst_flags_t complain,tree in_decl)12411 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12412 {
12413   tree orig_t = t;
12414   int len, need_new = 0, i, expanded_len_adjust = 0, out;
12415   tree *elts;
12416 
12417   if (t == error_mark_node)
12418     return error_mark_node;
12419 
12420   len = TREE_VEC_LENGTH (t);
12421   elts = XALLOCAVEC (tree, len);
12422 
12423   for (i = 0; i < len; i++)
12424     {
12425       tree orig_arg = TREE_VEC_ELT (t, i);
12426       tree new_arg;
12427 
12428       if (TREE_CODE (orig_arg) == TREE_VEC)
12429 	new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
12430       else if (PACK_EXPANSION_P (orig_arg))
12431         {
12432           /* Substitute into an expansion expression.  */
12433           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
12434 
12435           if (TREE_CODE (new_arg) == TREE_VEC)
12436             /* Add to the expanded length adjustment the number of
12437                expanded arguments. We subtract one from this
12438                measurement, because the argument pack expression
12439                itself is already counted as 1 in
12440                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
12441                the argument pack is empty.  */
12442             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
12443         }
12444       else if (ARGUMENT_PACK_P (orig_arg))
12445         {
12446           /* Substitute into each of the arguments.  */
12447           new_arg = TYPE_P (orig_arg)
12448             ? cxx_make_type (TREE_CODE (orig_arg))
12449             : make_node (TREE_CODE (orig_arg));
12450 
12451 	  tree pack_args = tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
12452 						 args, complain, in_decl);
12453           if (pack_args == error_mark_node)
12454             new_arg = error_mark_node;
12455 	  else
12456 	    SET_ARGUMENT_PACK_ARGS (new_arg, pack_args);
12457 
12458           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK)
12459 	    TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
12460         }
12461       else
12462 	new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
12463 
12464       if (new_arg == error_mark_node)
12465 	return error_mark_node;
12466 
12467       elts[i] = new_arg;
12468       if (new_arg != orig_arg)
12469 	need_new = 1;
12470     }
12471 
12472   if (!need_new)
12473     return t;
12474 
12475   /* Make space for the expanded arguments coming from template
12476      argument packs.  */
12477   t = make_tree_vec (len + expanded_len_adjust);
12478   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
12479      arguments for a member template.
12480      In that case each TREE_VEC in ORIG_T represents a level of template
12481      arguments, and ORIG_T won't carry any non defaulted argument count.
12482      It will rather be the nested TREE_VECs that will carry one.
12483      In other words, ORIG_T carries a non defaulted argument count only
12484      if it doesn't contain any nested TREE_VEC.  */
12485   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
12486     {
12487       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
12488       count += expanded_len_adjust;
12489       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
12490     }
12491   for (i = 0, out = 0; i < len; i++)
12492     {
12493       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
12494            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
12495           && TREE_CODE (elts[i]) == TREE_VEC)
12496         {
12497           int idx;
12498 
12499           /* Now expand the template argument pack "in place".  */
12500           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
12501             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
12502         }
12503       else
12504         {
12505           TREE_VEC_ELT (t, out) = elts[i];
12506           out++;
12507         }
12508     }
12509 
12510   return t;
12511 }
12512 
12513 /* Substitute ARGS into one level PARMS of template parameters.  */
12514 
12515 static tree
tsubst_template_parms_level(tree parms,tree args,tsubst_flags_t complain)12516 tsubst_template_parms_level (tree parms, tree args, tsubst_flags_t complain)
12517 {
12518   if (parms == error_mark_node)
12519     return error_mark_node;
12520 
12521   tree new_vec = make_tree_vec (TREE_VEC_LENGTH (parms));
12522 
12523   for (int i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
12524     {
12525       tree tuple = TREE_VEC_ELT (parms, i);
12526 
12527       if (tuple == error_mark_node)
12528 	continue;
12529 
12530       TREE_VEC_ELT (new_vec, i) =
12531 	tsubst_template_parm (tuple, args, complain);
12532     }
12533 
12534   return new_vec;
12535 }
12536 
12537 /* Return the result of substituting ARGS into the template parameters
12538    given by PARMS.  If there are m levels of ARGS and m + n levels of
12539    PARMS, then the result will contain n levels of PARMS.  For
12540    example, if PARMS is `template <class T> template <class U>
12541    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
12542    result will be `template <int*, double, class V>'.  */
12543 
12544 static tree
tsubst_template_parms(tree parms,tree args,tsubst_flags_t complain)12545 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
12546 {
12547   tree r = NULL_TREE;
12548   tree* new_parms;
12549 
12550   /* When substituting into a template, we must set
12551      PROCESSING_TEMPLATE_DECL as the template parameters may be
12552      dependent if they are based on one-another, and the dependency
12553      predicates are short-circuit outside of templates.  */
12554   ++processing_template_decl;
12555 
12556   for (new_parms = &r;
12557        parms && TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
12558        new_parms = &(TREE_CHAIN (*new_parms)),
12559 	 parms = TREE_CHAIN (parms))
12560     {
12561       tree new_vec = tsubst_template_parms_level (TREE_VALUE (parms),
12562 						  args, complain);
12563       *new_parms =
12564 	tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
12565 			     - TMPL_ARGS_DEPTH (args)),
12566 		   new_vec, NULL_TREE);
12567     }
12568 
12569   --processing_template_decl;
12570 
12571   return r;
12572 }
12573 
12574 /* Return the result of substituting ARGS into one template parameter
12575    given by T. T Must be a TREE_LIST which TREE_VALUE is the template
12576    parameter and which TREE_PURPOSE is the default argument of the
12577    template parameter.  */
12578 
12579 static tree
tsubst_template_parm(tree t,tree args,tsubst_flags_t complain)12580 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
12581 {
12582   tree default_value, parm_decl;
12583 
12584   if (args == NULL_TREE
12585       || t == NULL_TREE
12586       || t == error_mark_node)
12587     return t;
12588 
12589   gcc_assert (TREE_CODE (t) == TREE_LIST);
12590 
12591   default_value = TREE_PURPOSE (t);
12592   parm_decl = TREE_VALUE (t);
12593 
12594   parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
12595   if (TREE_CODE (parm_decl) == PARM_DECL
12596       && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
12597     parm_decl = error_mark_node;
12598   default_value = tsubst_template_arg (default_value, args,
12599 				       complain, NULL_TREE);
12600 
12601   return build_tree_list (default_value, parm_decl);
12602 }
12603 
12604 /* Substitute the ARGS into the indicated aggregate (or enumeration)
12605    type T.  If T is not an aggregate or enumeration type, it is
12606    handled as if by tsubst.  IN_DECL is as for tsubst.  If
12607    ENTERING_SCOPE is nonzero, T is the context for a template which
12608    we are presently tsubst'ing.  Return the substituted value.  */
12609 
12610 static tree
tsubst_aggr_type(tree t,tree args,tsubst_flags_t complain,tree in_decl,int entering_scope)12611 tsubst_aggr_type (tree t,
12612 		  tree args,
12613 		  tsubst_flags_t complain,
12614 		  tree in_decl,
12615 		  int entering_scope)
12616 {
12617   if (t == NULL_TREE)
12618     return NULL_TREE;
12619 
12620   switch (TREE_CODE (t))
12621     {
12622     case RECORD_TYPE:
12623       if (TYPE_PTRMEMFUNC_P (t))
12624 	return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
12625 
12626       /* Fall through.  */
12627     case ENUMERAL_TYPE:
12628     case UNION_TYPE:
12629       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
12630 	{
12631 	  tree argvec;
12632 	  tree context;
12633 	  tree r;
12634 	  int saved_unevaluated_operand;
12635 	  int saved_inhibit_evaluation_warnings;
12636 
12637 	  /* In "sizeof(X<I>)" we need to evaluate "I".  */
12638 	  saved_unevaluated_operand = cp_unevaluated_operand;
12639 	  cp_unevaluated_operand = 0;
12640 	  saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
12641 	  c_inhibit_evaluation_warnings = 0;
12642 
12643 	  /* First, determine the context for the type we are looking
12644 	     up.  */
12645 	  context = TYPE_CONTEXT (t);
12646 	  if (context && TYPE_P (context))
12647 	    {
12648 	      context = tsubst_aggr_type (context, args, complain,
12649 					  in_decl, /*entering_scope=*/1);
12650 	      /* If context is a nested class inside a class template,
12651 	         it may still need to be instantiated (c++/33959).  */
12652 	      context = complete_type (context);
12653 	    }
12654 
12655 	  /* Then, figure out what arguments are appropriate for the
12656 	     type we are trying to find.  For example, given:
12657 
12658 	       template <class T> struct S;
12659 	       template <class T, class U> void f(T, U) { S<U> su; }
12660 
12661 	     and supposing that we are instantiating f<int, double>,
12662 	     then our ARGS will be {int, double}, but, when looking up
12663 	     S we only want {double}.  */
12664 	  argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
12665 					 complain, in_decl);
12666 	  if (argvec == error_mark_node)
12667 	    r = error_mark_node;
12668 	  else
12669 	    {
12670 	      r = lookup_template_class (t, argvec, in_decl, context,
12671 					 entering_scope, complain);
12672 	      r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
12673 	    }
12674 
12675 	  cp_unevaluated_operand = saved_unevaluated_operand;
12676 	  c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
12677 
12678 	  return r;
12679 	}
12680       else
12681 	/* This is not a template type, so there's nothing to do.  */
12682 	return t;
12683 
12684     default:
12685       return tsubst (t, args, complain, in_decl);
12686     }
12687 }
12688 
12689 static GTY((cache)) tree_cache_map *defarg_inst;
12690 
12691 /* Substitute into the default argument ARG (a default argument for
12692    FN), which has the indicated TYPE.  */
12693 
12694 tree
tsubst_default_argument(tree fn,int parmnum,tree type,tree arg,tsubst_flags_t complain)12695 tsubst_default_argument (tree fn, int parmnum, tree type, tree arg,
12696 			 tsubst_flags_t complain)
12697 {
12698   tree saved_class_ptr = NULL_TREE;
12699   tree saved_class_ref = NULL_TREE;
12700   int errs = errorcount + sorrycount;
12701 
12702   /* This can happen in invalid code.  */
12703   if (TREE_CODE (arg) == DEFAULT_ARG)
12704     return arg;
12705 
12706   tree parm = FUNCTION_FIRST_USER_PARM (fn);
12707   parm = chain_index (parmnum, parm);
12708   tree parmtype = TREE_TYPE (parm);
12709   if (DECL_BY_REFERENCE (parm))
12710     parmtype = TREE_TYPE (parmtype);
12711   if (parmtype == error_mark_node)
12712     return error_mark_node;
12713 
12714   gcc_assert (same_type_ignoring_top_level_qualifiers_p (type, parmtype));
12715 
12716   tree *slot;
12717   if (defarg_inst && (slot = defarg_inst->get (parm)))
12718     return *slot;
12719 
12720   /* This default argument came from a template.  Instantiate the
12721      default argument here, not in tsubst.  In the case of
12722      something like:
12723 
12724        template <class T>
12725        struct S {
12726 	 static T t();
12727 	 void f(T = t());
12728        };
12729 
12730      we must be careful to do name lookup in the scope of S<T>,
12731      rather than in the current class.  */
12732   push_access_scope (fn);
12733   /* The "this" pointer is not valid in a default argument.  */
12734   if (cfun)
12735     {
12736       saved_class_ptr = current_class_ptr;
12737       cp_function_chain->x_current_class_ptr = NULL_TREE;
12738       saved_class_ref = current_class_ref;
12739       cp_function_chain->x_current_class_ref = NULL_TREE;
12740     }
12741 
12742   start_lambda_scope (parm);
12743 
12744   push_deferring_access_checks(dk_no_deferred);
12745   /* The default argument expression may cause implicitly defined
12746      member functions to be synthesized, which will result in garbage
12747      collection.  We must treat this situation as if we were within
12748      the body of function so as to avoid collecting live data on the
12749      stack.  */
12750   ++function_depth;
12751   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
12752 		     complain, NULL_TREE,
12753 		     /*integral_constant_expression_p=*/false);
12754   --function_depth;
12755   pop_deferring_access_checks();
12756 
12757   finish_lambda_scope ();
12758 
12759   /* Restore the "this" pointer.  */
12760   if (cfun)
12761     {
12762       cp_function_chain->x_current_class_ptr = saved_class_ptr;
12763       cp_function_chain->x_current_class_ref = saved_class_ref;
12764     }
12765 
12766   if (errorcount+sorrycount > errs
12767       && (complain & tf_warning_or_error))
12768     inform (input_location,
12769 	    "  when instantiating default argument for call to %qD", fn);
12770 
12771   /* Make sure the default argument is reasonable.  */
12772   arg = check_default_argument (type, arg, complain);
12773 
12774   pop_access_scope (fn);
12775 
12776   if (arg != error_mark_node && !cp_unevaluated_operand)
12777     {
12778       if (!defarg_inst)
12779 	defarg_inst = tree_cache_map::create_ggc (37);
12780       defarg_inst->put (parm, arg);
12781     }
12782 
12783   return arg;
12784 }
12785 
12786 /* Substitute into all the default arguments for FN.  */
12787 
12788 static void
tsubst_default_arguments(tree fn,tsubst_flags_t complain)12789 tsubst_default_arguments (tree fn, tsubst_flags_t complain)
12790 {
12791   tree arg;
12792   tree tmpl_args;
12793 
12794   tmpl_args = DECL_TI_ARGS (fn);
12795 
12796   /* If this function is not yet instantiated, we certainly don't need
12797      its default arguments.  */
12798   if (uses_template_parms (tmpl_args))
12799     return;
12800   /* Don't do this again for clones.  */
12801   if (DECL_CLONED_FUNCTION_P (fn))
12802     return;
12803 
12804   int i = 0;
12805   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
12806        arg;
12807        arg = TREE_CHAIN (arg), ++i)
12808     if (TREE_PURPOSE (arg))
12809       TREE_PURPOSE (arg) = tsubst_default_argument (fn, i,
12810 						    TREE_VALUE (arg),
12811 						    TREE_PURPOSE (arg),
12812 						    complain);
12813 }
12814 
12815 /* Subroutine of tsubst_decl for the case when T is a FUNCTION_DECL.  */
12816 
12817 static tree
tsubst_function_decl(tree t,tree args,tsubst_flags_t complain,tree lambda_fntype)12818 tsubst_function_decl (tree t, tree args, tsubst_flags_t complain,
12819 		      tree lambda_fntype)
12820 {
12821   tree gen_tmpl, argvec;
12822   hashval_t hash = 0;
12823   tree in_decl = t;
12824 
12825   /* Nobody should be tsubst'ing into non-template functions.  */
12826   gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
12827 
12828   if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
12829     {
12830       /* If T is not dependent, just return it.  */
12831       if (!uses_template_parms (DECL_TI_ARGS (t)))
12832 	return t;
12833 
12834       /* Calculate the most general template of which R is a
12835 	 specialization.  */
12836       gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
12837 
12838       /* We're substituting a lambda function under tsubst_lambda_expr but not
12839 	 directly from it; find the matching function we're already inside.
12840 	 But don't do this if T is a generic lambda with a single level of
12841 	 template parms, as in that case we're doing a normal instantiation. */
12842       if (LAMBDA_FUNCTION_P (t) && !lambda_fntype
12843 	  && (!generic_lambda_fn_p (t)
12844 	      || TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)) > 1))
12845 	return enclosing_instantiation_of (t);
12846 
12847       /* Calculate the complete set of arguments used to
12848 	 specialize R.  */
12849       argvec = tsubst_template_args (DECL_TI_ARGS
12850 				     (DECL_TEMPLATE_RESULT
12851 				      (DECL_TI_TEMPLATE (t))),
12852 				     args, complain, in_decl);
12853       if (argvec == error_mark_node)
12854 	return error_mark_node;
12855 
12856       /* Check to see if we already have this specialization.  */
12857       if (!lambda_fntype)
12858 	{
12859 	  hash = hash_tmpl_and_args (gen_tmpl, argvec);
12860 	  if (tree spec = retrieve_specialization (gen_tmpl, argvec, hash))
12861 	    return spec;
12862 	}
12863 
12864       /* We can see more levels of arguments than parameters if
12865 	 there was a specialization of a member template, like
12866 	 this:
12867 
12868 	 template <class T> struct S { template <class U> void f(); }
12869 	 template <> template <class U> void S<int>::f(U);
12870 
12871 	 Here, we'll be substituting into the specialization,
12872 	 because that's where we can find the code we actually
12873 	 want to generate, but we'll have enough arguments for
12874 	 the most general template.
12875 
12876 	 We also deal with the peculiar case:
12877 
12878 	 template <class T> struct S {
12879 	   template <class U> friend void f();
12880 	 };
12881 	 template <class U> void f() {}
12882 	 template S<int>;
12883 	 template void f<double>();
12884 
12885 	 Here, the ARGS for the instantiation of will be {int,
12886 	 double}.  But, we only need as many ARGS as there are
12887 	 levels of template parameters in CODE_PATTERN.  We are
12888 	 careful not to get fooled into reducing the ARGS in
12889 	 situations like:
12890 
12891 	 template <class T> struct S { template <class U> void f(U); }
12892 	 template <class T> template <> void S<T>::f(int) {}
12893 
12894 	 which we can spot because the pattern will be a
12895 	 specialization in this case.  */
12896       int args_depth = TMPL_ARGS_DEPTH (args);
12897       int parms_depth =
12898 	TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
12899 
12900       if (args_depth > parms_depth && !DECL_TEMPLATE_SPECIALIZATION (t))
12901 	args = get_innermost_template_args (args, parms_depth);
12902     }
12903   else
12904     {
12905       /* This special case arises when we have something like this:
12906 
12907 	 template <class T> struct S {
12908 	 friend void f<int>(int, double);
12909 	 };
12910 
12911 	 Here, the DECL_TI_TEMPLATE for the friend declaration
12912 	 will be an IDENTIFIER_NODE.  We are being called from
12913 	 tsubst_friend_function, and we want only to create a
12914 	 new decl (R) with appropriate types so that we can call
12915 	 determine_specialization.  */
12916       gen_tmpl = NULL_TREE;
12917       argvec = NULL_TREE;
12918     }
12919 
12920   tree closure = (lambda_fntype ? TYPE_METHOD_BASETYPE (lambda_fntype)
12921 		  : NULL_TREE);
12922   tree ctx = closure ? closure : DECL_CONTEXT (t);
12923   bool member = ctx && TYPE_P (ctx);
12924 
12925   if (member && !closure)
12926     ctx = tsubst_aggr_type (ctx, args,
12927 			    complain, t, /*entering_scope=*/1);
12928 
12929   tree type = (lambda_fntype ? lambda_fntype
12930 	       : tsubst (TREE_TYPE (t), args,
12931 			 complain | tf_fndecl_type, in_decl));
12932   if (type == error_mark_node)
12933     return error_mark_node;
12934 
12935   /* If we hit excessive deduction depth, the type is bogus even if
12936      it isn't error_mark_node, so don't build a decl.  */
12937   if (excessive_deduction_depth)
12938     return error_mark_node;
12939 
12940   /* We do NOT check for matching decls pushed separately at this
12941      point, as they may not represent instantiations of this
12942      template, and in any case are considered separate under the
12943      discrete model.  */
12944   tree r = copy_decl (t);
12945   DECL_USE_TEMPLATE (r) = 0;
12946   TREE_TYPE (r) = type;
12947   /* Clear out the mangled name and RTL for the instantiation.  */
12948   SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
12949   SET_DECL_RTL (r, NULL);
12950   /* Leave DECL_INITIAL set on deleted instantiations.  */
12951   if (!DECL_DELETED_FN (r))
12952     DECL_INITIAL (r) = NULL_TREE;
12953   DECL_CONTEXT (r) = ctx;
12954 
12955   /* OpenMP UDRs have the only argument a reference to the declared
12956      type.  We want to diagnose if the declared type is a reference,
12957      which is invalid, but as references to references are usually
12958      quietly merged, diagnose it here.  */
12959   if (DECL_OMP_DECLARE_REDUCTION_P (t))
12960     {
12961       tree argtype
12962 	= TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (t))));
12963       argtype = tsubst (argtype, args, complain, in_decl);
12964       if (TREE_CODE (argtype) == REFERENCE_TYPE)
12965 	error_at (DECL_SOURCE_LOCATION (t),
12966 		  "reference type %qT in "
12967 		  "%<#pragma omp declare reduction%>", argtype);
12968       if (strchr (IDENTIFIER_POINTER (DECL_NAME (t)), '~') == NULL)
12969 	DECL_NAME (r) = omp_reduction_id (ERROR_MARK, DECL_NAME (t),
12970 					  argtype);
12971     }
12972 
12973   if (member && DECL_CONV_FN_P (r))
12974     /* Type-conversion operator.  Reconstruct the name, in
12975        case it's the name of one of the template's parameters.  */
12976     DECL_NAME (r) = make_conv_op_name (TREE_TYPE (type));
12977 
12978   tree parms = DECL_ARGUMENTS (t);
12979   if (closure)
12980     parms = DECL_CHAIN (parms);
12981   parms = tsubst (parms, args, complain, t);
12982   for (tree parm = parms; parm; parm = DECL_CHAIN (parm))
12983     DECL_CONTEXT (parm) = r;
12984   if (closure)
12985     {
12986       tree tparm = build_this_parm (r, closure, type_memfn_quals (type));
12987       DECL_CHAIN (tparm) = parms;
12988       parms = tparm;
12989     }
12990   DECL_ARGUMENTS (r) = parms;
12991   DECL_RESULT (r) = NULL_TREE;
12992 
12993   TREE_STATIC (r) = 0;
12994   TREE_PUBLIC (r) = TREE_PUBLIC (t);
12995   DECL_EXTERNAL (r) = 1;
12996   /* If this is an instantiation of a function with internal
12997      linkage, we already know what object file linkage will be
12998      assigned to the instantiation.  */
12999   DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
13000   DECL_DEFER_OUTPUT (r) = 0;
13001   DECL_CHAIN (r) = NULL_TREE;
13002   DECL_PENDING_INLINE_INFO (r) = 0;
13003   DECL_PENDING_INLINE_P (r) = 0;
13004   DECL_SAVED_TREE (r) = NULL_TREE;
13005   DECL_STRUCT_FUNCTION (r) = NULL;
13006   TREE_USED (r) = 0;
13007   /* We'll re-clone as appropriate in instantiate_template.  */
13008   DECL_CLONED_FUNCTION (r) = NULL_TREE;
13009 
13010   /* If we aren't complaining now, return on error before we register
13011      the specialization so that we'll complain eventually.  */
13012   if ((complain & tf_error) == 0
13013       && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
13014       && !grok_op_properties (r, /*complain=*/false))
13015     return error_mark_node;
13016 
13017   /* When instantiating a constrained member, substitute
13018      into the constraints to create a new constraint.  */
13019   if (tree ci = get_constraints (t))
13020     if (member)
13021       {
13022 	ci = tsubst_constraint_info (ci, argvec, complain, NULL_TREE);
13023 	set_constraints (r, ci);
13024       }
13025 
13026   /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
13027      this in the special friend case mentioned above where
13028      GEN_TMPL is NULL.  */
13029   if (gen_tmpl && !closure)
13030     {
13031       DECL_TEMPLATE_INFO (r)
13032 	= build_template_info (gen_tmpl, argvec);
13033       SET_DECL_IMPLICIT_INSTANTIATION (r);
13034 
13035       tree new_r
13036 	= register_specialization (r, gen_tmpl, argvec, false, hash);
13037       if (new_r != r)
13038 	/* We instantiated this while substituting into
13039 	   the type earlier (template/friend54.C).  */
13040 	return new_r;
13041 
13042       /* We're not supposed to instantiate default arguments
13043 	 until they are called, for a template.  But, for a
13044 	 declaration like:
13045 
13046 	 template <class T> void f ()
13047 	 { extern void g(int i = T()); }
13048 
13049 	 we should do the substitution when the template is
13050 	 instantiated.  We handle the member function case in
13051 	 instantiate_class_template since the default arguments
13052 	 might refer to other members of the class.  */
13053       if (!member
13054 	  && !PRIMARY_TEMPLATE_P (gen_tmpl)
13055 	  && !uses_template_parms (argvec))
13056 	tsubst_default_arguments (r, complain);
13057     }
13058   else
13059     DECL_TEMPLATE_INFO (r) = NULL_TREE;
13060 
13061   /* Copy the list of befriending classes.  */
13062   for (tree *friends = &DECL_BEFRIENDING_CLASSES (r);
13063        *friends;
13064        friends = &TREE_CHAIN (*friends))
13065     {
13066       *friends = copy_node (*friends);
13067       TREE_VALUE (*friends)
13068 	= tsubst (TREE_VALUE (*friends), args, complain, in_decl);
13069     }
13070 
13071   if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
13072     {
13073       maybe_retrofit_in_chrg (r);
13074       if (DECL_CONSTRUCTOR_P (r) && !grok_ctor_properties (ctx, r))
13075 	return error_mark_node;
13076       /* If this is an instantiation of a member template, clone it.
13077 	 If it isn't, that'll be handled by
13078 	 clone_constructors_and_destructors.  */
13079       if (PRIMARY_TEMPLATE_P (gen_tmpl))
13080 	clone_function_decl (r, /*update_methods=*/false);
13081     }
13082   else if ((complain & tf_error) != 0
13083 	   && IDENTIFIER_ANY_OP_P (DECL_NAME (r))
13084 	   && !grok_op_properties (r, /*complain=*/true))
13085     return error_mark_node;
13086 
13087   if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
13088     SET_DECL_FRIEND_CONTEXT (r,
13089 			     tsubst (DECL_FRIEND_CONTEXT (t),
13090 				     args, complain, in_decl));
13091 
13092   /* Possibly limit visibility based on template args.  */
13093   DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
13094   if (DECL_VISIBILITY_SPECIFIED (t))
13095     {
13096       DECL_VISIBILITY_SPECIFIED (r) = 0;
13097       DECL_ATTRIBUTES (r)
13098 	= remove_attribute ("visibility", DECL_ATTRIBUTES (r));
13099     }
13100   determine_visibility (r);
13101   if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
13102       && !processing_template_decl)
13103     defaulted_late_check (r);
13104 
13105   apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
13106 				  args, complain, in_decl);
13107   return r;
13108 }
13109 
13110 /* Subroutine of tsubst_decl for the case when T is a TEMPLATE_DECL.  */
13111 
13112 static tree
tsubst_template_decl(tree t,tree args,tsubst_flags_t complain,tree lambda_fntype)13113 tsubst_template_decl (tree t, tree args, tsubst_flags_t complain,
13114 		      tree lambda_fntype)
13115 {
13116   /* We can get here when processing a member function template,
13117      member class template, or template template parameter.  */
13118   tree decl = DECL_TEMPLATE_RESULT (t);
13119   tree in_decl = t;
13120   tree spec;
13121   tree tmpl_args;
13122   tree full_args;
13123   tree r;
13124   hashval_t hash = 0;
13125 
13126   if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
13127     {
13128       /* Template template parameter is treated here.  */
13129       tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13130       if (new_type == error_mark_node)
13131 	r = error_mark_node;
13132       /* If we get a real template back, return it.  This can happen in
13133 	 the context of most_specialized_partial_spec.  */
13134       else if (TREE_CODE (new_type) == TEMPLATE_DECL)
13135 	r = new_type;
13136       else
13137 	/* The new TEMPLATE_DECL was built in
13138 	   reduce_template_parm_level.  */
13139 	r = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (new_type);
13140       return r;
13141     }
13142 
13143   if (!lambda_fntype)
13144     {
13145       /* We might already have an instance of this template.
13146 	 The ARGS are for the surrounding class type, so the
13147 	 full args contain the tsubst'd args for the context,
13148 	 plus the innermost args from the template decl.  */
13149       tmpl_args = DECL_CLASS_TEMPLATE_P (t)
13150 	? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
13151 	: DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
13152       /* Because this is a template, the arguments will still be
13153 	 dependent, even after substitution.  If
13154 	 PROCESSING_TEMPLATE_DECL is not set, the dependency
13155 	 predicates will short-circuit.  */
13156       ++processing_template_decl;
13157       full_args = tsubst_template_args (tmpl_args, args,
13158 					complain, in_decl);
13159       --processing_template_decl;
13160       if (full_args == error_mark_node)
13161 	return error_mark_node;
13162 
13163       /* If this is a default template template argument,
13164 	 tsubst might not have changed anything.  */
13165       if (full_args == tmpl_args)
13166 	return t;
13167 
13168       hash = hash_tmpl_and_args (t, full_args);
13169       spec = retrieve_specialization (t, full_args, hash);
13170       if (spec != NULL_TREE)
13171 	return spec;
13172     }
13173 
13174   /* Make a new template decl.  It will be similar to the
13175      original, but will record the current template arguments.
13176      We also create a new function declaration, which is just
13177      like the old one, but points to this new template, rather
13178      than the old one.  */
13179   r = copy_decl (t);
13180   gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
13181   DECL_CHAIN (r) = NULL_TREE;
13182 
13183   // Build new template info linking to the original template decl.
13184   if (!lambda_fntype)
13185     {
13186       DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
13187       SET_DECL_IMPLICIT_INSTANTIATION (r);
13188     }
13189   else
13190     DECL_TEMPLATE_INFO (r) = NULL_TREE;
13191 
13192   /* The template parameters for this new template are all the
13193      template parameters for the old template, except the
13194      outermost level of parameters.  */
13195   DECL_TEMPLATE_PARMS (r)
13196     = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
13197 			     complain);
13198 
13199   if (TREE_CODE (decl) == TYPE_DECL
13200       && !TYPE_DECL_ALIAS_P (decl))
13201     {
13202       tree new_type;
13203       ++processing_template_decl;
13204       new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13205       --processing_template_decl;
13206       if (new_type == error_mark_node)
13207 	return error_mark_node;
13208 
13209       TREE_TYPE (r) = new_type;
13210       /* For a partial specialization, we need to keep pointing to
13211 	 the primary template.  */
13212       if (!DECL_TEMPLATE_SPECIALIZATION (t))
13213 	CLASSTYPE_TI_TEMPLATE (new_type) = r;
13214       DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
13215       DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
13216       DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
13217     }
13218   else
13219     {
13220       tree new_decl;
13221       ++processing_template_decl;
13222       if (TREE_CODE (decl) == FUNCTION_DECL)
13223 	new_decl = tsubst_function_decl (decl, args, complain, lambda_fntype);
13224       else
13225 	new_decl = tsubst (decl, args, complain, in_decl);
13226       --processing_template_decl;
13227       if (new_decl == error_mark_node)
13228 	return error_mark_node;
13229 
13230       DECL_TEMPLATE_RESULT (r) = new_decl;
13231       TREE_TYPE (r) = TREE_TYPE (new_decl);
13232       DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
13233       if (lambda_fntype)
13234 	{
13235 	  tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (r));
13236 	  DECL_TEMPLATE_INFO (new_decl) = build_template_info (r, args);
13237 	}
13238       else
13239 	{
13240 	  DECL_TI_TEMPLATE (new_decl) = r;
13241 	  DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
13242 	}
13243     }
13244 
13245   DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
13246   DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
13247 
13248   if (PRIMARY_TEMPLATE_P (t))
13249     DECL_PRIMARY_TEMPLATE (r) = r;
13250 
13251   if (TREE_CODE (decl) != TYPE_DECL && !VAR_P (decl)
13252       && !lambda_fntype)
13253     /* Record this non-type partial instantiation.  */
13254     register_specialization (r, t,
13255 			     DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
13256 			     false, hash);
13257 
13258   return r;
13259 }
13260 
13261 /* True if FN is the op() for a lambda in an uninstantiated template.  */
13262 
13263 bool
lambda_fn_in_template_p(tree fn)13264 lambda_fn_in_template_p (tree fn)
13265 {
13266   if (!fn || !LAMBDA_FUNCTION_P (fn))
13267     return false;
13268   tree closure = DECL_CONTEXT (fn);
13269   return CLASSTYPE_TEMPLATE_INFO (closure) != NULL_TREE;
13270 }
13271 
13272 /* We're instantiating a variable from template function TCTX.  Return the
13273    corresponding current enclosing scope.  This gets complicated because lambda
13274    functions in templates are regenerated rather than instantiated, but generic
13275    lambda functions are subsequently instantiated.  */
13276 
13277 static tree
enclosing_instantiation_of(tree otctx)13278 enclosing_instantiation_of (tree otctx)
13279 {
13280   tree tctx = otctx;
13281   tree fn = current_function_decl;
13282   int lambda_count = 0;
13283 
13284   for (; tctx && lambda_fn_in_template_p (tctx);
13285        tctx = decl_function_context (tctx))
13286     ++lambda_count;
13287   for (; fn; fn = decl_function_context (fn))
13288     {
13289       tree ofn = fn;
13290       int flambda_count = 0;
13291       for (; flambda_count < lambda_count && fn && LAMBDA_FUNCTION_P (fn);
13292 	   fn = decl_function_context (fn))
13293 	++flambda_count;
13294       if ((fn && DECL_TEMPLATE_INFO (fn))
13295 	  ? most_general_template (fn) != most_general_template (tctx)
13296 	  : fn != tctx)
13297 	continue;
13298       gcc_assert (DECL_NAME (ofn) == DECL_NAME (otctx)
13299 		  || DECL_CONV_FN_P (ofn));
13300       return ofn;
13301     }
13302   gcc_unreachable ();
13303 }
13304 
13305 /* Substitute the ARGS into the T, which is a _DECL.  Return the
13306    result of the substitution.  Issue error and warning messages under
13307    control of COMPLAIN.  */
13308 
13309 static tree
tsubst_decl(tree t,tree args,tsubst_flags_t complain)13310 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
13311 {
13312 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
13313   location_t saved_loc;
13314   tree r = NULL_TREE;
13315   tree in_decl = t;
13316   hashval_t hash = 0;
13317 
13318   /* Set the filename and linenumber to improve error-reporting.  */
13319   saved_loc = input_location;
13320   input_location = DECL_SOURCE_LOCATION (t);
13321 
13322   switch (TREE_CODE (t))
13323     {
13324     case TEMPLATE_DECL:
13325       r = tsubst_template_decl (t, args, complain, /*lambda*/NULL_TREE);
13326       break;
13327 
13328     case FUNCTION_DECL:
13329       r = tsubst_function_decl (t, args, complain, /*lambda*/NULL_TREE);
13330       break;
13331 
13332     case PARM_DECL:
13333       {
13334 	tree type = NULL_TREE;
13335         int i, len = 1;
13336         tree expanded_types = NULL_TREE;
13337         tree prev_r = NULL_TREE;
13338         tree first_r = NULL_TREE;
13339 
13340         if (DECL_PACK_P (t))
13341           {
13342             /* If there is a local specialization that isn't a
13343                parameter pack, it means that we're doing a "simple"
13344                substitution from inside tsubst_pack_expansion. Just
13345                return the local specialization (which will be a single
13346                parm).  */
13347             tree spec = retrieve_local_specialization (t);
13348             if (spec
13349                 && TREE_CODE (spec) == PARM_DECL
13350                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
13351               RETURN (spec);
13352 
13353             /* Expand the TYPE_PACK_EXPANSION that provides the types for
13354                the parameters in this function parameter pack.  */
13355             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
13356 						    complain, in_decl);
13357             if (TREE_CODE (expanded_types) == TREE_VEC)
13358               {
13359                 len = TREE_VEC_LENGTH (expanded_types);
13360 
13361                 /* Zero-length parameter packs are boring. Just substitute
13362                    into the chain.  */
13363                 if (len == 0)
13364                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
13365 				  TREE_CHAIN (t)));
13366               }
13367             else
13368               {
13369                 /* All we did was update the type. Make a note of that.  */
13370                 type = expanded_types;
13371                 expanded_types = NULL_TREE;
13372               }
13373           }
13374 
13375         /* Loop through all of the parameters we'll build. When T is
13376            a function parameter pack, LEN is the number of expanded
13377            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
13378         r = NULL_TREE;
13379         for (i = 0; i < len; ++i)
13380           {
13381             prev_r = r;
13382             r = copy_node (t);
13383             if (DECL_TEMPLATE_PARM_P (t))
13384               SET_DECL_TEMPLATE_PARM_P (r);
13385 
13386             if (expanded_types)
13387               /* We're on the Ith parameter of the function parameter
13388                  pack.  */
13389               {
13390                 /* Get the Ith type.  */
13391                 type = TREE_VEC_ELT (expanded_types, i);
13392 
13393 		/* Rename the parameter to include the index.  */
13394 		DECL_NAME (r)
13395 		  = make_ith_pack_parameter_name (DECL_NAME (r), i);
13396               }
13397             else if (!type)
13398               /* We're dealing with a normal parameter.  */
13399               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13400 
13401             type = type_decays_to (type);
13402             TREE_TYPE (r) = type;
13403             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
13404 
13405             if (DECL_INITIAL (r))
13406               {
13407                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
13408                   DECL_INITIAL (r) = TREE_TYPE (r);
13409                 else
13410                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
13411                                              complain, in_decl);
13412               }
13413 
13414             DECL_CONTEXT (r) = NULL_TREE;
13415 
13416             if (!DECL_TEMPLATE_PARM_P (r))
13417               DECL_ARG_TYPE (r) = type_passed_as (type);
13418 
13419 	    apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
13420 					    args, complain, in_decl);
13421 
13422             /* Keep track of the first new parameter we
13423                generate. That's what will be returned to the
13424                caller.  */
13425             if (!first_r)
13426               first_r = r;
13427 
13428             /* Build a proper chain of parameters when substituting
13429                into a function parameter pack.  */
13430             if (prev_r)
13431               DECL_CHAIN (prev_r) = r;
13432           }
13433 
13434 	/* If cp_unevaluated_operand is set, we're just looking for a
13435 	   single dummy parameter, so don't keep going.  */
13436 	if (DECL_CHAIN (t) && !cp_unevaluated_operand)
13437 	  DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
13438 				   complain, DECL_CHAIN (t));
13439 
13440         /* FIRST_R contains the start of the chain we've built.  */
13441         r = first_r;
13442       }
13443       break;
13444 
13445     case FIELD_DECL:
13446       {
13447 	tree type = NULL_TREE;
13448 	tree vec = NULL_TREE;
13449 	tree expanded_types = NULL_TREE;
13450 	int len = 1;
13451 
13452 	if (PACK_EXPANSION_P (TREE_TYPE (t)))
13453 	  {
13454 	    /* This field is a lambda capture pack.  Return a TREE_VEC of
13455 	       the expanded fields to instantiate_class_template_1.  */
13456             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
13457 						    complain, in_decl);
13458             if (TREE_CODE (expanded_types) == TREE_VEC)
13459               {
13460                 len = TREE_VEC_LENGTH (expanded_types);
13461 		vec = make_tree_vec (len);
13462               }
13463             else
13464               {
13465                 /* All we did was update the type. Make a note of that.  */
13466                 type = expanded_types;
13467                 expanded_types = NULL_TREE;
13468               }
13469 	  }
13470 
13471 	for (int i = 0; i < len; ++i)
13472 	  {
13473 	    r = copy_decl (t);
13474 	    if (expanded_types)
13475 	      {
13476 		type = TREE_VEC_ELT (expanded_types, i);
13477 		DECL_NAME (r)
13478 		  = make_ith_pack_parameter_name (DECL_NAME (r), i);
13479 	      }
13480             else if (!type)
13481               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13482 
13483 	    if (type == error_mark_node)
13484 	      RETURN (error_mark_node);
13485 	    TREE_TYPE (r) = type;
13486 	    cp_apply_type_quals_to_decl (cp_type_quals (type), r);
13487 
13488 	    if (DECL_C_BIT_FIELD (r))
13489 	      /* For bit-fields, DECL_BIT_FIELD_REPRESENTATIVE gives the
13490 		 number of bits.  */
13491 	      DECL_BIT_FIELD_REPRESENTATIVE (r)
13492 		= tsubst_expr (DECL_BIT_FIELD_REPRESENTATIVE (t), args,
13493 			       complain, in_decl,
13494 			       /*integral_constant_expression_p=*/true);
13495 	    if (DECL_INITIAL (t))
13496 	      {
13497 		/* Set up DECL_TEMPLATE_INFO so that we can get at the
13498 		   NSDMI in perform_member_init.  Still set DECL_INITIAL
13499 		   so that we know there is one.  */
13500 		DECL_INITIAL (r) = void_node;
13501 		gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
13502 		retrofit_lang_decl (r);
13503 		DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
13504 	      }
13505 	    /* We don't have to set DECL_CONTEXT here; it is set by
13506 	       finish_member_declaration.  */
13507 	    DECL_CHAIN (r) = NULL_TREE;
13508 
13509 	    apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
13510 					    args, complain, in_decl);
13511 
13512 	    if (vec)
13513 	      TREE_VEC_ELT (vec, i) = r;
13514 	  }
13515 
13516 	if (vec)
13517 	  r = vec;
13518       }
13519       break;
13520 
13521     case USING_DECL:
13522       /* We reach here only for member using decls.  We also need to check
13523 	 uses_template_parms because DECL_DEPENDENT_P is not set for a
13524 	 using-declaration that designates a member of the current
13525 	 instantiation (c++/53549).  */
13526       if (DECL_DEPENDENT_P (t)
13527 	  || uses_template_parms (USING_DECL_SCOPE (t)))
13528 	{
13529 	  tree scope = USING_DECL_SCOPE (t);
13530 	  tree name = tsubst_copy (DECL_NAME (t), args, complain, in_decl);
13531 	  if (PACK_EXPANSION_P (scope))
13532 	    {
13533 	      tree vec = tsubst_pack_expansion (scope, args, complain, in_decl);
13534 	      int len = TREE_VEC_LENGTH (vec);
13535 	      r = make_tree_vec (len);
13536 	      for (int i = 0; i < len; ++i)
13537 		{
13538 		  tree escope = TREE_VEC_ELT (vec, i);
13539 		  tree elt = do_class_using_decl (escope, name);
13540 		  if (!elt)
13541 		    {
13542 		      r = error_mark_node;
13543 		      break;
13544 		    }
13545 		  else
13546 		    {
13547 		      TREE_PROTECTED (elt) = TREE_PROTECTED (t);
13548 		      TREE_PRIVATE (elt) = TREE_PRIVATE (t);
13549 		    }
13550 		  TREE_VEC_ELT (r, i) = elt;
13551 		}
13552 	    }
13553 	  else
13554 	    {
13555 	      tree inst_scope = tsubst_copy (USING_DECL_SCOPE (t), args,
13556 					     complain, in_decl);
13557 	      r = do_class_using_decl (inst_scope, name);
13558 	      if (!r)
13559 		r = error_mark_node;
13560 	      else
13561 		{
13562 		  TREE_PROTECTED (r) = TREE_PROTECTED (t);
13563 		  TREE_PRIVATE (r) = TREE_PRIVATE (t);
13564 		}
13565 	    }
13566 	}
13567       else
13568 	{
13569 	  r = copy_node (t);
13570 	  DECL_CHAIN (r) = NULL_TREE;
13571 	}
13572       break;
13573 
13574     case TYPE_DECL:
13575     case VAR_DECL:
13576       {
13577 	tree argvec = NULL_TREE;
13578 	tree gen_tmpl = NULL_TREE;
13579 	tree spec;
13580 	tree tmpl = NULL_TREE;
13581 	tree ctx;
13582 	tree type = NULL_TREE;
13583 	bool local_p;
13584 
13585 	if (TREE_TYPE (t) == error_mark_node)
13586 	  RETURN (error_mark_node);
13587 
13588 	if (TREE_CODE (t) == TYPE_DECL
13589 	    && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
13590 	  {
13591 	    /* If this is the canonical decl, we don't have to
13592 	       mess with instantiations, and often we can't (for
13593 	       typename, template type parms and such).  Note that
13594 	       TYPE_NAME is not correct for the above test if
13595 	       we've copied the type for a typedef.  */
13596 	    type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13597 	    if (type == error_mark_node)
13598 	      RETURN (error_mark_node);
13599 	    r = TYPE_NAME (type);
13600 	    break;
13601 	  }
13602 
13603 	/* Check to see if we already have the specialization we
13604 	   need.  */
13605 	spec = NULL_TREE;
13606 	if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
13607 	  {
13608 	    /* T is a static data member or namespace-scope entity.
13609 	       We have to substitute into namespace-scope variables
13610 	       (not just variable templates) because of cases like:
13611 
13612 	         template <class T> void f() { extern T t; }
13613 
13614 	       where the entity referenced is not known until
13615 	       instantiation time.  */
13616 	    local_p = false;
13617 	    ctx = DECL_CONTEXT (t);
13618 	    if (DECL_CLASS_SCOPE_P (t))
13619 	      {
13620 		ctx = tsubst_aggr_type (ctx, args,
13621 					complain,
13622 					in_decl, /*entering_scope=*/1);
13623 		/* If CTX is unchanged, then T is in fact the
13624 		   specialization we want.  That situation occurs when
13625 		   referencing a static data member within in its own
13626 		   class.  We can use pointer equality, rather than
13627 		   same_type_p, because DECL_CONTEXT is always
13628 		   canonical...  */
13629 		if (ctx == DECL_CONTEXT (t)
13630 		    /* ... unless T is a member template; in which
13631 		       case our caller can be willing to create a
13632 		       specialization of that template represented
13633 		       by T.  */
13634 		    && !(DECL_TI_TEMPLATE (t)
13635 			 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (t))))
13636 		  spec = t;
13637 	      }
13638 
13639 	    if (!spec)
13640 	      {
13641 		tmpl = DECL_TI_TEMPLATE (t);
13642 		gen_tmpl = most_general_template (tmpl);
13643 		argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
13644 		if (argvec != error_mark_node)
13645 		  argvec = (coerce_innermost_template_parms
13646 			    (DECL_TEMPLATE_PARMS (gen_tmpl),
13647 			     argvec, t, complain,
13648 			     /*all*/true, /*defarg*/true));
13649 		if (argvec == error_mark_node)
13650 		  RETURN (error_mark_node);
13651 		hash = hash_tmpl_and_args (gen_tmpl, argvec);
13652 		spec = retrieve_specialization (gen_tmpl, argvec, hash);
13653 	      }
13654 	  }
13655 	else
13656 	  {
13657 	    /* A local variable.  */
13658 	    local_p = true;
13659 	    /* Subsequent calls to pushdecl will fill this in.  */
13660 	    ctx = NULL_TREE;
13661 	    /* Unless this is a reference to a static variable from an
13662 	       enclosing function, in which case we need to fill it in now.  */
13663 	    if (TREE_STATIC (t))
13664 	      {
13665 		tree fn = enclosing_instantiation_of (DECL_CONTEXT (t));
13666 		if (fn != current_function_decl)
13667 		  ctx = fn;
13668 	      }
13669 	    spec = retrieve_local_specialization (t);
13670 	  }
13671 	/* If we already have the specialization we need, there is
13672 	   nothing more to do.  */
13673 	if (spec)
13674 	  {
13675 	    r = spec;
13676 	    break;
13677 	  }
13678 
13679 	/* Create a new node for the specialization we need.  */
13680 	r = copy_decl (t);
13681 	if (type == NULL_TREE)
13682 	  {
13683 	    if (is_typedef_decl (t))
13684 	      type = DECL_ORIGINAL_TYPE (t);
13685 	    else
13686 	      type = TREE_TYPE (t);
13687 	    if (VAR_P (t)
13688 		&& VAR_HAD_UNKNOWN_BOUND (t)
13689 		&& type != error_mark_node)
13690 	      type = strip_array_domain (type);
13691 	    tree sub_args = args;
13692 	    if (tree auto_node = type_uses_auto (type))
13693 	      {
13694 		/* Mask off any template args past the variable's context so we
13695 		   don't replace the auto with an unrelated argument.  */
13696 		int nouter = TEMPLATE_TYPE_LEVEL (auto_node) - 1;
13697 		int extra = TMPL_ARGS_DEPTH (args) - nouter;
13698 		if (extra > 0)
13699 		  /* This should never happen with the new lambda instantiation
13700 		     model, but keep the handling just in case.  */
13701 		  gcc_assert (!CHECKING_P),
13702 		  sub_args = strip_innermost_template_args (args, extra);
13703 	      }
13704 	    type = tsubst (type, sub_args, complain, in_decl);
13705 	  }
13706 	if (VAR_P (r))
13707 	  {
13708 	    /* Even if the original location is out of scope, the
13709 	       newly substituted one is not.  */
13710 	    DECL_DEAD_FOR_LOCAL (r) = 0;
13711 	    DECL_INITIALIZED_P (r) = 0;
13712 	    DECL_TEMPLATE_INSTANTIATED (r) = 0;
13713 	    if (type == error_mark_node)
13714 	      RETURN (error_mark_node);
13715 	    if (TREE_CODE (type) == FUNCTION_TYPE)
13716 	      {
13717 		/* It may seem that this case cannot occur, since:
13718 
13719 		   typedef void f();
13720 		   void g() { f x; }
13721 
13722 		   declares a function, not a variable.  However:
13723 
13724 		   typedef void f();
13725 		   template <typename T> void g() { T t; }
13726 		   template void g<f>();
13727 
13728 		   is an attempt to declare a variable with function
13729 		   type.  */
13730 		error ("variable %qD has function type",
13731 		       /* R is not yet sufficiently initialized, so we
13732 			  just use its name.  */
13733 		       DECL_NAME (r));
13734 		RETURN (error_mark_node);
13735 	      }
13736 	    type = complete_type (type);
13737 	    /* Wait until cp_finish_decl to set this again, to handle
13738 	       circular dependency (template/instantiate6.C). */
13739 	    DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
13740 	    type = check_var_type (DECL_NAME (r), type);
13741 
13742 	    if (DECL_HAS_VALUE_EXPR_P (t))
13743 	      {
13744 		tree ve = DECL_VALUE_EXPR (t);
13745 		ve = tsubst_expr (ve, args, complain, in_decl,
13746 				  /*constant_expression_p=*/false);
13747 		if (REFERENCE_REF_P (ve))
13748 		  {
13749 		    gcc_assert (TREE_CODE (type) == REFERENCE_TYPE);
13750 		    ve = TREE_OPERAND (ve, 0);
13751 		  }
13752 		SET_DECL_VALUE_EXPR (r, ve);
13753 	      }
13754 	    if (CP_DECL_THREAD_LOCAL_P (r)
13755 		&& !processing_template_decl)
13756 	      set_decl_tls_model (r, decl_default_tls_model (r));
13757 	  }
13758 	else if (DECL_SELF_REFERENCE_P (t))
13759 	  SET_DECL_SELF_REFERENCE_P (r);
13760 	TREE_TYPE (r) = type;
13761 	cp_apply_type_quals_to_decl (cp_type_quals (type), r);
13762 	DECL_CONTEXT (r) = ctx;
13763 	/* Clear out the mangled name and RTL for the instantiation.  */
13764 	SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
13765 	if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
13766 	  SET_DECL_RTL (r, NULL);
13767 	/* The initializer must not be expanded until it is required;
13768 	   see [temp.inst].  */
13769 	DECL_INITIAL (r) = NULL_TREE;
13770 	DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
13771 	if (VAR_P (r))
13772 	  {
13773 	    if (DECL_LANG_SPECIFIC (r))
13774 	      SET_DECL_DEPENDENT_INIT_P (r, false);
13775 
13776 	    SET_DECL_MODE (r, VOIDmode);
13777 
13778 	    /* Possibly limit visibility based on template args.  */
13779 	    DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
13780 	    if (DECL_VISIBILITY_SPECIFIED (t))
13781 	      {
13782 		DECL_VISIBILITY_SPECIFIED (r) = 0;
13783 		DECL_ATTRIBUTES (r)
13784 		  = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
13785 	      }
13786 	    determine_visibility (r);
13787 	  }
13788 
13789 	if (!local_p)
13790 	  {
13791 	    /* A static data member declaration is always marked
13792 	       external when it is declared in-class, even if an
13793 	       initializer is present.  We mimic the non-template
13794 	       processing here.  */
13795 	    DECL_EXTERNAL (r) = 1;
13796 	    if (DECL_NAMESPACE_SCOPE_P (t))
13797 	      DECL_NOT_REALLY_EXTERN (r) = 1;
13798 
13799 	    DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
13800 	    SET_DECL_IMPLICIT_INSTANTIATION (r);
13801 	    register_specialization (r, gen_tmpl, argvec, false, hash);
13802 	  }
13803 	else
13804 	  {
13805 	    if (DECL_LANG_SPECIFIC (r))
13806 	      DECL_TEMPLATE_INFO (r) = NULL_TREE;
13807 	    if (!cp_unevaluated_operand)
13808 	      register_local_specialization (r, t);
13809 	  }
13810 
13811 	DECL_CHAIN (r) = NULL_TREE;
13812 
13813 	apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
13814 					/*flags=*/0,
13815 					args, complain, in_decl);
13816 
13817 	/* Preserve a typedef that names a type.  */
13818 	if (is_typedef_decl (r) && type != error_mark_node)
13819 	  {
13820 	    DECL_ORIGINAL_TYPE (r) = NULL_TREE;
13821 	    set_underlying_type (r);
13822 	    if (TYPE_DECL_ALIAS_P (r))
13823 	      /* An alias template specialization can be dependent
13824 		 even if its underlying type is not.  */
13825 	      TYPE_DEPENDENT_P_VALID (TREE_TYPE (r)) = false;
13826 	  }
13827 
13828 	layout_decl (r, 0);
13829       }
13830       break;
13831 
13832     default:
13833       gcc_unreachable ();
13834     }
13835 #undef RETURN
13836 
13837  out:
13838   /* Restore the file and line information.  */
13839   input_location = saved_loc;
13840 
13841   return r;
13842 }
13843 
13844 /* Substitute into the ARG_TYPES of a function type.
13845    If END is a TREE_CHAIN, leave it and any following types
13846    un-substituted.  */
13847 
13848 static tree
tsubst_arg_types(tree arg_types,tree args,tree end,tsubst_flags_t complain,tree in_decl)13849 tsubst_arg_types (tree arg_types,
13850 		  tree args,
13851 		  tree end,
13852 		  tsubst_flags_t complain,
13853 		  tree in_decl)
13854 {
13855   tree remaining_arg_types;
13856   tree type = NULL_TREE;
13857   int i = 1;
13858   tree expanded_args = NULL_TREE;
13859   tree default_arg;
13860 
13861   if (!arg_types || arg_types == void_list_node || arg_types == end)
13862     return arg_types;
13863 
13864   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
13865 					  args, end, complain, in_decl);
13866   if (remaining_arg_types == error_mark_node)
13867     return error_mark_node;
13868 
13869   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
13870     {
13871       /* For a pack expansion, perform substitution on the
13872          entire expression. Later on, we'll handle the arguments
13873          one-by-one.  */
13874       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
13875                                             args, complain, in_decl);
13876 
13877       if (TREE_CODE (expanded_args) == TREE_VEC)
13878         /* So that we'll spin through the parameters, one by one.  */
13879         i = TREE_VEC_LENGTH (expanded_args);
13880       else
13881         {
13882           /* We only partially substituted into the parameter
13883              pack. Our type is TYPE_PACK_EXPANSION.  */
13884           type = expanded_args;
13885           expanded_args = NULL_TREE;
13886         }
13887     }
13888 
13889   while (i > 0) {
13890     --i;
13891 
13892     if (expanded_args)
13893       type = TREE_VEC_ELT (expanded_args, i);
13894     else if (!type)
13895       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
13896 
13897     if (type == error_mark_node)
13898       return error_mark_node;
13899     if (VOID_TYPE_P (type))
13900       {
13901         if (complain & tf_error)
13902           {
13903             error ("invalid parameter type %qT", type);
13904             if (in_decl)
13905               error ("in declaration %q+D", in_decl);
13906           }
13907         return error_mark_node;
13908     }
13909     /* DR 657. */
13910     if (abstract_virtuals_error_sfinae (ACU_PARM, type, complain))
13911       return error_mark_node;
13912 
13913     /* Do array-to-pointer, function-to-pointer conversion, and ignore
13914        top-level qualifiers as required.  */
13915     type = cv_unqualified (type_decays_to (type));
13916 
13917     /* We do not substitute into default arguments here.  The standard
13918        mandates that they be instantiated only when needed, which is
13919        done in build_over_call.  */
13920     default_arg = TREE_PURPOSE (arg_types);
13921 
13922     /* Except that we do substitute default arguments under tsubst_lambda_expr,
13923        since the new op() won't have any associated template arguments for us
13924        to refer to later.  */
13925     if (lambda_fn_in_template_p (in_decl))
13926       default_arg = tsubst_copy_and_build (default_arg, args, complain, in_decl,
13927 					   false/*fn*/, false/*constexpr*/);
13928 
13929     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
13930       {
13931         /* We've instantiated a template before its default arguments
13932            have been parsed.  This can happen for a nested template
13933            class, and is not an error unless we require the default
13934            argument in a call of this function.  */
13935         remaining_arg_types =
13936           tree_cons (default_arg, type, remaining_arg_types);
13937         vec_safe_push (DEFARG_INSTANTIATIONS(default_arg), remaining_arg_types);
13938       }
13939     else
13940       remaining_arg_types =
13941         hash_tree_cons (default_arg, type, remaining_arg_types);
13942   }
13943 
13944   return remaining_arg_types;
13945 }
13946 
13947 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
13948    *not* handle the exception-specification for FNTYPE, because the
13949    initial substitution of explicitly provided template parameters
13950    during argument deduction forbids substitution into the
13951    exception-specification:
13952 
13953      [temp.deduct]
13954 
13955      All references in the function type of the function template to  the
13956      corresponding template parameters are replaced by the specified tem-
13957      plate argument values.  If a substitution in a template parameter or
13958      in  the function type of the function template results in an invalid
13959      type, type deduction fails.  [Note: The equivalent  substitution  in
13960      exception specifications is done only when the function is instanti-
13961      ated, at which point a program is  ill-formed  if  the  substitution
13962      results in an invalid type.]  */
13963 
13964 static tree
tsubst_function_type(tree t,tree args,tsubst_flags_t complain,tree in_decl)13965 tsubst_function_type (tree t,
13966 		      tree args,
13967 		      tsubst_flags_t complain,
13968 		      tree in_decl)
13969 {
13970   tree return_type;
13971   tree arg_types = NULL_TREE;
13972   tree fntype;
13973 
13974   /* The TYPE_CONTEXT is not used for function/method types.  */
13975   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
13976 
13977   /* DR 1227: Mixing immediate and non-immediate contexts in deduction
13978      failure.  */
13979   bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
13980 
13981   if (late_return_type_p)
13982     {
13983       /* Substitute the argument types.  */
13984       arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
13985 				    complain, in_decl);
13986       if (arg_types == error_mark_node)
13987 	return error_mark_node;
13988 
13989       tree save_ccp = current_class_ptr;
13990       tree save_ccr = current_class_ref;
13991       tree this_type = (TREE_CODE (t) == METHOD_TYPE
13992 			? TREE_TYPE (TREE_VALUE (arg_types)) : NULL_TREE);
13993       bool do_inject = this_type && CLASS_TYPE_P (this_type);
13994       if (do_inject)
13995 	{
13996 	  /* DR 1207: 'this' is in scope in the trailing return type.  */
13997 	  inject_this_parameter (this_type, cp_type_quals (this_type));
13998 	}
13999 
14000       /* Substitute the return type.  */
14001       return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14002 
14003       if (do_inject)
14004 	{
14005 	  current_class_ptr = save_ccp;
14006 	  current_class_ref = save_ccr;
14007 	}
14008     }
14009   else
14010     /* Substitute the return type.  */
14011     return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14012 
14013   if (return_type == error_mark_node)
14014     return error_mark_node;
14015   /* DR 486 clarifies that creation of a function type with an
14016      invalid return type is a deduction failure.  */
14017   if (TREE_CODE (return_type) == ARRAY_TYPE
14018       || TREE_CODE (return_type) == FUNCTION_TYPE)
14019     {
14020       if (complain & tf_error)
14021 	{
14022 	  if (TREE_CODE (return_type) == ARRAY_TYPE)
14023 	    error ("function returning an array");
14024 	  else
14025 	    error ("function returning a function");
14026 	}
14027       return error_mark_node;
14028     }
14029   /* And DR 657. */
14030   if (abstract_virtuals_error_sfinae (ACU_RETURN, return_type, complain))
14031     return error_mark_node;
14032 
14033   if (!late_return_type_p)
14034     {
14035       /* Substitute the argument types.  */
14036       arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
14037 				    complain, in_decl);
14038       if (arg_types == error_mark_node)
14039 	return error_mark_node;
14040     }
14041 
14042   /* Construct a new type node and return it.  */
14043   if (TREE_CODE (t) == FUNCTION_TYPE)
14044     {
14045       fntype = build_function_type (return_type, arg_types);
14046       fntype = apply_memfn_quals (fntype,
14047 				  type_memfn_quals (t),
14048 				  type_memfn_rqual (t));
14049     }
14050   else
14051     {
14052       tree r = TREE_TYPE (TREE_VALUE (arg_types));
14053       /* Don't pick up extra function qualifiers from the basetype.  */
14054       r = cp_build_qualified_type_real (r, type_memfn_quals (t), complain);
14055       if (! MAYBE_CLASS_TYPE_P (r))
14056 	{
14057 	  /* [temp.deduct]
14058 
14059 	     Type deduction may fail for any of the following
14060 	     reasons:
14061 
14062 	     -- Attempting to create "pointer to member of T" when T
14063 	     is not a class type.  */
14064 	  if (complain & tf_error)
14065 	    error ("creating pointer to member function of non-class type %qT",
14066 		      r);
14067 	  return error_mark_node;
14068 	}
14069 
14070       fntype = build_method_type_directly (r, return_type,
14071 					   TREE_CHAIN (arg_types));
14072       fntype = build_ref_qualified_type (fntype, type_memfn_rqual (t));
14073     }
14074   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
14075 
14076   if (late_return_type_p)
14077     TYPE_HAS_LATE_RETURN_TYPE (fntype) = 1;
14078 
14079   return fntype;
14080 }
14081 
14082 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
14083    ARGS into that specification, and return the substituted
14084    specification.  If there is no specification, return NULL_TREE.  */
14085 
14086 static tree
tsubst_exception_specification(tree fntype,tree args,tsubst_flags_t complain,tree in_decl,bool defer_ok)14087 tsubst_exception_specification (tree fntype,
14088 				tree args,
14089 				tsubst_flags_t complain,
14090 				tree in_decl,
14091 				bool defer_ok)
14092 {
14093   tree specs;
14094   tree new_specs;
14095 
14096   specs = TYPE_RAISES_EXCEPTIONS (fntype);
14097   new_specs = NULL_TREE;
14098   if (specs && TREE_PURPOSE (specs))
14099     {
14100       /* A noexcept-specifier.  */
14101       tree expr = TREE_PURPOSE (specs);
14102       if (TREE_CODE (expr) == INTEGER_CST)
14103 	new_specs = expr;
14104       else if (defer_ok)
14105 	{
14106 	  /* Defer instantiation of noexcept-specifiers to avoid
14107 	     excessive instantiations (c++/49107).  */
14108 	  new_specs = make_node (DEFERRED_NOEXCEPT);
14109 	  if (DEFERRED_NOEXCEPT_SPEC_P (specs))
14110 	    {
14111 	      /* We already partially instantiated this member template,
14112 		 so combine the new args with the old.  */
14113 	      DEFERRED_NOEXCEPT_PATTERN (new_specs)
14114 		= DEFERRED_NOEXCEPT_PATTERN (expr);
14115 	      DEFERRED_NOEXCEPT_ARGS (new_specs)
14116 		= add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
14117 	    }
14118 	  else
14119 	    {
14120 	      DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
14121 	      DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
14122 	    }
14123 	}
14124       else
14125 	new_specs = tsubst_copy_and_build
14126 	  (expr, args, complain, in_decl, /*function_p=*/false,
14127 	   /*integral_constant_expression_p=*/true);
14128       new_specs = build_noexcept_spec (new_specs, complain);
14129     }
14130   else if (specs)
14131     {
14132       if (! TREE_VALUE (specs))
14133 	new_specs = specs;
14134       else
14135 	while (specs)
14136 	  {
14137 	    tree spec;
14138             int i, len = 1;
14139             tree expanded_specs = NULL_TREE;
14140 
14141             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
14142               {
14143                 /* Expand the pack expansion type.  */
14144                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
14145                                                        args, complain,
14146                                                        in_decl);
14147 
14148 		if (expanded_specs == error_mark_node)
14149 		  return error_mark_node;
14150 		else if (TREE_CODE (expanded_specs) == TREE_VEC)
14151 		  len = TREE_VEC_LENGTH (expanded_specs);
14152 		else
14153 		  {
14154 		    /* We're substituting into a member template, so
14155 		       we got a TYPE_PACK_EXPANSION back.  Add that
14156 		       expansion and move on.  */
14157 		    gcc_assert (TREE_CODE (expanded_specs)
14158 				== TYPE_PACK_EXPANSION);
14159 		    new_specs = add_exception_specifier (new_specs,
14160 							 expanded_specs,
14161 							 complain);
14162 		    specs = TREE_CHAIN (specs);
14163 		    continue;
14164 		  }
14165               }
14166 
14167             for (i = 0; i < len; ++i)
14168               {
14169                 if (expanded_specs)
14170                   spec = TREE_VEC_ELT (expanded_specs, i);
14171                 else
14172                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
14173                 if (spec == error_mark_node)
14174                   return spec;
14175                 new_specs = add_exception_specifier (new_specs, spec,
14176                                                      complain);
14177               }
14178 
14179             specs = TREE_CHAIN (specs);
14180 	  }
14181     }
14182   return new_specs;
14183 }
14184 
14185 /* Take the tree structure T and replace template parameters used
14186    therein with the argument vector ARGS.  IN_DECL is an associated
14187    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
14188    Issue error and warning messages under control of COMPLAIN.  Note
14189    that we must be relatively non-tolerant of extensions here, in
14190    order to preserve conformance; if we allow substitutions that
14191    should not be allowed, we may allow argument deductions that should
14192    not succeed, and therefore report ambiguous overload situations
14193    where there are none.  In theory, we could allow the substitution,
14194    but indicate that it should have failed, and allow our caller to
14195    make sure that the right thing happens, but we don't try to do this
14196    yet.
14197 
14198    This function is used for dealing with types, decls and the like;
14199    for expressions, use tsubst_expr or tsubst_copy.  */
14200 
14201 tree
tsubst(tree t,tree args,tsubst_flags_t complain,tree in_decl)14202 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
14203 {
14204   enum tree_code code;
14205   tree type, r = NULL_TREE;
14206 
14207   if (t == NULL_TREE || t == error_mark_node
14208       || t == integer_type_node
14209       || t == void_type_node
14210       || t == char_type_node
14211       || t == unknown_type_node
14212       || TREE_CODE (t) == NAMESPACE_DECL
14213       || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
14214     return t;
14215 
14216   if (DECL_P (t))
14217     return tsubst_decl (t, args, complain);
14218 
14219   if (args == NULL_TREE)
14220     return t;
14221 
14222   code = TREE_CODE (t);
14223 
14224   if (code == IDENTIFIER_NODE)
14225     type = IDENTIFIER_TYPE_VALUE (t);
14226   else
14227     type = TREE_TYPE (t);
14228 
14229   gcc_assert (type != unknown_type_node);
14230 
14231   /* Reuse typedefs.  We need to do this to handle dependent attributes,
14232      such as attribute aligned.  */
14233   if (TYPE_P (t)
14234       && typedef_variant_p (t))
14235     {
14236       tree decl = TYPE_NAME (t);
14237 
14238       if (alias_template_specialization_p (t))
14239 	{
14240 	  /* DECL represents an alias template and we want to
14241 	     instantiate it.  */
14242 	  tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
14243 	  tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
14244 	  r = instantiate_alias_template (tmpl, gen_args, complain);
14245 	}
14246       else if (DECL_CLASS_SCOPE_P (decl)
14247 	       && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
14248 	       && uses_template_parms (DECL_CONTEXT (decl)))
14249 	{
14250 	  tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
14251 	  tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
14252 	  r = retrieve_specialization (tmpl, gen_args, 0);
14253 	}
14254       else if (DECL_FUNCTION_SCOPE_P (decl)
14255 	       && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
14256 	       && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
14257 	r = retrieve_local_specialization (decl);
14258       else
14259 	/* The typedef is from a non-template context.  */
14260 	return t;
14261 
14262       if (r)
14263 	{
14264 	  r = TREE_TYPE (r);
14265 	  r = cp_build_qualified_type_real
14266 	    (r, cp_type_quals (t) | cp_type_quals (r),
14267 	     complain | tf_ignore_bad_quals);
14268 	  return r;
14269 	}
14270       else
14271 	{
14272 	  /* We don't have an instantiation yet, so drop the typedef.  */
14273 	  int quals = cp_type_quals (t);
14274 	  t = DECL_ORIGINAL_TYPE (decl);
14275 	  t = cp_build_qualified_type_real (t, quals,
14276 					    complain | tf_ignore_bad_quals);
14277 	}
14278     }
14279 
14280   bool fndecl_type = (complain & tf_fndecl_type);
14281   complain &= ~tf_fndecl_type;
14282 
14283   if (type
14284       && code != TYPENAME_TYPE
14285       && code != TEMPLATE_TYPE_PARM
14286       && code != TEMPLATE_PARM_INDEX
14287       && code != IDENTIFIER_NODE
14288       && code != FUNCTION_TYPE
14289       && code != METHOD_TYPE)
14290     type = tsubst (type, args, complain, in_decl);
14291   if (type == error_mark_node)
14292     return error_mark_node;
14293 
14294   switch (code)
14295     {
14296     case RECORD_TYPE:
14297     case UNION_TYPE:
14298     case ENUMERAL_TYPE:
14299       return tsubst_aggr_type (t, args, complain, in_decl,
14300 			       /*entering_scope=*/0);
14301 
14302     case ERROR_MARK:
14303     case IDENTIFIER_NODE:
14304     case VOID_TYPE:
14305     case REAL_TYPE:
14306     case COMPLEX_TYPE:
14307     case VECTOR_TYPE:
14308     case BOOLEAN_TYPE:
14309     case NULLPTR_TYPE:
14310     case LANG_TYPE:
14311       return t;
14312 
14313     case INTEGER_TYPE:
14314       if (t == integer_type_node)
14315 	return t;
14316 
14317       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
14318           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
14319         return t;
14320 
14321       {
14322 	tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
14323 
14324 	max = tsubst_expr (omax, args, complain, in_decl,
14325 			   /*integral_constant_expression_p=*/false);
14326 
14327 	/* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
14328 	   needed.  */
14329 	if (TREE_CODE (max) == NOP_EXPR
14330 	    && TREE_SIDE_EFFECTS (omax)
14331 	    && !TREE_TYPE (max))
14332 	  TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
14333 
14334 	/* If we're in a partial instantiation, preserve the magic NOP_EXPR
14335 	   with TREE_SIDE_EFFECTS that indicates this is not an integral
14336 	   constant expression.  */
14337 	if (processing_template_decl
14338 	    && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
14339 	  {
14340 	    gcc_assert (TREE_CODE (max) == NOP_EXPR);
14341 	    TREE_SIDE_EFFECTS (max) = 1;
14342 	  }
14343 
14344 	return compute_array_index_type (NULL_TREE, max, complain);
14345       }
14346 
14347     case TEMPLATE_TYPE_PARM:
14348     case TEMPLATE_TEMPLATE_PARM:
14349     case BOUND_TEMPLATE_TEMPLATE_PARM:
14350     case TEMPLATE_PARM_INDEX:
14351       {
14352 	int idx;
14353 	int level;
14354 	int levels;
14355 	tree arg = NULL_TREE;
14356 
14357 	/* Early in template argument deduction substitution, we don't
14358 	   want to reduce the level of 'auto', or it will be confused
14359 	   with a normal template parm in subsequent deduction.  */
14360 	if (is_auto (t) && (complain & tf_partial))
14361 	  return t;
14362 
14363 	r = NULL_TREE;
14364 
14365 	gcc_assert (TREE_VEC_LENGTH (args) > 0);
14366 	template_parm_level_and_index (t, &level, &idx);
14367 
14368 	levels = TMPL_ARGS_DEPTH (args);
14369 	if (level <= levels
14370 	    && TREE_VEC_LENGTH (TMPL_ARGS_LEVEL (args, level)) > 0)
14371 	  {
14372 	    arg = TMPL_ARG (args, level, idx);
14373 
14374 	    /* See through ARGUMENT_PACK_SELECT arguments. */
14375 	    if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
14376 	      arg = argument_pack_select_arg (arg);
14377 	  }
14378 
14379 	if (arg == error_mark_node)
14380 	  return error_mark_node;
14381 	else if (arg != NULL_TREE)
14382 	  {
14383 	    if (ARGUMENT_PACK_P (arg))
14384 	      /* If ARG is an argument pack, we don't actually want to
14385 		 perform a substitution here, because substitutions
14386 		 for argument packs are only done
14387 		 element-by-element. We can get to this point when
14388 		 substituting the type of a non-type template
14389 		 parameter pack, when that type actually contains
14390 		 template parameter packs from an outer template, e.g.,
14391 
14392 	         template<typename... Types> struct A {
14393 		   template<Types... Values> struct B { };
14394                  };  */
14395 	      return t;
14396 
14397 	    if (code == TEMPLATE_TYPE_PARM)
14398 	      {
14399 		int quals;
14400 		gcc_assert (TYPE_P (arg));
14401 
14402 		quals = cp_type_quals (arg) | cp_type_quals (t);
14403 
14404 		return cp_build_qualified_type_real
14405 		  (arg, quals, complain | tf_ignore_bad_quals);
14406 	      }
14407 	    else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
14408 	      {
14409 		/* We are processing a type constructed from a
14410 		   template template parameter.  */
14411 		tree argvec = tsubst (TYPE_TI_ARGS (t),
14412 				      args, complain, in_decl);
14413 		if (argvec == error_mark_node)
14414 		  return error_mark_node;
14415 
14416 		gcc_assert (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
14417 			    || TREE_CODE (arg) == TEMPLATE_DECL
14418 			    || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
14419 
14420 		if (TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
14421 		  /* Consider this code:
14422 
14423 			template <template <class> class Template>
14424 			struct Internal {
14425 			template <class Arg> using Bind = Template<Arg>;
14426 			};
14427 
14428 			template <template <class> class Template, class Arg>
14429 			using Instantiate = Template<Arg>; //#0
14430 
14431 			template <template <class> class Template,
14432                                   class Argument>
14433 			using Bind =
14434 			  Instantiate<Internal<Template>::template Bind,
14435 				      Argument>; //#1
14436 
14437 		     When #1 is parsed, the
14438 		     BOUND_TEMPLATE_TEMPLATE_PARM representing the
14439 		     parameter `Template' in #0 matches the
14440 		     UNBOUND_CLASS_TEMPLATE representing the argument
14441 		     `Internal<Template>::template Bind'; We then want
14442 		     to assemble the type `Bind<Argument>' that can't
14443 		     be fully created right now, because
14444 		     `Internal<Template>' not being complete, the Bind
14445 		     template cannot be looked up in that context.  So
14446 		     we need to "store" `Bind<Argument>' for later
14447 		     when the context of Bind becomes complete.  Let's
14448 		     store that in a TYPENAME_TYPE.  */
14449 		  return make_typename_type (TYPE_CONTEXT (arg),
14450 					     build_nt (TEMPLATE_ID_EXPR,
14451 						       TYPE_IDENTIFIER (arg),
14452 						       argvec),
14453 					     typename_type,
14454 					     complain);
14455 
14456 		/* We can get a TEMPLATE_TEMPLATE_PARM here when we
14457 		   are resolving nested-types in the signature of a
14458 		   member function templates.  Otherwise ARG is a
14459 		   TEMPLATE_DECL and is the real template to be
14460 		   instantiated.  */
14461 		if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
14462 		  arg = TYPE_NAME (arg);
14463 
14464 		r = lookup_template_class (arg,
14465 					   argvec, in_decl,
14466 					   DECL_CONTEXT (arg),
14467 					    /*entering_scope=*/0,
14468 					   complain);
14469 		return cp_build_qualified_type_real
14470 		  (r, cp_type_quals (t) | cp_type_quals (r), complain);
14471 	      }
14472 	    else if (code == TEMPLATE_TEMPLATE_PARM)
14473 	      return arg;
14474 	    else
14475 	      /* TEMPLATE_PARM_INDEX.  */
14476 	      return convert_from_reference (unshare_expr (arg));
14477 	  }
14478 
14479 	if (level == 1)
14480 	  /* This can happen during the attempted tsubst'ing in
14481 	     unify.  This means that we don't yet have any information
14482 	     about the template parameter in question.  */
14483 	  return t;
14484 
14485 	/* If we get here, we must have been looking at a parm for a
14486 	   more deeply nested template.  Make a new version of this
14487 	   template parameter, but with a lower level.  */
14488 	switch (code)
14489 	  {
14490 	  case TEMPLATE_TYPE_PARM:
14491 	  case TEMPLATE_TEMPLATE_PARM:
14492 	  case BOUND_TEMPLATE_TEMPLATE_PARM:
14493 	    if (cp_type_quals (t))
14494 	      {
14495 		r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
14496 		r = cp_build_qualified_type_real
14497 		  (r, cp_type_quals (t),
14498 		   complain | (code == TEMPLATE_TYPE_PARM
14499 			       ? tf_ignore_bad_quals : 0));
14500 	      }
14501 	    else if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
14502 		     && PLACEHOLDER_TYPE_CONSTRAINTS (t)
14503 		     && (r = (TEMPLATE_PARM_DESCENDANTS
14504 			      (TEMPLATE_TYPE_PARM_INDEX (t))))
14505 		     && (r = TREE_TYPE (r))
14506 		     && !PLACEHOLDER_TYPE_CONSTRAINTS (r))
14507 	      /* Break infinite recursion when substituting the constraints
14508 		 of a constrained placeholder.  */;
14509 	    else if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
14510 		     && !PLACEHOLDER_TYPE_CONSTRAINTS (t)
14511 		     && !CLASS_PLACEHOLDER_TEMPLATE (t)
14512 		     && (arg = TEMPLATE_TYPE_PARM_INDEX (t),
14513 			 r = TEMPLATE_PARM_DESCENDANTS (arg))
14514 		     && (TEMPLATE_PARM_LEVEL (r)
14515 			 == TEMPLATE_PARM_LEVEL (arg) - levels))
14516 		/* Cache the simple case of lowering a type parameter.  */
14517 	      r = TREE_TYPE (r);
14518 	    else
14519 	      {
14520 		r = copy_type (t);
14521 		TEMPLATE_TYPE_PARM_INDEX (r)
14522 		  = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
14523 						r, levels, args, complain);
14524 		TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
14525 		TYPE_MAIN_VARIANT (r) = r;
14526 		TYPE_POINTER_TO (r) = NULL_TREE;
14527 		TYPE_REFERENCE_TO (r) = NULL_TREE;
14528 
14529                 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
14530 		  {
14531 		    /* Propagate constraints on placeholders.  */
14532 		    if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (t))
14533 		      PLACEHOLDER_TYPE_CONSTRAINTS (r)
14534 			= tsubst_constraint (constr, args, complain, in_decl);
14535 		    else if (tree pl = CLASS_PLACEHOLDER_TEMPLATE (t))
14536 		      {
14537 			pl = tsubst_copy (pl, args, complain, in_decl);
14538 			CLASS_PLACEHOLDER_TEMPLATE (r) = pl;
14539 		      }
14540 		  }
14541 
14542 		if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
14543 		  /* We have reduced the level of the template
14544 		     template parameter, but not the levels of its
14545 		     template parameters, so canonical_type_parameter
14546 		     will not be able to find the canonical template
14547 		     template parameter for this level. Thus, we
14548 		     require structural equality checking to compare
14549 		     TEMPLATE_TEMPLATE_PARMs. */
14550 		  SET_TYPE_STRUCTURAL_EQUALITY (r);
14551 		else if (TYPE_STRUCTURAL_EQUALITY_P (t))
14552 		  SET_TYPE_STRUCTURAL_EQUALITY (r);
14553 		else
14554 		  TYPE_CANONICAL (r) = canonical_type_parameter (r);
14555 
14556 		if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
14557 		  {
14558 		    tree tinfo = TYPE_TEMPLATE_INFO (t);
14559 		    /* We might need to substitute into the types of non-type
14560 		       template parameters.  */
14561 		    tree tmpl = tsubst (TI_TEMPLATE (tinfo), args,
14562 					complain, in_decl);
14563 		    if (tmpl == error_mark_node)
14564 		      return error_mark_node;
14565 		    tree argvec = tsubst (TI_ARGS (tinfo), args,
14566 					  complain, in_decl);
14567 		    if (argvec == error_mark_node)
14568 		      return error_mark_node;
14569 
14570 		    TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
14571 		      = build_template_info (tmpl, argvec);
14572 		  }
14573 	      }
14574 	    break;
14575 
14576 	  case TEMPLATE_PARM_INDEX:
14577 	    /* OK, now substitute the type of the non-type parameter.  We
14578 	       couldn't do it earlier because it might be an auto parameter,
14579 	       and we wouldn't need to if we had an argument.  */
14580 	    type = tsubst (type, args, complain, in_decl);
14581 	    if (type == error_mark_node)
14582 	      return error_mark_node;
14583 	    r = reduce_template_parm_level (t, type, levels, args, complain);
14584 	    break;
14585 
14586 	  default:
14587 	    gcc_unreachable ();
14588 	  }
14589 
14590 	return r;
14591       }
14592 
14593     case TREE_LIST:
14594       {
14595 	tree purpose, value, chain;
14596 
14597 	if (t == void_list_node)
14598 	  return t;
14599 
14600 	purpose = TREE_PURPOSE (t);
14601 	if (purpose)
14602 	  {
14603 	    purpose = tsubst (purpose, args, complain, in_decl);
14604 	    if (purpose == error_mark_node)
14605 	      return error_mark_node;
14606 	  }
14607 	value = TREE_VALUE (t);
14608 	if (value)
14609 	  {
14610 	    value = tsubst (value, args, complain, in_decl);
14611 	    if (value == error_mark_node)
14612 	      return error_mark_node;
14613 	  }
14614 	chain = TREE_CHAIN (t);
14615 	if (chain && chain != void_type_node)
14616 	  {
14617 	    chain = tsubst (chain, args, complain, in_decl);
14618 	    if (chain == error_mark_node)
14619 	      return error_mark_node;
14620 	  }
14621 	if (purpose == TREE_PURPOSE (t)
14622 	    && value == TREE_VALUE (t)
14623 	    && chain == TREE_CHAIN (t))
14624 	  return t;
14625 	return hash_tree_cons (purpose, value, chain);
14626       }
14627 
14628     case TREE_BINFO:
14629       /* We should never be tsubsting a binfo.  */
14630       gcc_unreachable ();
14631 
14632     case TREE_VEC:
14633       /* A vector of template arguments.  */
14634       gcc_assert (!type);
14635       return tsubst_template_args (t, args, complain, in_decl);
14636 
14637     case POINTER_TYPE:
14638     case REFERENCE_TYPE:
14639       {
14640 	if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
14641 	  return t;
14642 
14643 	/* [temp.deduct]
14644 
14645 	   Type deduction may fail for any of the following
14646 	   reasons:
14647 
14648 	   -- Attempting to create a pointer to reference type.
14649 	   -- Attempting to create a reference to a reference type or
14650 	      a reference to void.
14651 
14652 	  Core issue 106 says that creating a reference to a reference
14653 	  during instantiation is no longer a cause for failure. We
14654 	  only enforce this check in strict C++98 mode.  */
14655 	if ((TREE_CODE (type) == REFERENCE_TYPE
14656 	     && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
14657 	    || (code == REFERENCE_TYPE && VOID_TYPE_P (type)))
14658 	  {
14659 	    static location_t last_loc;
14660 
14661 	    /* We keep track of the last time we issued this error
14662 	       message to avoid spewing a ton of messages during a
14663 	       single bad template instantiation.  */
14664 	    if (complain & tf_error
14665 		&& last_loc != input_location)
14666 	      {
14667 		if (VOID_TYPE_P (type))
14668 		  error ("forming reference to void");
14669                else if (code == POINTER_TYPE)
14670                  error ("forming pointer to reference type %qT", type);
14671                else
14672 		  error ("forming reference to reference type %qT", type);
14673 		last_loc = input_location;
14674 	      }
14675 
14676 	    return error_mark_node;
14677 	  }
14678 	else if (TREE_CODE (type) == FUNCTION_TYPE
14679 		 && (type_memfn_quals (type) != TYPE_UNQUALIFIED
14680 		     || type_memfn_rqual (type) != REF_QUAL_NONE))
14681 	  {
14682 	    if (complain & tf_error)
14683 	      {
14684 		if (code == POINTER_TYPE)
14685 		  error ("forming pointer to qualified function type %qT",
14686 			 type);
14687 		else
14688 		  error ("forming reference to qualified function type %qT",
14689 			 type);
14690 	      }
14691 	    return error_mark_node;
14692 	  }
14693 	else if (code == POINTER_TYPE)
14694 	  {
14695 	    r = build_pointer_type (type);
14696 	    if (TREE_CODE (type) == METHOD_TYPE)
14697 	      r = build_ptrmemfunc_type (r);
14698 	  }
14699 	else if (TREE_CODE (type) == REFERENCE_TYPE)
14700 	  /* In C++0x, during template argument substitution, when there is an
14701 	     attempt to create a reference to a reference type, reference
14702 	     collapsing is applied as described in [14.3.1/4 temp.arg.type]:
14703 
14704 	     "If a template-argument for a template-parameter T names a type
14705 	     that is a reference to a type A, an attempt to create the type
14706 	     'lvalue reference to cv T' creates the type 'lvalue reference to
14707 	     A,' while an attempt to create the type type rvalue reference to
14708 	     cv T' creates the type T"
14709 	  */
14710 	  r = cp_build_reference_type
14711 	      (TREE_TYPE (type),
14712 	       TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
14713 	else
14714 	  r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
14715 	r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
14716 
14717 	if (r != error_mark_node)
14718 	  /* Will this ever be needed for TYPE_..._TO values?  */
14719 	  layout_type (r);
14720 
14721 	return r;
14722       }
14723     case OFFSET_TYPE:
14724       {
14725 	r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
14726 	if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
14727 	  {
14728 	    /* [temp.deduct]
14729 
14730 	       Type deduction may fail for any of the following
14731 	       reasons:
14732 
14733 	       -- Attempting to create "pointer to member of T" when T
14734 		  is not a class type.  */
14735 	    if (complain & tf_error)
14736 	      error ("creating pointer to member of non-class type %qT", r);
14737 	    return error_mark_node;
14738 	  }
14739 	if (TREE_CODE (type) == REFERENCE_TYPE)
14740 	  {
14741 	    if (complain & tf_error)
14742 	      error ("creating pointer to member reference type %qT", type);
14743 	    return error_mark_node;
14744 	  }
14745 	if (VOID_TYPE_P (type))
14746 	  {
14747 	    if (complain & tf_error)
14748 	      error ("creating pointer to member of type void");
14749 	    return error_mark_node;
14750 	  }
14751 	gcc_assert (TREE_CODE (type) != METHOD_TYPE);
14752 	if (TREE_CODE (type) == FUNCTION_TYPE)
14753 	  {
14754 	    /* The type of the implicit object parameter gets its
14755 	       cv-qualifiers from the FUNCTION_TYPE. */
14756 	    tree memptr;
14757 	    tree method_type
14758 	      = build_memfn_type (type, r, type_memfn_quals (type),
14759 				  type_memfn_rqual (type));
14760 	    memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
14761 	    return cp_build_qualified_type_real (memptr, cp_type_quals (t),
14762 						 complain);
14763 	  }
14764 	else
14765 	  return cp_build_qualified_type_real (build_ptrmem_type (r, type),
14766 					       cp_type_quals (t),
14767 					       complain);
14768       }
14769     case FUNCTION_TYPE:
14770     case METHOD_TYPE:
14771       {
14772 	tree fntype;
14773 	tree specs;
14774 	fntype = tsubst_function_type (t, args, complain, in_decl);
14775 	if (fntype == error_mark_node)
14776 	  return error_mark_node;
14777 
14778 	/* Substitute the exception specification.  */
14779 	specs = tsubst_exception_specification (t, args, complain, in_decl,
14780 						/*defer_ok*/fndecl_type);
14781 	if (specs == error_mark_node)
14782 	  return error_mark_node;
14783 	if (specs)
14784 	  fntype = build_exception_variant (fntype, specs);
14785 	return fntype;
14786       }
14787     case ARRAY_TYPE:
14788       {
14789 	tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
14790 	if (domain == error_mark_node)
14791 	  return error_mark_node;
14792 
14793 	/* As an optimization, we avoid regenerating the array type if
14794 	   it will obviously be the same as T.  */
14795 	if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
14796 	  return t;
14797 
14798 	/* These checks should match the ones in create_array_type_for_decl.
14799 
14800 	   [temp.deduct]
14801 
14802 	   The deduction may fail for any of the following reasons:
14803 
14804 	   -- Attempting to create an array with an element type that
14805 	      is void, a function type, or a reference type, or [DR337]
14806 	      an abstract class type.  */
14807 	if (VOID_TYPE_P (type)
14808 	    || TREE_CODE (type) == FUNCTION_TYPE
14809 	    || (TREE_CODE (type) == ARRAY_TYPE
14810 		&& TYPE_DOMAIN (type) == NULL_TREE)
14811 	    || TREE_CODE (type) == REFERENCE_TYPE)
14812 	  {
14813 	    if (complain & tf_error)
14814 	      error ("creating array of %qT", type);
14815 	    return error_mark_node;
14816 	  }
14817 
14818 	if (abstract_virtuals_error_sfinae (ACU_ARRAY, type, complain))
14819 	  return error_mark_node;
14820 
14821 	r = build_cplus_array_type (type, domain);
14822 
14823 	if (TYPE_USER_ALIGN (t))
14824 	  {
14825 	    SET_TYPE_ALIGN (r, TYPE_ALIGN (t));
14826 	    TYPE_USER_ALIGN (r) = 1;
14827 	  }
14828 
14829 	return r;
14830       }
14831 
14832     case TYPENAME_TYPE:
14833       {
14834 	tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
14835 				     in_decl, /*entering_scope=*/1);
14836 	if (ctx == error_mark_node)
14837 	  return error_mark_node;
14838 
14839 	tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
14840 			      complain, in_decl);
14841 	if (f == error_mark_node)
14842 	  return error_mark_node;
14843 
14844 	if (!MAYBE_CLASS_TYPE_P (ctx))
14845 	  {
14846 	    if (complain & tf_error)
14847 	      error ("%qT is not a class, struct, or union type", ctx);
14848 	    return error_mark_node;
14849 	  }
14850 	else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
14851 	  {
14852 	    /* Normally, make_typename_type does not require that the CTX
14853 	       have complete type in order to allow things like:
14854 
14855 		 template <class T> struct S { typename S<T>::X Y; };
14856 
14857 	       But, such constructs have already been resolved by this
14858 	       point, so here CTX really should have complete type, unless
14859 	       it's a partial instantiation.  */
14860 	    ctx = complete_type (ctx);
14861 	    if (!COMPLETE_TYPE_P (ctx))
14862 	      {
14863 		if (complain & tf_error)
14864 		  cxx_incomplete_type_error (NULL_TREE, ctx);
14865 		return error_mark_node;
14866 	      }
14867 	  }
14868 
14869 	f = make_typename_type (ctx, f, typename_type,
14870 				complain | tf_keep_type_decl);
14871 	if (f == error_mark_node)
14872 	  return f;
14873 	if (TREE_CODE (f) == TYPE_DECL)
14874 	  {
14875 	    complain |= tf_ignore_bad_quals;
14876 	    f = TREE_TYPE (f);
14877 	  }
14878 
14879 	if (TREE_CODE (f) != TYPENAME_TYPE)
14880 	  {
14881 	    if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
14882 	      {
14883 		if (complain & tf_error)
14884 		  error ("%qT resolves to %qT, which is not an enumeration type",
14885 			 t, f);
14886 		else
14887 		  return error_mark_node;
14888 	      }
14889 	    else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
14890 	      {
14891 		if (complain & tf_error)
14892 		  error ("%qT resolves to %qT, which is is not a class type",
14893 			 t, f);
14894 		else
14895 		  return error_mark_node;
14896 	      }
14897 	  }
14898 
14899 	return cp_build_qualified_type_real
14900 	  (f, cp_type_quals (f) | cp_type_quals (t), complain);
14901       }
14902 
14903     case UNBOUND_CLASS_TEMPLATE:
14904       {
14905 	tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
14906 				     in_decl, /*entering_scope=*/1);
14907 	tree name = TYPE_IDENTIFIER (t);
14908 	tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
14909 
14910 	if (ctx == error_mark_node || name == error_mark_node)
14911 	  return error_mark_node;
14912 
14913 	if (parm_list)
14914 	  parm_list = tsubst_template_parms (parm_list, args, complain);
14915 	return make_unbound_class_template (ctx, name, parm_list, complain);
14916       }
14917 
14918     case TYPEOF_TYPE:
14919       {
14920 	tree type;
14921 
14922 	++cp_unevaluated_operand;
14923 	++c_inhibit_evaluation_warnings;
14924 
14925 	type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
14926 			    complain, in_decl,
14927 			    /*integral_constant_expression_p=*/false);
14928 
14929 	--cp_unevaluated_operand;
14930 	--c_inhibit_evaluation_warnings;
14931 
14932 	type = finish_typeof (type);
14933 	return cp_build_qualified_type_real (type,
14934 					     cp_type_quals (t)
14935 					     | cp_type_quals (type),
14936 					     complain);
14937       }
14938 
14939     case DECLTYPE_TYPE:
14940       {
14941 	tree type;
14942 
14943 	++cp_unevaluated_operand;
14944 	++c_inhibit_evaluation_warnings;
14945 
14946 	type = tsubst_copy_and_build (DECLTYPE_TYPE_EXPR (t), args,
14947 				      complain|tf_decltype, in_decl,
14948 				      /*function_p*/false,
14949 				      /*integral_constant_expression*/false);
14950 
14951 	if (DECLTYPE_FOR_INIT_CAPTURE (t))
14952 	  {
14953 	    if (type == NULL_TREE)
14954 	      {
14955 		if (complain & tf_error)
14956 		  error ("empty initializer in lambda init-capture");
14957 		type = error_mark_node;
14958 	      }
14959 	    else if (TREE_CODE (type) == TREE_LIST)
14960 	      type = build_x_compound_expr_from_list (type, ELK_INIT, complain);
14961 	  }
14962 
14963 	--cp_unevaluated_operand;
14964 	--c_inhibit_evaluation_warnings;
14965 
14966 	if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
14967 	  type = lambda_capture_field_type (type,
14968 					    DECLTYPE_FOR_INIT_CAPTURE (t),
14969 					    DECLTYPE_FOR_REF_CAPTURE (t));
14970 	else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
14971 	  type = lambda_proxy_type (type);
14972 	else
14973 	  {
14974 	    bool id = DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t);
14975 	    if (id && TREE_CODE (DECLTYPE_TYPE_EXPR (t)) == BIT_NOT_EXPR
14976 		&& EXPR_P (type))
14977 	      /* In a template ~id could be either a complement expression
14978 		 or an unqualified-id naming a destructor; if instantiating
14979 		 it produces an expression, it's not an id-expression or
14980 		 member access.  */
14981 	      id = false;
14982 	    type = finish_decltype_type (type, id, complain);
14983 	  }
14984 	return cp_build_qualified_type_real (type,
14985 					     cp_type_quals (t)
14986 					     | cp_type_quals (type),
14987 					     complain | tf_ignore_bad_quals);
14988       }
14989 
14990     case UNDERLYING_TYPE:
14991       {
14992 	tree type = tsubst (UNDERLYING_TYPE_TYPE (t), args,
14993 			    complain, in_decl);
14994 	return finish_underlying_type (type);
14995       }
14996 
14997     case TYPE_ARGUMENT_PACK:
14998     case NONTYPE_ARGUMENT_PACK:
14999       {
15000         tree r;
15001 
15002 	if (code == NONTYPE_ARGUMENT_PACK)
15003 	  r = make_node (code);
15004 	else
15005 	  r = cxx_make_type (code);
15006 
15007 	tree pack_args = ARGUMENT_PACK_ARGS (t);
15008 	pack_args = tsubst_template_args (pack_args, args, complain, in_decl);
15009 	SET_ARGUMENT_PACK_ARGS (r, pack_args);
15010 
15011 	return r;
15012       }
15013 
15014     case VOID_CST:
15015     case INTEGER_CST:
15016     case REAL_CST:
15017     case STRING_CST:
15018     case PLUS_EXPR:
15019     case MINUS_EXPR:
15020     case NEGATE_EXPR:
15021     case NOP_EXPR:
15022     case INDIRECT_REF:
15023     case ADDR_EXPR:
15024     case CALL_EXPR:
15025     case ARRAY_REF:
15026     case SCOPE_REF:
15027       /* We should use one of the expression tsubsts for these codes.  */
15028       gcc_unreachable ();
15029 
15030     default:
15031       sorry ("use of %qs in template", get_tree_code_name (code));
15032       return error_mark_node;
15033     }
15034 }
15035 
15036 /* tsubst a BASELINK.  OBJECT_TYPE, if non-NULL, is the type of the
15037    expression on the left-hand side of the "." or "->" operator.  We
15038    only do the lookup if we had a dependent BASELINK.  Otherwise we
15039    adjust it onto the instantiated heirarchy.  */
15040 
15041 static tree
tsubst_baselink(tree baselink,tree object_type,tree args,tsubst_flags_t complain,tree in_decl)15042 tsubst_baselink (tree baselink, tree object_type,
15043 		 tree args, tsubst_flags_t complain, tree in_decl)
15044 {
15045   bool qualified_p = BASELINK_QUALIFIED_P (baselink);
15046   tree qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
15047   qualifying_scope = tsubst (qualifying_scope, args, complain, in_decl);
15048 
15049   tree optype = BASELINK_OPTYPE (baselink);
15050   optype = tsubst (optype, args, complain, in_decl);
15051 
15052   tree template_args = NULL_TREE;
15053   bool template_id_p = false;
15054   tree fns = BASELINK_FUNCTIONS (baselink);
15055   if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
15056     {
15057       template_id_p = true;
15058       template_args = TREE_OPERAND (fns, 1);
15059       fns = TREE_OPERAND (fns, 0);
15060       if (template_args)
15061 	template_args = tsubst_template_args (template_args, args,
15062 					      complain, in_decl);
15063     }
15064 
15065   tree binfo_type = BINFO_TYPE (BASELINK_BINFO (baselink));
15066   binfo_type = tsubst (binfo_type, args, complain, in_decl);
15067   bool dependent_p = binfo_type != BINFO_TYPE (BASELINK_BINFO (baselink));
15068 
15069   if (dependent_p)
15070     {
15071       tree name = OVL_NAME (fns);
15072       if (IDENTIFIER_CONV_OP_P (name))
15073 	name = make_conv_op_name (optype);
15074 
15075       if (name == complete_dtor_identifier)
15076 	/* Treat as-if non-dependent below.  */
15077 	dependent_p = false;
15078 
15079       baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
15080       if (!baselink)
15081 	{
15082 	  if ((complain & tf_error)
15083 	      && constructor_name_p (name, qualifying_scope))
15084 	    error ("cannot call constructor %<%T::%D%> directly",
15085 		   qualifying_scope, name);
15086 	  return error_mark_node;
15087 	}
15088 
15089       if (BASELINK_P (baselink))
15090 	fns = BASELINK_FUNCTIONS (baselink);
15091     }
15092   else
15093     /* We're going to overwrite pieces below, make a duplicate.  */
15094     baselink = copy_node (baselink);
15095 
15096   /* If lookup found a single function, mark it as used at this point.
15097      (If lookup found multiple functions the one selected later by
15098      overload resolution will be marked as used at that point.)  */
15099   if (!template_id_p && !really_overloaded_fn (fns))
15100     {
15101       tree fn = OVL_FIRST (fns);
15102       bool ok = mark_used (fn, complain);
15103       if (!ok && !(complain & tf_error))
15104 	return error_mark_node;
15105       if (ok && BASELINK_P (baselink))
15106 	/* We might have instantiated an auto function.  */
15107 	TREE_TYPE (baselink) = TREE_TYPE (fn);
15108     }
15109 
15110   if (BASELINK_P (baselink))
15111     {
15112       /* Add back the template arguments, if present.  */
15113       if (template_id_p)
15114 	BASELINK_FUNCTIONS (baselink)
15115 	  = build2 (TEMPLATE_ID_EXPR, unknown_type_node, fns, template_args);
15116 
15117       /* Update the conversion operator type.  */
15118       BASELINK_OPTYPE (baselink) = optype;
15119     }
15120 
15121   if (!object_type)
15122     object_type = current_class_type;
15123 
15124   if (qualified_p || !dependent_p)
15125     {
15126       baselink = adjust_result_of_qualified_name_lookup (baselink,
15127 							 qualifying_scope,
15128 							 object_type);
15129       if (!qualified_p)
15130 	/* We need to call adjust_result_of_qualified_name_lookup in case the
15131 	   destructor names a base class, but we unset BASELINK_QUALIFIED_P
15132 	   so that we still get virtual function binding.  */
15133 	BASELINK_QUALIFIED_P (baselink) = false;
15134     }
15135 
15136   return baselink;
15137 }
15138 
15139 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
15140    true if the qualified-id will be a postfix-expression in-and-of
15141    itself; false if more of the postfix-expression follows the
15142    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
15143    of "&".  */
15144 
15145 static tree
tsubst_qualified_id(tree qualified_id,tree args,tsubst_flags_t complain,tree in_decl,bool done,bool address_p)15146 tsubst_qualified_id (tree qualified_id, tree args,
15147 		     tsubst_flags_t complain, tree in_decl,
15148 		     bool done, bool address_p)
15149 {
15150   tree expr;
15151   tree scope;
15152   tree name;
15153   bool is_template;
15154   tree template_args;
15155   location_t loc = UNKNOWN_LOCATION;
15156 
15157   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
15158 
15159   /* Figure out what name to look up.  */
15160   name = TREE_OPERAND (qualified_id, 1);
15161   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
15162     {
15163       is_template = true;
15164       loc = EXPR_LOCATION (name);
15165       template_args = TREE_OPERAND (name, 1);
15166       if (template_args)
15167 	template_args = tsubst_template_args (template_args, args,
15168 					      complain, in_decl);
15169       if (template_args == error_mark_node)
15170 	return error_mark_node;
15171       name = TREE_OPERAND (name, 0);
15172     }
15173   else
15174     {
15175       is_template = false;
15176       template_args = NULL_TREE;
15177     }
15178 
15179   /* Substitute into the qualifying scope.  When there are no ARGS, we
15180      are just trying to simplify a non-dependent expression.  In that
15181      case the qualifying scope may be dependent, and, in any case,
15182      substituting will not help.  */
15183   scope = TREE_OPERAND (qualified_id, 0);
15184   if (args)
15185     {
15186       scope = tsubst (scope, args, complain, in_decl);
15187       expr = tsubst_copy (name, args, complain, in_decl);
15188     }
15189   else
15190     expr = name;
15191 
15192   if (dependent_scope_p (scope))
15193     {
15194       if (is_template)
15195 	expr = build_min_nt_loc (loc, TEMPLATE_ID_EXPR, expr, template_args);
15196       tree r = build_qualified_name (NULL_TREE, scope, expr,
15197 				     QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
15198       REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (qualified_id);
15199       return r;
15200     }
15201 
15202   if (!BASELINK_P (name) && !DECL_P (expr))
15203     {
15204       if (TREE_CODE (expr) == BIT_NOT_EXPR)
15205 	{
15206 	  /* A BIT_NOT_EXPR is used to represent a destructor.  */
15207 	  if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
15208 	    {
15209 	      error ("qualifying type %qT does not match destructor name ~%qT",
15210 		     scope, TREE_OPERAND (expr, 0));
15211 	      expr = error_mark_node;
15212 	    }
15213 	  else
15214 	    expr = lookup_qualified_name (scope, complete_dtor_identifier,
15215 					  /*is_type_p=*/0, false);
15216 	}
15217       else
15218 	expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
15219       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
15220 		     ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
15221 	{
15222 	  if (complain & tf_error)
15223 	    {
15224 	      error ("dependent-name %qE is parsed as a non-type, but "
15225 		     "instantiation yields a type", qualified_id);
15226 	      inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
15227 	    }
15228 	  return error_mark_node;
15229 	}
15230     }
15231 
15232   if (DECL_P (expr))
15233     {
15234       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
15235 					   scope);
15236       /* Remember that there was a reference to this entity.  */
15237       if (!mark_used (expr, complain) && !(complain & tf_error))
15238 	return error_mark_node;
15239     }
15240 
15241   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
15242     {
15243       if (complain & tf_error)
15244 	qualified_name_lookup_error (scope,
15245 				     TREE_OPERAND (qualified_id, 1),
15246 				     expr, input_location);
15247       return error_mark_node;
15248     }
15249 
15250   if (is_template)
15251     {
15252       /* We may be repeating a check already done during parsing, but
15253 	 if it was well-formed and passed then, it will pass again
15254 	 now, and if it didn't, we wouldn't have got here.  The case
15255 	 we want to catch is when we couldn't tell then, and can now,
15256 	 namely when templ prior to substitution was an
15257 	 identifier.  */
15258       if (flag_concepts && check_auto_in_tmpl_args (expr, template_args))
15259 	return error_mark_node;
15260 
15261       if (variable_template_p (expr))
15262 	expr = lookup_and_finish_template_variable (expr, template_args,
15263 						    complain);
15264       else
15265 	expr = lookup_template_function (expr, template_args);
15266     }
15267 
15268   if (expr == error_mark_node && complain & tf_error)
15269     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
15270 				 expr, input_location);
15271   else if (TYPE_P (scope))
15272     {
15273       expr = (adjust_result_of_qualified_name_lookup
15274 	      (expr, scope, current_nonlambda_class_type ()));
15275       expr = (finish_qualified_id_expr
15276 	      (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
15277 	       QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
15278 	       /*template_arg_p=*/false, complain));
15279     }
15280 
15281   /* Expressions do not generally have reference type.  */
15282   if (TREE_CODE (expr) != SCOPE_REF
15283       /* However, if we're about to form a pointer-to-member, we just
15284 	 want the referenced member referenced.  */
15285       && TREE_CODE (expr) != OFFSET_REF)
15286     expr = convert_from_reference (expr);
15287 
15288   if (REF_PARENTHESIZED_P (qualified_id))
15289     expr = force_paren_expr (expr);
15290 
15291   return expr;
15292 }
15293 
15294 /* tsubst the initializer for a VAR_DECL.  INIT is the unsubstituted
15295    initializer, DECL is the substituted VAR_DECL.  Other arguments are as
15296    for tsubst.  */
15297 
15298 static tree
tsubst_init(tree init,tree decl,tree args,tsubst_flags_t complain,tree in_decl)15299 tsubst_init (tree init, tree decl, tree args,
15300 	     tsubst_flags_t complain, tree in_decl)
15301 {
15302   if (!init)
15303     return NULL_TREE;
15304 
15305   init = tsubst_expr (init, args, complain, in_decl, false);
15306 
15307   if (!init && TREE_TYPE (decl) != error_mark_node)
15308     {
15309       /* If we had an initializer but it
15310 	 instantiated to nothing,
15311 	 value-initialize the object.  This will
15312 	 only occur when the initializer was a
15313 	 pack expansion where the parameter packs
15314 	 used in that expansion were of length
15315 	 zero.  */
15316       init = build_value_init (TREE_TYPE (decl),
15317 			       complain);
15318       if (TREE_CODE (init) == AGGR_INIT_EXPR)
15319 	init = get_target_expr_sfinae (init, complain);
15320       if (TREE_CODE (init) == TARGET_EXPR)
15321 	TARGET_EXPR_DIRECT_INIT_P (init) = true;
15322     }
15323 
15324   return init;
15325 }
15326 
15327 /* Like tsubst, but deals with expressions.  This function just replaces
15328    template parms; to finish processing the resultant expression, use
15329    tsubst_copy_and_build or tsubst_expr.  */
15330 
15331 static tree
tsubst_copy(tree t,tree args,tsubst_flags_t complain,tree in_decl)15332 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
15333 {
15334   enum tree_code code;
15335   tree r;
15336 
15337   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
15338     return t;
15339 
15340   code = TREE_CODE (t);
15341 
15342   switch (code)
15343     {
15344     case PARM_DECL:
15345       r = retrieve_local_specialization (t);
15346 
15347       if (r == NULL_TREE)
15348 	{
15349 	  /* We get here for a use of 'this' in an NSDMI.  */
15350 	  if (DECL_NAME (t) == this_identifier && current_class_ptr)
15351 	    return current_class_ptr;
15352 
15353 	  /* This can happen for a parameter name used later in a function
15354 	     declaration (such as in a late-specified return type).  Just
15355 	     make a dummy decl, since it's only used for its type.  */
15356 	  gcc_assert (cp_unevaluated_operand != 0);
15357 	  r = tsubst_decl (t, args, complain);
15358 	  /* Give it the template pattern as its context; its true context
15359 	     hasn't been instantiated yet and this is good enough for
15360 	     mangling.  */
15361 	  DECL_CONTEXT (r) = DECL_CONTEXT (t);
15362 	}
15363 
15364       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
15365 	r = argument_pack_select_arg (r);
15366       if (!mark_used (r, complain) && !(complain & tf_error))
15367 	return error_mark_node;
15368       return r;
15369 
15370     case CONST_DECL:
15371       {
15372 	tree enum_type;
15373 	tree v;
15374 
15375 	if (DECL_TEMPLATE_PARM_P (t))
15376 	  return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
15377 	/* There is no need to substitute into namespace-scope
15378 	   enumerators.  */
15379 	if (DECL_NAMESPACE_SCOPE_P (t))
15380 	  return t;
15381 	/* If ARGS is NULL, then T is known to be non-dependent.  */
15382 	if (args == NULL_TREE)
15383 	  return scalar_constant_value (t);
15384 
15385 	/* Unfortunately, we cannot just call lookup_name here.
15386 	   Consider:
15387 
15388 	     template <int I> int f() {
15389 	     enum E { a = I };
15390 	     struct S { void g() { E e = a; } };
15391 	     };
15392 
15393 	   When we instantiate f<7>::S::g(), say, lookup_name is not
15394 	   clever enough to find f<7>::a.  */
15395 	enum_type
15396 	  = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
15397 			      /*entering_scope=*/0);
15398 
15399 	for (v = TYPE_VALUES (enum_type);
15400 	     v != NULL_TREE;
15401 	     v = TREE_CHAIN (v))
15402 	  if (TREE_PURPOSE (v) == DECL_NAME (t))
15403 	    return TREE_VALUE (v);
15404 
15405 	  /* We didn't find the name.  That should never happen; if
15406 	     name-lookup found it during preliminary parsing, we
15407 	     should find it again here during instantiation.  */
15408 	gcc_unreachable ();
15409       }
15410       return t;
15411 
15412     case FIELD_DECL:
15413       if (DECL_CONTEXT (t))
15414 	{
15415 	  tree ctx;
15416 
15417 	  ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
15418 				  /*entering_scope=*/1);
15419 	  if (ctx != DECL_CONTEXT (t))
15420 	    {
15421 	      tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
15422 	      if (!r)
15423 		{
15424 		  if (complain & tf_error)
15425 		    error ("using invalid field %qD", t);
15426 		  return error_mark_node;
15427 		}
15428 	      return r;
15429 	    }
15430 	}
15431 
15432       return t;
15433 
15434     case VAR_DECL:
15435     case FUNCTION_DECL:
15436       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
15437 	r = tsubst (t, args, complain, in_decl);
15438       else if (local_variable_p (t)
15439 	       && uses_template_parms (DECL_CONTEXT (t)))
15440 	{
15441 	  r = retrieve_local_specialization (t);
15442 	  if (r == NULL_TREE)
15443 	    {
15444 	      /* First try name lookup to find the instantiation.  */
15445 	      r = lookup_name (DECL_NAME (t));
15446 	      if (r && !is_capture_proxy (r))
15447 		{
15448 		  /* Make sure that the one we found is the one we want.  */
15449 		  tree ctx = enclosing_instantiation_of (DECL_CONTEXT (t));
15450 		  if (ctx != DECL_CONTEXT (r))
15451 		    r = NULL_TREE;
15452 		}
15453 
15454 	      if (r)
15455 		/* OK */;
15456 	      else
15457 		{
15458 		  /* This can happen for a variable used in a
15459 		     late-specified return type of a local lambda, or for a
15460 		     local static or constant.  Building a new VAR_DECL
15461 		     should be OK in all those cases.  */
15462 		  r = tsubst_decl (t, args, complain);
15463 		  if (local_specializations)
15464 		    /* Avoid infinite recursion (79640).  */
15465 		    register_local_specialization (r, t);
15466 		  if (decl_maybe_constant_var_p (r))
15467 		    {
15468 		      /* We can't call cp_finish_decl, so handle the
15469 			 initializer by hand.  */
15470 		      tree init = tsubst_init (DECL_INITIAL (t), r, args,
15471 					       complain, in_decl);
15472 		      if (!processing_template_decl)
15473 			init = maybe_constant_init (init);
15474 		      if (processing_template_decl
15475 			  ? potential_constant_expression (init)
15476 			  : reduced_constant_expression_p (init))
15477 			DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
15478 			  = TREE_CONSTANT (r) = true;
15479 		      DECL_INITIAL (r) = init;
15480 		      if (tree auto_node = type_uses_auto (TREE_TYPE (r)))
15481 			TREE_TYPE (r)
15482 			  = do_auto_deduction (TREE_TYPE (r), init, auto_node,
15483 					       complain, adc_variable_type);
15484 		    }
15485 		  gcc_assert (cp_unevaluated_operand || TREE_STATIC (r)
15486 			      || decl_constant_var_p (r)
15487 			      || errorcount || sorrycount);
15488 		  if (!processing_template_decl
15489 		      && !TREE_STATIC (r))
15490 		    r = process_outer_var_ref (r, complain);
15491 		}
15492 	      /* Remember this for subsequent uses.  */
15493 	      if (local_specializations)
15494 		register_local_specialization (r, t);
15495 	    }
15496 	  if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
15497 	    r = argument_pack_select_arg (r);
15498 	}
15499       else
15500 	r = t;
15501       if (!mark_used (r, complain))
15502 	return error_mark_node;
15503       return r;
15504 
15505     case NAMESPACE_DECL:
15506       return t;
15507 
15508     case OVERLOAD:
15509       /* An OVERLOAD will always be a non-dependent overload set; an
15510 	 overload set from function scope will just be represented with an
15511 	 IDENTIFIER_NODE, and from class scope with a BASELINK.  */
15512       gcc_assert (!uses_template_parms (t));
15513       /* We must have marked any lookups as persistent.  */
15514       gcc_assert (!OVL_LOOKUP_P (t) || OVL_USED_P (t));
15515       return t;
15516 
15517     case BASELINK:
15518       return tsubst_baselink (t, current_nonlambda_class_type (),
15519 			      args, complain, in_decl);
15520 
15521     case TEMPLATE_DECL:
15522       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
15523 	return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
15524 		       args, complain, in_decl);
15525       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
15526 	return tsubst (t, args, complain, in_decl);
15527       else if (DECL_CLASS_SCOPE_P (t)
15528 	       && uses_template_parms (DECL_CONTEXT (t)))
15529 	{
15530 	  /* Template template argument like the following example need
15531 	     special treatment:
15532 
15533 	       template <template <class> class TT> struct C {};
15534 	       template <class T> struct D {
15535 		 template <class U> struct E {};
15536 		 C<E> c;				// #1
15537 	       };
15538 	       D<int> d;				// #2
15539 
15540 	     We are processing the template argument `E' in #1 for
15541 	     the template instantiation #2.  Originally, `E' is a
15542 	     TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
15543 	     have to substitute this with one having context `D<int>'.  */
15544 
15545 	  tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
15546 	  if (dependent_scope_p (context))
15547 	    {
15548 	      /* When rewriting a constructor into a deduction guide, a
15549 		 non-dependent name can become dependent, so memtmpl<args>
15550 		 becomes context::template memtmpl<args>.  */
15551 	      tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15552 	      return build_qualified_name (type, context, DECL_NAME (t),
15553 					   /*template*/true);
15554 	    }
15555 	  return lookup_field (context, DECL_NAME(t), 0, false);
15556 	}
15557       else
15558 	/* Ordinary template template argument.  */
15559 	return t;
15560 
15561     case NON_LVALUE_EXPR:
15562     case VIEW_CONVERT_EXPR:
15563 	{
15564 	  /* Handle location wrappers by substituting the wrapped node
15565 	     first, *then* reusing the resulting type.  Doing the type
15566 	     first ensures that we handle template parameters and
15567 	     parameter pack expansions.  */
15568 	  gcc_assert (location_wrapper_p (t));
15569 	  tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15570 	  return maybe_wrap_with_location (op0, EXPR_LOCATION (t));
15571 	}
15572 
15573     case CAST_EXPR:
15574     case REINTERPRET_CAST_EXPR:
15575     case CONST_CAST_EXPR:
15576     case STATIC_CAST_EXPR:
15577     case DYNAMIC_CAST_EXPR:
15578     case IMPLICIT_CONV_EXPR:
15579     case CONVERT_EXPR:
15580     case NOP_EXPR:
15581       {
15582 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15583 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15584 	return build1 (code, type, op0);
15585       }
15586 
15587     case SIZEOF_EXPR:
15588       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
15589 	  || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
15590         {
15591           tree expanded, op = TREE_OPERAND (t, 0);
15592 	  int len = 0;
15593 
15594 	  if (SIZEOF_EXPR_TYPE_P (t))
15595 	    op = TREE_TYPE (op);
15596 
15597 	  ++cp_unevaluated_operand;
15598 	  ++c_inhibit_evaluation_warnings;
15599 	  /* We only want to compute the number of arguments.  */
15600 	  if (PACK_EXPANSION_P (op))
15601 	    expanded = tsubst_pack_expansion (op, args, complain, in_decl);
15602 	  else
15603 	    expanded = tsubst_template_args (ARGUMENT_PACK_ARGS (op),
15604 					     args, complain, in_decl);
15605 	  --cp_unevaluated_operand;
15606 	  --c_inhibit_evaluation_warnings;
15607 
15608 	  if (TREE_CODE (expanded) == TREE_VEC)
15609 	    {
15610 	      len = TREE_VEC_LENGTH (expanded);
15611 	      /* Set TREE_USED for the benefit of -Wunused.  */
15612 	      for (int i = 0; i < len; i++)
15613 		if (DECL_P (TREE_VEC_ELT (expanded, i)))
15614 		  TREE_USED (TREE_VEC_ELT (expanded, i)) = true;
15615 	    }
15616 
15617 	  if (expanded == error_mark_node)
15618 	    return error_mark_node;
15619 	  else if (PACK_EXPANSION_P (expanded)
15620 		   || (TREE_CODE (expanded) == TREE_VEC
15621 		       && pack_expansion_args_count (expanded)))
15622 
15623 	    {
15624 	      if (PACK_EXPANSION_P (expanded))
15625 		/* OK.  */;
15626 	      else if (TREE_VEC_LENGTH (expanded) == 1)
15627 		expanded = TREE_VEC_ELT (expanded, 0);
15628 	      else
15629 		expanded = make_argument_pack (expanded);
15630 
15631 	      if (TYPE_P (expanded))
15632 		return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR,
15633 						   false,
15634 						   complain & tf_error);
15635 	      else
15636 		return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
15637                                                    complain & tf_error);
15638 	    }
15639 	  else
15640 	    return build_int_cst (size_type_node, len);
15641         }
15642       if (SIZEOF_EXPR_TYPE_P (t))
15643 	{
15644 	  r = tsubst (TREE_TYPE (TREE_OPERAND (t, 0)),
15645 		      args, complain, in_decl);
15646 	  r = build1 (NOP_EXPR, r, error_mark_node);
15647 	  r = build1 (SIZEOF_EXPR,
15648 		      tsubst (TREE_TYPE (t), args, complain, in_decl), r);
15649 	  SIZEOF_EXPR_TYPE_P (r) = 1;
15650 	  return r;
15651 	}
15652       /* Fall through */
15653 
15654     case INDIRECT_REF:
15655     case NEGATE_EXPR:
15656     case TRUTH_NOT_EXPR:
15657     case BIT_NOT_EXPR:
15658     case ADDR_EXPR:
15659     case UNARY_PLUS_EXPR:      /* Unary + */
15660     case ALIGNOF_EXPR:
15661     case AT_ENCODE_EXPR:
15662     case ARROW_EXPR:
15663     case THROW_EXPR:
15664     case TYPEID_EXPR:
15665     case REALPART_EXPR:
15666     case IMAGPART_EXPR:
15667     case PAREN_EXPR:
15668       {
15669 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15670 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15671 	r = build1 (code, type, op0);
15672 	if (code == ALIGNOF_EXPR)
15673 	  ALIGNOF_EXPR_STD_P (r) = ALIGNOF_EXPR_STD_P (t);
15674 	return r;
15675       }
15676 
15677     case COMPONENT_REF:
15678       {
15679 	tree object;
15680 	tree name;
15681 
15682 	object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15683 	name = TREE_OPERAND (t, 1);
15684 	if (TREE_CODE (name) == BIT_NOT_EXPR)
15685 	  {
15686 	    name = tsubst_copy (TREE_OPERAND (name, 0), args,
15687 				complain, in_decl);
15688 	    name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
15689 	  }
15690 	else if (TREE_CODE (name) == SCOPE_REF
15691 		 && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
15692 	  {
15693 	    tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
15694 				     complain, in_decl);
15695 	    name = TREE_OPERAND (name, 1);
15696 	    name = tsubst_copy (TREE_OPERAND (name, 0), args,
15697 				complain, in_decl);
15698 	    name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
15699 	    name = build_qualified_name (/*type=*/NULL_TREE,
15700 					 base, name,
15701 					 /*template_p=*/false);
15702 	  }
15703 	else if (BASELINK_P (name))
15704 	  name = tsubst_baselink (name,
15705 				  non_reference (TREE_TYPE (object)),
15706 				  args, complain,
15707 				  in_decl);
15708 	else
15709 	  name = tsubst_copy (name, args, complain, in_decl);
15710 	return build_nt (COMPONENT_REF, object, name, NULL_TREE);
15711       }
15712 
15713     case PLUS_EXPR:
15714     case MINUS_EXPR:
15715     case MULT_EXPR:
15716     case TRUNC_DIV_EXPR:
15717     case CEIL_DIV_EXPR:
15718     case FLOOR_DIV_EXPR:
15719     case ROUND_DIV_EXPR:
15720     case EXACT_DIV_EXPR:
15721     case BIT_AND_EXPR:
15722     case BIT_IOR_EXPR:
15723     case BIT_XOR_EXPR:
15724     case TRUNC_MOD_EXPR:
15725     case FLOOR_MOD_EXPR:
15726     case TRUTH_ANDIF_EXPR:
15727     case TRUTH_ORIF_EXPR:
15728     case TRUTH_AND_EXPR:
15729     case TRUTH_OR_EXPR:
15730     case RSHIFT_EXPR:
15731     case LSHIFT_EXPR:
15732     case RROTATE_EXPR:
15733     case LROTATE_EXPR:
15734     case EQ_EXPR:
15735     case NE_EXPR:
15736     case MAX_EXPR:
15737     case MIN_EXPR:
15738     case LE_EXPR:
15739     case GE_EXPR:
15740     case LT_EXPR:
15741     case GT_EXPR:
15742     case COMPOUND_EXPR:
15743     case DOTSTAR_EXPR:
15744     case MEMBER_REF:
15745     case PREDECREMENT_EXPR:
15746     case PREINCREMENT_EXPR:
15747     case POSTDECREMENT_EXPR:
15748     case POSTINCREMENT_EXPR:
15749       {
15750 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15751 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15752 	return build_nt (code, op0, op1);
15753       }
15754 
15755     case SCOPE_REF:
15756       {
15757 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15758 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15759 	return build_qualified_name (/*type=*/NULL_TREE, op0, op1,
15760 				     QUALIFIED_NAME_IS_TEMPLATE (t));
15761       }
15762 
15763     case ARRAY_REF:
15764       {
15765 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15766 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15767 	return build_nt (ARRAY_REF, op0, op1, NULL_TREE, NULL_TREE);
15768       }
15769 
15770     case CALL_EXPR:
15771       {
15772 	int n = VL_EXP_OPERAND_LENGTH (t);
15773 	tree result = build_vl_exp (CALL_EXPR, n);
15774 	int i;
15775 	for (i = 0; i < n; i++)
15776 	  TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
15777 					     complain, in_decl);
15778 	return result;
15779       }
15780 
15781     case COND_EXPR:
15782     case MODOP_EXPR:
15783     case PSEUDO_DTOR_EXPR:
15784     case VEC_PERM_EXPR:
15785       {
15786 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15787 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15788 	tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
15789 	r = build_nt (code, op0, op1, op2);
15790 	TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
15791 	return r;
15792       }
15793 
15794     case NEW_EXPR:
15795       {
15796 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15797 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15798 	tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
15799 	r = build_nt (code, op0, op1, op2);
15800 	NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
15801 	return r;
15802       }
15803 
15804     case DELETE_EXPR:
15805       {
15806 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15807 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15808 	r = build_nt (code, op0, op1);
15809 	DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
15810 	DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
15811 	return r;
15812       }
15813 
15814     case TEMPLATE_ID_EXPR:
15815       {
15816 	/* Substituted template arguments */
15817 	tree fn = TREE_OPERAND (t, 0);
15818 	tree targs = TREE_OPERAND (t, 1);
15819 
15820 	fn = tsubst_copy (fn, args, complain, in_decl);
15821 	if (targs)
15822 	  targs = tsubst_template_args (targs, args, complain, in_decl);
15823 
15824 	return lookup_template_function (fn, targs);
15825       }
15826 
15827     case TREE_LIST:
15828       {
15829 	tree purpose, value, chain;
15830 
15831 	if (t == void_list_node)
15832 	  return t;
15833 
15834 	purpose = TREE_PURPOSE (t);
15835 	if (purpose)
15836 	  purpose = tsubst_copy (purpose, args, complain, in_decl);
15837 	value = TREE_VALUE (t);
15838 	if (value)
15839 	  value = tsubst_copy (value, args, complain, in_decl);
15840 	chain = TREE_CHAIN (t);
15841 	if (chain && chain != void_type_node)
15842 	  chain = tsubst_copy (chain, args, complain, in_decl);
15843 	if (purpose == TREE_PURPOSE (t)
15844 	    && value == TREE_VALUE (t)
15845 	    && chain == TREE_CHAIN (t))
15846 	  return t;
15847 	return tree_cons (purpose, value, chain);
15848       }
15849 
15850     case RECORD_TYPE:
15851     case UNION_TYPE:
15852     case ENUMERAL_TYPE:
15853     case INTEGER_TYPE:
15854     case TEMPLATE_TYPE_PARM:
15855     case TEMPLATE_TEMPLATE_PARM:
15856     case BOUND_TEMPLATE_TEMPLATE_PARM:
15857     case TEMPLATE_PARM_INDEX:
15858     case POINTER_TYPE:
15859     case REFERENCE_TYPE:
15860     case OFFSET_TYPE:
15861     case FUNCTION_TYPE:
15862     case METHOD_TYPE:
15863     case ARRAY_TYPE:
15864     case TYPENAME_TYPE:
15865     case UNBOUND_CLASS_TEMPLATE:
15866     case TYPEOF_TYPE:
15867     case DECLTYPE_TYPE:
15868     case TYPE_DECL:
15869       return tsubst (t, args, complain, in_decl);
15870 
15871     case USING_DECL:
15872       t = DECL_NAME (t);
15873       /* Fall through.  */
15874     case IDENTIFIER_NODE:
15875       if (IDENTIFIER_CONV_OP_P (t))
15876 	{
15877 	  tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15878 	  return make_conv_op_name (new_type);
15879 	}
15880       else
15881 	return t;
15882 
15883     case CONSTRUCTOR:
15884       /* This is handled by tsubst_copy_and_build.  */
15885       gcc_unreachable ();
15886 
15887     case VA_ARG_EXPR:
15888       {
15889 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15890 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15891 	return build_x_va_arg (EXPR_LOCATION (t), op0, type);
15892       }
15893 
15894     case CLEANUP_POINT_EXPR:
15895       /* We shouldn't have built any of these during initial template
15896 	 generation.  Instead, they should be built during instantiation
15897 	 in response to the saved STMT_IS_FULL_EXPR_P setting.  */
15898       gcc_unreachable ();
15899 
15900     case OFFSET_REF:
15901       {
15902 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15903 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
15904 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
15905 	r = build2 (code, type, op0, op1);
15906 	PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
15907 	if (!mark_used (TREE_OPERAND (r, 1), complain)
15908 	    && !(complain & tf_error))
15909 	  return error_mark_node;
15910 	return r;
15911       }
15912 
15913     case EXPR_PACK_EXPANSION:
15914       error ("invalid use of pack expansion expression");
15915       return error_mark_node;
15916 
15917     case NONTYPE_ARGUMENT_PACK:
15918       error ("use %<...%> to expand argument pack");
15919       return error_mark_node;
15920 
15921     case VOID_CST:
15922       gcc_checking_assert (t == void_node && VOID_TYPE_P (TREE_TYPE (t)));
15923       return t;
15924 
15925     case INTEGER_CST:
15926     case REAL_CST:
15927     case STRING_CST:
15928     case COMPLEX_CST:
15929       {
15930 	/* Instantiate any typedefs in the type.  */
15931 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
15932 	r = fold_convert (type, t);
15933 	gcc_assert (TREE_CODE (r) == code);
15934 	return r;
15935       }
15936 
15937     case PTRMEM_CST:
15938       /* These can sometimes show up in a partial instantiation, but never
15939 	 involve template parms.  */
15940       gcc_assert (!uses_template_parms (t));
15941       return t;
15942 
15943     case UNARY_LEFT_FOLD_EXPR:
15944       return tsubst_unary_left_fold (t, args, complain, in_decl);
15945     case UNARY_RIGHT_FOLD_EXPR:
15946       return tsubst_unary_right_fold (t, args, complain, in_decl);
15947     case BINARY_LEFT_FOLD_EXPR:
15948       return tsubst_binary_left_fold (t, args, complain, in_decl);
15949     case BINARY_RIGHT_FOLD_EXPR:
15950       return tsubst_binary_right_fold (t, args, complain, in_decl);
15951     case PREDICT_EXPR:
15952       return t;
15953 
15954     case DEBUG_BEGIN_STMT:
15955       /* ??? There's no point in copying it for now, but maybe some
15956 	 day it will contain more information, such as a pointer back
15957 	 to the containing function, inlined copy or so.  */
15958       return t;
15959 
15960     default:
15961       /* We shouldn't get here, but keep going if !flag_checking.  */
15962       if (flag_checking)
15963 	gcc_unreachable ();
15964       return t;
15965     }
15966 }
15967 
15968 /* Helper function for tsubst_omp_clauses, used for instantiation of
15969    OMP_CLAUSE_DECL of clauses.  */
15970 
15971 static tree
tsubst_omp_clause_decl(tree decl,tree args,tsubst_flags_t complain,tree in_decl)15972 tsubst_omp_clause_decl (tree decl, tree args, tsubst_flags_t complain,
15973 			tree in_decl)
15974 {
15975   if (decl == NULL_TREE)
15976     return NULL_TREE;
15977 
15978   /* Handle an OpenMP array section represented as a TREE_LIST (or
15979      OMP_CLAUSE_DEPEND_KIND).  An OMP_CLAUSE_DEPEND (with a depend
15980      kind of OMP_CLAUSE_DEPEND_SINK) can also be represented as a
15981      TREE_LIST.  We can handle it exactly the same as an array section
15982      (purpose, value, and a chain), even though the nomenclature
15983      (low_bound, length, etc) is different.  */
15984   if (TREE_CODE (decl) == TREE_LIST)
15985     {
15986       tree low_bound
15987 	= tsubst_expr (TREE_PURPOSE (decl), args, complain, in_decl,
15988 		       /*integral_constant_expression_p=*/false);
15989       tree length = tsubst_expr (TREE_VALUE (decl), args, complain, in_decl,
15990 				 /*integral_constant_expression_p=*/false);
15991       tree chain = tsubst_omp_clause_decl (TREE_CHAIN (decl), args, complain,
15992 					   in_decl);
15993       if (TREE_PURPOSE (decl) == low_bound
15994 	  && TREE_VALUE (decl) == length
15995 	  && TREE_CHAIN (decl) == chain)
15996 	return decl;
15997       tree ret = tree_cons (low_bound, length, chain);
15998       OMP_CLAUSE_DEPEND_SINK_NEGATIVE (ret)
15999 	= OMP_CLAUSE_DEPEND_SINK_NEGATIVE (decl);
16000       return ret;
16001     }
16002   tree ret = tsubst_expr (decl, args, complain, in_decl,
16003 			  /*integral_constant_expression_p=*/false);
16004   /* Undo convert_from_reference tsubst_expr could have called.  */
16005   if (decl
16006       && REFERENCE_REF_P (ret)
16007       && !REFERENCE_REF_P (decl))
16008     ret = TREE_OPERAND (ret, 0);
16009   return ret;
16010 }
16011 
16012 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
16013 
16014 static tree
tsubst_omp_clauses(tree clauses,enum c_omp_region_type ort,tree args,tsubst_flags_t complain,tree in_decl)16015 tsubst_omp_clauses (tree clauses, enum c_omp_region_type ort,
16016 		    tree args, tsubst_flags_t complain, tree in_decl)
16017 {
16018   tree new_clauses = NULL_TREE, nc, oc;
16019   tree linear_no_step = NULL_TREE;
16020 
16021   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
16022     {
16023       nc = copy_node (oc);
16024       OMP_CLAUSE_CHAIN (nc) = new_clauses;
16025       new_clauses = nc;
16026 
16027       switch (OMP_CLAUSE_CODE (nc))
16028 	{
16029 	case OMP_CLAUSE_LASTPRIVATE:
16030 	  if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
16031 	    {
16032 	      OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
16033 	      tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
16034 			   in_decl, /*integral_constant_expression_p=*/false);
16035 	      OMP_CLAUSE_LASTPRIVATE_STMT (nc)
16036 		= pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
16037 	    }
16038 	  /* FALLTHRU */
16039 	case OMP_CLAUSE_PRIVATE:
16040 	case OMP_CLAUSE_SHARED:
16041 	case OMP_CLAUSE_FIRSTPRIVATE:
16042 	case OMP_CLAUSE_COPYIN:
16043 	case OMP_CLAUSE_COPYPRIVATE:
16044 	case OMP_CLAUSE_UNIFORM:
16045 	case OMP_CLAUSE_DEPEND:
16046 	case OMP_CLAUSE_FROM:
16047 	case OMP_CLAUSE_TO:
16048 	case OMP_CLAUSE_MAP:
16049 	case OMP_CLAUSE_USE_DEVICE_PTR:
16050 	case OMP_CLAUSE_IS_DEVICE_PTR:
16051 	  OMP_CLAUSE_DECL (nc)
16052 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
16053 				      in_decl);
16054 	  break;
16055 	case OMP_CLAUSE_TILE:
16056 	case OMP_CLAUSE_IF:
16057 	case OMP_CLAUSE_NUM_THREADS:
16058 	case OMP_CLAUSE_SCHEDULE:
16059 	case OMP_CLAUSE_COLLAPSE:
16060 	case OMP_CLAUSE_FINAL:
16061 	case OMP_CLAUSE_DEVICE:
16062 	case OMP_CLAUSE_DIST_SCHEDULE:
16063 	case OMP_CLAUSE_NUM_TEAMS:
16064 	case OMP_CLAUSE_THREAD_LIMIT:
16065 	case OMP_CLAUSE_SAFELEN:
16066 	case OMP_CLAUSE_SIMDLEN:
16067 	case OMP_CLAUSE_NUM_TASKS:
16068 	case OMP_CLAUSE_GRAINSIZE:
16069 	case OMP_CLAUSE_PRIORITY:
16070 	case OMP_CLAUSE_ORDERED:
16071 	case OMP_CLAUSE_HINT:
16072 	case OMP_CLAUSE_NUM_GANGS:
16073 	case OMP_CLAUSE_NUM_WORKERS:
16074 	case OMP_CLAUSE_VECTOR_LENGTH:
16075 	case OMP_CLAUSE_WORKER:
16076 	case OMP_CLAUSE_VECTOR:
16077 	case OMP_CLAUSE_ASYNC:
16078 	case OMP_CLAUSE_WAIT:
16079 	  OMP_CLAUSE_OPERAND (nc, 0)
16080 	    = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain,
16081 			   in_decl, /*integral_constant_expression_p=*/false);
16082 	  break;
16083 	case OMP_CLAUSE_REDUCTION:
16084 	  if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc))
16085 	    {
16086 	      tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc);
16087 	      if (TREE_CODE (placeholder) == SCOPE_REF)
16088 		{
16089 		  tree scope = tsubst (TREE_OPERAND (placeholder, 0), args,
16090 				       complain, in_decl);
16091 		  OMP_CLAUSE_REDUCTION_PLACEHOLDER (nc)
16092 		    = build_qualified_name (NULL_TREE, scope,
16093 					    TREE_OPERAND (placeholder, 1),
16094 					    false);
16095 		}
16096 	      else
16097 		gcc_assert (identifier_p (placeholder));
16098 	    }
16099 	  OMP_CLAUSE_DECL (nc)
16100 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
16101 				      in_decl);
16102 	  break;
16103 	case OMP_CLAUSE_GANG:
16104 	case OMP_CLAUSE_ALIGNED:
16105 	  OMP_CLAUSE_DECL (nc)
16106 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
16107 				      in_decl);
16108 	  OMP_CLAUSE_OPERAND (nc, 1)
16109 	    = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 1), args, complain,
16110 			   in_decl, /*integral_constant_expression_p=*/false);
16111 	  break;
16112 	case OMP_CLAUSE_LINEAR:
16113 	  OMP_CLAUSE_DECL (nc)
16114 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
16115 				      in_decl);
16116 	  if (OMP_CLAUSE_LINEAR_STEP (oc) == NULL_TREE)
16117 	    {
16118 	      gcc_assert (!linear_no_step);
16119 	      linear_no_step = nc;
16120 	    }
16121 	  else if (OMP_CLAUSE_LINEAR_VARIABLE_STRIDE (oc))
16122 	    OMP_CLAUSE_LINEAR_STEP (nc)
16123 	      = tsubst_omp_clause_decl (OMP_CLAUSE_LINEAR_STEP (oc), args,
16124 					complain, in_decl);
16125 	  else
16126 	    OMP_CLAUSE_LINEAR_STEP (nc)
16127 	      = tsubst_expr (OMP_CLAUSE_LINEAR_STEP (oc), args, complain,
16128 			     in_decl,
16129 			     /*integral_constant_expression_p=*/false);
16130 	  break;
16131 	case OMP_CLAUSE_NOWAIT:
16132 	case OMP_CLAUSE_DEFAULT:
16133 	case OMP_CLAUSE_UNTIED:
16134 	case OMP_CLAUSE_MERGEABLE:
16135 	case OMP_CLAUSE_INBRANCH:
16136 	case OMP_CLAUSE_NOTINBRANCH:
16137 	case OMP_CLAUSE_PROC_BIND:
16138 	case OMP_CLAUSE_FOR:
16139 	case OMP_CLAUSE_PARALLEL:
16140 	case OMP_CLAUSE_SECTIONS:
16141 	case OMP_CLAUSE_TASKGROUP:
16142 	case OMP_CLAUSE_NOGROUP:
16143 	case OMP_CLAUSE_THREADS:
16144 	case OMP_CLAUSE_SIMD:
16145 	case OMP_CLAUSE_DEFAULTMAP:
16146 	case OMP_CLAUSE_INDEPENDENT:
16147 	case OMP_CLAUSE_AUTO:
16148 	case OMP_CLAUSE_SEQ:
16149 	  break;
16150 	default:
16151 	  gcc_unreachable ();
16152 	}
16153       if ((ort & C_ORT_OMP_DECLARE_SIMD) == C_ORT_OMP)
16154 	switch (OMP_CLAUSE_CODE (nc))
16155 	  {
16156 	  case OMP_CLAUSE_SHARED:
16157 	  case OMP_CLAUSE_PRIVATE:
16158 	  case OMP_CLAUSE_FIRSTPRIVATE:
16159 	  case OMP_CLAUSE_LASTPRIVATE:
16160 	  case OMP_CLAUSE_COPYPRIVATE:
16161 	  case OMP_CLAUSE_LINEAR:
16162 	  case OMP_CLAUSE_REDUCTION:
16163 	  case OMP_CLAUSE_USE_DEVICE_PTR:
16164 	  case OMP_CLAUSE_IS_DEVICE_PTR:
16165 	    /* tsubst_expr on SCOPE_REF results in returning
16166 	       finish_non_static_data_member result.  Undo that here.  */
16167 	    if (TREE_CODE (OMP_CLAUSE_DECL (oc)) == SCOPE_REF
16168 		&& (TREE_CODE (TREE_OPERAND (OMP_CLAUSE_DECL (oc), 1))
16169 		    == IDENTIFIER_NODE))
16170 	      {
16171 		tree t = OMP_CLAUSE_DECL (nc);
16172 		tree v = t;
16173 		while (v)
16174 		  switch (TREE_CODE (v))
16175 		    {
16176 		    case COMPONENT_REF:
16177 		    case MEM_REF:
16178 		    case INDIRECT_REF:
16179 		    CASE_CONVERT:
16180 		    case POINTER_PLUS_EXPR:
16181 		      v = TREE_OPERAND (v, 0);
16182 		      continue;
16183 		    case PARM_DECL:
16184 		      if (DECL_CONTEXT (v) == current_function_decl
16185 			  && DECL_ARTIFICIAL (v)
16186 			  && DECL_NAME (v) == this_identifier)
16187 			OMP_CLAUSE_DECL (nc) = TREE_OPERAND (t, 1);
16188 		      /* FALLTHRU */
16189 		    default:
16190 		      v = NULL_TREE;
16191 		      break;
16192 		    }
16193 	      }
16194 	    else if (VAR_P (OMP_CLAUSE_DECL (oc))
16195 		     && DECL_HAS_VALUE_EXPR_P (OMP_CLAUSE_DECL (oc))
16196 		     && DECL_ARTIFICIAL (OMP_CLAUSE_DECL (oc))
16197 		     && DECL_LANG_SPECIFIC (OMP_CLAUSE_DECL (oc))
16198 		     && DECL_OMP_PRIVATIZED_MEMBER (OMP_CLAUSE_DECL (oc)))
16199 	      {
16200 		tree decl = OMP_CLAUSE_DECL (nc);
16201 		if (VAR_P (decl))
16202 		  {
16203 		    retrofit_lang_decl (decl);
16204 		    DECL_OMP_PRIVATIZED_MEMBER (decl) = 1;
16205 		  }
16206 	      }
16207 	    break;
16208 	  default:
16209 	    break;
16210 	  }
16211     }
16212 
16213   new_clauses = nreverse (new_clauses);
16214   if (ort != C_ORT_OMP_DECLARE_SIMD)
16215     {
16216       new_clauses = finish_omp_clauses (new_clauses, ort);
16217       if (linear_no_step)
16218 	for (nc = new_clauses; nc; nc = OMP_CLAUSE_CHAIN (nc))
16219 	  if (nc == linear_no_step)
16220 	    {
16221 	      OMP_CLAUSE_LINEAR_STEP (nc) = NULL_TREE;
16222 	      break;
16223 	    }
16224     }
16225   return new_clauses;
16226 }
16227 
16228 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
16229 
16230 static tree
tsubst_copy_asm_operands(tree t,tree args,tsubst_flags_t complain,tree in_decl)16231 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
16232 			  tree in_decl)
16233 {
16234 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
16235 
16236   tree purpose, value, chain;
16237 
16238   if (t == NULL)
16239     return t;
16240 
16241   if (TREE_CODE (t) != TREE_LIST)
16242     return tsubst_copy_and_build (t, args, complain, in_decl,
16243 				  /*function_p=*/false,
16244 				  /*integral_constant_expression_p=*/false);
16245 
16246   if (t == void_list_node)
16247     return t;
16248 
16249   purpose = TREE_PURPOSE (t);
16250   if (purpose)
16251     purpose = RECUR (purpose);
16252   value = TREE_VALUE (t);
16253   if (value)
16254     {
16255       if (TREE_CODE (value) != LABEL_DECL)
16256 	value = RECUR (value);
16257       else
16258 	{
16259 	  value = lookup_label (DECL_NAME (value));
16260 	  gcc_assert (TREE_CODE (value) == LABEL_DECL);
16261 	  TREE_USED (value) = 1;
16262 	}
16263     }
16264   chain = TREE_CHAIN (t);
16265   if (chain && chain != void_type_node)
16266     chain = RECUR (chain);
16267   return tree_cons (purpose, value, chain);
16268 #undef RECUR
16269 }
16270 
16271 /* Used to temporarily communicate the list of #pragma omp parallel
16272    clauses to #pragma omp for instantiation if they are combined
16273    together.  */
16274 
16275 static tree *omp_parallel_combined_clauses;
16276 
16277 /* Substitute one OMP_FOR iterator.  */
16278 
16279 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)16280 tsubst_omp_for_iterator (tree t, int i, tree declv, tree orig_declv,
16281 			 tree initv, tree condv, tree incrv, tree *clauses,
16282 			 tree args, tsubst_flags_t complain, tree in_decl,
16283 			 bool integral_constant_expression_p)
16284 {
16285 #define RECUR(NODE)				\
16286   tsubst_expr ((NODE), args, complain, in_decl,	\
16287 	       integral_constant_expression_p)
16288   tree decl, init, cond, incr;
16289 
16290   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
16291   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
16292 
16293   if (orig_declv && OMP_FOR_ORIG_DECLS (t))
16294     {
16295       tree o = TREE_VEC_ELT (OMP_FOR_ORIG_DECLS (t), i);
16296       TREE_VEC_ELT (orig_declv, i) = RECUR (o);
16297     }
16298 
16299   decl = TREE_OPERAND (init, 0);
16300   init = TREE_OPERAND (init, 1);
16301   tree decl_expr = NULL_TREE;
16302   if (init && TREE_CODE (init) == DECL_EXPR)
16303     {
16304       /* We need to jump through some hoops to handle declarations in the
16305 	 init-statement, since we might need to handle auto deduction,
16306 	 but we need to keep control of initialization.  */
16307       decl_expr = init;
16308       init = DECL_INITIAL (DECL_EXPR_DECL (init));
16309       decl = tsubst_decl (decl, args, complain);
16310     }
16311   else
16312     {
16313       if (TREE_CODE (decl) == SCOPE_REF)
16314 	{
16315 	  decl = RECUR (decl);
16316 	  if (TREE_CODE (decl) == COMPONENT_REF)
16317 	    {
16318 	      tree v = decl;
16319 	      while (v)
16320 		switch (TREE_CODE (v))
16321 		  {
16322 		  case COMPONENT_REF:
16323 		  case MEM_REF:
16324 		  case INDIRECT_REF:
16325 		  CASE_CONVERT:
16326 		  case POINTER_PLUS_EXPR:
16327 		    v = TREE_OPERAND (v, 0);
16328 		    continue;
16329 		  case PARM_DECL:
16330 		    if (DECL_CONTEXT (v) == current_function_decl
16331 			&& DECL_ARTIFICIAL (v)
16332 			&& DECL_NAME (v) == this_identifier)
16333 		      {
16334 			decl = TREE_OPERAND (decl, 1);
16335 			decl = omp_privatize_field (decl, false);
16336 		      }
16337 		    /* FALLTHRU */
16338 		  default:
16339 		    v = NULL_TREE;
16340 		    break;
16341 		  }
16342 	    }
16343 	}
16344       else
16345 	decl = RECUR (decl);
16346     }
16347   init = RECUR (init);
16348 
16349   tree auto_node = type_uses_auto (TREE_TYPE (decl));
16350   if (auto_node && init)
16351     TREE_TYPE (decl)
16352       = do_auto_deduction (TREE_TYPE (decl), init, auto_node, complain);
16353 
16354   gcc_assert (!type_dependent_expression_p (decl));
16355 
16356   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
16357     {
16358       if (decl_expr)
16359 	{
16360 	  /* Declare the variable, but don't let that initialize it.  */
16361 	  tree init_sav = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
16362 	  DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL_TREE;
16363 	  RECUR (decl_expr);
16364 	  DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init_sav;
16365 	}
16366 
16367       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
16368       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
16369       if (TREE_CODE (incr) == MODIFY_EXPR)
16370 	{
16371 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
16372 	  tree rhs = RECUR (TREE_OPERAND (incr, 1));
16373 	  incr = build_x_modify_expr (EXPR_LOCATION (incr), lhs,
16374 				      NOP_EXPR, rhs, complain);
16375 	}
16376       else
16377 	incr = RECUR (incr);
16378       TREE_VEC_ELT (declv, i) = decl;
16379       TREE_VEC_ELT (initv, i) = init;
16380       TREE_VEC_ELT (condv, i) = cond;
16381       TREE_VEC_ELT (incrv, i) = incr;
16382       return;
16383     }
16384 
16385   if (decl_expr)
16386     {
16387       /* Declare and initialize the variable.  */
16388       RECUR (decl_expr);
16389       init = NULL_TREE;
16390     }
16391   else if (init)
16392     {
16393       tree *pc;
16394       int j;
16395       for (j = (omp_parallel_combined_clauses == NULL ? 1 : 0); j < 2; j++)
16396 	{
16397 	  for (pc = j ? clauses : omp_parallel_combined_clauses; *pc; )
16398 	    {
16399 	      if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_PRIVATE
16400 		  && OMP_CLAUSE_DECL (*pc) == decl)
16401 		break;
16402 	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_LASTPRIVATE
16403 		       && OMP_CLAUSE_DECL (*pc) == decl)
16404 		{
16405 		  if (j)
16406 		    break;
16407 		  /* Move lastprivate (decl) clause to OMP_FOR_CLAUSES.  */
16408 		  tree c = *pc;
16409 		  *pc = OMP_CLAUSE_CHAIN (c);
16410 		  OMP_CLAUSE_CHAIN (c) = *clauses;
16411 		  *clauses = c;
16412 		}
16413 	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_FIRSTPRIVATE
16414 		       && OMP_CLAUSE_DECL (*pc) == decl)
16415 		{
16416 		  error ("iteration variable %qD should not be firstprivate",
16417 			 decl);
16418 		  *pc = OMP_CLAUSE_CHAIN (*pc);
16419 		}
16420 	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_REDUCTION
16421 		       && OMP_CLAUSE_DECL (*pc) == decl)
16422 		{
16423 		  error ("iteration variable %qD should not be reduction",
16424 			 decl);
16425 		  *pc = OMP_CLAUSE_CHAIN (*pc);
16426 		}
16427 	      else
16428 		pc = &OMP_CLAUSE_CHAIN (*pc);
16429 	    }
16430 	  if (*pc)
16431 	    break;
16432 	}
16433       if (*pc == NULL_TREE)
16434 	{
16435 	  tree c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
16436 	  OMP_CLAUSE_DECL (c) = decl;
16437 	  c = finish_omp_clauses (c, C_ORT_OMP);
16438 	  if (c)
16439 	    {
16440 	      OMP_CLAUSE_CHAIN (c) = *clauses;
16441 	      *clauses = c;
16442 	    }
16443 	}
16444     }
16445   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
16446   if (COMPARISON_CLASS_P (cond))
16447     {
16448       tree op0 = RECUR (TREE_OPERAND (cond, 0));
16449       tree op1 = RECUR (TREE_OPERAND (cond, 1));
16450       cond = build2 (TREE_CODE (cond), boolean_type_node, op0, op1);
16451     }
16452   else
16453     cond = RECUR (cond);
16454   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
16455   switch (TREE_CODE (incr))
16456     {
16457     case PREINCREMENT_EXPR:
16458     case PREDECREMENT_EXPR:
16459     case POSTINCREMENT_EXPR:
16460     case POSTDECREMENT_EXPR:
16461       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
16462 		     RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
16463       break;
16464     case MODIFY_EXPR:
16465       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
16466 	  || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
16467 	{
16468 	  tree rhs = TREE_OPERAND (incr, 1);
16469 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
16470 	  tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
16471 	  tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
16472 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
16473 			 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
16474 				 rhs0, rhs1));
16475 	}
16476       else
16477 	incr = RECUR (incr);
16478       break;
16479     case MODOP_EXPR:
16480       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
16481 	  || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
16482 	{
16483 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
16484 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
16485 			 build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
16486 				 TREE_TYPE (decl), lhs,
16487 				 RECUR (TREE_OPERAND (incr, 2))));
16488 	}
16489       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
16490 	       && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
16491 		   || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
16492 	{
16493 	  tree rhs = TREE_OPERAND (incr, 2);
16494 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
16495 	  tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
16496 	  tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
16497 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
16498 			 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
16499 				 rhs0, rhs1));
16500 	}
16501       else
16502 	incr = RECUR (incr);
16503       break;
16504     default:
16505       incr = RECUR (incr);
16506       break;
16507     }
16508 
16509   TREE_VEC_ELT (declv, i) = decl;
16510   TREE_VEC_ELT (initv, i) = init;
16511   TREE_VEC_ELT (condv, i) = cond;
16512   TREE_VEC_ELT (incrv, i) = incr;
16513 #undef RECUR
16514 }
16515 
16516 /* Helper function of tsubst_expr, find OMP_TEAMS inside
16517    of OMP_TARGET's body.  */
16518 
16519 static tree
tsubst_find_omp_teams(tree * tp,int * walk_subtrees,void *)16520 tsubst_find_omp_teams (tree *tp, int *walk_subtrees, void *)
16521 {
16522   *walk_subtrees = 0;
16523   switch (TREE_CODE (*tp))
16524     {
16525     case OMP_TEAMS:
16526       return *tp;
16527     case BIND_EXPR:
16528     case STATEMENT_LIST:
16529       *walk_subtrees = 1;
16530       break;
16531     default:
16532       break;
16533     }
16534   return NULL_TREE;
16535 }
16536 
16537 /* Helper function for tsubst_expr.  For decomposition declaration
16538    artificial base DECL, which is tsubsted PATTERN_DECL, tsubst
16539    also the corresponding decls representing the identifiers
16540    of the decomposition declaration.  Return DECL if successful
16541    or error_mark_node otherwise, set *FIRST to the first decl
16542    in the list chained through DECL_CHAIN and *CNT to the number
16543    of such decls.  */
16544 
16545 static tree
tsubst_decomp_names(tree decl,tree pattern_decl,tree args,tsubst_flags_t complain,tree in_decl,tree * first,unsigned int * cnt)16546 tsubst_decomp_names (tree decl, tree pattern_decl, tree args,
16547 		     tsubst_flags_t complain, tree in_decl, tree *first,
16548 		     unsigned int *cnt)
16549 {
16550   tree decl2, decl3, prev = decl;
16551   *cnt = 0;
16552   gcc_assert (DECL_NAME (decl) == NULL_TREE);
16553   for (decl2 = DECL_CHAIN (pattern_decl);
16554        decl2
16555        && VAR_P (decl2)
16556        && DECL_DECOMPOSITION_P (decl2)
16557        && DECL_NAME (decl2);
16558        decl2 = DECL_CHAIN (decl2))
16559     {
16560       if (TREE_TYPE (decl2) == error_mark_node && *cnt == 0)
16561 	{
16562 	  gcc_assert (errorcount);
16563 	  return error_mark_node;
16564 	}
16565       (*cnt)++;
16566       gcc_assert (DECL_DECOMP_BASE (decl2) == pattern_decl);
16567       gcc_assert (DECL_HAS_VALUE_EXPR_P (decl2));
16568       tree v = DECL_VALUE_EXPR (decl2);
16569       DECL_HAS_VALUE_EXPR_P (decl2) = 0;
16570       SET_DECL_VALUE_EXPR (decl2, NULL_TREE);
16571       decl3 = tsubst (decl2, args, complain, in_decl);
16572       SET_DECL_VALUE_EXPR (decl2, v);
16573       DECL_HAS_VALUE_EXPR_P (decl2) = 1;
16574       if (VAR_P (decl3))
16575 	DECL_TEMPLATE_INSTANTIATED (decl3) = 1;
16576       else
16577 	{
16578 	  gcc_assert (errorcount);
16579 	  decl = error_mark_node;
16580 	  continue;
16581 	}
16582       maybe_push_decl (decl3);
16583       if (error_operand_p (decl3))
16584 	decl = error_mark_node;
16585       else if (decl != error_mark_node
16586 	       && DECL_CHAIN (decl3) != prev
16587 	       && decl != prev)
16588 	{
16589 	  gcc_assert (errorcount);
16590 	  decl = error_mark_node;
16591 	}
16592       else
16593 	prev = decl3;
16594     }
16595   *first = prev;
16596   return decl;
16597 }
16598 
16599 /* Like tsubst_copy for expressions, etc. but also does semantic
16600    processing.  */
16601 
16602 tree
tsubst_expr(tree t,tree args,tsubst_flags_t complain,tree in_decl,bool integral_constant_expression_p)16603 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
16604 	     bool integral_constant_expression_p)
16605 {
16606 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
16607 #define RECUR(NODE)				\
16608   tsubst_expr ((NODE), args, complain, in_decl,	\
16609 	       integral_constant_expression_p)
16610 
16611   tree stmt, tmp;
16612   tree r;
16613   location_t loc;
16614 
16615   if (t == NULL_TREE || t == error_mark_node)
16616     return t;
16617 
16618   loc = input_location;
16619   if (EXPR_HAS_LOCATION (t))
16620     input_location = EXPR_LOCATION (t);
16621   if (STATEMENT_CODE_P (TREE_CODE (t)))
16622     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
16623 
16624   switch (TREE_CODE (t))
16625     {
16626     case STATEMENT_LIST:
16627       {
16628 	tree_stmt_iterator i;
16629 	for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
16630 	  RECUR (tsi_stmt (i));
16631 	break;
16632       }
16633 
16634     case CTOR_INITIALIZER:
16635       finish_mem_initializers (tsubst_initializer_list
16636 			       (TREE_OPERAND (t, 0), args));
16637       break;
16638 
16639     case RETURN_EXPR:
16640       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
16641       break;
16642 
16643     case EXPR_STMT:
16644       tmp = RECUR (EXPR_STMT_EXPR (t));
16645       if (EXPR_STMT_STMT_EXPR_RESULT (t))
16646 	finish_stmt_expr_expr (tmp, cur_stmt_expr);
16647       else
16648 	finish_expr_stmt (tmp);
16649       break;
16650 
16651     case USING_STMT:
16652       finish_local_using_directive (USING_STMT_NAMESPACE (t),
16653 				    /*attribs=*/NULL_TREE);
16654       break;
16655 
16656     case DECL_EXPR:
16657       {
16658 	tree decl, pattern_decl;
16659 	tree init;
16660 
16661 	pattern_decl = decl = DECL_EXPR_DECL (t);
16662 	if (TREE_CODE (decl) == LABEL_DECL)
16663 	  finish_label_decl (DECL_NAME (decl));
16664 	else if (TREE_CODE (decl) == USING_DECL)
16665 	  {
16666 	    tree scope = USING_DECL_SCOPE (decl);
16667 	    tree name = DECL_NAME (decl);
16668 
16669 	    scope = tsubst (scope, args, complain, in_decl);
16670 	    decl = lookup_qualified_name (scope, name,
16671 					  /*is_type_p=*/false,
16672 					  /*complain=*/false);
16673 	    if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
16674 	      qualified_name_lookup_error (scope, name, decl, input_location);
16675 	    else
16676 	      finish_local_using_decl (decl, scope, name);
16677 	  }
16678 	else if (is_capture_proxy (decl)
16679 		 && !DECL_TEMPLATE_INSTANTIATION (current_function_decl))
16680 	  {
16681 	    /* We're in tsubst_lambda_expr, we've already inserted a new
16682 	       capture proxy, so look it up and register it.  */
16683 	    tree inst;
16684 	    if (DECL_PACK_P (decl))
16685 	      {
16686 		inst = (retrieve_local_specialization
16687 			(DECL_CAPTURED_VARIABLE (decl)));
16688 		gcc_assert (TREE_CODE (inst) == NONTYPE_ARGUMENT_PACK);
16689 	      }
16690 	    else
16691 	      {
16692 		inst = lookup_name_real (DECL_NAME (decl), 0, 0,
16693 					 /*block_p=*/true, 0, LOOKUP_HIDDEN);
16694 		gcc_assert (inst != decl && is_capture_proxy (inst));
16695 	      }
16696 	    register_local_specialization (inst, decl);
16697 	    break;
16698 	  }
16699 	else if (DECL_IMPLICIT_TYPEDEF_P (decl)
16700 		 && LAMBDA_TYPE_P (TREE_TYPE (decl)))
16701 	  /* Don't copy the old closure; we'll create a new one in
16702 	     tsubst_lambda_expr.  */
16703 	  break;
16704 	else
16705 	  {
16706 	    init = DECL_INITIAL (decl);
16707 	    decl = tsubst (decl, args, complain, in_decl);
16708 	    if (decl != error_mark_node)
16709 	      {
16710 		/* By marking the declaration as instantiated, we avoid
16711 		   trying to instantiate it.  Since instantiate_decl can't
16712 		   handle local variables, and since we've already done
16713 		   all that needs to be done, that's the right thing to
16714 		   do.  */
16715 		if (VAR_P (decl))
16716 		  DECL_TEMPLATE_INSTANTIATED (decl) = 1;
16717 		if (VAR_P (decl) && !DECL_NAME (decl)
16718 		    && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
16719 		  /* Anonymous aggregates are a special case.  */
16720 		  finish_anon_union (decl);
16721 		else if (is_capture_proxy (DECL_EXPR_DECL (t)))
16722 		  {
16723 		    DECL_CONTEXT (decl) = current_function_decl;
16724 		    if (DECL_NAME (decl) == this_identifier)
16725 		      {
16726 			tree lam = DECL_CONTEXT (current_function_decl);
16727 			lam = CLASSTYPE_LAMBDA_EXPR (lam);
16728 			LAMBDA_EXPR_THIS_CAPTURE (lam) = decl;
16729 		      }
16730 		    insert_capture_proxy (decl);
16731 		  }
16732 		else if (DECL_IMPLICIT_TYPEDEF_P (t))
16733 		  /* We already did a pushtag.  */;
16734 		else if (TREE_CODE (decl) == FUNCTION_DECL
16735 			 && DECL_OMP_DECLARE_REDUCTION_P (decl)
16736 			 && DECL_FUNCTION_SCOPE_P (pattern_decl))
16737 		  {
16738 		    DECL_CONTEXT (decl) = NULL_TREE;
16739 		    pushdecl (decl);
16740 		    DECL_CONTEXT (decl) = current_function_decl;
16741 		    cp_check_omp_declare_reduction (decl);
16742 		  }
16743 		else
16744 		  {
16745 		    int const_init = false;
16746 		    unsigned int cnt = 0;
16747 		    tree first = NULL_TREE, ndecl = error_mark_node;
16748 		    maybe_push_decl (decl);
16749 
16750 		    if (VAR_P (decl)
16751 			&& DECL_DECOMPOSITION_P (decl)
16752 			&& TREE_TYPE (pattern_decl) != error_mark_node)
16753 		      ndecl = tsubst_decomp_names (decl, pattern_decl, args,
16754 						   complain, in_decl, &first,
16755 						   &cnt);
16756 
16757 		    if (VAR_P (decl)
16758 			&& DECL_PRETTY_FUNCTION_P (decl))
16759 		      {
16760 			/* For __PRETTY_FUNCTION__ we have to adjust the
16761 			   initializer.  */
16762 			const char *const name
16763 			  = cxx_printable_name (current_function_decl, 2);
16764 			init = cp_fname_init (name, &TREE_TYPE (decl));
16765 		      }
16766 		    else
16767 		      init = tsubst_init (init, decl, args, complain, in_decl);
16768 
16769 		    if (VAR_P (decl))
16770 		      const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
16771 				    (pattern_decl));
16772 
16773 		    if (ndecl != error_mark_node)
16774 		      cp_maybe_mangle_decomp (ndecl, first, cnt);
16775 
16776 		    cp_finish_decl (decl, init, const_init, NULL_TREE, 0);
16777 
16778 		    if (ndecl != error_mark_node)
16779 		      cp_finish_decomp (ndecl, first, cnt);
16780 		  }
16781 	      }
16782 	  }
16783 
16784 	break;
16785       }
16786 
16787     case FOR_STMT:
16788       stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
16789       RECUR (FOR_INIT_STMT (t));
16790       finish_init_stmt (stmt);
16791       tmp = RECUR (FOR_COND (t));
16792       finish_for_cond (tmp, stmt, false, 0);
16793       tmp = RECUR (FOR_EXPR (t));
16794       finish_for_expr (tmp, stmt);
16795       {
16796 	bool prev = note_iteration_stmt_body_start ();
16797 	RECUR (FOR_BODY (t));
16798 	note_iteration_stmt_body_end (prev);
16799       }
16800       finish_for_stmt (stmt);
16801       break;
16802 
16803     case RANGE_FOR_STMT:
16804       {
16805 	/* Construct another range_for, if this is not a final
16806 	   substitution (for inside inside a generic lambda of a
16807 	   template).  Otherwise convert to a regular for.  */
16808         tree decl, expr;
16809         stmt = (processing_template_decl
16810 		? begin_range_for_stmt (NULL_TREE, NULL_TREE)
16811 		: begin_for_stmt (NULL_TREE, NULL_TREE));
16812         decl = RANGE_FOR_DECL (t);
16813         decl = tsubst (decl, args, complain, in_decl);
16814         maybe_push_decl (decl);
16815         expr = RECUR (RANGE_FOR_EXPR (t));
16816 
16817 	tree decomp_first = NULL_TREE;
16818 	unsigned decomp_cnt = 0;
16819 	if (VAR_P (decl) && DECL_DECOMPOSITION_P (decl))
16820 	  decl = tsubst_decomp_names (decl, RANGE_FOR_DECL (t), args,
16821 				      complain, in_decl,
16822 				      &decomp_first, &decomp_cnt);
16823 
16824 	if (processing_template_decl)
16825 	  {
16826 	    RANGE_FOR_IVDEP (stmt) = RANGE_FOR_IVDEP (t);
16827 	    RANGE_FOR_UNROLL (stmt) = RANGE_FOR_UNROLL (t);
16828 	    finish_range_for_decl (stmt, decl, expr);
16829 	    if (decomp_first && decl != error_mark_node)
16830 	      cp_finish_decomp (decl, decomp_first, decomp_cnt);
16831 	  }
16832 	else
16833 	  {
16834 	    unsigned short unroll = (RANGE_FOR_UNROLL (t)
16835 				     ? tree_to_uhwi (RANGE_FOR_UNROLL (t)) : 0);
16836 	    stmt = cp_convert_range_for (stmt, decl, expr,
16837 					 decomp_first, decomp_cnt,
16838 					 RANGE_FOR_IVDEP (t), unroll);
16839 	  }
16840 
16841 	bool prev = note_iteration_stmt_body_start ();
16842         RECUR (RANGE_FOR_BODY (t));
16843 	note_iteration_stmt_body_end (prev);
16844         finish_for_stmt (stmt);
16845       }
16846       break;
16847 
16848     case WHILE_STMT:
16849       stmt = begin_while_stmt ();
16850       tmp = RECUR (WHILE_COND (t));
16851       finish_while_stmt_cond (tmp, stmt, false, 0);
16852       {
16853 	bool prev = note_iteration_stmt_body_start ();
16854 	RECUR (WHILE_BODY (t));
16855 	note_iteration_stmt_body_end (prev);
16856       }
16857       finish_while_stmt (stmt);
16858       break;
16859 
16860     case DO_STMT:
16861       stmt = begin_do_stmt ();
16862       {
16863 	bool prev = note_iteration_stmt_body_start ();
16864 	RECUR (DO_BODY (t));
16865 	note_iteration_stmt_body_end (prev);
16866       }
16867       finish_do_body (stmt);
16868       tmp = RECUR (DO_COND (t));
16869       finish_do_stmt (tmp, stmt, false, 0);
16870       break;
16871 
16872     case IF_STMT:
16873       stmt = begin_if_stmt ();
16874       IF_STMT_CONSTEXPR_P (stmt) = IF_STMT_CONSTEXPR_P (t);
16875       if (IF_STMT_CONSTEXPR_P (t))
16876 	args = add_extra_args (IF_STMT_EXTRA_ARGS (t), args);
16877       tmp = RECUR (IF_COND (t));
16878       tmp = finish_if_stmt_cond (tmp, stmt);
16879       if (IF_STMT_CONSTEXPR_P (t)
16880 	  && instantiation_dependent_expression_p (tmp))
16881 	{
16882 	  /* We're partially instantiating a generic lambda, but the condition
16883 	     of the constexpr if is still dependent.  Don't substitute into the
16884 	     branches now, just remember the template arguments.  */
16885 	  do_poplevel (IF_SCOPE (stmt));
16886 	  IF_COND (stmt) = IF_COND (t);
16887 	  THEN_CLAUSE (stmt) = THEN_CLAUSE (t);
16888 	  ELSE_CLAUSE (stmt) = ELSE_CLAUSE (t);
16889 	  IF_STMT_EXTRA_ARGS (stmt) = build_extra_args (t, args, complain);
16890 	  add_stmt (stmt);
16891 	  break;
16892 	}
16893       if (IF_STMT_CONSTEXPR_P (t) && integer_zerop (tmp))
16894 	/* Don't instantiate the THEN_CLAUSE. */;
16895       else
16896 	{
16897 	  bool inhibit = integer_zerop (fold_non_dependent_expr (tmp));
16898 	  if (inhibit)
16899 	    ++c_inhibit_evaluation_warnings;
16900 	  RECUR (THEN_CLAUSE (t));
16901 	  if (inhibit)
16902 	    --c_inhibit_evaluation_warnings;
16903 	}
16904       finish_then_clause (stmt);
16905 
16906       if (IF_STMT_CONSTEXPR_P (t) && integer_nonzerop (tmp))
16907 	/* Don't instantiate the ELSE_CLAUSE. */;
16908       else if (ELSE_CLAUSE (t))
16909 	{
16910 	  bool inhibit = integer_nonzerop (fold_non_dependent_expr (tmp));
16911 	  begin_else_clause (stmt);
16912 	  if (inhibit)
16913 	    ++c_inhibit_evaluation_warnings;
16914 	  RECUR (ELSE_CLAUSE (t));
16915 	  if (inhibit)
16916 	    --c_inhibit_evaluation_warnings;
16917 	  finish_else_clause (stmt);
16918 	}
16919 
16920       finish_if_stmt (stmt);
16921       break;
16922 
16923     case BIND_EXPR:
16924       if (BIND_EXPR_BODY_BLOCK (t))
16925 	stmt = begin_function_body ();
16926       else
16927 	stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
16928 				    ? BCS_TRY_BLOCK : 0);
16929 
16930       RECUR (BIND_EXPR_BODY (t));
16931 
16932       if (BIND_EXPR_BODY_BLOCK (t))
16933 	finish_function_body (stmt);
16934       else
16935 	finish_compound_stmt (stmt);
16936       break;
16937 
16938     case BREAK_STMT:
16939       finish_break_stmt ();
16940       break;
16941 
16942     case CONTINUE_STMT:
16943       finish_continue_stmt ();
16944       break;
16945 
16946     case SWITCH_STMT:
16947       stmt = begin_switch_stmt ();
16948       tmp = RECUR (SWITCH_STMT_COND (t));
16949       finish_switch_cond (tmp, stmt);
16950       RECUR (SWITCH_STMT_BODY (t));
16951       finish_switch_stmt (stmt);
16952       break;
16953 
16954     case CASE_LABEL_EXPR:
16955       {
16956 	tree low = RECUR (CASE_LOW (t));
16957 	tree high = RECUR (CASE_HIGH (t));
16958 	tree l = finish_case_label (EXPR_LOCATION (t), low, high);
16959 	if (l && TREE_CODE (l) == CASE_LABEL_EXPR)
16960 	  FALLTHROUGH_LABEL_P (CASE_LABEL (l))
16961 	    = FALLTHROUGH_LABEL_P (CASE_LABEL (t));
16962       }
16963       break;
16964 
16965     case LABEL_EXPR:
16966       {
16967 	tree decl = LABEL_EXPR_LABEL (t);
16968 	tree label;
16969 
16970 	label = finish_label_stmt (DECL_NAME (decl));
16971 	if (TREE_CODE (label) == LABEL_DECL)
16972 	  FALLTHROUGH_LABEL_P (label) = FALLTHROUGH_LABEL_P (decl);
16973 	if (DECL_ATTRIBUTES (decl) != NULL_TREE)
16974 	  cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
16975       }
16976       break;
16977 
16978     case GOTO_EXPR:
16979       tmp = GOTO_DESTINATION (t);
16980       if (TREE_CODE (tmp) != LABEL_DECL)
16981 	/* Computed goto's must be tsubst'd into.  On the other hand,
16982 	   non-computed gotos must not be; the identifier in question
16983 	   will have no binding.  */
16984 	tmp = RECUR (tmp);
16985       else
16986 	tmp = DECL_NAME (tmp);
16987       finish_goto_stmt (tmp);
16988       break;
16989 
16990     case ASM_EXPR:
16991       {
16992 	tree string = RECUR (ASM_STRING (t));
16993 	tree outputs = tsubst_copy_asm_operands (ASM_OUTPUTS (t), args,
16994 						 complain, in_decl);
16995 	tree inputs = tsubst_copy_asm_operands (ASM_INPUTS (t), args,
16996 						complain, in_decl);
16997 	tree clobbers = tsubst_copy_asm_operands (ASM_CLOBBERS (t), args,
16998 	 					  complain, in_decl);
16999 	tree labels = tsubst_copy_asm_operands (ASM_LABELS (t), args,
17000 						complain, in_decl);
17001 	tmp = finish_asm_stmt (ASM_VOLATILE_P (t), string, outputs, inputs,
17002 			       clobbers, labels, ASM_INLINE_P (t));
17003 	tree asm_expr = tmp;
17004 	if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
17005 	  asm_expr = TREE_OPERAND (asm_expr, 0);
17006 	ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
17007       }
17008       break;
17009 
17010     case TRY_BLOCK:
17011       if (CLEANUP_P (t))
17012 	{
17013 	  stmt = begin_try_block ();
17014 	  RECUR (TRY_STMTS (t));
17015 	  finish_cleanup_try_block (stmt);
17016 	  finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
17017 	}
17018       else
17019 	{
17020 	  tree compound_stmt = NULL_TREE;
17021 
17022 	  if (FN_TRY_BLOCK_P (t))
17023 	    stmt = begin_function_try_block (&compound_stmt);
17024 	  else
17025 	    stmt = begin_try_block ();
17026 
17027 	  RECUR (TRY_STMTS (t));
17028 
17029 	  if (FN_TRY_BLOCK_P (t))
17030 	    finish_function_try_block (stmt);
17031 	  else
17032 	    finish_try_block (stmt);
17033 
17034 	  RECUR (TRY_HANDLERS (t));
17035 	  if (FN_TRY_BLOCK_P (t))
17036 	    finish_function_handler_sequence (stmt, compound_stmt);
17037 	  else
17038 	    finish_handler_sequence (stmt);
17039 	}
17040       break;
17041 
17042     case HANDLER:
17043       {
17044 	tree decl = HANDLER_PARMS (t);
17045 
17046 	if (decl)
17047 	  {
17048 	    decl = tsubst (decl, args, complain, in_decl);
17049 	    /* Prevent instantiate_decl from trying to instantiate
17050 	       this variable.  We've already done all that needs to be
17051 	       done.  */
17052 	    if (decl != error_mark_node)
17053 	      DECL_TEMPLATE_INSTANTIATED (decl) = 1;
17054 	  }
17055 	stmt = begin_handler ();
17056 	finish_handler_parms (decl, stmt);
17057 	RECUR (HANDLER_BODY (t));
17058 	finish_handler (stmt);
17059       }
17060       break;
17061 
17062     case TAG_DEFN:
17063       tmp = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
17064       if (CLASS_TYPE_P (tmp))
17065 	{
17066 	  /* Local classes are not independent templates; they are
17067 	     instantiated along with their containing function.  And this
17068 	     way we don't have to deal with pushing out of one local class
17069 	     to instantiate a member of another local class.  */
17070 	  /* Closures are handled by the LAMBDA_EXPR.  */
17071 	  gcc_assert (!LAMBDA_TYPE_P (TREE_TYPE (t)));
17072 	  complete_type (tmp);
17073 	  for (tree fld = TYPE_FIELDS (tmp); fld; fld = DECL_CHAIN (fld))
17074 	    if ((VAR_P (fld)
17075 		 || (TREE_CODE (fld) == FUNCTION_DECL
17076 		     && !DECL_ARTIFICIAL (fld)))
17077 		&& DECL_TEMPLATE_INSTANTIATION (fld))
17078 	      instantiate_decl (fld, /*defer_ok=*/false,
17079 				/*expl_inst_class=*/false);
17080 	}
17081       break;
17082 
17083     case STATIC_ASSERT:
17084       {
17085 	tree condition;
17086 
17087 	++c_inhibit_evaluation_warnings;
17088         condition =
17089           tsubst_expr (STATIC_ASSERT_CONDITION (t),
17090                        args,
17091                        complain, in_decl,
17092                        /*integral_constant_expression_p=*/true);
17093 	--c_inhibit_evaluation_warnings;
17094 
17095         finish_static_assert (condition,
17096                               STATIC_ASSERT_MESSAGE (t),
17097                               STATIC_ASSERT_SOURCE_LOCATION (t),
17098                               /*member_p=*/false);
17099       }
17100       break;
17101 
17102     case OACC_KERNELS:
17103     case OACC_PARALLEL:
17104       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_ACC, args, complain,
17105 				in_decl);
17106       stmt = begin_omp_parallel ();
17107       RECUR (OMP_BODY (t));
17108       finish_omp_construct (TREE_CODE (t), stmt, tmp);
17109       break;
17110 
17111     case OMP_PARALLEL:
17112       r = push_omp_privatization_clauses (OMP_PARALLEL_COMBINED (t));
17113       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t), C_ORT_OMP, args,
17114 				complain, in_decl);
17115       if (OMP_PARALLEL_COMBINED (t))
17116 	omp_parallel_combined_clauses = &tmp;
17117       stmt = begin_omp_parallel ();
17118       RECUR (OMP_PARALLEL_BODY (t));
17119       gcc_assert (omp_parallel_combined_clauses == NULL);
17120       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
17121 	= OMP_PARALLEL_COMBINED (t);
17122       pop_omp_privatization_clauses (r);
17123       break;
17124 
17125     case OMP_TASK:
17126       r = push_omp_privatization_clauses (false);
17127       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), C_ORT_OMP, args,
17128 				complain, in_decl);
17129       stmt = begin_omp_task ();
17130       RECUR (OMP_TASK_BODY (t));
17131       finish_omp_task (tmp, stmt);
17132       pop_omp_privatization_clauses (r);
17133       break;
17134 
17135     case OMP_FOR:
17136     case OMP_SIMD:
17137     case OMP_DISTRIBUTE:
17138     case OMP_TASKLOOP:
17139     case OACC_LOOP:
17140       {
17141 	tree clauses, body, pre_body;
17142 	tree declv = NULL_TREE, initv = NULL_TREE, condv = NULL_TREE;
17143 	tree orig_declv = NULL_TREE;
17144 	tree incrv = NULL_TREE;
17145 	enum c_omp_region_type ort = C_ORT_OMP;
17146 	int i;
17147 
17148 	if (TREE_CODE (t) == OACC_LOOP)
17149 	  ort = C_ORT_ACC;
17150 
17151 	r = push_omp_privatization_clauses (OMP_FOR_INIT (t) == NULL_TREE);
17152 	clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t), ort, args, complain,
17153 				      in_decl);
17154 	if (OMP_FOR_INIT (t) != NULL_TREE)
17155 	  {
17156 	    declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
17157 	    if (OMP_FOR_ORIG_DECLS (t))
17158 	      orig_declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
17159 	    initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
17160 	    condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
17161 	    incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
17162 	  }
17163 
17164 	stmt = begin_omp_structured_block ();
17165 
17166 	pre_body = push_stmt_list ();
17167 	RECUR (OMP_FOR_PRE_BODY (t));
17168 	pre_body = pop_stmt_list (pre_body);
17169 
17170 	if (OMP_FOR_INIT (t) != NULL_TREE)
17171 	  for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
17172 	    tsubst_omp_for_iterator (t, i, declv, orig_declv, initv, condv,
17173 				     incrv, &clauses, args, complain, in_decl,
17174 				     integral_constant_expression_p);
17175 	omp_parallel_combined_clauses = NULL;
17176 
17177 	body = push_stmt_list ();
17178 	RECUR (OMP_FOR_BODY (t));
17179 	body = pop_stmt_list (body);
17180 
17181 	if (OMP_FOR_INIT (t) != NULL_TREE)
17182 	  t = finish_omp_for (EXPR_LOCATION (t), TREE_CODE (t), declv,
17183 			      orig_declv, initv, condv, incrv, body, pre_body,
17184 			      NULL, clauses);
17185 	else
17186 	  {
17187 	    t = make_node (TREE_CODE (t));
17188 	    TREE_TYPE (t) = void_type_node;
17189 	    OMP_FOR_BODY (t) = body;
17190 	    OMP_FOR_PRE_BODY (t) = pre_body;
17191 	    OMP_FOR_CLAUSES (t) = clauses;
17192 	    SET_EXPR_LOCATION (t, EXPR_LOCATION (t));
17193 	    add_stmt (t);
17194 	  }
17195 
17196 	add_stmt (finish_omp_structured_block (stmt));
17197 	pop_omp_privatization_clauses (r);
17198       }
17199       break;
17200 
17201     case OMP_SECTIONS:
17202       omp_parallel_combined_clauses = NULL;
17203       /* FALLTHRU */
17204     case OMP_SINGLE:
17205     case OMP_TEAMS:
17206     case OMP_CRITICAL:
17207       r = push_omp_privatization_clauses (TREE_CODE (t) == OMP_TEAMS
17208 					  && OMP_TEAMS_COMBINED (t));
17209       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), C_ORT_OMP, args, complain,
17210 				in_decl);
17211       stmt = push_stmt_list ();
17212       RECUR (OMP_BODY (t));
17213       stmt = pop_stmt_list (stmt);
17214 
17215       t = copy_node (t);
17216       OMP_BODY (t) = stmt;
17217       OMP_CLAUSES (t) = tmp;
17218       add_stmt (t);
17219       pop_omp_privatization_clauses (r);
17220       break;
17221 
17222     case OACC_DATA:
17223     case OMP_TARGET_DATA:
17224     case OMP_TARGET:
17225       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), (TREE_CODE (t) == OACC_DATA)
17226 				? C_ORT_ACC : C_ORT_OMP, args, complain,
17227 				in_decl);
17228       keep_next_level (true);
17229       stmt = begin_omp_structured_block ();
17230 
17231       RECUR (OMP_BODY (t));
17232       stmt = finish_omp_structured_block (stmt);
17233 
17234       t = copy_node (t);
17235       OMP_BODY (t) = stmt;
17236       OMP_CLAUSES (t) = tmp;
17237       if (TREE_CODE (t) == OMP_TARGET && OMP_TARGET_COMBINED (t))
17238 	{
17239 	  tree teams = cp_walk_tree (&stmt, tsubst_find_omp_teams, NULL, NULL);
17240 	  if (teams)
17241 	    {
17242 	      /* For combined target teams, ensure the num_teams and
17243 		 thread_limit clause expressions are evaluated on the host,
17244 		 before entering the target construct.  */
17245 	      tree c;
17246 	      for (c = OMP_TEAMS_CLAUSES (teams);
17247 		   c; c = OMP_CLAUSE_CHAIN (c))
17248 		if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS
17249 		     || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_THREAD_LIMIT)
17250 		    && TREE_CODE (OMP_CLAUSE_OPERAND (c, 0)) != INTEGER_CST)
17251 		  {
17252 		    tree expr = OMP_CLAUSE_OPERAND (c, 0);
17253 		    expr = force_target_expr (TREE_TYPE (expr), expr, tf_none);
17254 		    if (expr == error_mark_node)
17255 		      continue;
17256 		    tmp = TARGET_EXPR_SLOT (expr);
17257 		    add_stmt (expr);
17258 		    OMP_CLAUSE_OPERAND (c, 0) = expr;
17259 		    tree tc = build_omp_clause (OMP_CLAUSE_LOCATION (c),
17260 						OMP_CLAUSE_FIRSTPRIVATE);
17261 		    OMP_CLAUSE_DECL (tc) = tmp;
17262 		    OMP_CLAUSE_CHAIN (tc) = OMP_TARGET_CLAUSES (t);
17263 		    OMP_TARGET_CLAUSES (t) = tc;
17264 		  }
17265 	    }
17266 	}
17267       add_stmt (t);
17268       break;
17269 
17270     case OACC_DECLARE:
17271       t = copy_node (t);
17272       tmp = tsubst_omp_clauses (OACC_DECLARE_CLAUSES (t), C_ORT_ACC, args,
17273 				complain, in_decl);
17274       OACC_DECLARE_CLAUSES (t) = tmp;
17275       add_stmt (t);
17276       break;
17277 
17278     case OMP_TARGET_UPDATE:
17279     case OMP_TARGET_ENTER_DATA:
17280     case OMP_TARGET_EXIT_DATA:
17281       tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_OMP, args,
17282 				complain, in_decl);
17283       t = copy_node (t);
17284       OMP_STANDALONE_CLAUSES (t) = tmp;
17285       add_stmt (t);
17286       break;
17287 
17288     case OACC_ENTER_DATA:
17289     case OACC_EXIT_DATA:
17290     case OACC_UPDATE:
17291       tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), C_ORT_ACC, args,
17292 				complain, in_decl);
17293       t = copy_node (t);
17294       OMP_STANDALONE_CLAUSES (t) = tmp;
17295       add_stmt (t);
17296       break;
17297 
17298     case OMP_ORDERED:
17299       tmp = tsubst_omp_clauses (OMP_ORDERED_CLAUSES (t), C_ORT_OMP, args,
17300 				complain, in_decl);
17301       stmt = push_stmt_list ();
17302       RECUR (OMP_BODY (t));
17303       stmt = pop_stmt_list (stmt);
17304 
17305       t = copy_node (t);
17306       OMP_BODY (t) = stmt;
17307       OMP_ORDERED_CLAUSES (t) = tmp;
17308       add_stmt (t);
17309       break;
17310 
17311     case OMP_SECTION:
17312     case OMP_MASTER:
17313     case OMP_TASKGROUP:
17314       stmt = push_stmt_list ();
17315       RECUR (OMP_BODY (t));
17316       stmt = pop_stmt_list (stmt);
17317 
17318       t = copy_node (t);
17319       OMP_BODY (t) = stmt;
17320       add_stmt (t);
17321       break;
17322 
17323     case OMP_ATOMIC:
17324       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
17325       if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
17326 	{
17327 	  tree op1 = TREE_OPERAND (t, 1);
17328 	  tree rhs1 = NULL_TREE;
17329 	  tree lhs, rhs;
17330 	  if (TREE_CODE (op1) == COMPOUND_EXPR)
17331 	    {
17332 	      rhs1 = RECUR (TREE_OPERAND (op1, 0));
17333 	      op1 = TREE_OPERAND (op1, 1);
17334 	    }
17335 	  lhs = RECUR (TREE_OPERAND (op1, 0));
17336 	  rhs = RECUR (TREE_OPERAND (op1, 1));
17337 	  finish_omp_atomic (OMP_ATOMIC, TREE_CODE (op1), lhs, rhs,
17338 			     NULL_TREE, NULL_TREE, rhs1,
17339 			     OMP_ATOMIC_SEQ_CST (t));
17340 	}
17341       else
17342 	{
17343 	  tree op1 = TREE_OPERAND (t, 1);
17344 	  tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
17345 	  tree rhs1 = NULL_TREE;
17346 	  enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
17347 	  enum tree_code opcode = NOP_EXPR;
17348 	  if (code == OMP_ATOMIC_READ)
17349 	    {
17350 	      v = RECUR (TREE_OPERAND (op1, 0));
17351 	      lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
17352 	    }
17353 	  else if (code == OMP_ATOMIC_CAPTURE_OLD
17354 		   || code == OMP_ATOMIC_CAPTURE_NEW)
17355 	    {
17356 	      tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
17357 	      v = RECUR (TREE_OPERAND (op1, 0));
17358 	      lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
17359 	      if (TREE_CODE (op11) == COMPOUND_EXPR)
17360 		{
17361 		  rhs1 = RECUR (TREE_OPERAND (op11, 0));
17362 		  op11 = TREE_OPERAND (op11, 1);
17363 		}
17364 	      lhs = RECUR (TREE_OPERAND (op11, 0));
17365 	      rhs = RECUR (TREE_OPERAND (op11, 1));
17366 	      opcode = TREE_CODE (op11);
17367 	      if (opcode == MODIFY_EXPR)
17368 		opcode = NOP_EXPR;
17369 	    }
17370 	  else
17371 	    {
17372 	      code = OMP_ATOMIC;
17373 	      lhs = RECUR (TREE_OPERAND (op1, 0));
17374 	      rhs = RECUR (TREE_OPERAND (op1, 1));
17375 	    }
17376 	  finish_omp_atomic (code, opcode, lhs, rhs, v, lhs1, rhs1,
17377 			     OMP_ATOMIC_SEQ_CST (t));
17378 	}
17379       break;
17380 
17381     case TRANSACTION_EXPR:
17382       {
17383 	int flags = 0;
17384 	flags |= (TRANSACTION_EXPR_OUTER (t) ? TM_STMT_ATTR_OUTER : 0);
17385 	flags |= (TRANSACTION_EXPR_RELAXED (t) ? TM_STMT_ATTR_RELAXED : 0);
17386 
17387         if (TRANSACTION_EXPR_IS_STMT (t))
17388           {
17389 	    tree body = TRANSACTION_EXPR_BODY (t);
17390 	    tree noex = NULL_TREE;
17391 	    if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
17392 	      {
17393 		noex = MUST_NOT_THROW_COND (body);
17394 		if (noex == NULL_TREE)
17395 		  noex = boolean_true_node;
17396 		body = TREE_OPERAND (body, 0);
17397 	      }
17398             stmt = begin_transaction_stmt (input_location, NULL, flags);
17399             RECUR (body);
17400             finish_transaction_stmt (stmt, NULL, flags, RECUR (noex));
17401           }
17402         else
17403           {
17404             stmt = build_transaction_expr (EXPR_LOCATION (t),
17405 					   RECUR (TRANSACTION_EXPR_BODY (t)),
17406 					   flags, NULL_TREE);
17407             RETURN (stmt);
17408           }
17409       }
17410       break;
17411 
17412     case MUST_NOT_THROW_EXPR:
17413       {
17414 	tree op0 = RECUR (TREE_OPERAND (t, 0));
17415 	tree cond = RECUR (MUST_NOT_THROW_COND (t));
17416 	RETURN (build_must_not_throw_expr (op0, cond));
17417       }
17418 
17419     case EXPR_PACK_EXPANSION:
17420       error ("invalid use of pack expansion expression");
17421       RETURN (error_mark_node);
17422 
17423     case NONTYPE_ARGUMENT_PACK:
17424       error ("use %<...%> to expand argument pack");
17425       RETURN (error_mark_node);
17426 
17427     case COMPOUND_EXPR:
17428       tmp = RECUR (TREE_OPERAND (t, 0));
17429       if (tmp == NULL_TREE)
17430 	/* If the first operand was a statement, we're done with it.  */
17431 	RETURN (RECUR (TREE_OPERAND (t, 1)));
17432       RETURN (build_x_compound_expr (EXPR_LOCATION (t), tmp,
17433 				    RECUR (TREE_OPERAND (t, 1)),
17434 				    complain));
17435 
17436     case ANNOTATE_EXPR:
17437       tmp = RECUR (TREE_OPERAND (t, 0));
17438       RETURN (build3_loc (EXPR_LOCATION (t), ANNOTATE_EXPR,
17439 			  TREE_TYPE (tmp), tmp,
17440 			  RECUR (TREE_OPERAND (t, 1)),
17441 			  RECUR (TREE_OPERAND (t, 2))));
17442 
17443     default:
17444       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
17445 
17446       RETURN (tsubst_copy_and_build (t, args, complain, in_decl,
17447 				    /*function_p=*/false,
17448 				    integral_constant_expression_p));
17449     }
17450 
17451   RETURN (NULL_TREE);
17452  out:
17453   input_location = loc;
17454   return r;
17455 #undef RECUR
17456 #undef RETURN
17457 }
17458 
17459 /* Instantiate the special body of the artificial DECL_OMP_DECLARE_REDUCTION
17460    function.  For description of the body see comment above
17461    cp_parser_omp_declare_reduction_exprs.  */
17462 
17463 static void
tsubst_omp_udr(tree t,tree args,tsubst_flags_t complain,tree in_decl)17464 tsubst_omp_udr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
17465 {
17466   if (t == NULL_TREE || t == error_mark_node)
17467     return;
17468 
17469   gcc_assert (TREE_CODE (t) == STATEMENT_LIST);
17470 
17471   tree_stmt_iterator tsi;
17472   int i;
17473   tree stmts[7];
17474   memset (stmts, 0, sizeof stmts);
17475   for (i = 0, tsi = tsi_start (t);
17476        i < 7 && !tsi_end_p (tsi);
17477        i++, tsi_next (&tsi))
17478     stmts[i] = tsi_stmt (tsi);
17479   gcc_assert (tsi_end_p (tsi));
17480 
17481   if (i >= 3)
17482     {
17483       gcc_assert (TREE_CODE (stmts[0]) == DECL_EXPR
17484 		  && TREE_CODE (stmts[1]) == DECL_EXPR);
17485       tree omp_out = tsubst (DECL_EXPR_DECL (stmts[0]),
17486 			     args, complain, in_decl);
17487       tree omp_in = tsubst (DECL_EXPR_DECL (stmts[1]),
17488 			    args, complain, in_decl);
17489       DECL_CONTEXT (omp_out) = current_function_decl;
17490       DECL_CONTEXT (omp_in) = current_function_decl;
17491       keep_next_level (true);
17492       tree block = begin_omp_structured_block ();
17493       tsubst_expr (stmts[2], args, complain, in_decl, false);
17494       block = finish_omp_structured_block (block);
17495       block = maybe_cleanup_point_expr_void (block);
17496       add_decl_expr (omp_out);
17497       if (TREE_NO_WARNING (DECL_EXPR_DECL (stmts[0])))
17498 	TREE_NO_WARNING (omp_out) = 1;
17499       add_decl_expr (omp_in);
17500       finish_expr_stmt (block);
17501     }
17502   if (i >= 6)
17503     {
17504       gcc_assert (TREE_CODE (stmts[3]) == DECL_EXPR
17505 		  && TREE_CODE (stmts[4]) == DECL_EXPR);
17506       tree omp_priv = tsubst (DECL_EXPR_DECL (stmts[3]),
17507 			      args, complain, in_decl);
17508       tree omp_orig = tsubst (DECL_EXPR_DECL (stmts[4]),
17509 			      args, complain, in_decl);
17510       DECL_CONTEXT (omp_priv) = current_function_decl;
17511       DECL_CONTEXT (omp_orig) = current_function_decl;
17512       keep_next_level (true);
17513       tree block = begin_omp_structured_block ();
17514       tsubst_expr (stmts[5], args, complain, in_decl, false);
17515       block = finish_omp_structured_block (block);
17516       block = maybe_cleanup_point_expr_void (block);
17517       cp_walk_tree (&block, cp_remove_omp_priv_cleanup_stmt, omp_priv, NULL);
17518       add_decl_expr (omp_priv);
17519       add_decl_expr (omp_orig);
17520       finish_expr_stmt (block);
17521       if (i == 7)
17522 	add_decl_expr (omp_orig);
17523     }
17524 }
17525 
17526 /* T is a postfix-expression that is not being used in a function
17527    call.  Return the substituted version of T.  */
17528 
17529 static tree
tsubst_non_call_postfix_expression(tree t,tree args,tsubst_flags_t complain,tree in_decl)17530 tsubst_non_call_postfix_expression (tree t, tree args,
17531 				    tsubst_flags_t complain,
17532 				    tree in_decl)
17533 {
17534   if (TREE_CODE (t) == SCOPE_REF)
17535     t = tsubst_qualified_id (t, args, complain, in_decl,
17536 			     /*done=*/false, /*address_p=*/false);
17537   else
17538     t = tsubst_copy_and_build (t, args, complain, in_decl,
17539 			       /*function_p=*/false,
17540 			       /*integral_constant_expression_p=*/false);
17541 
17542   return t;
17543 }
17544 
17545 /* T is a LAMBDA_EXPR.  Generate a new LAMBDA_EXPR for the current
17546    instantiation context.  Instantiating a pack expansion containing a lambda
17547    might result in multiple lambdas all based on the same lambda in the
17548    template.  */
17549 
17550 tree
tsubst_lambda_expr(tree t,tree args,tsubst_flags_t complain,tree in_decl)17551 tsubst_lambda_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
17552 {
17553   tree oldfn = lambda_function (t);
17554   in_decl = oldfn;
17555 
17556   tree r = build_lambda_expr ();
17557 
17558   LAMBDA_EXPR_LOCATION (r)
17559     = LAMBDA_EXPR_LOCATION (t);
17560   LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
17561     = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
17562   LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
17563 
17564   if (LAMBDA_EXPR_EXTRA_SCOPE (t) == NULL_TREE)
17565     /* A lambda in a default argument outside a class gets no
17566        LAMBDA_EXPR_EXTRA_SCOPE, as specified by the ABI.  But
17567        tsubst_default_argument calls start_lambda_scope, so we need to
17568        specifically ignore it here, and use the global scope.  */
17569     record_null_lambda_scope (r);
17570   else
17571     record_lambda_scope (r);
17572 
17573   gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
17574 	      && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
17575 
17576   for (tree cap = LAMBDA_EXPR_CAPTURE_LIST (t); cap;
17577        cap = TREE_CHAIN (cap))
17578     {
17579       tree field = TREE_PURPOSE (cap);
17580       if (PACK_EXPANSION_P (field))
17581 	field = PACK_EXPANSION_PATTERN (field);
17582       field = tsubst_decl (field, args, complain);
17583 
17584       if (field == error_mark_node)
17585 	return error_mark_node;
17586 
17587       tree init = TREE_VALUE (cap);
17588       if (PACK_EXPANSION_P (init))
17589 	init = tsubst_pack_expansion (init, args, complain, in_decl);
17590       else
17591 	init = tsubst_copy_and_build (init, args, complain, in_decl,
17592 				      /*fn*/false, /*constexpr*/false);
17593 
17594       if (TREE_CODE (field) == TREE_VEC)
17595 	{
17596 	  int len = TREE_VEC_LENGTH (field);
17597 	  gcc_assert (TREE_CODE (init) == TREE_VEC
17598 		      && TREE_VEC_LENGTH (init) == len);
17599 	  for (int i = 0; i < len; ++i)
17600 	    LAMBDA_EXPR_CAPTURE_LIST (r)
17601 	      = tree_cons (TREE_VEC_ELT (field, i),
17602 			   TREE_VEC_ELT (init, i),
17603 			   LAMBDA_EXPR_CAPTURE_LIST (r));
17604 	}
17605       else
17606 	{
17607 	  LAMBDA_EXPR_CAPTURE_LIST (r)
17608 	    = tree_cons (field, init, LAMBDA_EXPR_CAPTURE_LIST (r));
17609 
17610 	  if (id_equal (DECL_NAME (field), "__this"))
17611 	    LAMBDA_EXPR_THIS_CAPTURE (r) = field;
17612 	}
17613     }
17614 
17615   tree type = begin_lambda_type (r);
17616   if (type == error_mark_node)
17617     return error_mark_node;
17618 
17619   /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
17620   determine_visibility (TYPE_NAME (type));
17621 
17622   register_capture_members (LAMBDA_EXPR_CAPTURE_LIST (r));
17623 
17624   tree oldtmpl = (generic_lambda_fn_p (oldfn)
17625 		  ? DECL_TI_TEMPLATE (oldfn)
17626 		  : NULL_TREE);
17627 
17628   tree fntype = static_fn_type (oldfn);
17629   if (oldtmpl)
17630     ++processing_template_decl;
17631   fntype = tsubst (fntype, args, complain, in_decl);
17632   if (oldtmpl)
17633     --processing_template_decl;
17634 
17635   if (fntype == error_mark_node)
17636     r = error_mark_node;
17637   else
17638     {
17639       /* Fix the type of 'this'.  */
17640       fntype = build_memfn_type (fntype, type,
17641 				 type_memfn_quals (fntype),
17642 				 type_memfn_rqual (fntype));
17643       tree fn, tmpl;
17644       if (oldtmpl)
17645 	{
17646 	  tmpl = tsubst_template_decl (oldtmpl, args, complain, fntype);
17647 	  fn = DECL_TEMPLATE_RESULT (tmpl);
17648 	  finish_member_declaration (tmpl);
17649 	}
17650       else
17651 	{
17652 	  tmpl = NULL_TREE;
17653 	  fn = tsubst_function_decl (oldfn, args, complain, fntype);
17654 	  finish_member_declaration (fn);
17655 	}
17656 
17657       /* Let finish_function set this.  */
17658       DECL_DECLARED_CONSTEXPR_P (fn) = false;
17659 
17660       bool nested = cfun;
17661       if (nested)
17662 	push_function_context ();
17663       else
17664 	/* Still increment function_depth so that we don't GC in the
17665 	   middle of an expression.  */
17666 	++function_depth;
17667 
17668       local_specialization_stack s (lss_copy);
17669 
17670       tree body = start_lambda_function (fn, r);
17671 
17672       register_parameter_specializations (oldfn, fn);
17673 
17674       if (oldtmpl)
17675 	{
17676 	  /* We might not partially instantiate some parts of the function, so
17677 	     copy these flags from the original template.  */
17678 	  language_function *ol = DECL_STRUCT_FUNCTION (oldfn)->language;
17679 	  current_function_returns_value = ol->returns_value;
17680 	  current_function_returns_null = ol->returns_null;
17681 	  current_function_returns_abnormally = ol->returns_abnormally;
17682 	  current_function_infinite_loop = ol->infinite_loop;
17683 	}
17684 
17685       tsubst_expr (DECL_SAVED_TREE (oldfn), args, complain, r,
17686 		   /*constexpr*/false);
17687 
17688       finish_lambda_function (body);
17689 
17690       if (nested)
17691 	pop_function_context ();
17692       else
17693 	--function_depth;
17694 
17695       /* The capture list was built up in reverse order; fix that now.  */
17696       LAMBDA_EXPR_CAPTURE_LIST (r)
17697 	= nreverse (LAMBDA_EXPR_CAPTURE_LIST (r));
17698 
17699       LAMBDA_EXPR_THIS_CAPTURE (r) = NULL_TREE;
17700 
17701       maybe_add_lambda_conv_op (type);
17702     }
17703 
17704   finish_struct (type, /*attr*/NULL_TREE);
17705 
17706   insert_pending_capture_proxies ();
17707 
17708   return r;
17709 }
17710 
17711 /* Like tsubst but deals with expressions and performs semantic
17712    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
17713 
17714 tree
tsubst_copy_and_build(tree t,tree args,tsubst_flags_t complain,tree in_decl,bool function_p,bool integral_constant_expression_p)17715 tsubst_copy_and_build (tree t,
17716 		       tree args,
17717 		       tsubst_flags_t complain,
17718 		       tree in_decl,
17719 		       bool function_p,
17720 		       bool integral_constant_expression_p)
17721 {
17722 #define RETURN(EXP) do { retval = (EXP); goto out; } while(0)
17723 #define RECUR(NODE)						\
17724   tsubst_copy_and_build (NODE, args, complain, in_decl, 	\
17725 			 /*function_p=*/false,			\
17726 			 integral_constant_expression_p)
17727 
17728   tree retval, op1;
17729   location_t loc;
17730 
17731   if (t == NULL_TREE || t == error_mark_node)
17732     return t;
17733 
17734   loc = input_location;
17735   if (EXPR_HAS_LOCATION (t))
17736     input_location = EXPR_LOCATION (t);
17737 
17738   /* N3276 decltype magic only applies to calls at the top level or on the
17739      right side of a comma.  */
17740   tsubst_flags_t decltype_flag = (complain & tf_decltype);
17741   complain &= ~tf_decltype;
17742 
17743   switch (TREE_CODE (t))
17744     {
17745     case USING_DECL:
17746       t = DECL_NAME (t);
17747       /* Fall through.  */
17748     case IDENTIFIER_NODE:
17749       {
17750 	tree decl;
17751 	cp_id_kind idk;
17752 	bool non_integral_constant_expression_p;
17753 	const char *error_msg;
17754 
17755 	if (IDENTIFIER_CONV_OP_P (t))
17756 	  {
17757 	    tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17758 	    t = make_conv_op_name (new_type);
17759 	  }
17760 
17761 	/* Look up the name.  */
17762 	decl = lookup_name (t);
17763 
17764 	/* By convention, expressions use ERROR_MARK_NODE to indicate
17765 	   failure, not NULL_TREE.  */
17766 	if (decl == NULL_TREE)
17767 	  decl = error_mark_node;
17768 
17769 	decl = finish_id_expression (t, decl, NULL_TREE,
17770 				     &idk,
17771 				     integral_constant_expression_p,
17772           /*allow_non_integral_constant_expression_p=*/(cxx_dialect >= cxx11),
17773 				     &non_integral_constant_expression_p,
17774 				     /*template_p=*/false,
17775 				     /*done=*/true,
17776 				     /*address_p=*/false,
17777 				     /*template_arg_p=*/false,
17778 				     &error_msg,
17779 				     input_location);
17780 	if (error_msg)
17781 	  error (error_msg);
17782 	if (!function_p && identifier_p (decl))
17783 	  {
17784 	    if (complain & tf_error)
17785 	      unqualified_name_lookup_error (decl);
17786 	    decl = error_mark_node;
17787 	  }
17788 	RETURN (decl);
17789       }
17790 
17791     case TEMPLATE_ID_EXPR:
17792       {
17793 	tree object;
17794 	tree templ = RECUR (TREE_OPERAND (t, 0));
17795 	tree targs = TREE_OPERAND (t, 1);
17796 
17797 	if (targs)
17798 	  targs = tsubst_template_args (targs, args, complain, in_decl);
17799 	if (targs == error_mark_node)
17800 	  RETURN (error_mark_node);
17801 
17802 	if (TREE_CODE (templ) == SCOPE_REF)
17803 	  {
17804 	    tree name = TREE_OPERAND (templ, 1);
17805 	    tree tid = lookup_template_function (name, targs);
17806 	    TREE_OPERAND (templ, 1) = tid;
17807 	    RETURN (templ);
17808 	  }
17809 
17810 	if (variable_template_p (templ))
17811 	  RETURN (lookup_and_finish_template_variable (templ, targs, complain));
17812 
17813 	if (TREE_CODE (templ) == COMPONENT_REF)
17814 	  {
17815 	    object = TREE_OPERAND (templ, 0);
17816 	    templ = TREE_OPERAND (templ, 1);
17817 	  }
17818 	else
17819 	  object = NULL_TREE;
17820 	templ = lookup_template_function (templ, targs);
17821 
17822 	if (object)
17823 	  RETURN (build3 (COMPONENT_REF, TREE_TYPE (templ),
17824 			 object, templ, NULL_TREE));
17825 	else
17826 	  RETURN (baselink_for_fns (templ));
17827       }
17828 
17829     case INDIRECT_REF:
17830       {
17831 	tree r = RECUR (TREE_OPERAND (t, 0));
17832 
17833 	if (REFERENCE_REF_P (t))
17834 	  {
17835 	    /* A type conversion to reference type will be enclosed in
17836 	       such an indirect ref, but the substitution of the cast
17837 	       will have also added such an indirect ref.  */
17838 	    r = convert_from_reference (r);
17839 	  }
17840 	else
17841 	  r = build_x_indirect_ref (input_location, r, RO_UNARY_STAR,
17842 				    complain|decltype_flag);
17843 
17844 	if (REF_PARENTHESIZED_P (t))
17845 	  r = force_paren_expr (r);
17846 
17847 	RETURN (r);
17848       }
17849 
17850     case NOP_EXPR:
17851       {
17852 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17853 	tree op0 = RECUR (TREE_OPERAND (t, 0));
17854 	RETURN (build_nop (type, op0));
17855       }
17856 
17857     case IMPLICIT_CONV_EXPR:
17858       {
17859 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17860 	tree expr = RECUR (TREE_OPERAND (t, 0));
17861 	if (dependent_type_p (type) || type_dependent_expression_p (expr))
17862 	  {
17863 	    retval = copy_node (t);
17864 	    TREE_TYPE (retval) = type;
17865 	    TREE_OPERAND (retval, 0) = expr;
17866 	    RETURN (retval);
17867 	  }
17868 	if (IMPLICIT_CONV_EXPR_NONTYPE_ARG (t))
17869 	  /* We'll pass this to convert_nontype_argument again, we don't need
17870 	     to actually perform any conversion here.  */
17871 	  RETURN (expr);
17872 	int flags = LOOKUP_IMPLICIT;
17873 	if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
17874 	  flags = LOOKUP_NORMAL;
17875 	RETURN (perform_implicit_conversion_flags (type, expr, complain,
17876 						  flags));
17877       }
17878 
17879     case CONVERT_EXPR:
17880       {
17881 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17882 	tree op0 = RECUR (TREE_OPERAND (t, 0));
17883 	if (op0 == error_mark_node)
17884 	  RETURN (error_mark_node);
17885 	RETURN (build1 (CONVERT_EXPR, type, op0));
17886       }
17887 
17888     case CAST_EXPR:
17889     case REINTERPRET_CAST_EXPR:
17890     case CONST_CAST_EXPR:
17891     case DYNAMIC_CAST_EXPR:
17892     case STATIC_CAST_EXPR:
17893       {
17894 	tree type;
17895 	tree op, r = NULL_TREE;
17896 
17897 	type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17898 	if (integral_constant_expression_p
17899 	    && !cast_valid_in_integral_constant_expression_p (type))
17900 	  {
17901             if (complain & tf_error)
17902               error ("a cast to a type other than an integral or "
17903                      "enumeration type cannot appear in a constant-expression");
17904 	    RETURN (error_mark_node);
17905 	  }
17906 
17907 	op = RECUR (TREE_OPERAND (t, 0));
17908 
17909 	warning_sentinel s(warn_useless_cast);
17910 	warning_sentinel s2(warn_ignored_qualifiers);
17911 	switch (TREE_CODE (t))
17912 	  {
17913 	  case CAST_EXPR:
17914 	    r = build_functional_cast (type, op, complain);
17915 	    break;
17916 	  case REINTERPRET_CAST_EXPR:
17917 	    r = build_reinterpret_cast (type, op, complain);
17918 	    break;
17919 	  case CONST_CAST_EXPR:
17920 	    r = build_const_cast (type, op, complain);
17921 	    break;
17922 	  case DYNAMIC_CAST_EXPR:
17923 	    r = build_dynamic_cast (type, op, complain);
17924 	    break;
17925 	  case STATIC_CAST_EXPR:
17926 	    r = build_static_cast (type, op, complain);
17927 	    break;
17928 	  default:
17929 	    gcc_unreachable ();
17930 	  }
17931 
17932 	RETURN (r);
17933       }
17934 
17935     case POSTDECREMENT_EXPR:
17936     case POSTINCREMENT_EXPR:
17937       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
17938 						args, complain, in_decl);
17939       RETURN (build_x_unary_op (input_location, TREE_CODE (t), op1,
17940 				complain|decltype_flag));
17941 
17942     case PREDECREMENT_EXPR:
17943     case PREINCREMENT_EXPR:
17944     case NEGATE_EXPR:
17945     case BIT_NOT_EXPR:
17946     case ABS_EXPR:
17947     case TRUTH_NOT_EXPR:
17948     case UNARY_PLUS_EXPR:  /* Unary + */
17949     case REALPART_EXPR:
17950     case IMAGPART_EXPR:
17951       RETURN (build_x_unary_op (input_location, TREE_CODE (t),
17952 				RECUR (TREE_OPERAND (t, 0)),
17953 				complain|decltype_flag));
17954 
17955     case FIX_TRUNC_EXPR:
17956       gcc_unreachable ();
17957 
17958     case ADDR_EXPR:
17959       op1 = TREE_OPERAND (t, 0);
17960       if (TREE_CODE (op1) == LABEL_DECL)
17961 	RETURN (finish_label_address_expr (DECL_NAME (op1),
17962 					  EXPR_LOCATION (op1)));
17963       if (TREE_CODE (op1) == SCOPE_REF)
17964 	op1 = tsubst_qualified_id (op1, args, complain, in_decl,
17965 				   /*done=*/true, /*address_p=*/true);
17966       else
17967 	op1 = tsubst_non_call_postfix_expression (op1, args, complain,
17968 						  in_decl);
17969       RETURN (build_x_unary_op (input_location, ADDR_EXPR, op1,
17970 				complain|decltype_flag));
17971 
17972     case PLUS_EXPR:
17973     case MINUS_EXPR:
17974     case MULT_EXPR:
17975     case TRUNC_DIV_EXPR:
17976     case CEIL_DIV_EXPR:
17977     case FLOOR_DIV_EXPR:
17978     case ROUND_DIV_EXPR:
17979     case EXACT_DIV_EXPR:
17980     case BIT_AND_EXPR:
17981     case BIT_IOR_EXPR:
17982     case BIT_XOR_EXPR:
17983     case TRUNC_MOD_EXPR:
17984     case FLOOR_MOD_EXPR:
17985     case TRUTH_ANDIF_EXPR:
17986     case TRUTH_ORIF_EXPR:
17987     case TRUTH_AND_EXPR:
17988     case TRUTH_OR_EXPR:
17989     case RSHIFT_EXPR:
17990     case LSHIFT_EXPR:
17991     case RROTATE_EXPR:
17992     case LROTATE_EXPR:
17993     case EQ_EXPR:
17994     case NE_EXPR:
17995     case MAX_EXPR:
17996     case MIN_EXPR:
17997     case LE_EXPR:
17998     case GE_EXPR:
17999     case LT_EXPR:
18000     case GT_EXPR:
18001     case MEMBER_REF:
18002     case DOTSTAR_EXPR:
18003       {
18004 	warning_sentinel s1(warn_type_limits);
18005 	warning_sentinel s2(warn_div_by_zero);
18006 	warning_sentinel s3(warn_logical_op);
18007 	warning_sentinel s4(warn_tautological_compare);
18008 	tree op0 = RECUR (TREE_OPERAND (t, 0));
18009 	tree op1 = RECUR (TREE_OPERAND (t, 1));
18010 	tree r = build_x_binary_op
18011 	  (input_location, TREE_CODE (t),
18012 	   op0,
18013 	   (TREE_NO_WARNING (TREE_OPERAND (t, 0))
18014 	    ? ERROR_MARK
18015 	    : TREE_CODE (TREE_OPERAND (t, 0))),
18016 	   op1,
18017 	   (TREE_NO_WARNING (TREE_OPERAND (t, 1))
18018 	    ? ERROR_MARK
18019 	    : TREE_CODE (TREE_OPERAND (t, 1))),
18020 	   /*overload=*/NULL,
18021 	   complain|decltype_flag);
18022 	if (EXPR_P (r) && TREE_NO_WARNING (t))
18023 	  TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
18024 
18025 	RETURN (r);
18026       }
18027 
18028     case POINTER_PLUS_EXPR:
18029       {
18030 	tree op0 = RECUR (TREE_OPERAND (t, 0));
18031 	tree op1 = RECUR (TREE_OPERAND (t, 1));
18032 	RETURN (fold_build_pointer_plus (op0, op1));
18033       }
18034 
18035     case SCOPE_REF:
18036       RETURN (tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
18037 				  /*address_p=*/false));
18038     case ARRAY_REF:
18039       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
18040 						args, complain, in_decl);
18041       RETURN (build_x_array_ref (EXPR_LOCATION (t), op1,
18042 				 RECUR (TREE_OPERAND (t, 1)),
18043 				 complain|decltype_flag));
18044 
18045     case SIZEOF_EXPR:
18046       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
18047 	  || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
18048 	RETURN (tsubst_copy (t, args, complain, in_decl));
18049       /* Fall through */
18050 
18051     case ALIGNOF_EXPR:
18052       {
18053 	tree r;
18054 
18055 	op1 = TREE_OPERAND (t, 0);
18056 	if (TREE_CODE (t) == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (t))
18057 	  op1 = TREE_TYPE (op1);
18058 	bool std_alignof = (TREE_CODE (t) == ALIGNOF_EXPR
18059 			    && ALIGNOF_EXPR_STD_P (t));
18060         if (!args)
18061 	  {
18062 	    /* When there are no ARGS, we are trying to evaluate a
18063 	       non-dependent expression from the parser.  Trying to do
18064 	       the substitutions may not work.  */
18065 	    if (!TYPE_P (op1))
18066 	      op1 = TREE_TYPE (op1);
18067 	  }
18068 	else
18069 	  {
18070 	    ++cp_unevaluated_operand;
18071 	    ++c_inhibit_evaluation_warnings;
18072 	    if (TYPE_P (op1))
18073 	      op1 = tsubst (op1, args, complain, in_decl);
18074 	    else
18075 	      op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
18076 					   /*function_p=*/false,
18077 					   /*integral_constant_expression_p=*/
18078 					   false);
18079 	    --cp_unevaluated_operand;
18080 	    --c_inhibit_evaluation_warnings;
18081 	  }
18082         if (TYPE_P (op1))
18083 	  r = cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), std_alignof,
18084 					  complain & tf_error);
18085 	else
18086 	  r = cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t),
18087 					  complain & tf_error);
18088 	if (TREE_CODE (t) == SIZEOF_EXPR && r != error_mark_node)
18089 	  {
18090 	    if (TREE_CODE (r) != SIZEOF_EXPR || TYPE_P (op1))
18091 	      {
18092 		if (!processing_template_decl && TYPE_P (op1))
18093 		  {
18094 		    r = build_min (SIZEOF_EXPR, size_type_node,
18095 				   build1 (NOP_EXPR, op1, error_mark_node));
18096 		    SIZEOF_EXPR_TYPE_P (r) = 1;
18097 		  }
18098 		else
18099 		  r = build_min (SIZEOF_EXPR, size_type_node, op1);
18100 		TREE_SIDE_EFFECTS (r) = 0;
18101 		TREE_READONLY (r) = 1;
18102 	      }
18103 	    SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
18104 	  }
18105 	RETURN (r);
18106       }
18107 
18108     case AT_ENCODE_EXPR:
18109       {
18110 	op1 = TREE_OPERAND (t, 0);
18111 	++cp_unevaluated_operand;
18112 	++c_inhibit_evaluation_warnings;
18113 	op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
18114 				     /*function_p=*/false,
18115 				     /*integral_constant_expression_p=*/false);
18116 	--cp_unevaluated_operand;
18117 	--c_inhibit_evaluation_warnings;
18118 	RETURN (objc_build_encode_expr (op1));
18119       }
18120 
18121     case NOEXCEPT_EXPR:
18122       op1 = TREE_OPERAND (t, 0);
18123       ++cp_unevaluated_operand;
18124       ++c_inhibit_evaluation_warnings;
18125       ++cp_noexcept_operand;
18126       op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
18127 				   /*function_p=*/false,
18128 				   /*integral_constant_expression_p=*/false);
18129       --cp_unevaluated_operand;
18130       --c_inhibit_evaluation_warnings;
18131       --cp_noexcept_operand;
18132       RETURN (finish_noexcept_expr (op1, complain));
18133 
18134     case MODOP_EXPR:
18135       {
18136 	warning_sentinel s(warn_div_by_zero);
18137 	tree lhs = RECUR (TREE_OPERAND (t, 0));
18138 	tree rhs = RECUR (TREE_OPERAND (t, 2));
18139 	tree r = build_x_modify_expr
18140 	  (EXPR_LOCATION (t), lhs, TREE_CODE (TREE_OPERAND (t, 1)), rhs,
18141 	   complain|decltype_flag);
18142 	/* TREE_NO_WARNING must be set if either the expression was
18143 	   parenthesized or it uses an operator such as >>= rather
18144 	   than plain assignment.  In the former case, it was already
18145 	   set and must be copied.  In the latter case,
18146 	   build_x_modify_expr sets it and it must not be reset
18147 	   here.  */
18148 	if (TREE_NO_WARNING (t))
18149 	  TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
18150 
18151 	RETURN (r);
18152       }
18153 
18154     case ARROW_EXPR:
18155       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
18156 						args, complain, in_decl);
18157       /* Remember that there was a reference to this entity.  */
18158       if (DECL_P (op1)
18159 	  && !mark_used (op1, complain) && !(complain & tf_error))
18160 	RETURN (error_mark_node);
18161       RETURN (build_x_arrow (input_location, op1, complain));
18162 
18163     case NEW_EXPR:
18164       {
18165 	tree placement = RECUR (TREE_OPERAND (t, 0));
18166 	tree init = RECUR (TREE_OPERAND (t, 3));
18167 	vec<tree, va_gc> *placement_vec;
18168 	vec<tree, va_gc> *init_vec;
18169 	tree ret;
18170 
18171 	if (placement == NULL_TREE)
18172 	  placement_vec = NULL;
18173 	else
18174 	  {
18175 	    placement_vec = make_tree_vector ();
18176 	    for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
18177 	      vec_safe_push (placement_vec, TREE_VALUE (placement));
18178 	  }
18179 
18180 	/* If there was an initializer in the original tree, but it
18181 	   instantiated to an empty list, then we should pass a
18182 	   non-NULL empty vector to tell build_new that it was an
18183 	   empty initializer() rather than no initializer.  This can
18184 	   only happen when the initializer is a pack expansion whose
18185 	   parameter packs are of length zero.  */
18186 	if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
18187 	  init_vec = NULL;
18188 	else
18189 	  {
18190 	    init_vec = make_tree_vector ();
18191 	    if (init == void_node)
18192 	      gcc_assert (init_vec != NULL);
18193 	    else
18194 	      {
18195 		for (; init != NULL_TREE; init = TREE_CHAIN (init))
18196 		  vec_safe_push (init_vec, TREE_VALUE (init));
18197 	      }
18198 	  }
18199 
18200 	tree op1 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
18201 	tree op2 = RECUR (TREE_OPERAND (t, 2));
18202 	ret = build_new (&placement_vec, op1, op2, &init_vec,
18203 			 NEW_EXPR_USE_GLOBAL (t),
18204 			 complain);
18205 
18206 	if (placement_vec != NULL)
18207 	  release_tree_vector (placement_vec);
18208 	if (init_vec != NULL)
18209 	  release_tree_vector (init_vec);
18210 
18211 	RETURN (ret);
18212       }
18213 
18214     case DELETE_EXPR:
18215       {
18216 	tree op0 = RECUR (TREE_OPERAND (t, 0));
18217 	tree op1 = RECUR (TREE_OPERAND (t, 1));
18218 	RETURN (delete_sanity (op0, op1,
18219 			       DELETE_EXPR_USE_VEC (t),
18220 			       DELETE_EXPR_USE_GLOBAL (t),
18221 			       complain));
18222       }
18223 
18224     case COMPOUND_EXPR:
18225       {
18226 	tree op0 = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
18227 					  complain & ~tf_decltype, in_decl,
18228 					  /*function_p=*/false,
18229 					  integral_constant_expression_p);
18230 	RETURN (build_x_compound_expr (EXPR_LOCATION (t),
18231 				       op0,
18232 				       RECUR (TREE_OPERAND (t, 1)),
18233 				       complain|decltype_flag));
18234       }
18235 
18236     case CALL_EXPR:
18237       {
18238 	tree function;
18239 	vec<tree, va_gc> *call_args;
18240 	unsigned int nargs, i;
18241 	bool qualified_p;
18242 	bool koenig_p;
18243 	tree ret;
18244 
18245 	function = CALL_EXPR_FN (t);
18246 	/* Internal function with no arguments.  */
18247 	if (function == NULL_TREE && call_expr_nargs (t) == 0)
18248 	  RETURN (t);
18249 
18250 	/* When we parsed the expression, we determined whether or
18251 	   not Koenig lookup should be performed.  */
18252 	koenig_p = KOENIG_LOOKUP_P (t);
18253 	if (function == NULL_TREE)
18254 	  {
18255 	    koenig_p = false;
18256 	    qualified_p = false;
18257 	  }
18258 	else if (TREE_CODE (function) == SCOPE_REF)
18259 	  {
18260 	    qualified_p = true;
18261 	    function = tsubst_qualified_id (function, args, complain, in_decl,
18262 					    /*done=*/false,
18263 					    /*address_p=*/false);
18264 	  }
18265 	else if (koenig_p && identifier_p (function))
18266 	  {
18267 	    /* Do nothing; calling tsubst_copy_and_build on an identifier
18268 	       would incorrectly perform unqualified lookup again.
18269 
18270 	       Note that we can also have an IDENTIFIER_NODE if the earlier
18271 	       unqualified lookup found a member function; in that case
18272 	       koenig_p will be false and we do want to do the lookup
18273 	       again to find the instantiated member function.
18274 
18275 	       FIXME but doing that causes c++/15272, so we need to stop
18276 	       using IDENTIFIER_NODE in that situation.  */
18277 	    qualified_p = false;
18278 	  }
18279 	else
18280 	  {
18281 	    if (TREE_CODE (function) == COMPONENT_REF)
18282 	      {
18283 		tree op = TREE_OPERAND (function, 1);
18284 
18285 		qualified_p = (TREE_CODE (op) == SCOPE_REF
18286 			       || (BASELINK_P (op)
18287 				   && BASELINK_QUALIFIED_P (op)));
18288 	      }
18289 	    else
18290 	      qualified_p = false;
18291 
18292 	    if (TREE_CODE (function) == ADDR_EXPR
18293 		&& TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL)
18294 	      /* Avoid error about taking the address of a constructor.  */
18295 	      function = TREE_OPERAND (function, 0);
18296 
18297 	    function = tsubst_copy_and_build (function, args, complain,
18298 					      in_decl,
18299 					      !qualified_p,
18300 					      integral_constant_expression_p);
18301 
18302 	    if (BASELINK_P (function))
18303 	      qualified_p = true;
18304 	  }
18305 
18306 	nargs = call_expr_nargs (t);
18307 	call_args = make_tree_vector ();
18308 	for (i = 0; i < nargs; ++i)
18309 	  {
18310 	    tree arg = CALL_EXPR_ARG (t, i);
18311 
18312 	    if (!PACK_EXPANSION_P (arg))
18313 	      vec_safe_push (call_args, RECUR (CALL_EXPR_ARG (t, i)));
18314 	    else
18315 	      {
18316 		/* Expand the pack expansion and push each entry onto
18317 		   CALL_ARGS.  */
18318 		arg = tsubst_pack_expansion (arg, args, complain, in_decl);
18319 		if (TREE_CODE (arg) == TREE_VEC)
18320 		  {
18321 		    unsigned int len, j;
18322 
18323 		    len = TREE_VEC_LENGTH (arg);
18324 		    for (j = 0; j < len; ++j)
18325 		      {
18326 			tree value = TREE_VEC_ELT (arg, j);
18327 			if (value != NULL_TREE)
18328 			  value = convert_from_reference (value);
18329 			vec_safe_push (call_args, value);
18330 		      }
18331 		  }
18332 		else
18333 		  {
18334 		    /* A partial substitution.  Add one entry.  */
18335 		    vec_safe_push (call_args, arg);
18336 		  }
18337 	      }
18338 	  }
18339 
18340 	/* We do not perform argument-dependent lookup if normal
18341 	   lookup finds a non-function, in accordance with the
18342 	   expected resolution of DR 218.  */
18343 	if (koenig_p
18344 	    && ((is_overloaded_fn (function)
18345 		 /* If lookup found a member function, the Koenig lookup is
18346 		    not appropriate, even if an unqualified-name was used
18347 		    to denote the function.  */
18348 		 && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
18349 		|| identifier_p (function))
18350 	    /* Only do this when substitution turns a dependent call
18351 	       into a non-dependent call.  */
18352 	    && type_dependent_expression_p_push (t)
18353 	    && !any_type_dependent_arguments_p (call_args))
18354 	  function = perform_koenig_lookup (function, call_args, tf_none);
18355 
18356 	if (function != NULL_TREE
18357 	    && identifier_p (function)
18358 	    && !any_type_dependent_arguments_p (call_args))
18359 	  {
18360 	    if (koenig_p && (complain & tf_warning_or_error))
18361 	      {
18362 		/* For backwards compatibility and good diagnostics, try
18363 		   the unqualified lookup again if we aren't in SFINAE
18364 		   context.  */
18365 		tree unq = (tsubst_copy_and_build
18366 			    (function, args, complain, in_decl, true,
18367 			     integral_constant_expression_p));
18368 		if (unq == error_mark_node)
18369 		  {
18370 		    release_tree_vector (call_args);
18371 		    RETURN (error_mark_node);
18372 		  }
18373 
18374 		if (unq != function)
18375 		  {
18376 		    /* In a lambda fn, we have to be careful to not
18377 		       introduce new this captures.  Legacy code can't
18378 		       be using lambdas anyway, so it's ok to be
18379 		       stricter.  */
18380 		    bool in_lambda = (current_class_type
18381 				      && LAMBDA_TYPE_P (current_class_type));
18382 		    char const *const msg
18383 		      = G_("%qD was not declared in this scope, "
18384 			   "and no declarations were found by "
18385 			   "argument-dependent lookup at the point "
18386 			   "of instantiation");
18387 
18388 		    bool diag = true;
18389 		    if (in_lambda)
18390 		      error_at (EXPR_LOC_OR_LOC (t, input_location),
18391 				msg, function);
18392 		    else
18393 		      diag = permerror (EXPR_LOC_OR_LOC (t, input_location),
18394 					msg, function);
18395 		    if (diag)
18396 		      {
18397 			tree fn = unq;
18398 
18399 			if (INDIRECT_REF_P (fn))
18400 			  fn = TREE_OPERAND (fn, 0);
18401 			if (is_overloaded_fn (fn))
18402 			  fn = get_first_fn (fn);
18403 
18404 			if (!DECL_P (fn))
18405 			  /* Can't say anything more.  */;
18406 			else if (DECL_CLASS_SCOPE_P (fn))
18407 			  {
18408 			    location_t loc = EXPR_LOC_OR_LOC (t,
18409 							      input_location);
18410 			    inform (loc,
18411 				    "declarations in dependent base %qT are "
18412 				    "not found by unqualified lookup",
18413 				    DECL_CLASS_CONTEXT (fn));
18414 			    if (current_class_ptr)
18415 			      inform (loc,
18416 				      "use %<this->%D%> instead", function);
18417 			    else
18418 			      inform (loc,
18419 				      "use %<%T::%D%> instead",
18420 				      current_class_name, function);
18421 			  }
18422 			else
18423 			  inform (DECL_SOURCE_LOCATION (fn),
18424 				  "%qD declared here, later in the "
18425 				  "translation unit", fn);
18426 			if (in_lambda)
18427 			  {
18428 			    release_tree_vector (call_args);
18429 			    RETURN (error_mark_node);
18430 			  }
18431 		      }
18432 
18433 		    function = unq;
18434 		  }
18435 	      }
18436 	    if (identifier_p (function))
18437 	      {
18438 		if (complain & tf_error)
18439 		  unqualified_name_lookup_error (function);
18440 		release_tree_vector (call_args);
18441 		RETURN (error_mark_node);
18442 	      }
18443 	  }
18444 
18445 	/* Remember that there was a reference to this entity.  */
18446 	if (function != NULL_TREE
18447 	    && DECL_P (function)
18448 	    && !mark_used (function, complain) && !(complain & tf_error))
18449 	  {
18450 	    release_tree_vector (call_args);
18451 	    RETURN (error_mark_node);
18452 	  }
18453 
18454 	/* Put back tf_decltype for the actual call.  */
18455 	complain |= decltype_flag;
18456 
18457 	if (function == NULL_TREE)
18458 	  switch (CALL_EXPR_IFN (t))
18459 	    {
18460 	    case IFN_LAUNDER:
18461 	      gcc_assert (nargs == 1);
18462 	      if (vec_safe_length (call_args) != 1)
18463 		{
18464 		  error_at (EXPR_LOC_OR_LOC (t, input_location),
18465 			    "wrong number of arguments to "
18466 			    "%<__builtin_launder%>");
18467 		  ret = error_mark_node;
18468 		}
18469 	      else
18470 		ret = finish_builtin_launder (EXPR_LOC_OR_LOC (t,
18471 							       input_location),
18472 					      (*call_args)[0], complain);
18473 	      break;
18474 
18475 	    default:
18476 	      /* Unsupported internal function with arguments.  */
18477 	      gcc_unreachable ();
18478 	    }
18479 	else if (TREE_CODE (function) == OFFSET_REF
18480 		 || TREE_CODE (function) == DOTSTAR_EXPR
18481 		 || TREE_CODE (function) == MEMBER_REF)
18482 	  ret = build_offset_ref_call_from_tree (function, &call_args,
18483 						 complain);
18484 	else if (TREE_CODE (function) == COMPONENT_REF)
18485 	  {
18486 	    tree instance = TREE_OPERAND (function, 0);
18487 	    tree fn = TREE_OPERAND (function, 1);
18488 
18489 	    if (processing_template_decl
18490 		&& (type_dependent_expression_p (instance)
18491 		    || (!BASELINK_P (fn)
18492 			&& TREE_CODE (fn) != FIELD_DECL)
18493 		    || type_dependent_expression_p (fn)
18494 		    || any_type_dependent_arguments_p (call_args)))
18495 	      ret = build_min_nt_call_vec (function, call_args);
18496 	    else if (!BASELINK_P (fn))
18497 	      ret = finish_call_expr (function, &call_args,
18498 				       /*disallow_virtual=*/false,
18499 				       /*koenig_p=*/false,
18500 				       complain);
18501 	    else
18502 	      ret = (build_new_method_call
18503 		      (instance, fn,
18504 		       &call_args, NULL_TREE,
18505 		       qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
18506 		       /*fn_p=*/NULL,
18507 		       complain));
18508 	  }
18509 	else
18510 	  ret = finish_call_expr (function, &call_args,
18511 				  /*disallow_virtual=*/qualified_p,
18512 				  koenig_p,
18513 				  complain);
18514 
18515 	release_tree_vector (call_args);
18516 
18517 	if (ret != error_mark_node)
18518 	  {
18519 	    bool op = CALL_EXPR_OPERATOR_SYNTAX (t);
18520 	    bool ord = CALL_EXPR_ORDERED_ARGS (t);
18521 	    bool rev = CALL_EXPR_REVERSE_ARGS (t);
18522 	    bool thk = CALL_FROM_THUNK_P (t);
18523 	    if (op || ord || rev || thk)
18524 	      {
18525 		function = extract_call_expr (ret);
18526 		CALL_EXPR_OPERATOR_SYNTAX (function) = op;
18527 		CALL_EXPR_ORDERED_ARGS (function) = ord;
18528 		CALL_EXPR_REVERSE_ARGS (function) = rev;
18529 		if (thk)
18530 		  {
18531 		    /* The thunk location is not interesting.  */
18532 		    SET_EXPR_LOCATION (function, UNKNOWN_LOCATION);
18533 		  }
18534 	      }
18535 	  }
18536 
18537 	RETURN (ret);
18538       }
18539 
18540     case COND_EXPR:
18541       {
18542 	tree cond = RECUR (TREE_OPERAND (t, 0));
18543 	cond = mark_rvalue_use (cond);
18544 	tree folded_cond = fold_non_dependent_expr (cond);
18545 	tree exp1, exp2;
18546 
18547 	if (TREE_CODE (folded_cond) == INTEGER_CST)
18548 	  {
18549 	    if (integer_zerop (folded_cond))
18550 	      {
18551 		++c_inhibit_evaluation_warnings;
18552 		exp1 = RECUR (TREE_OPERAND (t, 1));
18553 		--c_inhibit_evaluation_warnings;
18554 		exp2 = RECUR (TREE_OPERAND (t, 2));
18555 	      }
18556 	    else
18557 	      {
18558 		exp1 = RECUR (TREE_OPERAND (t, 1));
18559 		++c_inhibit_evaluation_warnings;
18560 		exp2 = RECUR (TREE_OPERAND (t, 2));
18561 		--c_inhibit_evaluation_warnings;
18562 	      }
18563 	    cond = folded_cond;
18564 	  }
18565 	else
18566 	  {
18567 	    exp1 = RECUR (TREE_OPERAND (t, 1));
18568 	    exp2 = RECUR (TREE_OPERAND (t, 2));
18569 	  }
18570 
18571 	warning_sentinel s(warn_duplicated_branches);
18572 	RETURN (build_x_conditional_expr (EXPR_LOCATION (t),
18573 					 cond, exp1, exp2, complain));
18574       }
18575 
18576     case PSEUDO_DTOR_EXPR:
18577       {
18578 	tree op0 = RECUR (TREE_OPERAND (t, 0));
18579 	tree op1 = RECUR (TREE_OPERAND (t, 1));
18580 	tree op2 = tsubst (TREE_OPERAND (t, 2), args, complain, in_decl);
18581 	RETURN (finish_pseudo_destructor_expr (op0, op1, op2,
18582 					       input_location));
18583       }
18584 
18585     case TREE_LIST:
18586       {
18587 	tree purpose, value, chain;
18588 
18589 	if (t == void_list_node)
18590 	  RETURN (t);
18591 
18592         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
18593             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
18594           {
18595             /* We have pack expansions, so expand those and
18596                create a new list out of it.  */
18597             tree purposevec = NULL_TREE;
18598             tree valuevec = NULL_TREE;
18599             tree chain;
18600             int i, len = -1;
18601 
18602             /* Expand the argument expressions.  */
18603             if (TREE_PURPOSE (t))
18604               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
18605                                                  complain, in_decl);
18606             if (TREE_VALUE (t))
18607               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
18608                                                complain, in_decl);
18609 
18610             /* Build the rest of the list.  */
18611             chain = TREE_CHAIN (t);
18612             if (chain && chain != void_type_node)
18613               chain = RECUR (chain);
18614 
18615             /* Determine the number of arguments.  */
18616             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
18617               {
18618                 len = TREE_VEC_LENGTH (purposevec);
18619                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
18620               }
18621             else if (TREE_CODE (valuevec) == TREE_VEC)
18622               len = TREE_VEC_LENGTH (valuevec);
18623             else
18624               {
18625                 /* Since we only performed a partial substitution into
18626                    the argument pack, we only RETURN (a single list
18627                    node.  */
18628                 if (purposevec == TREE_PURPOSE (t)
18629                     && valuevec == TREE_VALUE (t)
18630                     && chain == TREE_CHAIN (t))
18631                   RETURN (t);
18632 
18633                 RETURN (tree_cons (purposevec, valuevec, chain));
18634               }
18635 
18636             /* Convert the argument vectors into a TREE_LIST */
18637             i = len;
18638             while (i > 0)
18639               {
18640                 /* Grab the Ith values.  */
18641                 i--;
18642                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i)
18643 		                     : NULL_TREE;
18644                 value
18645 		  = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i))
18646                              : NULL_TREE;
18647 
18648                 /* Build the list (backwards).  */
18649                 chain = tree_cons (purpose, value, chain);
18650               }
18651 
18652             RETURN (chain);
18653           }
18654 
18655 	purpose = TREE_PURPOSE (t);
18656 	if (purpose)
18657 	  purpose = RECUR (purpose);
18658 	value = TREE_VALUE (t);
18659 	if (value)
18660 	  value = RECUR (value);
18661 	chain = TREE_CHAIN (t);
18662 	if (chain && chain != void_type_node)
18663 	  chain = RECUR (chain);
18664 	if (purpose == TREE_PURPOSE (t)
18665 	    && value == TREE_VALUE (t)
18666 	    && chain == TREE_CHAIN (t))
18667 	  RETURN (t);
18668 	RETURN (tree_cons (purpose, value, chain));
18669       }
18670 
18671     case COMPONENT_REF:
18672       {
18673 	tree object;
18674 	tree object_type;
18675 	tree member;
18676 	tree r;
18677 
18678 	object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
18679 						     args, complain, in_decl);
18680 	/* Remember that there was a reference to this entity.  */
18681 	if (DECL_P (object)
18682 	    && !mark_used (object, complain) && !(complain & tf_error))
18683 	  RETURN (error_mark_node);
18684 	object_type = TREE_TYPE (object);
18685 
18686 	member = TREE_OPERAND (t, 1);
18687 	if (BASELINK_P (member))
18688 	  member = tsubst_baselink (member,
18689 				    non_reference (TREE_TYPE (object)),
18690 				    args, complain, in_decl);
18691 	else
18692 	  member = tsubst_copy (member, args, complain, in_decl);
18693 	if (member == error_mark_node)
18694 	  RETURN (error_mark_node);
18695 
18696 	if (TREE_CODE (member) == FIELD_DECL)
18697 	  {
18698 	    r = finish_non_static_data_member (member, object, NULL_TREE);
18699 	    if (TREE_CODE (r) == COMPONENT_REF)
18700 	      REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
18701 	    RETURN (r);
18702 	  }
18703 	else if (type_dependent_expression_p (object))
18704 	  /* We can't do much here.  */;
18705 	else if (!CLASS_TYPE_P (object_type))
18706 	  {
18707 	    if (scalarish_type_p (object_type))
18708 	      {
18709 		tree s = NULL_TREE;
18710 		tree dtor = member;
18711 
18712 		if (TREE_CODE (dtor) == SCOPE_REF)
18713 		  {
18714 		    s = TREE_OPERAND (dtor, 0);
18715 		    dtor = TREE_OPERAND (dtor, 1);
18716 		  }
18717 		if (TREE_CODE (dtor) == BIT_NOT_EXPR)
18718 		  {
18719 		    dtor = TREE_OPERAND (dtor, 0);
18720 		    if (TYPE_P (dtor))
18721 		      RETURN (finish_pseudo_destructor_expr
18722 			      (object, s, dtor, input_location));
18723 		  }
18724 	      }
18725 	  }
18726 	else if (TREE_CODE (member) == SCOPE_REF
18727 		 && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
18728 	  {
18729 	    /* Lookup the template functions now that we know what the
18730 	       scope is.  */
18731 	    tree scope = TREE_OPERAND (member, 0);
18732 	    tree tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
18733 	    tree args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
18734 	    member = lookup_qualified_name (scope, tmpl,
18735 					    /*is_type_p=*/false,
18736 					    /*complain=*/false);
18737 	    if (BASELINK_P (member))
18738 	      {
18739 		BASELINK_FUNCTIONS (member)
18740 		  = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
18741 			      args);
18742 		member = (adjust_result_of_qualified_name_lookup
18743 			  (member, BINFO_TYPE (BASELINK_BINFO (member)),
18744 			   object_type));
18745 	      }
18746 	    else
18747 	      {
18748 		qualified_name_lookup_error (scope, tmpl, member,
18749 					     input_location);
18750 		RETURN (error_mark_node);
18751 	      }
18752 	  }
18753 	else if (TREE_CODE (member) == SCOPE_REF
18754 		 && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
18755 		 && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
18756 	  {
18757 	    if (complain & tf_error)
18758 	      {
18759 		if (TYPE_P (TREE_OPERAND (member, 0)))
18760 		  error ("%qT is not a class or namespace",
18761 			 TREE_OPERAND (member, 0));
18762 		else
18763 		  error ("%qD is not a class or namespace",
18764 			 TREE_OPERAND (member, 0));
18765 	      }
18766 	    RETURN (error_mark_node);
18767 	  }
18768 
18769 	r = finish_class_member_access_expr (object, member,
18770 					     /*template_p=*/false,
18771 					     complain);
18772 	if (TREE_CODE (r) == COMPONENT_REF)
18773 	  REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
18774 	RETURN (r);
18775       }
18776 
18777     case THROW_EXPR:
18778       RETURN (build_throw
18779 	(RECUR (TREE_OPERAND (t, 0))));
18780 
18781     case CONSTRUCTOR:
18782       {
18783 	vec<constructor_elt, va_gc> *n;
18784 	constructor_elt *ce;
18785 	unsigned HOST_WIDE_INT idx;
18786 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
18787 	bool process_index_p;
18788         int newlen;
18789         bool need_copy_p = false;
18790 	tree r;
18791 
18792 	if (type == error_mark_node)
18793 	  RETURN (error_mark_node);
18794 
18795 	/* We do not want to process the index of aggregate
18796 	   initializers as they are identifier nodes which will be
18797 	   looked up by digest_init.  */
18798 	process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
18799 
18800 	n = vec_safe_copy (CONSTRUCTOR_ELTS (t));
18801         newlen = vec_safe_length (n);
18802 	FOR_EACH_VEC_SAFE_ELT (n, idx, ce)
18803 	  {
18804 	    if (ce->index && process_index_p
18805 		/* An identifier index is looked up in the type
18806 		   being initialized, not the current scope.  */
18807 		&& TREE_CODE (ce->index) != IDENTIFIER_NODE)
18808 	      ce->index = RECUR (ce->index);
18809 
18810             if (PACK_EXPANSION_P (ce->value))
18811               {
18812                 /* Substitute into the pack expansion.  */
18813                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
18814                                                   in_decl);
18815 
18816 		if (ce->value == error_mark_node
18817 		    || PACK_EXPANSION_P (ce->value))
18818 		  ;
18819 		else if (TREE_VEC_LENGTH (ce->value) == 1)
18820                   /* Just move the argument into place.  */
18821                   ce->value = TREE_VEC_ELT (ce->value, 0);
18822                 else
18823                   {
18824                     /* Update the length of the final CONSTRUCTOR
18825                        arguments vector, and note that we will need to
18826                        copy.*/
18827                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
18828                     need_copy_p = true;
18829                   }
18830               }
18831             else
18832               ce->value = RECUR (ce->value);
18833 	  }
18834 
18835         if (need_copy_p)
18836           {
18837             vec<constructor_elt, va_gc> *old_n = n;
18838 
18839             vec_alloc (n, newlen);
18840             FOR_EACH_VEC_ELT (*old_n, idx, ce)
18841               {
18842                 if (TREE_CODE (ce->value) == TREE_VEC)
18843                   {
18844                     int i, len = TREE_VEC_LENGTH (ce->value);
18845                     for (i = 0; i < len; ++i)
18846                       CONSTRUCTOR_APPEND_ELT (n, 0,
18847                                               TREE_VEC_ELT (ce->value, i));
18848                   }
18849                 else
18850                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
18851               }
18852           }
18853 
18854 	r = build_constructor (init_list_type_node, n);
18855 	CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
18856 
18857 	if (TREE_HAS_CONSTRUCTOR (t))
18858 	  {
18859 	    fcl_t cl = fcl_functional;
18860 	    if (CONSTRUCTOR_C99_COMPOUND_LITERAL (t))
18861 	      cl = fcl_c99;
18862 	    RETURN (finish_compound_literal (type, r, complain, cl));
18863 	  }
18864 
18865 	TREE_TYPE (r) = type;
18866 	RETURN (r);
18867       }
18868 
18869     case TYPEID_EXPR:
18870       {
18871 	tree operand_0 = TREE_OPERAND (t, 0);
18872 	if (TYPE_P (operand_0))
18873 	  {
18874 	    operand_0 = tsubst (operand_0, args, complain, in_decl);
18875 	    RETURN (get_typeid (operand_0, complain));
18876 	  }
18877 	else
18878 	  {
18879 	    operand_0 = RECUR (operand_0);
18880 	    RETURN (build_typeid (operand_0, complain));
18881 	  }
18882       }
18883 
18884     case VAR_DECL:
18885       if (!args)
18886 	RETURN (t);
18887       /* Fall through */
18888 
18889     case PARM_DECL:
18890       {
18891 	tree r = tsubst_copy (t, args, complain, in_decl);
18892 	/* ??? We're doing a subset of finish_id_expression here.  */
18893 	if (VAR_P (r)
18894 	    && !processing_template_decl
18895 	    && !cp_unevaluated_operand
18896 	    && (TREE_STATIC (r) || DECL_EXTERNAL (r))
18897 	    && CP_DECL_THREAD_LOCAL_P (r))
18898 	  {
18899 	    if (tree wrap = get_tls_wrapper_fn (r))
18900 	      /* Replace an evaluated use of the thread_local variable with
18901 		 a call to its wrapper.  */
18902 	      r = build_cxx_call (wrap, 0, NULL, tf_warning_or_error);
18903 	  }
18904 	else if (outer_automatic_var_p (r))
18905 	  r = process_outer_var_ref (r, complain);
18906 
18907 	if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
18908 	  /* If the original type was a reference, we'll be wrapped in
18909 	     the appropriate INDIRECT_REF.  */
18910 	  r = convert_from_reference (r);
18911 	RETURN (r);
18912       }
18913 
18914     case VA_ARG_EXPR:
18915       {
18916 	tree op0 = RECUR (TREE_OPERAND (t, 0));
18917 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
18918 	RETURN (build_x_va_arg (EXPR_LOCATION (t), op0, type));
18919       }
18920 
18921     case OFFSETOF_EXPR:
18922       {
18923 	tree object_ptr
18924 	  = tsubst_copy_and_build (TREE_OPERAND (t, 1), args, complain,
18925 				   in_decl, /*function_p=*/false,
18926 				   /*integral_constant_expression_p=*/false);
18927 	RETURN (finish_offsetof (object_ptr,
18928 				 RECUR (TREE_OPERAND (t, 0)),
18929 				 EXPR_LOCATION (t)));
18930       }
18931 
18932     case ADDRESSOF_EXPR:
18933       RETURN (cp_build_addressof (EXPR_LOCATION (t),
18934 				  RECUR (TREE_OPERAND (t, 0)), complain));
18935 
18936     case TRAIT_EXPR:
18937       {
18938 	tree type1 = tsubst (TRAIT_EXPR_TYPE1 (t), args,
18939 			     complain, in_decl);
18940 
18941 	tree type2 = TRAIT_EXPR_TYPE2 (t);
18942 	if (type2 && TREE_CODE (type2) == TREE_LIST)
18943 	  type2 = RECUR (type2);
18944 	else if (type2)
18945 	  type2 = tsubst (type2, args, complain, in_decl);
18946 
18947 	RETURN (finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2));
18948       }
18949 
18950     case STMT_EXPR:
18951       {
18952 	tree old_stmt_expr = cur_stmt_expr;
18953 	tree stmt_expr = begin_stmt_expr ();
18954 
18955 	cur_stmt_expr = stmt_expr;
18956 	tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
18957 		     integral_constant_expression_p);
18958 	stmt_expr = finish_stmt_expr (stmt_expr, false);
18959 	cur_stmt_expr = old_stmt_expr;
18960 
18961 	/* If the resulting list of expression statement is empty,
18962 	   fold it further into void_node.  */
18963 	if (empty_expr_stmt_p (stmt_expr))
18964 	  stmt_expr = void_node;
18965 
18966 	RETURN (stmt_expr);
18967       }
18968 
18969     case LAMBDA_EXPR:
18970       {
18971 	tree r = tsubst_lambda_expr (t, args, complain, in_decl);
18972 
18973 	RETURN (build_lambda_object (r));
18974       }
18975 
18976     case TARGET_EXPR:
18977       /* We can get here for a constant initializer of non-dependent type.
18978          FIXME stop folding in cp_parser_initializer_clause.  */
18979       {
18980 	tree r = get_target_expr_sfinae (RECUR (TARGET_EXPR_INITIAL (t)),
18981 					 complain);
18982 	RETURN (r);
18983       }
18984 
18985     case TRANSACTION_EXPR:
18986       RETURN (tsubst_expr(t, args, complain, in_decl,
18987 	     integral_constant_expression_p));
18988 
18989     case PAREN_EXPR:
18990       RETURN (finish_parenthesized_expr (RECUR (TREE_OPERAND (t, 0))));
18991 
18992     case VEC_PERM_EXPR:
18993       {
18994 	tree op0 = RECUR (TREE_OPERAND (t, 0));
18995 	tree op1 = RECUR (TREE_OPERAND (t, 1));
18996 	tree op2 = RECUR (TREE_OPERAND (t, 2));
18997 	RETURN (build_x_vec_perm_expr (input_location, op0, op1, op2,
18998 				       complain));
18999       }
19000 
19001     case REQUIRES_EXPR:
19002       RETURN (tsubst_requires_expr (t, args, complain, in_decl));
19003 
19004     case RANGE_EXPR:
19005       /* No need to substitute further, a RANGE_EXPR will always be built
19006 	 with constant operands.  */
19007       RETURN (t);
19008 
19009     case NON_LVALUE_EXPR:
19010     case VIEW_CONVERT_EXPR:
19011       /* We should only see these for location wrapper nodes, or within
19012 	 instantiate_non_dependent_expr (when args is NULL_TREE).  */
19013       gcc_assert (location_wrapper_p (t) || args == NULL_TREE);
19014       if (location_wrapper_p (t))
19015 	RETURN (maybe_wrap_with_location (RECUR (TREE_OPERAND (t, 0)),
19016 					  EXPR_LOCATION (t)));
19017       /* fallthrough.  */
19018 
19019     default:
19020       /* Handle Objective-C++ constructs, if appropriate.  */
19021       {
19022 	tree subst
19023 	  = objcp_tsubst_copy_and_build (t, args, complain,
19024 					 in_decl, /*function_p=*/false);
19025 	if (subst)
19026 	  RETURN (subst);
19027       }
19028       RETURN (tsubst_copy (t, args, complain, in_decl));
19029     }
19030 
19031 #undef RECUR
19032 #undef RETURN
19033  out:
19034   input_location = loc;
19035   return retval;
19036 }
19037 
19038 /* Verify that the instantiated ARGS are valid. For type arguments,
19039    make sure that the type's linkage is ok. For non-type arguments,
19040    make sure they are constants if they are integral or enumerations.
19041    Emit an error under control of COMPLAIN, and return TRUE on error.  */
19042 
19043 static bool
check_instantiated_arg(tree tmpl,tree t,tsubst_flags_t complain)19044 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
19045 {
19046   if (dependent_template_arg_p (t))
19047     return false;
19048   if (ARGUMENT_PACK_P (t))
19049     {
19050       tree vec = ARGUMENT_PACK_ARGS (t);
19051       int len = TREE_VEC_LENGTH (vec);
19052       bool result = false;
19053       int i;
19054 
19055       for (i = 0; i < len; ++i)
19056 	if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
19057 	  result = true;
19058       return result;
19059     }
19060   else if (TYPE_P (t))
19061     {
19062       /* [basic.link]: A name with no linkage (notably, the name
19063 	 of a class or enumeration declared in a local scope)
19064 	 shall not be used to declare an entity with linkage.
19065 	 This implies that names with no linkage cannot be used as
19066 	 template arguments
19067 
19068 	 DR 757 relaxes this restriction for C++0x.  */
19069       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
19070 		 : no_linkage_check (t, /*relaxed_p=*/false));
19071 
19072       if (nt)
19073 	{
19074 	  /* DR 488 makes use of a type with no linkage cause
19075 	     type deduction to fail.  */
19076 	  if (complain & tf_error)
19077 	    {
19078 	      if (TYPE_UNNAMED_P (nt))
19079 		error ("%qT is/uses unnamed type", t);
19080 	      else
19081 		error ("template argument for %qD uses local type %qT",
19082 		       tmpl, t);
19083 	    }
19084 	  return true;
19085 	}
19086       /* In order to avoid all sorts of complications, we do not
19087 	 allow variably-modified types as template arguments.  */
19088       else if (variably_modified_type_p (t, NULL_TREE))
19089 	{
19090 	  if (complain & tf_error)
19091 	    error ("%qT is a variably modified type", t);
19092 	  return true;
19093 	}
19094     }
19095   /* Class template and alias template arguments should be OK.  */
19096   else if (DECL_TYPE_TEMPLATE_P (t))
19097     ;
19098   /* A non-type argument of integral or enumerated type must be a
19099      constant.  */
19100   else if (TREE_TYPE (t)
19101 	   && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
19102 	   && !REFERENCE_REF_P (t)
19103 	   && !TREE_CONSTANT (t))
19104     {
19105       if (complain & tf_error)
19106 	error ("integral expression %qE is not constant", t);
19107       return true;
19108     }
19109   return false;
19110 }
19111 
19112 static bool
check_instantiated_args(tree tmpl,tree args,tsubst_flags_t complain)19113 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
19114 {
19115   int ix, len = DECL_NTPARMS (tmpl);
19116   bool result = false;
19117 
19118   for (ix = 0; ix != len; ix++)
19119     {
19120       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
19121 	result = true;
19122     }
19123   if (result && (complain & tf_error))
19124     error ("  trying to instantiate %qD", tmpl);
19125   return result;
19126 }
19127 
19128 /* We're out of SFINAE context now, so generate diagnostics for the access
19129    errors we saw earlier when instantiating D from TMPL and ARGS.  */
19130 
19131 static void
recheck_decl_substitution(tree d,tree tmpl,tree args)19132 recheck_decl_substitution (tree d, tree tmpl, tree args)
19133 {
19134   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
19135   tree type = TREE_TYPE (pattern);
19136   location_t loc = input_location;
19137 
19138   push_access_scope (d);
19139   push_deferring_access_checks (dk_no_deferred);
19140   input_location = DECL_SOURCE_LOCATION (pattern);
19141   tsubst (type, args, tf_warning_or_error, d);
19142   input_location = loc;
19143   pop_deferring_access_checks ();
19144   pop_access_scope (d);
19145 }
19146 
19147 /* Instantiate the indicated variable, function, or alias template TMPL with
19148    the template arguments in TARG_PTR.  */
19149 
19150 static tree
instantiate_template_1(tree tmpl,tree orig_args,tsubst_flags_t complain)19151 instantiate_template_1 (tree tmpl, tree orig_args, tsubst_flags_t complain)
19152 {
19153   tree targ_ptr = orig_args;
19154   tree fndecl;
19155   tree gen_tmpl;
19156   tree spec;
19157   bool access_ok = true;
19158 
19159   if (tmpl == error_mark_node)
19160     return error_mark_node;
19161 
19162   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
19163 
19164   /* If this function is a clone, handle it specially.  */
19165   if (DECL_CLONED_FUNCTION_P (tmpl))
19166     {
19167       tree spec;
19168       tree clone;
19169 
19170       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
19171 	 DECL_CLONED_FUNCTION.  */
19172       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
19173 				   targ_ptr, complain);
19174       if (spec == error_mark_node)
19175 	return error_mark_node;
19176 
19177       /* Look for the clone.  */
19178       FOR_EACH_CLONE (clone, spec)
19179 	if (DECL_NAME (clone) == DECL_NAME (tmpl))
19180 	  return clone;
19181       /* We should always have found the clone by now.  */
19182       gcc_unreachable ();
19183       return NULL_TREE;
19184     }
19185 
19186   if (targ_ptr == error_mark_node)
19187     return error_mark_node;
19188 
19189   /* Check to see if we already have this specialization.  */
19190   gen_tmpl = most_general_template (tmpl);
19191   if (TMPL_ARGS_DEPTH (targ_ptr)
19192       < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl)))
19193     /* targ_ptr only has the innermost template args, so add the outer ones
19194        from tmpl, which could be either a partial instantiation or gen_tmpl (in
19195        the case of a non-dependent call within a template definition).  */
19196     targ_ptr = (add_outermost_template_args
19197 		(DECL_TI_ARGS (DECL_TEMPLATE_RESULT (tmpl)),
19198 		 targ_ptr));
19199 
19200   /* It would be nice to avoid hashing here and then again in tsubst_decl,
19201      but it doesn't seem to be on the hot path.  */
19202   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
19203 
19204   gcc_assert (tmpl == gen_tmpl
19205 	      || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
19206 		  == spec)
19207 	      || fndecl == NULL_TREE);
19208 
19209   if (spec != NULL_TREE)
19210     {
19211       if (FNDECL_HAS_ACCESS_ERRORS (spec))
19212 	{
19213 	  if (complain & tf_error)
19214 	    recheck_decl_substitution (spec, gen_tmpl, targ_ptr);
19215 	  return error_mark_node;
19216 	}
19217       return spec;
19218     }
19219 
19220   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
19221 			       complain))
19222     return error_mark_node;
19223 
19224   /* We are building a FUNCTION_DECL, during which the access of its
19225      parameters and return types have to be checked.  However this
19226      FUNCTION_DECL which is the desired context for access checking
19227      is not built yet.  We solve this chicken-and-egg problem by
19228      deferring all checks until we have the FUNCTION_DECL.  */
19229   push_deferring_access_checks (dk_deferred);
19230 
19231   /* Instantiation of the function happens in the context of the function
19232      template, not the context of the overload resolution we're doing.  */
19233   push_to_top_level ();
19234   /* If there are dependent arguments, e.g. because we're doing partial
19235      ordering, make sure processing_template_decl stays set.  */
19236   if (uses_template_parms (targ_ptr))
19237     ++processing_template_decl;
19238   if (DECL_CLASS_SCOPE_P (gen_tmpl))
19239     {
19240       tree ctx = tsubst_aggr_type (DECL_CONTEXT (gen_tmpl), targ_ptr,
19241 				   complain, gen_tmpl, true);
19242       push_nested_class (ctx);
19243     }
19244 
19245   tree pattern = DECL_TEMPLATE_RESULT (gen_tmpl);
19246 
19247   fndecl = NULL_TREE;
19248   if (VAR_P (pattern))
19249     {
19250       /* We need to determine if we're using a partial or explicit
19251 	 specialization now, because the type of the variable could be
19252 	 different.  */
19253       tree tid = lookup_template_variable (gen_tmpl, targ_ptr);
19254       tree elt = most_specialized_partial_spec (tid, complain);
19255       if (elt == error_mark_node)
19256 	pattern = error_mark_node;
19257       else if (elt)
19258 	{
19259 	  tree partial_tmpl = TREE_VALUE (elt);
19260 	  tree partial_args = TREE_PURPOSE (elt);
19261 	  tree partial_pat = DECL_TEMPLATE_RESULT (partial_tmpl);
19262 	  fndecl = tsubst (partial_pat, partial_args, complain, gen_tmpl);
19263 	}
19264     }
19265 
19266   /* Substitute template parameters to obtain the specialization.  */
19267   if (fndecl == NULL_TREE)
19268     fndecl = tsubst (pattern, targ_ptr, complain, gen_tmpl);
19269   if (DECL_CLASS_SCOPE_P (gen_tmpl))
19270     pop_nested_class ();
19271   pop_from_top_level ();
19272 
19273   if (fndecl == error_mark_node)
19274     {
19275       pop_deferring_access_checks ();
19276       return error_mark_node;
19277     }
19278 
19279   /* The DECL_TI_TEMPLATE should always be the immediate parent
19280      template, not the most general template.  */
19281   DECL_TI_TEMPLATE (fndecl) = tmpl;
19282   DECL_TI_ARGS (fndecl) = targ_ptr;
19283 
19284   /* Now we know the specialization, compute access previously
19285      deferred.  Do no access control for inheriting constructors,
19286      as we already checked access for the inherited constructor.  */
19287   if (!(flag_new_inheriting_ctors
19288 	&& DECL_INHERITED_CTOR (fndecl)))
19289     {
19290       push_access_scope (fndecl);
19291       if (!perform_deferred_access_checks (complain))
19292 	access_ok = false;
19293       pop_access_scope (fndecl);
19294     }
19295   pop_deferring_access_checks ();
19296 
19297   /* If we've just instantiated the main entry point for a function,
19298      instantiate all the alternate entry points as well.  We do this
19299      by cloning the instantiation of the main entry point, not by
19300      instantiating the template clones.  */
19301   if (DECL_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (DECL_CHAIN (gen_tmpl)))
19302     clone_function_decl (fndecl, /*update_methods=*/false);
19303 
19304   if (!access_ok)
19305     {
19306       if (!(complain & tf_error))
19307 	{
19308 	  /* Remember to reinstantiate when we're out of SFINAE so the user
19309 	     can see the errors.  */
19310 	  FNDECL_HAS_ACCESS_ERRORS (fndecl) = true;
19311 	}
19312       return error_mark_node;
19313     }
19314   return fndecl;
19315 }
19316 
19317 /* Wrapper for instantiate_template_1.  */
19318 
19319 tree
instantiate_template(tree tmpl,tree orig_args,tsubst_flags_t complain)19320 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
19321 {
19322   tree ret;
19323   timevar_push (TV_TEMPLATE_INST);
19324   ret = instantiate_template_1 (tmpl, orig_args,  complain);
19325   timevar_pop (TV_TEMPLATE_INST);
19326   return ret;
19327 }
19328 
19329 /* Instantiate the alias template TMPL with ARGS.  Also push a template
19330    instantiation level, which instantiate_template doesn't do because
19331    functions and variables have sufficient context established by the
19332    callers.  */
19333 
19334 static tree
instantiate_alias_template(tree tmpl,tree args,tsubst_flags_t complain)19335 instantiate_alias_template (tree tmpl, tree args, tsubst_flags_t complain)
19336 {
19337   if (tmpl == error_mark_node || args == error_mark_node)
19338     return error_mark_node;
19339   if (!push_tinst_level (tmpl, args))
19340     return error_mark_node;
19341 
19342   args =
19343     coerce_innermost_template_parms (DECL_TEMPLATE_PARMS (tmpl),
19344 				     args, tmpl, complain,
19345 				     /*require_all_args=*/true,
19346 				     /*use_default_args=*/true);
19347 
19348   tree r = instantiate_template (tmpl, args, complain);
19349   pop_tinst_level ();
19350 
19351   return r;
19352 }
19353 
19354 /* PARM is a template parameter pack for FN.  Returns true iff
19355    PARM is used in a deducible way in the argument list of FN.  */
19356 
19357 static bool
pack_deducible_p(tree parm,tree fn)19358 pack_deducible_p (tree parm, tree fn)
19359 {
19360   tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
19361   for (; t; t = TREE_CHAIN (t))
19362     {
19363       tree type = TREE_VALUE (t);
19364       tree packs;
19365       if (!PACK_EXPANSION_P (type))
19366 	continue;
19367       for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
19368 	   packs; packs = TREE_CHAIN (packs))
19369 	if (template_args_equal (TREE_VALUE (packs), parm))
19370 	  {
19371 	    /* The template parameter pack is used in a function parameter
19372 	       pack.  If this is the end of the parameter list, the
19373 	       template parameter pack is deducible.  */
19374 	    if (TREE_CHAIN (t) == void_list_node)
19375 	      return true;
19376 	    else
19377 	      /* Otherwise, not.  Well, it could be deduced from
19378 		 a non-pack parameter, but doing so would end up with
19379 		 a deduction mismatch, so don't bother.  */
19380 	      return false;
19381 	  }
19382     }
19383   /* The template parameter pack isn't used in any function parameter
19384      packs, but it might be used deeper, e.g. tuple<Args...>.  */
19385   return true;
19386 }
19387 
19388 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
19389    NARGS elements of the arguments that are being used when calling
19390    it.  TARGS is a vector into which the deduced template arguments
19391    are placed.
19392 
19393    Returns either a FUNCTION_DECL for the matching specialization of FN or
19394    NULL_TREE if no suitable specialization can be found.  If EXPLAIN_P is
19395    true, diagnostics will be printed to explain why it failed.
19396 
19397    If FN is a conversion operator, or we are trying to produce a specific
19398    specialization, RETURN_TYPE is the return type desired.
19399 
19400    The EXPLICIT_TARGS are explicit template arguments provided via a
19401    template-id.
19402 
19403    The parameter STRICT is one of:
19404 
19405    DEDUCE_CALL:
19406      We are deducing arguments for a function call, as in
19407      [temp.deduct.call].  If RETURN_TYPE is non-null, we are
19408      deducing arguments for a call to the result of a conversion
19409      function template, as in [over.call.object].
19410 
19411    DEDUCE_CONV:
19412      We are deducing arguments for a conversion function, as in
19413      [temp.deduct.conv].
19414 
19415    DEDUCE_EXACT:
19416      We are deducing arguments when doing an explicit instantiation
19417      as in [temp.explicit], when determining an explicit specialization
19418      as in [temp.expl.spec], or when taking the address of a function
19419      template, as in [temp.deduct.funcaddr].  */
19420 
19421 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)19422 fn_type_unification (tree fn,
19423 		     tree explicit_targs,
19424 		     tree targs,
19425 		     const tree *args,
19426 		     unsigned int nargs,
19427 		     tree return_type,
19428 		     unification_kind_t strict,
19429 		     int flags,
19430 		     bool explain_p,
19431 		     bool decltype_p)
19432 {
19433   tree parms;
19434   tree fntype;
19435   tree decl = NULL_TREE;
19436   tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
19437   bool ok;
19438   static int deduction_depth;
19439 
19440   tree orig_fn = fn;
19441   if (flag_new_inheriting_ctors)
19442     fn = strip_inheriting_ctors (fn);
19443 
19444   tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
19445   tree r = error_mark_node;
19446 
19447   tree full_targs = targs;
19448   if (TMPL_ARGS_DEPTH (targs)
19449       < TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (fn)))
19450     full_targs = (add_outermost_template_args
19451 		  (DECL_TI_ARGS (DECL_TEMPLATE_RESULT (fn)),
19452 		   targs));
19453 
19454   if (decltype_p)
19455     complain |= tf_decltype;
19456 
19457   /* In C++0x, it's possible to have a function template whose type depends
19458      on itself recursively.  This is most obvious with decltype, but can also
19459      occur with enumeration scope (c++/48969).  So we need to catch infinite
19460      recursion and reject the substitution at deduction time; this function
19461      will return error_mark_node for any repeated substitution.
19462 
19463      This also catches excessive recursion such as when f<N> depends on
19464      f<N-1> across all integers, and returns error_mark_node for all the
19465      substitutions back up to the initial one.
19466 
19467      This is, of course, not reentrant.  */
19468   if (excessive_deduction_depth)
19469     return error_mark_node;
19470   ++deduction_depth;
19471 
19472   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
19473 
19474   fntype = TREE_TYPE (fn);
19475   if (explicit_targs)
19476     {
19477       /* [temp.deduct]
19478 
19479 	 The specified template arguments must match the template
19480 	 parameters in kind (i.e., type, nontype, template), and there
19481 	 must not be more arguments than there are parameters;
19482 	 otherwise type deduction fails.
19483 
19484 	 Nontype arguments must match the types of the corresponding
19485 	 nontype template parameters, or must be convertible to the
19486 	 types of the corresponding nontype parameters as specified in
19487 	 _temp.arg.nontype_, otherwise type deduction fails.
19488 
19489 	 All references in the function type of the function template
19490 	 to the corresponding template parameters are replaced by the
19491 	 specified template argument values.  If a substitution in a
19492 	 template parameter or in the function type of the function
19493 	 template results in an invalid type, type deduction fails.  */
19494       int i, len = TREE_VEC_LENGTH (tparms);
19495       location_t loc = input_location;
19496       bool incomplete = false;
19497 
19498       if (explicit_targs == error_mark_node)
19499 	goto fail;
19500 
19501       if (TMPL_ARGS_DEPTH (explicit_targs)
19502 	  < TMPL_ARGS_DEPTH (full_targs))
19503 	explicit_targs = add_outermost_template_args (full_targs,
19504 						      explicit_targs);
19505 
19506       /* Adjust any explicit template arguments before entering the
19507 	 substitution context.  */
19508       explicit_targs
19509 	= (coerce_template_parms (tparms, explicit_targs, NULL_TREE,
19510 				  complain,
19511 				  /*require_all_args=*/false,
19512 				  /*use_default_args=*/false));
19513       if (explicit_targs == error_mark_node)
19514 	goto fail;
19515 
19516       /* Substitute the explicit args into the function type.  This is
19517 	 necessary so that, for instance, explicitly declared function
19518 	 arguments can match null pointed constants.  If we were given
19519 	 an incomplete set of explicit args, we must not do semantic
19520 	 processing during substitution as we could create partial
19521 	 instantiations.  */
19522       for (i = 0; i < len; i++)
19523         {
19524           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
19525           bool parameter_pack = false;
19526 	  tree targ = TREE_VEC_ELT (explicit_targs, i);
19527 
19528           /* Dig out the actual parm.  */
19529           if (TREE_CODE (parm) == TYPE_DECL
19530               || TREE_CODE (parm) == TEMPLATE_DECL)
19531             {
19532               parm = TREE_TYPE (parm);
19533               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
19534             }
19535           else if (TREE_CODE (parm) == PARM_DECL)
19536             {
19537               parm = DECL_INITIAL (parm);
19538               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
19539             }
19540 
19541 	  if (!parameter_pack && targ == NULL_TREE)
19542 	    /* No explicit argument for this template parameter.  */
19543 	    incomplete = true;
19544 
19545           if (parameter_pack && pack_deducible_p (parm, fn))
19546             {
19547               /* Mark the argument pack as "incomplete". We could
19548                  still deduce more arguments during unification.
19549 	         We remove this mark in type_unification_real.  */
19550               if (targ)
19551                 {
19552                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
19553                   ARGUMENT_PACK_EXPLICIT_ARGS (targ)
19554                     = ARGUMENT_PACK_ARGS (targ);
19555                 }
19556 
19557               /* We have some incomplete argument packs.  */
19558               incomplete = true;
19559             }
19560         }
19561 
19562       if (!push_tinst_level (fn, explicit_targs))
19563 	{
19564 	  excessive_deduction_depth = true;
19565 	  goto fail;
19566 	}
19567       processing_template_decl += incomplete;
19568       input_location = DECL_SOURCE_LOCATION (fn);
19569       /* Ignore any access checks; we'll see them again in
19570 	 instantiate_template and they might have the wrong
19571 	 access path at this point.  */
19572       push_deferring_access_checks (dk_deferred);
19573       fntype = tsubst (TREE_TYPE (fn), explicit_targs,
19574 		       complain | tf_partial | tf_fndecl_type, NULL_TREE);
19575       pop_deferring_access_checks ();
19576       input_location = loc;
19577       processing_template_decl -= incomplete;
19578       pop_tinst_level ();
19579 
19580       if (fntype == error_mark_node)
19581 	goto fail;
19582 
19583       /* Place the explicitly specified arguments in TARGS.  */
19584       explicit_targs = INNERMOST_TEMPLATE_ARGS (explicit_targs);
19585       for (i = NUM_TMPL_ARGS (explicit_targs); i--;)
19586 	TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (explicit_targs, i);
19587     }
19588 
19589   /* Never do unification on the 'this' parameter.  */
19590   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
19591 
19592   if (return_type && strict == DEDUCE_CALL)
19593     {
19594       /* We're deducing for a call to the result of a template conversion
19595          function.  The parms we really want are in return_type.  */
19596       if (POINTER_TYPE_P (return_type))
19597 	return_type = TREE_TYPE (return_type);
19598       parms = TYPE_ARG_TYPES (return_type);
19599     }
19600   else if (return_type)
19601     {
19602       tree *new_args;
19603 
19604       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
19605       new_args = XALLOCAVEC (tree, nargs + 1);
19606       new_args[0] = return_type;
19607       memcpy (new_args + 1, args, nargs * sizeof (tree));
19608       args = new_args;
19609       ++nargs;
19610     }
19611 
19612   /* We allow incomplete unification without an error message here
19613      because the standard doesn't seem to explicitly prohibit it.  Our
19614      callers must be ready to deal with unification failures in any
19615      event.  */
19616 
19617   /* If we aren't explaining yet, push tinst context so we can see where
19618      any errors (e.g. from class instantiations triggered by instantiation
19619      of default template arguments) come from.  If we are explaining, this
19620      context is redundant.  */
19621   if (!explain_p && !push_tinst_level (fn, targs))
19622     {
19623       excessive_deduction_depth = true;
19624       goto fail;
19625     }
19626 
19627   /* type_unification_real will pass back any access checks from default
19628      template argument substitution.  */
19629   vec<deferred_access_check, va_gc> *checks;
19630   checks = NULL;
19631 
19632   ok = !type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
19633 			       full_targs, parms, args, nargs, /*subr=*/0,
19634 			       strict, flags, &checks, explain_p);
19635   if (!explain_p)
19636     pop_tinst_level ();
19637   if (!ok)
19638     goto fail;
19639 
19640   /* Now that we have bindings for all of the template arguments,
19641      ensure that the arguments deduced for the template template
19642      parameters have compatible template parameter lists.  We cannot
19643      check this property before we have deduced all template
19644      arguments, because the template parameter types of a template
19645      template parameter might depend on prior template parameters
19646      deduced after the template template parameter.  The following
19647      ill-formed example illustrates this issue:
19648 
19649        template<typename T, template<T> class C> void f(C<5>, T);
19650 
19651        template<int N> struct X {};
19652 
19653        void g() {
19654          f(X<5>(), 5l); // error: template argument deduction fails
19655        }
19656 
19657      The template parameter list of 'C' depends on the template type
19658      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
19659      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
19660      time that we deduce 'C'.  */
19661   if (!template_template_parm_bindings_ok_p
19662            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
19663     {
19664       unify_inconsistent_template_template_parameters (explain_p);
19665       goto fail;
19666     }
19667 
19668   /* All is well so far.  Now, check:
19669 
19670      [temp.deduct]
19671 
19672      When all template arguments have been deduced, all uses of
19673      template parameters in nondeduced contexts are replaced with
19674      the corresponding deduced argument values.  If the
19675      substitution results in an invalid type, as described above,
19676      type deduction fails.  */
19677   if (!push_tinst_level (fn, targs))
19678     {
19679       excessive_deduction_depth = true;
19680       goto fail;
19681     }
19682 
19683   /* Also collect access checks from the instantiation.  */
19684   reopen_deferring_access_checks (checks);
19685 
19686   decl = instantiate_template (fn, targs, complain);
19687 
19688   checks = get_deferred_access_checks ();
19689   pop_deferring_access_checks ();
19690 
19691   pop_tinst_level ();
19692 
19693   if (decl == error_mark_node)
19694     goto fail;
19695 
19696   /* Now perform any access checks encountered during substitution.  */
19697   push_access_scope (decl);
19698   ok = perform_access_checks (checks, complain);
19699   pop_access_scope (decl);
19700   if (!ok)
19701     goto fail;
19702 
19703   /* If we're looking for an exact match, check that what we got
19704      is indeed an exact match.  It might not be if some template
19705      parameters are used in non-deduced contexts.  But don't check
19706      for an exact match if we have dependent template arguments;
19707      in that case we're doing partial ordering, and we already know
19708      that we have two candidates that will provide the actual type.  */
19709   if (strict == DEDUCE_EXACT && !any_dependent_template_arguments_p (targs))
19710     {
19711       tree substed = TREE_TYPE (decl);
19712       unsigned int i;
19713 
19714       tree sarg
19715 	= skip_artificial_parms_for (decl, TYPE_ARG_TYPES (substed));
19716       if (return_type)
19717 	sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
19718       for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
19719 	if (!same_type_p (args[i], TREE_VALUE (sarg)))
19720 	  {
19721 	    unify_type_mismatch (explain_p, args[i],
19722 				 TREE_VALUE (sarg));
19723 	    goto fail;
19724 	  }
19725     }
19726 
19727   /* After doing deduction with the inherited constructor, actually return an
19728      instantiation of the inheriting constructor.  */
19729   if (orig_fn != fn)
19730     decl = instantiate_template (orig_fn, targs, complain);
19731 
19732   r = decl;
19733 
19734  fail:
19735   --deduction_depth;
19736   if (excessive_deduction_depth)
19737     {
19738       if (deduction_depth == 0)
19739 	/* Reset once we're all the way out.  */
19740 	excessive_deduction_depth = false;
19741     }
19742 
19743   return r;
19744 }
19745 
19746 /* Adjust types before performing type deduction, as described in
19747    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
19748    sections are symmetric.  PARM is the type of a function parameter
19749    or the return type of the conversion function.  ARG is the type of
19750    the argument passed to the call, or the type of the value
19751    initialized with the result of the conversion function.
19752    ARG_EXPR is the original argument expression, which may be null.  */
19753 
19754 static int
maybe_adjust_types_for_deduction(unification_kind_t strict,tree * parm,tree * arg,tree arg_expr)19755 maybe_adjust_types_for_deduction (unification_kind_t strict,
19756 				  tree* parm,
19757 				  tree* arg,
19758 				  tree arg_expr)
19759 {
19760   int result = 0;
19761 
19762   switch (strict)
19763     {
19764     case DEDUCE_CALL:
19765       break;
19766 
19767     case DEDUCE_CONV:
19768       /* Swap PARM and ARG throughout the remainder of this
19769 	 function; the handling is precisely symmetric since PARM
19770 	 will initialize ARG rather than vice versa.  */
19771       std::swap (parm, arg);
19772       break;
19773 
19774     case DEDUCE_EXACT:
19775       /* Core issue #873: Do the DR606 thing (see below) for these cases,
19776 	 too, but here handle it by stripping the reference from PARM
19777 	 rather than by adding it to ARG.  */
19778       if (TREE_CODE (*parm) == REFERENCE_TYPE
19779 	  && TYPE_REF_IS_RVALUE (*parm)
19780 	  && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
19781 	  && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
19782 	  && TREE_CODE (*arg) == REFERENCE_TYPE
19783 	  && !TYPE_REF_IS_RVALUE (*arg))
19784 	*parm = TREE_TYPE (*parm);
19785       /* Nothing else to do in this case.  */
19786       return 0;
19787 
19788     default:
19789       gcc_unreachable ();
19790     }
19791 
19792   if (TREE_CODE (*parm) != REFERENCE_TYPE)
19793     {
19794       /* [temp.deduct.call]
19795 
19796 	 If P is not a reference type:
19797 
19798 	 --If A is an array type, the pointer type produced by the
19799 	 array-to-pointer standard conversion (_conv.array_) is
19800 	 used in place of A for type deduction; otherwise,
19801 
19802 	 --If A is a function type, the pointer type produced by
19803 	 the function-to-pointer standard conversion
19804 	 (_conv.func_) is used in place of A for type deduction;
19805 	 otherwise,
19806 
19807 	 --If A is a cv-qualified type, the top level
19808 	 cv-qualifiers of A's type are ignored for type
19809 	 deduction.  */
19810       if (TREE_CODE (*arg) == ARRAY_TYPE)
19811 	*arg = build_pointer_type (TREE_TYPE (*arg));
19812       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
19813 	*arg = build_pointer_type (*arg);
19814       else
19815 	*arg = TYPE_MAIN_VARIANT (*arg);
19816     }
19817 
19818   /* [14.8.2.1/3 temp.deduct.call], "A forwarding reference is an rvalue
19819      reference to a cv-unqualified template parameter that does not represent a
19820      template parameter of a class template (during class template argument
19821      deduction (13.3.1.8)). If P is a forwarding reference and the argument is
19822      an lvalue, the type "lvalue reference to A" is used in place of A for type
19823      deduction. */
19824   if (TREE_CODE (*parm) == REFERENCE_TYPE
19825       && TYPE_REF_IS_RVALUE (*parm)
19826       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
19827       && !TEMPLATE_TYPE_PARM_FOR_CLASS (TREE_TYPE (*parm))
19828       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
19829       && (arg_expr ? lvalue_p (arg_expr)
19830 	  /* try_one_overload doesn't provide an arg_expr, but
19831 	     functions are always lvalues.  */
19832 	  : TREE_CODE (*arg) == FUNCTION_TYPE))
19833     *arg = build_reference_type (*arg);
19834 
19835   /* [temp.deduct.call]
19836 
19837      If P is a cv-qualified type, the top level cv-qualifiers
19838      of P's type are ignored for type deduction.  If P is a
19839      reference type, the type referred to by P is used for
19840      type deduction.  */
19841   *parm = TYPE_MAIN_VARIANT (*parm);
19842   if (TREE_CODE (*parm) == REFERENCE_TYPE)
19843     {
19844       *parm = TREE_TYPE (*parm);
19845       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
19846     }
19847 
19848   /* DR 322. For conversion deduction, remove a reference type on parm
19849      too (which has been swapped into ARG).  */
19850   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
19851     *arg = TREE_TYPE (*arg);
19852 
19853   return result;
19854 }
19855 
19856 /* Subroutine of unify_one_argument.  PARM is a function parameter of a
19857    template which does contain any deducible template parameters; check if
19858    ARG is a suitable match for it.  STRICT, FLAGS and EXPLAIN_P are as in
19859    unify_one_argument.  */
19860 
19861 static int
check_non_deducible_conversion(tree parm,tree arg,int strict,int flags,bool explain_p)19862 check_non_deducible_conversion (tree parm, tree arg, int strict,
19863 				int flags, bool explain_p)
19864 {
19865   tree type;
19866 
19867   if (!TYPE_P (arg))
19868     type = TREE_TYPE (arg);
19869   else
19870     type = arg;
19871 
19872   if (same_type_p (parm, type))
19873     return unify_success (explain_p);
19874 
19875   if (strict == DEDUCE_CONV)
19876     {
19877       if (can_convert_arg (type, parm, NULL_TREE, flags,
19878 			   explain_p ? tf_warning_or_error : tf_none))
19879 	return unify_success (explain_p);
19880     }
19881   else if (strict != DEDUCE_EXACT)
19882     {
19883       if (can_convert_arg (parm, type,
19884 			   TYPE_P (arg) ? NULL_TREE : arg,
19885 			   flags, explain_p ? tf_warning_or_error : tf_none))
19886 	return unify_success (explain_p);
19887     }
19888 
19889   if (strict == DEDUCE_EXACT)
19890     return unify_type_mismatch (explain_p, parm, arg);
19891   else
19892     return unify_arg_conversion (explain_p, parm, type, arg);
19893 }
19894 
19895 static bool uses_deducible_template_parms (tree type);
19896 
19897 /* Returns true iff the expression EXPR is one from which a template
19898    argument can be deduced.  In other words, if it's an undecorated
19899    use of a template non-type parameter.  */
19900 
19901 static bool
deducible_expression(tree expr)19902 deducible_expression (tree expr)
19903 {
19904   /* Strip implicit conversions.  */
19905   while (CONVERT_EXPR_P (expr))
19906     expr = TREE_OPERAND (expr, 0);
19907   return (TREE_CODE (expr) == TEMPLATE_PARM_INDEX);
19908 }
19909 
19910 /* Returns true iff the array domain DOMAIN uses a template parameter in a
19911    deducible way; that is, if it has a max value of <PARM> - 1.  */
19912 
19913 static bool
deducible_array_bound(tree domain)19914 deducible_array_bound (tree domain)
19915 {
19916   if (domain == NULL_TREE)
19917     return false;
19918 
19919   tree max = TYPE_MAX_VALUE (domain);
19920   if (TREE_CODE (max) != MINUS_EXPR)
19921     return false;
19922 
19923   return deducible_expression (TREE_OPERAND (max, 0));
19924 }
19925 
19926 /* Returns true iff the template arguments ARGS use a template parameter
19927    in a deducible way.  */
19928 
19929 static bool
deducible_template_args(tree args)19930 deducible_template_args (tree args)
19931 {
19932   for (int i = 0; i < TREE_VEC_LENGTH (args); ++i)
19933     {
19934       bool deducible;
19935       tree elt = TREE_VEC_ELT (args, i);
19936       if (ARGUMENT_PACK_P (elt))
19937 	deducible = deducible_template_args (ARGUMENT_PACK_ARGS (elt));
19938       else
19939 	{
19940 	  if (PACK_EXPANSION_P (elt))
19941 	    elt = PACK_EXPANSION_PATTERN (elt);
19942 	  if (TREE_CODE (elt) == TEMPLATE_TEMPLATE_PARM)
19943 	    deducible = true;
19944 	  else if (TYPE_P (elt))
19945 	    deducible = uses_deducible_template_parms (elt);
19946 	  else
19947 	    deducible = deducible_expression (elt);
19948 	}
19949       if (deducible)
19950 	return true;
19951     }
19952   return false;
19953 }
19954 
19955 /* Returns true iff TYPE contains any deducible references to template
19956    parameters, as per 14.8.2.5.  */
19957 
19958 static bool
uses_deducible_template_parms(tree type)19959 uses_deducible_template_parms (tree type)
19960 {
19961   if (PACK_EXPANSION_P (type))
19962     type = PACK_EXPANSION_PATTERN (type);
19963 
19964   /* T
19965      cv-list T
19966      TT<T>
19967      TT<i>
19968      TT<> */
19969   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
19970       || TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
19971     return true;
19972 
19973   /* T*
19974      T&
19975      T&&  */
19976   if (POINTER_TYPE_P (type))
19977     return uses_deducible_template_parms (TREE_TYPE (type));
19978 
19979   /* T[integer-constant ]
19980      type [i]  */
19981   if (TREE_CODE (type) == ARRAY_TYPE)
19982     return (uses_deducible_template_parms (TREE_TYPE (type))
19983 	    || deducible_array_bound (TYPE_DOMAIN (type)));
19984 
19985   /* T type ::*
19986      type T::*
19987      T T::*
19988      T (type ::*)()
19989      type (T::*)()
19990      type (type ::*)(T)
19991      type (T::*)(T)
19992      T (type ::*)(T)
19993      T (T::*)()
19994      T (T::*)(T) */
19995   if (TYPE_PTRMEM_P (type))
19996     return (uses_deducible_template_parms (TYPE_PTRMEM_CLASS_TYPE (type))
19997 	    || (uses_deducible_template_parms
19998 		(TYPE_PTRMEM_POINTED_TO_TYPE (type))));
19999 
20000   /* template-name <T> (where template-name refers to a class template)
20001      template-name <i> (where template-name refers to a class template) */
20002   if (CLASS_TYPE_P (type)
20003       && CLASSTYPE_TEMPLATE_INFO (type)
20004       && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type)))
20005     return deducible_template_args (INNERMOST_TEMPLATE_ARGS
20006 				    (CLASSTYPE_TI_ARGS (type)));
20007 
20008   /* type (T)
20009      T()
20010      T(T)  */
20011   if (TREE_CODE (type) == FUNCTION_TYPE
20012       || TREE_CODE (type) == METHOD_TYPE)
20013     {
20014       if (uses_deducible_template_parms (TREE_TYPE (type)))
20015 	return true;
20016       tree parm = TYPE_ARG_TYPES (type);
20017       if (TREE_CODE (type) == METHOD_TYPE)
20018 	parm = TREE_CHAIN (parm);
20019       for (; parm; parm = TREE_CHAIN (parm))
20020 	if (uses_deducible_template_parms (TREE_VALUE (parm)))
20021 	  return true;
20022     }
20023 
20024   return false;
20025 }
20026 
20027 /* Subroutine of type_unification_real and unify_pack_expansion to
20028    handle unification of a single P/A pair.  Parameters are as
20029    for those functions.  */
20030 
20031 static int
unify_one_argument(tree tparms,tree targs,tree parm,tree arg,int subr,unification_kind_t strict,bool explain_p)20032 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
20033 		    int subr, unification_kind_t strict,
20034 		    bool explain_p)
20035 {
20036   tree arg_expr = NULL_TREE;
20037   int arg_strict;
20038 
20039   if (arg == error_mark_node || parm == error_mark_node)
20040     return unify_invalid (explain_p);
20041   if (arg == unknown_type_node)
20042     /* We can't deduce anything from this, but we might get all the
20043        template args from other function args.  */
20044     return unify_success (explain_p);
20045 
20046   /* Implicit conversions (Clause 4) will be performed on a function
20047      argument to convert it to the type of the corresponding function
20048      parameter if the parameter type contains no template-parameters that
20049      participate in template argument deduction.  */
20050   if (strict != DEDUCE_EXACT
20051       && TYPE_P (parm) && !uses_deducible_template_parms (parm))
20052     /* For function parameters with no deducible template parameters,
20053        just return.  We'll check non-dependent conversions later.  */
20054     return unify_success (explain_p);
20055 
20056   switch (strict)
20057     {
20058     case DEDUCE_CALL:
20059       arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
20060 		    | UNIFY_ALLOW_MORE_CV_QUAL
20061 		    | UNIFY_ALLOW_DERIVED);
20062       break;
20063 
20064     case DEDUCE_CONV:
20065       arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
20066       break;
20067 
20068     case DEDUCE_EXACT:
20069       arg_strict = UNIFY_ALLOW_NONE;
20070       break;
20071 
20072     default:
20073       gcc_unreachable ();
20074     }
20075 
20076   /* We only do these transformations if this is the top-level
20077      parameter_type_list in a call or declaration matching; in other
20078      situations (nested function declarators, template argument lists) we
20079      won't be comparing a type to an expression, and we don't do any type
20080      adjustments.  */
20081   if (!subr)
20082     {
20083       if (!TYPE_P (arg))
20084 	{
20085 	  gcc_assert (TREE_TYPE (arg) != NULL_TREE);
20086 	  if (type_unknown_p (arg))
20087 	    {
20088 	      /* [temp.deduct.type] A template-argument can be
20089 		 deduced from a pointer to function or pointer
20090 		 to member function argument if the set of
20091 		 overloaded functions does not contain function
20092 		 templates and at most one of a set of
20093 		 overloaded functions provides a unique
20094 		 match.  */
20095 	      resolve_overloaded_unification (tparms, targs, parm,
20096 					      arg, strict,
20097 					      arg_strict, explain_p);
20098 	      /* If a unique match was not found, this is a
20099 	         non-deduced context, so we still succeed. */
20100 	      return unify_success (explain_p);
20101 	    }
20102 
20103 	  arg_expr = arg;
20104 	  arg = unlowered_expr_type (arg);
20105 	  if (arg == error_mark_node)
20106 	    return unify_invalid (explain_p);
20107 	}
20108 
20109       arg_strict |=
20110 	maybe_adjust_types_for_deduction (strict, &parm, &arg, arg_expr);
20111     }
20112   else
20113     if ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
20114 	!= (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL))
20115       return unify_template_argument_mismatch (explain_p, parm, arg);
20116 
20117   /* For deduction from an init-list we need the actual list.  */
20118   if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
20119     arg = arg_expr;
20120   return unify (tparms, targs, parm, arg, arg_strict, explain_p);
20121 }
20122 
20123 /* for_each_template_parm callback that always returns 0.  */
20124 
20125 static int
zero_r(tree,void *)20126 zero_r (tree, void *)
20127 {
20128   return 0;
20129 }
20130 
20131 /* for_each_template_parm any_fn callback to handle deduction of a template
20132    type argument from the type of an array bound.  */
20133 
20134 static int
array_deduction_r(tree t,void * data)20135 array_deduction_r (tree t, void *data)
20136 {
20137   tree_pair_p d = (tree_pair_p)data;
20138   tree &tparms = d->purpose;
20139   tree &targs = d->value;
20140 
20141   if (TREE_CODE (t) == ARRAY_TYPE)
20142     if (tree dom = TYPE_DOMAIN (t))
20143       if (tree max = TYPE_MAX_VALUE (dom))
20144 	{
20145 	  if (TREE_CODE (max) == MINUS_EXPR)
20146 	    max = TREE_OPERAND (max, 0);
20147 	  if (TREE_CODE (max) == TEMPLATE_PARM_INDEX)
20148 	    unify (tparms, targs, TREE_TYPE (max), size_type_node,
20149 		   UNIFY_ALLOW_NONE, /*explain*/false);
20150 	}
20151 
20152   /* Keep walking.  */
20153   return 0;
20154 }
20155 
20156 /* Try to deduce any not-yet-deduced template type arguments from the type of
20157    an array bound.  This is handled separately from unify because 14.8.2.5 says
20158    "The type of a type parameter is only deduced from an array bound if it is
20159    not otherwise deduced."  */
20160 
20161 static void
try_array_deduction(tree tparms,tree targs,tree parm)20162 try_array_deduction (tree tparms, tree targs, tree parm)
20163 {
20164   tree_pair_s data = { tparms, targs };
20165   hash_set<tree> visited;
20166   for_each_template_parm (parm, zero_r, &data, &visited,
20167 			  /*nondeduced*/false, array_deduction_r);
20168 }
20169 
20170 /* Returns how many levels of { } INIT contains.  */
20171 
20172 static int
braced_init_depth(tree init)20173 braced_init_depth (tree init)
20174 {
20175   if (!init || !BRACE_ENCLOSED_INITIALIZER_P (init))
20176     return 0;
20177   unsigned i; tree val;
20178   unsigned max = 0;
20179   FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (init), i, val)
20180     {
20181       unsigned elt_d = braced_init_depth (val);
20182       if (elt_d > max)
20183 	max = elt_d;
20184     }
20185   return max + 1;
20186 }
20187 
20188 /* Most parms like fn_type_unification.
20189 
20190    If SUBR is 1, we're being called recursively (to unify the
20191    arguments of a function or method parameter of a function
20192    template).
20193 
20194    CHECKS is a pointer to a vector of access checks encountered while
20195    substituting default template arguments.  */
20196 
20197 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)20198 type_unification_real (tree tparms,
20199 		       tree full_targs,
20200 		       tree xparms,
20201 		       const tree *xargs,
20202 		       unsigned int xnargs,
20203 		       int subr,
20204 		       unification_kind_t strict,
20205 		       int flags,
20206 		       vec<deferred_access_check, va_gc> **checks,
20207 		       bool explain_p)
20208 {
20209   tree parm, arg;
20210   int i;
20211   int ntparms = TREE_VEC_LENGTH (tparms);
20212   int saw_undeduced = 0;
20213   tree parms;
20214   const tree *args;
20215   unsigned int nargs;
20216   unsigned int ia;
20217 
20218   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
20219   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
20220   gcc_assert (ntparms > 0);
20221 
20222   tree targs = INNERMOST_TEMPLATE_ARGS (full_targs);
20223 
20224   /* Reset the number of non-defaulted template arguments contained
20225      in TARGS.  */
20226   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
20227 
20228  again:
20229   parms = xparms;
20230   args = xargs;
20231   nargs = xnargs;
20232 
20233   ia = 0;
20234   while (parms && parms != void_list_node
20235 	 && ia < nargs)
20236     {
20237       parm = TREE_VALUE (parms);
20238 
20239       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
20240 	  && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
20241 	/* For a function parameter pack that occurs at the end of the
20242 	   parameter-declaration-list, the type A of each remaining
20243 	   argument of the call is compared with the type P of the
20244 	   declarator-id of the function parameter pack.  */
20245 	break;
20246 
20247       parms = TREE_CHAIN (parms);
20248 
20249       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
20250 	/* For a function parameter pack that does not occur at the
20251 	   end of the parameter-declaration-list, the type of the
20252 	   parameter pack is a non-deduced context.  */
20253 	continue;
20254 
20255       arg = args[ia];
20256       ++ia;
20257 
20258       if (unify_one_argument (tparms, full_targs, parm, arg, subr, strict,
20259 			      explain_p))
20260 	return 1;
20261     }
20262 
20263   if (parms
20264       && parms != void_list_node
20265       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
20266     {
20267       /* Unify the remaining arguments with the pack expansion type.  */
20268       tree argvec;
20269       tree parmvec = make_tree_vec (1);
20270 
20271       /* Allocate a TREE_VEC and copy in all of the arguments */
20272       argvec = make_tree_vec (nargs - ia);
20273       for (i = 0; ia < nargs; ++ia, ++i)
20274 	TREE_VEC_ELT (argvec, i) = args[ia];
20275 
20276       /* Copy the parameter into parmvec.  */
20277       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
20278       if (unify_pack_expansion (tparms, full_targs, parmvec, argvec, strict,
20279                                 /*subr=*/subr, explain_p))
20280         return 1;
20281 
20282       /* Advance to the end of the list of parameters.  */
20283       parms = TREE_CHAIN (parms);
20284     }
20285 
20286   /* Fail if we've reached the end of the parm list, and more args
20287      are present, and the parm list isn't variadic.  */
20288   if (ia < nargs && parms == void_list_node)
20289     return unify_too_many_arguments (explain_p, nargs, ia);
20290   /* Fail if parms are left and they don't have default values and
20291      they aren't all deduced as empty packs (c++/57397).  This is
20292      consistent with sufficient_parms_p.  */
20293   if (parms && parms != void_list_node
20294       && TREE_PURPOSE (parms) == NULL_TREE)
20295     {
20296       unsigned int count = nargs;
20297       tree p = parms;
20298       bool type_pack_p;
20299       do
20300 	{
20301 	  type_pack_p = TREE_CODE (TREE_VALUE (p)) == TYPE_PACK_EXPANSION;
20302 	  if (!type_pack_p)
20303 	    count++;
20304 	  p = TREE_CHAIN (p);
20305 	}
20306       while (p && p != void_list_node);
20307       if (count != nargs)
20308 	return unify_too_few_arguments (explain_p, ia, count,
20309 					type_pack_p);
20310     }
20311 
20312   if (!subr)
20313     {
20314       tsubst_flags_t complain = (explain_p
20315 				 ? tf_warning_or_error
20316 				 : tf_none);
20317       bool tried_array_deduction = (cxx_dialect < cxx17);
20318 
20319       for (i = 0; i < ntparms; i++)
20320 	{
20321 	  tree targ = TREE_VEC_ELT (targs, i);
20322 	  tree tparm = TREE_VEC_ELT (tparms, i);
20323 
20324 	  /* Clear the "incomplete" flags on all argument packs now so that
20325 	     substituting them into later default arguments works.  */
20326 	  if (targ && ARGUMENT_PACK_P (targ))
20327             {
20328               ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
20329               ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
20330             }
20331 
20332 	  if (targ || tparm == error_mark_node)
20333 	    continue;
20334 	  tparm = TREE_VALUE (tparm);
20335 
20336 	  if (TREE_CODE (tparm) == TYPE_DECL
20337 	      && !tried_array_deduction)
20338 	    {
20339 	      try_array_deduction (tparms, targs, xparms);
20340 	      tried_array_deduction = true;
20341 	      if (TREE_VEC_ELT (targs, i))
20342 		continue;
20343 	    }
20344 
20345 	  /* If this is an undeduced nontype parameter that depends on
20346 	     a type parameter, try another pass; its type may have been
20347 	     deduced from a later argument than the one from which
20348 	     this parameter can be deduced.  */
20349 	  if (TREE_CODE (tparm) == PARM_DECL
20350 	      && uses_template_parms (TREE_TYPE (tparm))
20351 	      && saw_undeduced < 2)
20352 	    {
20353 	      saw_undeduced = 1;
20354 	      continue;
20355 	    }
20356 
20357 	  /* Core issue #226 (C++0x) [temp.deduct]:
20358 
20359 	     If a template argument has not been deduced, its
20360 	     default template argument, if any, is used.
20361 
20362 	     When we are in C++98 mode, TREE_PURPOSE will either
20363 	     be NULL_TREE or ERROR_MARK_NODE, so we do not need
20364 	     to explicitly check cxx_dialect here.  */
20365 	  if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
20366 	    /* OK, there is a default argument.  Wait until after the
20367 	       conversion check to do substitution.  */
20368 	    continue;
20369 
20370 	  /* If the type parameter is a parameter pack, then it will
20371 	     be deduced to an empty parameter pack.  */
20372 	  if (template_parameter_pack_p (tparm))
20373 	    {
20374 	      tree arg;
20375 
20376 	      if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
20377 		{
20378 		  arg = make_node (NONTYPE_ARGUMENT_PACK);
20379 		  TREE_CONSTANT (arg) = 1;
20380 		}
20381 	      else
20382 		arg = cxx_make_type (TYPE_ARGUMENT_PACK);
20383 
20384 	      SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
20385 
20386 	      TREE_VEC_ELT (targs, i) = arg;
20387 	      continue;
20388 	    }
20389 
20390 	  return unify_parameter_deduction_failure (explain_p, tparm);
20391 	}
20392 
20393       /* DR 1391: All parameters have args, now check non-dependent parms for
20394 	 convertibility.  */
20395       if (saw_undeduced < 2)
20396 	for (ia = 0, parms = xparms, args = xargs, nargs = xnargs;
20397 	     parms && parms != void_list_node && ia < nargs; )
20398 	  {
20399 	    parm = TREE_VALUE (parms);
20400 
20401 	    if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
20402 		&& (!TREE_CHAIN (parms)
20403 		    || TREE_CHAIN (parms) == void_list_node))
20404 	      /* For a function parameter pack that occurs at the end of the
20405 		 parameter-declaration-list, the type A of each remaining
20406 		 argument of the call is compared with the type P of the
20407 		 declarator-id of the function parameter pack.  */
20408 	      break;
20409 
20410 	    parms = TREE_CHAIN (parms);
20411 
20412 	    if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
20413 	      /* For a function parameter pack that does not occur at the
20414 		 end of the parameter-declaration-list, the type of the
20415 		 parameter pack is a non-deduced context.  */
20416 	      continue;
20417 
20418 	    arg = args[ia];
20419 	    ++ia;
20420 
20421 	    if (uses_template_parms (parm))
20422 	      continue;
20423 	    /* Workaround for c++/80290: avoid combinatorial explosion on
20424 	       deeply nested braced init-lists.  */
20425 	    if (braced_init_depth (arg) > 2)
20426 	      continue;
20427 	    if (check_non_deducible_conversion (parm, arg, strict, flags,
20428 						explain_p))
20429 	      return 1;
20430 	  }
20431 
20432       /* Now substitute into the default template arguments.  */
20433       for (i = 0; i < ntparms; i++)
20434 	{
20435 	  tree targ = TREE_VEC_ELT (targs, i);
20436 	  tree tparm = TREE_VEC_ELT (tparms, i);
20437 
20438 	  if (targ || tparm == error_mark_node)
20439 	    continue;
20440 	  tree parm = TREE_VALUE (tparm);
20441 	  tree arg = TREE_PURPOSE (tparm);
20442 	  reopen_deferring_access_checks (*checks);
20443 	  location_t save_loc = input_location;
20444 	  if (DECL_P (parm))
20445 	    input_location = DECL_SOURCE_LOCATION (parm);
20446 
20447 	  if (saw_undeduced == 1
20448 	      && TREE_CODE (parm) == PARM_DECL
20449 	      && uses_template_parms (TREE_TYPE (parm)))
20450 	    {
20451 	      /* The type of this non-type parameter depends on undeduced
20452 		 parameters.  Don't try to use its default argument yet,
20453 		 since we might deduce an argument for it on the next pass,
20454 		 but do check whether the arguments we already have cause
20455 		 substitution failure, so that that happens before we try
20456 		 later default arguments (78489).  */
20457 	      ++processing_template_decl;
20458 	      tree type = tsubst (TREE_TYPE (parm), full_targs, complain,
20459 				  NULL_TREE);
20460 	      --processing_template_decl;
20461 	      if (type == error_mark_node)
20462 		arg = error_mark_node;
20463 	      else
20464 		arg = NULL_TREE;
20465 	    }
20466 	  else
20467 	    {
20468 	      tree substed = NULL_TREE;
20469 	      if (saw_undeduced == 1 && processing_template_decl == 0)
20470 		{
20471 		  /* First instatiate in template context, in case we still
20472 		     depend on undeduced template parameters.  */
20473 		  ++processing_template_decl;
20474 		  substed = tsubst_template_arg (arg, full_targs, complain,
20475 						 NULL_TREE);
20476 		  --processing_template_decl;
20477 		  if (substed != error_mark_node
20478 		      && !uses_template_parms (substed))
20479 		    /* We replaced all the tparms, substitute again out of
20480 		       template context.  */
20481 		    substed = NULL_TREE;
20482 		}
20483 	      if (!substed)
20484 		substed = tsubst_template_arg (arg, full_targs, complain,
20485 					       NULL_TREE);
20486 
20487 	      if (!uses_template_parms (substed))
20488 		arg = convert_template_argument (parm, substed, full_targs,
20489 						 complain, i, NULL_TREE);
20490 	      else if (saw_undeduced == 1)
20491 		arg = NULL_TREE;
20492 	      else
20493 		arg = error_mark_node;
20494 	    }
20495 
20496 	  input_location = save_loc;
20497 	  *checks = get_deferred_access_checks ();
20498 	  pop_deferring_access_checks ();
20499 
20500 	  if (arg == error_mark_node)
20501 	    return 1;
20502 	  else if (arg)
20503 	    {
20504 	      TREE_VEC_ELT (targs, i) = arg;
20505 	      /* The position of the first default template argument,
20506 		 is also the number of non-defaulted arguments in TARGS.
20507 		 Record that.  */
20508 	      if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
20509 		SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
20510 	    }
20511 	}
20512 
20513       if (saw_undeduced++ == 1)
20514 	goto again;
20515     }
20516 
20517   if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
20518     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
20519 
20520   return unify_success (explain_p);
20521 }
20522 
20523 /* Subroutine of type_unification_real.  Args are like the variables
20524    at the call site.  ARG is an overloaded function (or template-id);
20525    we try deducing template args from each of the overloads, and if
20526    only one succeeds, we go with that.  Modifies TARGS and returns
20527    true on success.  */
20528 
20529 static bool
resolve_overloaded_unification(tree tparms,tree targs,tree parm,tree arg,unification_kind_t strict,int sub_strict,bool explain_p)20530 resolve_overloaded_unification (tree tparms,
20531 				tree targs,
20532 				tree parm,
20533 				tree arg,
20534 				unification_kind_t strict,
20535 				int sub_strict,
20536 			        bool explain_p)
20537 {
20538   tree tempargs = copy_node (targs);
20539   int good = 0;
20540   tree goodfn = NULL_TREE;
20541   bool addr_p;
20542 
20543   if (TREE_CODE (arg) == ADDR_EXPR)
20544     {
20545       arg = TREE_OPERAND (arg, 0);
20546       addr_p = true;
20547     }
20548   else
20549     addr_p = false;
20550 
20551   if (TREE_CODE (arg) == COMPONENT_REF)
20552     /* Handle `&x' where `x' is some static or non-static member
20553        function name.  */
20554     arg = TREE_OPERAND (arg, 1);
20555 
20556   if (TREE_CODE (arg) == OFFSET_REF)
20557     arg = TREE_OPERAND (arg, 1);
20558 
20559   /* Strip baselink information.  */
20560   if (BASELINK_P (arg))
20561     arg = BASELINK_FUNCTIONS (arg);
20562 
20563   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
20564     {
20565       /* If we got some explicit template args, we need to plug them into
20566 	 the affected templates before we try to unify, in case the
20567 	 explicit args will completely resolve the templates in question.  */
20568 
20569       int ok = 0;
20570       tree expl_subargs = TREE_OPERAND (arg, 1);
20571       arg = TREE_OPERAND (arg, 0);
20572 
20573       for (lkp_iterator iter (arg); iter; ++iter)
20574 	{
20575 	  tree fn = *iter;
20576 	  tree subargs, elem;
20577 
20578 	  if (TREE_CODE (fn) != TEMPLATE_DECL)
20579 	    continue;
20580 
20581 	  subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
20582 					   expl_subargs, NULL_TREE, tf_none,
20583 					   /*require_all_args=*/true,
20584 					   /*use_default_args=*/true);
20585 	  if (subargs != error_mark_node
20586 	      && !any_dependent_template_arguments_p (subargs))
20587 	    {
20588 	      elem = TREE_TYPE (instantiate_template (fn, subargs, tf_none));
20589 	      if (try_one_overload (tparms, targs, tempargs, parm,
20590 				    elem, strict, sub_strict, addr_p, explain_p)
20591 		  && (!goodfn || !same_type_p (goodfn, elem)))
20592 		{
20593 		  goodfn = elem;
20594 		  ++good;
20595 		}
20596 	    }
20597 	  else if (subargs)
20598 	    ++ok;
20599 	}
20600       /* If no templates (or more than one) are fully resolved by the
20601 	 explicit arguments, this template-id is a non-deduced context; it
20602 	 could still be OK if we deduce all template arguments for the
20603 	 enclosing call through other arguments.  */
20604       if (good != 1)
20605 	good = ok;
20606     }
20607   else if (TREE_CODE (arg) != OVERLOAD
20608 	   && TREE_CODE (arg) != FUNCTION_DECL)
20609     /* If ARG is, for example, "(0, &f)" then its type will be unknown
20610        -- but the deduction does not succeed because the expression is
20611        not just the function on its own.  */
20612     return false;
20613   else
20614     for (lkp_iterator iter (arg); iter; ++iter)
20615       {
20616 	tree fn = *iter;
20617 	if (try_one_overload (tparms, targs, tempargs, parm, TREE_TYPE (fn),
20618 			      strict, sub_strict, addr_p, explain_p)
20619 	    && (!goodfn || !decls_match (goodfn, fn)))
20620 	  {
20621 	    goodfn = fn;
20622 	    ++good;
20623 	  }
20624       }
20625 
20626   /* [temp.deduct.type] A template-argument can be deduced from a pointer
20627      to function or pointer to member function argument if the set of
20628      overloaded functions does not contain function templates and at most
20629      one of a set of overloaded functions provides a unique match.
20630 
20631      So if we found multiple possibilities, we return success but don't
20632      deduce anything.  */
20633 
20634   if (good == 1)
20635     {
20636       int i = TREE_VEC_LENGTH (targs);
20637       for (; i--; )
20638 	if (TREE_VEC_ELT (tempargs, i))
20639 	  {
20640 	    tree old = TREE_VEC_ELT (targs, i);
20641 	    tree new_ = TREE_VEC_ELT (tempargs, i);
20642 	    if (new_ && old && ARGUMENT_PACK_P (old)
20643 		&& ARGUMENT_PACK_EXPLICIT_ARGS (old))
20644 	      /* Don't forget explicit template arguments in a pack.  */
20645 	      ARGUMENT_PACK_EXPLICIT_ARGS (new_)
20646 		= ARGUMENT_PACK_EXPLICIT_ARGS (old);
20647 	    TREE_VEC_ELT (targs, i) = new_;
20648 	  }
20649     }
20650   if (good)
20651     return true;
20652 
20653   return false;
20654 }
20655 
20656 /* Core DR 115: In contexts where deduction is done and fails, or in
20657    contexts where deduction is not done, if a template argument list is
20658    specified and it, along with any default template arguments, identifies
20659    a single function template specialization, then the template-id is an
20660    lvalue for the function template specialization.  */
20661 
20662 tree
resolve_nondeduced_context(tree orig_expr,tsubst_flags_t complain)20663 resolve_nondeduced_context (tree orig_expr, tsubst_flags_t complain)
20664 {
20665   tree expr, offset, baselink;
20666   bool addr;
20667 
20668   if (!type_unknown_p (orig_expr))
20669     return orig_expr;
20670 
20671   expr = orig_expr;
20672   addr = false;
20673   offset = NULL_TREE;
20674   baselink = NULL_TREE;
20675 
20676   if (TREE_CODE (expr) == ADDR_EXPR)
20677     {
20678       expr = TREE_OPERAND (expr, 0);
20679       addr = true;
20680     }
20681   if (TREE_CODE (expr) == OFFSET_REF)
20682     {
20683       offset = expr;
20684       expr = TREE_OPERAND (expr, 1);
20685     }
20686   if (BASELINK_P (expr))
20687     {
20688       baselink = expr;
20689       expr = BASELINK_FUNCTIONS (expr);
20690     }
20691 
20692   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
20693     {
20694       int good = 0;
20695       tree goodfn = NULL_TREE;
20696 
20697       /* If we got some explicit template args, we need to plug them into
20698 	 the affected templates before we try to unify, in case the
20699 	 explicit args will completely resolve the templates in question.  */
20700 
20701       tree expl_subargs = TREE_OPERAND (expr, 1);
20702       tree arg = TREE_OPERAND (expr, 0);
20703       tree badfn = NULL_TREE;
20704       tree badargs = NULL_TREE;
20705 
20706       for (lkp_iterator iter (arg); iter; ++iter)
20707 	{
20708 	  tree fn = *iter;
20709 	  tree subargs, elem;
20710 
20711 	  if (TREE_CODE (fn) != TEMPLATE_DECL)
20712 	    continue;
20713 
20714 	  subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
20715 					   expl_subargs, NULL_TREE, tf_none,
20716 					   /*require_all_args=*/true,
20717 					   /*use_default_args=*/true);
20718 	  if (subargs != error_mark_node
20719 	      && !any_dependent_template_arguments_p (subargs))
20720 	    {
20721 	      elem = instantiate_template (fn, subargs, tf_none);
20722 	      if (elem == error_mark_node)
20723 		{
20724 		  badfn = fn;
20725 		  badargs = subargs;
20726 		}
20727 	      else if (elem && (!goodfn || !decls_match (goodfn, elem)))
20728 		{
20729 		  goodfn = elem;
20730 		  ++good;
20731 		}
20732 	    }
20733 	}
20734       if (good == 1)
20735 	{
20736 	  mark_used (goodfn);
20737 	  expr = goodfn;
20738 	  if (baselink)
20739 	    expr = build_baselink (BASELINK_BINFO (baselink),
20740 				   BASELINK_ACCESS_BINFO (baselink),
20741 				   expr, BASELINK_OPTYPE (baselink));
20742 	  if (offset)
20743 	    {
20744 	      tree base
20745 		= TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
20746 	      expr = build_offset_ref (base, expr, addr, complain);
20747 	    }
20748 	  if (addr)
20749 	    expr = cp_build_addr_expr (expr, complain);
20750 	  return expr;
20751 	}
20752       else if (good == 0 && badargs && (complain & tf_error))
20753 	/* There were no good options and at least one bad one, so let the
20754 	   user know what the problem is.  */
20755 	instantiate_template (badfn, badargs, complain);
20756     }
20757   return orig_expr;
20758 }
20759 
20760 /* Subroutine of resolve_overloaded_unification; does deduction for a single
20761    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
20762    different overloads deduce different arguments for a given parm.
20763    ADDR_P is true if the expression for which deduction is being
20764    performed was of the form "& fn" rather than simply "fn".
20765 
20766    Returns 1 on success.  */
20767 
20768 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)20769 try_one_overload (tree tparms,
20770 		  tree orig_targs,
20771 		  tree targs,
20772 		  tree parm,
20773 		  tree arg,
20774 		  unification_kind_t strict,
20775 		  int sub_strict,
20776 		  bool addr_p,
20777 		  bool explain_p)
20778 {
20779   int nargs;
20780   tree tempargs;
20781   int i;
20782 
20783   if (arg == error_mark_node)
20784     return 0;
20785 
20786   /* [temp.deduct.type] A template-argument can be deduced from a pointer
20787      to function or pointer to member function argument if the set of
20788      overloaded functions does not contain function templates and at most
20789      one of a set of overloaded functions provides a unique match.
20790 
20791      So if this is a template, just return success.  */
20792 
20793   if (uses_template_parms (arg))
20794     return 1;
20795 
20796   if (TREE_CODE (arg) == METHOD_TYPE)
20797     arg = build_ptrmemfunc_type (build_pointer_type (arg));
20798   else if (addr_p)
20799     arg = build_pointer_type (arg);
20800 
20801   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
20802 
20803   /* We don't copy orig_targs for this because if we have already deduced
20804      some template args from previous args, unify would complain when we
20805      try to deduce a template parameter for the same argument, even though
20806      there isn't really a conflict.  */
20807   nargs = TREE_VEC_LENGTH (targs);
20808   tempargs = make_tree_vec (nargs);
20809 
20810   if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
20811     return 0;
20812 
20813   /* First make sure we didn't deduce anything that conflicts with
20814      explicitly specified args.  */
20815   for (i = nargs; i--; )
20816     {
20817       tree elt = TREE_VEC_ELT (tempargs, i);
20818       tree oldelt = TREE_VEC_ELT (orig_targs, i);
20819 
20820       if (!elt)
20821 	/*NOP*/;
20822       else if (uses_template_parms (elt))
20823 	/* Since we're unifying against ourselves, we will fill in
20824 	   template args used in the function parm list with our own
20825 	   template parms.  Discard them.  */
20826 	TREE_VEC_ELT (tempargs, i) = NULL_TREE;
20827       else if (oldelt && ARGUMENT_PACK_P (oldelt))
20828 	{
20829 	  /* Check that the argument at each index of the deduced argument pack
20830 	     is equivalent to the corresponding explicitly specified argument.
20831 	     We may have deduced more arguments than were explicitly specified,
20832 	     and that's OK.  */
20833 
20834 	  /* We used to assert ARGUMENT_PACK_INCOMPLETE_P (oldelt) here, but
20835 	     that's wrong if we deduce the same argument pack from multiple
20836 	     function arguments: it's only incomplete the first time.  */
20837 
20838 	  tree explicit_pack = ARGUMENT_PACK_ARGS (oldelt);
20839 	  tree deduced_pack = ARGUMENT_PACK_ARGS (elt);
20840 
20841 	  if (TREE_VEC_LENGTH (deduced_pack)
20842 	      < TREE_VEC_LENGTH (explicit_pack))
20843 	    return 0;
20844 
20845 	  for (int j = 0; j < TREE_VEC_LENGTH (explicit_pack); j++)
20846 	    if (!template_args_equal (TREE_VEC_ELT (explicit_pack, j),
20847 				      TREE_VEC_ELT (deduced_pack, j)))
20848 	      return 0;
20849 	}
20850       else if (oldelt && !template_args_equal (oldelt, elt))
20851 	return 0;
20852     }
20853 
20854   for (i = nargs; i--; )
20855     {
20856       tree elt = TREE_VEC_ELT (tempargs, i);
20857 
20858       if (elt)
20859 	TREE_VEC_ELT (targs, i) = elt;
20860     }
20861 
20862   return 1;
20863 }
20864 
20865 /* PARM is a template class (perhaps with unbound template
20866    parameters).  ARG is a fully instantiated type.  If ARG can be
20867    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
20868    TARGS are as for unify.  */
20869 
20870 static tree
try_class_unification(tree tparms,tree targs,tree parm,tree arg,bool explain_p)20871 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
20872 		       bool explain_p)
20873 {
20874   tree copy_of_targs;
20875 
20876   if (!CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
20877     return NULL_TREE;
20878   else if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
20879     /* Matches anything.  */;
20880   else if (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
20881 	   != most_general_template (CLASSTYPE_TI_TEMPLATE (parm)))
20882     return NULL_TREE;
20883 
20884   /* We need to make a new template argument vector for the call to
20885      unify.  If we used TARGS, we'd clutter it up with the result of
20886      the attempted unification, even if this class didn't work out.
20887      We also don't want to commit ourselves to all the unifications
20888      we've already done, since unification is supposed to be done on
20889      an argument-by-argument basis.  In other words, consider the
20890      following pathological case:
20891 
20892        template <int I, int J, int K>
20893        struct S {};
20894 
20895        template <int I, int J>
20896        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
20897 
20898        template <int I, int J, int K>
20899        void f(S<I, J, K>, S<I, I, I>);
20900 
20901        void g() {
20902 	 S<0, 0, 0> s0;
20903 	 S<0, 1, 2> s2;
20904 
20905 	 f(s0, s2);
20906        }
20907 
20908      Now, by the time we consider the unification involving `s2', we
20909      already know that we must have `f<0, 0, 0>'.  But, even though
20910      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
20911      because there are two ways to unify base classes of S<0, 1, 2>
20912      with S<I, I, I>.  If we kept the already deduced knowledge, we
20913      would reject the possibility I=1.  */
20914   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
20915 
20916   if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
20917     {
20918       if (unify_bound_ttp_args (tparms, copy_of_targs, parm, arg, explain_p))
20919 	return NULL_TREE;
20920       return arg;
20921     }
20922 
20923   /* If unification failed, we're done.  */
20924   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
20925 	     CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE, explain_p))
20926     return NULL_TREE;
20927 
20928   return arg;
20929 }
20930 
20931 /* Given a template type PARM and a class type ARG, find the unique
20932    base type in ARG that is an instance of PARM.  We do not examine
20933    ARG itself; only its base-classes.  If there is not exactly one
20934    appropriate base class, return NULL_TREE.  PARM may be the type of
20935    a partial specialization, as well as a plain template type.  Used
20936    by unify.  */
20937 
20938 static enum template_base_result
get_template_base(tree tparms,tree targs,tree parm,tree arg,bool explain_p,tree * result)20939 get_template_base (tree tparms, tree targs, tree parm, tree arg,
20940 		   bool explain_p, tree *result)
20941 {
20942   tree rval = NULL_TREE;
20943   tree binfo;
20944 
20945   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
20946 
20947   binfo = TYPE_BINFO (complete_type (arg));
20948   if (!binfo)
20949     {
20950       /* The type could not be completed.  */
20951       *result = NULL_TREE;
20952       return tbr_incomplete_type;
20953     }
20954 
20955   /* Walk in inheritance graph order.  The search order is not
20956      important, and this avoids multiple walks of virtual bases.  */
20957   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
20958     {
20959       tree r = try_class_unification (tparms, targs, parm,
20960 				      BINFO_TYPE (binfo), explain_p);
20961 
20962       if (r)
20963 	{
20964 	  /* If there is more than one satisfactory baseclass, then:
20965 
20966 	       [temp.deduct.call]
20967 
20968 	      If they yield more than one possible deduced A, the type
20969 	      deduction fails.
20970 
20971 	     applies.  */
20972 	  if (rval && !same_type_p (r, rval))
20973 	    {
20974 	      *result = NULL_TREE;
20975 	      return tbr_ambiguous_baseclass;
20976 	    }
20977 
20978 	  rval = r;
20979 	}
20980     }
20981 
20982   *result = rval;
20983   return tbr_success;
20984 }
20985 
20986 /* Returns the level of DECL, which declares a template parameter.  */
20987 
20988 static int
template_decl_level(tree decl)20989 template_decl_level (tree decl)
20990 {
20991   switch (TREE_CODE (decl))
20992     {
20993     case TYPE_DECL:
20994     case TEMPLATE_DECL:
20995       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
20996 
20997     case PARM_DECL:
20998       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
20999 
21000     default:
21001       gcc_unreachable ();
21002     }
21003   return 0;
21004 }
21005 
21006 /* Decide whether ARG can be unified with PARM, considering only the
21007    cv-qualifiers of each type, given STRICT as documented for unify.
21008    Returns nonzero iff the unification is OK on that basis.  */
21009 
21010 static int
check_cv_quals_for_unify(int strict,tree arg,tree parm)21011 check_cv_quals_for_unify (int strict, tree arg, tree parm)
21012 {
21013   int arg_quals = cp_type_quals (arg);
21014   int parm_quals = cp_type_quals (parm);
21015 
21016   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
21017       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
21018     {
21019       /*  Although a CVR qualifier is ignored when being applied to a
21020 	  substituted template parameter ([8.3.2]/1 for example), that
21021 	  does not allow us to unify "const T" with "int&" because both
21022 	  types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
21023 	  It is ok when we're allowing additional CV qualifiers
21024 	  at the outer level [14.8.2.1]/3,1st bullet.  */
21025       if ((TREE_CODE (arg) == REFERENCE_TYPE
21026 	   || TREE_CODE (arg) == FUNCTION_TYPE
21027 	   || TREE_CODE (arg) == METHOD_TYPE)
21028 	  && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
21029 	return 0;
21030 
21031       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
21032 	  && (parm_quals & TYPE_QUAL_RESTRICT))
21033 	return 0;
21034     }
21035 
21036   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
21037       && (arg_quals & parm_quals) != parm_quals)
21038     return 0;
21039 
21040   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
21041       && (parm_quals & arg_quals) != arg_quals)
21042     return 0;
21043 
21044   return 1;
21045 }
21046 
21047 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
21048 void
template_parm_level_and_index(tree parm,int * level,int * index)21049 template_parm_level_and_index (tree parm, int* level, int* index)
21050 {
21051   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
21052       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
21053       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
21054     {
21055       *index = TEMPLATE_TYPE_IDX (parm);
21056       *level = TEMPLATE_TYPE_LEVEL (parm);
21057     }
21058   else
21059     {
21060       *index = TEMPLATE_PARM_IDX (parm);
21061       *level = TEMPLATE_PARM_LEVEL (parm);
21062     }
21063 }
21064 
21065 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP)			\
21066   do {									\
21067     if (unify (TP, TA, P, A, S, EP))					\
21068       return 1;								\
21069   } while (0)
21070 
21071 /* Unifies the remaining arguments in PACKED_ARGS with the pack
21072    expansion at the end of PACKED_PARMS. Returns 0 if the type
21073    deduction succeeds, 1 otherwise. STRICT is the same as in
21074    fn_type_unification. CALL_ARGS_P is true iff PACKED_ARGS is actually a
21075    function call argument list. We'll need to adjust the arguments to make them
21076    types. SUBR tells us if this is from a recursive call to
21077    type_unification_real, or for comparing two template argument
21078    lists. */
21079 
21080 static int
unify_pack_expansion(tree tparms,tree targs,tree packed_parms,tree packed_args,unification_kind_t strict,bool subr,bool explain_p)21081 unify_pack_expansion (tree tparms, tree targs, tree packed_parms,
21082                       tree packed_args, unification_kind_t strict,
21083                       bool subr, bool explain_p)
21084 {
21085   tree parm
21086     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
21087   tree pattern = PACK_EXPANSION_PATTERN (parm);
21088   tree pack, packs = NULL_TREE;
21089   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
21090 
21091   /* Add in any args remembered from an earlier partial instantiation.  */
21092   targs = add_to_template_args (PACK_EXPANSION_EXTRA_ARGS (parm), targs);
21093   int levels = TMPL_ARGS_DEPTH (targs);
21094 
21095   packed_args = expand_template_argument_pack (packed_args);
21096 
21097   int len = TREE_VEC_LENGTH (packed_args);
21098 
21099   /* Determine the parameter packs we will be deducing from the
21100      pattern, and record their current deductions.  */
21101   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm);
21102        pack; pack = TREE_CHAIN (pack))
21103     {
21104       tree parm_pack = TREE_VALUE (pack);
21105       int idx, level;
21106 
21107       /* Only template parameter packs can be deduced, not e.g. function
21108 	 parameter packs or __bases or __integer_pack.  */
21109       if (!TEMPLATE_PARM_P (parm_pack))
21110 	continue;
21111 
21112       /* Determine the index and level of this parameter pack.  */
21113       template_parm_level_and_index (parm_pack, &level, &idx);
21114       if (level < levels)
21115 	continue;
21116 
21117       /* Keep track of the parameter packs and their corresponding
21118          argument packs.  */
21119       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
21120       TREE_TYPE (packs) = make_tree_vec (len - start);
21121     }
21122 
21123   /* Loop through all of the arguments that have not yet been
21124      unified and unify each with the pattern.  */
21125   for (i = start; i < len; i++)
21126     {
21127       tree parm;
21128       bool any_explicit = false;
21129       tree arg = TREE_VEC_ELT (packed_args, i);
21130 
21131       /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
21132 	 or the element of its argument pack at the current index if
21133 	 this argument was explicitly specified.  */
21134       for (pack = packs; pack; pack = TREE_CHAIN (pack))
21135         {
21136           int idx, level;
21137           tree arg, pargs;
21138           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
21139 
21140           arg = NULL_TREE;
21141           if (TREE_VALUE (pack)
21142               && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
21143               && (i - start < TREE_VEC_LENGTH (pargs)))
21144             {
21145               any_explicit = true;
21146               arg = TREE_VEC_ELT (pargs, i - start);
21147             }
21148           TMPL_ARG (targs, level, idx) = arg;
21149         }
21150 
21151       /* If we had explicit template arguments, substitute them into the
21152 	 pattern before deduction.  */
21153       if (any_explicit)
21154 	{
21155 	  /* Some arguments might still be unspecified or dependent.  */
21156 	  bool dependent;
21157 	  ++processing_template_decl;
21158 	  dependent = any_dependent_template_arguments_p (targs);
21159 	  if (!dependent)
21160 	    --processing_template_decl;
21161 	  parm = tsubst (pattern, targs,
21162 			 explain_p ? tf_warning_or_error : tf_none,
21163 			 NULL_TREE);
21164 	  if (dependent)
21165 	    --processing_template_decl;
21166 	  if (parm == error_mark_node)
21167 	    return 1;
21168 	}
21169       else
21170 	parm = pattern;
21171 
21172       /* Unify the pattern with the current argument.  */
21173       if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
21174 			      explain_p))
21175 	return 1;
21176 
21177       /* For each parameter pack, collect the deduced value.  */
21178       for (pack = packs; pack; pack = TREE_CHAIN (pack))
21179         {
21180           int idx, level;
21181           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
21182 
21183           TREE_VEC_ELT (TREE_TYPE (pack), i - start) =
21184             TMPL_ARG (targs, level, idx);
21185         }
21186     }
21187 
21188   /* Verify that the results of unification with the parameter packs
21189      produce results consistent with what we've seen before, and make
21190      the deduced argument packs available.  */
21191   for (pack = packs; pack; pack = TREE_CHAIN (pack))
21192     {
21193       tree old_pack = TREE_VALUE (pack);
21194       tree new_args = TREE_TYPE (pack);
21195       int i, len = TREE_VEC_LENGTH (new_args);
21196       int idx, level;
21197       bool nondeduced_p = false;
21198 
21199       /* By default keep the original deduced argument pack.
21200 	 If necessary, more specific code is going to update the
21201 	 resulting deduced argument later down in this function.  */
21202       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
21203       TMPL_ARG (targs, level, idx) = old_pack;
21204 
21205       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
21206 	 actually deduce anything.  */
21207       for (i = 0; i < len && !nondeduced_p; ++i)
21208 	if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
21209 	  nondeduced_p = true;
21210       if (nondeduced_p)
21211 	continue;
21212 
21213       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
21214         {
21215           /* If we had fewer function args than explicit template args,
21216              just use the explicits.  */
21217           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
21218           int explicit_len = TREE_VEC_LENGTH (explicit_args);
21219           if (len < explicit_len)
21220             new_args = explicit_args;
21221         }
21222 
21223       if (!old_pack)
21224         {
21225           tree result;
21226           /* Build the deduced *_ARGUMENT_PACK.  */
21227           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
21228             {
21229               result = make_node (NONTYPE_ARGUMENT_PACK);
21230               TREE_CONSTANT (result) = 1;
21231             }
21232           else
21233             result = cxx_make_type (TYPE_ARGUMENT_PACK);
21234 
21235           SET_ARGUMENT_PACK_ARGS (result, new_args);
21236 
21237           /* Note the deduced argument packs for this parameter
21238              pack.  */
21239           TMPL_ARG (targs, level, idx) = result;
21240         }
21241       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
21242                && (ARGUMENT_PACK_ARGS (old_pack)
21243                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
21244         {
21245           /* We only had the explicitly-provided arguments before, but
21246              now we have a complete set of arguments.  */
21247           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
21248 
21249           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
21250           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
21251           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
21252         }
21253       else
21254 	{
21255 	  tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
21256 	  tree old_args = ARGUMENT_PACK_ARGS (old_pack);
21257 
21258 	  if (!comp_template_args (old_args, new_args,
21259 				   &bad_old_arg, &bad_new_arg))
21260 	    /* Inconsistent unification of this parameter pack.  */
21261 	    return unify_parameter_pack_inconsistent (explain_p,
21262 						      bad_old_arg,
21263 						      bad_new_arg);
21264 	}
21265     }
21266 
21267   return unify_success (explain_p);
21268 }
21269 
21270 /* Handle unification of the domain of an array.  PARM_DOM and ARG_DOM are
21271    INTEGER_TYPEs representing the TYPE_DOMAIN of ARRAY_TYPEs.  The other
21272    parameters and return value are as for unify.  */
21273 
21274 static int
unify_array_domain(tree tparms,tree targs,tree parm_dom,tree arg_dom,bool explain_p)21275 unify_array_domain (tree tparms, tree targs,
21276 		    tree parm_dom, tree arg_dom,
21277 		    bool explain_p)
21278 {
21279   tree parm_max;
21280   tree arg_max;
21281   bool parm_cst;
21282   bool arg_cst;
21283 
21284   /* Our representation of array types uses "N - 1" as the
21285      TYPE_MAX_VALUE for an array with "N" elements, if "N" is
21286      not an integer constant.  We cannot unify arbitrarily
21287      complex expressions, so we eliminate the MINUS_EXPRs
21288      here.  */
21289   parm_max = TYPE_MAX_VALUE (parm_dom);
21290   parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
21291   if (!parm_cst)
21292     {
21293       gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
21294       parm_max = TREE_OPERAND (parm_max, 0);
21295     }
21296   arg_max = TYPE_MAX_VALUE (arg_dom);
21297   arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
21298   if (!arg_cst)
21299     {
21300       /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
21301 	 trying to unify the type of a variable with the type
21302 	 of a template parameter.  For example:
21303 
21304 	   template <unsigned int N>
21305 	   void f (char (&) [N]);
21306 	   int g();
21307 	   void h(int i) {
21308 	     char a[g(i)];
21309 	     f(a);
21310 	   }
21311 
21312 	 Here, the type of the ARG will be "int [g(i)]", and
21313 	 may be a SAVE_EXPR, etc.  */
21314       if (TREE_CODE (arg_max) != MINUS_EXPR)
21315 	return unify_vla_arg (explain_p, arg_dom);
21316       arg_max = TREE_OPERAND (arg_max, 0);
21317     }
21318 
21319   /* If only one of the bounds used a MINUS_EXPR, compensate
21320      by adding one to the other bound.  */
21321   if (parm_cst && !arg_cst)
21322     parm_max = fold_build2_loc (input_location, PLUS_EXPR,
21323 				integer_type_node,
21324 				parm_max,
21325 				integer_one_node);
21326   else if (arg_cst && !parm_cst)
21327     arg_max = fold_build2_loc (input_location, PLUS_EXPR,
21328 			       integer_type_node,
21329 			       arg_max,
21330 			       integer_one_node);
21331 
21332   return unify (tparms, targs, parm_max, arg_max,
21333 		UNIFY_ALLOW_INTEGER, explain_p);
21334 }
21335 
21336 /* Returns whether T, a P or A in unify, is a type, template or expression.  */
21337 
21338 enum pa_kind_t { pa_type, pa_tmpl, pa_expr };
21339 
21340 static pa_kind_t
pa_kind(tree t)21341 pa_kind (tree t)
21342 {
21343   if (PACK_EXPANSION_P (t))
21344     t = PACK_EXPANSION_PATTERN (t);
21345   if (TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM
21346       || TREE_CODE (t) == UNBOUND_CLASS_TEMPLATE
21347       || DECL_TYPE_TEMPLATE_P (t))
21348     return pa_tmpl;
21349   else if (TYPE_P (t))
21350     return pa_type;
21351   else
21352     return pa_expr;
21353 }
21354 
21355 /* Deduce the value of template parameters.  TPARMS is the (innermost)
21356    set of template parameters to a template.  TARGS is the bindings
21357    for those template parameters, as determined thus far; TARGS may
21358    include template arguments for outer levels of template parameters
21359    as well.  PARM is a parameter to a template function, or a
21360    subcomponent of that parameter; ARG is the corresponding argument.
21361    This function attempts to match PARM with ARG in a manner
21362    consistent with the existing assignments in TARGS.  If more values
21363    are deduced, then TARGS is updated.
21364 
21365    Returns 0 if the type deduction succeeds, 1 otherwise.  The
21366    parameter STRICT is a bitwise or of the following flags:
21367 
21368      UNIFY_ALLOW_NONE:
21369        Require an exact match between PARM and ARG.
21370      UNIFY_ALLOW_MORE_CV_QUAL:
21371        Allow the deduced ARG to be more cv-qualified (by qualification
21372        conversion) than ARG.
21373      UNIFY_ALLOW_LESS_CV_QUAL:
21374        Allow the deduced ARG to be less cv-qualified than ARG.
21375      UNIFY_ALLOW_DERIVED:
21376        Allow the deduced ARG to be a template base class of ARG,
21377        or a pointer to a template base class of the type pointed to by
21378        ARG.
21379      UNIFY_ALLOW_INTEGER:
21380        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
21381        case for more information.
21382      UNIFY_ALLOW_OUTER_LEVEL:
21383        This is the outermost level of a deduction. Used to determine validity
21384        of qualification conversions. A valid qualification conversion must
21385        have const qualified pointers leading up to the inner type which
21386        requires additional CV quals, except at the outer level, where const
21387        is not required [conv.qual]. It would be normal to set this flag in
21388        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
21389      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
21390        This is the outermost level of a deduction, and PARM can be more CV
21391        qualified at this point.
21392      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
21393        This is the outermost level of a deduction, and PARM can be less CV
21394        qualified at this point.  */
21395 
21396 static int
unify(tree tparms,tree targs,tree parm,tree arg,int strict,bool explain_p)21397 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
21398        bool explain_p)
21399 {
21400   int idx;
21401   tree targ;
21402   tree tparm;
21403   int strict_in = strict;
21404   tsubst_flags_t complain = (explain_p
21405 			     ? tf_warning_or_error
21406 			     : tf_none);
21407 
21408   /* I don't think this will do the right thing with respect to types.
21409      But the only case I've seen it in so far has been array bounds, where
21410      signedness is the only information lost, and I think that will be
21411      okay.  */
21412   while (CONVERT_EXPR_P (parm))
21413     parm = TREE_OPERAND (parm, 0);
21414 
21415   if (arg == error_mark_node)
21416     return unify_invalid (explain_p);
21417   if (arg == unknown_type_node
21418       || arg == init_list_type_node)
21419     /* We can't deduce anything from this, but we might get all the
21420        template args from other function args.  */
21421     return unify_success (explain_p);
21422 
21423   if (parm == any_targ_node || arg == any_targ_node)
21424     return unify_success (explain_p);
21425 
21426   /* If PARM uses template parameters, then we can't bail out here,
21427      even if ARG == PARM, since we won't record unifications for the
21428      template parameters.  We might need them if we're trying to
21429      figure out which of two things is more specialized.  */
21430   if (arg == parm && !uses_template_parms (parm))
21431     return unify_success (explain_p);
21432 
21433   /* Handle init lists early, so the rest of the function can assume
21434      we're dealing with a type. */
21435   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
21436     {
21437       tree elt, elttype;
21438       unsigned i;
21439       tree orig_parm = parm;
21440 
21441       /* Replace T with std::initializer_list<T> for deduction.  */
21442       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
21443 	  && flag_deduce_init_list)
21444 	parm = listify (parm);
21445 
21446       if (!is_std_init_list (parm)
21447 	  && TREE_CODE (parm) != ARRAY_TYPE)
21448 	/* We can only deduce from an initializer list argument if the
21449 	   parameter is std::initializer_list or an array; otherwise this
21450 	   is a non-deduced context. */
21451 	return unify_success (explain_p);
21452 
21453       if (TREE_CODE (parm) == ARRAY_TYPE)
21454 	elttype = TREE_TYPE (parm);
21455       else
21456 	{
21457 	  elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
21458 	  /* Deduction is defined in terms of a single type, so just punt
21459 	     on the (bizarre) std::initializer_list<T...>.  */
21460 	  if (PACK_EXPANSION_P (elttype))
21461 	    return unify_success (explain_p);
21462 	}
21463 
21464       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
21465 	{
21466 	  int elt_strict = strict;
21467 
21468 	  if (elt == error_mark_node)
21469 	    return unify_invalid (explain_p);
21470 
21471 	  if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
21472 	    {
21473 	      tree type = TREE_TYPE (elt);
21474 	      if (type == error_mark_node)
21475 		return unify_invalid (explain_p);
21476 	      /* It should only be possible to get here for a call.  */
21477 	      gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
21478 	      elt_strict |= maybe_adjust_types_for_deduction
21479 		(DEDUCE_CALL, &elttype, &type, elt);
21480 	      elt = type;
21481 	    }
21482 
21483 	  RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
21484 				   explain_p);
21485 	}
21486 
21487       if (TREE_CODE (parm) == ARRAY_TYPE
21488 	  && deducible_array_bound (TYPE_DOMAIN (parm)))
21489 	{
21490 	  /* Also deduce from the length of the initializer list.  */
21491 	  tree max = size_int (CONSTRUCTOR_NELTS (arg));
21492 	  tree idx = compute_array_index_type (NULL_TREE, max, tf_none);
21493 	  if (idx == error_mark_node)
21494 	    return unify_invalid (explain_p);
21495 	  return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
21496 				     idx, explain_p);
21497 	}
21498 
21499       /* If the std::initializer_list<T> deduction worked, replace the
21500 	 deduced A with std::initializer_list<A>.  */
21501       if (orig_parm != parm)
21502 	{
21503 	  idx = TEMPLATE_TYPE_IDX (orig_parm);
21504 	  targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
21505 	  targ = listify (targ);
21506 	  TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
21507 	}
21508       return unify_success (explain_p);
21509     }
21510 
21511   /* If parm and arg aren't the same kind of thing (template, type, or
21512      expression), fail early.  */
21513   if (pa_kind (parm) != pa_kind (arg))
21514     return unify_invalid (explain_p);
21515 
21516   /* Immediately reject some pairs that won't unify because of
21517      cv-qualification mismatches.  */
21518   if (TREE_CODE (arg) == TREE_CODE (parm)
21519       && TYPE_P (arg)
21520       /* It is the elements of the array which hold the cv quals of an array
21521 	 type, and the elements might be template type parms. We'll check
21522 	 when we recurse.  */
21523       && TREE_CODE (arg) != ARRAY_TYPE
21524       /* We check the cv-qualifiers when unifying with template type
21525 	 parameters below.  We want to allow ARG `const T' to unify with
21526 	 PARM `T' for example, when computing which of two templates
21527 	 is more specialized, for example.  */
21528       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
21529       && !check_cv_quals_for_unify (strict_in, arg, parm))
21530     return unify_cv_qual_mismatch (explain_p, parm, arg);
21531 
21532   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
21533       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
21534     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
21535   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
21536   strict &= ~UNIFY_ALLOW_DERIVED;
21537   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
21538   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
21539 
21540   switch (TREE_CODE (parm))
21541     {
21542     case TYPENAME_TYPE:
21543     case SCOPE_REF:
21544     case UNBOUND_CLASS_TEMPLATE:
21545       /* In a type which contains a nested-name-specifier, template
21546 	 argument values cannot be deduced for template parameters used
21547 	 within the nested-name-specifier.  */
21548       return unify_success (explain_p);
21549 
21550     case TEMPLATE_TYPE_PARM:
21551     case TEMPLATE_TEMPLATE_PARM:
21552     case BOUND_TEMPLATE_TEMPLATE_PARM:
21553       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
21554       if (error_operand_p (tparm))
21555 	return unify_invalid (explain_p);
21556 
21557       if (TEMPLATE_TYPE_LEVEL (parm)
21558 	  != template_decl_level (tparm))
21559 	/* The PARM is not one we're trying to unify.  Just check
21560 	   to see if it matches ARG.  */
21561 	{
21562 	  if (TREE_CODE (arg) == TREE_CODE (parm)
21563 	      && (is_auto (parm) ? is_auto (arg)
21564 		  : same_type_p (parm, arg)))
21565 	    return unify_success (explain_p);
21566 	  else
21567 	    return unify_type_mismatch (explain_p, parm, arg);
21568 	}
21569       idx = TEMPLATE_TYPE_IDX (parm);
21570       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
21571       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
21572       if (error_operand_p (tparm))
21573 	return unify_invalid (explain_p);
21574 
21575       /* Check for mixed types and values.  */
21576       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
21577 	   && TREE_CODE (tparm) != TYPE_DECL)
21578 	  || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
21579 	      && TREE_CODE (tparm) != TEMPLATE_DECL))
21580 	gcc_unreachable ();
21581 
21582       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
21583 	{
21584 	  if ((strict_in & UNIFY_ALLOW_DERIVED)
21585 	      && CLASS_TYPE_P (arg))
21586 	    {
21587 	      /* First try to match ARG directly.  */
21588 	      tree t = try_class_unification (tparms, targs, parm, arg,
21589 					      explain_p);
21590 	      if (!t)
21591 		{
21592 		  /* Otherwise, look for a suitable base of ARG, as below.  */
21593 		  enum template_base_result r;
21594 		  r = get_template_base (tparms, targs, parm, arg,
21595 					 explain_p, &t);
21596 		  if (!t)
21597 		    return unify_no_common_base (explain_p, r, parm, arg);
21598 		  arg = t;
21599 		}
21600 	    }
21601 	  /* ARG must be constructed from a template class or a template
21602 	     template parameter.  */
21603 	  else if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
21604 		   && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
21605 	    return unify_template_deduction_failure (explain_p, parm, arg);
21606 
21607 	  /* Deduce arguments T, i from TT<T> or TT<i>.  */
21608 	  if (unify_bound_ttp_args (tparms, targs, parm, arg, explain_p))
21609 	    return 1;
21610 
21611 	  arg = TYPE_TI_TEMPLATE (arg);
21612 
21613 	  /* Fall through to deduce template name.  */
21614 	}
21615 
21616       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
21617 	  || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
21618 	{
21619 	  /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
21620 
21621 	  /* Simple cases: Value already set, does match or doesn't.  */
21622 	  if (targ != NULL_TREE && template_args_equal (targ, arg))
21623 	    return unify_success (explain_p);
21624 	  else if (targ)
21625 	    return unify_inconsistency (explain_p, parm, targ, arg);
21626 	}
21627       else
21628 	{
21629 	  /* If PARM is `const T' and ARG is only `int', we don't have
21630 	     a match unless we are allowing additional qualification.
21631 	     If ARG is `const int' and PARM is just `T' that's OK;
21632 	     that binds `const int' to `T'.  */
21633 	  if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
21634 					 arg, parm))
21635 	    return unify_cv_qual_mismatch (explain_p, parm, arg);
21636 
21637 	  /* Consider the case where ARG is `const volatile int' and
21638 	     PARM is `const T'.  Then, T should be `volatile int'.  */
21639 	  arg = cp_build_qualified_type_real
21640 	    (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
21641 	  if (arg == error_mark_node)
21642 	    return unify_invalid (explain_p);
21643 
21644 	  /* Simple cases: Value already set, does match or doesn't.  */
21645 	  if (targ != NULL_TREE && same_type_p (targ, arg))
21646 	    return unify_success (explain_p);
21647 	  else if (targ)
21648 	    return unify_inconsistency (explain_p, parm, targ, arg);
21649 
21650 	  /* Make sure that ARG is not a variable-sized array.  (Note
21651 	     that were talking about variable-sized arrays (like
21652 	     `int[n]'), rather than arrays of unknown size (like
21653 	     `int[]').)  We'll get very confused by such a type since
21654 	     the bound of the array is not constant, and therefore
21655 	     not mangleable.  Besides, such types are not allowed in
21656 	     ISO C++, so we can do as we please here.  We do allow
21657 	     them for 'auto' deduction, since that isn't ABI-exposed.  */
21658 	  if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
21659 	    return unify_vla_arg (explain_p, arg);
21660 
21661 	  /* Strip typedefs as in convert_template_argument.  */
21662 	  arg = canonicalize_type_argument (arg, tf_none);
21663 	}
21664 
21665       /* If ARG is a parameter pack or an expansion, we cannot unify
21666 	 against it unless PARM is also a parameter pack.  */
21667       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
21668 	  && !template_parameter_pack_p (parm))
21669 	return unify_parameter_pack_mismatch (explain_p, parm, arg);
21670 
21671       /* If the argument deduction results is a METHOD_TYPE,
21672          then there is a problem.
21673          METHOD_TYPE doesn't map to any real C++ type the result of
21674 	 the deduction can not be of that type.  */
21675       if (TREE_CODE (arg) == METHOD_TYPE)
21676 	return unify_method_type_error (explain_p, arg);
21677 
21678       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
21679       return unify_success (explain_p);
21680 
21681     case TEMPLATE_PARM_INDEX:
21682       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
21683       if (error_operand_p (tparm))
21684 	return unify_invalid (explain_p);
21685 
21686       if (TEMPLATE_PARM_LEVEL (parm)
21687 	  != template_decl_level (tparm))
21688 	{
21689 	  /* The PARM is not one we're trying to unify.  Just check
21690 	     to see if it matches ARG.  */
21691 	  int result = !(TREE_CODE (arg) == TREE_CODE (parm)
21692 			 && cp_tree_equal (parm, arg));
21693 	  if (result)
21694 	    unify_expression_unequal (explain_p, parm, arg);
21695 	  return result;
21696 	}
21697 
21698       idx = TEMPLATE_PARM_IDX (parm);
21699       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
21700 
21701       if (targ)
21702 	{
21703 	  if ((strict & UNIFY_ALLOW_INTEGER)
21704 	      && TREE_TYPE (targ) && TREE_TYPE (arg)
21705 	      && CP_INTEGRAL_TYPE_P (TREE_TYPE (targ)))
21706 	    /* We're deducing from an array bound, the type doesn't matter.  */
21707 	    arg = fold_convert (TREE_TYPE (targ), arg);
21708 	  int x = !cp_tree_equal (targ, arg);
21709 	  if (x)
21710 	    unify_inconsistency (explain_p, parm, targ, arg);
21711 	  return x;
21712 	}
21713 
21714       /* [temp.deduct.type] If, in the declaration of a function template
21715 	 with a non-type template-parameter, the non-type
21716 	 template-parameter is used in an expression in the function
21717 	 parameter-list and, if the corresponding template-argument is
21718 	 deduced, the template-argument type shall match the type of the
21719 	 template-parameter exactly, except that a template-argument
21720 	 deduced from an array bound may be of any integral type.
21721 	 The non-type parameter might use already deduced type parameters.  */
21722       tparm = TREE_TYPE (parm);
21723       if (TEMPLATE_PARM_LEVEL (parm) > TMPL_ARGS_DEPTH (targs))
21724 	/* We don't have enough levels of args to do any substitution.  This
21725 	   can happen in the context of -fnew-ttp-matching.  */;
21726       else
21727 	{
21728 	  ++processing_template_decl;
21729 	  tparm = tsubst (tparm, targs, tf_none, NULL_TREE);
21730 	  --processing_template_decl;
21731 
21732 	  if (tree a = type_uses_auto (tparm))
21733 	    {
21734 	      tparm = do_auto_deduction (tparm, arg, a, complain, adc_unify);
21735 	      if (tparm == error_mark_node)
21736 		return 1;
21737 	    }
21738 	}
21739 
21740       if (!TREE_TYPE (arg))
21741 	/* Template-parameter dependent expression.  Just accept it for now.
21742 	   It will later be processed in convert_template_argument.  */
21743 	;
21744       else if (same_type_p (non_reference (TREE_TYPE (arg)),
21745 			    non_reference (tparm)))
21746 	/* OK */;
21747       else if ((strict & UNIFY_ALLOW_INTEGER)
21748 	       && CP_INTEGRAL_TYPE_P (tparm))
21749 	/* Convert the ARG to the type of PARM; the deduced non-type
21750 	   template argument must exactly match the types of the
21751 	   corresponding parameter.  */
21752 	arg = fold (build_nop (tparm, arg));
21753       else if (uses_template_parms (tparm))
21754 	{
21755 	  /* We haven't deduced the type of this parameter yet.  */
21756 	  if (cxx_dialect >= cxx17
21757 	      /* We deduce from array bounds in try_array_deduction.  */
21758 	      && !(strict & UNIFY_ALLOW_INTEGER))
21759 	    {
21760 	      /* Deduce it from the non-type argument.  */
21761 	      tree atype = TREE_TYPE (arg);
21762 	      RECUR_AND_CHECK_FAILURE (tparms, targs,
21763 				       tparm, atype,
21764 				       UNIFY_ALLOW_NONE, explain_p);
21765 	    }
21766 	  else
21767 	    /* Try again later.  */
21768 	    return unify_success (explain_p);
21769 	}
21770       else
21771 	return unify_type_mismatch (explain_p, tparm, TREE_TYPE (arg));
21772 
21773       /* If ARG is a parameter pack or an expansion, we cannot unify
21774 	 against it unless PARM is also a parameter pack.  */
21775       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
21776 	  && !TEMPLATE_PARM_PARAMETER_PACK (parm))
21777 	return unify_parameter_pack_mismatch (explain_p, parm, arg);
21778 
21779       {
21780 	bool removed_attr = false;
21781 	arg = strip_typedefs_expr (arg, &removed_attr);
21782       }
21783       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
21784       return unify_success (explain_p);
21785 
21786     case PTRMEM_CST:
21787      {
21788 	/* A pointer-to-member constant can be unified only with
21789 	 another constant.  */
21790       if (TREE_CODE (arg) != PTRMEM_CST)
21791 	return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
21792 
21793       /* Just unify the class member. It would be useless (and possibly
21794 	 wrong, depending on the strict flags) to unify also
21795 	 PTRMEM_CST_CLASS, because we want to be sure that both parm and
21796 	 arg refer to the same variable, even if through different
21797 	 classes. For instance:
21798 
21799 	 struct A { int x; };
21800 	 struct B : A { };
21801 
21802 	 Unification of &A::x and &B::x must succeed.  */
21803       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
21804 		    PTRMEM_CST_MEMBER (arg), strict, explain_p);
21805      }
21806 
21807     case POINTER_TYPE:
21808       {
21809 	if (!TYPE_PTR_P (arg))
21810 	  return unify_type_mismatch (explain_p, parm, arg);
21811 
21812 	/* [temp.deduct.call]
21813 
21814 	   A can be another pointer or pointer to member type that can
21815 	   be converted to the deduced A via a qualification
21816 	   conversion (_conv.qual_).
21817 
21818 	   We pass down STRICT here rather than UNIFY_ALLOW_NONE.
21819 	   This will allow for additional cv-qualification of the
21820 	   pointed-to types if appropriate.  */
21821 
21822 	if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
21823 	  /* The derived-to-base conversion only persists through one
21824 	     level of pointers.  */
21825 	  strict |= (strict_in & UNIFY_ALLOW_DERIVED);
21826 
21827 	return unify (tparms, targs, TREE_TYPE (parm),
21828 		      TREE_TYPE (arg), strict, explain_p);
21829       }
21830 
21831     case REFERENCE_TYPE:
21832       if (TREE_CODE (arg) != REFERENCE_TYPE)
21833 	return unify_type_mismatch (explain_p, parm, arg);
21834       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
21835 		    strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
21836 
21837     case ARRAY_TYPE:
21838       if (TREE_CODE (arg) != ARRAY_TYPE)
21839 	return unify_type_mismatch (explain_p, parm, arg);
21840       if ((TYPE_DOMAIN (parm) == NULL_TREE)
21841 	  != (TYPE_DOMAIN (arg) == NULL_TREE))
21842 	return unify_type_mismatch (explain_p, parm, arg);
21843       RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
21844 			       strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
21845       if (TYPE_DOMAIN (parm) != NULL_TREE)
21846 	return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
21847 				   TYPE_DOMAIN (arg), explain_p);
21848       return unify_success (explain_p);
21849 
21850     case REAL_TYPE:
21851     case COMPLEX_TYPE:
21852     case VECTOR_TYPE:
21853     case INTEGER_TYPE:
21854     case BOOLEAN_TYPE:
21855     case ENUMERAL_TYPE:
21856     case VOID_TYPE:
21857     case NULLPTR_TYPE:
21858       if (TREE_CODE (arg) != TREE_CODE (parm))
21859 	return unify_type_mismatch (explain_p, parm, arg);
21860 
21861       /* We have already checked cv-qualification at the top of the
21862 	 function.  */
21863       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
21864 	return unify_type_mismatch (explain_p, parm, arg);
21865 
21866       /* As far as unification is concerned, this wins.	 Later checks
21867 	 will invalidate it if necessary.  */
21868       return unify_success (explain_p);
21869 
21870       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
21871       /* Type INTEGER_CST can come from ordinary constant template args.  */
21872     case INTEGER_CST:
21873       while (CONVERT_EXPR_P (arg))
21874 	arg = TREE_OPERAND (arg, 0);
21875 
21876       if (TREE_CODE (arg) != INTEGER_CST)
21877 	return unify_template_argument_mismatch (explain_p, parm, arg);
21878       return (tree_int_cst_equal (parm, arg)
21879 	      ? unify_success (explain_p)
21880 	      : unify_template_argument_mismatch (explain_p, parm, arg));
21881 
21882     case TREE_VEC:
21883       {
21884 	int i, len, argslen;
21885 	int parm_variadic_p = 0;
21886 
21887 	if (TREE_CODE (arg) != TREE_VEC)
21888 	  return unify_template_argument_mismatch (explain_p, parm, arg);
21889 
21890 	len = TREE_VEC_LENGTH (parm);
21891 	argslen = TREE_VEC_LENGTH (arg);
21892 
21893 	/* Check for pack expansions in the parameters.  */
21894 	for (i = 0; i < len; ++i)
21895 	  {
21896 	    if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
21897 	      {
21898 		if (i == len - 1)
21899 		  /* We can unify against something with a trailing
21900 		     parameter pack.  */
21901 		  parm_variadic_p = 1;
21902 		else
21903 		  /* [temp.deduct.type]/9: If the template argument list of
21904 		     P contains a pack expansion that is not the last
21905 		     template argument, the entire template argument list
21906 		     is a non-deduced context.  */
21907 		  return unify_success (explain_p);
21908 	      }
21909 	  }
21910 
21911         /* If we don't have enough arguments to satisfy the parameters
21912            (not counting the pack expression at the end), or we have
21913            too many arguments for a parameter list that doesn't end in
21914            a pack expression, we can't unify.  */
21915 	if (parm_variadic_p
21916 	    ? argslen < len - parm_variadic_p
21917 	    : argslen != len)
21918 	  return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
21919 
21920 	/* Unify all of the parameters that precede the (optional)
21921 	   pack expression.  */
21922 	for (i = 0; i < len - parm_variadic_p; ++i)
21923 	  {
21924 	    RECUR_AND_CHECK_FAILURE (tparms, targs,
21925 				     TREE_VEC_ELT (parm, i),
21926 				     TREE_VEC_ELT (arg, i),
21927 				     UNIFY_ALLOW_NONE, explain_p);
21928 	  }
21929 	if (parm_variadic_p)
21930 	  return unify_pack_expansion (tparms, targs, parm, arg,
21931 				       DEDUCE_EXACT,
21932 				       /*subr=*/true, explain_p);
21933 	return unify_success (explain_p);
21934       }
21935 
21936     case RECORD_TYPE:
21937     case UNION_TYPE:
21938       if (TREE_CODE (arg) != TREE_CODE (parm))
21939 	return unify_type_mismatch (explain_p, parm, arg);
21940 
21941       if (TYPE_PTRMEMFUNC_P (parm))
21942 	{
21943 	  if (!TYPE_PTRMEMFUNC_P (arg))
21944 	    return unify_type_mismatch (explain_p, parm, arg);
21945 
21946 	  return unify (tparms, targs,
21947 			TYPE_PTRMEMFUNC_FN_TYPE (parm),
21948 			TYPE_PTRMEMFUNC_FN_TYPE (arg),
21949 			strict, explain_p);
21950 	}
21951       else if (TYPE_PTRMEMFUNC_P (arg))
21952 	return unify_type_mismatch (explain_p, parm, arg);
21953 
21954       if (CLASSTYPE_TEMPLATE_INFO (parm))
21955 	{
21956 	  tree t = NULL_TREE;
21957 
21958 	  if (strict_in & UNIFY_ALLOW_DERIVED)
21959 	    {
21960 	      /* First, we try to unify the PARM and ARG directly.  */
21961 	      t = try_class_unification (tparms, targs,
21962 					 parm, arg, explain_p);
21963 
21964 	      if (!t)
21965 		{
21966 		  /* Fallback to the special case allowed in
21967 		     [temp.deduct.call]:
21968 
21969 		       If P is a class, and P has the form
21970 		       template-id, then A can be a derived class of
21971 		       the deduced A.  Likewise, if P is a pointer to
21972 		       a class of the form template-id, A can be a
21973 		       pointer to a derived class pointed to by the
21974 		       deduced A.  */
21975 		  enum template_base_result r;
21976 		  r = get_template_base (tparms, targs, parm, arg,
21977 					 explain_p, &t);
21978 
21979 		  if (!t)
21980 		    {
21981 		      /* Don't give the derived diagnostic if we're
21982 			 already dealing with the same template.  */
21983 		      bool same_template
21984 			= (CLASSTYPE_TEMPLATE_INFO (arg)
21985 			   && (CLASSTYPE_TI_TEMPLATE (parm)
21986 			       == CLASSTYPE_TI_TEMPLATE (arg)));
21987 		      return unify_no_common_base (explain_p && !same_template,
21988 						   r, parm, arg);
21989 		    }
21990 		}
21991 	    }
21992 	  else if (CLASSTYPE_TEMPLATE_INFO (arg)
21993 		   && (CLASSTYPE_TI_TEMPLATE (parm)
21994 		       == CLASSTYPE_TI_TEMPLATE (arg)))
21995 	    /* Perhaps PARM is something like S<U> and ARG is S<int>.
21996 	       Then, we should unify `int' and `U'.  */
21997 	    t = arg;
21998 	  else
21999 	    /* There's no chance of unification succeeding.  */
22000 	    return unify_type_mismatch (explain_p, parm, arg);
22001 
22002 	  return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
22003 			CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE, explain_p);
22004 	}
22005       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
22006 	return unify_type_mismatch (explain_p, parm, arg);
22007       return unify_success (explain_p);
22008 
22009     case METHOD_TYPE:
22010     case FUNCTION_TYPE:
22011       {
22012 	unsigned int nargs;
22013 	tree *args;
22014 	tree a;
22015 	unsigned int i;
22016 
22017 	if (TREE_CODE (arg) != TREE_CODE (parm))
22018 	  return unify_type_mismatch (explain_p, parm, arg);
22019 
22020 	/* CV qualifications for methods can never be deduced, they must
22021 	   match exactly.  We need to check them explicitly here,
22022 	   because type_unification_real treats them as any other
22023 	   cv-qualified parameter.  */
22024 	if (TREE_CODE (parm) == METHOD_TYPE
22025 	    && (!check_cv_quals_for_unify
22026 		(UNIFY_ALLOW_NONE,
22027 		 class_of_this_parm (arg),
22028 		 class_of_this_parm (parm))))
22029 	  return unify_cv_qual_mismatch (explain_p, parm, arg);
22030 	if (TREE_CODE (arg) == FUNCTION_TYPE
22031 	    && type_memfn_quals (parm) != type_memfn_quals (arg))
22032 	  return unify_cv_qual_mismatch (explain_p, parm, arg);
22033 	if (type_memfn_rqual (parm) != type_memfn_rqual (arg))
22034 	  return unify_type_mismatch (explain_p, parm, arg);
22035 
22036 	RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
22037 				 TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
22038 
22039 	nargs = list_length (TYPE_ARG_TYPES (arg));
22040 	args = XALLOCAVEC (tree, nargs);
22041 	for (a = TYPE_ARG_TYPES (arg), i = 0;
22042 	     a != NULL_TREE && a != void_list_node;
22043 	     a = TREE_CHAIN (a), ++i)
22044 	  args[i] = TREE_VALUE (a);
22045 	nargs = i;
22046 
22047 	if (type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
22048 				   args, nargs, 1, DEDUCE_EXACT,
22049 				   LOOKUP_NORMAL, NULL, explain_p))
22050 	  return 1;
22051 
22052 	if (flag_noexcept_type)
22053 	  {
22054 	    tree pspec = TYPE_RAISES_EXCEPTIONS (parm);
22055 	    tree aspec = canonical_eh_spec (TYPE_RAISES_EXCEPTIONS (arg));
22056 	    if (pspec == NULL_TREE) pspec = noexcept_false_spec;
22057 	    if (aspec == NULL_TREE) aspec = noexcept_false_spec;
22058 	    if (TREE_PURPOSE (pspec) && TREE_PURPOSE (aspec)
22059 		&& uses_template_parms (TREE_PURPOSE (pspec)))
22060 	      RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_PURPOSE (pspec),
22061 				       TREE_PURPOSE (aspec),
22062 				       UNIFY_ALLOW_NONE, explain_p);
22063 	    else if (nothrow_spec_p (pspec) && !nothrow_spec_p (aspec))
22064 	      return unify_type_mismatch (explain_p, parm, arg);
22065 	  }
22066 
22067 	return 0;
22068       }
22069 
22070     case OFFSET_TYPE:
22071       /* Unify a pointer to member with a pointer to member function, which
22072 	 deduces the type of the member as a function type. */
22073       if (TYPE_PTRMEMFUNC_P (arg))
22074 	{
22075 	  /* Check top-level cv qualifiers */
22076 	  if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
22077 	    return unify_cv_qual_mismatch (explain_p, parm, arg);
22078 
22079 	  RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
22080 				   TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
22081 				   UNIFY_ALLOW_NONE, explain_p);
22082 
22083 	  /* Determine the type of the function we are unifying against. */
22084 	  tree fntype = static_fn_type (arg);
22085 
22086 	  return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
22087 	}
22088 
22089       if (TREE_CODE (arg) != OFFSET_TYPE)
22090 	return unify_type_mismatch (explain_p, parm, arg);
22091       RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
22092 			       TYPE_OFFSET_BASETYPE (arg),
22093 			       UNIFY_ALLOW_NONE, explain_p);
22094       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
22095 		    strict, explain_p);
22096 
22097     case CONST_DECL:
22098       if (DECL_TEMPLATE_PARM_P (parm))
22099 	return unify (tparms, targs, DECL_INITIAL (parm), arg, strict, explain_p);
22100       if (arg != scalar_constant_value (parm))
22101 	return unify_template_argument_mismatch (explain_p, parm, arg);
22102       return unify_success (explain_p);
22103 
22104     case FIELD_DECL:
22105     case TEMPLATE_DECL:
22106       /* Matched cases are handled by the ARG == PARM test above.  */
22107       return unify_template_argument_mismatch (explain_p, parm, arg);
22108 
22109     case VAR_DECL:
22110       /* We might get a variable as a non-type template argument in parm if the
22111 	 corresponding parameter is type-dependent.  Make any necessary
22112 	 adjustments based on whether arg is a reference.  */
22113       if (CONSTANT_CLASS_P (arg))
22114 	parm = fold_non_dependent_expr (parm);
22115       else if (REFERENCE_REF_P (arg))
22116 	{
22117 	  tree sub = TREE_OPERAND (arg, 0);
22118 	  STRIP_NOPS (sub);
22119 	  if (TREE_CODE (sub) == ADDR_EXPR)
22120 	    arg = TREE_OPERAND (sub, 0);
22121 	}
22122       /* Now use the normal expression code to check whether they match.  */
22123       goto expr;
22124 
22125     case TYPE_ARGUMENT_PACK:
22126     case NONTYPE_ARGUMENT_PACK:
22127       return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
22128 		    ARGUMENT_PACK_ARGS (arg), strict, explain_p);
22129 
22130     case TYPEOF_TYPE:
22131     case DECLTYPE_TYPE:
22132     case UNDERLYING_TYPE:
22133       /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
22134 	 or UNDERLYING_TYPE nodes.  */
22135       return unify_success (explain_p);
22136 
22137     case ERROR_MARK:
22138       /* Unification fails if we hit an error node.  */
22139       return unify_invalid (explain_p);
22140 
22141     case INDIRECT_REF:
22142       if (REFERENCE_REF_P (parm))
22143 	{
22144 	  bool pexp = PACK_EXPANSION_P (arg);
22145 	  if (pexp)
22146 	    arg = PACK_EXPANSION_PATTERN (arg);
22147 	  if (REFERENCE_REF_P (arg))
22148 	    arg = TREE_OPERAND (arg, 0);
22149 	  if (pexp)
22150 	    arg = make_pack_expansion (arg, complain);
22151 	  return unify (tparms, targs, TREE_OPERAND (parm, 0), arg,
22152 			strict, explain_p);
22153 	}
22154       /* FALLTHRU */
22155 
22156     default:
22157       /* An unresolved overload is a nondeduced context.  */
22158       if (is_overloaded_fn (parm) || type_unknown_p (parm))
22159 	return unify_success (explain_p);
22160       gcc_assert (EXPR_P (parm) || TREE_CODE (parm) == TRAIT_EXPR);
22161     expr:
22162       /* We must be looking at an expression.  This can happen with
22163 	 something like:
22164 
22165 	   template <int I>
22166 	   void foo(S<I>, S<I + 2>);
22167 
22168 	 This is a "nondeduced context":
22169 
22170 	   [deduct.type]
22171 
22172 	   The nondeduced contexts are:
22173 
22174 	   --A type that is a template-id in which one or more of
22175 	     the template-arguments is an expression that references
22176 	     a template-parameter.
22177 
22178 	 In these cases, we assume deduction succeeded, but don't
22179 	 actually infer any unifications.  */
22180 
22181       if (!uses_template_parms (parm)
22182 	  && !template_args_equal (parm, arg))
22183 	return unify_expression_unequal (explain_p, parm, arg);
22184       else
22185 	return unify_success (explain_p);
22186     }
22187 }
22188 #undef RECUR_AND_CHECK_FAILURE
22189 
22190 /* Note that DECL can be defined in this translation unit, if
22191    required.  */
22192 
22193 static void
mark_definable(tree decl)22194 mark_definable (tree decl)
22195 {
22196   tree clone;
22197   DECL_NOT_REALLY_EXTERN (decl) = 1;
22198   FOR_EACH_CLONE (clone, decl)
22199     DECL_NOT_REALLY_EXTERN (clone) = 1;
22200 }
22201 
22202 /* Called if RESULT is explicitly instantiated, or is a member of an
22203    explicitly instantiated class.  */
22204 
22205 void
mark_decl_instantiated(tree result,int extern_p)22206 mark_decl_instantiated (tree result, int extern_p)
22207 {
22208   SET_DECL_EXPLICIT_INSTANTIATION (result);
22209 
22210   /* If this entity has already been written out, it's too late to
22211      make any modifications.  */
22212   if (TREE_ASM_WRITTEN (result))
22213     return;
22214 
22215   /* For anonymous namespace we don't need to do anything.  */
22216   if (decl_anon_ns_mem_p (result))
22217     {
22218       gcc_assert (!TREE_PUBLIC (result));
22219       return;
22220     }
22221 
22222   if (TREE_CODE (result) != FUNCTION_DECL)
22223     /* The TREE_PUBLIC flag for function declarations will have been
22224        set correctly by tsubst.  */
22225     TREE_PUBLIC (result) = 1;
22226 
22227   /* This might have been set by an earlier implicit instantiation.  */
22228   DECL_COMDAT (result) = 0;
22229 
22230   if (extern_p)
22231     DECL_NOT_REALLY_EXTERN (result) = 0;
22232   else
22233     {
22234       mark_definable (result);
22235       mark_needed (result);
22236       /* Always make artificials weak.  */
22237       if (DECL_ARTIFICIAL (result) && flag_weak)
22238 	comdat_linkage (result);
22239       /* For WIN32 we also want to put explicit instantiations in
22240 	 linkonce sections.  */
22241       else if (TREE_PUBLIC (result))
22242 	maybe_make_one_only (result);
22243     }
22244 
22245   /* If EXTERN_P, then this function will not be emitted -- unless
22246      followed by an explicit instantiation, at which point its linkage
22247      will be adjusted.  If !EXTERN_P, then this function will be
22248      emitted here.  In neither circumstance do we want
22249      import_export_decl to adjust the linkage.  */
22250   DECL_INTERFACE_KNOWN (result) = 1;
22251 }
22252 
22253 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
22254    important template arguments.  If any are missing, we check whether
22255    they're important by using error_mark_node for substituting into any
22256    args that were used for partial ordering (the ones between ARGS and END)
22257    and seeing if it bubbles up.  */
22258 
22259 static bool
check_undeduced_parms(tree targs,tree args,tree end)22260 check_undeduced_parms (tree targs, tree args, tree end)
22261 {
22262   bool found = false;
22263   int i;
22264   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
22265     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
22266       {
22267 	found = true;
22268 	TREE_VEC_ELT (targs, i) = error_mark_node;
22269       }
22270   if (found)
22271     {
22272       tree substed = tsubst_arg_types (args, targs, end, tf_none, NULL_TREE);
22273       if (substed == error_mark_node)
22274 	return true;
22275     }
22276   return false;
22277 }
22278 
22279 /* Given two function templates PAT1 and PAT2, return:
22280 
22281    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
22282    -1 if PAT2 is more specialized than PAT1.
22283    0 if neither is more specialized.
22284 
22285    LEN indicates the number of parameters we should consider
22286    (defaulted parameters should not be considered).
22287 
22288    The 1998 std underspecified function template partial ordering, and
22289    DR214 addresses the issue.  We take pairs of arguments, one from
22290    each of the templates, and deduce them against each other.  One of
22291    the templates will be more specialized if all the *other*
22292    template's arguments deduce against its arguments and at least one
22293    of its arguments *does* *not* deduce against the other template's
22294    corresponding argument.  Deduction is done as for class templates.
22295    The arguments used in deduction have reference and top level cv
22296    qualifiers removed.  Iff both arguments were originally reference
22297    types *and* deduction succeeds in both directions, an lvalue reference
22298    wins against an rvalue reference and otherwise the template
22299    with the more cv-qualified argument wins for that pairing (if
22300    neither is more cv-qualified, they both are equal).  Unlike regular
22301    deduction, after all the arguments have been deduced in this way,
22302    we do *not* verify the deduced template argument values can be
22303    substituted into non-deduced contexts.
22304 
22305    The logic can be a bit confusing here, because we look at deduce1 and
22306    targs1 to see if pat2 is at least as specialized, and vice versa; if we
22307    can find template arguments for pat1 to make arg1 look like arg2, that
22308    means that arg2 is at least as specialized as arg1.  */
22309 
22310 int
more_specialized_fn(tree pat1,tree pat2,int len)22311 more_specialized_fn (tree pat1, tree pat2, int len)
22312 {
22313   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
22314   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
22315   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
22316   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
22317   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
22318   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
22319   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
22320   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
22321   tree origs1, origs2;
22322   bool lose1 = false;
22323   bool lose2 = false;
22324 
22325   /* Remove the this parameter from non-static member functions.  If
22326      one is a non-static member function and the other is not a static
22327      member function, remove the first parameter from that function
22328      also.  This situation occurs for operator functions where we
22329      locate both a member function (with this pointer) and non-member
22330      operator (with explicit first operand).  */
22331   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
22332     {
22333       len--; /* LEN is the number of significant arguments for DECL1 */
22334       args1 = TREE_CHAIN (args1);
22335       if (!DECL_STATIC_FUNCTION_P (decl2))
22336 	args2 = TREE_CHAIN (args2);
22337     }
22338   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
22339     {
22340       args2 = TREE_CHAIN (args2);
22341       if (!DECL_STATIC_FUNCTION_P (decl1))
22342 	{
22343 	  len--;
22344 	  args1 = TREE_CHAIN (args1);
22345 	}
22346     }
22347 
22348   /* If only one is a conversion operator, they are unordered.  */
22349   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
22350     return 0;
22351 
22352   /* Consider the return type for a conversion function */
22353   if (DECL_CONV_FN_P (decl1))
22354     {
22355       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
22356       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
22357       len++;
22358     }
22359 
22360   processing_template_decl++;
22361 
22362   origs1 = args1;
22363   origs2 = args2;
22364 
22365   while (len--
22366 	 /* Stop when an ellipsis is seen.  */
22367 	 && args1 != NULL_TREE && args2 != NULL_TREE)
22368     {
22369       tree arg1 = TREE_VALUE (args1);
22370       tree arg2 = TREE_VALUE (args2);
22371       int deduce1, deduce2;
22372       int quals1 = -1;
22373       int quals2 = -1;
22374       int ref1 = 0;
22375       int ref2 = 0;
22376 
22377       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
22378           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
22379         {
22380           /* When both arguments are pack expansions, we need only
22381              unify the patterns themselves.  */
22382           arg1 = PACK_EXPANSION_PATTERN (arg1);
22383           arg2 = PACK_EXPANSION_PATTERN (arg2);
22384 
22385           /* This is the last comparison we need to do.  */
22386           len = 0;
22387         }
22388 
22389       /* DR 1847: If a particular P contains no template-parameters that
22390 	 participate in template argument deduction, that P is not used to
22391 	 determine the ordering.  */
22392       if (!uses_deducible_template_parms (arg1)
22393 	  && !uses_deducible_template_parms (arg2))
22394 	goto next;
22395 
22396       if (TREE_CODE (arg1) == REFERENCE_TYPE)
22397 	{
22398 	  ref1 = TYPE_REF_IS_RVALUE (arg1) + 1;
22399 	  arg1 = TREE_TYPE (arg1);
22400 	  quals1 = cp_type_quals (arg1);
22401 	}
22402 
22403       if (TREE_CODE (arg2) == REFERENCE_TYPE)
22404 	{
22405 	  ref2 = TYPE_REF_IS_RVALUE (arg2) + 1;
22406 	  arg2 = TREE_TYPE (arg2);
22407 	  quals2 = cp_type_quals (arg2);
22408 	}
22409 
22410       arg1 = TYPE_MAIN_VARIANT (arg1);
22411       arg2 = TYPE_MAIN_VARIANT (arg2);
22412 
22413       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
22414         {
22415           int i, len2 = remaining_arguments (args2);
22416           tree parmvec = make_tree_vec (1);
22417           tree argvec = make_tree_vec (len2);
22418           tree ta = args2;
22419 
22420           /* Setup the parameter vector, which contains only ARG1.  */
22421           TREE_VEC_ELT (parmvec, 0) = arg1;
22422 
22423           /* Setup the argument vector, which contains the remaining
22424              arguments.  */
22425           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
22426             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
22427 
22428           deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
22429 					   argvec, DEDUCE_EXACT,
22430 					   /*subr=*/true, /*explain_p=*/false)
22431 		     == 0);
22432 
22433           /* We cannot deduce in the other direction, because ARG1 is
22434              a pack expansion but ARG2 is not.  */
22435           deduce2 = 0;
22436         }
22437       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
22438         {
22439           int i, len1 = remaining_arguments (args1);
22440           tree parmvec = make_tree_vec (1);
22441           tree argvec = make_tree_vec (len1);
22442           tree ta = args1;
22443 
22444           /* Setup the parameter vector, which contains only ARG1.  */
22445           TREE_VEC_ELT (parmvec, 0) = arg2;
22446 
22447           /* Setup the argument vector, which contains the remaining
22448              arguments.  */
22449           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
22450             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
22451 
22452           deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
22453 					   argvec, DEDUCE_EXACT,
22454 					   /*subr=*/true, /*explain_p=*/false)
22455 		     == 0);
22456 
22457           /* We cannot deduce in the other direction, because ARG2 is
22458              a pack expansion but ARG1 is not.*/
22459           deduce1 = 0;
22460         }
22461 
22462       else
22463         {
22464           /* The normal case, where neither argument is a pack
22465              expansion.  */
22466           deduce1 = (unify (tparms1, targs1, arg1, arg2,
22467 			    UNIFY_ALLOW_NONE, /*explain_p=*/false)
22468 		     == 0);
22469           deduce2 = (unify (tparms2, targs2, arg2, arg1,
22470 			    UNIFY_ALLOW_NONE, /*explain_p=*/false)
22471 		     == 0);
22472         }
22473 
22474       /* If we couldn't deduce arguments for tparms1 to make arg1 match
22475 	 arg2, then arg2 is not as specialized as arg1.  */
22476       if (!deduce1)
22477 	lose2 = true;
22478       if (!deduce2)
22479 	lose1 = true;
22480 
22481       /* "If, for a given type, deduction succeeds in both directions
22482 	 (i.e., the types are identical after the transformations above)
22483 	 and both P and A were reference types (before being replaced with
22484 	 the type referred to above):
22485 	 - if the type from the argument template was an lvalue reference and
22486 	 the type from the parameter template was not, the argument type is
22487 	 considered to be more specialized than the other; otherwise,
22488 	 - if the type from the argument template is more cv-qualified
22489 	 than the type from the parameter template (as described above),
22490 	 the argument type is considered to be more specialized than the other;
22491 	 otherwise,
22492 	 - neither type is more specialized than the other."  */
22493 
22494       if (deduce1 && deduce2)
22495 	{
22496 	  if (ref1 && ref2 && ref1 != ref2)
22497 	    {
22498 	      if (ref1 > ref2)
22499 		lose1 = true;
22500 	      else
22501 		lose2 = true;
22502 	    }
22503 	  else if (quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
22504 	    {
22505 	      if ((quals1 & quals2) == quals2)
22506 		lose2 = true;
22507 	      if ((quals1 & quals2) == quals1)
22508 		lose1 = true;
22509 	    }
22510 	}
22511 
22512       if (lose1 && lose2)
22513 	/* We've failed to deduce something in either direction.
22514 	   These must be unordered.  */
22515 	break;
22516 
22517     next:
22518 
22519       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
22520           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
22521         /* We have already processed all of the arguments in our
22522            handing of the pack expansion type.  */
22523         len = 0;
22524 
22525       args1 = TREE_CHAIN (args1);
22526       args2 = TREE_CHAIN (args2);
22527     }
22528 
22529   /* "In most cases, all template parameters must have values in order for
22530      deduction to succeed, but for partial ordering purposes a template
22531      parameter may remain without a value provided it is not used in the
22532      types being used for partial ordering."
22533 
22534      Thus, if we are missing any of the targs1 we need to substitute into
22535      origs1, then pat2 is not as specialized as pat1.  This can happen when
22536      there is a nondeduced context.  */
22537   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
22538     lose2 = true;
22539   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
22540     lose1 = true;
22541 
22542   processing_template_decl--;
22543 
22544   /* If both deductions succeed, the partial ordering selects the more
22545      constrained template.  */
22546   if (!lose1 && !lose2)
22547     {
22548       tree c1 = get_constraints (DECL_TEMPLATE_RESULT (pat1));
22549       tree c2 = get_constraints (DECL_TEMPLATE_RESULT (pat2));
22550       lose1 = !subsumes_constraints (c1, c2);
22551       lose2 = !subsumes_constraints (c2, c1);
22552     }
22553 
22554   /* All things being equal, if the next argument is a pack expansion
22555      for one function but not for the other, prefer the
22556      non-variadic function.  FIXME this is bogus; see c++/41958.  */
22557   if (lose1 == lose2
22558       && args1 && TREE_VALUE (args1)
22559       && args2 && TREE_VALUE (args2))
22560     {
22561       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
22562       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
22563     }
22564 
22565   if (lose1 == lose2)
22566     return 0;
22567   else if (!lose1)
22568     return 1;
22569   else
22570     return -1;
22571 }
22572 
22573 /* Determine which of two partial specializations of TMPL is more
22574    specialized.
22575 
22576    PAT1 is a TREE_LIST whose TREE_VALUE is the TEMPLATE_DECL corresponding
22577    to the first partial specialization.  The TREE_PURPOSE is the
22578    innermost set of template parameters for the partial
22579    specialization.  PAT2 is similar, but for the second template.
22580 
22581    Return 1 if the first partial specialization is more specialized;
22582    -1 if the second is more specialized; 0 if neither is more
22583    specialized.
22584 
22585    See [temp.class.order] for information about determining which of
22586    two templates is more specialized.  */
22587 
22588 static int
more_specialized_partial_spec(tree tmpl,tree pat1,tree pat2)22589 more_specialized_partial_spec (tree tmpl, tree pat1, tree pat2)
22590 {
22591   tree targs;
22592   int winner = 0;
22593   bool any_deductions = false;
22594 
22595   tree tmpl1 = TREE_VALUE (pat1);
22596   tree tmpl2 = TREE_VALUE (pat2);
22597   tree specargs1 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl1)));
22598   tree specargs2 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl2)));
22599 
22600   /* Just like what happens for functions, if we are ordering between
22601      different template specializations, we may encounter dependent
22602      types in the arguments, and we need our dependency check functions
22603      to behave correctly.  */
22604   ++processing_template_decl;
22605   targs = get_partial_spec_bindings (tmpl, tmpl1, specargs2);
22606   if (targs)
22607     {
22608       --winner;
22609       any_deductions = true;
22610     }
22611 
22612   targs = get_partial_spec_bindings (tmpl, tmpl2, specargs1);
22613   if (targs)
22614     {
22615       ++winner;
22616       any_deductions = true;
22617     }
22618   --processing_template_decl;
22619 
22620   /* If both deductions succeed, the partial ordering selects the more
22621      constrained template.  */
22622   if (!winner && any_deductions)
22623     return more_constrained (tmpl1, tmpl2);
22624 
22625   /* In the case of a tie where at least one of the templates
22626      has a parameter pack at the end, the template with the most
22627      non-packed parameters wins.  */
22628   if (winner == 0
22629       && any_deductions
22630       && (template_args_variadic_p (TREE_PURPOSE (pat1))
22631           || template_args_variadic_p (TREE_PURPOSE (pat2))))
22632     {
22633       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
22634       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
22635       int len1 = TREE_VEC_LENGTH (args1);
22636       int len2 = TREE_VEC_LENGTH (args2);
22637 
22638       /* We don't count the pack expansion at the end.  */
22639       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
22640         --len1;
22641       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
22642         --len2;
22643 
22644       if (len1 > len2)
22645         return 1;
22646       else if (len1 < len2)
22647         return -1;
22648     }
22649 
22650   return winner;
22651 }
22652 
22653 /* Return the template arguments that will produce the function signature
22654    DECL from the function template FN, with the explicit template
22655    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
22656    also match.  Return NULL_TREE if no satisfactory arguments could be
22657    found.  */
22658 
22659 static tree
get_bindings(tree fn,tree decl,tree explicit_args,bool check_rettype)22660 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
22661 {
22662   int ntparms = DECL_NTPARMS (fn);
22663   tree targs = make_tree_vec (ntparms);
22664   tree decl_type = TREE_TYPE (decl);
22665   tree decl_arg_types;
22666   tree *args;
22667   unsigned int nargs, ix;
22668   tree arg;
22669 
22670   gcc_assert (decl != DECL_TEMPLATE_RESULT (fn));
22671 
22672   /* Never do unification on the 'this' parameter.  */
22673   decl_arg_types = skip_artificial_parms_for (decl,
22674 					      TYPE_ARG_TYPES (decl_type));
22675 
22676   nargs = list_length (decl_arg_types);
22677   args = XALLOCAVEC (tree, nargs);
22678   for (arg = decl_arg_types, ix = 0;
22679        arg != NULL_TREE && arg != void_list_node;
22680        arg = TREE_CHAIN (arg), ++ix)
22681     args[ix] = TREE_VALUE (arg);
22682 
22683   if (fn_type_unification (fn, explicit_args, targs,
22684 			   args, ix,
22685 			   (check_rettype || DECL_CONV_FN_P (fn)
22686 			    ? TREE_TYPE (decl_type) : NULL_TREE),
22687 			   DEDUCE_EXACT, LOOKUP_NORMAL, /*explain_p=*/false,
22688 			   /*decltype*/false)
22689       == error_mark_node)
22690     return NULL_TREE;
22691 
22692   return targs;
22693 }
22694 
22695 /* Return the innermost template arguments that, when applied to a partial
22696    specialization SPEC_TMPL of TMPL, yield the ARGS.
22697 
22698    For example, suppose we have:
22699 
22700      template <class T, class U> struct S {};
22701      template <class T> struct S<T*, int> {};
22702 
22703    Then, suppose we want to get `S<double*, int>'.  SPEC_TMPL will be the
22704    partial specialization and the ARGS will be {double*, int}.  The resulting
22705    vector will be {double}, indicating that `T' is bound to `double'.  */
22706 
22707 static tree
get_partial_spec_bindings(tree tmpl,tree spec_tmpl,tree args)22708 get_partial_spec_bindings (tree tmpl, tree spec_tmpl, tree args)
22709 {
22710   tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (spec_tmpl);
22711   tree spec_args
22712     = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (spec_tmpl)));
22713   int i, ntparms = TREE_VEC_LENGTH (tparms);
22714   tree deduced_args;
22715   tree innermost_deduced_args;
22716 
22717   innermost_deduced_args = make_tree_vec (ntparms);
22718   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
22719     {
22720       deduced_args = copy_node (args);
22721       SET_TMPL_ARGS_LEVEL (deduced_args,
22722 			   TMPL_ARGS_DEPTH (deduced_args),
22723 			   innermost_deduced_args);
22724     }
22725   else
22726     deduced_args = innermost_deduced_args;
22727 
22728   bool tried_array_deduction = (cxx_dialect < cxx17);
22729  again:
22730   if (unify (tparms, deduced_args,
22731 	     INNERMOST_TEMPLATE_ARGS (spec_args),
22732 	     INNERMOST_TEMPLATE_ARGS (args),
22733 	     UNIFY_ALLOW_NONE, /*explain_p=*/false))
22734     return NULL_TREE;
22735 
22736   for (i =  0; i < ntparms; ++i)
22737     if (! TREE_VEC_ELT (innermost_deduced_args, i))
22738       {
22739 	if (!tried_array_deduction)
22740 	  {
22741 	    try_array_deduction (tparms, innermost_deduced_args,
22742 				 INNERMOST_TEMPLATE_ARGS (spec_args));
22743 	    tried_array_deduction = true;
22744 	    if (TREE_VEC_ELT (innermost_deduced_args, i))
22745 	      goto again;
22746 	  }
22747 	return NULL_TREE;
22748       }
22749 
22750   if (!push_tinst_level (spec_tmpl, deduced_args))
22751     {
22752       excessive_deduction_depth = true;
22753       return NULL_TREE;
22754     }
22755 
22756   /* Verify that nondeduced template arguments agree with the type
22757      obtained from argument deduction.
22758 
22759      For example:
22760 
22761        struct A { typedef int X; };
22762        template <class T, class U> struct C {};
22763        template <class T> struct C<T, typename T::X> {};
22764 
22765      Then with the instantiation `C<A, int>', we can deduce that
22766      `T' is `A' but unify () does not check whether `typename T::X'
22767      is `int'.  */
22768   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
22769 
22770   if (spec_args != error_mark_node)
22771     spec_args = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
22772 				       INNERMOST_TEMPLATE_ARGS (spec_args),
22773 				       tmpl, tf_none, false, false);
22774 
22775   pop_tinst_level ();
22776 
22777   if (spec_args == error_mark_node
22778       /* We only need to check the innermost arguments; the other
22779 	 arguments will always agree.  */
22780       || !comp_template_args_porder (INNERMOST_TEMPLATE_ARGS (spec_args),
22781 				     INNERMOST_TEMPLATE_ARGS (args)))
22782     return NULL_TREE;
22783 
22784   /* Now that we have bindings for all of the template arguments,
22785      ensure that the arguments deduced for the template template
22786      parameters have compatible template parameter lists.  See the use
22787      of template_template_parm_bindings_ok_p in fn_type_unification
22788      for more information.  */
22789   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
22790     return NULL_TREE;
22791 
22792   return deduced_args;
22793 }
22794 
22795 // Compare two function templates T1 and T2 by deducing bindings
22796 // from one against the other. If both deductions succeed, compare
22797 // constraints to see which is more constrained.
22798 static int
more_specialized_inst(tree t1,tree t2)22799 more_specialized_inst (tree t1, tree t2)
22800 {
22801   int fate = 0;
22802   int count = 0;
22803 
22804   if (get_bindings (t1, DECL_TEMPLATE_RESULT (t2), NULL_TREE, true))
22805     {
22806       --fate;
22807       ++count;
22808     }
22809 
22810   if (get_bindings (t2, DECL_TEMPLATE_RESULT (t1), NULL_TREE, true))
22811     {
22812       ++fate;
22813       ++count;
22814     }
22815 
22816   // If both deductions succeed, then one may be more constrained.
22817   if (count == 2 && fate == 0)
22818     fate = more_constrained (t1, t2);
22819 
22820   return fate;
22821 }
22822 
22823 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
22824    Return the TREE_LIST node with the most specialized template, if
22825    any.  If there is no most specialized template, the error_mark_node
22826    is returned.
22827 
22828    Note that this function does not look at, or modify, the
22829    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
22830    returned is one of the elements of INSTANTIATIONS, callers may
22831    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
22832    and retrieve it from the value returned.  */
22833 
22834 tree
most_specialized_instantiation(tree templates)22835 most_specialized_instantiation (tree templates)
22836 {
22837   tree fn, champ;
22838 
22839   ++processing_template_decl;
22840 
22841   champ = templates;
22842   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
22843     {
22844       gcc_assert (TREE_VALUE (champ) != TREE_VALUE (fn));
22845       int fate = more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn));
22846       if (fate == -1)
22847 	champ = fn;
22848       else if (!fate)
22849 	{
22850 	  /* Equally specialized, move to next function.  If there
22851 	     is no next function, nothing's most specialized.  */
22852 	  fn = TREE_CHAIN (fn);
22853 	  champ = fn;
22854 	  if (!fn)
22855 	    break;
22856 	}
22857     }
22858 
22859   if (champ)
22860     /* Now verify that champ is better than everything earlier in the
22861        instantiation list.  */
22862     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn)) {
22863       if (more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn)) != 1)
22864       {
22865         champ = NULL_TREE;
22866         break;
22867       }
22868     }
22869 
22870   processing_template_decl--;
22871 
22872   if (!champ)
22873     return error_mark_node;
22874 
22875   return champ;
22876 }
22877 
22878 /* If DECL is a specialization of some template, return the most
22879    general such template.  Otherwise, returns NULL_TREE.
22880 
22881    For example, given:
22882 
22883      template <class T> struct S { template <class U> void f(U); };
22884 
22885    if TMPL is `template <class U> void S<int>::f(U)' this will return
22886    the full template.  This function will not trace past partial
22887    specializations, however.  For example, given in addition:
22888 
22889      template <class T> struct S<T*> { template <class U> void f(U); };
22890 
22891    if TMPL is `template <class U> void S<int*>::f(U)' this will return
22892    `template <class T> template <class U> S<T*>::f(U)'.  */
22893 
22894 tree
most_general_template(tree decl)22895 most_general_template (tree decl)
22896 {
22897   if (TREE_CODE (decl) != TEMPLATE_DECL)
22898     {
22899       if (tree tinfo = get_template_info (decl))
22900 	decl = TI_TEMPLATE (tinfo);
22901       /* The TI_TEMPLATE can be an IDENTIFIER_NODE for a
22902 	 template friend, or a FIELD_DECL for a capture pack.  */
22903       if (TREE_CODE (decl) != TEMPLATE_DECL)
22904 	return NULL_TREE;
22905     }
22906 
22907   /* Look for more and more general templates.  */
22908   while (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
22909     {
22910       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
22911 	 (See cp-tree.h for details.)  */
22912       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
22913 	break;
22914 
22915       if (CLASS_TYPE_P (TREE_TYPE (decl))
22916 	  && !TYPE_DECL_ALIAS_P (TYPE_NAME (TREE_TYPE (decl)))
22917 	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
22918 	break;
22919 
22920       /* Stop if we run into an explicitly specialized class template.  */
22921       if (!DECL_NAMESPACE_SCOPE_P (decl)
22922 	  && DECL_CONTEXT (decl)
22923 	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
22924 	break;
22925 
22926       decl = DECL_TI_TEMPLATE (decl);
22927     }
22928 
22929   return decl;
22930 }
22931 
22932 /* Return the most specialized of the template partial specializations
22933    which can produce TARGET, a specialization of some class or variable
22934    template.  The value returned is actually a TREE_LIST; the TREE_VALUE is
22935    a TEMPLATE_DECL node corresponding to the partial specialization, while
22936    the TREE_PURPOSE is the set of template arguments that must be
22937    substituted into the template pattern in order to generate TARGET.
22938 
22939    If the choice of partial specialization is ambiguous, a diagnostic
22940    is issued, and the error_mark_node is returned.  If there are no
22941    partial specializations matching TARGET, then NULL_TREE is
22942    returned, indicating that the primary template should be used.  */
22943 
22944 static tree
most_specialized_partial_spec(tree target,tsubst_flags_t complain)22945 most_specialized_partial_spec (tree target, tsubst_flags_t complain)
22946 {
22947   tree list = NULL_TREE;
22948   tree t;
22949   tree champ;
22950   int fate;
22951   bool ambiguous_p;
22952   tree outer_args = NULL_TREE;
22953   tree tmpl, args;
22954 
22955   if (TYPE_P (target))
22956     {
22957       tree tinfo = CLASSTYPE_TEMPLATE_INFO (target);
22958       tmpl = TI_TEMPLATE (tinfo);
22959       args = TI_ARGS (tinfo);
22960     }
22961   else if (TREE_CODE (target) == TEMPLATE_ID_EXPR)
22962     {
22963       tmpl = TREE_OPERAND (target, 0);
22964       args = TREE_OPERAND (target, 1);
22965     }
22966   else if (VAR_P (target))
22967     {
22968       tree tinfo = DECL_TEMPLATE_INFO (target);
22969       tmpl = TI_TEMPLATE (tinfo);
22970       args = TI_ARGS (tinfo);
22971     }
22972   else
22973     gcc_unreachable ();
22974 
22975   tree main_tmpl = most_general_template (tmpl);
22976 
22977   /* For determining which partial specialization to use, only the
22978      innermost args are interesting.  */
22979   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
22980     {
22981       outer_args = strip_innermost_template_args (args, 1);
22982       args = INNERMOST_TEMPLATE_ARGS (args);
22983     }
22984 
22985   for (t = DECL_TEMPLATE_SPECIALIZATIONS (main_tmpl); t; t = TREE_CHAIN (t))
22986     {
22987       tree spec_args;
22988       tree spec_tmpl = TREE_VALUE (t);
22989 
22990       if (outer_args)
22991 	{
22992 	  /* Substitute in the template args from the enclosing class.  */
22993 	  ++processing_template_decl;
22994 	  spec_tmpl = tsubst (spec_tmpl, outer_args, tf_none, NULL_TREE);
22995 	  --processing_template_decl;
22996 	}
22997 
22998       if (spec_tmpl == error_mark_node)
22999 	return error_mark_node;
23000 
23001       spec_args = get_partial_spec_bindings (tmpl, spec_tmpl, args);
23002       if (spec_args)
23003 	{
23004 	  if (outer_args)
23005 	    spec_args = add_to_template_args (outer_args, spec_args);
23006 
23007           /* Keep the candidate only if the constraints are satisfied,
23008              or if we're not compiling with concepts.  */
23009           if (!flag_concepts
23010               || constraints_satisfied_p (spec_tmpl, spec_args))
23011             {
23012               list = tree_cons (spec_args, TREE_VALUE (t), list);
23013               TREE_TYPE (list) = TREE_TYPE (t);
23014             }
23015 	}
23016     }
23017 
23018   if (! list)
23019     return NULL_TREE;
23020 
23021   ambiguous_p = false;
23022   t = list;
23023   champ = t;
23024   t = TREE_CHAIN (t);
23025   for (; t; t = TREE_CHAIN (t))
23026     {
23027       fate = more_specialized_partial_spec (tmpl, champ, t);
23028       if (fate == 1)
23029 	;
23030       else
23031 	{
23032 	  if (fate == 0)
23033 	    {
23034 	      t = TREE_CHAIN (t);
23035 	      if (! t)
23036 		{
23037 		  ambiguous_p = true;
23038 		  break;
23039 		}
23040 	    }
23041 	  champ = t;
23042 	}
23043     }
23044 
23045   if (!ambiguous_p)
23046     for (t = list; t && t != champ; t = TREE_CHAIN (t))
23047       {
23048 	fate = more_specialized_partial_spec (tmpl, champ, t);
23049 	if (fate != 1)
23050 	  {
23051 	    ambiguous_p = true;
23052 	    break;
23053 	  }
23054       }
23055 
23056   if (ambiguous_p)
23057     {
23058       const char *str;
23059       char *spaces = NULL;
23060       if (!(complain & tf_error))
23061 	return error_mark_node;
23062       if (TYPE_P (target))
23063 	error ("ambiguous template instantiation for %q#T", target);
23064       else
23065 	error ("ambiguous template instantiation for %q#D", target);
23066       str = ngettext ("candidate is:", "candidates are:", list_length (list));
23067       for (t = list; t; t = TREE_CHAIN (t))
23068         {
23069 	  tree subst = build_tree_list (TREE_VALUE (t), TREE_PURPOSE (t));
23070           inform (DECL_SOURCE_LOCATION (TREE_VALUE (t)),
23071 		  "%s %#qS", spaces ? spaces : str, subst);
23072           spaces = spaces ? spaces : get_spaces (str);
23073         }
23074       free (spaces);
23075       return error_mark_node;
23076     }
23077 
23078   return champ;
23079 }
23080 
23081 /* Explicitly instantiate DECL.  */
23082 
23083 void
do_decl_instantiation(tree decl,tree storage)23084 do_decl_instantiation (tree decl, tree storage)
23085 {
23086   tree result = NULL_TREE;
23087   int extern_p = 0;
23088 
23089   if (!decl || decl == error_mark_node)
23090     /* An error occurred, for which grokdeclarator has already issued
23091        an appropriate message.  */
23092     return;
23093   else if (! DECL_LANG_SPECIFIC (decl))
23094     {
23095       error ("explicit instantiation of non-template %q#D", decl);
23096       return;
23097     }
23098 
23099   bool var_templ = (DECL_TEMPLATE_INFO (decl)
23100                     && variable_template_p (DECL_TI_TEMPLATE (decl)));
23101 
23102   if (VAR_P (decl) && !var_templ)
23103     {
23104       /* There is an asymmetry here in the way VAR_DECLs and
23105 	 FUNCTION_DECLs are handled by grokdeclarator.  In the case of
23106 	 the latter, the DECL we get back will be marked as a
23107 	 template instantiation, and the appropriate
23108 	 DECL_TEMPLATE_INFO will be set up.  This does not happen for
23109 	 VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
23110 	 should handle VAR_DECLs as it currently handles
23111 	 FUNCTION_DECLs.  */
23112       if (!DECL_CLASS_SCOPE_P (decl))
23113 	{
23114 	  error ("%qD is not a static data member of a class template", decl);
23115 	  return;
23116 	}
23117       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
23118       if (!result || !VAR_P (result))
23119 	{
23120 	  error ("no matching template for %qD found", decl);
23121 	  return;
23122 	}
23123       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
23124 	{
23125 	  error ("type %qT for explicit instantiation %qD does not match "
23126 		 "declared type %qT", TREE_TYPE (result), decl,
23127 		 TREE_TYPE (decl));
23128 	  return;
23129 	}
23130     }
23131   else if (TREE_CODE (decl) != FUNCTION_DECL && !var_templ)
23132     {
23133       error ("explicit instantiation of %q#D", decl);
23134       return;
23135     }
23136   else
23137     result = decl;
23138 
23139   /* Check for various error cases.  Note that if the explicit
23140      instantiation is valid the RESULT will currently be marked as an
23141      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
23142      until we get here.  */
23143 
23144   if (DECL_TEMPLATE_SPECIALIZATION (result))
23145     {
23146       /* DR 259 [temp.spec].
23147 
23148 	 Both an explicit instantiation and a declaration of an explicit
23149 	 specialization shall not appear in a program unless the explicit
23150 	 instantiation follows a declaration of the explicit specialization.
23151 
23152 	 For a given set of template parameters, if an explicit
23153 	 instantiation of a template appears after a declaration of an
23154 	 explicit specialization for that template, the explicit
23155 	 instantiation has no effect.  */
23156       return;
23157     }
23158   else if (DECL_EXPLICIT_INSTANTIATION (result))
23159     {
23160       /* [temp.spec]
23161 
23162 	 No program shall explicitly instantiate any template more
23163 	 than once.
23164 
23165 	 We check DECL_NOT_REALLY_EXTERN so as not to complain when
23166 	 the first instantiation was `extern' and the second is not,
23167 	 and EXTERN_P for the opposite case.  */
23168       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
23169 	permerror (input_location, "duplicate explicit instantiation of %q#D", result);
23170       /* If an "extern" explicit instantiation follows an ordinary
23171 	 explicit instantiation, the template is instantiated.  */
23172       if (extern_p)
23173 	return;
23174     }
23175   else if (!DECL_IMPLICIT_INSTANTIATION (result))
23176     {
23177       error ("no matching template for %qD found", result);
23178       return;
23179     }
23180   else if (!DECL_TEMPLATE_INFO (result))
23181     {
23182       permerror (input_location, "explicit instantiation of non-template %q#D", result);
23183       return;
23184     }
23185 
23186   if (storage == NULL_TREE)
23187     ;
23188   else if (storage == ridpointers[(int) RID_EXTERN])
23189     {
23190       if (!in_system_header_at (input_location) && (cxx_dialect == cxx98))
23191 	pedwarn (input_location, OPT_Wpedantic,
23192 		 "ISO C++ 1998 forbids the use of %<extern%> on explicit "
23193 		 "instantiations");
23194       extern_p = 1;
23195     }
23196   else
23197     error ("storage class %qD applied to template instantiation", storage);
23198 
23199   check_explicit_instantiation_namespace (result);
23200   mark_decl_instantiated (result, extern_p);
23201   if (! extern_p)
23202     instantiate_decl (result, /*defer_ok=*/true,
23203 		      /*expl_inst_class_mem_p=*/false);
23204 }
23205 
23206 static void
mark_class_instantiated(tree t,int extern_p)23207 mark_class_instantiated (tree t, int extern_p)
23208 {
23209   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
23210   SET_CLASSTYPE_INTERFACE_KNOWN (t);
23211   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
23212   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
23213   if (! extern_p)
23214     {
23215       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
23216       rest_of_type_compilation (t, 1);
23217     }
23218 }
23219 
23220 /* Called from do_type_instantiation through binding_table_foreach to
23221    do recursive instantiation for the type bound in ENTRY.  */
23222 static void
bt_instantiate_type_proc(binding_entry entry,void * data)23223 bt_instantiate_type_proc (binding_entry entry, void *data)
23224 {
23225   tree storage = *(tree *) data;
23226 
23227   if (MAYBE_CLASS_TYPE_P (entry->type)
23228       && CLASSTYPE_TEMPLATE_INFO (entry->type)
23229       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
23230     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
23231 }
23232 
23233 /* Perform an explicit instantiation of template class T.  STORAGE, if
23234    non-null, is the RID for extern, inline or static.  COMPLAIN is
23235    nonzero if this is called from the parser, zero if called recursively,
23236    since the standard is unclear (as detailed below).  */
23237 
23238 void
do_type_instantiation(tree t,tree storage,tsubst_flags_t complain)23239 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
23240 {
23241   int extern_p = 0;
23242   int nomem_p = 0;
23243   int static_p = 0;
23244   int previous_instantiation_extern_p = 0;
23245 
23246   if (TREE_CODE (t) == TYPE_DECL)
23247     t = TREE_TYPE (t);
23248 
23249   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
23250     {
23251       tree tmpl =
23252 	(TYPE_TEMPLATE_INFO (t)) ? TYPE_TI_TEMPLATE (t) : NULL;
23253       if (tmpl)
23254 	error ("explicit instantiation of non-class template %qD", tmpl);
23255       else
23256 	error ("explicit instantiation of non-template type %qT", t);
23257       return;
23258     }
23259 
23260   complete_type (t);
23261 
23262   if (!COMPLETE_TYPE_P (t))
23263     {
23264       if (complain & tf_error)
23265 	error ("explicit instantiation of %q#T before definition of template",
23266 	       t);
23267       return;
23268     }
23269 
23270   if (storage != NULL_TREE)
23271     {
23272       if (!in_system_header_at (input_location))
23273 	{
23274 	  if (storage == ridpointers[(int) RID_EXTERN])
23275 	    {
23276 	      if (cxx_dialect == cxx98)
23277 		pedwarn (input_location, OPT_Wpedantic,
23278 			 "ISO C++ 1998 forbids the use of %<extern%> on "
23279 			 "explicit instantiations");
23280 	    }
23281 	  else
23282 	    pedwarn (input_location, OPT_Wpedantic,
23283 		     "ISO C++ forbids the use of %qE"
23284 		     " on explicit instantiations", storage);
23285 	}
23286 
23287       if (storage == ridpointers[(int) RID_INLINE])
23288 	nomem_p = 1;
23289       else if (storage == ridpointers[(int) RID_EXTERN])
23290 	extern_p = 1;
23291       else if (storage == ridpointers[(int) RID_STATIC])
23292 	static_p = 1;
23293       else
23294 	{
23295 	  error ("storage class %qD applied to template instantiation",
23296 		 storage);
23297 	  extern_p = 0;
23298 	}
23299     }
23300 
23301   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
23302     {
23303       /* DR 259 [temp.spec].
23304 
23305 	 Both an explicit instantiation and a declaration of an explicit
23306 	 specialization shall not appear in a program unless the explicit
23307 	 instantiation follows a declaration of the explicit specialization.
23308 
23309 	 For a given set of template parameters, if an explicit
23310 	 instantiation of a template appears after a declaration of an
23311 	 explicit specialization for that template, the explicit
23312 	 instantiation has no effect.  */
23313       return;
23314     }
23315   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
23316     {
23317       /* [temp.spec]
23318 
23319 	 No program shall explicitly instantiate any template more
23320 	 than once.
23321 
23322 	 If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
23323 	 instantiation was `extern'.  If EXTERN_P then the second is.
23324 	 These cases are OK.  */
23325       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
23326 
23327       if (!previous_instantiation_extern_p && !extern_p
23328 	  && (complain & tf_error))
23329 	permerror (input_location, "duplicate explicit instantiation of %q#T", t);
23330 
23331       /* If we've already instantiated the template, just return now.  */
23332       if (!CLASSTYPE_INTERFACE_ONLY (t))
23333 	return;
23334     }
23335 
23336   check_explicit_instantiation_namespace (TYPE_NAME (t));
23337   mark_class_instantiated (t, extern_p);
23338 
23339   if (nomem_p)
23340     return;
23341 
23342   /* In contrast to implicit instantiation, where only the
23343      declarations, and not the definitions, of members are
23344      instantiated, we have here:
23345 
23346 	 [temp.explicit]
23347 
23348 	 The explicit instantiation of a class template specialization
23349 	 implies the instantiation of all of its members not
23350 	 previously explicitly specialized in the translation unit
23351 	 containing the explicit instantiation.
23352 
23353      Of course, we can't instantiate member template classes, since we
23354      don't have any arguments for them.  Note that the standard is
23355      unclear on whether the instantiation of the members are
23356      *explicit* instantiations or not.  However, the most natural
23357      interpretation is that it should be an explicit
23358      instantiation.  */
23359   for (tree fld = TYPE_FIELDS (t); fld; fld = DECL_CHAIN (fld))
23360     if ((VAR_P (fld)
23361 	 || (TREE_CODE (fld) == FUNCTION_DECL
23362 	     && !static_p
23363 	     && user_provided_p (fld)))
23364 	&& DECL_TEMPLATE_INSTANTIATION (fld))
23365       {
23366 	mark_decl_instantiated (fld, extern_p);
23367 	if (! extern_p)
23368 	  instantiate_decl (fld, /*defer_ok=*/true,
23369 			    /*expl_inst_class_mem_p=*/true);
23370       }
23371 
23372   if (CLASSTYPE_NESTED_UTDS (t))
23373     binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
23374 			   bt_instantiate_type_proc, &storage);
23375 }
23376 
23377 /* Given a function DECL, which is a specialization of TMPL, modify
23378    DECL to be a re-instantiation of TMPL with the same template
23379    arguments.  TMPL should be the template into which tsubst'ing
23380    should occur for DECL, not the most general template.
23381 
23382    One reason for doing this is a scenario like this:
23383 
23384      template <class T>
23385      void f(const T&, int i);
23386 
23387      void g() { f(3, 7); }
23388 
23389      template <class T>
23390      void f(const T& t, const int i) { }
23391 
23392    Note that when the template is first instantiated, with
23393    instantiate_template, the resulting DECL will have no name for the
23394    first parameter, and the wrong type for the second.  So, when we go
23395    to instantiate the DECL, we regenerate it.  */
23396 
23397 static void
regenerate_decl_from_template(tree decl,tree tmpl,tree args)23398 regenerate_decl_from_template (tree decl, tree tmpl, tree args)
23399 {
23400   /* The arguments used to instantiate DECL, from the most general
23401      template.  */
23402   tree code_pattern;
23403 
23404   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
23405 
23406   /* Make sure that we can see identifiers, and compute access
23407      correctly.  */
23408   push_access_scope (decl);
23409 
23410   if (TREE_CODE (decl) == FUNCTION_DECL)
23411     {
23412       tree decl_parm;
23413       tree pattern_parm;
23414       tree specs;
23415       int args_depth;
23416       int parms_depth;
23417 
23418       args_depth = TMPL_ARGS_DEPTH (args);
23419       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
23420       if (args_depth > parms_depth)
23421 	args = get_innermost_template_args (args, parms_depth);
23422 
23423       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
23424 					      args, tf_error, NULL_TREE,
23425 					      /*defer_ok*/false);
23426       if (specs && specs != error_mark_node)
23427 	TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
23428 						    specs);
23429 
23430       /* Merge parameter declarations.  */
23431       decl_parm = skip_artificial_parms_for (decl,
23432 					     DECL_ARGUMENTS (decl));
23433       pattern_parm
23434 	= skip_artificial_parms_for (code_pattern,
23435 				     DECL_ARGUMENTS (code_pattern));
23436       while (decl_parm && !DECL_PACK_P (pattern_parm))
23437 	{
23438 	  tree parm_type;
23439 	  tree attributes;
23440 
23441 	  if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
23442 	    DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
23443 	  parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
23444 			      NULL_TREE);
23445 	  parm_type = type_decays_to (parm_type);
23446 	  if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
23447 	    TREE_TYPE (decl_parm) = parm_type;
23448 	  attributes = DECL_ATTRIBUTES (pattern_parm);
23449 	  if (DECL_ATTRIBUTES (decl_parm) != attributes)
23450 	    {
23451 	      DECL_ATTRIBUTES (decl_parm) = attributes;
23452 	      cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
23453 	    }
23454 	  decl_parm = DECL_CHAIN (decl_parm);
23455 	  pattern_parm = DECL_CHAIN (pattern_parm);
23456 	}
23457       /* Merge any parameters that match with the function parameter
23458          pack.  */
23459       if (pattern_parm && DECL_PACK_P (pattern_parm))
23460         {
23461           int i, len;
23462           tree expanded_types;
23463           /* Expand the TYPE_PACK_EXPANSION that provides the types for
23464              the parameters in this function parameter pack.  */
23465           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm),
23466                                                  args, tf_error, NULL_TREE);
23467           len = TREE_VEC_LENGTH (expanded_types);
23468           for (i = 0; i < len; i++)
23469             {
23470               tree parm_type;
23471               tree attributes;
23472 
23473               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
23474                 /* Rename the parameter to include the index.  */
23475                 DECL_NAME (decl_parm) =
23476                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
23477               parm_type = TREE_VEC_ELT (expanded_types, i);
23478               parm_type = type_decays_to (parm_type);
23479               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
23480                 TREE_TYPE (decl_parm) = parm_type;
23481               attributes = DECL_ATTRIBUTES (pattern_parm);
23482               if (DECL_ATTRIBUTES (decl_parm) != attributes)
23483                 {
23484                   DECL_ATTRIBUTES (decl_parm) = attributes;
23485                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
23486                 }
23487               decl_parm = DECL_CHAIN (decl_parm);
23488             }
23489         }
23490       /* Merge additional specifiers from the CODE_PATTERN.  */
23491       if (DECL_DECLARED_INLINE_P (code_pattern)
23492 	  && !DECL_DECLARED_INLINE_P (decl))
23493 	DECL_DECLARED_INLINE_P (decl) = 1;
23494     }
23495   else if (VAR_P (decl))
23496     {
23497       start_lambda_scope (decl);
23498       DECL_INITIAL (decl) =
23499 	tsubst_expr (DECL_INITIAL (code_pattern), args,
23500 		     tf_error, DECL_TI_TEMPLATE (decl),
23501 		     /*integral_constant_expression_p=*/false);
23502       finish_lambda_scope ();
23503       if (VAR_HAD_UNKNOWN_BOUND (decl))
23504 	TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
23505 				   tf_error, DECL_TI_TEMPLATE (decl));
23506     }
23507   else
23508     gcc_unreachable ();
23509 
23510   pop_access_scope (decl);
23511 }
23512 
23513 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
23514    substituted to get DECL.  */
23515 
23516 tree
template_for_substitution(tree decl)23517 template_for_substitution (tree decl)
23518 {
23519   tree tmpl = DECL_TI_TEMPLATE (decl);
23520 
23521   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
23522      for the instantiation.  This is not always the most general
23523      template.  Consider, for example:
23524 
23525 	template <class T>
23526 	struct S { template <class U> void f();
23527 		   template <> void f<int>(); };
23528 
23529      and an instantiation of S<double>::f<int>.  We want TD to be the
23530      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
23531   while (/* An instantiation cannot have a definition, so we need a
23532 	    more general template.  */
23533 	 DECL_TEMPLATE_INSTANTIATION (tmpl)
23534 	   /* We must also deal with friend templates.  Given:
23535 
23536 		template <class T> struct S {
23537 		  template <class U> friend void f() {};
23538 		};
23539 
23540 	      S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
23541 	      so far as the language is concerned, but that's still
23542 	      where we get the pattern for the instantiation from.  On
23543 	      other hand, if the definition comes outside the class, say:
23544 
23545 		template <class T> struct S {
23546 		  template <class U> friend void f();
23547 		};
23548 		template <class U> friend void f() {}
23549 
23550 	      we don't need to look any further.  That's what the check for
23551 	      DECL_INITIAL is for.  */
23552 	  || (TREE_CODE (decl) == FUNCTION_DECL
23553 	      && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
23554 	      && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
23555     {
23556       /* The present template, TD, should not be a definition.  If it
23557 	 were a definition, we should be using it!  Note that we
23558 	 cannot restructure the loop to just keep going until we find
23559 	 a template with a definition, since that might go too far if
23560 	 a specialization was declared, but not defined.  */
23561 
23562       /* Fetch the more general template.  */
23563       tmpl = DECL_TI_TEMPLATE (tmpl);
23564     }
23565 
23566   return tmpl;
23567 }
23568 
23569 /* Returns true if we need to instantiate this template instance even if we
23570    know we aren't going to emit it.  */
23571 
23572 bool
always_instantiate_p(tree decl)23573 always_instantiate_p (tree decl)
23574 {
23575   /* We always instantiate inline functions so that we can inline them.  An
23576      explicit instantiation declaration prohibits implicit instantiation of
23577      non-inline functions.  With high levels of optimization, we would
23578      normally inline non-inline functions -- but we're not allowed to do
23579      that for "extern template" functions.  Therefore, we check
23580      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
23581   return ((TREE_CODE (decl) == FUNCTION_DECL
23582 	   && (DECL_DECLARED_INLINE_P (decl)
23583 	       || type_uses_auto (TREE_TYPE (TREE_TYPE (decl)))))
23584 	  /* And we need to instantiate static data members so that
23585 	     their initializers are available in integral constant
23586 	     expressions.  */
23587 	  || (VAR_P (decl)
23588 	      && decl_maybe_constant_var_p (decl)));
23589 }
23590 
23591 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
23592    instantiate it now, modifying TREE_TYPE (fn).  Returns false on
23593    error, true otherwise.  */
23594 
23595 bool
maybe_instantiate_noexcept(tree fn,tsubst_flags_t complain)23596 maybe_instantiate_noexcept (tree fn, tsubst_flags_t complain)
23597 {
23598   tree fntype, spec, noex, clone;
23599 
23600   /* Don't instantiate a noexcept-specification from template context.  */
23601   if (processing_template_decl
23602       && (!flag_noexcept_type || type_dependent_expression_p (fn)))
23603     return true;
23604 
23605   if (DECL_CLONED_FUNCTION_P (fn))
23606     fn = DECL_CLONED_FUNCTION (fn);
23607   fntype = TREE_TYPE (fn);
23608   spec = TYPE_RAISES_EXCEPTIONS (fntype);
23609 
23610   if (!spec || !TREE_PURPOSE (spec))
23611     return true;
23612 
23613   noex = TREE_PURPOSE (spec);
23614 
23615   if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
23616     {
23617       static hash_set<tree>* fns = new hash_set<tree>;
23618       bool added = false;
23619       if (DEFERRED_NOEXCEPT_PATTERN (noex) == NULL_TREE)
23620 	spec = get_defaulted_eh_spec (fn, complain);
23621       else if (!(added = !fns->add (fn)))
23622 	{
23623 	  /* If hash_set::add returns true, the element was already there.  */
23624 	  location_t loc = EXPR_LOC_OR_LOC (DEFERRED_NOEXCEPT_PATTERN (noex),
23625 					    DECL_SOURCE_LOCATION (fn));
23626 	  error_at (loc,
23627 		    "exception specification of %qD depends on itself",
23628 		    fn);
23629 	  spec = noexcept_false_spec;
23630 	}
23631       else if (push_tinst_level (fn))
23632 	{
23633 	  push_access_scope (fn);
23634 	  push_deferring_access_checks (dk_no_deferred);
23635 	  input_location = DECL_SOURCE_LOCATION (fn);
23636 	  noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
23637 					DEFERRED_NOEXCEPT_ARGS (noex),
23638 					tf_warning_or_error, fn,
23639 					/*function_p=*/false,
23640 					/*integral_constant_expression_p=*/true);
23641 	  spec = build_noexcept_spec (noex, tf_warning_or_error);
23642 	  pop_deferring_access_checks ();
23643 	  pop_access_scope (fn);
23644 	  pop_tinst_level ();
23645 	  if (spec == error_mark_node)
23646 	    spec = noexcept_false_spec;
23647 	}
23648       else
23649 	spec = noexcept_false_spec;
23650 
23651       if (added)
23652 	fns->remove (fn);
23653 
23654       if (spec == error_mark_node)
23655 	return false;
23656 
23657       TREE_TYPE (fn) = build_exception_variant (fntype, spec);
23658     }
23659 
23660   FOR_EACH_CLONE (clone, fn)
23661     {
23662       if (TREE_TYPE (clone) == fntype)
23663 	TREE_TYPE (clone) = TREE_TYPE (fn);
23664       else
23665 	TREE_TYPE (clone) = build_exception_variant (TREE_TYPE (clone), spec);
23666     }
23667 
23668   return true;
23669 }
23670 
23671 /* We're starting to process the function INST, an instantiation of PATTERN;
23672    add their parameters to local_specializations.  */
23673 
23674 static void
register_parameter_specializations(tree pattern,tree inst)23675 register_parameter_specializations (tree pattern, tree inst)
23676 {
23677   tree tmpl_parm = DECL_ARGUMENTS (pattern);
23678   tree spec_parm = DECL_ARGUMENTS (inst);
23679   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (inst))
23680     {
23681       register_local_specialization (spec_parm, tmpl_parm);
23682       spec_parm = skip_artificial_parms_for (inst, spec_parm);
23683       tmpl_parm = skip_artificial_parms_for (pattern, tmpl_parm);
23684     }
23685   for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
23686     {
23687       if (!DECL_PACK_P (tmpl_parm))
23688 	{
23689 	  register_local_specialization (spec_parm, tmpl_parm);
23690 	  spec_parm = DECL_CHAIN (spec_parm);
23691 	}
23692       else
23693 	{
23694 	  /* Register the (value) argument pack as a specialization of
23695 	     TMPL_PARM, then move on.  */
23696 	  tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
23697 	  register_local_specialization (argpack, tmpl_parm);
23698 	}
23699     }
23700   gcc_assert (!spec_parm);
23701 }
23702 
23703 /* Produce the definition of D, a _DECL generated from a template.  If
23704    DEFER_OK is true, then we don't have to actually do the
23705    instantiation now; we just have to do it sometime.  Normally it is
23706    an error if this is an explicit instantiation but D is undefined.
23707    EXPL_INST_CLASS_MEM_P is true iff D is a member of an explicitly
23708    instantiated class template.  */
23709 
23710 tree
instantiate_decl(tree d,bool defer_ok,bool expl_inst_class_mem_p)23711 instantiate_decl (tree d, bool defer_ok, bool expl_inst_class_mem_p)
23712 {
23713   tree tmpl = DECL_TI_TEMPLATE (d);
23714   tree gen_args;
23715   tree args;
23716   tree td;
23717   tree code_pattern;
23718   tree spec;
23719   tree gen_tmpl;
23720   bool pattern_defined;
23721   location_t saved_loc = input_location;
23722   int saved_unevaluated_operand = cp_unevaluated_operand;
23723   int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
23724   bool external_p;
23725   bool deleted_p;
23726 
23727   /* This function should only be used to instantiate templates for
23728      functions and static member variables.  */
23729   gcc_assert (VAR_OR_FUNCTION_DECL_P (d));
23730 
23731   /* A concept is never instantiated. */
23732   gcc_assert (!DECL_DECLARED_CONCEPT_P (d));
23733 
23734   /* Variables are never deferred; if instantiation is required, they
23735      are instantiated right away.  That allows for better code in the
23736      case that an expression refers to the value of the variable --
23737      if the variable has a constant value the referring expression can
23738      take advantage of that fact.  */
23739   if (VAR_P (d))
23740     defer_ok = false;
23741 
23742   /* Don't instantiate cloned functions.  Instead, instantiate the
23743      functions they cloned.  */
23744   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
23745     d = DECL_CLONED_FUNCTION (d);
23746 
23747   if (DECL_TEMPLATE_INSTANTIATED (d)
23748       || (TREE_CODE (d) == FUNCTION_DECL
23749 	  && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
23750       || DECL_TEMPLATE_SPECIALIZATION (d))
23751     /* D has already been instantiated or explicitly specialized, so
23752        there's nothing for us to do here.
23753 
23754        It might seem reasonable to check whether or not D is an explicit
23755        instantiation, and, if so, stop here.  But when an explicit
23756        instantiation is deferred until the end of the compilation,
23757        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
23758        the instantiation.  */
23759     return d;
23760 
23761   /* Check to see whether we know that this template will be
23762      instantiated in some other file, as with "extern template"
23763      extension.  */
23764   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
23765 
23766   /* In general, we do not instantiate such templates.  */
23767   if (external_p && !always_instantiate_p (d))
23768     return d;
23769 
23770   gen_tmpl = most_general_template (tmpl);
23771   gen_args = DECL_TI_ARGS (d);
23772 
23773   if (tmpl != gen_tmpl)
23774     /* We should already have the extra args.  */
23775     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
23776 		== TMPL_ARGS_DEPTH (gen_args));
23777   /* And what's in the hash table should match D.  */
23778   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
23779 	      || spec == NULL_TREE);
23780 
23781   /* This needs to happen before any tsubsting.  */
23782   if (! push_tinst_level (d))
23783     return d;
23784 
23785   timevar_push (TV_TEMPLATE_INST);
23786 
23787   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
23788      for the instantiation.  */
23789   td = template_for_substitution (d);
23790   args = gen_args;
23791 
23792   if (VAR_P (d))
23793     {
23794       /* Look up an explicit specialization, if any.  */
23795       tree tid = lookup_template_variable (gen_tmpl, gen_args);
23796       tree elt = most_specialized_partial_spec (tid, tf_warning_or_error);
23797       if (elt && elt != error_mark_node)
23798 	{
23799 	  td = TREE_VALUE (elt);
23800 	  args = TREE_PURPOSE (elt);
23801 	}
23802     }
23803 
23804   code_pattern = DECL_TEMPLATE_RESULT (td);
23805 
23806   /* We should never be trying to instantiate a member of a class
23807      template or partial specialization.  */
23808   gcc_assert (d != code_pattern);
23809 
23810   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
23811       || DECL_TEMPLATE_SPECIALIZATION (td))
23812     /* In the case of a friend template whose definition is provided
23813        outside the class, we may have too many arguments.  Drop the
23814        ones we don't need.  The same is true for specializations.  */
23815     args = get_innermost_template_args
23816       (args, TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (td)));
23817 
23818   if (TREE_CODE (d) == FUNCTION_DECL)
23819     {
23820       deleted_p = DECL_DELETED_FN (code_pattern);
23821       pattern_defined = ((DECL_SAVED_TREE (code_pattern) != NULL_TREE
23822 			  && DECL_INITIAL (code_pattern) != error_mark_node)
23823 			 || DECL_DEFAULTED_OUTSIDE_CLASS_P (code_pattern)
23824 			 || deleted_p);
23825     }
23826   else
23827     {
23828       deleted_p = false;
23829       if (DECL_CLASS_SCOPE_P (code_pattern))
23830 	pattern_defined = (! DECL_IN_AGGR_P (code_pattern)
23831 			   || DECL_INLINE_VAR_P (code_pattern));
23832       else
23833 	pattern_defined = ! DECL_EXTERNAL (code_pattern);
23834     }
23835 
23836   /* We may be in the middle of deferred access check.  Disable it now.  */
23837   push_deferring_access_checks (dk_no_deferred);
23838 
23839   /* Unless an explicit instantiation directive has already determined
23840      the linkage of D, remember that a definition is available for
23841      this entity.  */
23842   if (pattern_defined
23843       && !DECL_INTERFACE_KNOWN (d)
23844       && !DECL_NOT_REALLY_EXTERN (d))
23845     mark_definable (d);
23846 
23847   DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
23848   DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
23849   input_location = DECL_SOURCE_LOCATION (d);
23850 
23851   /* If D is a member of an explicitly instantiated class template,
23852      and no definition is available, treat it like an implicit
23853      instantiation.  */
23854   if (!pattern_defined && expl_inst_class_mem_p
23855       && DECL_EXPLICIT_INSTANTIATION (d))
23856     {
23857       /* Leave linkage flags alone on instantiations with anonymous
23858 	 visibility.  */
23859       if (TREE_PUBLIC (d))
23860 	{
23861 	  DECL_NOT_REALLY_EXTERN (d) = 0;
23862 	  DECL_INTERFACE_KNOWN (d) = 0;
23863 	}
23864       SET_DECL_IMPLICIT_INSTANTIATION (d);
23865     }
23866 
23867   /* Defer all other templates, unless we have been explicitly
23868      forbidden from doing so.  */
23869   if (/* If there is no definition, we cannot instantiate the
23870 	 template.  */
23871       ! pattern_defined
23872       /* If it's OK to postpone instantiation, do so.  */
23873       || defer_ok
23874       /* If this is a static data member that will be defined
23875 	 elsewhere, we don't want to instantiate the entire data
23876 	 member, but we do want to instantiate the initializer so that
23877 	 we can substitute that elsewhere.  */
23878       || (external_p && VAR_P (d))
23879       /* Handle here a deleted function too, avoid generating
23880 	 its body (c++/61080).  */
23881       || deleted_p)
23882     {
23883       /* The definition of the static data member is now required so
23884 	 we must substitute the initializer.  */
23885       if (VAR_P (d)
23886 	  && !DECL_INITIAL (d)
23887 	  && DECL_INITIAL (code_pattern))
23888 	{
23889 	  tree ns;
23890 	  tree init;
23891 	  bool const_init = false;
23892 	  bool enter_context = DECL_CLASS_SCOPE_P (d);
23893 
23894 	  ns = decl_namespace_context (d);
23895 	  push_nested_namespace (ns);
23896 	  if (enter_context)
23897 	    push_nested_class (DECL_CONTEXT (d));
23898 	  init = tsubst_expr (DECL_INITIAL (code_pattern),
23899 			      args,
23900 			      tf_warning_or_error, NULL_TREE,
23901 			      /*integral_constant_expression_p=*/false);
23902 	  /* If instantiating the initializer involved instantiating this
23903 	     again, don't call cp_finish_decl twice.  */
23904 	  if (!DECL_INITIAL (d))
23905 	    {
23906 	      /* Make sure the initializer is still constant, in case of
23907 		 circular dependency (template/instantiate6.C). */
23908 	      const_init
23909 		= DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
23910 	      cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
23911 			      /*asmspec_tree=*/NULL_TREE,
23912 			      LOOKUP_ONLYCONVERTING);
23913 	    }
23914 	  if (enter_context)
23915 	    pop_nested_class ();
23916 	  pop_nested_namespace (ns);
23917 	}
23918 
23919       /* We restore the source position here because it's used by
23920 	 add_pending_template.  */
23921       input_location = saved_loc;
23922 
23923       if (at_eof && !pattern_defined
23924 	  && DECL_EXPLICIT_INSTANTIATION (d)
23925 	  && DECL_NOT_REALLY_EXTERN (d))
23926 	/* [temp.explicit]
23927 
23928 	   The definition of a non-exported function template, a
23929 	   non-exported member function template, or a non-exported
23930 	   member function or static data member of a class template
23931 	   shall be present in every translation unit in which it is
23932 	   explicitly instantiated.  */
23933 	permerror (input_location,  "explicit instantiation of %qD "
23934 		   "but no definition available", d);
23935 
23936       /* If we're in unevaluated context, we just wanted to get the
23937 	 constant value; this isn't an odr use, so don't queue
23938 	 a full instantiation.  */
23939       if (cp_unevaluated_operand != 0)
23940 	goto out;
23941       /* ??? Historically, we have instantiated inline functions, even
23942 	 when marked as "extern template".  */
23943       if (!(external_p && VAR_P (d)))
23944 	add_pending_template (d);
23945       goto out;
23946     }
23947   /* Tell the repository that D is available in this translation unit
23948      -- and see if it is supposed to be instantiated here.  */
23949   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
23950     {
23951       /* In a PCH file, despite the fact that the repository hasn't
23952 	 requested instantiation in the PCH it is still possible that
23953 	 an instantiation will be required in a file that includes the
23954 	 PCH.  */
23955       if (pch_file)
23956 	add_pending_template (d);
23957       /* Instantiate inline functions so that the inliner can do its
23958 	 job, even though we'll not be emitting a copy of this
23959 	 function.  */
23960       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
23961 	goto out;
23962     }
23963 
23964   bool push_to_top, nested;
23965   tree fn_context;
23966   fn_context = decl_function_context (d);
23967   if (LAMBDA_FUNCTION_P (d))
23968     /* tsubst_lambda_expr resolved any references to enclosing functions.  */
23969     fn_context = NULL_TREE;
23970   nested = current_function_decl != NULL_TREE;
23971   push_to_top = !(nested && fn_context == current_function_decl);
23972 
23973   vec<tree> omp_privatization_save;
23974   if (nested)
23975     save_omp_privatization_clauses (omp_privatization_save);
23976 
23977   if (push_to_top)
23978     push_to_top_level ();
23979   else
23980     {
23981       push_function_context ();
23982       cp_unevaluated_operand = 0;
23983       c_inhibit_evaluation_warnings = 0;
23984     }
23985 
23986   /* Mark D as instantiated so that recursive calls to
23987      instantiate_decl do not try to instantiate it again.  */
23988   DECL_TEMPLATE_INSTANTIATED (d) = 1;
23989 
23990   /* Regenerate the declaration in case the template has been modified
23991      by a subsequent redeclaration.  */
23992   regenerate_decl_from_template (d, td, args);
23993 
23994   /* We already set the file and line above.  Reset them now in case
23995      they changed as a result of calling regenerate_decl_from_template.  */
23996   input_location = DECL_SOURCE_LOCATION (d);
23997 
23998   if (VAR_P (d))
23999     {
24000       tree init;
24001       bool const_init = false;
24002 
24003       /* Clear out DECL_RTL; whatever was there before may not be right
24004 	 since we've reset the type of the declaration.  */
24005       SET_DECL_RTL (d, NULL);
24006       DECL_IN_AGGR_P (d) = 0;
24007 
24008       /* The initializer is placed in DECL_INITIAL by
24009 	 regenerate_decl_from_template so we don't need to
24010 	 push/pop_access_scope again here.  Pull it out so that
24011 	 cp_finish_decl can process it.  */
24012       init = DECL_INITIAL (d);
24013       DECL_INITIAL (d) = NULL_TREE;
24014       DECL_INITIALIZED_P (d) = 0;
24015 
24016       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
24017 	 initializer.  That function will defer actual emission until
24018 	 we have a chance to determine linkage.  */
24019       DECL_EXTERNAL (d) = 0;
24020 
24021       /* Enter the scope of D so that access-checking works correctly.  */
24022       bool enter_context = DECL_CLASS_SCOPE_P (d);
24023       if (enter_context)
24024         push_nested_class (DECL_CONTEXT (d));
24025 
24026       const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
24027       cp_finish_decl (d, init, const_init, NULL_TREE, 0);
24028 
24029       if (enter_context)
24030         pop_nested_class ();
24031 
24032       if (variable_template_p (gen_tmpl))
24033 	note_variable_template_instantiation (d);
24034     }
24035   else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
24036     synthesize_method (d);
24037   else if (TREE_CODE (d) == FUNCTION_DECL)
24038     {
24039       /* Set up the list of local specializations.  */
24040       local_specialization_stack lss (push_to_top ? lss_blank : lss_copy);
24041       tree block = NULL_TREE;
24042 
24043       /* Set up context.  */
24044       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern)
24045 	  && TREE_CODE (DECL_CONTEXT (code_pattern)) == FUNCTION_DECL)
24046 	block = push_stmt_list ();
24047       else
24048 	start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
24049 
24050       /* Some typedefs referenced from within the template code need to be
24051 	 access checked at template instantiation time, i.e now. These
24052 	 types were added to the template at parsing time. Let's get those
24053 	 and perform the access checks then.  */
24054       perform_typedefs_access_check (DECL_TEMPLATE_RESULT (td),
24055 				     args);
24056 
24057       /* Create substitution entries for the parameters.  */
24058       register_parameter_specializations (code_pattern, d);
24059 
24060       /* Substitute into the body of the function.  */
24061       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
24062 	tsubst_omp_udr (DECL_SAVED_TREE (code_pattern), args,
24063 			tf_warning_or_error, tmpl);
24064       else
24065 	{
24066 	  tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
24067 		       tf_warning_or_error, tmpl,
24068 		       /*integral_constant_expression_p=*/false);
24069 
24070 	  /* Set the current input_location to the end of the function
24071 	     so that finish_function knows where we are.  */
24072 	  input_location
24073 	    = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
24074 
24075 	  /* Remember if we saw an infinite loop in the template.  */
24076 	  current_function_infinite_loop
24077 	    = DECL_STRUCT_FUNCTION (code_pattern)->language->infinite_loop;
24078 	}
24079 
24080       /* Finish the function.  */
24081       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern)
24082 	  && TREE_CODE (DECL_CONTEXT (code_pattern)) == FUNCTION_DECL)
24083 	DECL_SAVED_TREE (d) = pop_stmt_list (block);
24084       else
24085 	{
24086 	  d = finish_function (/*inline_p=*/false);
24087 	  expand_or_defer_fn (d);
24088 	}
24089 
24090       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
24091 	cp_check_omp_declare_reduction (d);
24092     }
24093 
24094   /* We're not deferring instantiation any more.  */
24095   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
24096 
24097   if (push_to_top)
24098     pop_from_top_level ();
24099   else
24100     pop_function_context ();
24101 
24102   if (nested)
24103     restore_omp_privatization_clauses (omp_privatization_save);
24104 
24105 out:
24106   pop_deferring_access_checks ();
24107   timevar_pop (TV_TEMPLATE_INST);
24108   pop_tinst_level ();
24109   input_location = saved_loc;
24110   cp_unevaluated_operand = saved_unevaluated_operand;
24111   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
24112 
24113   return d;
24114 }
24115 
24116 /* Run through the list of templates that we wish we could
24117    instantiate, and instantiate any we can.  RETRIES is the
24118    number of times we retry pending template instantiation.  */
24119 
24120 void
instantiate_pending_templates(int retries)24121 instantiate_pending_templates (int retries)
24122 {
24123   int reconsider;
24124   location_t saved_loc = input_location;
24125 
24126   /* Instantiating templates may trigger vtable generation.  This in turn
24127      may require further template instantiations.  We place a limit here
24128      to avoid infinite loop.  */
24129   if (pending_templates && retries >= max_tinst_depth)
24130     {
24131       tree decl = pending_templates->tinst->maybe_get_node ();
24132 
24133       fatal_error (input_location,
24134 		   "template instantiation depth exceeds maximum of %d"
24135                    " instantiating %q+D, possibly from virtual table generation"
24136                    " (use -ftemplate-depth= to increase the maximum)",
24137                    max_tinst_depth, decl);
24138       if (TREE_CODE (decl) == FUNCTION_DECL)
24139 	/* Pretend that we defined it.  */
24140 	DECL_INITIAL (decl) = error_mark_node;
24141       return;
24142     }
24143 
24144   do
24145     {
24146       struct pending_template **t = &pending_templates;
24147       struct pending_template *last = NULL;
24148       reconsider = 0;
24149       while (*t)
24150 	{
24151 	  tree instantiation = reopen_tinst_level ((*t)->tinst);
24152 	  bool complete = false;
24153 
24154 	  if (TYPE_P (instantiation))
24155 	    {
24156 	      if (!COMPLETE_TYPE_P (instantiation))
24157 		{
24158 		  instantiate_class_template (instantiation);
24159 		  if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
24160 		    for (tree fld = TYPE_FIELDS (instantiation);
24161 			 fld; fld = TREE_CHAIN (fld))
24162 		      if ((VAR_P (fld)
24163 			   || (TREE_CODE (fld) == FUNCTION_DECL
24164 			       && !DECL_ARTIFICIAL (fld)))
24165 			  && DECL_TEMPLATE_INSTANTIATION (fld))
24166 			instantiate_decl (fld,
24167 					  /*defer_ok=*/false,
24168 					  /*expl_inst_class_mem_p=*/false);
24169 
24170 		  if (COMPLETE_TYPE_P (instantiation))
24171 		    reconsider = 1;
24172 		}
24173 
24174 	      complete = COMPLETE_TYPE_P (instantiation);
24175 	    }
24176 	  else
24177 	    {
24178 	      if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
24179 		  && !DECL_TEMPLATE_INSTANTIATED (instantiation))
24180 		{
24181 		  instantiation
24182 		    = instantiate_decl (instantiation,
24183 					/*defer_ok=*/false,
24184 					/*expl_inst_class_mem_p=*/false);
24185 		  if (DECL_TEMPLATE_INSTANTIATED (instantiation))
24186 		    reconsider = 1;
24187 		}
24188 
24189 	      complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
24190 			  || DECL_TEMPLATE_INSTANTIATED (instantiation));
24191 	    }
24192 
24193 	  if (complete)
24194 	    {
24195 	      /* If INSTANTIATION has been instantiated, then we don't
24196 		 need to consider it again in the future.  */
24197 	      struct pending_template *drop = *t;
24198 	      *t = (*t)->next;
24199 	      set_refcount_ptr (drop->tinst);
24200 	      pending_template_freelist ().free (drop);
24201 	    }
24202 	  else
24203 	    {
24204 	      last = *t;
24205 	      t = &(*t)->next;
24206 	    }
24207 	  tinst_depth = 0;
24208 	  set_refcount_ptr (current_tinst_level);
24209 	}
24210       last_pending_template = last;
24211     }
24212   while (reconsider);
24213 
24214   input_location = saved_loc;
24215 }
24216 
24217 /* Substitute ARGVEC into T, which is a list of initializers for
24218    either base class or a non-static data member.  The TREE_PURPOSEs
24219    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
24220    instantiate_decl.  */
24221 
24222 static tree
tsubst_initializer_list(tree t,tree argvec)24223 tsubst_initializer_list (tree t, tree argvec)
24224 {
24225   tree inits = NULL_TREE;
24226   tree target_ctor = error_mark_node;
24227 
24228   for (; t; t = TREE_CHAIN (t))
24229     {
24230       tree decl;
24231       tree init;
24232       tree expanded_bases = NULL_TREE;
24233       tree expanded_arguments = NULL_TREE;
24234       int i, len = 1;
24235 
24236       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
24237         {
24238           tree expr;
24239           tree arg;
24240 
24241           /* Expand the base class expansion type into separate base
24242              classes.  */
24243           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
24244                                                  tf_warning_or_error,
24245                                                  NULL_TREE);
24246           if (expanded_bases == error_mark_node)
24247             continue;
24248 
24249           /* We'll be building separate TREE_LISTs of arguments for
24250              each base.  */
24251           len = TREE_VEC_LENGTH (expanded_bases);
24252           expanded_arguments = make_tree_vec (len);
24253           for (i = 0; i < len; i++)
24254             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
24255 
24256           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
24257              expand each argument in the TREE_VALUE of t.  */
24258           expr = make_node (EXPR_PACK_EXPANSION);
24259 	  PACK_EXPANSION_LOCAL_P (expr) = true;
24260           PACK_EXPANSION_PARAMETER_PACKS (expr) =
24261             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
24262 
24263 	  if (TREE_VALUE (t) == void_type_node)
24264 	    /* VOID_TYPE_NODE is used to indicate
24265 	       value-initialization.  */
24266 	    {
24267 	      for (i = 0; i < len; i++)
24268 		TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
24269 	    }
24270 	  else
24271 	    {
24272 	      /* Substitute parameter packs into each argument in the
24273 		 TREE_LIST.  */
24274 	      in_base_initializer = 1;
24275 	      for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
24276 		{
24277 		  tree expanded_exprs;
24278 
24279 		  /* Expand the argument.  */
24280 		  SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
24281 		  expanded_exprs
24282 		    = tsubst_pack_expansion (expr, argvec,
24283 					     tf_warning_or_error,
24284 					     NULL_TREE);
24285 		  if (expanded_exprs == error_mark_node)
24286 		    continue;
24287 
24288 		  /* Prepend each of the expanded expressions to the
24289 		     corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
24290 		  for (i = 0; i < len; i++)
24291 		    {
24292 		      TREE_VEC_ELT (expanded_arguments, i) =
24293 			tree_cons (NULL_TREE,
24294 				   TREE_VEC_ELT (expanded_exprs, i),
24295 				   TREE_VEC_ELT (expanded_arguments, i));
24296 		    }
24297 		}
24298 	      in_base_initializer = 0;
24299 
24300 	      /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
24301 		 since we built them backwards.  */
24302 	      for (i = 0; i < len; i++)
24303 		{
24304 		  TREE_VEC_ELT (expanded_arguments, i) =
24305 		    nreverse (TREE_VEC_ELT (expanded_arguments, i));
24306 		}
24307 	    }
24308         }
24309 
24310       for (i = 0; i < len; ++i)
24311         {
24312           if (expanded_bases)
24313             {
24314               decl = TREE_VEC_ELT (expanded_bases, i);
24315               decl = expand_member_init (decl);
24316               init = TREE_VEC_ELT (expanded_arguments, i);
24317             }
24318           else
24319             {
24320 	      tree tmp;
24321               decl = tsubst_copy (TREE_PURPOSE (t), argvec,
24322                                   tf_warning_or_error, NULL_TREE);
24323 
24324               decl = expand_member_init (decl);
24325               if (decl && !DECL_P (decl))
24326                 in_base_initializer = 1;
24327 
24328 	      init = TREE_VALUE (t);
24329 	      tmp = init;
24330 	      if (init != void_type_node)
24331 		init = tsubst_expr (init, argvec,
24332 				    tf_warning_or_error, NULL_TREE,
24333 				    /*integral_constant_expression_p=*/false);
24334 	      if (init == NULL_TREE && tmp != NULL_TREE)
24335 		/* If we had an initializer but it instantiated to nothing,
24336 		   value-initialize the object.  This will only occur when
24337 		   the initializer was a pack expansion where the parameter
24338 		   packs used in that expansion were of length zero.  */
24339 		init = void_type_node;
24340               in_base_initializer = 0;
24341             }
24342 
24343 	  if (target_ctor != error_mark_node
24344 	      && init != error_mark_node)
24345 	    {
24346 	      error ("mem-initializer for %qD follows constructor delegation",
24347 		     decl);
24348 	      return inits;
24349 	    }
24350 	  /* Look for a target constructor. */
24351 	  if (init != error_mark_node
24352 	      && decl && CLASS_TYPE_P (decl)
24353 	      && same_type_p (decl, current_class_type))
24354 	    {
24355 	      maybe_warn_cpp0x (CPP0X_DELEGATING_CTORS);
24356 	      if (inits)
24357 		{
24358 		  error ("constructor delegation follows mem-initializer for %qD",
24359 			 TREE_PURPOSE (inits));
24360 		  continue;
24361 		}
24362 	      target_ctor = init;
24363 	    }
24364 
24365           if (decl)
24366             {
24367               init = build_tree_list (decl, init);
24368               TREE_CHAIN (init) = inits;
24369               inits = init;
24370             }
24371         }
24372     }
24373   return inits;
24374 }
24375 
24376 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
24377 
24378 static void
set_current_access_from_decl(tree decl)24379 set_current_access_from_decl (tree decl)
24380 {
24381   if (TREE_PRIVATE (decl))
24382     current_access_specifier = access_private_node;
24383   else if (TREE_PROTECTED (decl))
24384     current_access_specifier = access_protected_node;
24385   else
24386     current_access_specifier = access_public_node;
24387 }
24388 
24389 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
24390    is the instantiation (which should have been created with
24391    start_enum) and ARGS are the template arguments to use.  */
24392 
24393 static void
tsubst_enum(tree tag,tree newtag,tree args)24394 tsubst_enum (tree tag, tree newtag, tree args)
24395 {
24396   tree e;
24397 
24398   if (SCOPED_ENUM_P (newtag))
24399     begin_scope (sk_scoped_enum, newtag);
24400 
24401   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
24402     {
24403       tree value;
24404       tree decl;
24405 
24406       decl = TREE_VALUE (e);
24407       /* Note that in a template enum, the TREE_VALUE is the
24408 	 CONST_DECL, not the corresponding INTEGER_CST.  */
24409       value = tsubst_expr (DECL_INITIAL (decl),
24410 			   args, tf_warning_or_error, NULL_TREE,
24411 			   /*integral_constant_expression_p=*/true);
24412 
24413       /* Give this enumeration constant the correct access.  */
24414       set_current_access_from_decl (decl);
24415 
24416       /* Actually build the enumerator itself.  Here we're assuming that
24417 	 enumerators can't have dependent attributes.  */
24418       build_enumerator (DECL_NAME (decl), value, newtag,
24419 			DECL_ATTRIBUTES (decl), DECL_SOURCE_LOCATION (decl));
24420     }
24421 
24422   if (SCOPED_ENUM_P (newtag))
24423     finish_scope ();
24424 
24425   finish_enum_value_list (newtag);
24426   finish_enum (newtag);
24427 
24428   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
24429     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
24430 }
24431 
24432 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
24433    its type -- but without substituting the innermost set of template
24434    arguments.  So, innermost set of template parameters will appear in
24435    the type.  */
24436 
24437 tree
get_mostly_instantiated_function_type(tree decl)24438 get_mostly_instantiated_function_type (tree decl)
24439 {
24440   /* For a function, DECL_TI_TEMPLATE is partially instantiated.  */
24441   return TREE_TYPE (DECL_TI_TEMPLATE (decl));
24442 }
24443 
24444 /* Return truthvalue if we're processing a template different from
24445    the last one involved in diagnostics.  */
24446 bool
problematic_instantiation_changed(void)24447 problematic_instantiation_changed (void)
24448 {
24449   return current_tinst_level != last_error_tinst_level;
24450 }
24451 
24452 /* Remember current template involved in diagnostics.  */
24453 void
record_last_problematic_instantiation(void)24454 record_last_problematic_instantiation (void)
24455 {
24456   set_refcount_ptr (last_error_tinst_level, current_tinst_level);
24457 }
24458 
24459 struct tinst_level *
current_instantiation(void)24460 current_instantiation (void)
24461 {
24462   return current_tinst_level;
24463 }
24464 
24465 /* Return TRUE if current_function_decl is being instantiated, false
24466    otherwise.  */
24467 
24468 bool
instantiating_current_function_p(void)24469 instantiating_current_function_p (void)
24470 {
24471   return (current_instantiation ()
24472 	  && (current_instantiation ()->maybe_get_node ()
24473 	      == current_function_decl));
24474 }
24475 
24476 /* [temp.param] Check that template non-type parm TYPE is of an allowable
24477    type.  Return false for ok, true for disallowed.  Issue error and
24478    inform messages under control of COMPLAIN.  */
24479 
24480 static bool
invalid_nontype_parm_type_p(tree type,tsubst_flags_t complain)24481 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
24482 {
24483   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
24484     return false;
24485   else if (TYPE_PTR_P (type))
24486     return false;
24487   else if (TREE_CODE (type) == REFERENCE_TYPE
24488 	   && !TYPE_REF_IS_RVALUE (type))
24489     return false;
24490   else if (TYPE_PTRMEM_P (type))
24491     return false;
24492   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
24493     return false;
24494   else if (TREE_CODE (type) == TYPENAME_TYPE)
24495     return false;
24496   else if (TREE_CODE (type) == DECLTYPE_TYPE)
24497     return false;
24498   else if (TREE_CODE (type) == NULLPTR_TYPE)
24499     return false;
24500   /* A bound template template parm could later be instantiated to have a valid
24501      nontype parm type via an alias template.  */
24502   else if (cxx_dialect >= cxx11
24503 	   && TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
24504     return false;
24505 
24506   if (complain & tf_error)
24507     {
24508       if (type == error_mark_node)
24509 	inform (input_location, "invalid template non-type parameter");
24510       else
24511 	error ("%q#T is not a valid type for a template non-type parameter",
24512 	       type);
24513     }
24514   return true;
24515 }
24516 
24517 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
24518    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
24519 
24520 static bool
dependent_type_p_r(tree type)24521 dependent_type_p_r (tree type)
24522 {
24523   tree scope;
24524 
24525   /* [temp.dep.type]
24526 
24527      A type is dependent if it is:
24528 
24529      -- a template parameter. Template template parameters are types
24530 	for us (since TYPE_P holds true for them) so we handle
24531 	them here.  */
24532   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
24533       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
24534     return true;
24535   /* -- a qualified-id with a nested-name-specifier which contains a
24536 	class-name that names a dependent type or whose unqualified-id
24537 	names a dependent type.  */
24538   if (TREE_CODE (type) == TYPENAME_TYPE)
24539     return true;
24540 
24541   /* An alias template specialization can be dependent even if the
24542      resulting type is not.  */
24543   if (dependent_alias_template_spec_p (type))
24544     return true;
24545 
24546   /* -- a cv-qualified type where the cv-unqualified type is
24547 	dependent.
24548      No code is necessary for this bullet; the code below handles
24549      cv-qualified types, and we don't want to strip aliases with
24550      TYPE_MAIN_VARIANT because of DR 1558.  */
24551   /* -- a compound type constructed from any dependent type.  */
24552   if (TYPE_PTRMEM_P (type))
24553     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
24554 	    || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
24555 					   (type)));
24556   else if (TYPE_PTR_P (type)
24557 	   || TREE_CODE (type) == REFERENCE_TYPE)
24558     return dependent_type_p (TREE_TYPE (type));
24559   else if (TREE_CODE (type) == FUNCTION_TYPE
24560 	   || TREE_CODE (type) == METHOD_TYPE)
24561     {
24562       tree arg_type;
24563 
24564       if (dependent_type_p (TREE_TYPE (type)))
24565 	return true;
24566       for (arg_type = TYPE_ARG_TYPES (type);
24567 	   arg_type;
24568 	   arg_type = TREE_CHAIN (arg_type))
24569 	if (dependent_type_p (TREE_VALUE (arg_type)))
24570 	  return true;
24571       if (cxx_dialect >= cxx17)
24572 	/* A value-dependent noexcept-specifier makes the type dependent.  */
24573 	if (tree spec = TYPE_RAISES_EXCEPTIONS (type))
24574 	  if (tree noex = TREE_PURPOSE (spec))
24575 	    /* Treat DEFERRED_NOEXCEPT as non-dependent, since it doesn't
24576 	       affect overload resolution and treating it as dependent breaks
24577 	       things.  */
24578 	    if (TREE_CODE (noex) != DEFERRED_NOEXCEPT
24579 		&& value_dependent_expression_p (noex))
24580 	      return true;
24581       return false;
24582     }
24583   /* -- an array type constructed from any dependent type or whose
24584 	size is specified by a constant expression that is
24585 	value-dependent.
24586 
24587         We checked for type- and value-dependence of the bounds in
24588         compute_array_index_type, so TYPE_DEPENDENT_P is already set.  */
24589   if (TREE_CODE (type) == ARRAY_TYPE)
24590     {
24591       if (TYPE_DOMAIN (type)
24592 	  && dependent_type_p (TYPE_DOMAIN (type)))
24593 	return true;
24594       return dependent_type_p (TREE_TYPE (type));
24595     }
24596 
24597   /* -- a template-id in which either the template name is a template
24598      parameter ...  */
24599   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
24600     return true;
24601   /* ... or any of the template arguments is a dependent type or
24602 	an expression that is type-dependent or value-dependent.  */
24603   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
24604 	   && (any_dependent_template_arguments_p
24605 	       (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
24606     return true;
24607 
24608   /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and UNDERLYING_TYPEs are
24609      dependent; if the argument of the `typeof' expression is not
24610      type-dependent, then it should already been have resolved.  */
24611   if (TREE_CODE (type) == TYPEOF_TYPE
24612       || TREE_CODE (type) == DECLTYPE_TYPE
24613       || TREE_CODE (type) == UNDERLYING_TYPE)
24614     return true;
24615 
24616   /* A template argument pack is dependent if any of its packed
24617      arguments are.  */
24618   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
24619     {
24620       tree args = ARGUMENT_PACK_ARGS (type);
24621       int i, len = TREE_VEC_LENGTH (args);
24622       for (i = 0; i < len; ++i)
24623         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
24624           return true;
24625     }
24626 
24627   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
24628      be template parameters.  */
24629   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
24630     return true;
24631 
24632   if (any_dependent_type_attributes_p (TYPE_ATTRIBUTES (type)))
24633     return true;
24634 
24635   /* The standard does not specifically mention types that are local
24636      to template functions or local classes, but they should be
24637      considered dependent too.  For example:
24638 
24639        template <int I> void f() {
24640 	 enum E { a = I };
24641 	 S<sizeof (E)> s;
24642        }
24643 
24644      The size of `E' cannot be known until the value of `I' has been
24645      determined.  Therefore, `E' must be considered dependent.  */
24646   scope = TYPE_CONTEXT (type);
24647   if (scope && TYPE_P (scope))
24648     return dependent_type_p (scope);
24649   /* Don't use type_dependent_expression_p here, as it can lead
24650      to infinite recursion trying to determine whether a lambda
24651      nested in a lambda is dependent (c++/47687).  */
24652   else if (scope && TREE_CODE (scope) == FUNCTION_DECL
24653 	   && DECL_LANG_SPECIFIC (scope)
24654 	   && DECL_TEMPLATE_INFO (scope)
24655 	   && (any_dependent_template_arguments_p
24656 	       (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
24657     return true;
24658 
24659   /* Other types are non-dependent.  */
24660   return false;
24661 }
24662 
24663 /* Returns TRUE if TYPE is dependent, in the sense of
24664    [temp.dep.type].  Note that a NULL type is considered dependent.  */
24665 
24666 bool
dependent_type_p(tree type)24667 dependent_type_p (tree type)
24668 {
24669   /* If there are no template parameters in scope, then there can't be
24670      any dependent types.  */
24671   if (!processing_template_decl)
24672     {
24673       /* If we are not processing a template, then nobody should be
24674 	 providing us with a dependent type.  */
24675       gcc_assert (type);
24676       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
24677       return false;
24678     }
24679 
24680   /* If the type is NULL, we have not computed a type for the entity
24681      in question; in that case, the type is dependent.  */
24682   if (!type)
24683     return true;
24684 
24685   /* Erroneous types can be considered non-dependent.  */
24686   if (type == error_mark_node)
24687     return false;
24688 
24689   /* Getting here with global_type_node means we improperly called this
24690      function on the TREE_TYPE of an IDENTIFIER_NODE.  */
24691   gcc_checking_assert (type != global_type_node);
24692 
24693   /* If we have not already computed the appropriate value for TYPE,
24694      do so now.  */
24695   if (!TYPE_DEPENDENT_P_VALID (type))
24696     {
24697       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
24698       TYPE_DEPENDENT_P_VALID (type) = 1;
24699     }
24700 
24701   return TYPE_DEPENDENT_P (type);
24702 }
24703 
24704 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
24705    lookup.  In other words, a dependent type that is not the current
24706    instantiation.  */
24707 
24708 bool
dependent_scope_p(tree scope)24709 dependent_scope_p (tree scope)
24710 {
24711   return (scope && TYPE_P (scope) && dependent_type_p (scope)
24712 	  && !currently_open_class (scope));
24713 }
24714 
24715 /* T is a SCOPE_REF.  Return whether it represents a non-static member of
24716    an unknown base of 'this' (and is therefore instantiation-dependent).  */
24717 
24718 static bool
unknown_base_ref_p(tree t)24719 unknown_base_ref_p (tree t)
24720 {
24721   if (!current_class_ptr)
24722     return false;
24723 
24724   tree mem = TREE_OPERAND (t, 1);
24725   if (shared_member_p (mem))
24726     return false;
24727 
24728   tree cur = current_nonlambda_class_type ();
24729   if (!any_dependent_bases_p (cur))
24730     return false;
24731 
24732   tree ctx = TREE_OPERAND (t, 0);
24733   if (DERIVED_FROM_P (ctx, cur))
24734     return false;
24735 
24736   return true;
24737 }
24738 
24739 /* T is a SCOPE_REF; return whether we need to consider it
24740     instantiation-dependent so that we can check access at instantiation
24741     time even though we know which member it resolves to.  */
24742 
24743 static bool
instantiation_dependent_scope_ref_p(tree t)24744 instantiation_dependent_scope_ref_p (tree t)
24745 {
24746   if (DECL_P (TREE_OPERAND (t, 1))
24747       && CLASS_TYPE_P (TREE_OPERAND (t, 0))
24748       && !unknown_base_ref_p (t)
24749       && accessible_in_template_p (TREE_OPERAND (t, 0),
24750 				   TREE_OPERAND (t, 1)))
24751     return false;
24752   else
24753     return true;
24754 }
24755 
24756 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
24757    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
24758    expression.  */
24759 
24760 /* Note that this predicate is not appropriate for general expressions;
24761    only constant expressions (that satisfy potential_constant_expression)
24762    can be tested for value dependence.  */
24763 
24764 bool
value_dependent_expression_p(tree expression)24765 value_dependent_expression_p (tree expression)
24766 {
24767   if (!processing_template_decl || expression == NULL_TREE)
24768     return false;
24769 
24770   /* A type-dependent expression is also value-dependent.  */
24771   if (type_dependent_expression_p (expression))
24772     return true;
24773 
24774   switch (TREE_CODE (expression))
24775     {
24776     case BASELINK:
24777       /* A dependent member function of the current instantiation.  */
24778       return dependent_type_p (BINFO_TYPE (BASELINK_BINFO (expression)));
24779 
24780     case FUNCTION_DECL:
24781       /* A dependent member function of the current instantiation.  */
24782       if (DECL_CLASS_SCOPE_P (expression)
24783 	  && dependent_type_p (DECL_CONTEXT (expression)))
24784 	return true;
24785       break;
24786 
24787     case IDENTIFIER_NODE:
24788       /* A name that has not been looked up -- must be dependent.  */
24789       return true;
24790 
24791     case TEMPLATE_PARM_INDEX:
24792       /* A non-type template parm.  */
24793       return true;
24794 
24795     case CONST_DECL:
24796       /* A non-type template parm.  */
24797       if (DECL_TEMPLATE_PARM_P (expression))
24798 	return true;
24799       return value_dependent_expression_p (DECL_INITIAL (expression));
24800 
24801     case VAR_DECL:
24802        /* A constant with literal type and is initialized
24803 	  with an expression that is value-dependent.  */
24804       if (DECL_DEPENDENT_INIT_P (expression)
24805 	  /* FIXME cp_finish_decl doesn't fold reference initializers.  */
24806 	  || TREE_CODE (TREE_TYPE (expression)) == REFERENCE_TYPE)
24807 	return true;
24808       if (DECL_HAS_VALUE_EXPR_P (expression))
24809 	{
24810 	  tree value_expr = DECL_VALUE_EXPR (expression);
24811 	  if (value_dependent_expression_p (value_expr))
24812 	    return true;
24813 	}
24814       return false;
24815 
24816     case DYNAMIC_CAST_EXPR:
24817     case STATIC_CAST_EXPR:
24818     case CONST_CAST_EXPR:
24819     case REINTERPRET_CAST_EXPR:
24820     case CAST_EXPR:
24821     case IMPLICIT_CONV_EXPR:
24822       /* These expressions are value-dependent if the type to which
24823 	 the cast occurs is dependent or the expression being casted
24824 	 is value-dependent.  */
24825       {
24826 	tree type = TREE_TYPE (expression);
24827 
24828 	if (dependent_type_p (type))
24829 	  return true;
24830 
24831 	/* A functional cast has a list of operands.  */
24832 	expression = TREE_OPERAND (expression, 0);
24833 	if (!expression)
24834 	  {
24835 	    /* If there are no operands, it must be an expression such
24836 	       as "int()". This should not happen for aggregate types
24837 	       because it would form non-constant expressions.  */
24838 	    gcc_assert (cxx_dialect >= cxx11
24839 			|| INTEGRAL_OR_ENUMERATION_TYPE_P (type));
24840 
24841 	    return false;
24842 	  }
24843 
24844 	if (TREE_CODE (expression) == TREE_LIST)
24845 	  return any_value_dependent_elements_p (expression);
24846 
24847 	return value_dependent_expression_p (expression);
24848       }
24849 
24850     case SIZEOF_EXPR:
24851       if (SIZEOF_EXPR_TYPE_P (expression))
24852 	return dependent_type_p (TREE_TYPE (TREE_OPERAND (expression, 0)));
24853       /* FALLTHRU */
24854     case ALIGNOF_EXPR:
24855     case TYPEID_EXPR:
24856       /* A `sizeof' expression is value-dependent if the operand is
24857 	 type-dependent or is a pack expansion.  */
24858       expression = TREE_OPERAND (expression, 0);
24859       if (PACK_EXPANSION_P (expression))
24860         return true;
24861       else if (TYPE_P (expression))
24862 	return dependent_type_p (expression);
24863       return instantiation_dependent_uneval_expression_p (expression);
24864 
24865     case AT_ENCODE_EXPR:
24866       /* An 'encode' expression is value-dependent if the operand is
24867 	 type-dependent.  */
24868       expression = TREE_OPERAND (expression, 0);
24869       return dependent_type_p (expression);
24870 
24871     case NOEXCEPT_EXPR:
24872       expression = TREE_OPERAND (expression, 0);
24873       return instantiation_dependent_uneval_expression_p (expression);
24874 
24875     case SCOPE_REF:
24876       /* All instantiation-dependent expressions should also be considered
24877 	 value-dependent.  */
24878       return instantiation_dependent_scope_ref_p (expression);
24879 
24880     case COMPONENT_REF:
24881       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
24882 	      || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
24883 
24884     case NONTYPE_ARGUMENT_PACK:
24885       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
24886          is value-dependent.  */
24887       {
24888         tree values = ARGUMENT_PACK_ARGS (expression);
24889         int i, len = TREE_VEC_LENGTH (values);
24890 
24891         for (i = 0; i < len; ++i)
24892           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
24893             return true;
24894 
24895         return false;
24896       }
24897 
24898     case TRAIT_EXPR:
24899       {
24900 	tree type2 = TRAIT_EXPR_TYPE2 (expression);
24901 
24902 	if (dependent_type_p (TRAIT_EXPR_TYPE1 (expression)))
24903 	  return true;
24904 
24905 	if (!type2)
24906 	  return false;
24907 
24908 	if (TREE_CODE (type2) != TREE_LIST)
24909 	  return dependent_type_p (type2);
24910 
24911 	for (; type2; type2 = TREE_CHAIN (type2))
24912 	  if (dependent_type_p (TREE_VALUE (type2)))
24913 	    return true;
24914 
24915 	return false;
24916       }
24917 
24918     case MODOP_EXPR:
24919       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
24920 	      || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
24921 
24922     case ARRAY_REF:
24923       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
24924 	      || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
24925 
24926     case ADDR_EXPR:
24927       {
24928 	tree op = TREE_OPERAND (expression, 0);
24929 	return (value_dependent_expression_p (op)
24930 		|| has_value_dependent_address (op));
24931       }
24932 
24933     case REQUIRES_EXPR:
24934       /* Treat all requires-expressions as value-dependent so
24935          we don't try to fold them.  */
24936       return true;
24937 
24938     case TYPE_REQ:
24939       return dependent_type_p (TREE_OPERAND (expression, 0));
24940 
24941     case CALL_EXPR:
24942       {
24943 	if (value_dependent_expression_p (CALL_EXPR_FN (expression)))
24944 	  return true;
24945 	tree fn = get_callee_fndecl (expression);
24946 	int i, nargs;
24947 	nargs = call_expr_nargs (expression);
24948 	for (i = 0; i < nargs; ++i)
24949 	  {
24950 	    tree op = CALL_EXPR_ARG (expression, i);
24951 	    /* In a call to a constexpr member function, look through the
24952 	       implicit ADDR_EXPR on the object argument so that it doesn't
24953 	       cause the call to be considered value-dependent.  We also
24954 	       look through it in potential_constant_expression.  */
24955 	    if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
24956 		&& DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
24957 		&& TREE_CODE (op) == ADDR_EXPR)
24958 	      op = TREE_OPERAND (op, 0);
24959 	    if (value_dependent_expression_p (op))
24960 	      return true;
24961 	  }
24962 	return false;
24963       }
24964 
24965     case TEMPLATE_ID_EXPR:
24966       return variable_concept_p (TREE_OPERAND (expression, 0));
24967 
24968     case CONSTRUCTOR:
24969       {
24970 	unsigned ix;
24971 	tree val;
24972 	if (dependent_type_p (TREE_TYPE (expression)))
24973 	  return true;
24974 	FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
24975 	  if (value_dependent_expression_p (val))
24976 	    return true;
24977 	return false;
24978       }
24979 
24980     case STMT_EXPR:
24981       /* Treat a GNU statement expression as dependent to avoid crashing
24982 	 under instantiate_non_dependent_expr; it can't be constant.  */
24983       return true;
24984 
24985     default:
24986       /* A constant expression is value-dependent if any subexpression is
24987 	 value-dependent.  */
24988       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
24989 	{
24990 	case tcc_reference:
24991 	case tcc_unary:
24992 	case tcc_comparison:
24993 	case tcc_binary:
24994 	case tcc_expression:
24995 	case tcc_vl_exp:
24996 	  {
24997 	    int i, len = cp_tree_operand_length (expression);
24998 
24999 	    for (i = 0; i < len; i++)
25000 	      {
25001 		tree t = TREE_OPERAND (expression, i);
25002 
25003 		/* In some cases, some of the operands may be missing.
25004 		   (For example, in the case of PREDECREMENT_EXPR, the
25005 		   amount to increment by may be missing.)  That doesn't
25006 		   make the expression dependent.  */
25007 		if (t && value_dependent_expression_p (t))
25008 		  return true;
25009 	      }
25010 	  }
25011 	  break;
25012 	default:
25013 	  break;
25014 	}
25015       break;
25016     }
25017 
25018   /* The expression is not value-dependent.  */
25019   return false;
25020 }
25021 
25022 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
25023    [temp.dep.expr].  Note that an expression with no type is
25024    considered dependent.  Other parts of the compiler arrange for an
25025    expression with type-dependent subexpressions to have no type, so
25026    this function doesn't have to be fully recursive.  */
25027 
25028 bool
type_dependent_expression_p(tree expression)25029 type_dependent_expression_p (tree expression)
25030 {
25031   if (!processing_template_decl)
25032     return false;
25033 
25034   if (expression == NULL_TREE || expression == error_mark_node)
25035     return false;
25036 
25037   STRIP_ANY_LOCATION_WRAPPER (expression);
25038 
25039   /* An unresolved name is always dependent.  */
25040   if (identifier_p (expression)
25041       || TREE_CODE (expression) == USING_DECL
25042       || TREE_CODE (expression) == WILDCARD_DECL)
25043     return true;
25044 
25045   /* A fold expression is type-dependent. */
25046   if (TREE_CODE (expression) == UNARY_LEFT_FOLD_EXPR
25047       || TREE_CODE (expression) == UNARY_RIGHT_FOLD_EXPR
25048       || TREE_CODE (expression) == BINARY_LEFT_FOLD_EXPR
25049       || TREE_CODE (expression) == BINARY_RIGHT_FOLD_EXPR)
25050     return true;
25051 
25052   /* Some expression forms are never type-dependent.  */
25053   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
25054       || TREE_CODE (expression) == SIZEOF_EXPR
25055       || TREE_CODE (expression) == ALIGNOF_EXPR
25056       || TREE_CODE (expression) == AT_ENCODE_EXPR
25057       || TREE_CODE (expression) == NOEXCEPT_EXPR
25058       || TREE_CODE (expression) == TRAIT_EXPR
25059       || TREE_CODE (expression) == TYPEID_EXPR
25060       || TREE_CODE (expression) == DELETE_EXPR
25061       || TREE_CODE (expression) == VEC_DELETE_EXPR
25062       || TREE_CODE (expression) == THROW_EXPR
25063       || TREE_CODE (expression) == REQUIRES_EXPR)
25064     return false;
25065 
25066   /* The types of these expressions depends only on the type to which
25067      the cast occurs.  */
25068   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
25069       || TREE_CODE (expression) == STATIC_CAST_EXPR
25070       || TREE_CODE (expression) == CONST_CAST_EXPR
25071       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
25072       || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
25073       || TREE_CODE (expression) == CAST_EXPR)
25074     return dependent_type_p (TREE_TYPE (expression));
25075 
25076   /* The types of these expressions depends only on the type created
25077      by the expression.  */
25078   if (TREE_CODE (expression) == NEW_EXPR
25079       || TREE_CODE (expression) == VEC_NEW_EXPR)
25080     {
25081       /* For NEW_EXPR tree nodes created inside a template, either
25082 	 the object type itself or a TREE_LIST may appear as the
25083 	 operand 1.  */
25084       tree type = TREE_OPERAND (expression, 1);
25085       if (TREE_CODE (type) == TREE_LIST)
25086 	/* This is an array type.  We need to check array dimensions
25087 	   as well.  */
25088 	return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
25089 	       || value_dependent_expression_p
25090 		    (TREE_OPERAND (TREE_VALUE (type), 1));
25091       else
25092 	return dependent_type_p (type);
25093     }
25094 
25095   if (TREE_CODE (expression) == SCOPE_REF)
25096     {
25097       tree scope = TREE_OPERAND (expression, 0);
25098       tree name = TREE_OPERAND (expression, 1);
25099 
25100       /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
25101 	 contains an identifier associated by name lookup with one or more
25102 	 declarations declared with a dependent type, or...a
25103 	 nested-name-specifier or qualified-id that names a member of an
25104 	 unknown specialization.  */
25105       return (type_dependent_expression_p (name)
25106 	      || dependent_scope_p (scope));
25107     }
25108 
25109   if (TREE_CODE (expression) == TEMPLATE_DECL
25110       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
25111     return uses_outer_template_parms (expression);
25112 
25113   if (TREE_CODE (expression) == STMT_EXPR)
25114     expression = stmt_expr_value_expr (expression);
25115 
25116   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
25117     {
25118       tree elt;
25119       unsigned i;
25120 
25121       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
25122 	{
25123 	  if (type_dependent_expression_p (elt))
25124 	    return true;
25125 	}
25126       return false;
25127     }
25128 
25129   /* A static data member of the current instantiation with incomplete
25130      array type is type-dependent, as the definition and specializations
25131      can have different bounds.  */
25132   if (VAR_P (expression)
25133       && DECL_CLASS_SCOPE_P (expression)
25134       && dependent_type_p (DECL_CONTEXT (expression))
25135       && VAR_HAD_UNKNOWN_BOUND (expression))
25136     return true;
25137 
25138   /* An array of unknown bound depending on a variadic parameter, eg:
25139 
25140      template<typename... Args>
25141        void foo (Args... args)
25142        {
25143          int arr[] = { args... };
25144        }
25145 
25146      template<int... vals>
25147        void bar ()
25148        {
25149          int arr[] = { vals... };
25150        }
25151 
25152      If the array has no length and has an initializer, it must be that
25153      we couldn't determine its length in cp_complete_array_type because
25154      it is dependent.  */
25155   if (VAR_P (expression)
25156       && TREE_TYPE (expression) != NULL_TREE
25157       && TREE_CODE (TREE_TYPE (expression)) == ARRAY_TYPE
25158       && !TYPE_DOMAIN (TREE_TYPE (expression))
25159       && DECL_INITIAL (expression))
25160    return true;
25161 
25162   /* A function or variable template-id is type-dependent if it has any
25163      dependent template arguments.  */
25164   if (VAR_OR_FUNCTION_DECL_P (expression)
25165       && DECL_LANG_SPECIFIC (expression)
25166       && DECL_TEMPLATE_INFO (expression))
25167     {
25168       /* Consider the innermost template arguments, since those are the ones
25169 	 that come from the template-id; the template arguments for the
25170 	 enclosing class do not make it type-dependent unless they are used in
25171 	 the type of the decl.  */
25172       if (PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (expression))
25173 	  && (any_dependent_template_arguments_p
25174 	      (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
25175 	return true;
25176     }
25177 
25178   /* Otherwise, if the function decl isn't from a dependent scope, it can't be
25179      type-dependent.  Checking this is important for functions with auto return
25180      type, which looks like a dependent type.  */
25181   if (TREE_CODE (expression) == FUNCTION_DECL
25182       && !(DECL_CLASS_SCOPE_P (expression)
25183 	   && dependent_type_p (DECL_CONTEXT (expression)))
25184       && !(DECL_LANG_SPECIFIC (expression)
25185 	   && DECL_FRIEND_P (expression)
25186 	   && (!DECL_FRIEND_CONTEXT (expression)
25187 	       || dependent_type_p (DECL_FRIEND_CONTEXT (expression))))
25188       && !DECL_LOCAL_FUNCTION_P (expression))
25189     {
25190       gcc_assert (!dependent_type_p (TREE_TYPE (expression))
25191 		  || undeduced_auto_decl (expression));
25192       return false;
25193     }
25194 
25195   /* Always dependent, on the number of arguments if nothing else.  */
25196   if (TREE_CODE (expression) == EXPR_PACK_EXPANSION)
25197     return true;
25198 
25199   if (TREE_TYPE (expression) == unknown_type_node)
25200     {
25201       if (TREE_CODE (expression) == ADDR_EXPR)
25202 	return type_dependent_expression_p (TREE_OPERAND (expression, 0));
25203       if (TREE_CODE (expression) == COMPONENT_REF
25204 	  || TREE_CODE (expression) == OFFSET_REF)
25205 	{
25206 	  if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
25207 	    return true;
25208 	  expression = TREE_OPERAND (expression, 1);
25209 	  if (identifier_p (expression))
25210 	    return false;
25211 	}
25212       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
25213       if (TREE_CODE (expression) == SCOPE_REF)
25214 	return false;
25215 
25216       if (BASELINK_P (expression))
25217 	{
25218 	  if (BASELINK_OPTYPE (expression)
25219 	      && dependent_type_p (BASELINK_OPTYPE (expression)))
25220 	    return true;
25221 	  expression = BASELINK_FUNCTIONS (expression);
25222 	}
25223 
25224       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
25225 	{
25226 	  if (any_dependent_template_arguments_p
25227 	      (TREE_OPERAND (expression, 1)))
25228 	    return true;
25229 	  expression = TREE_OPERAND (expression, 0);
25230 	  if (identifier_p (expression))
25231 	    return true;
25232 	}
25233 
25234       gcc_assert (TREE_CODE (expression) == OVERLOAD
25235 		  || TREE_CODE (expression) == FUNCTION_DECL);
25236 
25237       for (lkp_iterator iter (expression); iter; ++iter)
25238 	if (type_dependent_expression_p (*iter))
25239 	  return true;
25240 
25241       return false;
25242     }
25243 
25244   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
25245 
25246   /* Dependent type attributes might not have made it from the decl to
25247      the type yet.  */
25248   if (DECL_P (expression)
25249       && any_dependent_type_attributes_p (DECL_ATTRIBUTES (expression)))
25250     return true;
25251 
25252   return (dependent_type_p (TREE_TYPE (expression)));
25253 }
25254 
25255 /* [temp.dep.expr]/5: A class member access expression (5.2.5) is
25256    type-dependent if the expression refers to a member of the current
25257    instantiation and the type of the referenced member is dependent, or the
25258    class member access expression refers to a member of an unknown
25259    specialization.
25260 
25261    This function returns true if the OBJECT in such a class member access
25262    expression is of an unknown specialization.  */
25263 
25264 bool
type_dependent_object_expression_p(tree object)25265 type_dependent_object_expression_p (tree object)
25266 {
25267   /* An IDENTIFIER_NODE can sometimes have a TREE_TYPE, but it's still
25268      dependent.  */
25269   if (TREE_CODE (object) == IDENTIFIER_NODE)
25270     return true;
25271   tree scope = TREE_TYPE (object);
25272   return (!scope || dependent_scope_p (scope));
25273 }
25274 
25275 /* walk_tree callback function for instantiation_dependent_expression_p,
25276    below.  Returns non-zero if a dependent subexpression is found.  */
25277 
25278 static tree
instantiation_dependent_r(tree * tp,int * walk_subtrees,void *)25279 instantiation_dependent_r (tree *tp, int *walk_subtrees,
25280 			   void * /*data*/)
25281 {
25282   if (TYPE_P (*tp))
25283     {
25284       /* We don't have to worry about decltype currently because decltype
25285 	 of an instantiation-dependent expr is a dependent type.  This
25286 	 might change depending on the resolution of DR 1172.  */
25287       *walk_subtrees = false;
25288       return NULL_TREE;
25289     }
25290   enum tree_code code = TREE_CODE (*tp);
25291   switch (code)
25292     {
25293       /* Don't treat an argument list as dependent just because it has no
25294 	 TREE_TYPE.  */
25295     case TREE_LIST:
25296     case TREE_VEC:
25297     case NONTYPE_ARGUMENT_PACK:
25298       return NULL_TREE;
25299 
25300     case TEMPLATE_PARM_INDEX:
25301       return *tp;
25302 
25303       /* Handle expressions with type operands.  */
25304     case SIZEOF_EXPR:
25305     case ALIGNOF_EXPR:
25306     case TYPEID_EXPR:
25307     case AT_ENCODE_EXPR:
25308       {
25309 	tree op = TREE_OPERAND (*tp, 0);
25310 	if (code == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (*tp))
25311 	  op = TREE_TYPE (op);
25312 	if (TYPE_P (op))
25313 	  {
25314 	    if (dependent_type_p (op))
25315 	      return *tp;
25316 	    else
25317 	      {
25318 		*walk_subtrees = false;
25319 		return NULL_TREE;
25320 	      }
25321 	  }
25322 	break;
25323       }
25324 
25325     case COMPONENT_REF:
25326       if (identifier_p (TREE_OPERAND (*tp, 1)))
25327 	/* In a template, finish_class_member_access_expr creates a
25328 	   COMPONENT_REF with an IDENTIFIER_NODE for op1 even if it isn't
25329 	   type-dependent, so that we can check access control at
25330 	   instantiation time (PR 42277).  See also Core issue 1273.  */
25331 	return *tp;
25332       break;
25333 
25334     case SCOPE_REF:
25335       if (instantiation_dependent_scope_ref_p (*tp))
25336 	return *tp;
25337       else
25338 	break;
25339 
25340       /* Treat statement-expressions as dependent.  */
25341     case BIND_EXPR:
25342       return *tp;
25343 
25344       /* Treat requires-expressions as dependent. */
25345     case REQUIRES_EXPR:
25346       return *tp;
25347 
25348     case CALL_EXPR:
25349       /* Treat calls to function concepts as dependent. */
25350       if (function_concept_check_p (*tp))
25351         return *tp;
25352       break;
25353 
25354     case TEMPLATE_ID_EXPR:
25355       /* And variable concepts.  */
25356       if (variable_concept_p (TREE_OPERAND (*tp, 0)))
25357 	return *tp;
25358       break;
25359 
25360     default:
25361       break;
25362     }
25363 
25364   if (type_dependent_expression_p (*tp))
25365     return *tp;
25366   else
25367     return NULL_TREE;
25368 }
25369 
25370 /* Returns TRUE if the EXPRESSION is instantiation-dependent, in the
25371    sense defined by the ABI:
25372 
25373    "An expression is instantiation-dependent if it is type-dependent
25374    or value-dependent, or it has a subexpression that is type-dependent
25375    or value-dependent."
25376 
25377    Except don't actually check value-dependence for unevaluated expressions,
25378    because in sizeof(i) we don't care about the value of i.  Checking
25379    type-dependence will in turn check value-dependence of array bounds/template
25380    arguments as needed.  */
25381 
25382 bool
instantiation_dependent_uneval_expression_p(tree expression)25383 instantiation_dependent_uneval_expression_p (tree expression)
25384 {
25385   tree result;
25386 
25387   if (!processing_template_decl)
25388     return false;
25389 
25390   if (expression == error_mark_node)
25391     return false;
25392 
25393   result = cp_walk_tree_without_duplicates (&expression,
25394 					    instantiation_dependent_r, NULL);
25395   return result != NULL_TREE;
25396 }
25397 
25398 /* As above, but also check value-dependence of the expression as a whole.  */
25399 
25400 bool
instantiation_dependent_expression_p(tree expression)25401 instantiation_dependent_expression_p (tree expression)
25402 {
25403   return (instantiation_dependent_uneval_expression_p (expression)
25404 	  || value_dependent_expression_p (expression));
25405 }
25406 
25407 /* Like type_dependent_expression_p, but it also works while not processing
25408    a template definition, i.e. during substitution or mangling.  */
25409 
25410 bool
type_dependent_expression_p_push(tree expr)25411 type_dependent_expression_p_push (tree expr)
25412 {
25413   bool b;
25414   ++processing_template_decl;
25415   b = type_dependent_expression_p (expr);
25416   --processing_template_decl;
25417   return b;
25418 }
25419 
25420 /* Returns TRUE if ARGS contains a type-dependent expression.  */
25421 
25422 bool
any_type_dependent_arguments_p(const vec<tree,va_gc> * args)25423 any_type_dependent_arguments_p (const vec<tree, va_gc> *args)
25424 {
25425   unsigned int i;
25426   tree arg;
25427 
25428   FOR_EACH_VEC_SAFE_ELT (args, i, arg)
25429     {
25430       if (type_dependent_expression_p (arg))
25431 	return true;
25432     }
25433   return false;
25434 }
25435 
25436 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
25437    expressions) contains any type-dependent expressions.  */
25438 
25439 bool
any_type_dependent_elements_p(const_tree list)25440 any_type_dependent_elements_p (const_tree list)
25441 {
25442   for (; list; list = TREE_CHAIN (list))
25443     if (type_dependent_expression_p (TREE_VALUE (list)))
25444       return true;
25445 
25446   return false;
25447 }
25448 
25449 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
25450    expressions) contains any value-dependent expressions.  */
25451 
25452 bool
any_value_dependent_elements_p(const_tree list)25453 any_value_dependent_elements_p (const_tree list)
25454 {
25455   for (; list; list = TREE_CHAIN (list))
25456     if (value_dependent_expression_p (TREE_VALUE (list)))
25457       return true;
25458 
25459   return false;
25460 }
25461 
25462 /* Returns TRUE if the ARG (a template argument) is dependent.  */
25463 
25464 bool
dependent_template_arg_p(tree arg)25465 dependent_template_arg_p (tree arg)
25466 {
25467   if (!processing_template_decl)
25468     return false;
25469 
25470   /* Assume a template argument that was wrongly written by the user
25471      is dependent. This is consistent with what
25472      any_dependent_template_arguments_p [that calls this function]
25473      does.  */
25474   if (!arg || arg == error_mark_node)
25475     return true;
25476 
25477   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
25478     arg = argument_pack_select_arg (arg);
25479 
25480   if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
25481     return true;
25482   if (TREE_CODE (arg) == TEMPLATE_DECL)
25483     {
25484       if (DECL_TEMPLATE_PARM_P (arg))
25485 	return true;
25486       /* A member template of a dependent class is not necessarily
25487 	 type-dependent, but it is a dependent template argument because it
25488 	 will be a member of an unknown specialization to that template.  */
25489       tree scope = CP_DECL_CONTEXT (arg);
25490       return TYPE_P (scope) && dependent_type_p (scope);
25491     }
25492   else if (ARGUMENT_PACK_P (arg))
25493     {
25494       tree args = ARGUMENT_PACK_ARGS (arg);
25495       int i, len = TREE_VEC_LENGTH (args);
25496       for (i = 0; i < len; ++i)
25497         {
25498           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
25499             return true;
25500         }
25501 
25502       return false;
25503     }
25504   else if (TYPE_P (arg))
25505     return dependent_type_p (arg);
25506   else
25507     return (type_dependent_expression_p (arg)
25508 	    || value_dependent_expression_p (arg));
25509 }
25510 
25511 /* Returns true if ARGS (a collection of template arguments) contains
25512    any types that require structural equality testing.  */
25513 
25514 bool
any_template_arguments_need_structural_equality_p(tree args)25515 any_template_arguments_need_structural_equality_p (tree args)
25516 {
25517   int i;
25518   int j;
25519 
25520   if (!args)
25521     return false;
25522   if (args == error_mark_node)
25523     return true;
25524 
25525   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
25526     {
25527       tree level = TMPL_ARGS_LEVEL (args, i + 1);
25528       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
25529 	{
25530 	  tree arg = TREE_VEC_ELT (level, j);
25531 	  tree packed_args = NULL_TREE;
25532 	  int k, len = 1;
25533 
25534 	  if (ARGUMENT_PACK_P (arg))
25535 	    {
25536 	      /* Look inside the argument pack.  */
25537 	      packed_args = ARGUMENT_PACK_ARGS (arg);
25538 	      len = TREE_VEC_LENGTH (packed_args);
25539 	    }
25540 
25541 	  for (k = 0; k < len; ++k)
25542 	    {
25543 	      if (packed_args)
25544 		arg = TREE_VEC_ELT (packed_args, k);
25545 
25546 	      if (error_operand_p (arg))
25547 		return true;
25548 	      else if (TREE_CODE (arg) == TEMPLATE_DECL)
25549 		continue;
25550 	      else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
25551 		return true;
25552 	      else if (!TYPE_P (arg) && TREE_TYPE (arg)
25553 		       && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
25554 		return true;
25555 	    }
25556 	}
25557     }
25558 
25559   return false;
25560 }
25561 
25562 /* Returns true if ARGS (a collection of template arguments) contains
25563    any dependent arguments.  */
25564 
25565 bool
any_dependent_template_arguments_p(const_tree args)25566 any_dependent_template_arguments_p (const_tree args)
25567 {
25568   int i;
25569   int j;
25570 
25571   if (!args)
25572     return false;
25573   if (args == error_mark_node)
25574     return true;
25575 
25576   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
25577     {
25578       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
25579       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
25580 	if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
25581 	  return true;
25582     }
25583 
25584   return false;
25585 }
25586 
25587 /* Returns true if ARGS contains any errors.  */
25588 
25589 bool
any_erroneous_template_args_p(const_tree args)25590 any_erroneous_template_args_p (const_tree args)
25591 {
25592   int i;
25593   int j;
25594 
25595   if (args == error_mark_node)
25596     return true;
25597 
25598   if (args && TREE_CODE (args) != TREE_VEC)
25599     {
25600       if (tree ti = get_template_info (args))
25601 	args = TI_ARGS (ti);
25602       else
25603 	args = NULL_TREE;
25604     }
25605 
25606   if (!args)
25607     return false;
25608 
25609   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
25610     {
25611       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
25612       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
25613 	if (error_operand_p (TREE_VEC_ELT (level, j)))
25614 	  return true;
25615     }
25616 
25617   return false;
25618 }
25619 
25620 /* Returns TRUE if the template TMPL is type-dependent.  */
25621 
25622 bool
dependent_template_p(tree tmpl)25623 dependent_template_p (tree tmpl)
25624 {
25625   if (TREE_CODE (tmpl) == OVERLOAD)
25626     {
25627       for (lkp_iterator iter (tmpl); iter; ++iter)
25628 	if (dependent_template_p (*iter))
25629 	  return true;
25630       return false;
25631     }
25632 
25633   /* Template template parameters are dependent.  */
25634   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
25635       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
25636     return true;
25637   /* So are names that have not been looked up.  */
25638   if (TREE_CODE (tmpl) == SCOPE_REF || identifier_p (tmpl))
25639     return true;
25640   return false;
25641 }
25642 
25643 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
25644 
25645 bool
dependent_template_id_p(tree tmpl,tree args)25646 dependent_template_id_p (tree tmpl, tree args)
25647 {
25648   return (dependent_template_p (tmpl)
25649 	  || any_dependent_template_arguments_p (args));
25650 }
25651 
25652 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
25653    are dependent.  */
25654 
25655 bool
dependent_omp_for_p(tree declv,tree initv,tree condv,tree incrv)25656 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
25657 {
25658   int i;
25659 
25660   if (!processing_template_decl)
25661     return false;
25662 
25663   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
25664     {
25665       tree decl = TREE_VEC_ELT (declv, i);
25666       tree init = TREE_VEC_ELT (initv, i);
25667       tree cond = TREE_VEC_ELT (condv, i);
25668       tree incr = TREE_VEC_ELT (incrv, i);
25669 
25670       if (type_dependent_expression_p (decl)
25671 	  || TREE_CODE (decl) == SCOPE_REF)
25672 	return true;
25673 
25674       if (init && type_dependent_expression_p (init))
25675 	return true;
25676 
25677       if (type_dependent_expression_p (cond))
25678 	return true;
25679 
25680       if (COMPARISON_CLASS_P (cond)
25681 	  && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
25682 	      || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
25683 	return true;
25684 
25685       if (TREE_CODE (incr) == MODOP_EXPR)
25686 	{
25687 	  if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
25688 	      || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
25689 	    return true;
25690 	}
25691       else if (type_dependent_expression_p (incr))
25692 	return true;
25693       else if (TREE_CODE (incr) == MODIFY_EXPR)
25694 	{
25695 	  if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
25696 	    return true;
25697 	  else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
25698 	    {
25699 	      tree t = TREE_OPERAND (incr, 1);
25700 	      if (type_dependent_expression_p (TREE_OPERAND (t, 0))
25701 		  || type_dependent_expression_p (TREE_OPERAND (t, 1)))
25702 		return true;
25703 	    }
25704 	}
25705     }
25706 
25707   return false;
25708 }
25709 
25710 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
25711    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
25712    no such TYPE can be found.  Note that this function peers inside
25713    uninstantiated templates and therefore should be used only in
25714    extremely limited situations.  ONLY_CURRENT_P restricts this
25715    peering to the currently open classes hierarchy (which is required
25716    when comparing types).  */
25717 
25718 tree
resolve_typename_type(tree type,bool only_current_p)25719 resolve_typename_type (tree type, bool only_current_p)
25720 {
25721   tree scope;
25722   tree name;
25723   tree decl;
25724   int quals;
25725   tree pushed_scope;
25726   tree result;
25727 
25728   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
25729 
25730   scope = TYPE_CONTEXT (type);
25731   /* We shouldn't have built a TYPENAME_TYPE with a non-dependent scope.  */
25732   gcc_checking_assert (uses_template_parms (scope));
25733 
25734   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
25735      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
25736      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
25737      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
25738      identifier  of the TYPENAME_TYPE anymore.
25739      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
25740      TYPENAME_TYPE instead, we avoid messing up with a possible
25741      typedef variant case.  */
25742   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
25743 
25744   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
25745      it first before we can figure out what NAME refers to.  */
25746   if (TREE_CODE (scope) == TYPENAME_TYPE)
25747     {
25748       if (TYPENAME_IS_RESOLVING_P (scope))
25749 	/* Given a class template A with a dependent base with nested type C,
25750 	   typedef typename A::C::C C will land us here, as trying to resolve
25751 	   the initial A::C leads to the local C typedef, which leads back to
25752 	   A::C::C.  So we break the recursion now.  */
25753 	return type;
25754       else
25755 	scope = resolve_typename_type (scope, only_current_p);
25756     }
25757   /* If we don't know what SCOPE refers to, then we cannot resolve the
25758      TYPENAME_TYPE.  */
25759   if (!CLASS_TYPE_P (scope))
25760     return type;
25761   /* If this is a typedef, we don't want to look inside (c++/11987).  */
25762   if (typedef_variant_p (type))
25763     return type;
25764   /* If SCOPE isn't the template itself, it will not have a valid
25765      TYPE_FIELDS list.  */
25766   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
25767     /* scope is either the template itself or a compatible instantiation
25768        like X<T>, so look up the name in the original template.  */
25769     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
25770   /* If scope has no fields, it can't be a current instantiation.  Check this
25771      before currently_open_class to avoid infinite recursion (71515).  */
25772   if (!TYPE_FIELDS (scope))
25773     return type;
25774   /* If the SCOPE is not the current instantiation, there's no reason
25775      to look inside it.  */
25776   if (only_current_p && !currently_open_class (scope))
25777     return type;
25778   /* Enter the SCOPE so that name lookup will be resolved as if we
25779      were in the class definition.  In particular, SCOPE will no
25780      longer be considered a dependent type.  */
25781   pushed_scope = push_scope (scope);
25782   /* Look up the declaration.  */
25783   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true,
25784 			tf_warning_or_error);
25785 
25786   result = NULL_TREE;
25787 
25788   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
25789      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
25790   tree fullname = TYPENAME_TYPE_FULLNAME (type);
25791   if (!decl)
25792     /*nop*/;
25793   else if (identifier_p (fullname)
25794 	   && TREE_CODE (decl) == TYPE_DECL)
25795     {
25796       result = TREE_TYPE (decl);
25797       if (result == error_mark_node)
25798 	result = NULL_TREE;
25799     }
25800   else if (TREE_CODE (fullname) == TEMPLATE_ID_EXPR
25801 	   && DECL_CLASS_TEMPLATE_P (decl))
25802     {
25803       /* Obtain the template and the arguments.  */
25804       tree tmpl = TREE_OPERAND (fullname, 0);
25805       if (TREE_CODE (tmpl) == IDENTIFIER_NODE)
25806 	{
25807 	  /* We get here with a plain identifier because a previous tentative
25808 	     parse of the nested-name-specifier as part of a ptr-operator saw
25809 	     ::template X<A>.  The use of ::template is necessary in a
25810 	     ptr-operator, but wrong in a declarator-id.
25811 
25812 	     [temp.names]: In a qualified-id of a declarator-id, the keyword
25813 	     template shall not appear at the top level.  */
25814 	  pedwarn (EXPR_LOC_OR_LOC (fullname, input_location), OPT_Wpedantic,
25815 		   "keyword %<template%> not allowed in declarator-id");
25816 	  tmpl = decl;
25817 	}
25818       tree args = TREE_OPERAND (fullname, 1);
25819       /* Instantiate the template.  */
25820       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
25821 				      /*entering_scope=*/true,
25822 				      tf_error | tf_user);
25823       if (result == error_mark_node)
25824 	result = NULL_TREE;
25825     }
25826 
25827   /* Leave the SCOPE.  */
25828   if (pushed_scope)
25829     pop_scope (pushed_scope);
25830 
25831   /* If we failed to resolve it, return the original typename.  */
25832   if (!result)
25833     return type;
25834 
25835   /* If lookup found a typename type, resolve that too.  */
25836   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
25837     {
25838       /* Ill-formed programs can cause infinite recursion here, so we
25839 	 must catch that.  */
25840       TYPENAME_IS_RESOLVING_P (result) = 1;
25841       result = resolve_typename_type (result, only_current_p);
25842       TYPENAME_IS_RESOLVING_P (result) = 0;
25843     }
25844 
25845   /* Qualify the resulting type.  */
25846   quals = cp_type_quals (type);
25847   if (quals)
25848     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
25849 
25850   return result;
25851 }
25852 
25853 /* EXPR is an expression which is not type-dependent.  Return a proxy
25854    for EXPR that can be used to compute the types of larger
25855    expressions containing EXPR.  */
25856 
25857 tree
build_non_dependent_expr(tree expr)25858 build_non_dependent_expr (tree expr)
25859 {
25860   tree orig_expr = expr;
25861   tree inner_expr;
25862 
25863   /* When checking, try to get a constant value for all non-dependent
25864      expressions in order to expose bugs in *_dependent_expression_p
25865      and constexpr.  This can affect code generation, see PR70704, so
25866      only do this for -fchecking=2.  */
25867   if (flag_checking > 1
25868       && cxx_dialect >= cxx11
25869       /* Don't do this during nsdmi parsing as it can lead to
25870 	 unexpected recursive instantiations.  */
25871       && !parsing_nsdmi ()
25872       /* Don't do this during concept expansion either and for
25873          the same reason.  */
25874       && !expanding_concept ())
25875     fold_non_dependent_expr (expr);
25876 
25877   STRIP_ANY_LOCATION_WRAPPER (expr);
25878 
25879   /* Preserve OVERLOADs; the functions must be available to resolve
25880      types.  */
25881   inner_expr = expr;
25882   if (TREE_CODE (inner_expr) == STMT_EXPR)
25883     inner_expr = stmt_expr_value_expr (inner_expr);
25884   if (TREE_CODE (inner_expr) == ADDR_EXPR)
25885     inner_expr = TREE_OPERAND (inner_expr, 0);
25886   if (TREE_CODE (inner_expr) == COMPONENT_REF)
25887     inner_expr = TREE_OPERAND (inner_expr, 1);
25888   if (is_overloaded_fn (inner_expr)
25889       || TREE_CODE (inner_expr) == OFFSET_REF)
25890     return orig_expr;
25891   /* There is no need to return a proxy for a variable.  */
25892   if (VAR_P (expr))
25893     return orig_expr;
25894   /* Preserve string constants; conversions from string constants to
25895      "char *" are allowed, even though normally a "const char *"
25896      cannot be used to initialize a "char *".  */
25897   if (TREE_CODE (expr) == STRING_CST)
25898     return orig_expr;
25899   /* Preserve void and arithmetic constants, as an optimization -- there is no
25900      reason to create a new node.  */
25901   if (TREE_CODE (expr) == VOID_CST
25902       || TREE_CODE (expr) == INTEGER_CST
25903       || TREE_CODE (expr) == REAL_CST)
25904     return orig_expr;
25905   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
25906      There is at least one place where we want to know that a
25907      particular expression is a throw-expression: when checking a ?:
25908      expression, there are special rules if the second or third
25909      argument is a throw-expression.  */
25910   if (TREE_CODE (expr) == THROW_EXPR)
25911     return orig_expr;
25912 
25913   /* Don't wrap an initializer list, we need to be able to look inside.  */
25914   if (BRACE_ENCLOSED_INITIALIZER_P (expr))
25915     return orig_expr;
25916 
25917   /* Don't wrap a dummy object, we need to be able to test for it.  */
25918   if (is_dummy_object (expr))
25919     return orig_expr;
25920 
25921   if (TREE_CODE (expr) == COND_EXPR)
25922     return build3 (COND_EXPR,
25923 		   TREE_TYPE (expr),
25924 		   TREE_OPERAND (expr, 0),
25925 		   (TREE_OPERAND (expr, 1)
25926 		    ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
25927 		    : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
25928 		   build_non_dependent_expr (TREE_OPERAND (expr, 2)));
25929   if (TREE_CODE (expr) == COMPOUND_EXPR
25930       && !COMPOUND_EXPR_OVERLOADED (expr))
25931     return build2 (COMPOUND_EXPR,
25932 		   TREE_TYPE (expr),
25933 		   TREE_OPERAND (expr, 0),
25934 		   build_non_dependent_expr (TREE_OPERAND (expr, 1)));
25935 
25936   /* If the type is unknown, it can't really be non-dependent */
25937   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
25938 
25939   /* Otherwise, build a NON_DEPENDENT_EXPR.  */
25940   return build1_loc (EXPR_LOCATION (orig_expr), NON_DEPENDENT_EXPR,
25941 		     TREE_TYPE (expr), expr);
25942 }
25943 
25944 /* ARGS is a vector of expressions as arguments to a function call.
25945    Replace the arguments with equivalent non-dependent expressions.
25946    This modifies ARGS in place.  */
25947 
25948 void
make_args_non_dependent(vec<tree,va_gc> * args)25949 make_args_non_dependent (vec<tree, va_gc> *args)
25950 {
25951   unsigned int ix;
25952   tree arg;
25953 
25954   FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
25955     {
25956       tree newarg = build_non_dependent_expr (arg);
25957       if (newarg != arg)
25958 	(*args)[ix] = newarg;
25959     }
25960 }
25961 
25962 /* Returns a type which represents 'auto' or 'decltype(auto)'.  We use a
25963    TEMPLATE_TYPE_PARM with a level one deeper than the actual template
25964    parms.  If set_canonical is true, we set TYPE_CANONICAL on it.  */
25965 
25966 static tree
make_auto_1(tree name,bool set_canonical)25967 make_auto_1 (tree name, bool set_canonical)
25968 {
25969   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
25970   TYPE_NAME (au) = build_decl (input_location,
25971 			       TYPE_DECL, name, au);
25972   TYPE_STUB_DECL (au) = TYPE_NAME (au);
25973   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
25974     (0, processing_template_decl + 1, processing_template_decl + 1,
25975      TYPE_NAME (au), NULL_TREE);
25976   if (set_canonical)
25977     TYPE_CANONICAL (au) = canonical_type_parameter (au);
25978   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
25979   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
25980 
25981   return au;
25982 }
25983 
25984 tree
make_decltype_auto(void)25985 make_decltype_auto (void)
25986 {
25987   return make_auto_1 (decltype_auto_identifier, true);
25988 }
25989 
25990 tree
make_auto(void)25991 make_auto (void)
25992 {
25993   return make_auto_1 (auto_identifier, true);
25994 }
25995 
25996 /* Return a C++17 deduction placeholder for class template TMPL.  */
25997 
25998 tree
make_template_placeholder(tree tmpl)25999 make_template_placeholder (tree tmpl)
26000 {
26001   tree t = make_auto_1 (DECL_NAME (tmpl), true);
26002   CLASS_PLACEHOLDER_TEMPLATE (t) = tmpl;
26003   return t;
26004 }
26005 
26006 /* True iff T is a C++17 class template deduction placeholder.  */
26007 
26008 bool
template_placeholder_p(tree t)26009 template_placeholder_p (tree t)
26010 {
26011   return is_auto (t) && CLASS_PLACEHOLDER_TEMPLATE (t);
26012 }
26013 
26014 /* Make a "constrained auto" type-specifier. This is an
26015    auto type with constraints that must be associated after
26016    deduction.  The constraint is formed from the given
26017    CONC and its optional sequence of arguments, which are
26018    non-null if written as partial-concept-id.  */
26019 
26020 tree
make_constrained_auto(tree con,tree args)26021 make_constrained_auto (tree con, tree args)
26022 {
26023   tree type = make_auto_1 (auto_identifier, false);
26024 
26025   /* Build the constraint. */
26026   tree tmpl = DECL_TI_TEMPLATE (con);
26027   tree expr = VAR_P (con) ? tmpl : ovl_make (tmpl);
26028   expr = build_concept_check (expr, type, args);
26029 
26030   tree constr = normalize_expression (expr);
26031   PLACEHOLDER_TYPE_CONSTRAINTS (type) = constr;
26032 
26033   /* Our canonical type depends on the constraint.  */
26034   TYPE_CANONICAL (type) = canonical_type_parameter (type);
26035 
26036   /* Attach the constraint to the type declaration. */
26037   tree decl = TYPE_NAME (type);
26038   return decl;
26039 }
26040 
26041 /* Given type ARG, return std::initializer_list<ARG>.  */
26042 
26043 static tree
listify(tree arg)26044 listify (tree arg)
26045 {
26046   tree std_init_list = get_namespace_binding (std_node, init_list_identifier);
26047 
26048   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
26049     {
26050       gcc_rich_location richloc (input_location);
26051       maybe_add_include_fixit (&richloc, "<initializer_list>");
26052       error_at (&richloc,
26053 		"deducing from brace-enclosed initializer list"
26054 		" requires %<#include <initializer_list>%>");
26055 
26056       return error_mark_node;
26057     }
26058   tree argvec = make_tree_vec (1);
26059   TREE_VEC_ELT (argvec, 0) = arg;
26060 
26061   return lookup_template_class (std_init_list, argvec, NULL_TREE,
26062 				NULL_TREE, 0, tf_warning_or_error);
26063 }
26064 
26065 /* Replace auto in TYPE with std::initializer_list<auto>.  */
26066 
26067 static tree
listify_autos(tree type,tree auto_node)26068 listify_autos (tree type, tree auto_node)
26069 {
26070   tree init_auto = listify (auto_node);
26071   tree argvec = make_tree_vec (1);
26072   TREE_VEC_ELT (argvec, 0) = init_auto;
26073   if (processing_template_decl)
26074     argvec = add_to_template_args (current_template_args (), argvec);
26075   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
26076 }
26077 
26078 /* Hash traits for hashing possibly constrained 'auto'
26079    TEMPLATE_TYPE_PARMs for use by do_auto_deduction.  */
26080 
26081 struct auto_hash : default_hash_traits<tree>
26082 {
26083   static inline hashval_t hash (tree);
26084   static inline bool equal (tree, tree);
26085 };
26086 
26087 /* Hash the 'auto' T.  */
26088 
26089 inline hashval_t
hash(tree t)26090 auto_hash::hash (tree t)
26091 {
26092   if (tree c = PLACEHOLDER_TYPE_CONSTRAINTS (t))
26093     /* Matching constrained-type-specifiers denote the same template
26094        parameter, so hash the constraint.  */
26095     return hash_placeholder_constraint (c);
26096   else
26097     /* But unconstrained autos are all separate, so just hash the pointer.  */
26098     return iterative_hash_object (t, 0);
26099 }
26100 
26101 /* Compare two 'auto's.  */
26102 
26103 inline bool
equal(tree t1,tree t2)26104 auto_hash::equal (tree t1, tree t2)
26105 {
26106   if (t1 == t2)
26107     return true;
26108 
26109   tree c1 = PLACEHOLDER_TYPE_CONSTRAINTS (t1);
26110   tree c2 = PLACEHOLDER_TYPE_CONSTRAINTS (t2);
26111 
26112   /* Two unconstrained autos are distinct.  */
26113   if (!c1 || !c2)
26114     return false;
26115 
26116   return equivalent_placeholder_constraints (c1, c2);
26117 }
26118 
26119 /* for_each_template_parm callback for extract_autos: if t is a (possibly
26120    constrained) auto, add it to the vector.  */
26121 
26122 static int
extract_autos_r(tree t,void * data)26123 extract_autos_r (tree t, void *data)
26124 {
26125   hash_table<auto_hash> &hash = *(hash_table<auto_hash>*)data;
26126   if (is_auto (t))
26127     {
26128       /* All the autos were built with index 0; fix that up now.  */
26129       tree *p = hash.find_slot (t, INSERT);
26130       unsigned idx;
26131       if (*p)
26132 	/* If this is a repeated constrained-type-specifier, use the index we
26133 	   chose before.  */
26134 	idx = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (*p));
26135       else
26136 	{
26137 	  /* Otherwise this is new, so use the current count.  */
26138 	  *p = t;
26139 	  idx = hash.elements () - 1;
26140 	}
26141       TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (t)) = idx;
26142     }
26143 
26144   /* Always keep walking.  */
26145   return 0;
26146 }
26147 
26148 /* Return a TREE_VEC of the 'auto's used in type under the Concepts TS, which
26149    says they can appear anywhere in the type.  */
26150 
26151 static tree
extract_autos(tree type)26152 extract_autos (tree type)
26153 {
26154   hash_set<tree> visited;
26155   hash_table<auto_hash> hash (2);
26156 
26157   for_each_template_parm (type, extract_autos_r, &hash, &visited, true);
26158 
26159   tree tree_vec = make_tree_vec (hash.elements());
26160   for (hash_table<auto_hash>::iterator iter = hash.begin();
26161        iter != hash.end(); ++iter)
26162     {
26163       tree elt = *iter;
26164       unsigned i = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (elt));
26165       TREE_VEC_ELT (tree_vec, i)
26166 	= build_tree_list (NULL_TREE, TYPE_NAME (elt));
26167     }
26168 
26169   return tree_vec;
26170 }
26171 
26172 /* The stem for deduction guide names.  */
26173 const char *const dguide_base = "__dguide_";
26174 
26175 /* Return the name for a deduction guide for class template TMPL.  */
26176 
26177 tree
dguide_name(tree tmpl)26178 dguide_name (tree tmpl)
26179 {
26180   tree type = (TYPE_P (tmpl) ? tmpl : TREE_TYPE (tmpl));
26181   tree tname = TYPE_IDENTIFIER (type);
26182   char *buf = (char *) alloca (1 + strlen (dguide_base)
26183 			       + IDENTIFIER_LENGTH (tname));
26184   memcpy (buf, dguide_base, strlen (dguide_base));
26185   memcpy (buf + strlen (dguide_base), IDENTIFIER_POINTER (tname),
26186 	  IDENTIFIER_LENGTH (tname) + 1);
26187   tree dname = get_identifier (buf);
26188   TREE_TYPE (dname) = type;
26189   return dname;
26190 }
26191 
26192 /* True if NAME is the name of a deduction guide.  */
26193 
26194 bool
dguide_name_p(tree name)26195 dguide_name_p (tree name)
26196 {
26197   return (TREE_CODE (name) == IDENTIFIER_NODE
26198 	  && TREE_TYPE (name)
26199 	  && !strncmp (IDENTIFIER_POINTER (name), dguide_base,
26200 		       strlen (dguide_base)));
26201 }
26202 
26203 /* True if FN is a deduction guide.  */
26204 
26205 bool
deduction_guide_p(const_tree fn)26206 deduction_guide_p (const_tree fn)
26207 {
26208   if (DECL_P (fn))
26209     if (tree name = DECL_NAME (fn))
26210       return dguide_name_p (name);
26211   return false;
26212 }
26213 
26214 /* True if FN is the copy deduction guide, i.e. A(A)->A.  */
26215 
26216 bool
copy_guide_p(const_tree fn)26217 copy_guide_p (const_tree fn)
26218 {
26219   gcc_assert (deduction_guide_p (fn));
26220   if (!DECL_ARTIFICIAL (fn))
26221     return false;
26222   tree parms = FUNCTION_FIRST_USER_PARMTYPE (DECL_TI_TEMPLATE (fn));
26223   return (TREE_CHAIN (parms) == void_list_node
26224 	  && same_type_p (TREE_VALUE (parms), TREE_TYPE (DECL_NAME (fn))));
26225 }
26226 
26227 /* True if FN is a guide generated from a constructor template.  */
26228 
26229 bool
template_guide_p(const_tree fn)26230 template_guide_p (const_tree fn)
26231 {
26232   gcc_assert (deduction_guide_p (fn));
26233   if (!DECL_ARTIFICIAL (fn))
26234     return false;
26235   tree tmpl = DECL_TI_TEMPLATE (fn);
26236   if (tree org = DECL_ABSTRACT_ORIGIN (tmpl))
26237     return PRIMARY_TEMPLATE_P (org);
26238   return false;
26239 }
26240 
26241 /* OLDDECL is a _DECL for a template parameter.  Return a similar parameter at
26242    LEVEL:INDEX, using tsubst_args and complain for substitution into non-type
26243    template parameter types.  Note that the handling of template template
26244    parameters relies on current_template_parms being set appropriately for the
26245    new template.  */
26246 
26247 static tree
rewrite_template_parm(tree olddecl,unsigned index,unsigned level,tree tsubst_args,tsubst_flags_t complain)26248 rewrite_template_parm (tree olddecl, unsigned index, unsigned level,
26249 		       tree tsubst_args, tsubst_flags_t complain)
26250 {
26251   if (olddecl == error_mark_node)
26252     return error_mark_node;
26253 
26254   tree oldidx = get_template_parm_index (olddecl);
26255 
26256   tree newtype;
26257   if (TREE_CODE (olddecl) == TYPE_DECL
26258       || TREE_CODE (olddecl) == TEMPLATE_DECL)
26259     {
26260       tree oldtype = TREE_TYPE (olddecl);
26261       newtype = cxx_make_type (TREE_CODE (oldtype));
26262       TYPE_MAIN_VARIANT (newtype) = newtype;
26263       if (TREE_CODE (oldtype) == TEMPLATE_TYPE_PARM)
26264 	TEMPLATE_TYPE_PARM_FOR_CLASS (newtype)
26265 	  = TEMPLATE_TYPE_PARM_FOR_CLASS (oldtype);
26266     }
26267   else
26268     {
26269       newtype = TREE_TYPE (olddecl);
26270       if (type_uses_auto (newtype))
26271 	{
26272 	  // Substitute once to fix references to other template parameters.
26273 	  newtype = tsubst (newtype, tsubst_args,
26274 			    complain|tf_partial, NULL_TREE);
26275 	  // Now substitute again to reduce the level of the auto.
26276 	  newtype = tsubst (newtype, current_template_args (),
26277 			    complain, NULL_TREE);
26278 	}
26279       else
26280 	newtype = tsubst (newtype, tsubst_args,
26281 			  complain, NULL_TREE);
26282     }
26283 
26284   tree newdecl
26285     = build_decl (DECL_SOURCE_LOCATION (olddecl), TREE_CODE (olddecl),
26286 		  DECL_NAME (olddecl), newtype);
26287   SET_DECL_TEMPLATE_PARM_P (newdecl);
26288 
26289   tree newidx;
26290   if (TREE_CODE (olddecl) == TYPE_DECL
26291       || TREE_CODE (olddecl) == TEMPLATE_DECL)
26292     {
26293       newidx = TEMPLATE_TYPE_PARM_INDEX (newtype)
26294 	= build_template_parm_index (index, level, level,
26295 				     newdecl, newtype);
26296       TEMPLATE_PARM_PARAMETER_PACK (newidx)
26297 	= TEMPLATE_PARM_PARAMETER_PACK (oldidx);
26298       TYPE_STUB_DECL (newtype) = TYPE_NAME (newtype) = newdecl;
26299       TYPE_CANONICAL (newtype) = canonical_type_parameter (newtype);
26300 
26301       if (TREE_CODE (olddecl) == TEMPLATE_DECL)
26302 	{
26303 	  DECL_TEMPLATE_RESULT (newdecl)
26304 	    = build_decl (DECL_SOURCE_LOCATION (olddecl), TYPE_DECL,
26305 			  DECL_NAME (olddecl), newtype);
26306 	  DECL_ARTIFICIAL (DECL_TEMPLATE_RESULT (newdecl)) = true;
26307 	  // First create a copy (ttargs) of tsubst_args with an
26308 	  // additional level for the template template parameter's own
26309 	  // template parameters (ttparms).
26310 	  tree ttparms = (INNERMOST_TEMPLATE_PARMS
26311 			  (DECL_TEMPLATE_PARMS (olddecl)));
26312 	  const int depth = TMPL_ARGS_DEPTH (tsubst_args);
26313 	  tree ttargs = make_tree_vec (depth + 1);
26314 	  for (int i = 0; i < depth; ++i)
26315 	    TREE_VEC_ELT (ttargs, i) = TREE_VEC_ELT (tsubst_args, i);
26316 	  TREE_VEC_ELT (ttargs, depth)
26317 	    = template_parms_level_to_args (ttparms);
26318 	  // Substitute ttargs into ttparms to fix references to
26319 	  // other template parameters.
26320 	  ttparms = tsubst_template_parms_level (ttparms, ttargs,
26321 						 complain|tf_partial);
26322 	  // Now substitute again with args based on tparms, to reduce
26323 	  // the level of the ttparms.
26324 	  ttargs = current_template_args ();
26325 	  ttparms = tsubst_template_parms_level (ttparms, ttargs,
26326 						 complain);
26327 	  // Finally, tack the adjusted parms onto tparms.
26328 	  ttparms = tree_cons (size_int (depth), ttparms,
26329 			       current_template_parms);
26330 	  DECL_TEMPLATE_PARMS (newdecl) = ttparms;
26331 	}
26332     }
26333   else
26334     {
26335       tree oldconst = TEMPLATE_PARM_DECL (oldidx);
26336       tree newconst
26337 	= build_decl (DECL_SOURCE_LOCATION (oldconst),
26338 		      TREE_CODE (oldconst),
26339 		      DECL_NAME (oldconst), newtype);
26340       TREE_CONSTANT (newconst) = TREE_CONSTANT (newdecl)
26341 	= TREE_READONLY (newconst) = TREE_READONLY (newdecl) = true;
26342       SET_DECL_TEMPLATE_PARM_P (newconst);
26343       newidx = build_template_parm_index (index, level, level,
26344 					  newconst, newtype);
26345       TEMPLATE_PARM_PARAMETER_PACK (newidx)
26346 	= TEMPLATE_PARM_PARAMETER_PACK (oldidx);
26347       DECL_INITIAL (newdecl) = DECL_INITIAL (newconst) = newidx;
26348     }
26349 
26350   return newdecl;
26351 }
26352 
26353 /* Returns a C++17 class deduction guide template based on the constructor
26354    CTOR.  As a special case, CTOR can be a RECORD_TYPE for an implicit default
26355    guide, or REFERENCE_TYPE for an implicit copy/move guide.  */
26356 
26357 static tree
build_deduction_guide(tree ctor,tree outer_args,tsubst_flags_t complain)26358 build_deduction_guide (tree ctor, tree outer_args, tsubst_flags_t complain)
26359 {
26360   tree type, tparms, targs, fparms, fargs, ci;
26361   bool memtmpl = false;
26362   bool explicit_p;
26363   location_t loc;
26364   tree fn_tmpl = NULL_TREE;
26365 
26366   if (TYPE_P (ctor))
26367     {
26368       type = ctor;
26369       bool copy_p = TREE_CODE (type) == REFERENCE_TYPE;
26370       if (copy_p)
26371 	{
26372 	  type = TREE_TYPE (type);
26373 	  fparms = tree_cons (NULL_TREE, type, void_list_node);
26374 	}
26375       else
26376 	fparms = void_list_node;
26377 
26378       tree ctmpl = CLASSTYPE_TI_TEMPLATE (type);
26379       tparms = DECL_TEMPLATE_PARMS (ctmpl);
26380       targs = CLASSTYPE_TI_ARGS (type);
26381       ci = NULL_TREE;
26382       fargs = NULL_TREE;
26383       loc = DECL_SOURCE_LOCATION (ctmpl);
26384       explicit_p = false;
26385     }
26386   else
26387     {
26388       ++processing_template_decl;
26389       bool ok = true;
26390 
26391       fn_tmpl
26392 	= (TREE_CODE (ctor) == TEMPLATE_DECL ? ctor
26393 	   : DECL_TI_TEMPLATE (ctor));
26394       if (outer_args)
26395 	fn_tmpl = tsubst (fn_tmpl, outer_args, complain, ctor);
26396       ctor = DECL_TEMPLATE_RESULT (fn_tmpl);
26397 
26398       type = DECL_CONTEXT (ctor);
26399 
26400       tparms = DECL_TEMPLATE_PARMS (fn_tmpl);
26401       /* If type is a member class template, DECL_TI_ARGS (ctor) will have
26402 	 fully specialized args for the enclosing class.  Strip those off, as
26403 	 the deduction guide won't have those template parameters.  */
26404       targs = get_innermost_template_args (DECL_TI_ARGS (ctor),
26405 						TMPL_PARMS_DEPTH (tparms));
26406       /* Discard the 'this' parameter.  */
26407       fparms = FUNCTION_ARG_CHAIN (ctor);
26408       fargs = TREE_CHAIN (DECL_ARGUMENTS (ctor));
26409       ci = get_constraints (ctor);
26410       loc = DECL_SOURCE_LOCATION (ctor);
26411       explicit_p = DECL_NONCONVERTING_P (ctor);
26412 
26413       if (PRIMARY_TEMPLATE_P (fn_tmpl))
26414 	{
26415 	  memtmpl = true;
26416 
26417 	  /* For a member template constructor, we need to flatten the two
26418 	     template parameter lists into one, and then adjust the function
26419 	     signature accordingly.  This gets...complicated.  */
26420 	  tree save_parms = current_template_parms;
26421 
26422 	  /* For a member template we should have two levels of parms/args, one
26423 	     for the class and one for the constructor.  We stripped
26424 	     specialized args for further enclosing classes above.  */
26425 	  const int depth = 2;
26426 	  gcc_assert (TMPL_ARGS_DEPTH (targs) == depth);
26427 
26428 	  /* Template args for translating references to the two-level template
26429 	     parameters into references to the one-level template parameters we
26430 	     are creating.  */
26431 	  tree tsubst_args = copy_node (targs);
26432 	  TMPL_ARGS_LEVEL (tsubst_args, depth)
26433 	    = copy_node (TMPL_ARGS_LEVEL (tsubst_args, depth));
26434 
26435 	  /* Template parms for the constructor template.  */
26436 	  tree ftparms = TREE_VALUE (tparms);
26437 	  unsigned flen = TREE_VEC_LENGTH (ftparms);
26438 	  /* Template parms for the class template.  */
26439 	  tparms = TREE_CHAIN (tparms);
26440 	  tree ctparms = TREE_VALUE (tparms);
26441 	  unsigned clen = TREE_VEC_LENGTH (ctparms);
26442 	  /* Template parms for the deduction guide start as a copy of the
26443 	     template parms for the class.  We set current_template_parms for
26444 	     lookup_template_class_1.  */
26445 	  current_template_parms = tparms = copy_node (tparms);
26446 	  tree new_vec = TREE_VALUE (tparms) = make_tree_vec (flen + clen);
26447 	  for (unsigned i = 0; i < clen; ++i)
26448 	    TREE_VEC_ELT (new_vec, i) = TREE_VEC_ELT (ctparms, i);
26449 
26450 	  /* Now we need to rewrite the constructor parms to append them to the
26451 	     class parms.  */
26452 	  for (unsigned i = 0; i < flen; ++i)
26453 	    {
26454 	      unsigned index = i + clen;
26455 	      unsigned level = 1;
26456 	      tree oldelt = TREE_VEC_ELT (ftparms, i);
26457 	      tree olddecl = TREE_VALUE (oldelt);
26458 	      tree newdecl = rewrite_template_parm (olddecl, index, level,
26459 						    tsubst_args, complain);
26460 	      if (newdecl == error_mark_node)
26461 		ok = false;
26462 	      tree newdef = tsubst_template_arg (TREE_PURPOSE (oldelt),
26463 						 tsubst_args, complain, ctor);
26464 	      tree list = build_tree_list (newdef, newdecl);
26465 	      TEMPLATE_PARM_CONSTRAINTS (list)
26466 		= tsubst_constraint_info (TEMPLATE_PARM_CONSTRAINTS (oldelt),
26467 					  tsubst_args, complain, ctor);
26468 	      TREE_VEC_ELT (new_vec, index) = list;
26469 	      TMPL_ARG (tsubst_args, depth, i) = template_parm_to_arg (list);
26470 	    }
26471 
26472 	  /* Now we have a final set of template parms to substitute into the
26473 	     function signature.  */
26474 	  targs = template_parms_to_args (tparms);
26475 	  fparms = tsubst_arg_types (fparms, tsubst_args, NULL_TREE,
26476 				     complain, ctor);
26477 	  if (fparms == error_mark_node)
26478 	    ok = false;
26479 	  fargs = tsubst (fargs, tsubst_args, complain, ctor);
26480 	  if (ci)
26481 	    ci = tsubst_constraint_info (ci, tsubst_args, complain, ctor);
26482 
26483 	  current_template_parms = save_parms;
26484 	}
26485 
26486       --processing_template_decl;
26487       if (!ok)
26488 	return error_mark_node;
26489     }
26490 
26491   if (!memtmpl)
26492     {
26493       /* Copy the parms so we can set DECL_PRIMARY_TEMPLATE.  */
26494       tparms = copy_node (tparms);
26495       INNERMOST_TEMPLATE_PARMS (tparms)
26496 	= copy_node (INNERMOST_TEMPLATE_PARMS (tparms));
26497     }
26498 
26499   tree fntype = build_function_type (type, fparms);
26500   tree ded_fn = build_lang_decl_loc (loc,
26501 				     FUNCTION_DECL,
26502 				     dguide_name (type), fntype);
26503   DECL_ARGUMENTS (ded_fn) = fargs;
26504   DECL_ARTIFICIAL (ded_fn) = true;
26505   DECL_NONCONVERTING_P (ded_fn) = explicit_p;
26506   tree ded_tmpl = build_template_decl (ded_fn, tparms, /*member*/false);
26507   DECL_ARTIFICIAL (ded_tmpl) = true;
26508   DECL_TEMPLATE_RESULT (ded_tmpl) = ded_fn;
26509   TREE_TYPE (ded_tmpl) = TREE_TYPE (ded_fn);
26510   DECL_TEMPLATE_INFO (ded_fn) = build_template_info (ded_tmpl, targs);
26511   DECL_PRIMARY_TEMPLATE (ded_tmpl) = ded_tmpl;
26512   if (DECL_P (ctor))
26513     DECL_ABSTRACT_ORIGIN (ded_tmpl) = fn_tmpl;
26514   if (ci)
26515     set_constraints (ded_tmpl, ci);
26516 
26517   return ded_tmpl;
26518 }
26519 
26520 /* Deduce template arguments for the class template placeholder PTYPE for
26521    template TMPL based on the initializer INIT, and return the resulting
26522    type.  */
26523 
26524 static tree
do_class_deduction(tree ptype,tree tmpl,tree init,int flags,tsubst_flags_t complain)26525 do_class_deduction (tree ptype, tree tmpl, tree init, int flags,
26526 		    tsubst_flags_t complain)
26527 {
26528   if (!DECL_CLASS_TEMPLATE_P (tmpl))
26529     {
26530       /* We should have handled this in the caller.  */
26531       if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl))
26532 	return ptype;
26533       if (complain & tf_error)
26534 	error ("non-class template %qT used without template arguments", tmpl);
26535       return error_mark_node;
26536     }
26537 
26538   tree type = TREE_TYPE (tmpl);
26539 
26540   bool try_list_ctor = false;
26541 
26542   vec<tree,va_gc> *args;
26543   if (init == NULL_TREE
26544       || TREE_CODE (init) == TREE_LIST)
26545     args = make_tree_vector_from_list (init);
26546   else if (BRACE_ENCLOSED_INITIALIZER_P (init))
26547     {
26548       try_list_ctor = TYPE_HAS_LIST_CTOR (type);
26549       if (try_list_ctor && CONSTRUCTOR_NELTS (init) == 1)
26550 	{
26551 	  /* As an exception, the first phase in 16.3.1.7 (considering the
26552 	     initializer list as a single argument) is omitted if the
26553 	     initializer list consists of a single expression of type cv U,
26554 	     where U is a specialization of C or a class derived from a
26555 	     specialization of C.  */
26556 	  tree elt = CONSTRUCTOR_ELT (init, 0)->value;
26557 	  tree etype = TREE_TYPE (elt);
26558 
26559 	  tree tparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
26560 	  tree targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
26561 	  int err = unify (tparms, targs, type, etype,
26562 			   UNIFY_ALLOW_DERIVED, /*explain*/false);
26563 	  if (err == 0)
26564 	    try_list_ctor = false;
26565 	  ggc_free (targs);
26566 	}
26567       if (try_list_ctor || is_std_init_list (type))
26568 	args = make_tree_vector_single (init);
26569       else
26570 	args = make_tree_vector_from_ctor (init);
26571     }
26572   else
26573     args = make_tree_vector_single (init);
26574 
26575   tree dname = dguide_name (tmpl);
26576   tree cands = lookup_qualified_name (CP_DECL_CONTEXT (tmpl), dname,
26577 				      /*type*/false, /*complain*/false,
26578 				      /*hidden*/false);
26579   bool elided = false;
26580   if (cands == error_mark_node)
26581     cands = NULL_TREE;
26582 
26583   /* Prune explicit deduction guides in copy-initialization context.  */
26584   if (flags & LOOKUP_ONLYCONVERTING)
26585     {
26586       for (lkp_iterator iter (cands); !elided && iter; ++iter)
26587 	if (DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
26588 	  elided = true;
26589 
26590       if (elided)
26591 	{
26592 	  /* Found a nonconverting guide, prune the candidates.  */
26593 	  tree pruned = NULL_TREE;
26594 	  for (lkp_iterator iter (cands); iter; ++iter)
26595 	    if (!DECL_NONCONVERTING_P (STRIP_TEMPLATE (*iter)))
26596 	      pruned = lookup_add (*iter, pruned);
26597 
26598 	  cands = pruned;
26599 	}
26600     }
26601 
26602   tree outer_args = NULL_TREE;
26603   if (DECL_CLASS_SCOPE_P (tmpl)
26604       && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (tmpl)))
26605     {
26606       outer_args = CLASSTYPE_TI_ARGS (DECL_CONTEXT (tmpl));
26607       type = TREE_TYPE (most_general_template (tmpl));
26608     }
26609 
26610   bool saw_ctor = false;
26611   // FIXME cache artificial deduction guides
26612   for (ovl_iterator iter (CLASSTYPE_CONSTRUCTORS (type)); iter; ++iter)
26613     {
26614       /* Skip inherited constructors.  */
26615       if (iter.using_p ())
26616 	continue;
26617 
26618       tree guide = build_deduction_guide (*iter, outer_args, complain);
26619       if (guide == error_mark_node)
26620 	return error_mark_node;
26621       if ((flags & LOOKUP_ONLYCONVERTING)
26622 	  && DECL_NONCONVERTING_P (STRIP_TEMPLATE (guide)))
26623 	elided = true;
26624       else
26625 	cands = lookup_add (guide, cands);
26626 
26627       saw_ctor = true;
26628     }
26629 
26630   tree call = error_mark_node;
26631 
26632   /* If this is list-initialization and the class has a list constructor, first
26633      try deducing from the list as a single argument, as [over.match.list].  */
26634   tree list_cands = NULL_TREE;
26635   if (try_list_ctor && cands)
26636     for (lkp_iterator iter (cands); iter; ++iter)
26637       {
26638 	tree dg = *iter;
26639 	if (is_list_ctor (dg))
26640 	  list_cands = lookup_add (dg, list_cands);
26641       }
26642   if (list_cands)
26643     {
26644       ++cp_unevaluated_operand;
26645       call = build_new_function_call (list_cands, &args, tf_decltype);
26646       --cp_unevaluated_operand;
26647 
26648       if (call == error_mark_node)
26649 	{
26650 	  /* That didn't work, now try treating the list as a sequence of
26651 	     arguments.  */
26652 	  release_tree_vector (args);
26653 	  args = make_tree_vector_from_ctor (init);
26654 	}
26655     }
26656 
26657   /* Maybe generate an implicit deduction guide.  */
26658   if (call == error_mark_node && args->length () < 2)
26659     {
26660       tree gtype = NULL_TREE;
26661 
26662       if (args->length () == 1)
26663 	/* Generate a copy guide.  */
26664 	gtype = build_reference_type (type);
26665       else if (!saw_ctor)
26666 	/* Generate a default guide.  */
26667 	gtype = type;
26668 
26669       if (gtype)
26670 	{
26671 	  tree guide = build_deduction_guide (gtype, outer_args, complain);
26672 	  if (guide == error_mark_node)
26673 	    return error_mark_node;
26674 	  cands = lookup_add (guide, cands);
26675 	}
26676     }
26677 
26678   if (elided && !cands)
26679     {
26680       error ("cannot deduce template arguments for copy-initialization"
26681 	     " of %qT, as it has no non-explicit deduction guides or "
26682 	     "user-declared constructors", type);
26683       return error_mark_node;
26684     }
26685   else if (!cands && call == error_mark_node)
26686     {
26687       error ("cannot deduce template arguments of %qT, as it has no viable "
26688 	     "deduction guides", type);
26689       return error_mark_node;
26690     }
26691 
26692   if (call == error_mark_node)
26693     {
26694       ++cp_unevaluated_operand;
26695       call = build_new_function_call (cands, &args, tf_decltype);
26696       --cp_unevaluated_operand;
26697     }
26698 
26699   if (call == error_mark_node && (complain & tf_warning_or_error))
26700     {
26701       error ("class template argument deduction failed:");
26702 
26703       ++cp_unevaluated_operand;
26704       call = build_new_function_call (cands, &args, complain | tf_decltype);
26705       --cp_unevaluated_operand;
26706 
26707       if (elided)
26708 	inform (input_location, "explicit deduction guides not considered "
26709 		"for copy-initialization");
26710     }
26711 
26712   release_tree_vector (args);
26713 
26714   return cp_build_qualified_type (TREE_TYPE (call), cp_type_quals (ptype));
26715 }
26716 
26717 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
26718    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.
26719    The CONTEXT determines the context in which auto deduction is performed
26720    and is used to control error diagnostics.  FLAGS are the LOOKUP_* flags.
26721    OUTER_TARGS are used during template argument deduction
26722    (context == adc_unify) to properly substitute the result, and is ignored
26723    in other contexts.
26724 
26725    For partial-concept-ids, extra args may be appended to the list of deduced
26726    template arguments prior to determining constraint satisfaction.  */
26727 
26728 tree
do_auto_deduction(tree type,tree init,tree auto_node,tsubst_flags_t complain,auto_deduction_context context,tree outer_targs,int flags)26729 do_auto_deduction (tree type, tree init, tree auto_node,
26730                    tsubst_flags_t complain, auto_deduction_context context,
26731 		   tree outer_targs, int flags)
26732 {
26733   tree targs;
26734 
26735   if (init == error_mark_node)
26736     return error_mark_node;
26737 
26738   if (init && type_dependent_expression_p (init)
26739       && context != adc_unify)
26740     /* Defining a subset of type-dependent expressions that we can deduce
26741        from ahead of time isn't worth the trouble.  */
26742     return type;
26743 
26744   /* Similarly, we can't deduce from another undeduced decl.  */
26745   if (init && undeduced_auto_decl (init))
26746     return type;
26747 
26748   if (tree tmpl = CLASS_PLACEHOLDER_TEMPLATE (auto_node))
26749     /* C++17 class template argument deduction.  */
26750     return do_class_deduction (type, tmpl, init, flags, complain);
26751 
26752   if (init == NULL_TREE || TREE_TYPE (init) == NULL_TREE)
26753     /* Nothing we can do with this, even in deduction context.  */
26754     return type;
26755 
26756   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
26757      with either a new invented type template parameter U or, if the
26758      initializer is a braced-init-list (8.5.4), with
26759      std::initializer_list<U>.  */
26760   if (BRACE_ENCLOSED_INITIALIZER_P (init))
26761     {
26762       if (!DIRECT_LIST_INIT_P (init))
26763 	type = listify_autos (type, auto_node);
26764       else if (CONSTRUCTOR_NELTS (init) == 1)
26765 	init = CONSTRUCTOR_ELT (init, 0)->value;
26766       else
26767 	{
26768           if (complain & tf_warning_or_error)
26769             {
26770 	      if (permerror (input_location, "direct-list-initialization of "
26771 			     "%<auto%> requires exactly one element"))
26772 	        inform (input_location,
26773 		        "for deduction to %<std::initializer_list%>, use copy-"
26774 		        "list-initialization (i.e. add %<=%> before the %<{%>)");
26775             }
26776 	  type = listify_autos (type, auto_node);
26777 	}
26778     }
26779 
26780   if (type == error_mark_node)
26781     return error_mark_node;
26782 
26783   init = resolve_nondeduced_context (init, complain);
26784 
26785   if (context == adc_decomp_type
26786       && auto_node == type
26787       && init != error_mark_node
26788       && TREE_CODE (TREE_TYPE (init)) == ARRAY_TYPE)
26789     /* [dcl.decomp]/1 - if decomposition declaration has no ref-qualifiers
26790        and initializer has array type, deduce cv-qualified array type.  */
26791     return cp_build_qualified_type_real (TREE_TYPE (init), TYPE_QUALS (type),
26792 					 complain);
26793   else if (AUTO_IS_DECLTYPE (auto_node))
26794     {
26795       bool id = (DECL_P (init)
26796 		 || ((TREE_CODE (init) == COMPONENT_REF
26797 		      || TREE_CODE (init) == SCOPE_REF)
26798 		     && !REF_PARENTHESIZED_P (init)));
26799       targs = make_tree_vec (1);
26800       TREE_VEC_ELT (targs, 0)
26801 	= finish_decltype_type (init, id, tf_warning_or_error);
26802       if (type != auto_node)
26803 	{
26804           if (complain & tf_error)
26805 	    error ("%qT as type rather than plain %<decltype(auto)%>", type);
26806 	  return error_mark_node;
26807 	}
26808     }
26809   else
26810     {
26811       tree parms = build_tree_list (NULL_TREE, type);
26812       tree tparms;
26813 
26814       if (flag_concepts)
26815 	tparms = extract_autos (type);
26816       else
26817 	{
26818 	  tparms = make_tree_vec (1);
26819 	  TREE_VEC_ELT (tparms, 0)
26820 	    = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
26821 	}
26822 
26823       targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
26824       int val = type_unification_real (tparms, targs, parms, &init, 1, 0,
26825 				       DEDUCE_CALL, LOOKUP_NORMAL,
26826 				       NULL, /*explain_p=*/false);
26827       if (val > 0)
26828 	{
26829 	  if (processing_template_decl)
26830 	    /* Try again at instantiation time.  */
26831 	    return type;
26832 	  if (type && type != error_mark_node
26833 	      && (complain & tf_error))
26834 	    /* If type is error_mark_node a diagnostic must have been
26835 	       emitted by now.  Also, having a mention to '<type error>'
26836 	       in the diagnostic is not really useful to the user.  */
26837 	    {
26838 	      if (cfun && auto_node == current_function_auto_return_pattern
26839 		  && LAMBDA_FUNCTION_P (current_function_decl))
26840 		error ("unable to deduce lambda return type from %qE", init);
26841 	      else
26842 		error ("unable to deduce %qT from %qE", type, init);
26843 	      type_unification_real (tparms, targs, parms, &init, 1, 0,
26844 				     DEDUCE_CALL, LOOKUP_NORMAL,
26845 				     NULL, /*explain_p=*/true);
26846 	    }
26847 	  return error_mark_node;
26848 	}
26849     }
26850 
26851   /* Check any placeholder constraints against the deduced type. */
26852   if (flag_concepts && !processing_template_decl)
26853     if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (auto_node))
26854       {
26855         /* Use the deduced type to check the associated constraints. If we
26856            have a partial-concept-id, rebuild the argument list so that
26857            we check using the extra arguments. */
26858         gcc_assert (TREE_CODE (constr) == CHECK_CONSTR);
26859         tree cargs = CHECK_CONSTR_ARGS (constr);
26860         if (TREE_VEC_LENGTH (cargs) > 1)
26861           {
26862             cargs = copy_node (cargs);
26863             TREE_VEC_ELT (cargs, 0) = TREE_VEC_ELT (targs, 0);
26864           }
26865         else
26866           cargs = targs;
26867         if (!constraints_satisfied_p (constr, cargs))
26868           {
26869             if (complain & tf_warning_or_error)
26870               {
26871                 switch (context)
26872                   {
26873                   case adc_unspecified:
26874 		  case adc_unify:
26875                     error("placeholder constraints not satisfied");
26876                     break;
26877                   case adc_variable_type:
26878 		  case adc_decomp_type:
26879                     error ("deduced initializer does not satisfy "
26880                            "placeholder constraints");
26881                     break;
26882                   case adc_return_type:
26883                     error ("deduced return type does not satisfy "
26884                            "placeholder constraints");
26885                     break;
26886                   case adc_requirement:
26887 		    error ("deduced expression type does not satisfy "
26888                            "placeholder constraints");
26889                     break;
26890                   }
26891                 diagnose_constraints (input_location, constr, targs);
26892               }
26893             return error_mark_node;
26894           }
26895       }
26896 
26897   if (processing_template_decl && context != adc_unify)
26898     outer_targs = current_template_args ();
26899   targs = add_to_template_args (outer_targs, targs);
26900   return tsubst (type, targs, complain, NULL_TREE);
26901 }
26902 
26903 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
26904    result.  */
26905 
26906 tree
splice_late_return_type(tree type,tree late_return_type)26907 splice_late_return_type (tree type, tree late_return_type)
26908 {
26909   if (is_auto (type))
26910     {
26911       if (late_return_type)
26912 	return late_return_type;
26913 
26914       tree idx = get_template_parm_index (type);
26915       if (TEMPLATE_PARM_LEVEL (idx) <= processing_template_decl)
26916 	/* In an abbreviated function template we didn't know we were dealing
26917 	   with a function template when we saw the auto return type, so update
26918 	   it to have the correct level.  */
26919 	return make_auto_1 (TYPE_IDENTIFIER (type), true);
26920     }
26921   return type;
26922 }
26923 
26924 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto' or
26925    'decltype(auto)' or a deduced class template.  */
26926 
26927 bool
is_auto(const_tree type)26928 is_auto (const_tree type)
26929 {
26930   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
26931       && (TYPE_IDENTIFIER (type) == auto_identifier
26932 	  || TYPE_IDENTIFIER (type) == decltype_auto_identifier
26933 	  || CLASS_PLACEHOLDER_TEMPLATE (type)))
26934     return true;
26935   else
26936     return false;
26937 }
26938 
26939 /* for_each_template_parm callback for type_uses_auto.  */
26940 
26941 int
is_auto_r(tree tp,void *)26942 is_auto_r (tree tp, void */*data*/)
26943 {
26944   return is_auto (tp);
26945 }
26946 
26947 /* Returns the TEMPLATE_TYPE_PARM in TYPE representing `auto' iff TYPE contains
26948    a use of `auto'.  Returns NULL_TREE otherwise.  */
26949 
26950 tree
type_uses_auto(tree type)26951 type_uses_auto (tree type)
26952 {
26953   if (type == NULL_TREE)
26954     return NULL_TREE;
26955   else if (flag_concepts)
26956     {
26957       /* The Concepts TS allows multiple autos in one type-specifier; just
26958 	 return the first one we find, do_auto_deduction will collect all of
26959 	 them.  */
26960       if (uses_template_parms (type))
26961 	return for_each_template_parm (type, is_auto_r, /*data*/NULL,
26962 				       /*visited*/NULL, /*nondeduced*/false);
26963       else
26964 	return NULL_TREE;
26965     }
26966   else
26967     return find_type_usage (type, is_auto);
26968 }
26969 
26970 /* Report ill-formed occurrences of auto types in ARGUMENTS.  If
26971    concepts are enabled, auto is acceptable in template arguments, but
26972    only when TEMPL identifies a template class.  Return TRUE if any
26973    such errors were reported.  */
26974 
26975 bool
check_auto_in_tmpl_args(tree tmpl,tree args)26976 check_auto_in_tmpl_args (tree tmpl, tree args)
26977 {
26978   /* If there were previous errors, nevermind.  */
26979   if (!args || TREE_CODE (args) != TREE_VEC)
26980     return false;
26981 
26982   /* If TMPL is an identifier, we're parsing and we can't tell yet
26983      whether TMPL is supposed to be a type, a function or a variable.
26984      We'll only be able to tell during template substitution, so we
26985      expect to be called again then.  If concepts are enabled and we
26986      know we have a type, we're ok.  */
26987   if (flag_concepts
26988       && (identifier_p (tmpl)
26989 	  || (DECL_P (tmpl)
26990 	      &&  (DECL_TYPE_TEMPLATE_P (tmpl)
26991 		   || DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)))))
26992     return false;
26993 
26994   /* Quickly search for any occurrences of auto; usually there won't
26995      be any, and then we'll avoid allocating the vector.  */
26996   if (!type_uses_auto (args))
26997     return false;
26998 
26999   bool errors = false;
27000 
27001   tree vec = extract_autos (args);
27002   for (int i = 0; i < TREE_VEC_LENGTH (vec); i++)
27003     {
27004       tree xauto = TREE_VALUE (TREE_VEC_ELT (vec, i));
27005       error_at (DECL_SOURCE_LOCATION (xauto),
27006 		"invalid use of %qT in template argument", xauto);
27007       errors = true;
27008     }
27009 
27010   return errors;
27011 }
27012 
27013 /* For a given template T, return the vector of typedefs referenced
27014    in T for which access check is needed at T instantiation time.
27015    T is either  a FUNCTION_DECL or a RECORD_TYPE.
27016    Those typedefs were added to T by the function
27017    append_type_to_template_for_access_check.  */
27018 
27019 vec<qualified_typedef_usage_t, va_gc> *
get_types_needing_access_check(tree t)27020 get_types_needing_access_check (tree t)
27021 {
27022   tree ti;
27023   vec<qualified_typedef_usage_t, va_gc> *result = NULL;
27024 
27025   if (!t || t == error_mark_node)
27026     return NULL;
27027 
27028   if (!(ti = get_template_info (t)))
27029     return NULL;
27030 
27031   if (CLASS_TYPE_P (t)
27032       || TREE_CODE (t) == FUNCTION_DECL)
27033     {
27034       if (!TI_TEMPLATE (ti))
27035 	return NULL;
27036 
27037       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
27038     }
27039 
27040   return result;
27041 }
27042 
27043 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
27044    tied to T. That list of typedefs will be access checked at
27045    T instantiation time.
27046    T is either a FUNCTION_DECL or a RECORD_TYPE.
27047    TYPE_DECL is a TYPE_DECL node representing a typedef.
27048    SCOPE is the scope through which TYPE_DECL is accessed.
27049    LOCATION is the location of the usage point of TYPE_DECL.
27050 
27051    This function is a subroutine of
27052    append_type_to_template_for_access_check.  */
27053 
27054 static void
append_type_to_template_for_access_check_1(tree t,tree type_decl,tree scope,location_t location)27055 append_type_to_template_for_access_check_1 (tree t,
27056 					    tree type_decl,
27057 					    tree scope,
27058 					    location_t location)
27059 {
27060   qualified_typedef_usage_t typedef_usage;
27061   tree ti;
27062 
27063   if (!t || t == error_mark_node)
27064     return;
27065 
27066   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
27067 	       || CLASS_TYPE_P (t))
27068 	      && type_decl
27069 	      && TREE_CODE (type_decl) == TYPE_DECL
27070 	      && scope);
27071 
27072   if (!(ti = get_template_info (t)))
27073     return;
27074 
27075   gcc_assert (TI_TEMPLATE (ti));
27076 
27077   typedef_usage.typedef_decl = type_decl;
27078   typedef_usage.context = scope;
27079   typedef_usage.locus = location;
27080 
27081   vec_safe_push (TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti), typedef_usage);
27082 }
27083 
27084 /* Append TYPE_DECL to the template TEMPL.
27085    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
27086    At TEMPL instanciation time, TYPE_DECL will be checked to see
27087    if it can be accessed through SCOPE.
27088    LOCATION is the location of the usage point of TYPE_DECL.
27089 
27090    e.g. consider the following code snippet:
27091 
27092      class C
27093      {
27094        typedef int myint;
27095      };
27096 
27097      template<class U> struct S
27098      {
27099        C::myint mi; // <-- usage point of the typedef C::myint
27100      };
27101 
27102      S<char> s;
27103 
27104    At S<char> instantiation time, we need to check the access of C::myint
27105    In other words, we need to check the access of the myint typedef through
27106    the C scope. For that purpose, this function will add the myint typedef
27107    and the scope C through which its being accessed to a list of typedefs
27108    tied to the template S. That list will be walked at template instantiation
27109    time and access check performed on each typedefs it contains.
27110    Note that this particular code snippet should yield an error because
27111    myint is private to C.  */
27112 
27113 void
append_type_to_template_for_access_check(tree templ,tree type_decl,tree scope,location_t location)27114 append_type_to_template_for_access_check (tree templ,
27115                                           tree type_decl,
27116 					  tree scope,
27117 					  location_t location)
27118 {
27119   qualified_typedef_usage_t *iter;
27120   unsigned i;
27121 
27122   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
27123 
27124   /* Make sure we don't append the type to the template twice.  */
27125   FOR_EACH_VEC_SAFE_ELT (get_types_needing_access_check (templ), i, iter)
27126     if (iter->typedef_decl == type_decl && scope == iter->context)
27127       return;
27128 
27129   append_type_to_template_for_access_check_1 (templ, type_decl,
27130 					      scope, location);
27131 }
27132 
27133 /* Convert the generic type parameters in PARM that match the types given in the
27134    range [START_IDX, END_IDX) from the current_template_parms into generic type
27135    packs.  */
27136 
27137 tree
convert_generic_types_to_packs(tree parm,int start_idx,int end_idx)27138 convert_generic_types_to_packs (tree parm, int start_idx, int end_idx)
27139 {
27140   tree current = current_template_parms;
27141   int depth = TMPL_PARMS_DEPTH (current);
27142   current = INNERMOST_TEMPLATE_PARMS (current);
27143   tree replacement = make_tree_vec (TREE_VEC_LENGTH (current));
27144 
27145   for (int i = 0; i < start_idx; ++i)
27146     TREE_VEC_ELT (replacement, i)
27147       = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
27148 
27149   for (int i = start_idx; i < end_idx; ++i)
27150     {
27151       /* Create a distinct parameter pack type from the current parm and add it
27152 	 to the replacement args to tsubst below into the generic function
27153 	 parameter.  */
27154 
27155       tree o = TREE_TYPE (TREE_VALUE
27156 			  (TREE_VEC_ELT (current, i)));
27157       tree t = copy_type (o);
27158       TEMPLATE_TYPE_PARM_INDEX (t)
27159 	= reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (o),
27160 				      o, 0, 0, tf_none);
27161       TREE_TYPE (TEMPLATE_TYPE_DECL (t)) = t;
27162       TYPE_STUB_DECL (t) = TYPE_NAME (t) = TEMPLATE_TYPE_DECL (t);
27163       TYPE_MAIN_VARIANT (t) = t;
27164       TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
27165       TYPE_CANONICAL (t) = canonical_type_parameter (t);
27166       TREE_VEC_ELT (replacement, i) = t;
27167       TREE_VALUE (TREE_VEC_ELT (current, i)) = TREE_CHAIN (t);
27168     }
27169 
27170   for (int i = end_idx, e = TREE_VEC_LENGTH (current); i < e; ++i)
27171     TREE_VEC_ELT (replacement, i)
27172       = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
27173 
27174   /* If there are more levels then build up the replacement with the outer
27175      template parms.  */
27176   if (depth > 1)
27177     replacement = add_to_template_args (template_parms_to_args
27178 					(TREE_CHAIN (current_template_parms)),
27179 					replacement);
27180 
27181   return tsubst (parm, replacement, tf_none, NULL_TREE);
27182 }
27183 
27184 /* Entries in the decl_constraint hash table. */
27185 struct GTY((for_user)) constr_entry
27186 {
27187   tree decl;
27188   tree ci;
27189 };
27190 
27191 /* Hashing function and equality for constraint entries. */
27192 struct constr_hasher : ggc_ptr_hash<constr_entry>
27193 {
hashconstr_hasher27194   static hashval_t hash (constr_entry *e)
27195   {
27196     return (hashval_t)DECL_UID (e->decl);
27197   }
27198 
equalconstr_hasher27199   static bool equal (constr_entry *e1, constr_entry *e2)
27200   {
27201     return e1->decl == e2->decl;
27202   }
27203 };
27204 
27205 /* A mapping from declarations to constraint information. Note that
27206    both templates and their underlying declarations are mapped to the
27207    same constraint information.
27208 
27209    FIXME: This is defined in pt.c because garbage collection
27210    code is not being generated for constraint.cc. */
27211 
27212 static GTY (()) hash_table<constr_hasher> *decl_constraints;
27213 
27214 /* Returns the template constraints of declaration T. If T is not
27215    constrained, return NULL_TREE. Note that T must be non-null. */
27216 
27217 tree
get_constraints(tree t)27218 get_constraints (tree t)
27219 {
27220   if (!flag_concepts)
27221     return NULL_TREE;
27222 
27223   gcc_assert (DECL_P (t));
27224   if (TREE_CODE (t) == TEMPLATE_DECL)
27225     t = DECL_TEMPLATE_RESULT (t);
27226   constr_entry elt = { t, NULL_TREE };
27227   constr_entry* found = decl_constraints->find (&elt);
27228   if (found)
27229     return found->ci;
27230   else
27231     return NULL_TREE;
27232 }
27233 
27234 /* Associate the given constraint information CI with the declaration
27235    T. If T is a template, then the constraints are associated with
27236    its underlying declaration. Don't build associations if CI is
27237    NULL_TREE.  */
27238 
27239 void
set_constraints(tree t,tree ci)27240 set_constraints (tree t, tree ci)
27241 {
27242   if (!ci)
27243     return;
27244   gcc_assert (t && flag_concepts);
27245   if (TREE_CODE (t) == TEMPLATE_DECL)
27246     t = DECL_TEMPLATE_RESULT (t);
27247   gcc_assert (!get_constraints (t));
27248   constr_entry elt = {t, ci};
27249   constr_entry** slot = decl_constraints->find_slot (&elt, INSERT);
27250   constr_entry* entry = ggc_alloc<constr_entry> ();
27251   *entry = elt;
27252   *slot = entry;
27253 }
27254 
27255 /* Remove the associated constraints of the declaration T.  */
27256 
27257 void
remove_constraints(tree t)27258 remove_constraints (tree t)
27259 {
27260   gcc_assert (DECL_P (t));
27261   if (TREE_CODE (t) == TEMPLATE_DECL)
27262     t = DECL_TEMPLATE_RESULT (t);
27263 
27264   constr_entry elt = {t, NULL_TREE};
27265   constr_entry** slot = decl_constraints->find_slot (&elt, NO_INSERT);
27266   if (slot)
27267     decl_constraints->clear_slot (slot);
27268 }
27269 
27270 /* Memoized satisfaction results for declarations. This
27271    maps the pair (constraint_info, arguments) to the result computed
27272    by constraints_satisfied_p.  */
27273 
27274 struct GTY((for_user)) constraint_sat_entry
27275 {
27276   tree ci;
27277   tree args;
27278   tree result;
27279 };
27280 
27281 /* Hashing function and equality for constraint entries. */
27282 
27283 struct constraint_sat_hasher : ggc_ptr_hash<constraint_sat_entry>
27284 {
hashconstraint_sat_hasher27285   static hashval_t hash (constraint_sat_entry *e)
27286   {
27287     hashval_t val = iterative_hash_object(e->ci, 0);
27288     return iterative_hash_template_arg (e->args, val);
27289   }
27290 
equalconstraint_sat_hasher27291   static bool equal (constraint_sat_entry *e1, constraint_sat_entry *e2)
27292   {
27293     return e1->ci == e2->ci && comp_template_args (e1->args, e2->args);
27294   }
27295 };
27296 
27297 /* Memoized satisfaction results for concept checks. */
27298 
27299 struct GTY((for_user)) concept_spec_entry
27300 {
27301   tree tmpl;
27302   tree args;
27303   tree result;
27304 };
27305 
27306 /* Hashing function and equality for constraint entries.  */
27307 
27308 struct concept_spec_hasher : ggc_ptr_hash<concept_spec_entry>
27309 {
hashconcept_spec_hasher27310   static hashval_t hash (concept_spec_entry *e)
27311   {
27312     return hash_tmpl_and_args (e->tmpl, e->args);
27313   }
27314 
equalconcept_spec_hasher27315   static bool equal (concept_spec_entry *e1, concept_spec_entry *e2)
27316   {
27317     ++comparing_specializations;
27318     bool eq = e1->tmpl == e2->tmpl && comp_template_args (e1->args, e2->args);
27319     --comparing_specializations;
27320     return eq;
27321   }
27322 };
27323 
27324 static GTY (()) hash_table<constraint_sat_hasher> *constraint_memos;
27325 static GTY (()) hash_table<concept_spec_hasher> *concept_memos;
27326 
27327 /* Search for a memoized satisfaction result. Returns one of the
27328    truth value nodes if previously memoized, or NULL_TREE otherwise.   */
27329 
27330 tree
lookup_constraint_satisfaction(tree ci,tree args)27331 lookup_constraint_satisfaction (tree ci, tree args)
27332 {
27333   constraint_sat_entry elt = { ci, args, NULL_TREE };
27334   constraint_sat_entry* found = constraint_memos->find (&elt);
27335   if (found)
27336     return found->result;
27337   else
27338     return NULL_TREE;
27339 }
27340 
27341 /* Memoize the result of a satisfication test. Returns the saved result.  */
27342 
27343 tree
memoize_constraint_satisfaction(tree ci,tree args,tree result)27344 memoize_constraint_satisfaction (tree ci, tree args, tree result)
27345 {
27346   constraint_sat_entry elt = {ci, args, result};
27347   constraint_sat_entry** slot = constraint_memos->find_slot (&elt, INSERT);
27348   constraint_sat_entry* entry = ggc_alloc<constraint_sat_entry> ();
27349   *entry = elt;
27350   *slot = entry;
27351   return result;
27352 }
27353 
27354 /* Search for a memoized satisfaction result for a concept. */
27355 
27356 tree
lookup_concept_satisfaction(tree tmpl,tree args)27357 lookup_concept_satisfaction (tree tmpl, tree args)
27358 {
27359   concept_spec_entry elt = { tmpl, args, NULL_TREE };
27360   concept_spec_entry* found = concept_memos->find (&elt);
27361   if (found)
27362     return found->result;
27363   else
27364     return NULL_TREE;
27365 }
27366 
27367 /* Memoize the result of a concept check. Returns the saved result.  */
27368 
27369 tree
memoize_concept_satisfaction(tree tmpl,tree args,tree result)27370 memoize_concept_satisfaction (tree tmpl, tree args, tree result)
27371 {
27372   concept_spec_entry elt = {tmpl, args, result};
27373   concept_spec_entry** slot = concept_memos->find_slot (&elt, INSERT);
27374   concept_spec_entry* entry = ggc_alloc<concept_spec_entry> ();
27375   *entry = elt;
27376   *slot = entry;
27377   return result;
27378 }
27379 
27380 static GTY (()) hash_table<concept_spec_hasher> *concept_expansions;
27381 
27382 /* Returns a prior concept specialization. This returns the substituted
27383    and normalized constraints defined by the concept.  */
27384 
27385 tree
get_concept_expansion(tree tmpl,tree args)27386 get_concept_expansion (tree tmpl, tree args)
27387 {
27388   concept_spec_entry elt = { tmpl, args, NULL_TREE };
27389   concept_spec_entry* found = concept_expansions->find (&elt);
27390   if (found)
27391     return found->result;
27392   else
27393     return NULL_TREE;
27394 }
27395 
27396 /* Save a concept expansion for later.  */
27397 
27398 tree
save_concept_expansion(tree tmpl,tree args,tree def)27399 save_concept_expansion (tree tmpl, tree args, tree def)
27400 {
27401   concept_spec_entry elt = {tmpl, args, def};
27402   concept_spec_entry** slot = concept_expansions->find_slot (&elt, INSERT);
27403   concept_spec_entry* entry = ggc_alloc<concept_spec_entry> ();
27404   *entry = elt;
27405   *slot = entry;
27406   return def;
27407 }
27408 
27409 static hashval_t
hash_subsumption_args(tree t1,tree t2)27410 hash_subsumption_args (tree t1, tree t2)
27411 {
27412   gcc_assert (TREE_CODE (t1) == CHECK_CONSTR);
27413   gcc_assert (TREE_CODE (t2) == CHECK_CONSTR);
27414   int val = 0;
27415   val = iterative_hash_object (CHECK_CONSTR_CONCEPT (t1), val);
27416   val = iterative_hash_template_arg (CHECK_CONSTR_ARGS (t1), val);
27417   val = iterative_hash_object (CHECK_CONSTR_CONCEPT (t2), val);
27418   val = iterative_hash_template_arg (CHECK_CONSTR_ARGS (t2), val);
27419   return val;
27420 }
27421 
27422 /* Compare the constraints of two subsumption entries.  The LEFT1 and
27423    LEFT2 arguments comprise the first subsumption pair and the RIGHT1
27424    and RIGHT2 arguments comprise the second. These are all CHECK_CONSTRs. */
27425 
27426 static bool
comp_subsumption_args(tree left1,tree left2,tree right1,tree right2)27427 comp_subsumption_args (tree left1, tree left2, tree right1, tree right2)
27428 {
27429   if (CHECK_CONSTR_CONCEPT (left1) == CHECK_CONSTR_CONCEPT (right1))
27430     if (CHECK_CONSTR_CONCEPT (left2) == CHECK_CONSTR_CONCEPT (right2))
27431       if (comp_template_args (CHECK_CONSTR_ARGS (left1),
27432                              CHECK_CONSTR_ARGS (right1)))
27433         return comp_template_args (CHECK_CONSTR_ARGS (left2),
27434                                   CHECK_CONSTR_ARGS (right2));
27435   return false;
27436 }
27437 
27438 /* Key/value pair for learning and memoizing subsumption results. This
27439    associates a pair of check constraints (including arguments) with
27440    a boolean value indicating the result.  */
27441 
27442 struct GTY((for_user)) subsumption_entry
27443 {
27444   tree t1;
27445   tree t2;
27446   bool result;
27447 };
27448 
27449 /* Hashing function and equality for constraint entries.  */
27450 
27451 struct subsumption_hasher : ggc_ptr_hash<subsumption_entry>
27452 {
hashsubsumption_hasher27453   static hashval_t hash (subsumption_entry *e)
27454   {
27455     return hash_subsumption_args (e->t1, e->t2);
27456   }
27457 
equalsubsumption_hasher27458   static bool equal (subsumption_entry *e1, subsumption_entry *e2)
27459   {
27460     ++comparing_specializations;
27461     bool eq = comp_subsumption_args(e1->t1, e1->t2, e2->t1, e2->t2);
27462     --comparing_specializations;
27463     return eq;
27464   }
27465 };
27466 
27467 static GTY (()) hash_table<subsumption_hasher> *subsumption_table;
27468 
27469 /* Search for a previously cached subsumption result. */
27470 
27471 bool*
lookup_subsumption_result(tree t1,tree t2)27472 lookup_subsumption_result (tree t1, tree t2)
27473 {
27474   subsumption_entry elt = { t1, t2, false };
27475   subsumption_entry* found = subsumption_table->find (&elt);
27476   if (found)
27477     return &found->result;
27478   else
27479     return 0;
27480 }
27481 
27482 /* Save a subsumption result. */
27483 
27484 bool
save_subsumption_result(tree t1,tree t2,bool result)27485 save_subsumption_result (tree t1, tree t2, bool result)
27486 {
27487   subsumption_entry elt = {t1, t2, result};
27488   subsumption_entry** slot = subsumption_table->find_slot (&elt, INSERT);
27489   subsumption_entry* entry = ggc_alloc<subsumption_entry> ();
27490   *entry = elt;
27491   *slot = entry;
27492   return result;
27493 }
27494 
27495 /* Set up the hash table for constraint association. */
27496 
27497 void
init_constraint_processing(void)27498 init_constraint_processing (void)
27499 {
27500   if (!flag_concepts)
27501     return;
27502 
27503   decl_constraints = hash_table<constr_hasher>::create_ggc(37);
27504   constraint_memos = hash_table<constraint_sat_hasher>::create_ggc(37);
27505   concept_memos = hash_table<concept_spec_hasher>::create_ggc(37);
27506   concept_expansions = hash_table<concept_spec_hasher>::create_ggc(37);
27507   subsumption_table = hash_table<subsumption_hasher>::create_ggc(37);
27508 }
27509 
27510 /* __integer_pack(N) in a pack expansion expands to a sequence of numbers from
27511    0..N-1.  */
27512 
27513 void
declare_integer_pack(void)27514 declare_integer_pack (void)
27515 {
27516   tree ipfn = push_library_fn (get_identifier ("__integer_pack"),
27517 			       build_function_type_list (integer_type_node,
27518 							 integer_type_node,
27519 							 NULL_TREE),
27520 			       NULL_TREE, ECF_CONST);
27521   DECL_DECLARED_CONSTEXPR_P (ipfn) = true;
27522   DECL_BUILT_IN_CLASS (ipfn) = BUILT_IN_FRONTEND;
27523 }
27524 
27525 /* Set up the hash tables for template instantiations.  */
27526 
27527 void
init_template_processing(void)27528 init_template_processing (void)
27529 {
27530   decl_specializations = hash_table<spec_hasher>::create_ggc (37);
27531   type_specializations = hash_table<spec_hasher>::create_ggc (37);
27532 
27533   if (cxx_dialect >= cxx11)
27534     declare_integer_pack ();
27535 }
27536 
27537 /* Print stats about the template hash tables for -fstats.  */
27538 
27539 void
print_template_statistics(void)27540 print_template_statistics (void)
27541 {
27542   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
27543 	   "%f collisions\n", (long) decl_specializations->size (),
27544 	   (long) decl_specializations->elements (),
27545 	   decl_specializations->collisions ());
27546   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
27547 	   "%f collisions\n", (long) type_specializations->size (),
27548 	   (long) type_specializations->elements (),
27549 	   type_specializations->collisions ());
27550 }
27551 
27552 #if CHECKING_P
27553 
27554 namespace selftest {
27555 
27556 /* Verify that build_non_dependent_expr () works, for various expressions,
27557    and that location wrappers don't affect the results.  */
27558 
27559 static void
test_build_non_dependent_expr()27560 test_build_non_dependent_expr ()
27561 {
27562   location_t loc = BUILTINS_LOCATION;
27563 
27564   /* Verify constants, without and with location wrappers.  */
27565   tree int_cst = build_int_cst (integer_type_node, 42);
27566   ASSERT_EQ (int_cst, build_non_dependent_expr (int_cst));
27567 
27568   tree wrapped_int_cst = maybe_wrap_with_location (int_cst, loc);
27569   ASSERT_TRUE (location_wrapper_p (wrapped_int_cst));
27570   ASSERT_EQ (wrapped_int_cst, build_non_dependent_expr (wrapped_int_cst));
27571 
27572   tree string_lit = build_string (4, "foo");
27573   TREE_TYPE (string_lit) = char_array_type_node;
27574   string_lit = fix_string_type (string_lit);
27575   ASSERT_EQ (string_lit, build_non_dependent_expr (string_lit));
27576 
27577   tree wrapped_string_lit = maybe_wrap_with_location (string_lit, loc);
27578   ASSERT_TRUE (location_wrapper_p (wrapped_string_lit));
27579   ASSERT_EQ (wrapped_string_lit,
27580 	     build_non_dependent_expr (wrapped_string_lit));
27581 }
27582 
27583 /* Verify that type_dependent_expression_p () works correctly, even
27584    in the presence of location wrapper nodes.  */
27585 
27586 static void
test_type_dependent_expression_p()27587 test_type_dependent_expression_p ()
27588 {
27589   location_t loc = BUILTINS_LOCATION;
27590 
27591   tree name = get_identifier ("foo");
27592 
27593   /* If no templates are involved, nothing is type-dependent.  */
27594   gcc_assert (!processing_template_decl);
27595   ASSERT_FALSE (type_dependent_expression_p (name));
27596 
27597   ++processing_template_decl;
27598 
27599   /* Within a template, an unresolved name is always type-dependent.  */
27600   ASSERT_TRUE (type_dependent_expression_p (name));
27601 
27602   /* Ensure it copes with NULL_TREE and errors.  */
27603   ASSERT_FALSE (type_dependent_expression_p (NULL_TREE));
27604   ASSERT_FALSE (type_dependent_expression_p (error_mark_node));
27605 
27606   /* A USING_DECL in a template should be type-dependent, even if wrapped
27607      with a location wrapper (PR c++/83799).  */
27608   tree using_decl = build_lang_decl (USING_DECL, name, NULL_TREE);
27609   TREE_TYPE (using_decl) = integer_type_node;
27610   ASSERT_TRUE (type_dependent_expression_p (using_decl));
27611   tree wrapped_using_decl = maybe_wrap_with_location (using_decl, loc);
27612   ASSERT_TRUE (location_wrapper_p (wrapped_using_decl));
27613   ASSERT_TRUE (type_dependent_expression_p (wrapped_using_decl));
27614 
27615   --processing_template_decl;
27616 }
27617 
27618 /* Run all of the selftests within this file.  */
27619 
27620 void
cp_pt_c_tests()27621 cp_pt_c_tests ()
27622 {
27623   test_build_non_dependent_expr ();
27624   test_type_dependent_expression_p ();
27625 }
27626 
27627 } // namespace selftest
27628 
27629 #endif /* #if CHECKING_P */
27630 
27631 #include "gt-cp-pt.h"
27632