1 /* Handle parameterized types (templates) for GNU -*- C++ -*-.
2    Copyright (C) 1992-2016 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 
44 /* The type of functions taking a tree, and some additional data, and
45    returning an int.  */
46 typedef int (*tree_fn_t) (tree, void*);
47 
48 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
49    instantiations have been deferred, either because their definitions
50    were not yet available, or because we were putting off doing the work.  */
51 struct GTY ((chain_next ("%h.next"))) pending_template {
52   struct pending_template *next;
53   struct tinst_level *tinst;
54 };
55 
56 static GTY(()) struct pending_template *pending_templates;
57 static GTY(()) struct pending_template *last_pending_template;
58 
59 int processing_template_parmlist;
60 static int template_header_count;
61 
62 static GTY(()) tree saved_trees;
63 static vec<int> inline_parm_levels;
64 
65 static GTY(()) struct tinst_level *current_tinst_level;
66 
67 static GTY(()) tree saved_access_scope;
68 
69 /* Live only within one (recursive) call to tsubst_expr.  We use
70    this to pass the statement expression node from the STMT_EXPR
71    to the EXPR_STMT that is its result.  */
72 static tree cur_stmt_expr;
73 
74 // -------------------------------------------------------------------------- //
75 // Local Specialization Stack
76 //
77 // Implementation of the RAII helper for creating new local
78 // specializations.
local_specialization_stack()79 local_specialization_stack::local_specialization_stack ()
80   : saved (local_specializations)
81 {
82   local_specializations = new hash_map<tree, tree>;
83 }
84 
~local_specialization_stack()85 local_specialization_stack::~local_specialization_stack ()
86 {
87   delete local_specializations;
88   local_specializations = saved;
89 }
90 
91 /* True if we've recursed into fn_type_unification too many times.  */
92 static bool excessive_deduction_depth;
93 
94 struct GTY((for_user)) spec_entry
95 {
96   tree tmpl;
97   tree args;
98   tree spec;
99 };
100 
101 struct spec_hasher : ggc_ptr_hash<spec_entry>
102 {
103   static hashval_t hash (spec_entry *);
104   static bool equal (spec_entry *, spec_entry *);
105 };
106 
107 static GTY (()) hash_table<spec_hasher> *decl_specializations;
108 
109 static GTY (()) hash_table<spec_hasher> *type_specializations;
110 
111 /* Contains canonical template parameter types. The vector is indexed by
112    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
113    TREE_LIST, whose TREE_VALUEs contain the canonical template
114    parameters of various types and levels.  */
115 static GTY(()) vec<tree, va_gc> *canonical_template_parms;
116 
117 #define UNIFY_ALLOW_NONE 0
118 #define UNIFY_ALLOW_MORE_CV_QUAL 1
119 #define UNIFY_ALLOW_LESS_CV_QUAL 2
120 #define UNIFY_ALLOW_DERIVED 4
121 #define UNIFY_ALLOW_INTEGER 8
122 #define UNIFY_ALLOW_OUTER_LEVEL 16
123 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
124 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
125 
126 enum template_base_result {
127   tbr_incomplete_type,
128   tbr_ambiguous_baseclass,
129   tbr_success
130 };
131 
132 static void push_access_scope (tree);
133 static void pop_access_scope (tree);
134 static bool resolve_overloaded_unification (tree, tree, tree, tree,
135 					    unification_kind_t, int,
136 					    bool);
137 static int try_one_overload (tree, tree, tree, tree, tree,
138 			     unification_kind_t, int, bool, bool);
139 static int unify (tree, tree, tree, tree, int, bool);
140 static void add_pending_template (tree);
141 static tree reopen_tinst_level (struct tinst_level *);
142 static tree tsubst_initializer_list (tree, tree);
143 static tree get_partial_spec_bindings (tree, tree, tree, tree);
144 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
145 				   bool, bool);
146 static tree coerce_innermost_template_parms (tree, tree, tree, tsubst_flags_t,
147 					      bool, bool);
148 static void tsubst_enum	(tree, tree, tree);
149 static tree add_to_template_args (tree, tree);
150 static tree add_outermost_template_args (tree, tree);
151 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
152 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
153 					     tree);
154 static int type_unification_real (tree, tree, tree, const tree *,
155 				  unsigned int, int, unification_kind_t, int,
156 				  vec<deferred_access_check, va_gc> **,
157 				  bool);
158 static void note_template_header (int);
159 static tree convert_nontype_argument_function (tree, tree, tsubst_flags_t);
160 static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
161 static tree convert_template_argument (tree, tree, tree,
162 				       tsubst_flags_t, int, tree);
163 static tree for_each_template_parm (tree, tree_fn_t, void*,
164 				    hash_set<tree> *, bool);
165 static tree expand_template_argument_pack (tree);
166 static tree build_template_parm_index (int, int, int, tree, tree);
167 static bool inline_needs_template_parms (tree, bool);
168 static void push_inline_template_parms_recursive (tree, int);
169 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
170 static int mark_template_parm (tree, void *);
171 static int template_parm_this_level_p (tree, void *);
172 static tree tsubst_friend_function (tree, tree);
173 static tree tsubst_friend_class (tree, tree);
174 static int can_complete_type_without_circularity (tree);
175 static tree get_bindings (tree, tree, tree, bool);
176 static int template_decl_level (tree);
177 static int check_cv_quals_for_unify (int, tree, tree);
178 static void template_parm_level_and_index (tree, int*, int*);
179 static int unify_pack_expansion (tree, tree, tree,
180 				 tree, unification_kind_t, bool, bool);
181 static tree copy_template_args (tree);
182 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
183 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
184 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
185 static tree most_specialized_partial_spec (tree, tsubst_flags_t);
186 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
187 static tree tsubst_arg_types (tree, tree, tree, tsubst_flags_t, tree);
188 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
189 static bool check_specialization_scope (void);
190 static tree process_partial_specialization (tree);
191 static void set_current_access_from_decl (tree);
192 static enum template_base_result get_template_base (tree, tree, tree, tree,
193 						    bool , tree *);
194 static tree try_class_unification (tree, tree, tree, tree, bool);
195 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
196 					   tree, tree);
197 static bool template_template_parm_bindings_ok_p (tree, tree);
198 static void tsubst_default_arguments (tree, tsubst_flags_t);
199 static tree for_each_template_parm_r (tree *, int *, void *);
200 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
201 static void copy_default_args_to_explicit_spec (tree);
202 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
203 static bool dependent_template_arg_p (tree);
204 static bool any_template_arguments_need_structural_equality_p (tree);
205 static bool dependent_type_p_r (tree);
206 static tree tsubst_copy	(tree, tree, tsubst_flags_t, tree);
207 static tree tsubst_decl (tree, tree, tsubst_flags_t);
208 static void perform_typedefs_access_check (tree tmpl, tree targs);
209 static void append_type_to_template_for_access_check_1 (tree, tree, tree,
210 							location_t);
211 static tree listify (tree);
212 static tree listify_autos (tree, tree);
213 static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
214 static tree instantiate_alias_template (tree, tree, tsubst_flags_t);
215 static bool complex_alias_template_p (const_tree tmpl);
216 static tree tsubst_attributes (tree, tree, tsubst_flags_t, tree);
217 
218 /* Make the current scope suitable for access checking when we are
219    processing T.  T can be FUNCTION_DECL for instantiated function
220    template, VAR_DECL for static member variable, or TYPE_DECL for
221    alias template (needed by instantiate_decl).  */
222 
223 static void
push_access_scope(tree t)224 push_access_scope (tree t)
225 {
226   gcc_assert (VAR_OR_FUNCTION_DECL_P (t)
227 	      || TREE_CODE (t) == TYPE_DECL);
228 
229   if (DECL_FRIEND_CONTEXT (t))
230     push_nested_class (DECL_FRIEND_CONTEXT (t));
231   else if (DECL_CLASS_SCOPE_P (t))
232     push_nested_class (DECL_CONTEXT (t));
233   else
234     push_to_top_level ();
235 
236   if (TREE_CODE (t) == FUNCTION_DECL)
237     {
238       saved_access_scope = tree_cons
239 	(NULL_TREE, current_function_decl, saved_access_scope);
240       current_function_decl = t;
241     }
242 }
243 
244 /* Restore the scope set up by push_access_scope.  T is the node we
245    are processing.  */
246 
247 static void
pop_access_scope(tree t)248 pop_access_scope (tree t)
249 {
250   if (TREE_CODE (t) == FUNCTION_DECL)
251     {
252       current_function_decl = TREE_VALUE (saved_access_scope);
253       saved_access_scope = TREE_CHAIN (saved_access_scope);
254     }
255 
256   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
257     pop_nested_class ();
258   else
259     pop_from_top_level ();
260 }
261 
262 /* Do any processing required when DECL (a member template
263    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
264    to DECL, unless it is a specialization, in which case the DECL
265    itself is returned.  */
266 
267 tree
finish_member_template_decl(tree decl)268 finish_member_template_decl (tree decl)
269 {
270   if (decl == error_mark_node)
271     return error_mark_node;
272 
273   gcc_assert (DECL_P (decl));
274 
275   if (TREE_CODE (decl) == TYPE_DECL)
276     {
277       tree type;
278 
279       type = TREE_TYPE (decl);
280       if (type == error_mark_node)
281 	return error_mark_node;
282       if (MAYBE_CLASS_TYPE_P (type)
283 	  && CLASSTYPE_TEMPLATE_INFO (type)
284 	  && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
285 	{
286 	  tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
287 	  check_member_template (tmpl);
288 	  return tmpl;
289 	}
290       return NULL_TREE;
291     }
292   else if (TREE_CODE (decl) == FIELD_DECL)
293     error ("data member %qD cannot be a member template", decl);
294   else if (DECL_TEMPLATE_INFO (decl))
295     {
296       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
297 	{
298 	  check_member_template (DECL_TI_TEMPLATE (decl));
299 	  return DECL_TI_TEMPLATE (decl);
300 	}
301       else
302 	return decl;
303     }
304   else
305     error ("invalid member template declaration %qD", decl);
306 
307   return error_mark_node;
308 }
309 
310 /* Create a template info node.  */
311 
312 tree
build_template_info(tree template_decl,tree template_args)313 build_template_info (tree template_decl, tree template_args)
314 {
315   tree result = make_node (TEMPLATE_INFO);
316   TI_TEMPLATE (result) = template_decl;
317   TI_ARGS (result) = template_args;
318   return result;
319 }
320 
321 /* Return the template info node corresponding to T, whatever T is.  */
322 
323 tree
get_template_info(const_tree t)324 get_template_info (const_tree t)
325 {
326   tree tinfo = NULL_TREE;
327 
328   if (!t || t == error_mark_node)
329     return NULL;
330 
331   if (TREE_CODE (t) == NAMESPACE_DECL
332       || TREE_CODE (t) == PARM_DECL)
333     return NULL;
334 
335   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
336     tinfo = DECL_TEMPLATE_INFO (t);
337 
338   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
339     t = TREE_TYPE (t);
340 
341   if (OVERLOAD_TYPE_P (t))
342     tinfo = TYPE_TEMPLATE_INFO (t);
343   else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
344     tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
345 
346   return tinfo;
347 }
348 
349 /* Returns the template nesting level of the indicated class TYPE.
350 
351    For example, in:
352      template <class T>
353      struct A
354      {
355        template <class U>
356        struct B {};
357      };
358 
359    A<T>::B<U> has depth two, while A<T> has depth one.
360    Both A<T>::B<int> and A<int>::B<U> have depth one, if
361    they are instantiations, not specializations.
362 
363    This function is guaranteed to return 0 if passed NULL_TREE so
364    that, for example, `template_class_depth (current_class_type)' is
365    always safe.  */
366 
367 int
template_class_depth(tree type)368 template_class_depth (tree type)
369 {
370   int depth;
371 
372   for (depth = 0; type && TREE_CODE (type) != NAMESPACE_DECL; )
373     {
374       tree tinfo = get_template_info (type);
375 
376       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
377 	  && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
378 	++depth;
379 
380       if (DECL_P (type))
381 	type = CP_DECL_CONTEXT (type);
382       else if (LAMBDA_TYPE_P (type))
383 	type = LAMBDA_TYPE_EXTRA_SCOPE (type);
384       else
385 	type = CP_TYPE_CONTEXT (type);
386     }
387 
388   return depth;
389 }
390 
391 /* Subroutine of maybe_begin_member_template_processing.
392    Returns true if processing DECL needs us to push template parms.  */
393 
394 static bool
inline_needs_template_parms(tree decl,bool nsdmi)395 inline_needs_template_parms (tree decl, bool nsdmi)
396 {
397   if (!decl || (!nsdmi && ! DECL_TEMPLATE_INFO (decl)))
398     return false;
399 
400   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
401 	  > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
402 }
403 
404 /* Subroutine of maybe_begin_member_template_processing.
405    Push the template parms in PARMS, starting from LEVELS steps into the
406    chain, and ending at the beginning, since template parms are listed
407    innermost first.  */
408 
409 static void
push_inline_template_parms_recursive(tree parmlist,int levels)410 push_inline_template_parms_recursive (tree parmlist, int levels)
411 {
412   tree parms = TREE_VALUE (parmlist);
413   int i;
414 
415   if (levels > 1)
416     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
417 
418   ++processing_template_decl;
419   current_template_parms
420     = tree_cons (size_int (processing_template_decl),
421 		 parms, current_template_parms);
422   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
423 
424   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
425 	       NULL);
426   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
427     {
428       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
429 
430       if (error_operand_p (parm))
431 	continue;
432 
433       gcc_assert (DECL_P (parm));
434 
435       switch (TREE_CODE (parm))
436 	{
437 	case TYPE_DECL:
438 	case TEMPLATE_DECL:
439 	  pushdecl (parm);
440 	  break;
441 
442 	case PARM_DECL:
443 	  /* Push the CONST_DECL.  */
444 	  pushdecl (TEMPLATE_PARM_DECL (DECL_INITIAL (parm)));
445 	  break;
446 
447 	default:
448 	  gcc_unreachable ();
449 	}
450     }
451 }
452 
453 /* Restore the template parameter context for a member template, a
454    friend template defined in a class definition, or a non-template
455    member of template class.  */
456 
457 void
maybe_begin_member_template_processing(tree decl)458 maybe_begin_member_template_processing (tree decl)
459 {
460   tree parms;
461   int levels = 0;
462   bool nsdmi = TREE_CODE (decl) == FIELD_DECL;
463 
464   if (nsdmi)
465     {
466       tree ctx = DECL_CONTEXT (decl);
467       decl = (CLASSTYPE_TEMPLATE_INFO (ctx)
468 	      /* Disregard full specializations (c++/60999).  */
469 	      && uses_template_parms (ctx)
470 	      ? CLASSTYPE_TI_TEMPLATE (ctx) : NULL_TREE);
471     }
472 
473   if (inline_needs_template_parms (decl, nsdmi))
474     {
475       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
476       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
477 
478       if (DECL_TEMPLATE_SPECIALIZATION (decl))
479 	{
480 	  --levels;
481 	  parms = TREE_CHAIN (parms);
482 	}
483 
484       push_inline_template_parms_recursive (parms, levels);
485     }
486 
487   /* Remember how many levels of template parameters we pushed so that
488      we can pop them later.  */
489   inline_parm_levels.safe_push (levels);
490 }
491 
492 /* Undo the effects of maybe_begin_member_template_processing.  */
493 
494 void
maybe_end_member_template_processing(void)495 maybe_end_member_template_processing (void)
496 {
497   int i;
498   int last;
499 
500   if (inline_parm_levels.length () == 0)
501     return;
502 
503   last = inline_parm_levels.pop ();
504   for (i = 0; i < last; ++i)
505     {
506       --processing_template_decl;
507       current_template_parms = TREE_CHAIN (current_template_parms);
508       poplevel (0, 0, 0);
509     }
510 }
511 
512 /* Return a new template argument vector which contains all of ARGS,
513    but has as its innermost set of arguments the EXTRA_ARGS.  */
514 
515 static tree
add_to_template_args(tree args,tree extra_args)516 add_to_template_args (tree args, tree extra_args)
517 {
518   tree new_args;
519   int extra_depth;
520   int i;
521   int j;
522 
523   if (args == NULL_TREE || extra_args == error_mark_node)
524     return extra_args;
525 
526   extra_depth = TMPL_ARGS_DEPTH (extra_args);
527   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
528 
529   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
530     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
531 
532   for (j = 1; j <= extra_depth; ++j, ++i)
533     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
534 
535   return new_args;
536 }
537 
538 /* Like add_to_template_args, but only the outermost ARGS are added to
539    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
540    (EXTRA_ARGS) levels are added.  This function is used to combine
541    the template arguments from a partial instantiation with the
542    template arguments used to attain the full instantiation from the
543    partial instantiation.  */
544 
545 static tree
add_outermost_template_args(tree args,tree extra_args)546 add_outermost_template_args (tree args, tree extra_args)
547 {
548   tree new_args;
549 
550   /* If there are more levels of EXTRA_ARGS than there are ARGS,
551      something very fishy is going on.  */
552   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
553 
554   /* If *all* the new arguments will be the EXTRA_ARGS, just return
555      them.  */
556   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
557     return extra_args;
558 
559   /* For the moment, we make ARGS look like it contains fewer levels.  */
560   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
561 
562   new_args = add_to_template_args (args, extra_args);
563 
564   /* Now, we restore ARGS to its full dimensions.  */
565   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
566 
567   return new_args;
568 }
569 
570 /* Return the N levels of innermost template arguments from the ARGS.  */
571 
572 tree
get_innermost_template_args(tree args,int n)573 get_innermost_template_args (tree args, int n)
574 {
575   tree new_args;
576   int extra_levels;
577   int i;
578 
579   gcc_assert (n >= 0);
580 
581   /* If N is 1, just return the innermost set of template arguments.  */
582   if (n == 1)
583     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
584 
585   /* If we're not removing anything, just return the arguments we were
586      given.  */
587   extra_levels = TMPL_ARGS_DEPTH (args) - n;
588   gcc_assert (extra_levels >= 0);
589   if (extra_levels == 0)
590     return args;
591 
592   /* Make a new set of arguments, not containing the outer arguments.  */
593   new_args = make_tree_vec (n);
594   for (i = 1; i <= n; ++i)
595     SET_TMPL_ARGS_LEVEL (new_args, i,
596 			 TMPL_ARGS_LEVEL (args, i + extra_levels));
597 
598   return new_args;
599 }
600 
601 /* The inverse of get_innermost_template_args: Return all but the innermost
602    EXTRA_LEVELS levels of template arguments from the ARGS.  */
603 
604 static tree
strip_innermost_template_args(tree args,int extra_levels)605 strip_innermost_template_args (tree args, int extra_levels)
606 {
607   tree new_args;
608   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
609   int i;
610 
611   gcc_assert (n >= 0);
612 
613   /* If N is 1, just return the outermost set of template arguments.  */
614   if (n == 1)
615     return TMPL_ARGS_LEVEL (args, 1);
616 
617   /* If we're not removing anything, just return the arguments we were
618      given.  */
619   gcc_assert (extra_levels >= 0);
620   if (extra_levels == 0)
621     return args;
622 
623   /* Make a new set of arguments, not containing the inner arguments.  */
624   new_args = make_tree_vec (n);
625   for (i = 1; i <= n; ++i)
626     SET_TMPL_ARGS_LEVEL (new_args, i,
627 			 TMPL_ARGS_LEVEL (args, i));
628 
629   return new_args;
630 }
631 
632 /* We've got a template header coming up; push to a new level for storing
633    the parms.  */
634 
635 void
begin_template_parm_list(void)636 begin_template_parm_list (void)
637 {
638   /* We use a non-tag-transparent scope here, which causes pushtag to
639      put tags in this scope, rather than in the enclosing class or
640      namespace scope.  This is the right thing, since we want
641      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
642      global template class, push_template_decl handles putting the
643      TEMPLATE_DECL into top-level scope.  For a nested template class,
644      e.g.:
645 
646        template <class T> struct S1 {
647 	 template <class T> struct S2 {};
648        };
649 
650      pushtag contains special code to call pushdecl_with_scope on the
651      TEMPLATE_DECL for S2.  */
652   begin_scope (sk_template_parms, NULL);
653   ++processing_template_decl;
654   ++processing_template_parmlist;
655   note_template_header (0);
656 
657   /* Add a dummy parameter level while we process the parameter list.  */
658   current_template_parms
659     = tree_cons (size_int (processing_template_decl),
660 		 make_tree_vec (0),
661 		 current_template_parms);
662 }
663 
664 /* This routine is called when a specialization is declared.  If it is
665    invalid to declare a specialization here, an error is reported and
666    false is returned, otherwise this routine will return true.  */
667 
668 static bool
check_specialization_scope(void)669 check_specialization_scope (void)
670 {
671   tree scope = current_scope ();
672 
673   /* [temp.expl.spec]
674 
675      An explicit specialization shall be declared in the namespace of
676      which the template is a member, or, for member templates, in the
677      namespace of which the enclosing class or enclosing class
678      template is a member.  An explicit specialization of a member
679      function, member class or static data member of a class template
680      shall be declared in the namespace of which the class template
681      is a member.  */
682   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
683     {
684       error ("explicit specialization in non-namespace scope %qD", scope);
685       return false;
686     }
687 
688   /* [temp.expl.spec]
689 
690      In an explicit specialization declaration for a member of a class
691      template or a member template that appears in namespace scope,
692      the member template and some of its enclosing class templates may
693      remain unspecialized, except that the declaration shall not
694      explicitly specialize a class member template if its enclosing
695      class templates are not explicitly specialized as well.  */
696   if (current_template_parms)
697     {
698       error ("enclosing class templates are not explicitly specialized");
699       return false;
700     }
701 
702   return true;
703 }
704 
705 /* We've just seen template <>.  */
706 
707 bool
begin_specialization(void)708 begin_specialization (void)
709 {
710   begin_scope (sk_template_spec, NULL);
711   note_template_header (1);
712   return check_specialization_scope ();
713 }
714 
715 /* Called at then end of processing a declaration preceded by
716    template<>.  */
717 
718 void
end_specialization(void)719 end_specialization (void)
720 {
721   finish_scope ();
722   reset_specialization ();
723 }
724 
725 /* Any template <>'s that we have seen thus far are not referring to a
726    function specialization.  */
727 
728 void
reset_specialization(void)729 reset_specialization (void)
730 {
731   processing_specialization = 0;
732   template_header_count = 0;
733 }
734 
735 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
736    it was of the form template <>.  */
737 
738 static void
note_template_header(int specialization)739 note_template_header (int specialization)
740 {
741   processing_specialization = specialization;
742   template_header_count++;
743 }
744 
745 /* We're beginning an explicit instantiation.  */
746 
747 void
begin_explicit_instantiation(void)748 begin_explicit_instantiation (void)
749 {
750   gcc_assert (!processing_explicit_instantiation);
751   processing_explicit_instantiation = true;
752 }
753 
754 
755 void
end_explicit_instantiation(void)756 end_explicit_instantiation (void)
757 {
758   gcc_assert (processing_explicit_instantiation);
759   processing_explicit_instantiation = false;
760 }
761 
762 /* An explicit specialization or partial specialization of TMPL is being
763    declared.  Check that the namespace in which the specialization is
764    occurring is permissible.  Returns false iff it is invalid to
765    specialize TMPL in the current namespace.  */
766 
767 static bool
check_specialization_namespace(tree tmpl)768 check_specialization_namespace (tree tmpl)
769 {
770   tree tpl_ns = decl_namespace_context (tmpl);
771 
772   /* [tmpl.expl.spec]
773 
774      An explicit specialization shall be declared in the namespace of
775      which the template is a member, or, for member templates, in the
776      namespace of which the enclosing class or enclosing class
777      template is a member.  An explicit specialization of a member
778      function, member class or static data member of a class template
779      shall be declared in the namespace of which the class template is
780      a member.  */
781   if (current_scope() != DECL_CONTEXT (tmpl)
782       && !at_namespace_scope_p ())
783     {
784       error ("specialization of %qD must appear at namespace scope", tmpl);
785       return false;
786     }
787   if (is_associated_namespace (current_namespace, tpl_ns))
788     /* Same or super-using namespace.  */
789     return true;
790   else
791     {
792       permerror (input_location,
793 		 "specialization of %qD in different namespace", tmpl);
794       permerror (DECL_SOURCE_LOCATION (tmpl),
795 		 "  from definition of %q#D", tmpl);
796       return false;
797     }
798 }
799 
800 /* SPEC is an explicit instantiation.  Check that it is valid to
801    perform this explicit instantiation in the current namespace.  */
802 
803 static void
check_explicit_instantiation_namespace(tree spec)804 check_explicit_instantiation_namespace (tree spec)
805 {
806   tree ns;
807 
808   /* DR 275: An explicit instantiation shall appear in an enclosing
809      namespace of its template.  */
810   ns = decl_namespace_context (spec);
811   if (!is_ancestor (current_namespace, ns))
812     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
813 	       "(which does not enclose namespace %qD)",
814 	       spec, current_namespace, ns);
815 }
816 
817 // Returns the type of a template specialization only if that
818 // specialization needs to be defined. Otherwise (e.g., if the type has
819 // already been defined), the function returns NULL_TREE.
820 static tree
maybe_new_partial_specialization(tree type)821 maybe_new_partial_specialization (tree type)
822 {
823   // An implicit instantiation of an incomplete type implies
824   // the definition of a new class template.
825   //
826   //    template<typename T>
827   //      struct S;
828   //
829   //    template<typename T>
830   //      struct S<T*>;
831   //
832   // Here, S<T*> is an implicit instantiation of S whose type
833   // is incomplete.
834   if (CLASSTYPE_IMPLICIT_INSTANTIATION (type) && !COMPLETE_TYPE_P (type))
835     return type;
836 
837   // It can also be the case that TYPE is a completed specialization.
838   // Continuing the previous example, suppose we also declare:
839   //
840   //    template<typename T>
841   //      requires Integral<T>
842   //        struct S<T*>;
843   //
844   // Here, S<T*> refers to the specialization S<T*> defined
845   // above. However, we need to differentiate definitions because
846   // we intend to define a new partial specialization. In this case,
847   // we rely on the fact that the constraints are different for
848   // this declaration than that above.
849   //
850   // Note that we also get here for injected class names and
851   // late-parsed template definitions. We must ensure that we
852   // do not create new type declarations for those cases.
853   if (flag_concepts && CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
854     {
855       tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
856       tree args = CLASSTYPE_TI_ARGS (type);
857 
858       // If there are no template parameters, this cannot be a new
859       // partial template specializtion?
860       if (!current_template_parms)
861         return NULL_TREE;
862 
863       // The injected-class-name is not a new partial specialization.
864       if (DECL_SELF_REFERENCE_P (TYPE_NAME (type)))
865 	return NULL_TREE;
866 
867       // If the constraints are not the same as those of the primary
868       // then, we can probably create a new specialization.
869       tree type_constr = current_template_constraints ();
870 
871       if (type == TREE_TYPE (tmpl))
872 	{
873 	  tree main_constr = get_constraints (tmpl);
874 	  if (equivalent_constraints (type_constr, main_constr))
875 	    return NULL_TREE;
876 	}
877 
878       // Also, if there's a pre-existing specialization with matching
879       // constraints, then this also isn't new.
880       tree specs = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
881       while (specs)
882         {
883           tree spec_tmpl = TREE_VALUE (specs);
884           tree spec_args = TREE_PURPOSE (specs);
885           tree spec_constr = get_constraints (spec_tmpl);
886           if (comp_template_args (args, spec_args)
887 	      && equivalent_constraints (type_constr, spec_constr))
888             return NULL_TREE;
889           specs = TREE_CHAIN (specs);
890         }
891 
892       // Create a new type node (and corresponding type decl)
893       // for the newly declared specialization.
894       tree t = make_class_type (TREE_CODE (type));
895       CLASSTYPE_DECLARED_CLASS (t) = CLASSTYPE_DECLARED_CLASS (type);
896       TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (type);
897       SET_TYPE_TEMPLATE_INFO (t, build_template_info (tmpl, args));
898 
899       /* We only need a separate type node for storing the definition of this
900 	 partial specialization; uses of S<T*> are unconstrained, so all are
901 	 equivalent.  So keep TYPE_CANONICAL the same.  */
902       TYPE_CANONICAL (t) = TYPE_CANONICAL (type);
903 
904       // Build the corresponding type decl.
905       tree d = create_implicit_typedef (DECL_NAME (tmpl), t);
906       DECL_CONTEXT (d) = TYPE_CONTEXT (t);
907       DECL_SOURCE_LOCATION (d) = input_location;
908 
909       return t;
910     }
911 
912   return NULL_TREE;
913 }
914 
915 /* The TYPE is being declared.  If it is a template type, that means it
916    is a partial specialization.  Do appropriate error-checking.  */
917 
918 tree
maybe_process_partial_specialization(tree type)919 maybe_process_partial_specialization (tree type)
920 {
921   tree context;
922 
923   if (type == error_mark_node)
924     return error_mark_node;
925 
926   /* A lambda that appears in specialization context is not itself a
927      specialization.  */
928   if (CLASS_TYPE_P (type) && CLASSTYPE_LAMBDA_EXPR (type))
929     return type;
930 
931   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
932     {
933       error ("name of class shadows template template parameter %qD",
934 	     TYPE_NAME (type));
935       return error_mark_node;
936     }
937 
938   context = TYPE_CONTEXT (type);
939 
940   if (TYPE_ALIAS_P (type))
941     {
942       if (TYPE_TEMPLATE_INFO (type)
943 	  && DECL_ALIAS_TEMPLATE_P (TYPE_TI_TEMPLATE (type)))
944 	error ("specialization of alias template %qD",
945 	       TYPE_TI_TEMPLATE (type));
946       else
947 	error ("explicit specialization of non-template %qT", type);
948       return error_mark_node;
949     }
950   else if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
951     {
952       /* This is for ordinary explicit specialization and partial
953 	 specialization of a template class such as:
954 
955 	   template <> class C<int>;
956 
957 	 or:
958 
959 	   template <class T> class C<T*>;
960 
961 	 Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
962 
963       if (tree t = maybe_new_partial_specialization (type))
964 	{
965 	  if (!check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (t))
966 	      && !at_namespace_scope_p ())
967 	    return error_mark_node;
968 	  SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (t);
969 	  DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (t)) = input_location;
970 	  if (processing_template_decl)
971 	    {
972 	      tree decl = push_template_decl (TYPE_MAIN_DECL (t));
973 	      if (decl == error_mark_node)
974 		return error_mark_node;
975 	      return TREE_TYPE (decl);
976 	    }
977 	}
978       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
979 	error ("specialization of %qT after instantiation", type);
980       else if (errorcount && !processing_specialization
981 	        && CLASSTYPE_TEMPLATE_SPECIALIZATION (type)
982 	       && !uses_template_parms (CLASSTYPE_TI_ARGS (type)))
983 	/* Trying to define a specialization either without a template<> header
984 	   or in an inappropriate place.  We've already given an error, so just
985 	   bail now so we don't actually define the specialization.  */
986 	return error_mark_node;
987     }
988   else if (CLASS_TYPE_P (type)
989 	   && !CLASSTYPE_USE_TEMPLATE (type)
990 	   && CLASSTYPE_TEMPLATE_INFO (type)
991 	   && context && CLASS_TYPE_P (context)
992 	   && CLASSTYPE_TEMPLATE_INFO (context))
993     {
994       /* This is for an explicit specialization of member class
995 	 template according to [temp.expl.spec/18]:
996 
997 	   template <> template <class U> class C<int>::D;
998 
999 	 The context `C<int>' must be an implicit instantiation.
1000 	 Otherwise this is just a member class template declared
1001 	 earlier like:
1002 
1003 	   template <> class C<int> { template <class U> class D; };
1004 	   template <> template <class U> class C<int>::D;
1005 
1006 	 In the first case, `C<int>::D' is a specialization of `C<T>::D'
1007 	 while in the second case, `C<int>::D' is a primary template
1008 	 and `C<T>::D' may not exist.  */
1009 
1010       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
1011 	  && !COMPLETE_TYPE_P (type))
1012 	{
1013 	  tree t;
1014 	  tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
1015 
1016 	  if (current_namespace
1017 	      != decl_namespace_context (tmpl))
1018 	    {
1019 	      permerror (input_location,
1020 			 "specializing %q#T in different namespace", type);
1021 	      permerror (DECL_SOURCE_LOCATION (tmpl),
1022 			 "  from definition of %q#D", tmpl);
1023 	    }
1024 
1025 	  /* Check for invalid specialization after instantiation:
1026 
1027 	       template <> template <> class C<int>::D<int>;
1028 	       template <> template <class U> class C<int>::D;  */
1029 
1030 	  for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
1031 	       t; t = TREE_CHAIN (t))
1032 	    {
1033 	      tree inst = TREE_VALUE (t);
1034 	      if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst)
1035 		  || !COMPLETE_OR_OPEN_TYPE_P (inst))
1036 		{
1037 		  /* We already have a full specialization of this partial
1038 		     instantiation, or a full specialization has been
1039 		     looked up but not instantiated.  Reassign it to the
1040 		     new member specialization template.  */
1041 		  spec_entry elt;
1042 		  spec_entry *entry;
1043 
1044 		  elt.tmpl = most_general_template (tmpl);
1045 		  elt.args = CLASSTYPE_TI_ARGS (inst);
1046 		  elt.spec = inst;
1047 
1048 		  type_specializations->remove_elt (&elt);
1049 
1050 		  elt.tmpl = tmpl;
1051 		  elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
1052 
1053 		  spec_entry **slot
1054 		    = type_specializations->find_slot (&elt, INSERT);
1055 		  entry = ggc_alloc<spec_entry> ();
1056 		  *entry = elt;
1057 		  *slot = entry;
1058 		}
1059 	      else
1060 		/* But if we've had an implicit instantiation, that's a
1061 		   problem ([temp.expl.spec]/6).  */
1062 		error ("specialization %qT after instantiation %qT",
1063 		       type, inst);
1064 	    }
1065 
1066 	  /* Mark TYPE as a specialization.  And as a result, we only
1067 	     have one level of template argument for the innermost
1068 	     class template.  */
1069 	  SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
1070 	  DECL_SOURCE_LOCATION (TYPE_MAIN_DECL (type)) = input_location;
1071 	  CLASSTYPE_TI_ARGS (type)
1072 	    = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
1073 	}
1074     }
1075   else if (processing_specialization)
1076     {
1077        /* Someday C++0x may allow for enum template specialization.  */
1078       if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
1079 	  && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
1080 	pedwarn (input_location, OPT_Wpedantic, "template specialization "
1081 		 "of %qD not allowed by ISO C++", type);
1082       else
1083 	{
1084 	  error ("explicit specialization of non-template %qT", type);
1085 	  return error_mark_node;
1086 	}
1087     }
1088 
1089   return type;
1090 }
1091 
1092 /* Returns nonzero if we can optimize the retrieval of specializations
1093    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
1094    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
1095 
1096 static inline bool
optimize_specialization_lookup_p(tree tmpl)1097 optimize_specialization_lookup_p (tree tmpl)
1098 {
1099   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
1100 	  && DECL_CLASS_SCOPE_P (tmpl)
1101 	  /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
1102 	     parameter.  */
1103 	  && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
1104 	  /* The optimized lookup depends on the fact that the
1105 	     template arguments for the member function template apply
1106 	     purely to the containing class, which is not true if the
1107 	     containing class is an explicit or partial
1108 	     specialization.  */
1109 	  && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
1110 	  && !DECL_MEMBER_TEMPLATE_P (tmpl)
1111 	  && !DECL_CONV_FN_P (tmpl)
1112 	  /* It is possible to have a template that is not a member
1113 	     template and is not a member of a template class:
1114 
1115 	     template <typename T>
1116 	     struct S { friend A::f(); };
1117 
1118 	     Here, the friend function is a template, but the context does
1119 	     not have template information.  The optimized lookup relies
1120 	     on having ARGS be the template arguments for both the class
1121 	     and the function template.  */
1122 	  && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
1123 }
1124 
1125 /* Make sure ARGS doesn't use any inappropriate typedefs; we should have
1126    gone through coerce_template_parms by now.  */
1127 
1128 static void
verify_unstripped_args(tree args)1129 verify_unstripped_args (tree args)
1130 {
1131   ++processing_template_decl;
1132   if (!any_dependent_template_arguments_p (args))
1133     {
1134       tree inner = INNERMOST_TEMPLATE_ARGS (args);
1135       for (int i = 0; i < TREE_VEC_LENGTH (inner); ++i)
1136 	{
1137 	  tree arg = TREE_VEC_ELT (inner, i);
1138 	  if (TREE_CODE (arg) == TEMPLATE_DECL)
1139 	    /* OK */;
1140 	  else if (TYPE_P (arg))
1141 	    gcc_assert (strip_typedefs (arg, NULL) == arg);
1142 	  else if (strip_typedefs (TREE_TYPE (arg), NULL) != TREE_TYPE (arg))
1143 	    /* Allow typedefs on the type of a non-type argument, since a
1144 	       parameter can have them.  */;
1145 	  else
1146 	    gcc_assert (strip_typedefs_expr (arg, NULL) == arg);
1147 	}
1148     }
1149   --processing_template_decl;
1150 }
1151 
1152 /* Retrieve the specialization (in the sense of [temp.spec] - a
1153    specialization is either an instantiation or an explicit
1154    specialization) of TMPL for the given template ARGS.  If there is
1155    no such specialization, return NULL_TREE.  The ARGS are a vector of
1156    arguments, or a vector of vectors of arguments, in the case of
1157    templates with more than one level of parameters.
1158 
1159    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
1160    then we search for a partial specialization matching ARGS.  This
1161    parameter is ignored if TMPL is not a class template.
1162 
1163    We can also look up a FIELD_DECL, if it is a lambda capture pack; the
1164    result is a NONTYPE_ARGUMENT_PACK.  */
1165 
1166 static tree
retrieve_specialization(tree tmpl,tree args,hashval_t hash)1167 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
1168 {
1169   if (tmpl == NULL_TREE)
1170     return NULL_TREE;
1171 
1172   if (args == error_mark_node)
1173     return NULL_TREE;
1174 
1175   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL
1176 	      || TREE_CODE (tmpl) == FIELD_DECL);
1177 
1178   /* There should be as many levels of arguments as there are
1179      levels of parameters.  */
1180   gcc_assert (TMPL_ARGS_DEPTH (args)
1181 	      == (TREE_CODE (tmpl) == TEMPLATE_DECL
1182 		  ? TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl))
1183 		  : template_class_depth (DECL_CONTEXT (tmpl))));
1184 
1185   if (flag_checking)
1186     verify_unstripped_args (args);
1187 
1188   if (optimize_specialization_lookup_p (tmpl))
1189     {
1190       tree class_template;
1191       tree class_specialization;
1192       vec<tree, va_gc> *methods;
1193       tree fns;
1194       int idx;
1195 
1196       /* The template arguments actually apply to the containing
1197 	 class.  Find the class specialization with those
1198 	 arguments.  */
1199       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
1200       class_specialization
1201 	= retrieve_specialization (class_template, args, 0);
1202       if (!class_specialization)
1203 	return NULL_TREE;
1204       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
1205 	 for the specialization.  */
1206       idx = class_method_index_for_fn (class_specialization, tmpl);
1207       if (idx == -1)
1208 	return NULL_TREE;
1209       /* Iterate through the methods with the indicated name, looking
1210 	 for the one that has an instance of TMPL.  */
1211       methods = CLASSTYPE_METHOD_VEC (class_specialization);
1212       for (fns = (*methods)[idx]; fns; fns = OVL_NEXT (fns))
1213 	{
1214 	  tree fn = OVL_CURRENT (fns);
1215 	  if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl
1216 	      /* using-declarations can add base methods to the method vec,
1217 		 and we don't want those here.  */
1218 	      && DECL_CONTEXT (fn) == class_specialization)
1219 	    return fn;
1220 	}
1221       return NULL_TREE;
1222     }
1223   else
1224     {
1225       spec_entry *found;
1226       spec_entry elt;
1227       hash_table<spec_hasher> *specializations;
1228 
1229       elt.tmpl = tmpl;
1230       elt.args = args;
1231       elt.spec = NULL_TREE;
1232 
1233       if (DECL_CLASS_TEMPLATE_P (tmpl))
1234 	specializations = type_specializations;
1235       else
1236 	specializations = decl_specializations;
1237 
1238       if (hash == 0)
1239 	hash = spec_hasher::hash (&elt);
1240       found = specializations->find_with_hash (&elt, hash);
1241       if (found)
1242 	return found->spec;
1243     }
1244 
1245   return NULL_TREE;
1246 }
1247 
1248 /* Like retrieve_specialization, but for local declarations.  */
1249 
1250 tree
retrieve_local_specialization(tree tmpl)1251 retrieve_local_specialization (tree tmpl)
1252 {
1253   if (local_specializations == NULL)
1254     return NULL_TREE;
1255 
1256   tree *slot = local_specializations->get (tmpl);
1257   return slot ? *slot : NULL_TREE;
1258 }
1259 
1260 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1261 
1262 int
is_specialization_of(tree decl,tree tmpl)1263 is_specialization_of (tree decl, tree tmpl)
1264 {
1265   tree t;
1266 
1267   if (TREE_CODE (decl) == FUNCTION_DECL)
1268     {
1269       for (t = decl;
1270 	   t != NULL_TREE;
1271 	   t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1272 	if (t == tmpl)
1273 	  return 1;
1274     }
1275   else
1276     {
1277       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1278 
1279       for (t = TREE_TYPE (decl);
1280 	   t != NULL_TREE;
1281 	   t = CLASSTYPE_USE_TEMPLATE (t)
1282 	     ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1283 	if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1284 	  return 1;
1285     }
1286 
1287   return 0;
1288 }
1289 
1290 /* Returns nonzero iff DECL is a specialization of friend declaration
1291    FRIEND_DECL according to [temp.friend].  */
1292 
1293 bool
is_specialization_of_friend(tree decl,tree friend_decl)1294 is_specialization_of_friend (tree decl, tree friend_decl)
1295 {
1296   bool need_template = true;
1297   int template_depth;
1298 
1299   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1300 	      || TREE_CODE (decl) == TYPE_DECL);
1301 
1302   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1303      of a template class, we want to check if DECL is a specialization
1304      if this.  */
1305   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1306       && DECL_TEMPLATE_INFO (friend_decl)
1307       && !DECL_USE_TEMPLATE (friend_decl))
1308     {
1309       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1310       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1311       need_template = false;
1312     }
1313   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1314 	   && !PRIMARY_TEMPLATE_P (friend_decl))
1315     need_template = false;
1316 
1317   /* There is nothing to do if this is not a template friend.  */
1318   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1319     return false;
1320 
1321   if (is_specialization_of (decl, friend_decl))
1322     return true;
1323 
1324   /* [temp.friend/6]
1325      A member of a class template may be declared to be a friend of a
1326      non-template class.  In this case, the corresponding member of
1327      every specialization of the class template is a friend of the
1328      class granting friendship.
1329 
1330      For example, given a template friend declaration
1331 
1332        template <class T> friend void A<T>::f();
1333 
1334      the member function below is considered a friend
1335 
1336        template <> struct A<int> {
1337 	 void f();
1338        };
1339 
1340      For this type of template friend, TEMPLATE_DEPTH below will be
1341      nonzero.  To determine if DECL is a friend of FRIEND, we first
1342      check if the enclosing class is a specialization of another.  */
1343 
1344   template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1345   if (template_depth
1346       && DECL_CLASS_SCOPE_P (decl)
1347       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1348 			       CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1349     {
1350       /* Next, we check the members themselves.  In order to handle
1351 	 a few tricky cases, such as when FRIEND_DECL's are
1352 
1353 	   template <class T> friend void A<T>::g(T t);
1354 	   template <class T> template <T t> friend void A<T>::h();
1355 
1356 	 and DECL's are
1357 
1358 	   void A<int>::g(int);
1359 	   template <int> void A<int>::h();
1360 
1361 	 we need to figure out ARGS, the template arguments from
1362 	 the context of DECL.  This is required for template substitution
1363 	 of `T' in the function parameter of `g' and template parameter
1364 	 of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1365 
1366       tree context = DECL_CONTEXT (decl);
1367       tree args = NULL_TREE;
1368       int current_depth = 0;
1369 
1370       while (current_depth < template_depth)
1371 	{
1372 	  if (CLASSTYPE_TEMPLATE_INFO (context))
1373 	    {
1374 	      if (current_depth == 0)
1375 		args = TYPE_TI_ARGS (context);
1376 	      else
1377 		args = add_to_template_args (TYPE_TI_ARGS (context), args);
1378 	      current_depth++;
1379 	    }
1380 	  context = TYPE_CONTEXT (context);
1381 	}
1382 
1383       if (TREE_CODE (decl) == FUNCTION_DECL)
1384 	{
1385 	  bool is_template;
1386 	  tree friend_type;
1387 	  tree decl_type;
1388 	  tree friend_args_type;
1389 	  tree decl_args_type;
1390 
1391 	  /* Make sure that both DECL and FRIEND_DECL are templates or
1392 	     non-templates.  */
1393 	  is_template = DECL_TEMPLATE_INFO (decl)
1394 			&& PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1395 	  if (need_template ^ is_template)
1396 	    return false;
1397 	  else if (is_template)
1398 	    {
1399 	      /* If both are templates, check template parameter list.  */
1400 	      tree friend_parms
1401 		= tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1402 					 args, tf_none);
1403 	      if (!comp_template_parms
1404 		     (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1405 		      friend_parms))
1406 		return false;
1407 
1408 	      decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1409 	    }
1410 	  else
1411 	    decl_type = TREE_TYPE (decl);
1412 
1413 	  friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1414 					      tf_none, NULL_TREE);
1415 	  if (friend_type == error_mark_node)
1416 	    return false;
1417 
1418 	  /* Check if return types match.  */
1419 	  if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1420 	    return false;
1421 
1422 	  /* Check if function parameter types match, ignoring the
1423 	     `this' parameter.  */
1424 	  friend_args_type = TYPE_ARG_TYPES (friend_type);
1425 	  decl_args_type = TYPE_ARG_TYPES (decl_type);
1426 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1427 	    friend_args_type = TREE_CHAIN (friend_args_type);
1428 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1429 	    decl_args_type = TREE_CHAIN (decl_args_type);
1430 
1431 	  return compparms (decl_args_type, friend_args_type);
1432 	}
1433       else
1434 	{
1435 	  /* DECL is a TYPE_DECL */
1436 	  bool is_template;
1437 	  tree decl_type = TREE_TYPE (decl);
1438 
1439 	  /* Make sure that both DECL and FRIEND_DECL are templates or
1440 	     non-templates.  */
1441 	  is_template
1442 	    = CLASSTYPE_TEMPLATE_INFO (decl_type)
1443 	      && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1444 
1445 	  if (need_template ^ is_template)
1446 	    return false;
1447 	  else if (is_template)
1448 	    {
1449 	      tree friend_parms;
1450 	      /* If both are templates, check the name of the two
1451 		 TEMPLATE_DECL's first because is_friend didn't.  */
1452 	      if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1453 		  != DECL_NAME (friend_decl))
1454 		return false;
1455 
1456 	      /* Now check template parameter list.  */
1457 	      friend_parms
1458 		= tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1459 					 args, tf_none);
1460 	      return comp_template_parms
1461 		(DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1462 		 friend_parms);
1463 	    }
1464 	  else
1465 	    return (DECL_NAME (decl)
1466 		    == DECL_NAME (friend_decl));
1467 	}
1468     }
1469   return false;
1470 }
1471 
1472 /* Register the specialization SPEC as a specialization of TMPL with
1473    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1474    is actually just a friend declaration.  Returns SPEC, or an
1475    equivalent prior declaration, if available.
1476 
1477    We also store instantiations of field packs in the hash table, even
1478    though they are not themselves templates, to make lookup easier.  */
1479 
1480 static tree
register_specialization(tree spec,tree tmpl,tree args,bool is_friend,hashval_t hash)1481 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1482 			 hashval_t hash)
1483 {
1484   tree fn;
1485   spec_entry **slot = NULL;
1486   spec_entry elt;
1487 
1488   gcc_assert ((TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec))
1489 	      || (TREE_CODE (tmpl) == FIELD_DECL
1490 		  && TREE_CODE (spec) == NONTYPE_ARGUMENT_PACK));
1491 
1492   if (TREE_CODE (spec) == FUNCTION_DECL
1493       && uses_template_parms (DECL_TI_ARGS (spec)))
1494     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1495        register it; we want the corresponding TEMPLATE_DECL instead.
1496        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1497        the more obvious `uses_template_parms (spec)' to avoid problems
1498        with default function arguments.  In particular, given
1499        something like this:
1500 
1501 	  template <class T> void f(T t1, T t = T())
1502 
1503        the default argument expression is not substituted for in an
1504        instantiation unless and until it is actually needed.  */
1505     return spec;
1506 
1507   if (optimize_specialization_lookup_p (tmpl))
1508     /* We don't put these specializations in the hash table, but we might
1509        want to give an error about a mismatch.  */
1510     fn = retrieve_specialization (tmpl, args, 0);
1511   else
1512     {
1513       elt.tmpl = tmpl;
1514       elt.args = args;
1515       elt.spec = spec;
1516 
1517       if (hash == 0)
1518 	hash = spec_hasher::hash (&elt);
1519 
1520       slot =
1521 	decl_specializations->find_slot_with_hash (&elt, hash, INSERT);
1522       if (*slot)
1523 	fn = ((spec_entry *) *slot)->spec;
1524       else
1525 	fn = NULL_TREE;
1526     }
1527 
1528   /* We can sometimes try to re-register a specialization that we've
1529      already got.  In particular, regenerate_decl_from_template calls
1530      duplicate_decls which will update the specialization list.  But,
1531      we'll still get called again here anyhow.  It's more convenient
1532      to simply allow this than to try to prevent it.  */
1533   if (fn == spec)
1534     return spec;
1535   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1536     {
1537       if (DECL_TEMPLATE_INSTANTIATION (fn))
1538 	{
1539 	  if (DECL_ODR_USED (fn)
1540 	      || DECL_EXPLICIT_INSTANTIATION (fn))
1541 	    {
1542 	      error ("specialization of %qD after instantiation",
1543 		     fn);
1544 	      return error_mark_node;
1545 	    }
1546 	  else
1547 	    {
1548 	      tree clone;
1549 	      /* This situation should occur only if the first
1550 		 specialization is an implicit instantiation, the
1551 		 second is an explicit specialization, and the
1552 		 implicit instantiation has not yet been used.  That
1553 		 situation can occur if we have implicitly
1554 		 instantiated a member function and then specialized
1555 		 it later.
1556 
1557 		 We can also wind up here if a friend declaration that
1558 		 looked like an instantiation turns out to be a
1559 		 specialization:
1560 
1561 		   template <class T> void foo(T);
1562 		   class S { friend void foo<>(int) };
1563 		   template <> void foo(int);
1564 
1565 		 We transform the existing DECL in place so that any
1566 		 pointers to it become pointers to the updated
1567 		 declaration.
1568 
1569 		 If there was a definition for the template, but not
1570 		 for the specialization, we want this to look as if
1571 		 there were no definition, and vice versa.  */
1572 	      DECL_INITIAL (fn) = NULL_TREE;
1573 	      duplicate_decls (spec, fn, is_friend);
1574 	      /* The call to duplicate_decls will have applied
1575 		 [temp.expl.spec]:
1576 
1577 		   An explicit specialization of a function template
1578 		   is inline only if it is explicitly declared to be,
1579 		   and independently of whether its function template
1580 		   is.
1581 
1582 		to the primary function; now copy the inline bits to
1583 		the various clones.  */
1584 	      FOR_EACH_CLONE (clone, fn)
1585 		{
1586 		  DECL_DECLARED_INLINE_P (clone)
1587 		    = DECL_DECLARED_INLINE_P (fn);
1588 		  DECL_SOURCE_LOCATION (clone)
1589 		    = DECL_SOURCE_LOCATION (fn);
1590 		  DECL_DELETED_FN (clone)
1591 		    = DECL_DELETED_FN (fn);
1592 		}
1593 	      check_specialization_namespace (tmpl);
1594 
1595 	      return fn;
1596 	    }
1597 	}
1598       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1599 	{
1600 	  if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1601 	    /* Dup decl failed, but this is a new definition. Set the
1602 	       line number so any errors match this new
1603 	       definition.  */
1604 	    DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1605 
1606 	  return fn;
1607 	}
1608     }
1609   else if (fn)
1610     return duplicate_decls (spec, fn, is_friend);
1611 
1612   /* A specialization must be declared in the same namespace as the
1613      template it is specializing.  */
1614   if (DECL_P (spec) && DECL_TEMPLATE_SPECIALIZATION (spec)
1615       && !check_specialization_namespace (tmpl))
1616     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1617 
1618   if (slot != NULL /* !optimize_specialization_lookup_p (tmpl) */)
1619     {
1620       spec_entry *entry = ggc_alloc<spec_entry> ();
1621       gcc_assert (tmpl && args && spec);
1622       *entry = elt;
1623       *slot = entry;
1624       if ((TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1625 	   && PRIMARY_TEMPLATE_P (tmpl)
1626 	   && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1627 	  || variable_template_p (tmpl))
1628 	/* If TMPL is a forward declaration of a template function, keep a list
1629 	   of all specializations in case we need to reassign them to a friend
1630 	   template later in tsubst_friend_function.
1631 
1632 	   Also keep a list of all variable template instantiations so that
1633 	   process_partial_specialization can check whether a later partial
1634 	   specialization would have used it.  */
1635 	DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1636 	  = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1637     }
1638 
1639   return spec;
1640 }
1641 
1642 /* Returns true iff two spec_entry nodes are equivalent.  */
1643 
1644 int comparing_specializations;
1645 
1646 bool
equal(spec_entry * e1,spec_entry * e2)1647 spec_hasher::equal (spec_entry *e1, spec_entry *e2)
1648 {
1649   int equal;
1650 
1651   ++comparing_specializations;
1652   equal = (e1->tmpl == e2->tmpl
1653 	   && comp_template_args (e1->args, e2->args));
1654   if (equal && flag_concepts
1655       /* tmpl could be a FIELD_DECL for a capture pack.  */
1656       && TREE_CODE (e1->tmpl) == TEMPLATE_DECL
1657       && VAR_P (DECL_TEMPLATE_RESULT (e1->tmpl))
1658       && uses_template_parms (e1->args))
1659     {
1660       /* Partial specializations of a variable template can be distinguished by
1661 	 constraints.  */
1662       tree c1 = e1->spec ? get_constraints (e1->spec) : NULL_TREE;
1663       tree c2 = e2->spec ? get_constraints (e2->spec) : NULL_TREE;
1664       equal = equivalent_constraints (c1, c2);
1665     }
1666   --comparing_specializations;
1667 
1668   return equal;
1669 }
1670 
1671 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1672 
1673 static hashval_t
hash_tmpl_and_args(tree tmpl,tree args)1674 hash_tmpl_and_args (tree tmpl, tree args)
1675 {
1676   hashval_t val = iterative_hash_object (DECL_UID (tmpl), 0);
1677   return iterative_hash_template_arg (args, val);
1678 }
1679 
1680 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1681    ignoring SPEC.  */
1682 
1683 hashval_t
hash(spec_entry * e)1684 spec_hasher::hash (spec_entry *e)
1685 {
1686   return hash_tmpl_and_args (e->tmpl, e->args);
1687 }
1688 
1689 /* Recursively calculate a hash value for a template argument ARG, for use
1690    in the hash tables of template specializations.  */
1691 
1692 hashval_t
iterative_hash_template_arg(tree arg,hashval_t val)1693 iterative_hash_template_arg (tree arg, hashval_t val)
1694 {
1695   unsigned HOST_WIDE_INT i;
1696   enum tree_code code;
1697   char tclass;
1698 
1699   if (arg == NULL_TREE)
1700     return iterative_hash_object (arg, val);
1701 
1702   if (!TYPE_P (arg))
1703     STRIP_NOPS (arg);
1704 
1705   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
1706     /* We can get one of these when re-hashing a previous entry in the middle
1707        of substituting into a pack expansion.  Just look through it.  */
1708     arg = ARGUMENT_PACK_SELECT_FROM_PACK (arg);
1709 
1710   code = TREE_CODE (arg);
1711   tclass = TREE_CODE_CLASS (code);
1712 
1713   val = iterative_hash_object (code, val);
1714 
1715   switch (code)
1716     {
1717     case ERROR_MARK:
1718       return val;
1719 
1720     case IDENTIFIER_NODE:
1721       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1722 
1723     case TREE_VEC:
1724       {
1725 	int i, len = TREE_VEC_LENGTH (arg);
1726 	for (i = 0; i < len; ++i)
1727 	  val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1728 	return val;
1729       }
1730 
1731     case TYPE_PACK_EXPANSION:
1732     case EXPR_PACK_EXPANSION:
1733       val = iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1734       return iterative_hash_template_arg (PACK_EXPANSION_EXTRA_ARGS (arg), val);
1735 
1736     case TYPE_ARGUMENT_PACK:
1737     case NONTYPE_ARGUMENT_PACK:
1738       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1739 
1740     case TREE_LIST:
1741       for (; arg; arg = TREE_CHAIN (arg))
1742 	val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1743       return val;
1744 
1745     case OVERLOAD:
1746       for (; arg; arg = OVL_NEXT (arg))
1747 	val = iterative_hash_template_arg (OVL_CURRENT (arg), val);
1748       return val;
1749 
1750     case CONSTRUCTOR:
1751       {
1752 	tree field, value;
1753 	iterative_hash_template_arg (TREE_TYPE (arg), val);
1754 	FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1755 	  {
1756 	    val = iterative_hash_template_arg (field, val);
1757 	    val = iterative_hash_template_arg (value, val);
1758 	  }
1759 	return val;
1760       }
1761 
1762     case PARM_DECL:
1763       if (!DECL_ARTIFICIAL (arg))
1764 	{
1765 	  val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1766 	  val = iterative_hash_object (DECL_PARM_LEVEL (arg), val);
1767 	}
1768       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1769 
1770     case TARGET_EXPR:
1771       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1772 
1773     case PTRMEM_CST:
1774       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1775       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1776 
1777     case TEMPLATE_PARM_INDEX:
1778       val = iterative_hash_template_arg
1779 	(TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1780       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1781       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1782 
1783     case TRAIT_EXPR:
1784       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1785       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1786       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1787 
1788     case BASELINK:
1789       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1790 					 val);
1791       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1792 					  val);
1793 
1794     case MODOP_EXPR:
1795       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1796       code = TREE_CODE (TREE_OPERAND (arg, 1));
1797       val = iterative_hash_object (code, val);
1798       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1799 
1800     case LAMBDA_EXPR:
1801       /* A lambda can't appear in a template arg, but don't crash on
1802 	 erroneous input.  */
1803       gcc_assert (seen_error ());
1804       return val;
1805 
1806     case CAST_EXPR:
1807     case IMPLICIT_CONV_EXPR:
1808     case STATIC_CAST_EXPR:
1809     case REINTERPRET_CAST_EXPR:
1810     case CONST_CAST_EXPR:
1811     case DYNAMIC_CAST_EXPR:
1812     case NEW_EXPR:
1813       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1814       /* Now hash operands as usual.  */
1815       break;
1816 
1817     default:
1818       break;
1819     }
1820 
1821   switch (tclass)
1822     {
1823     case tcc_type:
1824       if (alias_template_specialization_p (arg))
1825 	{
1826 	  // We want an alias specialization that survived strip_typedefs
1827 	  // to hash differently from its TYPE_CANONICAL, to avoid hash
1828 	  // collisions that compare as different in template_args_equal.
1829 	  // These could be dependent specializations that strip_typedefs
1830 	  // left alone, or untouched specializations because
1831 	  // coerce_template_parms returns the unconverted template
1832 	  // arguments if it sees incomplete argument packs.
1833 	  tree ti = TYPE_TEMPLATE_INFO (arg);
1834 	  return hash_tmpl_and_args (TI_TEMPLATE (ti), TI_ARGS (ti));
1835 	}
1836       if (TYPE_CANONICAL (arg))
1837 	return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1838 				      val);
1839       else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1840 	return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1841       /* Otherwise just compare the types during lookup.  */
1842       return val;
1843 
1844     case tcc_declaration:
1845     case tcc_constant:
1846       return iterative_hash_expr (arg, val);
1847 
1848     default:
1849       gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1850       {
1851 	unsigned n = cp_tree_operand_length (arg);
1852 	for (i = 0; i < n; ++i)
1853 	  val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1854 	return val;
1855       }
1856     }
1857   gcc_unreachable ();
1858   return 0;
1859 }
1860 
1861 /* Unregister the specialization SPEC as a specialization of TMPL.
1862    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1863    if the SPEC was listed as a specialization of TMPL.
1864 
1865    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1866 
1867 bool
reregister_specialization(tree spec,tree tinfo,tree new_spec)1868 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1869 {
1870   spec_entry *entry;
1871   spec_entry elt;
1872 
1873   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1874   elt.args = TI_ARGS (tinfo);
1875   elt.spec = NULL_TREE;
1876 
1877   entry = decl_specializations->find (&elt);
1878   if (entry != NULL)
1879     {
1880       gcc_assert (entry->spec == spec || entry->spec == new_spec);
1881       gcc_assert (new_spec != NULL_TREE);
1882       entry->spec = new_spec;
1883       return 1;
1884     }
1885 
1886   return 0;
1887 }
1888 
1889 /* Like register_specialization, but for local declarations.  We are
1890    registering SPEC, an instantiation of TMPL.  */
1891 
1892 void
register_local_specialization(tree spec,tree tmpl)1893 register_local_specialization (tree spec, tree tmpl)
1894 {
1895   local_specializations->put (tmpl, spec);
1896 }
1897 
1898 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1899    specialized class.  */
1900 
1901 bool
explicit_class_specialization_p(tree type)1902 explicit_class_specialization_p (tree type)
1903 {
1904   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1905     return false;
1906   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1907 }
1908 
1909 /* Print the list of functions at FNS, going through all the overloads
1910    for each element of the list.  Alternatively, FNS can not be a
1911    TREE_LIST, in which case it will be printed together with all the
1912    overloads.
1913 
1914    MORE and *STR should respectively be FALSE and NULL when the function
1915    is called from the outside.  They are used internally on recursive
1916    calls.  print_candidates manages the two parameters and leaves NULL
1917    in *STR when it ends.  */
1918 
1919 static void
print_candidates_1(tree fns,bool more,const char ** str)1920 print_candidates_1 (tree fns, bool more, const char **str)
1921 {
1922   tree fn, fn2;
1923   char *spaces = NULL;
1924 
1925   for (fn = fns; fn; fn = OVL_NEXT (fn))
1926     if (TREE_CODE (fn) == TREE_LIST)
1927       {
1928         for (fn2 = fn; fn2 != NULL_TREE; fn2 = TREE_CHAIN (fn2))
1929           print_candidates_1 (TREE_VALUE (fn2),
1930                               TREE_CHAIN (fn2) || more, str);
1931       }
1932     else
1933       {
1934 	tree cand = OVL_CURRENT (fn);
1935         if (!*str)
1936           {
1937             /* Pick the prefix string.  */
1938             if (!more && !OVL_NEXT (fns))
1939               {
1940                 inform (DECL_SOURCE_LOCATION (cand),
1941 			"candidate is: %#D", cand);
1942                 continue;
1943               }
1944 
1945             *str = _("candidates are:");
1946             spaces = get_spaces (*str);
1947           }
1948         inform (DECL_SOURCE_LOCATION (cand), "%s %#D", *str, cand);
1949         *str = spaces ? spaces : *str;
1950       }
1951 
1952   if (!more)
1953     {
1954       free (spaces);
1955       *str = NULL;
1956     }
1957 }
1958 
1959 /* Print the list of candidate FNS in an error message.  FNS can also
1960    be a TREE_LIST of non-functions in the case of an ambiguous lookup.  */
1961 
1962 void
print_candidates(tree fns)1963 print_candidates (tree fns)
1964 {
1965   const char *str = NULL;
1966   print_candidates_1 (fns, false, &str);
1967   gcc_assert (str == NULL);
1968 }
1969 
1970 /* Get a (possibly) constrained template declaration for the
1971    purpose of ordering candidates.  */
1972 static tree
get_template_for_ordering(tree list)1973 get_template_for_ordering (tree list)
1974 {
1975   gcc_assert (TREE_CODE (list) == TREE_LIST);
1976   tree f = TREE_VALUE (list);
1977   if (tree ti = DECL_TEMPLATE_INFO (f))
1978     return TI_TEMPLATE (ti);
1979   return f;
1980 }
1981 
1982 /* Among candidates having the same signature, return the
1983    most constrained or NULL_TREE if there is no best candidate.
1984    If the signatures of candidates vary (e.g., template
1985    specialization vs. member function), then there can be no
1986    most constrained.
1987 
1988    Note that we don't compare constraints on the functions
1989    themselves, but rather those of their templates. */
1990 static tree
most_constrained_function(tree candidates)1991 most_constrained_function (tree candidates)
1992 {
1993   // Try to find the best candidate in a first pass.
1994   tree champ = candidates;
1995   for (tree c = TREE_CHAIN (champ); c; c = TREE_CHAIN (c))
1996     {
1997       int winner = more_constrained (get_template_for_ordering (champ),
1998                                      get_template_for_ordering (c));
1999       if (winner == -1)
2000         champ = c; // The candidate is more constrained
2001       else if (winner == 0)
2002         return NULL_TREE; // Neither is more constrained
2003     }
2004 
2005   // Verify that the champ is better than previous candidates.
2006   for (tree c = candidates; c != champ; c = TREE_CHAIN (c)) {
2007     if (!more_constrained (get_template_for_ordering (champ),
2008                            get_template_for_ordering (c)))
2009       return NULL_TREE;
2010   }
2011 
2012   return champ;
2013 }
2014 
2015 
2016 /* Returns the template (one of the functions given by TEMPLATE_ID)
2017    which can be specialized to match the indicated DECL with the
2018    explicit template args given in TEMPLATE_ID.  The DECL may be
2019    NULL_TREE if none is available.  In that case, the functions in
2020    TEMPLATE_ID are non-members.
2021 
2022    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
2023    specialization of a member template.
2024 
2025    The TEMPLATE_COUNT is the number of references to qualifying
2026    template classes that appeared in the name of the function. See
2027    check_explicit_specialization for a more accurate description.
2028 
2029    TSK indicates what kind of template declaration (if any) is being
2030    declared.  TSK_TEMPLATE indicates that the declaration given by
2031    DECL, though a FUNCTION_DECL, has template parameters, and is
2032    therefore a template function.
2033 
2034    The template args (those explicitly specified and those deduced)
2035    are output in a newly created vector *TARGS_OUT.
2036 
2037    If it is impossible to determine the result, an error message is
2038    issued.  The error_mark_node is returned to indicate failure.  */
2039 
2040 static tree
determine_specialization(tree template_id,tree decl,tree * targs_out,int need_member_template,int template_count,tmpl_spec_kind tsk)2041 determine_specialization (tree template_id,
2042 			  tree decl,
2043 			  tree* targs_out,
2044 			  int need_member_template,
2045 			  int template_count,
2046 			  tmpl_spec_kind tsk)
2047 {
2048   tree fns;
2049   tree targs;
2050   tree explicit_targs;
2051   tree candidates = NULL_TREE;
2052 
2053   /* A TREE_LIST of templates of which DECL may be a specialization.
2054      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
2055      corresponding TREE_PURPOSE is the set of template arguments that,
2056      when used to instantiate the template, would produce a function
2057      with the signature of DECL.  */
2058   tree templates = NULL_TREE;
2059   int header_count;
2060   cp_binding_level *b;
2061 
2062   *targs_out = NULL_TREE;
2063 
2064   if (template_id == error_mark_node || decl == error_mark_node)
2065     return error_mark_node;
2066 
2067   /* We shouldn't be specializing a member template of an
2068      unspecialized class template; we already gave an error in
2069      check_specialization_scope, now avoid crashing.  */
2070   if (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 (; fns; fns = OVL_NEXT (fns))
2118     {
2119       tree fn = OVL_CURRENT (fns);
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           /* Remove, from the set of candidates, all those functions
2223              whose constraints are not satisfied. */
2224           if (flag_concepts && !constraints_satisfied_p (fn, targs))
2225             continue;
2226 
2227           // Then, try to form the new function type.
2228 	  insttype = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
2229 	  if (insttype == error_mark_node)
2230 	    continue;
2231 	  fn_arg_types
2232 	    = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (insttype));
2233 	  if (!compparms (fn_arg_types, decl_arg_types))
2234 	    continue;
2235 
2236 	  /* Save this template, and the arguments deduced.  */
2237 	  templates = tree_cons (targs, fn, templates);
2238 	}
2239       else if (need_member_template)
2240 	/* FN is an ordinary member function, and we need a
2241 	   specialization of a member template.  */
2242 	;
2243       else if (TREE_CODE (fn) != FUNCTION_DECL)
2244 	/* We can get IDENTIFIER_NODEs here in certain erroneous
2245 	   cases.  */
2246 	;
2247       else if (!DECL_FUNCTION_MEMBER_P (fn))
2248 	/* This is just an ordinary non-member function.  Nothing can
2249 	   be a specialization of that.  */
2250 	;
2251       else if (DECL_ARTIFICIAL (fn))
2252 	/* Cannot specialize functions that are created implicitly.  */
2253 	;
2254       else
2255 	{
2256 	  tree decl_arg_types;
2257 
2258 	  /* This is an ordinary member function.  However, since
2259 	     we're here, we can assume its enclosing class is a
2260 	     template class.  For example,
2261 
2262 	       template <typename T> struct S { void f(); };
2263 	       template <> void S<int>::f() {}
2264 
2265 	     Here, S<int>::f is a non-template, but S<int> is a
2266 	     template class.  If FN has the same type as DECL, we
2267 	     might be in business.  */
2268 
2269 	  if (!DECL_TEMPLATE_INFO (fn))
2270 	    /* Its enclosing class is an explicit specialization
2271 	       of a template class.  This is not a candidate.  */
2272 	    continue;
2273 
2274 	  if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
2275 			    TREE_TYPE (TREE_TYPE (fn))))
2276 	    /* The return types differ.  */
2277 	    continue;
2278 
2279 	  /* Adjust the type of DECL in case FN is a static member.  */
2280 	  decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
2281 	  if (DECL_STATIC_FUNCTION_P (fn)
2282 	      && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2283 	    decl_arg_types = TREE_CHAIN (decl_arg_types);
2284 
2285 	  if (!compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
2286 			 decl_arg_types))
2287             continue;
2288 
2289 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
2290 	      && (type_memfn_rqual (TREE_TYPE (decl))
2291 		  != type_memfn_rqual (TREE_TYPE (fn))))
2292 	    continue;
2293 
2294           // If the deduced arguments do not satisfy the constraints,
2295           // this is not a candidate.
2296           if (flag_concepts && !constraints_satisfied_p (fn))
2297             continue;
2298 
2299           // Add the candidate.
2300           candidates = tree_cons (NULL_TREE, fn, candidates);
2301 	}
2302     }
2303 
2304   if (templates && TREE_CHAIN (templates))
2305     {
2306       /* We have:
2307 
2308 	   [temp.expl.spec]
2309 
2310 	   It is possible for a specialization with a given function
2311 	   signature to be instantiated from more than one function
2312 	   template.  In such cases, explicit specification of the
2313 	   template arguments must be used to uniquely identify the
2314 	   function template specialization being specialized.
2315 
2316 	 Note that here, there's no suggestion that we're supposed to
2317 	 determine which of the candidate templates is most
2318 	 specialized.  However, we, also have:
2319 
2320 	   [temp.func.order]
2321 
2322 	   Partial ordering of overloaded function template
2323 	   declarations is used in the following contexts to select
2324 	   the function template to which a function template
2325 	   specialization refers:
2326 
2327 	   -- when an explicit specialization refers to a function
2328 	      template.
2329 
2330 	 So, we do use the partial ordering rules, at least for now.
2331 	 This extension can only serve to make invalid programs valid,
2332 	 so it's safe.  And, there is strong anecdotal evidence that
2333 	 the committee intended the partial ordering rules to apply;
2334 	 the EDG front end has that behavior, and John Spicer claims
2335 	 that the committee simply forgot to delete the wording in
2336 	 [temp.expl.spec].  */
2337       tree tmpl = most_specialized_instantiation (templates);
2338       if (tmpl != error_mark_node)
2339 	{
2340 	  templates = tmpl;
2341 	  TREE_CHAIN (templates) = NULL_TREE;
2342 	}
2343     }
2344 
2345   // Concepts allows multiple declarations of member functions
2346   // with the same signature. Like above, we need to rely on
2347   // on the partial ordering of those candidates to determine which
2348   // is the best.
2349   if (flag_concepts && candidates && TREE_CHAIN (candidates))
2350     {
2351       if (tree cand = most_constrained_function (candidates))
2352         {
2353           candidates = cand;
2354           TREE_CHAIN (cand) = NULL_TREE;
2355         }
2356     }
2357 
2358   if (templates == NULL_TREE && candidates == NULL_TREE)
2359     {
2360       error ("template-id %qD for %q+D does not match any template "
2361 	     "declaration", template_id, decl);
2362       if (header_count && header_count != template_count + 1)
2363 	inform (input_location, "saw %d %<template<>%>, need %d for "
2364 		"specializing a member function template",
2365 		header_count, template_count + 1);
2366       else
2367 	print_candidates (orig_fns);
2368       return error_mark_node;
2369     }
2370   else if ((templates && TREE_CHAIN (templates))
2371 	   || (candidates && TREE_CHAIN (candidates))
2372 	   || (templates && candidates))
2373     {
2374       error ("ambiguous template specialization %qD for %q+D",
2375 	     template_id, decl);
2376       candidates = chainon (candidates, templates);
2377       print_candidates (candidates);
2378       return error_mark_node;
2379     }
2380 
2381   /* We have one, and exactly one, match.  */
2382   if (candidates)
2383     {
2384       tree fn = TREE_VALUE (candidates);
2385       *targs_out = copy_node (DECL_TI_ARGS (fn));
2386 
2387       // Propagate the candidate's constraints to the declaration.
2388       set_constraints (decl, get_constraints (fn));
2389 
2390       /* DECL is a re-declaration or partial instantiation of a template
2391 	 function.  */
2392       if (TREE_CODE (fn) == TEMPLATE_DECL)
2393 	return fn;
2394       /* It was a specialization of an ordinary member function in a
2395 	 template class.  */
2396       return DECL_TI_TEMPLATE (fn);
2397     }
2398 
2399   /* It was a specialization of a template.  */
2400   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2401   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2402     {
2403       *targs_out = copy_node (targs);
2404       SET_TMPL_ARGS_LEVEL (*targs_out,
2405 			   TMPL_ARGS_DEPTH (*targs_out),
2406 			   TREE_PURPOSE (templates));
2407     }
2408   else
2409     *targs_out = TREE_PURPOSE (templates);
2410   return TREE_VALUE (templates);
2411 }
2412 
2413 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2414    but with the default argument values filled in from those in the
2415    TMPL_TYPES.  */
2416 
2417 static tree
copy_default_args_to_explicit_spec_1(tree spec_types,tree tmpl_types)2418 copy_default_args_to_explicit_spec_1 (tree spec_types,
2419 				      tree tmpl_types)
2420 {
2421   tree new_spec_types;
2422 
2423   if (!spec_types)
2424     return NULL_TREE;
2425 
2426   if (spec_types == void_list_node)
2427     return void_list_node;
2428 
2429   /* Substitute into the rest of the list.  */
2430   new_spec_types =
2431     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2432 					  TREE_CHAIN (tmpl_types));
2433 
2434   /* Add the default argument for this parameter.  */
2435   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2436 			 TREE_VALUE (spec_types),
2437 			 new_spec_types);
2438 }
2439 
2440 /* DECL is an explicit specialization.  Replicate default arguments
2441    from the template it specializes.  (That way, code like:
2442 
2443      template <class T> void f(T = 3);
2444      template <> void f(double);
2445      void g () { f (); }
2446 
2447    works, as required.)  An alternative approach would be to look up
2448    the correct default arguments at the call-site, but this approach
2449    is consistent with how implicit instantiations are handled.  */
2450 
2451 static void
copy_default_args_to_explicit_spec(tree decl)2452 copy_default_args_to_explicit_spec (tree decl)
2453 {
2454   tree tmpl;
2455   tree spec_types;
2456   tree tmpl_types;
2457   tree new_spec_types;
2458   tree old_type;
2459   tree new_type;
2460   tree t;
2461   tree object_type = NULL_TREE;
2462   tree in_charge = NULL_TREE;
2463   tree vtt = NULL_TREE;
2464 
2465   /* See if there's anything we need to do.  */
2466   tmpl = DECL_TI_TEMPLATE (decl);
2467   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2468   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2469     if (TREE_PURPOSE (t))
2470       break;
2471   if (!t)
2472     return;
2473 
2474   old_type = TREE_TYPE (decl);
2475   spec_types = TYPE_ARG_TYPES (old_type);
2476 
2477   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2478     {
2479       /* Remove the this pointer, but remember the object's type for
2480 	 CV quals.  */
2481       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2482       spec_types = TREE_CHAIN (spec_types);
2483       tmpl_types = TREE_CHAIN (tmpl_types);
2484 
2485       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2486 	{
2487 	  /* DECL may contain more parameters than TMPL due to the extra
2488 	     in-charge parameter in constructors and destructors.  */
2489 	  in_charge = spec_types;
2490 	  spec_types = TREE_CHAIN (spec_types);
2491 	}
2492       if (DECL_HAS_VTT_PARM_P (decl))
2493 	{
2494 	  vtt = spec_types;
2495 	  spec_types = TREE_CHAIN (spec_types);
2496 	}
2497     }
2498 
2499   /* Compute the merged default arguments.  */
2500   new_spec_types =
2501     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2502 
2503   /* Compute the new FUNCTION_TYPE.  */
2504   if (object_type)
2505     {
2506       if (vtt)
2507 	new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2508 					 TREE_VALUE (vtt),
2509 					 new_spec_types);
2510 
2511       if (in_charge)
2512 	/* Put the in-charge parameter back.  */
2513 	new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2514 					 TREE_VALUE (in_charge),
2515 					 new_spec_types);
2516 
2517       new_type = build_method_type_directly (object_type,
2518 					     TREE_TYPE (old_type),
2519 					     new_spec_types);
2520     }
2521   else
2522     new_type = build_function_type (TREE_TYPE (old_type),
2523 				    new_spec_types);
2524   new_type = cp_build_type_attribute_variant (new_type,
2525 					      TYPE_ATTRIBUTES (old_type));
2526   new_type = build_exception_variant (new_type,
2527 				      TYPE_RAISES_EXCEPTIONS (old_type));
2528 
2529   if (TYPE_HAS_LATE_RETURN_TYPE (old_type))
2530     TYPE_HAS_LATE_RETURN_TYPE (new_type) = 1;
2531 
2532   TREE_TYPE (decl) = new_type;
2533 }
2534 
2535 /* Return the number of template headers we expect to see for a definition
2536    or specialization of CTYPE or one of its non-template members.  */
2537 
2538 int
num_template_headers_for_class(tree ctype)2539 num_template_headers_for_class (tree ctype)
2540 {
2541   int num_templates = 0;
2542 
2543   while (ctype && CLASS_TYPE_P (ctype))
2544     {
2545       /* You're supposed to have one `template <...>' for every
2546 	 template class, but you don't need one for a full
2547 	 specialization.  For example:
2548 
2549 	 template <class T> struct S{};
2550 	 template <> struct S<int> { void f(); };
2551 	 void S<int>::f () {}
2552 
2553 	 is correct; there shouldn't be a `template <>' for the
2554 	 definition of `S<int>::f'.  */
2555       if (!CLASSTYPE_TEMPLATE_INFO (ctype))
2556 	/* If CTYPE does not have template information of any
2557 	   kind,  then it is not a template, nor is it nested
2558 	   within a template.  */
2559 	break;
2560       if (explicit_class_specialization_p (ctype))
2561 	break;
2562       if (PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (ctype)))
2563 	++num_templates;
2564 
2565       ctype = TYPE_CONTEXT (ctype);
2566     }
2567 
2568   return num_templates;
2569 }
2570 
2571 /* Do a simple sanity check on the template headers that precede the
2572    variable declaration DECL.  */
2573 
2574 void
check_template_variable(tree decl)2575 check_template_variable (tree decl)
2576 {
2577   tree ctx = CP_DECL_CONTEXT (decl);
2578   int wanted = num_template_headers_for_class (ctx);
2579   if (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl)
2580       && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl)))
2581     {
2582       if (cxx_dialect < cxx14)
2583         pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2584                  "variable templates only available with "
2585                  "-std=c++14 or -std=gnu++14");
2586 
2587       // Namespace-scope variable templates should have a template header.
2588       ++wanted;
2589     }
2590   if (template_header_count > wanted)
2591     {
2592       bool warned = pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2593 			     "too many template headers for %D (should be %d)",
2594 			     decl, wanted);
2595       if (warned && CLASS_TYPE_P (ctx)
2596 	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (ctx))
2597 	inform (DECL_SOURCE_LOCATION (decl),
2598 		"members of an explicitly specialized class are defined "
2599 		"without a template header");
2600     }
2601 }
2602 
2603 /* Check to see if the function just declared, as indicated in
2604    DECLARATOR, and in DECL, is a specialization of a function
2605    template.  We may also discover that the declaration is an explicit
2606    instantiation at this point.
2607 
2608    Returns DECL, or an equivalent declaration that should be used
2609    instead if all goes well.  Issues an error message if something is
2610    amiss.  Returns error_mark_node if the error is not easily
2611    recoverable.
2612 
2613    FLAGS is a bitmask consisting of the following flags:
2614 
2615    2: The function has a definition.
2616    4: The function is a friend.
2617 
2618    The TEMPLATE_COUNT is the number of references to qualifying
2619    template classes that appeared in the name of the function.  For
2620    example, in
2621 
2622      template <class T> struct S { void f(); };
2623      void S<int>::f();
2624 
2625    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2626    classes are not counted in the TEMPLATE_COUNT, so that in
2627 
2628      template <class T> struct S {};
2629      template <> struct S<int> { void f(); }
2630      template <> void S<int>::f();
2631 
2632    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2633    invalid; there should be no template <>.)
2634 
2635    If the function is a specialization, it is marked as such via
2636    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2637    is set up correctly, and it is added to the list of specializations
2638    for that template.  */
2639 
2640 tree
check_explicit_specialization(tree declarator,tree decl,int template_count,int flags)2641 check_explicit_specialization (tree declarator,
2642 			       tree decl,
2643 			       int template_count,
2644 			       int flags)
2645 {
2646   int have_def = flags & 2;
2647   int is_friend = flags & 4;
2648   bool is_concept = flags & 8;
2649   int specialization = 0;
2650   int explicit_instantiation = 0;
2651   int member_specialization = 0;
2652   tree ctype = DECL_CLASS_CONTEXT (decl);
2653   tree dname = DECL_NAME (decl);
2654   tmpl_spec_kind tsk;
2655 
2656   if (is_friend)
2657     {
2658       if (!processing_specialization)
2659 	tsk = tsk_none;
2660       else
2661 	tsk = tsk_excessive_parms;
2662     }
2663   else
2664     tsk = current_tmpl_spec_kind (template_count);
2665 
2666   switch (tsk)
2667     {
2668     case tsk_none:
2669       if (processing_specialization && !VAR_P (decl))
2670 	{
2671 	  specialization = 1;
2672 	  SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2673 	}
2674       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2675 	{
2676 	  if (is_friend)
2677 	    /* This could be something like:
2678 
2679 	       template <class T> void f(T);
2680 	       class S { friend void f<>(int); }  */
2681 	    specialization = 1;
2682 	  else
2683 	    {
2684 	      /* This case handles bogus declarations like template <>
2685 		 template <class T> void f<int>(); */
2686 
2687 	      error ("template-id %qD in declaration of primary template",
2688 		     declarator);
2689 	      return decl;
2690 	    }
2691 	}
2692       break;
2693 
2694     case tsk_invalid_member_spec:
2695       /* The error has already been reported in
2696 	 check_specialization_scope.  */
2697       return error_mark_node;
2698 
2699     case tsk_invalid_expl_inst:
2700       error ("template parameter list used in explicit instantiation");
2701 
2702       /* Fall through.  */
2703 
2704     case tsk_expl_inst:
2705       if (have_def)
2706 	error ("definition provided for explicit instantiation");
2707 
2708       explicit_instantiation = 1;
2709       break;
2710 
2711     case tsk_excessive_parms:
2712     case tsk_insufficient_parms:
2713       if (tsk == tsk_excessive_parms)
2714 	error ("too many template parameter lists in declaration of %qD",
2715 	       decl);
2716       else if (template_header_count)
2717 	error("too few template parameter lists in declaration of %qD", decl);
2718       else
2719 	error("explicit specialization of %qD must be introduced by "
2720 	      "%<template <>%>", decl);
2721 
2722       /* Fall through.  */
2723     case tsk_expl_spec:
2724       if (is_concept)
2725         error ("explicit specialization declared %<concept%>");
2726 
2727       if (VAR_P (decl) && TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2728 	/* In cases like template<> constexpr bool v = true;
2729 	   We'll give an error in check_template_variable.  */
2730 	break;
2731 
2732       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2733       if (ctype)
2734 	member_specialization = 1;
2735       else
2736 	specialization = 1;
2737       break;
2738 
2739     case tsk_template:
2740       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2741 	{
2742 	  /* This case handles bogus declarations like template <>
2743 	     template <class T> void f<int>(); */
2744 
2745 	  if (!uses_template_parms (declarator))
2746 	    error ("template-id %qD in declaration of primary template",
2747 		   declarator);
2748 	  else if (variable_template_p (TREE_OPERAND (declarator, 0)))
2749 	    {
2750 	      /* Partial specialization of variable template.  */
2751 	      SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2752 	      specialization = 1;
2753 	      goto ok;
2754 	    }
2755 	  else if (cxx_dialect < cxx14)
2756 	    error ("non-type partial specialization %qD "
2757 		   "is not allowed", declarator);
2758 	  else
2759 	    error ("non-class, non-variable partial specialization %qD "
2760 		   "is not allowed", declarator);
2761 	  return decl;
2762 	ok:;
2763 	}
2764 
2765       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2766 	/* This is a specialization of a member template, without
2767 	   specialization the containing class.  Something like:
2768 
2769 	     template <class T> struct S {
2770 	       template <class U> void f (U);
2771 	     };
2772 	     template <> template <class U> void S<int>::f(U) {}
2773 
2774 	   That's a specialization -- but of the entire template.  */
2775 	specialization = 1;
2776       break;
2777 
2778     default:
2779       gcc_unreachable ();
2780     }
2781 
2782   if ((specialization || member_specialization)
2783       /* This doesn't apply to variable templates.  */
2784       && (TREE_CODE (TREE_TYPE (decl)) == FUNCTION_TYPE
2785           || TREE_CODE (TREE_TYPE (decl)) == METHOD_TYPE))
2786     {
2787       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2788       for (; t; t = TREE_CHAIN (t))
2789 	if (TREE_PURPOSE (t))
2790 	  {
2791 	    permerror (input_location,
2792 		       "default argument specified in explicit specialization");
2793 	    break;
2794 	  }
2795     }
2796 
2797   if (specialization || member_specialization || explicit_instantiation)
2798     {
2799       tree tmpl = NULL_TREE;
2800       tree targs = NULL_TREE;
2801       bool was_template_id = (TREE_CODE (declarator) == TEMPLATE_ID_EXPR);
2802 
2803       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2804       if (!was_template_id)
2805 	{
2806 	  tree fns;
2807 
2808 	  gcc_assert (identifier_p (declarator));
2809 	  if (ctype)
2810 	    fns = dname;
2811 	  else
2812 	    {
2813 	      /* If there is no class context, the explicit instantiation
2814 		 must be at namespace scope.  */
2815 	      gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2816 
2817 	      /* Find the namespace binding, using the declaration
2818 		 context.  */
2819 	      fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2820 					   false, true);
2821 	      if (fns == error_mark_node)
2822 		/* If lookup fails, look for a friend declaration so we can
2823 		   give a better diagnostic.  */
2824 		fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2825 					     /*type*/false, /*complain*/true,
2826 					     /*hidden*/true);
2827 
2828 	      if (fns == error_mark_node || !is_overloaded_fn (fns))
2829 		{
2830 		  error ("%qD is not a template function", dname);
2831 		  fns = error_mark_node;
2832 		}
2833 	    }
2834 
2835 	  declarator = lookup_template_function (fns, NULL_TREE);
2836 	}
2837 
2838       if (declarator == error_mark_node)
2839 	return error_mark_node;
2840 
2841       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2842 	{
2843 	  if (!explicit_instantiation)
2844 	    /* A specialization in class scope.  This is invalid,
2845 	       but the error will already have been flagged by
2846 	       check_specialization_scope.  */
2847 	    return error_mark_node;
2848 	  else
2849 	    {
2850 	      /* It's not valid to write an explicit instantiation in
2851 		 class scope, e.g.:
2852 
2853 		   class C { template void f(); }
2854 
2855 		   This case is caught by the parser.  However, on
2856 		   something like:
2857 
2858 		   template class C { void f(); };
2859 
2860 		   (which is invalid) we can get here.  The error will be
2861 		   issued later.  */
2862 	      ;
2863 	    }
2864 
2865 	  return decl;
2866 	}
2867       else if (ctype != NULL_TREE
2868 	       && (identifier_p (TREE_OPERAND (declarator, 0))))
2869 	{
2870 	  // We'll match variable templates in start_decl.
2871 	  if (VAR_P (decl))
2872 	    return decl;
2873 
2874 	  /* Find the list of functions in ctype that have the same
2875 	     name as the declared function.  */
2876 	  tree name = TREE_OPERAND (declarator, 0);
2877 	  tree fns = NULL_TREE;
2878 	  int idx;
2879 
2880 	  if (constructor_name_p (name, ctype))
2881 	    {
2882 	      int is_constructor = DECL_CONSTRUCTOR_P (decl);
2883 
2884 	      if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2885 		  : !CLASSTYPE_DESTRUCTORS (ctype))
2886 		{
2887 		  /* From [temp.expl.spec]:
2888 
2889 		     If such an explicit specialization for the member
2890 		     of a class template names an implicitly-declared
2891 		     special member function (clause _special_), the
2892 		     program is ill-formed.
2893 
2894 		     Similar language is found in [temp.explicit].  */
2895 		  error ("specialization of implicitly-declared special member function");
2896 		  return error_mark_node;
2897 		}
2898 
2899 	      name = is_constructor ? ctor_identifier : dtor_identifier;
2900 	    }
2901 
2902 	  if (!DECL_CONV_FN_P (decl))
2903 	    {
2904 	      idx = lookup_fnfields_1 (ctype, name);
2905 	      if (idx >= 0)
2906 		fns = (*CLASSTYPE_METHOD_VEC (ctype))[idx];
2907 	    }
2908 	  else
2909 	    {
2910 	      vec<tree, va_gc> *methods;
2911 	      tree ovl;
2912 
2913 	      /* For a type-conversion operator, we cannot do a
2914 		 name-based lookup.  We might be looking for `operator
2915 		 int' which will be a specialization of `operator T'.
2916 		 So, we find *all* the conversion operators, and then
2917 		 select from them.  */
2918 	      fns = NULL_TREE;
2919 
2920 	      methods = CLASSTYPE_METHOD_VEC (ctype);
2921 	      if (methods)
2922 		for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2923 		     methods->iterate (idx, &ovl);
2924 		     ++idx)
2925 		  {
2926 		    if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2927 		      /* There are no more conversion functions.  */
2928 		      break;
2929 
2930 		    /* Glue all these conversion functions together
2931 		       with those we already have.  */
2932 		    for (; ovl; ovl = OVL_NEXT (ovl))
2933 		      fns = ovl_cons (OVL_CURRENT (ovl), fns);
2934 		  }
2935 	    }
2936 
2937 	  if (fns == NULL_TREE)
2938 	    {
2939 	      error ("no member function %qD declared in %qT", name, ctype);
2940 	      return error_mark_node;
2941 	    }
2942 	  else
2943 	    TREE_OPERAND (declarator, 0) = fns;
2944 	}
2945 
2946       /* Figure out what exactly is being specialized at this point.
2947 	 Note that for an explicit instantiation, even one for a
2948 	 member function, we cannot tell apriori whether the
2949 	 instantiation is for a member template, or just a member
2950 	 function of a template class.  Even if a member template is
2951 	 being instantiated, the member template arguments may be
2952 	 elided if they can be deduced from the rest of the
2953 	 declaration.  */
2954       tmpl = determine_specialization (declarator, decl,
2955 				       &targs,
2956 				       member_specialization,
2957 				       template_count,
2958 				       tsk);
2959 
2960       if (!tmpl || tmpl == error_mark_node)
2961 	/* We couldn't figure out what this declaration was
2962 	   specializing.  */
2963 	return error_mark_node;
2964       else
2965 	{
2966 	  if (!ctype && !was_template_id
2967 	      && (specialization || member_specialization
2968 		  || explicit_instantiation)
2969 	      && !is_associated_namespace (CP_DECL_CONTEXT (decl),
2970 					   CP_DECL_CONTEXT (tmpl)))
2971 	    error ("%qD is not declared in %qD",
2972 		   tmpl, current_namespace);
2973 	  else if (TREE_CODE (decl) == FUNCTION_DECL
2974 		   && DECL_HIDDEN_FRIEND_P (tmpl))
2975 	    {
2976 	      if (pedwarn (DECL_SOURCE_LOCATION (decl), 0,
2977 			   "friend declaration %qD is not visible to "
2978 			   "explicit specialization", tmpl))
2979 		inform (DECL_SOURCE_LOCATION (tmpl),
2980 			"friend declaration here");
2981 	    }
2982 
2983 	  tree gen_tmpl = most_general_template (tmpl);
2984 
2985 	  if (explicit_instantiation)
2986 	    {
2987 	      /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2988 		 is done by do_decl_instantiation later.  */
2989 
2990 	      int arg_depth = TMPL_ARGS_DEPTH (targs);
2991 	      int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2992 
2993 	      if (arg_depth > parm_depth)
2994 		{
2995 		  /* If TMPL is not the most general template (for
2996 		     example, if TMPL is a friend template that is
2997 		     injected into namespace scope), then there will
2998 		     be too many levels of TARGS.  Remove some of them
2999 		     here.  */
3000 		  int i;
3001 		  tree new_targs;
3002 
3003 		  new_targs = make_tree_vec (parm_depth);
3004 		  for (i = arg_depth - parm_depth; i < arg_depth; ++i)
3005 		    TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
3006 		      = TREE_VEC_ELT (targs, i);
3007 		  targs = new_targs;
3008 		}
3009 
3010 	      return instantiate_template (tmpl, targs, tf_error);
3011 	    }
3012 
3013 	  /* If we thought that the DECL was a member function, but it
3014 	     turns out to be specializing a static member function,
3015 	     make DECL a static member function as well.  */
3016 	  if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3017 	      && DECL_STATIC_FUNCTION_P (tmpl)
3018 	      && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
3019 	    revert_static_member_fn (decl);
3020 
3021 	  /* If this is a specialization of a member template of a
3022 	     template class, we want to return the TEMPLATE_DECL, not
3023 	     the specialization of it.  */
3024 	  if (tsk == tsk_template && !was_template_id)
3025 	    {
3026 	      tree result = DECL_TEMPLATE_RESULT (tmpl);
3027 	      SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3028 	      DECL_INITIAL (result) = NULL_TREE;
3029 	      if (have_def)
3030 		{
3031 		  tree parm;
3032 		  DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
3033 		  DECL_SOURCE_LOCATION (result)
3034 		    = DECL_SOURCE_LOCATION (decl);
3035 		  /* We want to use the argument list specified in the
3036 		     definition, not in the original declaration.  */
3037 		  DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
3038 		  for (parm = DECL_ARGUMENTS (result); parm;
3039 		       parm = DECL_CHAIN (parm))
3040 		    DECL_CONTEXT (parm) = result;
3041 		}
3042 	      return register_specialization (tmpl, gen_tmpl, targs,
3043 					      is_friend, 0);
3044 	    }
3045 
3046 	  /* Set up the DECL_TEMPLATE_INFO for DECL.  */
3047 	  DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
3048 
3049 	  if (was_template_id)
3050 	    TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl)) = true;
3051 
3052 	  /* Inherit default function arguments from the template
3053 	     DECL is specializing.  */
3054 	  if (DECL_FUNCTION_TEMPLATE_P (tmpl))
3055 	    copy_default_args_to_explicit_spec (decl);
3056 
3057 	  /* This specialization has the same protection as the
3058 	     template it specializes.  */
3059 	  TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
3060 	  TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
3061 
3062           /* 7.1.1-1 [dcl.stc]
3063 
3064              A storage-class-specifier shall not be specified in an
3065              explicit specialization...
3066 
3067              The parser rejects these, so unless action is taken here,
3068              explicit function specializations will always appear with
3069              global linkage.
3070 
3071              The action recommended by the C++ CWG in response to C++
3072              defect report 605 is to make the storage class and linkage
3073              of the explicit specialization match the templated function:
3074 
3075              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
3076            */
3077           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
3078             {
3079               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
3080               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
3081 
3082               /* A concept cannot be specialized.  */
3083               if (DECL_DECLARED_CONCEPT_P (tmpl_func))
3084                 {
3085                   error ("explicit specialization of function concept %qD",
3086                          gen_tmpl);
3087                   return error_mark_node;
3088                 }
3089 
3090               /* This specialization has the same linkage and visibility as
3091                  the function template it specializes.  */
3092               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
3093 	      if (! TREE_PUBLIC (decl))
3094 		{
3095 		  DECL_INTERFACE_KNOWN (decl) = 1;
3096 		  DECL_NOT_REALLY_EXTERN (decl) = 1;
3097 		}
3098               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
3099               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
3100                 {
3101                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
3102                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
3103                 }
3104             }
3105 
3106 	  /* If DECL is a friend declaration, declared using an
3107 	     unqualified name, the namespace associated with DECL may
3108 	     have been set incorrectly.  For example, in:
3109 
3110 	       template <typename T> void f(T);
3111 	       namespace N {
3112 		 struct S { friend void f<int>(int); }
3113 	       }
3114 
3115 	     we will have set the DECL_CONTEXT for the friend
3116 	     declaration to N, rather than to the global namespace.  */
3117 	  if (DECL_NAMESPACE_SCOPE_P (decl))
3118 	    DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
3119 
3120 	  if (is_friend && !have_def)
3121 	    /* This is not really a declaration of a specialization.
3122 	       It's just the name of an instantiation.  But, it's not
3123 	       a request for an instantiation, either.  */
3124 	    SET_DECL_IMPLICIT_INSTANTIATION (decl);
3125 	  else if (TREE_CODE (decl) == FUNCTION_DECL)
3126 	    /* A specialization is not necessarily COMDAT.  */
3127 	    DECL_COMDAT (decl) = (TREE_PUBLIC (decl)
3128 				  && DECL_DECLARED_INLINE_P (decl));
3129 	  else if (VAR_P (decl))
3130 	    DECL_COMDAT (decl) = false;
3131 
3132 	  /* If this is a full specialization, register it so that we can find
3133 	     it again.  Partial specializations will be registered in
3134 	     process_partial_specialization.  */
3135 	  if (!processing_template_decl)
3136 	    decl = register_specialization (decl, gen_tmpl, targs,
3137 					    is_friend, 0);
3138 
3139 	  /* A 'structor should already have clones.  */
3140 	  gcc_assert (decl == error_mark_node
3141 		      || variable_template_p (tmpl)
3142 		      || !(DECL_CONSTRUCTOR_P (decl)
3143 			   || DECL_DESTRUCTOR_P (decl))
3144 		      || DECL_CLONED_FUNCTION_P (DECL_CHAIN (decl)));
3145 	}
3146     }
3147 
3148   return decl;
3149 }
3150 
3151 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
3152    parameters.  These are represented in the same format used for
3153    DECL_TEMPLATE_PARMS.  */
3154 
3155 int
comp_template_parms(const_tree parms1,const_tree parms2)3156 comp_template_parms (const_tree parms1, const_tree parms2)
3157 {
3158   const_tree p1;
3159   const_tree p2;
3160 
3161   if (parms1 == parms2)
3162     return 1;
3163 
3164   for (p1 = parms1, p2 = parms2;
3165        p1 != NULL_TREE && p2 != NULL_TREE;
3166        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
3167     {
3168       tree t1 = TREE_VALUE (p1);
3169       tree t2 = TREE_VALUE (p2);
3170       int i;
3171 
3172       gcc_assert (TREE_CODE (t1) == TREE_VEC);
3173       gcc_assert (TREE_CODE (t2) == TREE_VEC);
3174 
3175       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
3176 	return 0;
3177 
3178       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
3179 	{
3180           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
3181           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
3182 
3183           /* If either of the template parameters are invalid, assume
3184              they match for the sake of error recovery. */
3185           if (error_operand_p (parm1) || error_operand_p (parm2))
3186             return 1;
3187 
3188 	  if (TREE_CODE (parm1) != TREE_CODE (parm2))
3189 	    return 0;
3190 
3191 	  if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
3192               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
3193                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
3194 	    continue;
3195 	  else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
3196 	    return 0;
3197 	}
3198     }
3199 
3200   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
3201     /* One set of parameters has more parameters lists than the
3202        other.  */
3203     return 0;
3204 
3205   return 1;
3206 }
3207 
3208 /* Determine whether PARM is a parameter pack.  */
3209 
3210 bool
template_parameter_pack_p(const_tree parm)3211 template_parameter_pack_p (const_tree parm)
3212 {
3213   /* Determine if we have a non-type template parameter pack.  */
3214   if (TREE_CODE (parm) == PARM_DECL)
3215     return (DECL_TEMPLATE_PARM_P (parm)
3216             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
3217   if (TREE_CODE (parm) == TEMPLATE_PARM_INDEX)
3218     return TEMPLATE_PARM_PARAMETER_PACK (parm);
3219 
3220   /* If this is a list of template parameters, we could get a
3221      TYPE_DECL or a TEMPLATE_DECL.  */
3222   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
3223     parm = TREE_TYPE (parm);
3224 
3225   /* Otherwise it must be a type template parameter.  */
3226   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
3227 	   || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
3228 	  && TEMPLATE_TYPE_PARAMETER_PACK (parm));
3229 }
3230 
3231 /* Determine if T is a function parameter pack.  */
3232 
3233 bool
function_parameter_pack_p(const_tree t)3234 function_parameter_pack_p (const_tree t)
3235 {
3236   if (t && TREE_CODE (t) == PARM_DECL)
3237     return DECL_PACK_P (t);
3238   return false;
3239 }
3240 
3241 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
3242    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
3243 
3244 tree
get_function_template_decl(const_tree primary_func_tmpl_inst)3245 get_function_template_decl (const_tree primary_func_tmpl_inst)
3246 {
3247   if (! primary_func_tmpl_inst
3248       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
3249       || ! primary_template_instantiation_p (primary_func_tmpl_inst))
3250     return NULL;
3251 
3252   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
3253 }
3254 
3255 /* Return true iff the function parameter PARAM_DECL was expanded
3256    from the function parameter pack PACK.  */
3257 
3258 bool
function_parameter_expanded_from_pack_p(tree param_decl,tree pack)3259 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
3260 {
3261   if (DECL_ARTIFICIAL (param_decl)
3262       || !function_parameter_pack_p (pack))
3263     return false;
3264 
3265   /* The parameter pack and its pack arguments have the same
3266      DECL_PARM_INDEX.  */
3267   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
3268 }
3269 
3270 /* Determine whether ARGS describes a variadic template args list,
3271    i.e., one that is terminated by a template argument pack.  */
3272 
3273 static bool
template_args_variadic_p(tree args)3274 template_args_variadic_p (tree args)
3275 {
3276   int nargs;
3277   tree last_parm;
3278 
3279   if (args == NULL_TREE)
3280     return false;
3281 
3282   args = INNERMOST_TEMPLATE_ARGS (args);
3283   nargs = TREE_VEC_LENGTH (args);
3284 
3285   if (nargs == 0)
3286     return false;
3287 
3288   last_parm = TREE_VEC_ELT (args, nargs - 1);
3289 
3290   return ARGUMENT_PACK_P (last_parm);
3291 }
3292 
3293 /* Generate a new name for the parameter pack name NAME (an
3294    IDENTIFIER_NODE) that incorporates its */
3295 
3296 static tree
make_ith_pack_parameter_name(tree name,int i)3297 make_ith_pack_parameter_name (tree name, int i)
3298 {
3299   /* Munge the name to include the parameter index.  */
3300 #define NUMBUF_LEN 128
3301   char numbuf[NUMBUF_LEN];
3302   char* newname;
3303   int newname_len;
3304 
3305   if (name == NULL_TREE)
3306     return name;
3307   snprintf (numbuf, NUMBUF_LEN, "%i", i);
3308   newname_len = IDENTIFIER_LENGTH (name)
3309 	        + strlen (numbuf) + 2;
3310   newname = (char*)alloca (newname_len);
3311   snprintf (newname, newname_len,
3312 	    "%s#%i", IDENTIFIER_POINTER (name), i);
3313   return get_identifier (newname);
3314 }
3315 
3316 /* Return true if T is a primary function, class or alias template
3317    instantiation.  */
3318 
3319 bool
primary_template_instantiation_p(const_tree t)3320 primary_template_instantiation_p (const_tree t)
3321 {
3322   if (!t)
3323     return false;
3324 
3325   if (TREE_CODE (t) == FUNCTION_DECL)
3326     return DECL_LANG_SPECIFIC (t)
3327 	   && DECL_TEMPLATE_INSTANTIATION (t)
3328 	   && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t));
3329   else if (CLASS_TYPE_P (t) && !TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
3330     return CLASSTYPE_TEMPLATE_INSTANTIATION (t)
3331 	   && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t));
3332   else if (alias_template_specialization_p (t))
3333     return true;
3334   return false;
3335 }
3336 
3337 /* Return true if PARM is a template template parameter.  */
3338 
3339 bool
template_template_parameter_p(const_tree parm)3340 template_template_parameter_p (const_tree parm)
3341 {
3342   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
3343 }
3344 
3345 /* Return true iff PARM is a DECL representing a type template
3346    parameter.  */
3347 
3348 bool
template_type_parameter_p(const_tree parm)3349 template_type_parameter_p (const_tree parm)
3350 {
3351   return (parm
3352 	  && (TREE_CODE (parm) == TYPE_DECL
3353 	      || TREE_CODE (parm) == TEMPLATE_DECL)
3354 	  && DECL_TEMPLATE_PARM_P (parm));
3355 }
3356 
3357 /* Return the template parameters of T if T is a
3358    primary template instantiation, NULL otherwise.  */
3359 
3360 tree
get_primary_template_innermost_parameters(const_tree t)3361 get_primary_template_innermost_parameters (const_tree t)
3362 {
3363   tree parms = NULL, template_info = NULL;
3364 
3365   if ((template_info = get_template_info (t))
3366       && primary_template_instantiation_p (t))
3367     parms = INNERMOST_TEMPLATE_PARMS
3368 	(DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
3369 
3370   return parms;
3371 }
3372 
3373 /* Return the template parameters of the LEVELth level from the full list
3374    of template parameters PARMS.  */
3375 
3376 tree
get_template_parms_at_level(tree parms,int level)3377 get_template_parms_at_level (tree parms, int level)
3378 {
3379   tree p;
3380   if (!parms
3381       || TREE_CODE (parms) != TREE_LIST
3382       || level > TMPL_PARMS_DEPTH (parms))
3383     return NULL_TREE;
3384 
3385   for (p = parms; p; p = TREE_CHAIN (p))
3386     if (TMPL_PARMS_DEPTH (p) == level)
3387       return p;
3388 
3389   return NULL_TREE;
3390 }
3391 
3392 /* Returns the template arguments of T if T is a template instantiation,
3393    NULL otherwise.  */
3394 
3395 tree
get_template_innermost_arguments(const_tree t)3396 get_template_innermost_arguments (const_tree t)
3397 {
3398   tree args = NULL, template_info = NULL;
3399 
3400   if ((template_info = get_template_info (t))
3401       && TI_ARGS (template_info))
3402     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
3403 
3404   return args;
3405 }
3406 
3407 /* Return the argument pack elements of T if T is a template argument pack,
3408    NULL otherwise.  */
3409 
3410 tree
get_template_argument_pack_elems(const_tree t)3411 get_template_argument_pack_elems (const_tree t)
3412 {
3413   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
3414       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
3415     return NULL;
3416 
3417   return ARGUMENT_PACK_ARGS (t);
3418 }
3419 
3420 /* Structure used to track the progress of find_parameter_packs_r.  */
3421 struct find_parameter_pack_data
3422 {
3423   /* TREE_LIST that will contain all of the parameter packs found by
3424      the traversal.  */
3425   tree* parameter_packs;
3426 
3427   /* Set of AST nodes that have been visited by the traversal.  */
3428   hash_set<tree> *visited;
3429 
3430   /* True iff we're making a type pack expansion.  */
3431   bool type_pack_expansion_p;
3432 };
3433 
3434 /* Identifies all of the argument packs that occur in a template
3435    argument and appends them to the TREE_LIST inside DATA, which is a
3436    find_parameter_pack_data structure. This is a subroutine of
3437    make_pack_expansion and uses_parameter_packs.  */
3438 static tree
find_parameter_packs_r(tree * tp,int * walk_subtrees,void * data)3439 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
3440 {
3441   tree t = *tp;
3442   struct find_parameter_pack_data* ppd =
3443     (struct find_parameter_pack_data*)data;
3444   bool parameter_pack_p = false;
3445 
3446   /* Handle type aliases/typedefs.  */
3447   if (TYPE_ALIAS_P (t))
3448     {
3449       if (TYPE_TEMPLATE_INFO (t))
3450 	cp_walk_tree (&TYPE_TI_ARGS (t),
3451 		      &find_parameter_packs_r,
3452 		      ppd, ppd->visited);
3453       *walk_subtrees = 0;
3454       return NULL_TREE;
3455     }
3456 
3457   /* Identify whether this is a parameter pack or not.  */
3458   switch (TREE_CODE (t))
3459     {
3460     case TEMPLATE_PARM_INDEX:
3461       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3462         parameter_pack_p = true;
3463       break;
3464 
3465     case TEMPLATE_TYPE_PARM:
3466       t = TYPE_MAIN_VARIANT (t);
3467     case TEMPLATE_TEMPLATE_PARM:
3468       /* If the placeholder appears in the decl-specifier-seq of a function
3469 	 parameter pack (14.6.3), or the type-specifier-seq of a type-id that
3470 	 is a pack expansion, the invented template parameter is a template
3471 	 parameter pack.  */
3472       if (ppd->type_pack_expansion_p && is_auto_or_concept (t))
3473 	TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
3474       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3475         parameter_pack_p = true;
3476       break;
3477 
3478     case FIELD_DECL:
3479     case PARM_DECL:
3480       if (DECL_PACK_P (t))
3481         {
3482           /* We don't want to walk into the type of a PARM_DECL,
3483              because we don't want to see the type parameter pack.  */
3484           *walk_subtrees = 0;
3485 	  parameter_pack_p = true;
3486         }
3487       break;
3488 
3489       /* Look through a lambda capture proxy to the field pack.  */
3490     case VAR_DECL:
3491       if (DECL_HAS_VALUE_EXPR_P (t))
3492 	{
3493 	  tree v = DECL_VALUE_EXPR (t);
3494 	  cp_walk_tree (&v,
3495 			&find_parameter_packs_r,
3496 			ppd, ppd->visited);
3497 	  *walk_subtrees = 0;
3498 	}
3499       else if (variable_template_specialization_p (t))
3500 	{
3501 	  cp_walk_tree (&DECL_TI_ARGS (t),
3502 			find_parameter_packs_r,
3503 			ppd, ppd->visited);
3504 	  *walk_subtrees = 0;
3505 	}
3506       break;
3507 
3508     case BASES:
3509       parameter_pack_p = true;
3510       break;
3511     default:
3512       /* Not a parameter pack.  */
3513       break;
3514     }
3515 
3516   if (parameter_pack_p)
3517     {
3518       /* Add this parameter pack to the list.  */
3519       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
3520     }
3521 
3522   if (TYPE_P (t))
3523     cp_walk_tree (&TYPE_CONTEXT (t),
3524 		  &find_parameter_packs_r, ppd, ppd->visited);
3525 
3526   /* This switch statement will return immediately if we don't find a
3527      parameter pack.  */
3528   switch (TREE_CODE (t))
3529     {
3530     case TEMPLATE_PARM_INDEX:
3531       return NULL_TREE;
3532 
3533     case BOUND_TEMPLATE_TEMPLATE_PARM:
3534       /* Check the template itself.  */
3535       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)),
3536 		    &find_parameter_packs_r, ppd, ppd->visited);
3537       /* Check the template arguments.  */
3538       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd,
3539 		    ppd->visited);
3540       *walk_subtrees = 0;
3541       return NULL_TREE;
3542 
3543     case TEMPLATE_TYPE_PARM:
3544     case TEMPLATE_TEMPLATE_PARM:
3545       return NULL_TREE;
3546 
3547     case PARM_DECL:
3548       return NULL_TREE;
3549 
3550     case RECORD_TYPE:
3551       if (TYPE_PTRMEMFUNC_P (t))
3552 	return NULL_TREE;
3553       /* Fall through.  */
3554 
3555     case UNION_TYPE:
3556     case ENUMERAL_TYPE:
3557       if (TYPE_TEMPLATE_INFO (t))
3558 	cp_walk_tree (&TYPE_TI_ARGS (t),
3559 		      &find_parameter_packs_r, ppd, ppd->visited);
3560 
3561       *walk_subtrees = 0;
3562       return NULL_TREE;
3563 
3564     case TEMPLATE_DECL:
3565       if (!DECL_TEMPLATE_TEMPLATE_PARM_P (t))
3566 	return NULL_TREE;
3567       /* Fall through.  */
3568 
3569     case CONSTRUCTOR:
3570       cp_walk_tree (&TREE_TYPE (t),
3571 		    &find_parameter_packs_r, ppd, ppd->visited);
3572       return NULL_TREE;
3573 
3574     case TYPENAME_TYPE:
3575       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
3576                    ppd, ppd->visited);
3577       *walk_subtrees = 0;
3578       return NULL_TREE;
3579 
3580     case TYPE_PACK_EXPANSION:
3581     case EXPR_PACK_EXPANSION:
3582       *walk_subtrees = 0;
3583       return NULL_TREE;
3584 
3585     case INTEGER_TYPE:
3586       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r,
3587 		    ppd, ppd->visited);
3588       *walk_subtrees = 0;
3589       return NULL_TREE;
3590 
3591     case IDENTIFIER_NODE:
3592       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd,
3593 		    ppd->visited);
3594       *walk_subtrees = 0;
3595       return NULL_TREE;
3596 
3597     case DECLTYPE_TYPE:
3598       {
3599 	/* When traversing a DECLTYPE_TYPE_EXPR, we need to set
3600 	   type_pack_expansion_p to false so that any placeholders
3601 	   within the expression don't get marked as parameter packs.  */
3602 	bool type_pack_expansion_p = ppd->type_pack_expansion_p;
3603 	ppd->type_pack_expansion_p = false;
3604 	cp_walk_tree (&DECLTYPE_TYPE_EXPR (t), &find_parameter_packs_r,
3605 		      ppd, ppd->visited);
3606 	ppd->type_pack_expansion_p = type_pack_expansion_p;
3607 	*walk_subtrees = 0;
3608 	return NULL_TREE;
3609       }
3610 
3611     default:
3612       return NULL_TREE;
3613     }
3614 
3615   return NULL_TREE;
3616 }
3617 
3618 /* Determines if the expression or type T uses any parameter packs.  */
3619 bool
uses_parameter_packs(tree t)3620 uses_parameter_packs (tree t)
3621 {
3622   tree parameter_packs = NULL_TREE;
3623   struct find_parameter_pack_data ppd;
3624   ppd.parameter_packs = &parameter_packs;
3625   ppd.visited = new hash_set<tree>;
3626   ppd.type_pack_expansion_p = false;
3627   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3628   delete ppd.visited;
3629   return parameter_packs != NULL_TREE;
3630 }
3631 
3632 /* Turn ARG, which may be an expression, type, or a TREE_LIST
3633    representation a base-class initializer into a parameter pack
3634    expansion. If all goes well, the resulting node will be an
3635    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
3636    respectively.  */
3637 tree
make_pack_expansion(tree arg)3638 make_pack_expansion (tree arg)
3639 {
3640   tree result;
3641   tree parameter_packs = NULL_TREE;
3642   bool for_types = false;
3643   struct find_parameter_pack_data ppd;
3644 
3645   if (!arg || arg == error_mark_node)
3646     return arg;
3647 
3648   if (TREE_CODE (arg) == TREE_LIST && TREE_PURPOSE (arg))
3649     {
3650       /* A TREE_LIST with a non-null TREE_PURPOSE is for a base
3651          class initializer.  In this case, the TREE_PURPOSE will be a
3652          _TYPE node (representing the base class expansion we're
3653          initializing) and the TREE_VALUE will be a TREE_LIST
3654          containing the initialization arguments.
3655 
3656          The resulting expansion looks somewhat different from most
3657          expansions. Rather than returning just one _EXPANSION, we
3658          return a TREE_LIST whose TREE_PURPOSE is a
3659          TYPE_PACK_EXPANSION containing the bases that will be
3660          initialized.  The TREE_VALUE will be identical to the
3661          original TREE_VALUE, which is a list of arguments that will
3662          be passed to each base.  We do not introduce any new pack
3663          expansion nodes into the TREE_VALUE (although it is possible
3664          that some already exist), because the TREE_PURPOSE and
3665          TREE_VALUE all need to be expanded together with the same
3666          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3667          resulting TREE_PURPOSE will mention the parameter packs in
3668          both the bases and the arguments to the bases.  */
3669       tree purpose;
3670       tree value;
3671       tree parameter_packs = NULL_TREE;
3672 
3673       /* Determine which parameter packs will be used by the base
3674          class expansion.  */
3675       ppd.visited = new hash_set<tree>;
3676       ppd.parameter_packs = &parameter_packs;
3677       ppd.type_pack_expansion_p = true;
3678       gcc_assert (TYPE_P (TREE_PURPOSE (arg)));
3679       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r,
3680                     &ppd, ppd.visited);
3681 
3682       if (parameter_packs == NULL_TREE)
3683         {
3684           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
3685           delete ppd.visited;
3686           return error_mark_node;
3687         }
3688 
3689       if (TREE_VALUE (arg) != void_type_node)
3690         {
3691           /* Collect the sets of parameter packs used in each of the
3692              initialization arguments.  */
3693           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3694             {
3695               /* Determine which parameter packs will be expanded in this
3696                  argument.  */
3697               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r,
3698                             &ppd, ppd.visited);
3699             }
3700         }
3701 
3702       delete ppd.visited;
3703 
3704       /* Create the pack expansion type for the base type.  */
3705       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3706       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3707       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3708 
3709       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3710 	 they will rarely be compared to anything.  */
3711       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3712 
3713       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3714     }
3715 
3716   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3717     for_types = true;
3718 
3719   /* Build the PACK_EXPANSION_* node.  */
3720   result = for_types
3721      ? cxx_make_type (TYPE_PACK_EXPANSION)
3722      : make_node (EXPR_PACK_EXPANSION);
3723   SET_PACK_EXPANSION_PATTERN (result, arg);
3724   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3725     {
3726       /* Propagate type and const-expression information.  */
3727       TREE_TYPE (result) = TREE_TYPE (arg);
3728       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3729       /* Mark this read now, since the expansion might be length 0.  */
3730       mark_exp_read (arg);
3731     }
3732   else
3733     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3734        they will rarely be compared to anything.  */
3735     SET_TYPE_STRUCTURAL_EQUALITY (result);
3736 
3737   /* Determine which parameter packs will be expanded.  */
3738   ppd.parameter_packs = &parameter_packs;
3739   ppd.visited = new hash_set<tree>;
3740   ppd.type_pack_expansion_p = TYPE_P (arg);
3741   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3742   delete ppd.visited;
3743 
3744   /* Make sure we found some parameter packs.  */
3745   if (parameter_packs == NULL_TREE)
3746     {
3747       if (TYPE_P (arg))
3748         error ("expansion pattern %<%T%> contains no argument packs", arg);
3749       else
3750         error ("expansion pattern %<%E%> contains no argument packs", arg);
3751       return error_mark_node;
3752     }
3753   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
3754 
3755   PACK_EXPANSION_LOCAL_P (result) = at_function_scope_p ();
3756 
3757   return result;
3758 }
3759 
3760 /* Checks T for any "bare" parameter packs, which have not yet been
3761    expanded, and issues an error if any are found. This operation can
3762    only be done on full expressions or types (e.g., an expression
3763    statement, "if" condition, etc.), because we could have expressions like:
3764 
3765      foo(f(g(h(args)))...)
3766 
3767    where "args" is a parameter pack. check_for_bare_parameter_packs
3768    should not be called for the subexpressions args, h(args),
3769    g(h(args)), or f(g(h(args))), because we would produce erroneous
3770    error messages.
3771 
3772    Returns TRUE and emits an error if there were bare parameter packs,
3773    returns FALSE otherwise.  */
3774 bool
check_for_bare_parameter_packs(tree t)3775 check_for_bare_parameter_packs (tree t)
3776 {
3777   tree parameter_packs = NULL_TREE;
3778   struct find_parameter_pack_data ppd;
3779 
3780   if (!processing_template_decl || !t || t == error_mark_node)
3781     return false;
3782 
3783   if (TREE_CODE (t) == TYPE_DECL)
3784     t = TREE_TYPE (t);
3785 
3786   ppd.parameter_packs = &parameter_packs;
3787   ppd.visited = new hash_set<tree>;
3788   ppd.type_pack_expansion_p = false;
3789   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3790   delete ppd.visited;
3791 
3792   if (parameter_packs)
3793     {
3794       error ("parameter packs not expanded with %<...%>:");
3795       while (parameter_packs)
3796         {
3797           tree pack = TREE_VALUE (parameter_packs);
3798           tree name = NULL_TREE;
3799 
3800           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
3801               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
3802             name = TYPE_NAME (pack);
3803           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
3804             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
3805           else
3806             name = DECL_NAME (pack);
3807 
3808 	  if (name)
3809 	    inform (input_location, "        %qD", name);
3810 	  else
3811 	    inform (input_location, "        <anonymous>");
3812 
3813           parameter_packs = TREE_CHAIN (parameter_packs);
3814         }
3815 
3816       return true;
3817     }
3818 
3819   return false;
3820 }
3821 
3822 /* Expand any parameter packs that occur in the template arguments in
3823    ARGS.  */
3824 tree
expand_template_argument_pack(tree args)3825 expand_template_argument_pack (tree args)
3826 {
3827   tree result_args = NULL_TREE;
3828   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3829   int num_result_args = -1;
3830   int non_default_args_count = -1;
3831 
3832   /* First, determine if we need to expand anything, and the number of
3833      slots we'll need.  */
3834   for (in_arg = 0; in_arg < nargs; ++in_arg)
3835     {
3836       tree arg = TREE_VEC_ELT (args, in_arg);
3837       if (arg == NULL_TREE)
3838 	return args;
3839       if (ARGUMENT_PACK_P (arg))
3840         {
3841           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3842           if (num_result_args < 0)
3843             num_result_args = in_arg + num_packed;
3844           else
3845             num_result_args += num_packed;
3846         }
3847       else
3848         {
3849           if (num_result_args >= 0)
3850             num_result_args++;
3851         }
3852     }
3853 
3854   /* If no expansion is necessary, we're done.  */
3855   if (num_result_args < 0)
3856     return args;
3857 
3858   /* Expand arguments.  */
3859   result_args = make_tree_vec (num_result_args);
3860   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
3861     non_default_args_count =
3862       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
3863   for (in_arg = 0; in_arg < nargs; ++in_arg)
3864     {
3865       tree arg = TREE_VEC_ELT (args, in_arg);
3866       if (ARGUMENT_PACK_P (arg))
3867         {
3868           tree packed = ARGUMENT_PACK_ARGS (arg);
3869           int i, num_packed = TREE_VEC_LENGTH (packed);
3870           for (i = 0; i < num_packed; ++i, ++out_arg)
3871             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3872 	  if (non_default_args_count > 0)
3873 	    non_default_args_count += num_packed - 1;
3874         }
3875       else
3876         {
3877           TREE_VEC_ELT (result_args, out_arg) = arg;
3878           ++out_arg;
3879         }
3880     }
3881   if (non_default_args_count >= 0)
3882     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
3883   return result_args;
3884 }
3885 
3886 /* Checks if DECL shadows a template parameter.
3887 
3888    [temp.local]: A template-parameter shall not be redeclared within its
3889    scope (including nested scopes).
3890 
3891    Emits an error and returns TRUE if the DECL shadows a parameter,
3892    returns FALSE otherwise.  */
3893 
3894 bool
check_template_shadow(tree decl)3895 check_template_shadow (tree decl)
3896 {
3897   tree olddecl;
3898 
3899   /* If we're not in a template, we can't possibly shadow a template
3900      parameter.  */
3901   if (!current_template_parms)
3902     return true;
3903 
3904   /* Figure out what we're shadowing.  */
3905   if (TREE_CODE (decl) == OVERLOAD)
3906     decl = OVL_CURRENT (decl);
3907   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3908 
3909   /* If there's no previous binding for this name, we're not shadowing
3910      anything, let alone a template parameter.  */
3911   if (!olddecl)
3912     return true;
3913 
3914   /* If we're not shadowing a template parameter, we're done.  Note
3915      that OLDDECL might be an OVERLOAD (or perhaps even an
3916      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3917      node.  */
3918   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3919     return true;
3920 
3921   /* We check for decl != olddecl to avoid bogus errors for using a
3922      name inside a class.  We check TPFI to avoid duplicate errors for
3923      inline member templates.  */
3924   if (decl == olddecl
3925       || (DECL_TEMPLATE_PARM_P (decl)
3926 	  && TEMPLATE_PARMS_FOR_INLINE (current_template_parms)))
3927     return true;
3928 
3929   /* Don't complain about the injected class name, as we've already
3930      complained about the class itself.  */
3931   if (DECL_SELF_REFERENCE_P (decl))
3932     return false;
3933 
3934   if (DECL_TEMPLATE_PARM_P (decl))
3935     error ("declaration of template parameter %q+D shadows "
3936 	   "template parameter", decl);
3937   else
3938     error ("declaration of %q+#D shadows template parameter", decl);
3939   inform (DECL_SOURCE_LOCATION (olddecl),
3940 	  "template parameter %qD declared here", olddecl);
3941   return false;
3942 }
3943 
3944 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3945    ORIG_LEVEL, DECL, and TYPE.  */
3946 
3947 static tree
build_template_parm_index(int index,int level,int orig_level,tree decl,tree type)3948 build_template_parm_index (int index,
3949 			   int level,
3950 			   int orig_level,
3951 			   tree decl,
3952 			   tree type)
3953 {
3954   tree t = make_node (TEMPLATE_PARM_INDEX);
3955   TEMPLATE_PARM_IDX (t) = index;
3956   TEMPLATE_PARM_LEVEL (t) = level;
3957   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3958   TEMPLATE_PARM_DECL (t) = decl;
3959   TREE_TYPE (t) = type;
3960   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3961   TREE_READONLY (t) = TREE_READONLY (decl);
3962 
3963   return t;
3964 }
3965 
3966 /* Find the canonical type parameter for the given template type
3967    parameter.  Returns the canonical type parameter, which may be TYPE
3968    if no such parameter existed.  */
3969 
3970 static tree
canonical_type_parameter(tree type)3971 canonical_type_parameter (tree type)
3972 {
3973   tree list;
3974   int idx = TEMPLATE_TYPE_IDX (type);
3975   if (!canonical_template_parms)
3976     vec_alloc (canonical_template_parms, idx+1);
3977 
3978   while (canonical_template_parms->length () <= (unsigned)idx)
3979     vec_safe_push (canonical_template_parms, NULL_TREE);
3980 
3981   list = (*canonical_template_parms)[idx];
3982   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3983     list = TREE_CHAIN (list);
3984 
3985   if (list)
3986     return TREE_VALUE (list);
3987   else
3988     {
3989       (*canonical_template_parms)[idx]
3990 		= tree_cons (NULL_TREE, type,
3991 			     (*canonical_template_parms)[idx]);
3992       return type;
3993     }
3994 }
3995 
3996 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3997    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3998    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3999    new one is created.  */
4000 
4001 static tree
reduce_template_parm_level(tree index,tree type,int levels,tree args,tsubst_flags_t complain)4002 reduce_template_parm_level (tree index, tree type, int levels, tree args,
4003 			    tsubst_flags_t complain)
4004 {
4005   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
4006       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
4007 	  != TEMPLATE_PARM_LEVEL (index) - levels)
4008       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
4009     {
4010       tree orig_decl = TEMPLATE_PARM_DECL (index);
4011       tree decl, t;
4012 
4013       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
4014 			 TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
4015       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
4016       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
4017       DECL_ARTIFICIAL (decl) = 1;
4018       SET_DECL_TEMPLATE_PARM_P (decl);
4019 
4020       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
4021 				     TEMPLATE_PARM_LEVEL (index) - levels,
4022 				     TEMPLATE_PARM_ORIG_LEVEL (index),
4023 				     decl, type);
4024       TEMPLATE_PARM_DESCENDANTS (index) = t;
4025       TEMPLATE_PARM_PARAMETER_PACK (t)
4026 	= TEMPLATE_PARM_PARAMETER_PACK (index);
4027 
4028 	/* Template template parameters need this.  */
4029       if (TREE_CODE (decl) == TEMPLATE_DECL)
4030 	{
4031 	  DECL_TEMPLATE_RESULT (decl)
4032 	    = build_decl (DECL_SOURCE_LOCATION (decl),
4033 			  TYPE_DECL, DECL_NAME (decl), type);
4034 	  DECL_ARTIFICIAL (DECL_TEMPLATE_RESULT (decl)) = true;
4035 	  DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
4036 	    (DECL_TEMPLATE_PARMS (orig_decl), args, complain);
4037 	}
4038     }
4039 
4040   return TEMPLATE_PARM_DESCENDANTS (index);
4041 }
4042 
4043 /* Process information from new template parameter PARM and append it
4044    to the LIST being built.  This new parameter is a non-type
4045    parameter iff IS_NON_TYPE is true. This new parameter is a
4046    parameter pack iff IS_PARAMETER_PACK is true.  The location of PARM
4047    is in PARM_LOC.  */
4048 
4049 tree
process_template_parm(tree list,location_t parm_loc,tree parm,bool is_non_type,bool is_parameter_pack)4050 process_template_parm (tree list, location_t parm_loc, tree parm,
4051 		       bool is_non_type, bool is_parameter_pack)
4052 {
4053   tree decl = 0;
4054   int idx = 0;
4055 
4056   gcc_assert (TREE_CODE (parm) == TREE_LIST);
4057   tree defval = TREE_PURPOSE (parm);
4058   tree constr = TREE_TYPE (parm);
4059 
4060   if (list)
4061     {
4062       tree p = tree_last (list);
4063 
4064       if (p && TREE_VALUE (p) != error_mark_node)
4065         {
4066           p = TREE_VALUE (p);
4067           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
4068             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
4069           else
4070             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
4071         }
4072 
4073       ++idx;
4074     }
4075 
4076   if (is_non_type)
4077     {
4078       parm = TREE_VALUE (parm);
4079 
4080       SET_DECL_TEMPLATE_PARM_P (parm);
4081 
4082       if (TREE_TYPE (parm) != error_mark_node)
4083 	{
4084 	  /* [temp.param]
4085 
4086 	     The top-level cv-qualifiers on the template-parameter are
4087 	     ignored when determining its type.  */
4088 	  TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
4089 	  if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
4090 	    TREE_TYPE (parm) = error_mark_node;
4091 	  else if (uses_parameter_packs (TREE_TYPE (parm))
4092 		   && !is_parameter_pack
4093 		   /* If we're in a nested template parameter list, the template
4094 		      template parameter could be a parameter pack.  */
4095 		   && processing_template_parmlist == 1)
4096 	    {
4097 	      /* This template parameter is not a parameter pack, but it
4098 		 should be. Complain about "bare" parameter packs.  */
4099 	      check_for_bare_parameter_packs (TREE_TYPE (parm));
4100 
4101 	      /* Recover by calling this a parameter pack.  */
4102 	      is_parameter_pack = true;
4103 	    }
4104 	}
4105 
4106       /* A template parameter is not modifiable.  */
4107       TREE_CONSTANT (parm) = 1;
4108       TREE_READONLY (parm) = 1;
4109       decl = build_decl (parm_loc,
4110 			 CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
4111       TREE_CONSTANT (decl) = 1;
4112       TREE_READONLY (decl) = 1;
4113       DECL_INITIAL (parm) = DECL_INITIAL (decl)
4114 	= build_template_parm_index (idx, processing_template_decl,
4115 				     processing_template_decl,
4116 				     decl, TREE_TYPE (parm));
4117 
4118       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))
4119 	= is_parameter_pack;
4120     }
4121   else
4122     {
4123       tree t;
4124       parm = TREE_VALUE (TREE_VALUE (parm));
4125 
4126       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
4127 	{
4128 	  t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
4129 	  /* This is for distinguishing between real templates and template
4130 	     template parameters */
4131 	  TREE_TYPE (parm) = t;
4132 	  TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
4133 	  decl = parm;
4134 	}
4135       else
4136 	{
4137 	  t = cxx_make_type (TEMPLATE_TYPE_PARM);
4138 	  /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
4139 	  decl = build_decl (parm_loc,
4140 			     TYPE_DECL, parm, t);
4141 	}
4142 
4143       TYPE_NAME (t) = decl;
4144       TYPE_STUB_DECL (t) = decl;
4145       parm = decl;
4146       TEMPLATE_TYPE_PARM_INDEX (t)
4147 	= build_template_parm_index (idx, processing_template_decl,
4148 				     processing_template_decl,
4149 				     decl, TREE_TYPE (parm));
4150       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
4151       TYPE_CANONICAL (t) = canonical_type_parameter (t);
4152     }
4153   DECL_ARTIFICIAL (decl) = 1;
4154   SET_DECL_TEMPLATE_PARM_P (decl);
4155 
4156   /* Build requirements for the type/template parameter.
4157      This must be done after SET_DECL_TEMPLATE_PARM_P or
4158      process_template_parm could fail. */
4159   tree reqs = finish_shorthand_constraint (parm, constr);
4160 
4161   pushdecl (decl);
4162 
4163   /* Build the parameter node linking the parameter declaration,
4164      its default argument (if any), and its constraints (if any). */
4165   parm = build_tree_list (defval, parm);
4166   TEMPLATE_PARM_CONSTRAINTS (parm) = reqs;
4167 
4168   return chainon (list, parm);
4169 }
4170 
4171 /* The end of a template parameter list has been reached.  Process the
4172    tree list into a parameter vector, converting each parameter into a more
4173    useful form.	 Type parameters are saved as IDENTIFIER_NODEs, and others
4174    as PARM_DECLs.  */
4175 
4176 tree
end_template_parm_list(tree parms)4177 end_template_parm_list (tree parms)
4178 {
4179   int nparms;
4180   tree parm, next;
4181   tree saved_parmlist = make_tree_vec (list_length (parms));
4182 
4183   /* Pop the dummy parameter level and add the real one.  */
4184   current_template_parms = TREE_CHAIN (current_template_parms);
4185 
4186   current_template_parms
4187     = tree_cons (size_int (processing_template_decl),
4188 		 saved_parmlist, current_template_parms);
4189 
4190   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
4191     {
4192       next = TREE_CHAIN (parm);
4193       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
4194       TREE_CHAIN (parm) = NULL_TREE;
4195     }
4196 
4197   --processing_template_parmlist;
4198 
4199   return saved_parmlist;
4200 }
4201 
4202 // Explicitly indicate the end of the template parameter list. We assume
4203 // that the current template parameters have been constructed and/or
4204 // managed explicitly, as when creating new template template parameters
4205 // from a shorthand constraint.
4206 void
end_template_parm_list()4207 end_template_parm_list ()
4208 {
4209   --processing_template_parmlist;
4210 }
4211 
4212 /* end_template_decl is called after a template declaration is seen.  */
4213 
4214 void
end_template_decl(void)4215 end_template_decl (void)
4216 {
4217   reset_specialization ();
4218 
4219   if (! processing_template_decl)
4220     return;
4221 
4222   /* This matches the pushlevel in begin_template_parm_list.  */
4223   finish_scope ();
4224 
4225   --processing_template_decl;
4226   current_template_parms = TREE_CHAIN (current_template_parms);
4227 }
4228 
4229 /* Takes a TREE_LIST representing a template parameter and convert it
4230    into an argument suitable to be passed to the type substitution
4231    functions.  Note that If the TREE_LIST contains an error_mark
4232    node, the returned argument is error_mark_node.  */
4233 
4234 tree
template_parm_to_arg(tree t)4235 template_parm_to_arg (tree t)
4236 {
4237 
4238   if (t == NULL_TREE
4239       || TREE_CODE (t) != TREE_LIST)
4240     return t;
4241 
4242   if (error_operand_p (TREE_VALUE (t)))
4243     return error_mark_node;
4244 
4245   t = TREE_VALUE (t);
4246 
4247   if (TREE_CODE (t) == TYPE_DECL
4248       || TREE_CODE (t) == TEMPLATE_DECL)
4249     {
4250       t = TREE_TYPE (t);
4251 
4252       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
4253 	{
4254 	  /* Turn this argument into a TYPE_ARGUMENT_PACK
4255 	     with a single element, which expands T.  */
4256 	  tree vec = make_tree_vec (1);
4257 	  if (CHECKING_P)
4258 	    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4259 
4260 	  TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4261 
4262 	  t = cxx_make_type (TYPE_ARGUMENT_PACK);
4263 	  SET_ARGUMENT_PACK_ARGS (t, vec);
4264 	}
4265     }
4266   else
4267     {
4268       t = DECL_INITIAL (t);
4269 
4270       if (TEMPLATE_PARM_PARAMETER_PACK (t))
4271 	{
4272 	  /* Turn this argument into a NONTYPE_ARGUMENT_PACK
4273 	     with a single element, which expands T.  */
4274 	  tree vec = make_tree_vec (1);
4275 	  tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
4276 	  if (CHECKING_P)
4277 	    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (vec, TREE_VEC_LENGTH (vec));
4278 
4279 	  t = convert_from_reference (t);
4280 	  TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
4281 
4282 	  t  = make_node (NONTYPE_ARGUMENT_PACK);
4283 	  SET_ARGUMENT_PACK_ARGS (t, vec);
4284 	  TREE_TYPE (t) = type;
4285 	}
4286       else
4287 	t = convert_from_reference (t);
4288     }
4289   return t;
4290 }
4291 
4292 /* Given a set of template parameters, return them as a set of template
4293    arguments.  The template parameters are represented as a TREE_VEC, in
4294    the form documented in cp-tree.h for template arguments.  */
4295 
4296 static tree
template_parms_to_args(tree parms)4297 template_parms_to_args (tree parms)
4298 {
4299   tree header;
4300   tree args = NULL_TREE;
4301   int length = TMPL_PARMS_DEPTH (parms);
4302   int l = length;
4303 
4304   /* If there is only one level of template parameters, we do not
4305      create a TREE_VEC of TREE_VECs.  Instead, we return a single
4306      TREE_VEC containing the arguments.  */
4307   if (length > 1)
4308     args = make_tree_vec (length);
4309 
4310   for (header = parms; header; header = TREE_CHAIN (header))
4311     {
4312       tree a = copy_node (TREE_VALUE (header));
4313       int i;
4314 
4315       TREE_TYPE (a) = NULL_TREE;
4316       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
4317 	TREE_VEC_ELT (a, i) = template_parm_to_arg (TREE_VEC_ELT (a, i));
4318 
4319       if (CHECKING_P)
4320 	SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
4321 
4322       if (length > 1)
4323 	TREE_VEC_ELT (args, --l) = a;
4324       else
4325 	args = a;
4326     }
4327 
4328   return args;
4329 }
4330 
4331 /* Within the declaration of a template, return the currently active
4332    template parameters as an argument TREE_VEC.  */
4333 
4334 static tree
current_template_args(void)4335 current_template_args (void)
4336 {
4337   return template_parms_to_args (current_template_parms);
4338 }
4339 
4340 /* Update the declared TYPE by doing any lookups which were thought to be
4341    dependent, but are not now that we know the SCOPE of the declarator.  */
4342 
4343 tree
maybe_update_decl_type(tree orig_type,tree scope)4344 maybe_update_decl_type (tree orig_type, tree scope)
4345 {
4346   tree type = orig_type;
4347 
4348   if (type == NULL_TREE)
4349     return type;
4350 
4351   if (TREE_CODE (orig_type) == TYPE_DECL)
4352     type = TREE_TYPE (type);
4353 
4354   if (scope && TYPE_P (scope) && dependent_type_p (scope)
4355       && dependent_type_p (type)
4356       /* Don't bother building up the args in this case.  */
4357       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
4358     {
4359       /* tsubst in the args corresponding to the template parameters,
4360 	 including auto if present.  Most things will be unchanged, but
4361 	 make_typename_type and tsubst_qualified_id will resolve
4362 	 TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
4363       tree args = current_template_args ();
4364       tree auto_node = type_uses_auto (type);
4365       tree pushed;
4366       if (auto_node)
4367 	{
4368 	  tree auto_vec = make_tree_vec (1);
4369 	  TREE_VEC_ELT (auto_vec, 0) = auto_node;
4370 	  args = add_to_template_args (args, auto_vec);
4371 	}
4372       pushed = push_scope (scope);
4373       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
4374       if (pushed)
4375 	pop_scope (scope);
4376     }
4377 
4378   if (type == error_mark_node)
4379     return orig_type;
4380 
4381   if (TREE_CODE (orig_type) == TYPE_DECL)
4382     {
4383       if (same_type_p (type, TREE_TYPE (orig_type)))
4384 	type = orig_type;
4385       else
4386 	type = TYPE_NAME (type);
4387     }
4388   return type;
4389 }
4390 
4391 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
4392    template PARMS and constraints, CONSTR.  If MEMBER_TEMPLATE_P is true,
4393    the new  template is a member template. */
4394 
4395 tree
build_template_decl(tree decl,tree parms,bool member_template_p)4396 build_template_decl (tree decl, tree parms, bool member_template_p)
4397 {
4398   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
4399   DECL_TEMPLATE_PARMS (tmpl) = parms;
4400   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
4401   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
4402   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
4403 
4404   return tmpl;
4405 }
4406 
4407 struct template_parm_data
4408 {
4409   /* The level of the template parameters we are currently
4410      processing.  */
4411   int level;
4412 
4413   /* The index of the specialization argument we are currently
4414      processing.  */
4415   int current_arg;
4416 
4417   /* An array whose size is the number of template parameters.  The
4418      elements are nonzero if the parameter has been used in any one
4419      of the arguments processed so far.  */
4420   int* parms;
4421 
4422   /* An array whose size is the number of template arguments.  The
4423      elements are nonzero if the argument makes use of template
4424      parameters of this level.  */
4425   int* arg_uses_template_parms;
4426 };
4427 
4428 /* Subroutine of push_template_decl used to see if each template
4429    parameter in a partial specialization is used in the explicit
4430    argument list.  If T is of the LEVEL given in DATA (which is
4431    treated as a template_parm_data*), then DATA->PARMS is marked
4432    appropriately.  */
4433 
4434 static int
mark_template_parm(tree t,void * data)4435 mark_template_parm (tree t, void* data)
4436 {
4437   int level;
4438   int idx;
4439   struct template_parm_data* tpd = (struct template_parm_data*) data;
4440 
4441   template_parm_level_and_index (t, &level, &idx);
4442 
4443   if (level == tpd->level)
4444     {
4445       tpd->parms[idx] = 1;
4446       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
4447     }
4448 
4449   /* Return zero so that for_each_template_parm will continue the
4450      traversal of the tree; we want to mark *every* template parm.  */
4451   return 0;
4452 }
4453 
4454 /* Process the partial specialization DECL.  */
4455 
4456 static tree
process_partial_specialization(tree decl)4457 process_partial_specialization (tree decl)
4458 {
4459   tree type = TREE_TYPE (decl);
4460   tree tinfo = get_template_info (decl);
4461   tree maintmpl = TI_TEMPLATE (tinfo);
4462   tree specargs = TI_ARGS (tinfo);
4463   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
4464   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
4465   tree inner_parms;
4466   tree inst;
4467   int nargs = TREE_VEC_LENGTH (inner_args);
4468   int ntparms;
4469   int  i;
4470   bool did_error_intro = false;
4471   struct template_parm_data tpd;
4472   struct template_parm_data tpd2;
4473 
4474   gcc_assert (current_template_parms);
4475 
4476   /* A concept cannot be specialized.  */
4477   if (flag_concepts && variable_concept_p (maintmpl))
4478     {
4479       error ("specialization of variable concept %q#D", maintmpl);
4480       return error_mark_node;
4481     }
4482 
4483   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
4484   ntparms = TREE_VEC_LENGTH (inner_parms);
4485 
4486   /* We check that each of the template parameters given in the
4487      partial specialization is used in the argument list to the
4488      specialization.  For example:
4489 
4490        template <class T> struct S;
4491        template <class T> struct S<T*>;
4492 
4493      The second declaration is OK because `T*' uses the template
4494      parameter T, whereas
4495 
4496        template <class T> struct S<int>;
4497 
4498      is no good.  Even trickier is:
4499 
4500        template <class T>
4501        struct S1
4502        {
4503 	  template <class U>
4504 	  struct S2;
4505 	  template <class U>
4506 	  struct S2<T>;
4507        };
4508 
4509      The S2<T> declaration is actually invalid; it is a
4510      full-specialization.  Of course,
4511 
4512 	  template <class U>
4513 	  struct S2<T (*)(U)>;
4514 
4515      or some such would have been OK.  */
4516   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
4517   tpd.parms = XALLOCAVEC (int, ntparms);
4518   memset (tpd.parms, 0, sizeof (int) * ntparms);
4519 
4520   tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4521   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
4522   for (i = 0; i < nargs; ++i)
4523     {
4524       tpd.current_arg = i;
4525       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
4526 			      &mark_template_parm,
4527 			      &tpd,
4528 			      NULL,
4529 			      /*include_nondeduced_p=*/false);
4530     }
4531   for (i = 0; i < ntparms; ++i)
4532     if (tpd.parms[i] == 0)
4533       {
4534 	/* One of the template parms was not used in a deduced context in the
4535 	   specialization.  */
4536 	if (!did_error_intro)
4537 	  {
4538 	    error ("template parameters not deducible in "
4539 		   "partial specialization:");
4540 	    did_error_intro = true;
4541 	  }
4542 
4543 	inform (input_location, "        %qD",
4544 		TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
4545       }
4546 
4547   if (did_error_intro)
4548     return error_mark_node;
4549 
4550   /* [temp.class.spec]
4551 
4552      The argument list of the specialization shall not be identical to
4553      the implicit argument list of the primary template.  */
4554   tree main_args
4555     = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (maintmpl)));
4556   if (comp_template_args (inner_args, INNERMOST_TEMPLATE_ARGS (main_args))
4557       && (!flag_concepts
4558 	  || !strictly_subsumes (current_template_constraints (),
4559 				 get_constraints (maintmpl))))
4560     {
4561       if (!flag_concepts)
4562         error ("partial specialization %q+D does not specialize "
4563 	       "any template arguments", decl);
4564       else
4565         error ("partial specialization %q+D does not specialize any "
4566 	       "template arguments and is not more constrained than", decl);
4567       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
4568     }
4569 
4570   /* A partial specialization that replaces multiple parameters of the
4571      primary template with a pack expansion is less specialized for those
4572      parameters.  */
4573   if (nargs < DECL_NTPARMS (maintmpl))
4574     {
4575       error ("partial specialization is not more specialized than the "
4576 	     "primary template because it replaces multiple parameters "
4577 	     "with a pack expansion");
4578       inform (DECL_SOURCE_LOCATION (maintmpl), "primary template here");
4579       return decl;
4580     }
4581 
4582   /* [temp.class.spec]
4583 
4584      A partially specialized non-type argument expression shall not
4585      involve template parameters of the partial specialization except
4586      when the argument expression is a simple identifier.
4587 
4588      The type of a template parameter corresponding to a specialized
4589      non-type argument shall not be dependent on a parameter of the
4590      specialization.
4591 
4592      Also, we verify that pack expansions only occur at the
4593      end of the argument list.  */
4594   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
4595   tpd2.parms = 0;
4596   for (i = 0; i < nargs; ++i)
4597     {
4598       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
4599       tree arg = TREE_VEC_ELT (inner_args, i);
4600       tree packed_args = NULL_TREE;
4601       int j, len = 1;
4602 
4603       if (ARGUMENT_PACK_P (arg))
4604         {
4605           /* Extract the arguments from the argument pack. We'll be
4606              iterating over these in the following loop.  */
4607           packed_args = ARGUMENT_PACK_ARGS (arg);
4608           len = TREE_VEC_LENGTH (packed_args);
4609         }
4610 
4611       for (j = 0; j < len; j++)
4612         {
4613           if (packed_args)
4614             /* Get the Jth argument in the parameter pack.  */
4615             arg = TREE_VEC_ELT (packed_args, j);
4616 
4617           if (PACK_EXPANSION_P (arg))
4618             {
4619               /* Pack expansions must come at the end of the
4620                  argument list.  */
4621               if ((packed_args && j < len - 1)
4622                   || (!packed_args && i < nargs - 1))
4623                 {
4624                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4625                     error ("parameter pack argument %qE must be at the "
4626 			   "end of the template argument list", arg);
4627                   else
4628                     error ("parameter pack argument %qT must be at the "
4629 			   "end of the template argument list", arg);
4630                 }
4631             }
4632 
4633           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4634             /* We only care about the pattern.  */
4635             arg = PACK_EXPANSION_PATTERN (arg);
4636 
4637           if (/* These first two lines are the `non-type' bit.  */
4638               !TYPE_P (arg)
4639               && TREE_CODE (arg) != TEMPLATE_DECL
4640               /* This next two lines are the `argument expression is not just a
4641                  simple identifier' condition and also the `specialized
4642                  non-type argument' bit.  */
4643               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX
4644 	      && !(REFERENCE_REF_P (arg)
4645 		   && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_PARM_INDEX))
4646             {
4647               if ((!packed_args && tpd.arg_uses_template_parms[i])
4648                   || (packed_args && uses_template_parms (arg)))
4649                 error ("template argument %qE involves template parameter(s)",
4650                        arg);
4651               else
4652                 {
4653                   /* Look at the corresponding template parameter,
4654                      marking which template parameters its type depends
4655                      upon.  */
4656                   tree type = TREE_TYPE (parm);
4657 
4658                   if (!tpd2.parms)
4659                     {
4660                       /* We haven't yet initialized TPD2.  Do so now.  */
4661                       tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4662                       /* The number of parameters here is the number in the
4663                          main template, which, as checked in the assertion
4664                          above, is NARGS.  */
4665                       tpd2.parms = XALLOCAVEC (int, nargs);
4666                       tpd2.level =
4667                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
4668                     }
4669 
4670                   /* Mark the template parameters.  But this time, we're
4671                      looking for the template parameters of the main
4672                      template, not in the specialization.  */
4673                   tpd2.current_arg = i;
4674                   tpd2.arg_uses_template_parms[i] = 0;
4675                   memset (tpd2.parms, 0, sizeof (int) * nargs);
4676                   for_each_template_parm (type,
4677                                           &mark_template_parm,
4678                                           &tpd2,
4679                                           NULL,
4680 					  /*include_nondeduced_p=*/false);
4681 
4682                   if (tpd2.arg_uses_template_parms [i])
4683                     {
4684                       /* The type depended on some template parameters.
4685                          If they are fully specialized in the
4686                          specialization, that's OK.  */
4687                       int j;
4688                       int count = 0;
4689                       for (j = 0; j < nargs; ++j)
4690                         if (tpd2.parms[j] != 0
4691                             && tpd.arg_uses_template_parms [j])
4692                           ++count;
4693                       if (count != 0)
4694                         error_n (input_location, count,
4695                                  "type %qT of template argument %qE depends "
4696                                  "on a template parameter",
4697                                  "type %qT of template argument %qE depends "
4698                                  "on template parameters",
4699                                  type,
4700                                  arg);
4701                     }
4702                 }
4703             }
4704         }
4705     }
4706 
4707   /* We should only get here once.  */
4708   if (TREE_CODE (decl) == TYPE_DECL)
4709     gcc_assert (!COMPLETE_TYPE_P (type));
4710 
4711   // Build the template decl.
4712   tree tmpl = build_template_decl (decl, current_template_parms,
4713 				   DECL_MEMBER_TEMPLATE_P (maintmpl));
4714   TREE_TYPE (tmpl) = type;
4715   DECL_TEMPLATE_RESULT (tmpl) = decl;
4716   SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4717   DECL_TEMPLATE_INFO (tmpl) = build_template_info (maintmpl, specargs);
4718   DECL_PRIMARY_TEMPLATE (tmpl) = maintmpl;
4719 
4720   if (VAR_P (decl))
4721     /* We didn't register this in check_explicit_specialization so we could
4722        wait until the constraints were set.  */
4723     decl = register_specialization (decl, maintmpl, specargs, false, 0);
4724   else
4725     associate_classtype_constraints (type);
4726 
4727   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
4728     = tree_cons (specargs, tmpl,
4729                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
4730   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
4731 
4732   for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
4733        inst = TREE_CHAIN (inst))
4734     {
4735       tree instance = TREE_VALUE (inst);
4736       if (TYPE_P (instance)
4737 	  ? (COMPLETE_TYPE_P (instance)
4738 	     && CLASSTYPE_IMPLICIT_INSTANTIATION (instance))
4739 	  : DECL_TEMPLATE_INSTANTIATION (instance))
4740 	{
4741 	  tree spec = most_specialized_partial_spec (instance, tf_none);
4742 	  tree inst_decl = (DECL_P (instance)
4743 			    ? instance : TYPE_NAME (instance));
4744 	  if (!spec)
4745 	    /* OK */;
4746 	  else if (spec == error_mark_node)
4747 	    permerror (input_location,
4748 		       "declaration of %qD ambiguates earlier template "
4749 		       "instantiation for %qD", decl, inst_decl);
4750 	  else if (TREE_VALUE (spec) == tmpl)
4751 	    permerror (input_location,
4752 		       "partial specialization of %qD after instantiation "
4753 		       "of %qD", decl, inst_decl);
4754 	}
4755     }
4756 
4757   return decl;
4758 }
4759 
4760 /* PARM is a template parameter of some form; return the corresponding
4761    TEMPLATE_PARM_INDEX.  */
4762 
4763 static tree
get_template_parm_index(tree parm)4764 get_template_parm_index (tree parm)
4765 {
4766   if (TREE_CODE (parm) == PARM_DECL
4767       || TREE_CODE (parm) == CONST_DECL)
4768     parm = DECL_INITIAL (parm);
4769   else if (TREE_CODE (parm) == TYPE_DECL
4770 	   || TREE_CODE (parm) == TEMPLATE_DECL)
4771     parm = TREE_TYPE (parm);
4772   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
4773       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM
4774       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
4775     parm = TEMPLATE_TYPE_PARM_INDEX (parm);
4776   gcc_assert (TREE_CODE (parm) == TEMPLATE_PARM_INDEX);
4777   return parm;
4778 }
4779 
4780 /* Subroutine of fixed_parameter_pack_p below.  Look for any template
4781    parameter packs used by the template parameter PARM.  */
4782 
4783 static void
fixed_parameter_pack_p_1(tree parm,struct find_parameter_pack_data * ppd)4784 fixed_parameter_pack_p_1 (tree parm, struct find_parameter_pack_data *ppd)
4785 {
4786   /* A type parm can't refer to another parm.  */
4787   if (TREE_CODE (parm) == TYPE_DECL)
4788     return;
4789   else if (TREE_CODE (parm) == PARM_DECL)
4790     {
4791       cp_walk_tree (&TREE_TYPE (parm), &find_parameter_packs_r,
4792 		    ppd, ppd->visited);
4793       return;
4794     }
4795 
4796   gcc_assert (TREE_CODE (parm) == TEMPLATE_DECL);
4797 
4798   tree vec = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
4799   for (int i = 0; i < TREE_VEC_LENGTH (vec); ++i)
4800     fixed_parameter_pack_p_1 (TREE_VALUE (TREE_VEC_ELT (vec, i)), ppd);
4801 }
4802 
4803 /* PARM is a template parameter pack.  Return any parameter packs used in
4804    its type or the type of any of its template parameters.  If there are
4805    any such packs, it will be instantiated into a fixed template parameter
4806    list by partial instantiation rather than be fully deduced.  */
4807 
4808 tree
fixed_parameter_pack_p(tree parm)4809 fixed_parameter_pack_p (tree parm)
4810 {
4811   /* This can only be true in a member template.  */
4812   if (TEMPLATE_PARM_ORIG_LEVEL (get_template_parm_index (parm)) < 2)
4813     return NULL_TREE;
4814   /* This can only be true for a parameter pack.  */
4815   if (!template_parameter_pack_p (parm))
4816     return NULL_TREE;
4817   /* A type parm can't refer to another parm.  */
4818   if (TREE_CODE (parm) == TYPE_DECL)
4819     return NULL_TREE;
4820 
4821   tree parameter_packs = NULL_TREE;
4822   struct find_parameter_pack_data ppd;
4823   ppd.parameter_packs = &parameter_packs;
4824   ppd.visited = new hash_set<tree>;
4825   ppd.type_pack_expansion_p = false;
4826 
4827   fixed_parameter_pack_p_1 (parm, &ppd);
4828 
4829   delete ppd.visited;
4830   return parameter_packs;
4831 }
4832 
4833 /* Check that a template declaration's use of default arguments and
4834    parameter packs is not invalid.  Here, PARMS are the template
4835    parameters.  IS_PRIMARY is true if DECL is the thing declared by
4836    a primary template.  IS_PARTIAL is true if DECL is a partial
4837    specialization.
4838 
4839    IS_FRIEND_DECL is nonzero if DECL is a friend function template
4840    declaration (but not a definition); 1 indicates a declaration, 2
4841    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
4842    emitted for extraneous default arguments.
4843 
4844    Returns TRUE if there were no errors found, FALSE otherwise. */
4845 
4846 bool
check_default_tmpl_args(tree decl,tree parms,bool is_primary,bool is_partial,int is_friend_decl)4847 check_default_tmpl_args (tree decl, tree parms, bool is_primary,
4848                          bool is_partial, int is_friend_decl)
4849 {
4850   const char *msg;
4851   int last_level_to_check;
4852   tree parm_level;
4853   bool no_errors = true;
4854 
4855   /* [temp.param]
4856 
4857      A default template-argument shall not be specified in a
4858      function template declaration or a function template definition, nor
4859      in the template-parameter-list of the definition of a member of a
4860      class template.  */
4861 
4862   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL
4863       || (TREE_CODE (decl) == FUNCTION_DECL && DECL_LOCAL_FUNCTION_P (decl)))
4864     /* You can't have a function template declaration in a local
4865        scope, nor you can you define a member of a class template in a
4866        local scope.  */
4867     return true;
4868 
4869   if ((TREE_CODE (decl) == TYPE_DECL
4870        && TREE_TYPE (decl)
4871        && LAMBDA_TYPE_P (TREE_TYPE (decl)))
4872       || (TREE_CODE (decl) == FUNCTION_DECL
4873 	  && LAMBDA_FUNCTION_P (decl)))
4874     /* A lambda doesn't have an explicit declaration; don't complain
4875        about the parms of the enclosing class.  */
4876     return true;
4877 
4878   if (current_class_type
4879       && !TYPE_BEING_DEFINED (current_class_type)
4880       && DECL_LANG_SPECIFIC (decl)
4881       && DECL_DECLARES_FUNCTION_P (decl)
4882       /* If this is either a friend defined in the scope of the class
4883 	 or a member function.  */
4884       && (DECL_FUNCTION_MEMBER_P (decl)
4885 	  ? same_type_p (DECL_CONTEXT (decl), current_class_type)
4886 	  : DECL_FRIEND_CONTEXT (decl)
4887 	  ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
4888 	  : false)
4889       /* And, if it was a member function, it really was defined in
4890 	 the scope of the class.  */
4891       && (!DECL_FUNCTION_MEMBER_P (decl)
4892 	  || DECL_INITIALIZED_IN_CLASS_P (decl)))
4893     /* We already checked these parameters when the template was
4894        declared, so there's no need to do it again now.  This function
4895        was defined in class scope, but we're processing its body now
4896        that the class is complete.  */
4897     return true;
4898 
4899   /* Core issue 226 (C++0x only): the following only applies to class
4900      templates.  */
4901   if (is_primary
4902       && ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL))
4903     {
4904       /* [temp.param]
4905 
4906          If a template-parameter has a default template-argument, all
4907          subsequent template-parameters shall have a default
4908          template-argument supplied.  */
4909       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
4910         {
4911           tree inner_parms = TREE_VALUE (parm_level);
4912           int ntparms = TREE_VEC_LENGTH (inner_parms);
4913           int seen_def_arg_p = 0;
4914           int i;
4915 
4916           for (i = 0; i < ntparms; ++i)
4917             {
4918               tree parm = TREE_VEC_ELT (inner_parms, i);
4919 
4920               if (parm == error_mark_node)
4921                 continue;
4922 
4923               if (TREE_PURPOSE (parm))
4924                 seen_def_arg_p = 1;
4925               else if (seen_def_arg_p
4926 		       && !template_parameter_pack_p (TREE_VALUE (parm)))
4927                 {
4928                   error ("no default argument for %qD", TREE_VALUE (parm));
4929                   /* For better subsequent error-recovery, we indicate that
4930                      there should have been a default argument.  */
4931                   TREE_PURPOSE (parm) = error_mark_node;
4932                   no_errors = false;
4933                 }
4934 	      else if (!is_partial
4935 		       && !is_friend_decl
4936 		       /* Don't complain about an enclosing partial
4937 			  specialization.  */
4938 		       && parm_level == parms
4939 		       && TREE_CODE (decl) == TYPE_DECL
4940 		       && i < ntparms - 1
4941 		       && template_parameter_pack_p (TREE_VALUE (parm))
4942 		       /* A fixed parameter pack will be partially
4943 			  instantiated into a fixed length list.  */
4944 		       && !fixed_parameter_pack_p (TREE_VALUE (parm)))
4945 		{
4946 		  /* A primary class template can only have one
4947 		     parameter pack, at the end of the template
4948 		     parameter list.  */
4949 
4950 		  error ("parameter pack %q+D must be at the end of the"
4951 			 " template parameter list", TREE_VALUE (parm));
4952 
4953 		  TREE_VALUE (TREE_VEC_ELT (inner_parms, i))
4954 		    = error_mark_node;
4955 		  no_errors = false;
4956 		}
4957             }
4958         }
4959     }
4960 
4961   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
4962       || is_partial
4963       || !is_primary
4964       || is_friend_decl)
4965     /* For an ordinary class template, default template arguments are
4966        allowed at the innermost level, e.g.:
4967 	 template <class T = int>
4968 	 struct S {};
4969        but, in a partial specialization, they're not allowed even
4970        there, as we have in [temp.class.spec]:
4971 
4972 	 The template parameter list of a specialization shall not
4973 	 contain default template argument values.
4974 
4975        So, for a partial specialization, or for a function template
4976        (in C++98/C++03), we look at all of them.  */
4977     ;
4978   else
4979     /* But, for a primary class template that is not a partial
4980        specialization we look at all template parameters except the
4981        innermost ones.  */
4982     parms = TREE_CHAIN (parms);
4983 
4984   /* Figure out what error message to issue.  */
4985   if (is_friend_decl == 2)
4986     msg = G_("default template arguments may not be used in function template "
4987 	     "friend re-declaration");
4988   else if (is_friend_decl)
4989     msg = G_("default template arguments may not be used in function template "
4990 	     "friend declarations");
4991   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
4992     msg = G_("default template arguments may not be used in function templates "
4993 	     "without -std=c++11 or -std=gnu++11");
4994   else if (is_partial)
4995     msg = G_("default template arguments may not be used in "
4996 	     "partial specializations");
4997   else if (current_class_type && CLASSTYPE_IS_TEMPLATE (current_class_type))
4998     msg = G_("default argument for template parameter for class enclosing %qD");
4999   else
5000     /* Per [temp.param]/9, "A default template-argument shall not be
5001        specified in the template-parameter-lists of the definition of
5002        a member of a class template that appears outside of the member's
5003        class.", thus if we aren't handling a member of a class template
5004        there is no need to examine the parameters.  */
5005     return true;
5006 
5007   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
5008     /* If we're inside a class definition, there's no need to
5009        examine the parameters to the class itself.  On the one
5010        hand, they will be checked when the class is defined, and,
5011        on the other, default arguments are valid in things like:
5012 	 template <class T = double>
5013 	 struct S { template <class U> void f(U); };
5014        Here the default argument for `S' has no bearing on the
5015        declaration of `f'.  */
5016     last_level_to_check = template_class_depth (current_class_type) + 1;
5017   else
5018     /* Check everything.  */
5019     last_level_to_check = 0;
5020 
5021   for (parm_level = parms;
5022        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
5023        parm_level = TREE_CHAIN (parm_level))
5024     {
5025       tree inner_parms = TREE_VALUE (parm_level);
5026       int i;
5027       int ntparms;
5028 
5029       ntparms = TREE_VEC_LENGTH (inner_parms);
5030       for (i = 0; i < ntparms; ++i)
5031         {
5032           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
5033             continue;
5034 
5035 	  if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
5036 	    {
5037 	      if (msg)
5038 	        {
5039                   no_errors = false;
5040                   if (is_friend_decl == 2)
5041                     return no_errors;
5042 
5043 		  error (msg, decl);
5044 		  msg = 0;
5045 	        }
5046 
5047 	      /* Clear out the default argument so that we are not
5048 	         confused later.  */
5049 	      TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
5050 	    }
5051         }
5052 
5053       /* At this point, if we're still interested in issuing messages,
5054 	 they must apply to classes surrounding the object declared.  */
5055       if (msg)
5056 	msg = G_("default argument for template parameter for class "
5057 		 "enclosing %qD");
5058     }
5059 
5060   return no_errors;
5061 }
5062 
5063 /* Worker for push_template_decl_real, called via
5064    for_each_template_parm.  DATA is really an int, indicating the
5065    level of the parameters we are interested in.  If T is a template
5066    parameter of that level, return nonzero.  */
5067 
5068 static int
template_parm_this_level_p(tree t,void * data)5069 template_parm_this_level_p (tree t, void* data)
5070 {
5071   int this_level = *(int *)data;
5072   int level;
5073 
5074   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
5075     level = TEMPLATE_PARM_LEVEL (t);
5076   else
5077     level = TEMPLATE_TYPE_LEVEL (t);
5078   return level == this_level;
5079 }
5080 
5081 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
5082    parameters given by current_template_args, or reuses a
5083    previously existing one, if appropriate.  Returns the DECL, or an
5084    equivalent one, if it is replaced via a call to duplicate_decls.
5085 
5086    If IS_FRIEND is true, DECL is a friend declaration.  */
5087 
5088 tree
push_template_decl_real(tree decl,bool is_friend)5089 push_template_decl_real (tree decl, bool is_friend)
5090 {
5091   tree tmpl;
5092   tree args;
5093   tree info;
5094   tree ctx;
5095   bool is_primary;
5096   bool is_partial;
5097   int new_template_p = 0;
5098   /* True if the template is a member template, in the sense of
5099      [temp.mem].  */
5100   bool member_template_p = false;
5101 
5102   if (decl == error_mark_node || !current_template_parms)
5103     return error_mark_node;
5104 
5105   /* See if this is a partial specialization.  */
5106   is_partial = ((DECL_IMPLICIT_TYPEDEF_P (decl)
5107 		 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
5108 		 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
5109 		|| (VAR_P (decl)
5110 		    && DECL_LANG_SPECIFIC (decl)
5111 		    && DECL_TEMPLATE_SPECIALIZATION (decl)
5112 		    && TINFO_USED_TEMPLATE_ID (DECL_TEMPLATE_INFO (decl))));
5113 
5114   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
5115     is_friend = true;
5116 
5117   if (is_friend)
5118     /* For a friend, we want the context of the friend function, not
5119        the type of which it is a friend.  */
5120     ctx = CP_DECL_CONTEXT (decl);
5121   else if (CP_DECL_CONTEXT (decl)
5122 	   && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
5123     /* In the case of a virtual function, we want the class in which
5124        it is defined.  */
5125     ctx = CP_DECL_CONTEXT (decl);
5126   else
5127     /* Otherwise, if we're currently defining some class, the DECL
5128        is assumed to be a member of the class.  */
5129     ctx = current_scope ();
5130 
5131   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
5132     ctx = NULL_TREE;
5133 
5134   if (!DECL_CONTEXT (decl))
5135     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
5136 
5137   /* See if this is a primary template.  */
5138   if (is_friend && ctx
5139       && uses_template_parms_level (ctx, processing_template_decl))
5140     /* A friend template that specifies a class context, i.e.
5141          template <typename T> friend void A<T>::f();
5142        is not primary.  */
5143     is_primary = false;
5144   else if (TREE_CODE (decl) == TYPE_DECL
5145 	   && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5146     is_primary = false;
5147   else
5148     is_primary = template_parm_scope_p ();
5149 
5150   if (is_primary)
5151     {
5152       warning (OPT_Wtemplates, "template %qD declared", decl);
5153 
5154       if (DECL_CLASS_SCOPE_P (decl))
5155 	member_template_p = true;
5156       if (TREE_CODE (decl) == TYPE_DECL
5157 	  && anon_aggrname_p (DECL_NAME (decl)))
5158 	{
5159 	  error ("template class without a name");
5160 	  return error_mark_node;
5161 	}
5162       else if (TREE_CODE (decl) == FUNCTION_DECL)
5163 	{
5164 	  if (member_template_p)
5165 	    {
5166 	      if (DECL_OVERRIDE_P (decl) || DECL_FINAL_P (decl))
5167 		error ("member template %qD may not have virt-specifiers", decl);
5168 	    }
5169 	  if (DECL_DESTRUCTOR_P (decl))
5170 	    {
5171 	      /* [temp.mem]
5172 
5173 		 A destructor shall not be a member template.  */
5174 	      error ("destructor %qD declared as member template", decl);
5175 	      return error_mark_node;
5176 	    }
5177 	  if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
5178 	      && (!prototype_p (TREE_TYPE (decl))
5179 		  || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
5180 		  || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
5181 		  || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
5182 		      == void_list_node)))
5183 	    {
5184 	      /* [basic.stc.dynamic.allocation]
5185 
5186 		 An allocation function can be a function
5187 		 template. ... Template allocation functions shall
5188 		 have two or more parameters.  */
5189 	      error ("invalid template declaration of %qD", decl);
5190 	      return error_mark_node;
5191 	    }
5192 	}
5193       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5194 	       && CLASS_TYPE_P (TREE_TYPE (decl)))
5195 	/* OK */;
5196       else if (TREE_CODE (decl) == TYPE_DECL
5197 	       && TYPE_DECL_ALIAS_P (decl))
5198 	/* alias-declaration */
5199 	gcc_assert (!DECL_ARTIFICIAL (decl));
5200       else if (VAR_P (decl))
5201 	/* C++14 variable template. */;
5202       else
5203 	{
5204 	  error ("template declaration of %q#D", decl);
5205 	  return error_mark_node;
5206 	}
5207     }
5208 
5209   /* Check to see that the rules regarding the use of default
5210      arguments are not being violated.  */
5211   check_default_tmpl_args (decl, current_template_parms,
5212 			   is_primary, is_partial, /*is_friend_decl=*/0);
5213 
5214   /* Ensure that there are no parameter packs in the type of this
5215      declaration that have not been expanded.  */
5216   if (TREE_CODE (decl) == FUNCTION_DECL)
5217     {
5218       /* Check each of the arguments individually to see if there are
5219          any bare parameter packs.  */
5220       tree type = TREE_TYPE (decl);
5221       tree arg = DECL_ARGUMENTS (decl);
5222       tree argtype = TYPE_ARG_TYPES (type);
5223 
5224       while (arg && argtype)
5225         {
5226           if (!DECL_PACK_P (arg)
5227               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
5228             {
5229             /* This is a PARM_DECL that contains unexpanded parameter
5230                packs. We have already complained about this in the
5231                check_for_bare_parameter_packs call, so just replace
5232                these types with ERROR_MARK_NODE.  */
5233               TREE_TYPE (arg) = error_mark_node;
5234               TREE_VALUE (argtype) = error_mark_node;
5235             }
5236 
5237           arg = DECL_CHAIN (arg);
5238           argtype = TREE_CHAIN (argtype);
5239         }
5240 
5241       /* Check for bare parameter packs in the return type and the
5242          exception specifiers.  */
5243       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
5244 	/* Errors were already issued, set return type to int
5245 	   as the frontend doesn't expect error_mark_node as
5246 	   the return type.  */
5247 	TREE_TYPE (type) = integer_type_node;
5248       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
5249 	TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
5250     }
5251   else if (check_for_bare_parameter_packs ((TREE_CODE (decl) == TYPE_DECL
5252 					    && TYPE_DECL_ALIAS_P (decl))
5253 					   ? DECL_ORIGINAL_TYPE (decl)
5254 					   : TREE_TYPE (decl)))
5255     {
5256       TREE_TYPE (decl) = error_mark_node;
5257       return error_mark_node;
5258     }
5259 
5260   if (is_partial)
5261     return process_partial_specialization (decl);
5262 
5263   args = current_template_args ();
5264 
5265   if (!ctx
5266       || TREE_CODE (ctx) == FUNCTION_DECL
5267       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
5268       || (TREE_CODE (decl) == TYPE_DECL
5269 	  && LAMBDA_TYPE_P (TREE_TYPE (decl)))
5270       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
5271     {
5272       if (DECL_LANG_SPECIFIC (decl)
5273 	  && DECL_TEMPLATE_INFO (decl)
5274 	  && DECL_TI_TEMPLATE (decl))
5275 	tmpl = DECL_TI_TEMPLATE (decl);
5276       /* If DECL is a TYPE_DECL for a class-template, then there won't
5277 	 be DECL_LANG_SPECIFIC.  The information equivalent to
5278 	 DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
5279       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
5280 	       && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
5281 	       && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
5282 	{
5283 	  /* Since a template declaration already existed for this
5284 	     class-type, we must be redeclaring it here.  Make sure
5285 	     that the redeclaration is valid.  */
5286 	  redeclare_class_template (TREE_TYPE (decl),
5287 				    current_template_parms,
5288 				    current_template_constraints ());
5289 	  /* We don't need to create a new TEMPLATE_DECL; just use the
5290 	     one we already had.  */
5291 	  tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
5292 	}
5293       else
5294 	{
5295 	  tmpl = build_template_decl (decl, current_template_parms,
5296 				      member_template_p);
5297 	  new_template_p = 1;
5298 
5299 	  if (DECL_LANG_SPECIFIC (decl)
5300 	      && DECL_TEMPLATE_SPECIALIZATION (decl))
5301 	    {
5302 	      /* A specialization of a member template of a template
5303 		 class.  */
5304 	      SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
5305 	      DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
5306 	      DECL_TEMPLATE_INFO (decl) = NULL_TREE;
5307 	    }
5308 	}
5309     }
5310   else
5311     {
5312       tree a, t, current, parms;
5313       int i;
5314       tree tinfo = get_template_info (decl);
5315 
5316       if (!tinfo)
5317 	{
5318 	  error ("template definition of non-template %q#D", decl);
5319 	  return error_mark_node;
5320 	}
5321 
5322       tmpl = TI_TEMPLATE (tinfo);
5323 
5324       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
5325 	  && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
5326 	  && DECL_TEMPLATE_SPECIALIZATION (decl)
5327 	  && DECL_MEMBER_TEMPLATE_P (tmpl))
5328 	{
5329 	  tree new_tmpl;
5330 
5331 	  /* The declaration is a specialization of a member
5332 	     template, declared outside the class.  Therefore, the
5333 	     innermost template arguments will be NULL, so we
5334 	     replace them with the arguments determined by the
5335 	     earlier call to check_explicit_specialization.  */
5336 	  args = DECL_TI_ARGS (decl);
5337 
5338 	  new_tmpl
5339 	    = build_template_decl (decl, current_template_parms,
5340 				   member_template_p);
5341 	  DECL_TEMPLATE_RESULT (new_tmpl) = decl;
5342 	  TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
5343 	  DECL_TI_TEMPLATE (decl) = new_tmpl;
5344 	  SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
5345 	  DECL_TEMPLATE_INFO (new_tmpl)
5346 	    = build_template_info (tmpl, args);
5347 
5348 	  register_specialization (new_tmpl,
5349 				   most_general_template (tmpl),
5350 				   args,
5351 				   is_friend, 0);
5352 	  return decl;
5353 	}
5354 
5355       /* Make sure the template headers we got make sense.  */
5356 
5357       parms = DECL_TEMPLATE_PARMS (tmpl);
5358       i = TMPL_PARMS_DEPTH (parms);
5359       if (TMPL_ARGS_DEPTH (args) != i)
5360 	{
5361 	  error ("expected %d levels of template parms for %q#D, got %d",
5362 		 i, decl, TMPL_ARGS_DEPTH (args));
5363 	  DECL_INTERFACE_KNOWN (decl) = 1;
5364 	  return error_mark_node;
5365 	}
5366       else
5367 	for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
5368 	  {
5369 	    a = TMPL_ARGS_LEVEL (args, i);
5370 	    t = INNERMOST_TEMPLATE_PARMS (parms);
5371 
5372 	    if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
5373 	      {
5374 		if (current == decl)
5375 		  error ("got %d template parameters for %q#D",
5376 			 TREE_VEC_LENGTH (a), decl);
5377 		else
5378 		  error ("got %d template parameters for %q#T",
5379 			 TREE_VEC_LENGTH (a), current);
5380 		error ("  but %d required", TREE_VEC_LENGTH (t));
5381 		/* Avoid crash in import_export_decl.  */
5382 		DECL_INTERFACE_KNOWN (decl) = 1;
5383 		return error_mark_node;
5384 	      }
5385 
5386 	    if (current == decl)
5387 	      current = ctx;
5388 	    else if (current == NULL_TREE)
5389 	      /* Can happen in erroneous input.  */
5390 	      break;
5391 	    else
5392 	      current = get_containing_scope (current);
5393 	  }
5394 
5395       /* Check that the parms are used in the appropriate qualifying scopes
5396 	 in the declarator.  */
5397       if (!comp_template_args
5398 	  (TI_ARGS (tinfo),
5399 	   TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
5400 	{
5401 	  error ("\
5402 template arguments to %qD do not match original template %qD",
5403 		 decl, DECL_TEMPLATE_RESULT (tmpl));
5404 	  if (!uses_template_parms (TI_ARGS (tinfo)))
5405 	    inform (input_location, "use template<> for an explicit specialization");
5406 	  /* Avoid crash in import_export_decl.  */
5407 	  DECL_INTERFACE_KNOWN (decl) = 1;
5408 	  return error_mark_node;
5409 	}
5410     }
5411 
5412   DECL_TEMPLATE_RESULT (tmpl) = decl;
5413   TREE_TYPE (tmpl) = TREE_TYPE (decl);
5414 
5415   /* Push template declarations for global functions and types.  Note
5416      that we do not try to push a global template friend declared in a
5417      template class; such a thing may well depend on the template
5418      parameters of the class.  */
5419   if (new_template_p && !ctx
5420       && !(is_friend && template_class_depth (current_class_type) > 0))
5421     {
5422       tmpl = pushdecl_namespace_level (tmpl, is_friend);
5423       if (tmpl == error_mark_node)
5424 	return error_mark_node;
5425 
5426       /* Hide template friend classes that haven't been declared yet.  */
5427       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
5428 	{
5429 	  DECL_ANTICIPATED (tmpl) = 1;
5430 	  DECL_FRIEND_P (tmpl) = 1;
5431 	}
5432     }
5433 
5434   if (is_primary)
5435     {
5436       tree parms = DECL_TEMPLATE_PARMS (tmpl);
5437       int i;
5438 
5439       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
5440       if (DECL_CONV_FN_P (tmpl))
5441 	{
5442 	  int depth = TMPL_PARMS_DEPTH (parms);
5443 
5444 	  /* It is a conversion operator. See if the type converted to
5445 	     depends on innermost template operands.  */
5446 
5447 	  if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
5448 					 depth))
5449 	    DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
5450 	}
5451 
5452       /* Give template template parms a DECL_CONTEXT of the template
5453 	 for which they are a parameter.  */
5454       parms = INNERMOST_TEMPLATE_PARMS (parms);
5455       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
5456 	{
5457 	  tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5458 	  if (TREE_CODE (parm) == TEMPLATE_DECL)
5459 	    DECL_CONTEXT (parm) = tmpl;
5460 	}
5461 
5462       if (TREE_CODE (decl) == TYPE_DECL
5463 	  && TYPE_DECL_ALIAS_P (decl)
5464 	  && complex_alias_template_p (tmpl))
5465 	TEMPLATE_DECL_COMPLEX_ALIAS_P (tmpl) = true;
5466     }
5467 
5468   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
5469      back to its most general template.  If TMPL is a specialization,
5470      ARGS may only have the innermost set of arguments.  Add the missing
5471      argument levels if necessary.  */
5472   if (DECL_TEMPLATE_INFO (tmpl))
5473     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
5474 
5475   info = build_template_info (tmpl, args);
5476 
5477   if (DECL_IMPLICIT_TYPEDEF_P (decl))
5478     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
5479   else
5480     {
5481       if (is_primary && !DECL_LANG_SPECIFIC (decl))
5482 	retrofit_lang_decl (decl);
5483       if (DECL_LANG_SPECIFIC (decl))
5484 	DECL_TEMPLATE_INFO (decl) = info;
5485     }
5486 
5487   if (flag_implicit_templates
5488       && !is_friend
5489       && TREE_PUBLIC (decl)
5490       && VAR_OR_FUNCTION_DECL_P (decl))
5491     /* Set DECL_COMDAT on template instantiations; if we force
5492        them to be emitted by explicit instantiation or -frepo,
5493        mark_needed will tell cgraph to do the right thing.  */
5494     DECL_COMDAT (decl) = true;
5495 
5496   return DECL_TEMPLATE_RESULT (tmpl);
5497 }
5498 
5499 tree
push_template_decl(tree decl)5500 push_template_decl (tree decl)
5501 {
5502   return push_template_decl_real (decl, false);
5503 }
5504 
5505 /* FN is an inheriting constructor that inherits from the constructor
5506    template INHERITED; turn FN into a constructor template with a matching
5507    template header.  */
5508 
5509 tree
add_inherited_template_parms(tree fn,tree inherited)5510 add_inherited_template_parms (tree fn, tree inherited)
5511 {
5512   tree inner_parms
5513     = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (inherited));
5514   inner_parms = copy_node (inner_parms);
5515   tree parms
5516     = tree_cons (size_int (processing_template_decl + 1),
5517 		 inner_parms, current_template_parms);
5518   tree tmpl = build_template_decl (fn, parms, /*member*/true);
5519   tree args = template_parms_to_args (parms);
5520   DECL_TEMPLATE_INFO (fn) = build_template_info (tmpl, args);
5521   TREE_TYPE (tmpl) = TREE_TYPE (fn);
5522   DECL_TEMPLATE_RESULT (tmpl) = fn;
5523   DECL_ARTIFICIAL (tmpl) = true;
5524   DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
5525   return tmpl;
5526 }
5527 
5528 /* Called when a class template TYPE is redeclared with the indicated
5529    template PARMS, e.g.:
5530 
5531      template <class T> struct S;
5532      template <class T> struct S {};  */
5533 
5534 bool
redeclare_class_template(tree type,tree parms,tree cons)5535 redeclare_class_template (tree type, tree parms, tree cons)
5536 {
5537   tree tmpl;
5538   tree tmpl_parms;
5539   int i;
5540 
5541   if (!TYPE_TEMPLATE_INFO (type))
5542     {
5543       error ("%qT is not a template type", type);
5544       return false;
5545     }
5546 
5547   tmpl = TYPE_TI_TEMPLATE (type);
5548   if (!PRIMARY_TEMPLATE_P (tmpl))
5549     /* The type is nested in some template class.  Nothing to worry
5550        about here; there are no new template parameters for the nested
5551        type.  */
5552     return true;
5553 
5554   if (!parms)
5555     {
5556       error ("template specifiers not specified in declaration of %qD",
5557 	     tmpl);
5558       return false;
5559     }
5560 
5561   parms = INNERMOST_TEMPLATE_PARMS (parms);
5562   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
5563 
5564   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
5565     {
5566       error_n (input_location, TREE_VEC_LENGTH (parms),
5567                "redeclared with %d template parameter",
5568                "redeclared with %d template parameters",
5569                TREE_VEC_LENGTH (parms));
5570       inform_n (DECL_SOURCE_LOCATION (tmpl), TREE_VEC_LENGTH (tmpl_parms),
5571                 "previous declaration %qD used %d template parameter",
5572                 "previous declaration %qD used %d template parameters",
5573                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
5574       return false;
5575     }
5576 
5577   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
5578     {
5579       tree tmpl_parm;
5580       tree parm;
5581       tree tmpl_default;
5582       tree parm_default;
5583 
5584       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
5585           || TREE_VEC_ELT (parms, i) == error_mark_node)
5586         continue;
5587 
5588       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
5589       if (error_operand_p (tmpl_parm))
5590 	return false;
5591 
5592       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5593       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
5594       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
5595 
5596       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
5597 	 TEMPLATE_DECL.  */
5598       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
5599 	  || (TREE_CODE (tmpl_parm) != TYPE_DECL
5600 	      && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
5601 	  || (TREE_CODE (tmpl_parm) != PARM_DECL
5602 	      && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
5603 		  != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
5604 	  || (TREE_CODE (tmpl_parm) == PARM_DECL
5605 	      && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
5606 		  != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
5607 	{
5608 	  error ("template parameter %q+#D", tmpl_parm);
5609 	  error ("redeclared here as %q#D", parm);
5610 	  return false;
5611 	}
5612 
5613       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
5614 	{
5615 	  /* We have in [temp.param]:
5616 
5617 	     A template-parameter may not be given default arguments
5618 	     by two different declarations in the same scope.  */
5619 	  error_at (input_location, "redefinition of default argument for %q#D", parm);
5620 	  inform (DECL_SOURCE_LOCATION (tmpl_parm),
5621 		  "original definition appeared here");
5622 	  return false;
5623 	}
5624 
5625       if (parm_default != NULL_TREE)
5626 	/* Update the previous template parameters (which are the ones
5627 	   that will really count) with the new default value.  */
5628 	TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
5629       else if (tmpl_default != NULL_TREE)
5630 	/* Update the new parameters, too; they'll be used as the
5631 	   parameters for any members.  */
5632 	TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
5633 
5634       /* Give each template template parm in this redeclaration a
5635 	 DECL_CONTEXT of the template for which they are a parameter.  */
5636       if (TREE_CODE (parm) == TEMPLATE_DECL)
5637 	{
5638 	  gcc_assert (DECL_CONTEXT (parm) == NULL_TREE);
5639 	  DECL_CONTEXT (parm) = tmpl;
5640 	}
5641     }
5642 
5643   // Cannot redeclare a class template with a different set of constraints.
5644   if (!equivalent_constraints (get_constraints (tmpl), cons))
5645     {
5646       error_at (input_location, "redeclaration %q#D with different "
5647                                 "constraints", tmpl);
5648       inform (DECL_SOURCE_LOCATION (tmpl),
5649               "original declaration appeared here");
5650     }
5651 
5652     return true;
5653 }
5654 
5655 /* The actual substitution part of instantiate_non_dependent_expr_sfinae,
5656    to be used when the caller has already checked
5657    (processing_template_decl
5658     && !instantiation_dependent_expression_p (expr)
5659     && potential_constant_expression (expr))
5660    and cleared processing_template_decl.  */
5661 
5662 tree
instantiate_non_dependent_expr_internal(tree expr,tsubst_flags_t complain)5663 instantiate_non_dependent_expr_internal (tree expr, tsubst_flags_t complain)
5664 {
5665   return tsubst_copy_and_build (expr,
5666 				/*args=*/NULL_TREE,
5667 				complain,
5668 				/*in_decl=*/NULL_TREE,
5669 				/*function_p=*/false,
5670 				/*integral_constant_expression_p=*/true);
5671 }
5672 
5673 /* Simplify EXPR if it is a non-dependent expression.  Returns the
5674    (possibly simplified) expression.  */
5675 
5676 tree
instantiate_non_dependent_expr_sfinae(tree expr,tsubst_flags_t complain)5677 instantiate_non_dependent_expr_sfinae (tree expr, tsubst_flags_t complain)
5678 {
5679   if (expr == NULL_TREE)
5680     return NULL_TREE;
5681 
5682   /* If we're in a template, but EXPR isn't value dependent, simplify
5683      it.  We're supposed to treat:
5684 
5685        template <typename T> void f(T[1 + 1]);
5686        template <typename T> void f(T[2]);
5687 
5688      as two declarations of the same function, for example.  */
5689   if (processing_template_decl
5690       && potential_nondependent_constant_expression (expr))
5691     {
5692       processing_template_decl_sentinel s;
5693       expr = instantiate_non_dependent_expr_internal (expr, complain);
5694     }
5695   return expr;
5696 }
5697 
5698 tree
instantiate_non_dependent_expr(tree expr)5699 instantiate_non_dependent_expr (tree expr)
5700 {
5701   return instantiate_non_dependent_expr_sfinae (expr, tf_error);
5702 }
5703 
5704 /* Like instantiate_non_dependent_expr, but return NULL_TREE rather than
5705    an uninstantiated expression.  */
5706 
5707 tree
instantiate_non_dependent_or_null(tree expr)5708 instantiate_non_dependent_or_null (tree expr)
5709 {
5710   if (expr == NULL_TREE)
5711     return NULL_TREE;
5712   if (processing_template_decl)
5713     {
5714       if (!potential_nondependent_constant_expression (expr))
5715 	expr = NULL_TREE;
5716       else
5717 	{
5718 	  processing_template_decl_sentinel s;
5719 	  expr = instantiate_non_dependent_expr_internal (expr, tf_error);
5720 	}
5721     }
5722   return expr;
5723 }
5724 
5725 /* True iff T is a specialization of a variable template.  */
5726 
5727 bool
variable_template_specialization_p(tree t)5728 variable_template_specialization_p (tree t)
5729 {
5730   if (!VAR_P (t) || !DECL_LANG_SPECIFIC (t) || !DECL_TEMPLATE_INFO (t))
5731     return false;
5732   tree tmpl = DECL_TI_TEMPLATE (t);
5733   return variable_template_p (tmpl);
5734 }
5735 
5736 /* Return TRUE iff T is a type alias, a TEMPLATE_DECL for an alias
5737    template declaration, or a TYPE_DECL for an alias declaration.  */
5738 
5739 bool
alias_type_or_template_p(tree t)5740 alias_type_or_template_p (tree t)
5741 {
5742   if (t == NULL_TREE)
5743     return false;
5744   return ((TREE_CODE (t) == TYPE_DECL && TYPE_DECL_ALIAS_P (t))
5745 	  || (TYPE_P (t)
5746 	      && TYPE_NAME (t)
5747 	      && TYPE_DECL_ALIAS_P (TYPE_NAME (t)))
5748 	  || DECL_ALIAS_TEMPLATE_P (t));
5749 }
5750 
5751 /* Return TRUE iff T is a specialization of an alias template.  */
5752 
5753 bool
alias_template_specialization_p(const_tree t)5754 alias_template_specialization_p (const_tree t)
5755 {
5756   /* It's an alias template specialization if it's an alias and its
5757      TYPE_NAME is a specialization of a primary template.  */
5758   if (TYPE_ALIAS_P (t))
5759     {
5760       tree name = TYPE_NAME (t);
5761       if (DECL_LANG_SPECIFIC (name))
5762 	if (tree ti = DECL_TEMPLATE_INFO (name))
5763 	  {
5764 	    tree tmpl = TI_TEMPLATE (ti);
5765 	    return PRIMARY_TEMPLATE_P (tmpl);
5766 	  }
5767     }
5768   return false;
5769 }
5770 
5771 /* An alias template is complex from a SFINAE perspective if a template-id
5772    using that alias can be ill-formed when the expansion is not, as with
5773    the void_t template.  We determine this by checking whether the
5774    expansion for the alias template uses all its template parameters.  */
5775 
5776 struct uses_all_template_parms_data
5777 {
5778   int level;
5779   bool *seen;
5780 };
5781 
5782 static int
uses_all_template_parms_r(tree t,void * data_)5783 uses_all_template_parms_r (tree t, void *data_)
5784 {
5785   struct uses_all_template_parms_data &data
5786     = *(struct uses_all_template_parms_data*)data_;
5787   tree idx = get_template_parm_index (t);
5788 
5789   if (TEMPLATE_PARM_LEVEL (idx) == data.level)
5790     data.seen[TEMPLATE_PARM_IDX (idx)] = true;
5791   return 0;
5792 }
5793 
5794 static bool
complex_alias_template_p(const_tree tmpl)5795 complex_alias_template_p (const_tree tmpl)
5796 {
5797   struct uses_all_template_parms_data data;
5798   tree pat = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
5799   tree parms = DECL_TEMPLATE_PARMS (tmpl);
5800   data.level = TMPL_PARMS_DEPTH (parms);
5801   int len = TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS (parms));
5802   data.seen = XALLOCAVEC (bool, len);
5803   for (int i = 0; i < len; ++i)
5804     data.seen[i] = false;
5805 
5806   for_each_template_parm (pat, uses_all_template_parms_r, &data, NULL, true);
5807   for (int i = 0; i < len; ++i)
5808     if (!data.seen[i])
5809       return true;
5810   return false;
5811 }
5812 
5813 /* Return TRUE iff T is a specialization of a complex alias template with
5814    dependent template-arguments.  */
5815 
5816 bool
dependent_alias_template_spec_p(const_tree t)5817 dependent_alias_template_spec_p (const_tree t)
5818 {
5819   return (alias_template_specialization_p (t)
5820 	  && TEMPLATE_DECL_COMPLEX_ALIAS_P (DECL_TI_TEMPLATE (TYPE_NAME (t)))
5821 	  && (any_dependent_template_arguments_p
5822 	      (INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (t)))));
5823 }
5824 
5825 /* Return the number of innermost template parameters in TMPL.  */
5826 
5827 static int
num_innermost_template_parms(tree tmpl)5828 num_innermost_template_parms (tree tmpl)
5829 {
5830   tree parms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (tmpl));
5831   return TREE_VEC_LENGTH (parms);
5832 }
5833 
5834 /* Return either TMPL or another template that it is equivalent to under DR
5835    1286: An alias that just changes the name of a template is equivalent to
5836    the other template.  */
5837 
5838 static tree
get_underlying_template(tree tmpl)5839 get_underlying_template (tree tmpl)
5840 {
5841   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
5842   while (DECL_ALIAS_TEMPLATE_P (tmpl))
5843     {
5844       tree result = DECL_ORIGINAL_TYPE (DECL_TEMPLATE_RESULT (tmpl));
5845       if (TYPE_TEMPLATE_INFO (result))
5846 	{
5847 	  tree sub = TYPE_TI_TEMPLATE (result);
5848 	  if (PRIMARY_TEMPLATE_P (sub)
5849 	      && (num_innermost_template_parms (tmpl)
5850 		  == num_innermost_template_parms (sub)))
5851 	    {
5852 	      tree alias_args = INNERMOST_TEMPLATE_ARGS
5853 		(template_parms_to_args (DECL_TEMPLATE_PARMS (tmpl)));
5854 	      if (!comp_template_args (TYPE_TI_ARGS (result), alias_args))
5855 		break;
5856 	      /* The alias type is equivalent to the pattern of the
5857 		 underlying template, so strip the alias.  */
5858 	      tmpl = sub;
5859 	      continue;
5860 	    }
5861 	}
5862       break;
5863     }
5864   return tmpl;
5865 }
5866 
5867 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
5868    must be a function or a pointer-to-function type, as specified
5869    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
5870    and check that the resulting function has external linkage.  */
5871 
5872 static tree
convert_nontype_argument_function(tree type,tree expr,tsubst_flags_t complain)5873 convert_nontype_argument_function (tree type, tree expr,
5874 				   tsubst_flags_t complain)
5875 {
5876   tree fns = expr;
5877   tree fn, fn_no_ptr;
5878   linkage_kind linkage;
5879 
5880   fn = instantiate_type (type, fns, tf_none);
5881   if (fn == error_mark_node)
5882     return error_mark_node;
5883 
5884   fn_no_ptr = fn;
5885   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
5886     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
5887   if (BASELINK_P (fn_no_ptr))
5888     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
5889 
5890   /* [temp.arg.nontype]/1
5891 
5892      A template-argument for a non-type, non-template template-parameter
5893      shall be one of:
5894      [...]
5895      -- the address of an object or function with external [C++11: or
5896         internal] linkage.  */
5897 
5898   if (TREE_CODE (fn_no_ptr) != FUNCTION_DECL)
5899     {
5900       if (complain & tf_error)
5901 	{
5902 	  error ("%qE is not a valid template argument for type %qT",
5903 		 expr, type);
5904 	  if (TYPE_PTR_P (type))
5905 	    error ("it must be the address of a function with "
5906 		   "external linkage");
5907 	  else
5908 	    error ("it must be the name of a function with "
5909 		   "external linkage");
5910 	}
5911       return NULL_TREE;
5912     }
5913 
5914   linkage = decl_linkage (fn_no_ptr);
5915   if (cxx_dialect >= cxx11 ? linkage == lk_none : linkage != lk_external)
5916     {
5917       if (complain & tf_error)
5918 	{
5919 	  if (cxx_dialect >= cxx11)
5920 	    error ("%qE is not a valid template argument for type %qT "
5921 		   "because %qD has no linkage",
5922 		   expr, type, fn_no_ptr);
5923 	  else
5924 	    error ("%qE is not a valid template argument for type %qT "
5925 		   "because %qD does not have external linkage",
5926 		   expr, type, fn_no_ptr);
5927 	}
5928       return NULL_TREE;
5929     }
5930 
5931   return fn;
5932 }
5933 
5934 /* Subroutine of convert_nontype_argument.
5935    Check if EXPR of type TYPE is a valid pointer-to-member constant.
5936    Emit an error otherwise.  */
5937 
5938 static bool
check_valid_ptrmem_cst_expr(tree type,tree expr,tsubst_flags_t complain)5939 check_valid_ptrmem_cst_expr (tree type, tree expr,
5940 			     tsubst_flags_t complain)
5941 {
5942   STRIP_NOPS (expr);
5943   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
5944     return true;
5945   if (cxx_dialect >= cxx11 && null_member_pointer_value_p (expr))
5946     return true;
5947   if (processing_template_decl
5948       && TREE_CODE (expr) == ADDR_EXPR
5949       && TREE_CODE (TREE_OPERAND (expr, 0)) == OFFSET_REF)
5950     return true;
5951   if (complain & tf_error)
5952     {
5953       error ("%qE is not a valid template argument for type %qT",
5954 	     expr, type);
5955       error ("it must be a pointer-to-member of the form %<&X::Y%>");
5956     }
5957   return false;
5958 }
5959 
5960 /* Returns TRUE iff the address of OP is value-dependent.
5961 
5962    14.6.2.4 [temp.dep.temp]:
5963    A non-integral non-type template-argument is dependent if its type is
5964    dependent or it has either of the following forms
5965      qualified-id
5966      & qualified-id
5967    and contains a nested-name-specifier which specifies a class-name that
5968    names a dependent type.
5969 
5970    We generalize this to just say that the address of a member of a
5971    dependent class is value-dependent; the above doesn't cover the
5972    address of a static data member named with an unqualified-id.  */
5973 
5974 static bool
has_value_dependent_address(tree op)5975 has_value_dependent_address (tree op)
5976 {
5977   /* We could use get_inner_reference here, but there's no need;
5978      this is only relevant for template non-type arguments, which
5979      can only be expressed as &id-expression.  */
5980   if (DECL_P (op))
5981     {
5982       tree ctx = CP_DECL_CONTEXT (op);
5983       if (TYPE_P (ctx) && dependent_type_p (ctx))
5984 	return true;
5985     }
5986 
5987   return false;
5988 }
5989 
5990 /* The next set of functions are used for providing helpful explanatory
5991    diagnostics for failed overload resolution.  Their messages should be
5992    indented by two spaces for consistency with the messages in
5993    call.c  */
5994 
5995 static int
unify_success(bool)5996 unify_success (bool /*explain_p*/)
5997 {
5998   return 0;
5999 }
6000 
6001 static int
unify_parameter_deduction_failure(bool explain_p,tree parm)6002 unify_parameter_deduction_failure (bool explain_p, tree parm)
6003 {
6004   if (explain_p)
6005     inform (input_location,
6006 	    "  couldn't deduce template parameter %qD", parm);
6007   return 1;
6008 }
6009 
6010 static int
unify_invalid(bool)6011 unify_invalid (bool /*explain_p*/)
6012 {
6013   return 1;
6014 }
6015 
6016 static int
unify_cv_qual_mismatch(bool explain_p,tree parm,tree arg)6017 unify_cv_qual_mismatch (bool explain_p, tree parm, tree arg)
6018 {
6019   if (explain_p)
6020     inform (input_location,
6021 	    "  types %qT and %qT have incompatible cv-qualifiers",
6022 	    parm, arg);
6023   return 1;
6024 }
6025 
6026 static int
unify_type_mismatch(bool explain_p,tree parm,tree arg)6027 unify_type_mismatch (bool explain_p, tree parm, tree arg)
6028 {
6029   if (explain_p)
6030     inform (input_location, "  mismatched types %qT and %qT", parm, arg);
6031   return 1;
6032 }
6033 
6034 static int
unify_parameter_pack_mismatch(bool explain_p,tree parm,tree arg)6035 unify_parameter_pack_mismatch (bool explain_p, tree parm, tree arg)
6036 {
6037   if (explain_p)
6038     inform (input_location,
6039 	    "  template parameter %qD is not a parameter pack, but "
6040 	    "argument %qD is",
6041 	    parm, arg);
6042   return 1;
6043 }
6044 
6045 static int
unify_ptrmem_cst_mismatch(bool explain_p,tree parm,tree arg)6046 unify_ptrmem_cst_mismatch (bool explain_p, tree parm, tree arg)
6047 {
6048   if (explain_p)
6049     inform (input_location,
6050 	    "  template argument %qE does not match "
6051 	    "pointer-to-member constant %qE",
6052 	    arg, parm);
6053   return 1;
6054 }
6055 
6056 static int
unify_expression_unequal(bool explain_p,tree parm,tree arg)6057 unify_expression_unequal (bool explain_p, tree parm, tree arg)
6058 {
6059   if (explain_p)
6060     inform (input_location, "  %qE is not equivalent to %qE", parm, arg);
6061   return 1;
6062 }
6063 
6064 static int
unify_parameter_pack_inconsistent(bool explain_p,tree old_arg,tree new_arg)6065 unify_parameter_pack_inconsistent (bool explain_p, tree old_arg, tree new_arg)
6066 {
6067   if (explain_p)
6068     inform (input_location,
6069 	    "  inconsistent parameter pack deduction with %qT and %qT",
6070 	    old_arg, new_arg);
6071   return 1;
6072 }
6073 
6074 static int
unify_inconsistency(bool explain_p,tree parm,tree first,tree second)6075 unify_inconsistency (bool explain_p, tree parm, tree first, tree second)
6076 {
6077   if (explain_p)
6078     {
6079       if (TYPE_P (parm))
6080 	inform (input_location,
6081 		"  deduced conflicting types for parameter %qT (%qT and %qT)",
6082 		parm, first, second);
6083       else
6084 	inform (input_location,
6085 		"  deduced conflicting values for non-type parameter "
6086 		"%qE (%qE and %qE)", parm, first, second);
6087     }
6088   return 1;
6089 }
6090 
6091 static int
unify_vla_arg(bool explain_p,tree arg)6092 unify_vla_arg (bool explain_p, tree arg)
6093 {
6094   if (explain_p)
6095     inform (input_location,
6096 	    "  variable-sized array type %qT is not "
6097 	    "a valid template argument",
6098 	    arg);
6099   return 1;
6100 }
6101 
6102 static int
unify_method_type_error(bool explain_p,tree arg)6103 unify_method_type_error (bool explain_p, tree arg)
6104 {
6105   if (explain_p)
6106     inform (input_location,
6107 	    "  member function type %qT is not a valid template argument",
6108 	    arg);
6109   return 1;
6110 }
6111 
6112 static int
6113 unify_arity (bool explain_p, int have, int wanted, bool least_p = false)
6114 {
6115   if (explain_p)
6116     {
6117       if (least_p)
6118 	inform_n (input_location, wanted,
6119 		  "  candidate expects at least %d argument, %d provided",
6120 		  "  candidate expects at least %d arguments, %d provided",
6121 		  wanted, have);
6122       else
6123 	inform_n (input_location, wanted,
6124 		  "  candidate expects %d argument, %d provided",
6125 		  "  candidate expects %d arguments, %d provided",
6126 		  wanted, have);
6127     }
6128   return 1;
6129 }
6130 
6131 static int
unify_too_many_arguments(bool explain_p,int have,int wanted)6132 unify_too_many_arguments (bool explain_p, int have, int wanted)
6133 {
6134   return unify_arity (explain_p, have, wanted);
6135 }
6136 
6137 static int
6138 unify_too_few_arguments (bool explain_p, int have, int wanted,
6139 			 bool least_p = false)
6140 {
6141   return unify_arity (explain_p, have, wanted, least_p);
6142 }
6143 
6144 static int
unify_arg_conversion(bool explain_p,tree to_type,tree from_type,tree arg)6145 unify_arg_conversion (bool explain_p, tree to_type,
6146 		      tree from_type, tree arg)
6147 {
6148   if (explain_p)
6149     inform (EXPR_LOC_OR_LOC (arg, input_location),
6150 	    "  cannot convert %qE (type %qT) to type %qT",
6151 	    arg, from_type, to_type);
6152   return 1;
6153 }
6154 
6155 static int
unify_no_common_base(bool explain_p,enum template_base_result r,tree parm,tree arg)6156 unify_no_common_base (bool explain_p, enum template_base_result r,
6157 		      tree parm, tree arg)
6158 {
6159   if (explain_p)
6160     switch (r)
6161       {
6162       case tbr_ambiguous_baseclass:
6163 	inform (input_location, "  %qT is an ambiguous base class of %qT",
6164 		parm, arg);
6165 	break;
6166       default:
6167 	inform (input_location, "  %qT is not derived from %qT", arg, parm);
6168 	break;
6169       }
6170   return 1;
6171 }
6172 
6173 static int
unify_inconsistent_template_template_parameters(bool explain_p)6174 unify_inconsistent_template_template_parameters (bool explain_p)
6175 {
6176   if (explain_p)
6177     inform (input_location,
6178 	    "  template parameters of a template template argument are "
6179 	    "inconsistent with other deduced template arguments");
6180   return 1;
6181 }
6182 
6183 static int
unify_template_deduction_failure(bool explain_p,tree parm,tree arg)6184 unify_template_deduction_failure (bool explain_p, tree parm, tree arg)
6185 {
6186   if (explain_p)
6187     inform (input_location,
6188 	    "  can't deduce a template for %qT from non-template type %qT",
6189 	    parm, arg);
6190   return 1;
6191 }
6192 
6193 static int
unify_template_argument_mismatch(bool explain_p,tree parm,tree arg)6194 unify_template_argument_mismatch (bool explain_p, tree parm, tree arg)
6195 {
6196   if (explain_p)
6197     inform (input_location,
6198 	    "  template argument %qE does not match %qD", arg, parm);
6199   return 1;
6200 }
6201 
6202 static int
unify_overload_resolution_failure(bool explain_p,tree arg)6203 unify_overload_resolution_failure (bool explain_p, tree arg)
6204 {
6205   if (explain_p)
6206     inform (input_location,
6207 	    "  could not resolve address from overloaded function %qE",
6208 	    arg);
6209   return 1;
6210 }
6211 
6212 /* Attempt to convert the non-type template parameter EXPR to the
6213    indicated TYPE.  If the conversion is successful, return the
6214    converted value.  If the conversion is unsuccessful, return
6215    NULL_TREE if we issued an error message, or error_mark_node if we
6216    did not.  We issue error messages for out-and-out bad template
6217    parameters, but not simply because the conversion failed, since we
6218    might be just trying to do argument deduction.  Both TYPE and EXPR
6219    must be non-dependent.
6220 
6221    The conversion follows the special rules described in
6222    [temp.arg.nontype], and it is much more strict than an implicit
6223    conversion.
6224 
6225    This function is called twice for each template argument (see
6226    lookup_template_class for a more accurate description of this
6227    problem). This means that we need to handle expressions which
6228    are not valid in a C++ source, but can be created from the
6229    first call (for instance, casts to perform conversions). These
6230    hacks can go away after we fix the double coercion problem.  */
6231 
6232 static tree
convert_nontype_argument(tree type,tree expr,tsubst_flags_t complain)6233 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
6234 {
6235   tree expr_type;
6236 
6237   /* Detect immediately string literals as invalid non-type argument.
6238      This special-case is not needed for correctness (we would easily
6239      catch this later), but only to provide better diagnostic for this
6240      common user mistake. As suggested by DR 100, we do not mention
6241      linkage issues in the diagnostic as this is not the point.  */
6242   /* FIXME we're making this OK.  */
6243   if (TREE_CODE (expr) == STRING_CST)
6244     {
6245       if (complain & tf_error)
6246 	error ("%qE is not a valid template argument for type %qT "
6247 	       "because string literals can never be used in this context",
6248 	       expr, type);
6249       return NULL_TREE;
6250     }
6251 
6252   /* Add the ADDR_EXPR now for the benefit of
6253      value_dependent_expression_p.  */
6254   if (TYPE_PTROBV_P (type)
6255       && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
6256     {
6257       expr = decay_conversion (expr, complain);
6258       if (expr == error_mark_node)
6259 	return error_mark_node;
6260     }
6261 
6262   /* If we are in a template, EXPR may be non-dependent, but still
6263      have a syntactic, rather than semantic, form.  For example, EXPR
6264      might be a SCOPE_REF, rather than the VAR_DECL to which the
6265      SCOPE_REF refers.  Preserving the qualifying scope is necessary
6266      so that access checking can be performed when the template is
6267      instantiated -- but here we need the resolved form so that we can
6268      convert the argument.  */
6269   bool non_dep = false;
6270   if (TYPE_REF_OBJ_P (type)
6271       && has_value_dependent_address (expr))
6272     /* If we want the address and it's value-dependent, don't fold.  */;
6273   else if (processing_template_decl
6274 	   && potential_nondependent_constant_expression (expr))
6275     non_dep = true;
6276   if (error_operand_p (expr))
6277     return error_mark_node;
6278   expr_type = TREE_TYPE (expr);
6279   if (TREE_CODE (type) == REFERENCE_TYPE)
6280     expr = mark_lvalue_use (expr);
6281   else
6282     expr = mark_rvalue_use (expr);
6283 
6284   /* If the argument is non-dependent, perform any conversions in
6285      non-dependent context as well.  */
6286   processing_template_decl_sentinel s (non_dep);
6287   if (non_dep)
6288     expr = instantiate_non_dependent_expr_internal (expr, complain);
6289 
6290   /* 14.3.2/5: The null pointer{,-to-member} conversion is applied
6291      to a non-type argument of "nullptr".  */
6292   if (expr == nullptr_node && TYPE_PTR_OR_PTRMEM_P (type))
6293     expr = fold_simple (convert (type, expr));
6294 
6295   /* In C++11, integral or enumeration non-type template arguments can be
6296      arbitrary constant expressions.  Pointer and pointer to
6297      member arguments can be general constant expressions that evaluate
6298      to a null value, but otherwise still need to be of a specific form.  */
6299   if (cxx_dialect >= cxx11)
6300     {
6301       if (TREE_CODE (expr) == PTRMEM_CST)
6302 	/* A PTRMEM_CST is already constant, and a valid template
6303 	   argument for a parameter of pointer to member type, we just want
6304 	   to leave it in that form rather than lower it to a
6305 	   CONSTRUCTOR.  */;
6306       else if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
6307 	expr = maybe_constant_value (expr);
6308       else if (cxx_dialect >= cxx1z)
6309 	{
6310 	  if (TREE_CODE (type) != REFERENCE_TYPE)
6311 	    expr = maybe_constant_value (expr);
6312 	  else if (REFERENCE_REF_P (expr))
6313 	    {
6314 	      expr = TREE_OPERAND (expr, 0);
6315 	      expr = maybe_constant_value (expr);
6316 	      expr = convert_from_reference (expr);
6317 	    }
6318 	}
6319       else if (TYPE_PTR_OR_PTRMEM_P (type))
6320 	{
6321 	  tree folded = maybe_constant_value (expr);
6322 	  if (TYPE_PTR_P (type) ? integer_zerop (folded)
6323 	      : null_member_pointer_value_p (folded))
6324 	    expr = folded;
6325 	}
6326     }
6327 
6328   /* HACK: Due to double coercion, we can get a
6329      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
6330      which is the tree that we built on the first call (see
6331      below when coercing to reference to object or to reference to
6332      function). We just strip everything and get to the arg.
6333      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
6334      for examples.  */
6335   if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
6336     {
6337       tree probe_type, probe = expr;
6338       if (REFERENCE_REF_P (probe))
6339 	probe = TREE_OPERAND (probe, 0);
6340       probe_type = TREE_TYPE (probe);
6341       if (TREE_CODE (probe) == NOP_EXPR)
6342 	{
6343 	  /* ??? Maybe we could use convert_from_reference here, but we
6344 	     would need to relax its constraints because the NOP_EXPR
6345 	     could actually change the type to something more cv-qualified,
6346 	     and this is not folded by convert_from_reference.  */
6347 	  tree addr = TREE_OPERAND (probe, 0);
6348 	  if (TREE_CODE (probe_type) == REFERENCE_TYPE
6349 	      && TREE_CODE (addr) == ADDR_EXPR
6350 	      && TYPE_PTR_P (TREE_TYPE (addr))
6351 	      && (same_type_ignoring_top_level_qualifiers_p
6352 		  (TREE_TYPE (probe_type),
6353 		   TREE_TYPE (TREE_TYPE (addr)))))
6354 	    {
6355 	      expr = TREE_OPERAND (addr, 0);
6356 	      expr_type = TREE_TYPE (probe_type);
6357 	    }
6358 	}
6359     }
6360 
6361   /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
6362      parameter is a pointer to object, through decay and
6363      qualification conversion. Let's strip everything.  */
6364   else if (TREE_CODE (expr) == NOP_EXPR && TYPE_PTROBV_P (type))
6365     {
6366       tree probe = expr;
6367       STRIP_NOPS (probe);
6368       if (TREE_CODE (probe) == ADDR_EXPR
6369 	  && TYPE_PTR_P (TREE_TYPE (probe)))
6370 	{
6371 	  /* Skip the ADDR_EXPR only if it is part of the decay for
6372 	     an array. Otherwise, it is part of the original argument
6373 	     in the source code.  */
6374 	  if (TREE_CODE (TREE_TYPE (TREE_OPERAND (probe, 0))) == ARRAY_TYPE)
6375 	    probe = TREE_OPERAND (probe, 0);
6376 	  expr = probe;
6377 	  expr_type = TREE_TYPE (expr);
6378 	}
6379     }
6380 
6381   /* [temp.arg.nontype]/5, bullet 1
6382 
6383      For a non-type template-parameter of integral or enumeration type,
6384      integral promotions (_conv.prom_) and integral conversions
6385      (_conv.integral_) are applied.  */
6386   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
6387     {
6388       tree t = build_integral_nontype_arg_conv (type, expr, complain);
6389       t = maybe_constant_value (t);
6390       if (t != error_mark_node)
6391 	expr = t;
6392 
6393       if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
6394 	return error_mark_node;
6395 
6396       /* Notice that there are constant expressions like '4 % 0' which
6397 	 do not fold into integer constants.  */
6398       if (TREE_CODE (expr) != INTEGER_CST)
6399 	{
6400 	  if (complain & tf_error)
6401 	    {
6402 	      int errs = errorcount, warns = warningcount + werrorcount;
6403 	      if (processing_template_decl
6404 		  && !require_potential_constant_expression (expr))
6405 		return NULL_TREE;
6406 	      expr = cxx_constant_value (expr);
6407 	      if (errorcount > errs || warningcount + werrorcount > warns)
6408 		inform (EXPR_LOC_OR_LOC (expr, input_location),
6409 			"in template argument for type %qT ", type);
6410 	      if (expr == error_mark_node)
6411 		return NULL_TREE;
6412 	      /* else cxx_constant_value complained but gave us
6413 		 a real constant, so go ahead.  */
6414 	      gcc_assert (TREE_CODE (expr) == INTEGER_CST);
6415 	    }
6416 	  else
6417 	    return NULL_TREE;
6418 	}
6419 
6420       /* Avoid typedef problems.  */
6421       if (TREE_TYPE (expr) != type)
6422 	expr = fold_convert (type, expr);
6423     }
6424   /* [temp.arg.nontype]/5, bullet 2
6425 
6426      For a non-type template-parameter of type pointer to object,
6427      qualification conversions (_conv.qual_) and the array-to-pointer
6428      conversion (_conv.array_) are applied.  */
6429   else if (TYPE_PTROBV_P (type))
6430     {
6431       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
6432 
6433 	 A template-argument for a non-type, non-template template-parameter
6434 	 shall be one of: [...]
6435 
6436 	 -- the name of a non-type template-parameter;
6437 	 -- the address of an object or function with external linkage, [...]
6438 	    expressed as "& id-expression" where the & is optional if the name
6439 	    refers to a function or array, or if the corresponding
6440 	    template-parameter is a reference.
6441 
6442 	Here, we do not care about functions, as they are invalid anyway
6443 	for a parameter of type pointer-to-object.  */
6444 
6445       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
6446 	/* Non-type template parameters are OK.  */
6447 	;
6448       else if (cxx_dialect >= cxx11 && integer_zerop (expr))
6449 	/* Null pointer values are OK in C++11.  */;
6450       else if (TREE_CODE (expr) != ADDR_EXPR
6451 	       && TREE_CODE (expr_type) != ARRAY_TYPE)
6452 	{
6453 	  if (VAR_P (expr))
6454 	    {
6455 	      if (complain & tf_error)
6456 		error ("%qD is not a valid template argument "
6457 		       "because %qD is a variable, not the address of "
6458 		       "a variable", expr, expr);
6459 	      return NULL_TREE;
6460 	    }
6461 	  if (POINTER_TYPE_P (expr_type))
6462 	    {
6463 	      if (complain & tf_error)
6464 		error ("%qE is not a valid template argument for %qT "
6465 		       "because it is not the address of a variable",
6466 		       expr, type);
6467 	      return NULL_TREE;
6468 	    }
6469 	  /* Other values, like integer constants, might be valid
6470 	     non-type arguments of some other type.  */
6471 	  return error_mark_node;
6472 	}
6473       else
6474 	{
6475 	  tree decl;
6476 
6477 	  decl = ((TREE_CODE (expr) == ADDR_EXPR)
6478 		  ? TREE_OPERAND (expr, 0) : expr);
6479 	  if (!VAR_P (decl))
6480 	    {
6481 	      if (complain & tf_error)
6482 		error ("%qE is not a valid template argument of type %qT "
6483 		       "because %qE is not a variable", expr, type, decl);
6484 	      return NULL_TREE;
6485 	    }
6486 	  else if (cxx_dialect < cxx11 && !DECL_EXTERNAL_LINKAGE_P (decl))
6487 	    {
6488 	      if (complain & tf_error)
6489 		error ("%qE is not a valid template argument of type %qT "
6490 		       "because %qD does not have external linkage",
6491 		       expr, type, decl);
6492 	      return NULL_TREE;
6493 	    }
6494 	  else if (cxx_dialect >= cxx11 && decl_linkage (decl) == lk_none)
6495 	    {
6496 	      if (complain & tf_error)
6497 		error ("%qE is not a valid template argument of type %qT "
6498 		       "because %qD has no linkage", expr, type, decl);
6499 	      return NULL_TREE;
6500 	    }
6501 	}
6502 
6503       expr = decay_conversion (expr, complain);
6504       if (expr == error_mark_node)
6505 	return error_mark_node;
6506 
6507       expr = perform_qualification_conversions (type, expr);
6508       if (expr == error_mark_node)
6509 	return error_mark_node;
6510     }
6511   /* [temp.arg.nontype]/5, bullet 3
6512 
6513      For a non-type template-parameter of type reference to object, no
6514      conversions apply. The type referred to by the reference may be more
6515      cv-qualified than the (otherwise identical) type of the
6516      template-argument. The template-parameter is bound directly to the
6517      template-argument, which must be an lvalue.  */
6518   else if (TYPE_REF_OBJ_P (type))
6519     {
6520       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
6521 						      expr_type))
6522 	return error_mark_node;
6523 
6524       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
6525 	{
6526 	  if (complain & tf_error)
6527 	    error ("%qE is not a valid template argument for type %qT "
6528 		   "because of conflicts in cv-qualification", expr, type);
6529 	  return NULL_TREE;
6530 	}
6531 
6532       if (!real_lvalue_p (expr))
6533 	{
6534 	  if (complain & tf_error)
6535 	    error ("%qE is not a valid template argument for type %qT "
6536 		   "because it is not an lvalue", expr, type);
6537 	  return NULL_TREE;
6538 	}
6539 
6540       /* [temp.arg.nontype]/1
6541 
6542 	 A template-argument for a non-type, non-template template-parameter
6543 	 shall be one of: [...]
6544 
6545 	 -- the address of an object or function with external linkage.  */
6546       if (INDIRECT_REF_P (expr)
6547 	  && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
6548 	{
6549 	  expr = TREE_OPERAND (expr, 0);
6550 	  if (DECL_P (expr))
6551 	    {
6552 	      if (complain & tf_error)
6553 		error ("%q#D is not a valid template argument for type %qT "
6554 		       "because a reference variable does not have a constant "
6555 		       "address", expr, type);
6556 	      return NULL_TREE;
6557 	    }
6558 	}
6559 
6560       if (!DECL_P (expr))
6561 	{
6562 	  if (complain & tf_error)
6563 	    error ("%qE is not a valid template argument for type %qT "
6564 		   "because it is not an object with linkage",
6565 		   expr, type);
6566 	  return NULL_TREE;
6567 	}
6568 
6569       /* DR 1155 allows internal linkage in C++11 and up.  */
6570       linkage_kind linkage = decl_linkage (expr);
6571       if (linkage < (cxx_dialect >= cxx11 ? lk_internal : lk_external))
6572 	{
6573 	  if (complain & tf_error)
6574 	    error ("%qE is not a valid template argument for type %qT "
6575 		   "because object %qD does not have linkage",
6576 		   expr, type, expr);
6577 	  return NULL_TREE;
6578 	}
6579 
6580       expr = build_nop (type, build_address (expr));
6581     }
6582   /* [temp.arg.nontype]/5, bullet 4
6583 
6584      For a non-type template-parameter of type pointer to function, only
6585      the function-to-pointer conversion (_conv.func_) is applied. If the
6586      template-argument represents a set of overloaded functions (or a
6587      pointer to such), the matching function is selected from the set
6588      (_over.over_).  */
6589   else if (TYPE_PTRFN_P (type))
6590     {
6591       /* If the argument is a template-id, we might not have enough
6592 	 context information to decay the pointer.  */
6593       if (!type_unknown_p (expr_type))
6594 	{
6595 	  expr = decay_conversion (expr, complain);
6596 	  if (expr == error_mark_node)
6597 	    return error_mark_node;
6598 	}
6599 
6600       if (cxx_dialect >= cxx11 && integer_zerop (expr))
6601 	/* Null pointer values are OK in C++11.  */
6602 	return perform_qualification_conversions (type, expr);
6603 
6604       expr = convert_nontype_argument_function (type, expr, complain);
6605       if (!expr || expr == error_mark_node)
6606 	return expr;
6607     }
6608   /* [temp.arg.nontype]/5, bullet 5
6609 
6610      For a non-type template-parameter of type reference to function, no
6611      conversions apply. If the template-argument represents a set of
6612      overloaded functions, the matching function is selected from the set
6613      (_over.over_).  */
6614   else if (TYPE_REFFN_P (type))
6615     {
6616       if (TREE_CODE (expr) == ADDR_EXPR)
6617 	{
6618 	  if (complain & tf_error)
6619 	    {
6620 	      error ("%qE is not a valid template argument for type %qT "
6621 		     "because it is a pointer", expr, type);
6622 	      inform (input_location, "try using %qE instead",
6623 		      TREE_OPERAND (expr, 0));
6624 	    }
6625 	  return NULL_TREE;
6626 	}
6627 
6628       expr = convert_nontype_argument_function (type, expr, complain);
6629       if (!expr || expr == error_mark_node)
6630 	return expr;
6631 
6632       expr = build_nop (type, build_address (expr));
6633     }
6634   /* [temp.arg.nontype]/5, bullet 6
6635 
6636      For a non-type template-parameter of type pointer to member function,
6637      no conversions apply. If the template-argument represents a set of
6638      overloaded member functions, the matching member function is selected
6639      from the set (_over.over_).  */
6640   else if (TYPE_PTRMEMFUNC_P (type))
6641     {
6642       expr = instantiate_type (type, expr, tf_none);
6643       if (expr == error_mark_node)
6644 	return error_mark_node;
6645 
6646       /* [temp.arg.nontype] bullet 1 says the pointer to member
6647          expression must be a pointer-to-member constant.  */
6648       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
6649 	return error_mark_node;
6650 
6651       /* There is no way to disable standard conversions in
6652 	 resolve_address_of_overloaded_function (called by
6653 	 instantiate_type). It is possible that the call succeeded by
6654 	 converting &B::I to &D::I (where B is a base of D), so we need
6655 	 to reject this conversion here.
6656 
6657 	 Actually, even if there was a way to disable standard conversions,
6658 	 it would still be better to reject them here so that we can
6659 	 provide a superior diagnostic.  */
6660       if (!same_type_p (TREE_TYPE (expr), type))
6661 	{
6662 	  if (complain & tf_error)
6663 	    {
6664 	      error ("%qE is not a valid template argument for type %qT "
6665 		     "because it is of type %qT", expr, type,
6666 		     TREE_TYPE (expr));
6667 	      /* If we are just one standard conversion off, explain.  */
6668 	      if (can_convert_standard (type, TREE_TYPE (expr), complain))
6669 		inform (input_location,
6670 			"standard conversions are not allowed in this context");
6671 	    }
6672 	  return NULL_TREE;
6673 	}
6674     }
6675   /* [temp.arg.nontype]/5, bullet 7
6676 
6677      For a non-type template-parameter of type pointer to data member,
6678      qualification conversions (_conv.qual_) are applied.  */
6679   else if (TYPE_PTRDATAMEM_P (type))
6680     {
6681       /* [temp.arg.nontype] bullet 1 says the pointer to member
6682          expression must be a pointer-to-member constant.  */
6683       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
6684 	return error_mark_node;
6685 
6686       expr = perform_qualification_conversions (type, expr);
6687       if (expr == error_mark_node)
6688 	return expr;
6689     }
6690   else if (NULLPTR_TYPE_P (type))
6691     {
6692       if (expr != nullptr_node)
6693 	{
6694 	  if (complain & tf_error)
6695 	    error ("%qE is not a valid template argument for type %qT "
6696 		   "because it is of type %qT", expr, type, TREE_TYPE (expr));
6697 	  return NULL_TREE;
6698 	}
6699       return expr;
6700     }
6701   /* A template non-type parameter must be one of the above.  */
6702   else
6703     gcc_unreachable ();
6704 
6705   /* Sanity check: did we actually convert the argument to the
6706      right type?  */
6707   gcc_assert (same_type_ignoring_top_level_qualifiers_p
6708 	      (type, TREE_TYPE (expr)));
6709   return convert_from_reference (expr);
6710 }
6711 
6712 /* Subroutine of coerce_template_template_parms, which returns 1 if
6713    PARM_PARM and ARG_PARM match using the rule for the template
6714    parameters of template template parameters. Both PARM and ARG are
6715    template parameters; the rest of the arguments are the same as for
6716    coerce_template_template_parms.
6717  */
6718 static int
coerce_template_template_parm(tree parm,tree arg,tsubst_flags_t complain,tree in_decl,tree outer_args)6719 coerce_template_template_parm (tree parm,
6720                               tree arg,
6721                               tsubst_flags_t complain,
6722                               tree in_decl,
6723                               tree outer_args)
6724 {
6725   if (arg == NULL_TREE || error_operand_p (arg)
6726       || parm == NULL_TREE || error_operand_p (parm))
6727     return 0;
6728 
6729   if (TREE_CODE (arg) != TREE_CODE (parm))
6730     return 0;
6731 
6732   switch (TREE_CODE (parm))
6733     {
6734     case TEMPLATE_DECL:
6735       /* We encounter instantiations of templates like
6736 	 template <template <template <class> class> class TT>
6737 	 class C;  */
6738       {
6739 	tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
6740 	tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
6741 
6742 	if (!coerce_template_template_parms
6743 	    (parmparm, argparm, complain, in_decl, outer_args))
6744 	  return 0;
6745       }
6746       /* Fall through.  */
6747 
6748     case TYPE_DECL:
6749       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
6750 	  && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
6751 	/* Argument is a parameter pack but parameter is not.  */
6752 	return 0;
6753       break;
6754 
6755     case PARM_DECL:
6756       /* The tsubst call is used to handle cases such as
6757 
6758            template <int> class C {};
6759 	   template <class T, template <T> class TT> class D {};
6760 	   D<int, C> d;
6761 
6762 	 i.e. the parameter list of TT depends on earlier parameters.  */
6763       if (!uses_template_parms (TREE_TYPE (arg)))
6764 	{
6765 	  tree t = tsubst (TREE_TYPE (parm), outer_args, complain, in_decl);
6766 	  if (!uses_template_parms (t)
6767 	      && !same_type_p (t, TREE_TYPE (arg)))
6768 	    return 0;
6769 	}
6770 
6771       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
6772 	  && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
6773 	/* Argument is a parameter pack but parameter is not.  */
6774 	return 0;
6775 
6776       break;
6777 
6778     default:
6779       gcc_unreachable ();
6780     }
6781 
6782   return 1;
6783 }
6784 
6785 
6786 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
6787    template template parameters.  Both PARM_PARMS and ARG_PARMS are
6788    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
6789    or PARM_DECL.
6790 
6791    Consider the example:
6792      template <class T> class A;
6793      template<template <class U> class TT> class B;
6794 
6795    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
6796    the parameters to A, and OUTER_ARGS contains A.  */
6797 
6798 static int
coerce_template_template_parms(tree parm_parms,tree arg_parms,tsubst_flags_t complain,tree in_decl,tree outer_args)6799 coerce_template_template_parms (tree parm_parms,
6800 				tree arg_parms,
6801 				tsubst_flags_t complain,
6802 				tree in_decl,
6803 				tree outer_args)
6804 {
6805   int nparms, nargs, i;
6806   tree parm, arg;
6807   int variadic_p = 0;
6808 
6809   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
6810   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
6811 
6812   nparms = TREE_VEC_LENGTH (parm_parms);
6813   nargs = TREE_VEC_LENGTH (arg_parms);
6814 
6815   /* Determine whether we have a parameter pack at the end of the
6816      template template parameter's template parameter list.  */
6817   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
6818     {
6819       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
6820 
6821       if (error_operand_p (parm))
6822 	return 0;
6823 
6824       switch (TREE_CODE (parm))
6825         {
6826         case TEMPLATE_DECL:
6827         case TYPE_DECL:
6828           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
6829             variadic_p = 1;
6830           break;
6831 
6832         case PARM_DECL:
6833           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
6834             variadic_p = 1;
6835           break;
6836 
6837         default:
6838           gcc_unreachable ();
6839         }
6840     }
6841 
6842   if (nargs != nparms
6843       && !(variadic_p && nargs >= nparms - 1))
6844     return 0;
6845 
6846   /* Check all of the template parameters except the parameter pack at
6847      the end (if any).  */
6848   for (i = 0; i < nparms - variadic_p; ++i)
6849     {
6850       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
6851           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
6852         continue;
6853 
6854       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
6855       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
6856 
6857       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
6858                                           outer_args))
6859 	return 0;
6860 
6861     }
6862 
6863   if (variadic_p)
6864     {
6865       /* Check each of the template parameters in the template
6866 	 argument against the template parameter pack at the end of
6867 	 the template template parameter.  */
6868       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
6869 	return 0;
6870 
6871       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
6872 
6873       for (; i < nargs; ++i)
6874         {
6875           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
6876             continue;
6877 
6878           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
6879 
6880           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
6881                                               outer_args))
6882             return 0;
6883         }
6884     }
6885 
6886   return 1;
6887 }
6888 
6889 /* Verifies that the deduced template arguments (in TARGS) for the
6890    template template parameters (in TPARMS) represent valid bindings,
6891    by comparing the template parameter list of each template argument
6892    to the template parameter list of its corresponding template
6893    template parameter, in accordance with DR150. This
6894    routine can only be called after all template arguments have been
6895    deduced. It will return TRUE if all of the template template
6896    parameter bindings are okay, FALSE otherwise.  */
6897 bool
template_template_parm_bindings_ok_p(tree tparms,tree targs)6898 template_template_parm_bindings_ok_p (tree tparms, tree targs)
6899 {
6900   int i, ntparms = TREE_VEC_LENGTH (tparms);
6901   bool ret = true;
6902 
6903   /* We're dealing with template parms in this process.  */
6904   ++processing_template_decl;
6905 
6906   targs = INNERMOST_TEMPLATE_ARGS (targs);
6907 
6908   for (i = 0; i < ntparms; ++i)
6909     {
6910       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
6911       tree targ = TREE_VEC_ELT (targs, i);
6912 
6913       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
6914 	{
6915 	  tree packed_args = NULL_TREE;
6916 	  int idx, len = 1;
6917 
6918 	  if (ARGUMENT_PACK_P (targ))
6919 	    {
6920 	      /* Look inside the argument pack.  */
6921 	      packed_args = ARGUMENT_PACK_ARGS (targ);
6922 	      len = TREE_VEC_LENGTH (packed_args);
6923 	    }
6924 
6925 	  for (idx = 0; idx < len; ++idx)
6926 	    {
6927 	      tree targ_parms = NULL_TREE;
6928 
6929 	      if (packed_args)
6930 		/* Extract the next argument from the argument
6931 		   pack.  */
6932 		targ = TREE_VEC_ELT (packed_args, idx);
6933 
6934 	      if (PACK_EXPANSION_P (targ))
6935 		/* Look at the pattern of the pack expansion.  */
6936 		targ = PACK_EXPANSION_PATTERN (targ);
6937 
6938 	      /* Extract the template parameters from the template
6939 		 argument.  */
6940 	      if (TREE_CODE (targ) == TEMPLATE_DECL)
6941 		targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
6942 	      else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
6943 		targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
6944 
6945 	      /* Verify that we can coerce the template template
6946 		 parameters from the template argument to the template
6947 		 parameter.  This requires an exact match.  */
6948 	      if (targ_parms
6949 		  && !coerce_template_template_parms
6950 		       (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
6951 			targ_parms,
6952 			tf_none,
6953 			tparm,
6954 			targs))
6955 		{
6956 		  ret = false;
6957 		  goto out;
6958 		}
6959 	    }
6960 	}
6961     }
6962 
6963  out:
6964 
6965   --processing_template_decl;
6966   return ret;
6967 }
6968 
6969 /* Since type attributes aren't mangled, we need to strip them from
6970    template type arguments.  */
6971 
6972 static tree
canonicalize_type_argument(tree arg,tsubst_flags_t complain)6973 canonicalize_type_argument (tree arg, tsubst_flags_t complain)
6974 {
6975   if (!arg || arg == error_mark_node || arg == TYPE_CANONICAL (arg))
6976     return arg;
6977   bool removed_attributes = false;
6978   tree canon = strip_typedefs (arg, &removed_attributes);
6979   if (removed_attributes
6980       && (complain & tf_warning))
6981     warning (OPT_Wignored_attributes,
6982 	     "ignoring attributes on template argument %qT", arg);
6983   return canon;
6984 }
6985 
6986 // A template declaration can be substituted for a constrained
6987 // template template parameter only when the argument is more
6988 // constrained than the parameter.
6989 static bool
is_compatible_template_arg(tree parm,tree arg)6990 is_compatible_template_arg (tree parm, tree arg)
6991 {
6992   tree parm_cons = get_constraints (parm);
6993 
6994   /* For now, allow constrained template template arguments
6995      and unconstrained template template parameters.  */
6996   if (parm_cons == NULL_TREE)
6997     return true;
6998 
6999   tree arg_cons = get_constraints (arg);
7000 
7001   // If the template parameter is constrained, we need to rewrite its
7002   // constraints in terms of the ARG's template parameters. This ensures
7003   // that all of the template parameter types will have the same depth.
7004   //
7005   // Note that this is only valid when coerce_template_template_parm is
7006   // true for the innermost template parameters of PARM and ARG. In other
7007   // words, because coercion is successful, this conversion will be valid.
7008   if (parm_cons)
7009     {
7010       tree args = template_parms_to_args (DECL_TEMPLATE_PARMS (arg));
7011       parm_cons = tsubst_constraint_info (parm_cons,
7012 					  INNERMOST_TEMPLATE_ARGS (args),
7013 					  tf_none, NULL_TREE);
7014       if (parm_cons == error_mark_node)
7015         return false;
7016     }
7017 
7018   return subsumes (parm_cons, arg_cons);
7019 }
7020 
7021 // Convert a placeholder argument into a binding to the original
7022 // parameter. The original parameter is saved as the TREE_TYPE of
7023 // ARG.
7024 static inline tree
convert_wildcard_argument(tree parm,tree arg)7025 convert_wildcard_argument (tree parm, tree arg)
7026 {
7027   TREE_TYPE (arg) = parm;
7028   return arg;
7029 }
7030 
7031 /* Convert the indicated template ARG as necessary to match the
7032    indicated template PARM.  Returns the converted ARG, or
7033    error_mark_node if the conversion was unsuccessful.  Error and
7034    warning messages are issued under control of COMPLAIN.  This
7035    conversion is for the Ith parameter in the parameter list.  ARGS is
7036    the full set of template arguments deduced so far.  */
7037 
7038 static tree
convert_template_argument(tree parm,tree arg,tree args,tsubst_flags_t complain,int i,tree in_decl)7039 convert_template_argument (tree parm,
7040 			   tree arg,
7041 			   tree args,
7042 			   tsubst_flags_t complain,
7043 			   int i,
7044 			   tree in_decl)
7045 {
7046   tree orig_arg;
7047   tree val;
7048   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
7049 
7050   if (parm == error_mark_node)
7051     return error_mark_node;
7052 
7053   /* Trivially convert placeholders. */
7054   if (TREE_CODE (arg) == WILDCARD_DECL)
7055     return convert_wildcard_argument (parm, arg);
7056 
7057   if (TREE_CODE (arg) == TREE_LIST
7058       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
7059     {
7060       /* The template argument was the name of some
7061 	 member function.  That's usually
7062 	 invalid, but static members are OK.  In any
7063 	 case, grab the underlying fields/functions
7064 	 and issue an error later if required.  */
7065       orig_arg = TREE_VALUE (arg);
7066       TREE_TYPE (arg) = unknown_type_node;
7067     }
7068 
7069   orig_arg = arg;
7070 
7071   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
7072   requires_type = (TREE_CODE (parm) == TYPE_DECL
7073 		   || requires_tmpl_type);
7074 
7075   /* When determining whether an argument pack expansion is a template,
7076      look at the pattern.  */
7077   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
7078     arg = PACK_EXPANSION_PATTERN (arg);
7079 
7080   /* Deal with an injected-class-name used as a template template arg.  */
7081   if (requires_tmpl_type && CLASS_TYPE_P (arg))
7082     {
7083       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
7084       if (TREE_CODE (t) == TEMPLATE_DECL)
7085 	{
7086 	  if (cxx_dialect >= cxx11)
7087 	    /* OK under DR 1004.  */;
7088 	  else if (complain & tf_warning_or_error)
7089 	    pedwarn (input_location, OPT_Wpedantic, "injected-class-name %qD"
7090 		     " used as template template argument", TYPE_NAME (arg));
7091 	  else if (flag_pedantic_errors)
7092 	    t = arg;
7093 
7094 	  arg = t;
7095 	}
7096     }
7097 
7098   is_tmpl_type =
7099     ((TREE_CODE (arg) == TEMPLATE_DECL
7100       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
7101      || (requires_tmpl_type && TREE_CODE (arg) == TYPE_ARGUMENT_PACK)
7102      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
7103      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
7104 
7105   if (is_tmpl_type
7106       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
7107 	  || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
7108     arg = TYPE_STUB_DECL (arg);
7109 
7110   is_type = TYPE_P (arg) || is_tmpl_type;
7111 
7112   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
7113       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
7114     {
7115       if (TREE_CODE (TREE_OPERAND (arg, 1)) == BIT_NOT_EXPR)
7116 	{
7117 	  if (complain & tf_error)
7118 	    error ("invalid use of destructor %qE as a type", orig_arg);
7119 	  return error_mark_node;
7120 	}
7121 
7122       permerror (input_location,
7123 		 "to refer to a type member of a template parameter, "
7124 		 "use %<typename %E%>", orig_arg);
7125 
7126       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
7127 				     TREE_OPERAND (arg, 1),
7128 				     typename_type,
7129 				     complain);
7130       arg = orig_arg;
7131       is_type = 1;
7132     }
7133   if (is_type != requires_type)
7134     {
7135       if (in_decl)
7136 	{
7137 	  if (complain & tf_error)
7138 	    {
7139 	      error ("type/value mismatch at argument %d in template "
7140 		     "parameter list for %qD",
7141 		     i + 1, in_decl);
7142 	      if (is_type)
7143 		inform (input_location,
7144 			"  expected a constant of type %qT, got %qT",
7145 			TREE_TYPE (parm),
7146 			(DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
7147 	      else if (requires_tmpl_type)
7148 		inform (input_location,
7149 			"  expected a class template, got %qE", orig_arg);
7150 	      else
7151 		inform (input_location,
7152 			"  expected a type, got %qE", orig_arg);
7153 	    }
7154 	}
7155       return error_mark_node;
7156     }
7157   if (is_tmpl_type ^ requires_tmpl_type)
7158     {
7159       if (in_decl && (complain & tf_error))
7160 	{
7161 	  error ("type/value mismatch at argument %d in template "
7162 		 "parameter list for %qD",
7163 		 i + 1, in_decl);
7164 	  if (is_tmpl_type)
7165 	    inform (input_location,
7166 		    "  expected a type, got %qT", DECL_NAME (arg));
7167 	  else
7168 	    inform (input_location,
7169 		    "  expected a class template, got %qT", orig_arg);
7170 	}
7171       return error_mark_node;
7172     }
7173 
7174   if (is_type)
7175     {
7176       if (requires_tmpl_type)
7177 	{
7178 	  if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
7179 	    val = orig_arg;
7180 	  else if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
7181 	    /* The number of argument required is not known yet.
7182 	       Just accept it for now.  */
7183 	    val = TREE_TYPE (arg);
7184 	  else
7185 	    {
7186 	      tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
7187 	      tree argparm;
7188 
7189 	      /* Strip alias templates that are equivalent to another
7190 		 template.  */
7191 	      arg = get_underlying_template (arg);
7192               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
7193 
7194 	      if (coerce_template_template_parms (parmparm, argparm,
7195 						  complain, in_decl,
7196 						  args))
7197 		{
7198 		  val = arg;
7199 
7200 		  /* TEMPLATE_TEMPLATE_PARM node is preferred over
7201 		     TEMPLATE_DECL.  */
7202 		  if (val != error_mark_node)
7203                     {
7204                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
7205                         val = TREE_TYPE (val);
7206 		      if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
7207 			val = make_pack_expansion (val);
7208                     }
7209 		}
7210 	      else
7211 		{
7212 		  if (in_decl && (complain & tf_error))
7213 		    {
7214 		      error ("type/value mismatch at argument %d in "
7215 			     "template parameter list for %qD",
7216 			     i + 1, in_decl);
7217 		      inform (input_location,
7218 			      "  expected a template of type %qD, got %qT",
7219 			      parm, orig_arg);
7220 		    }
7221 
7222 		  val = error_mark_node;
7223 		}
7224 
7225               // Check that the constraints are compatible before allowing the
7226               // substitution.
7227               if (val != error_mark_node)
7228                 if (!is_compatible_template_arg (parm, arg))
7229                   {
7230 		    if (in_decl && (complain & tf_error))
7231                       {
7232                         error ("constraint mismatch at argument %d in "
7233                                "template parameter list for %qD",
7234                                i + 1, in_decl);
7235                         inform (input_location, "  expected %qD but got %qD",
7236                                 parm, arg);
7237                       }
7238 		    val = error_mark_node;
7239                   }
7240 	    }
7241 	}
7242       else
7243 	val = orig_arg;
7244       /* We only form one instance of each template specialization.
7245 	 Therefore, if we use a non-canonical variant (i.e., a
7246 	 typedef), any future messages referring to the type will use
7247 	 the typedef, which is confusing if those future uses do not
7248 	 themselves also use the typedef.  */
7249       if (TYPE_P (val))
7250 	val = canonicalize_type_argument (val, complain);
7251     }
7252   else
7253     {
7254       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
7255 
7256       if (invalid_nontype_parm_type_p (t, complain))
7257 	return error_mark_node;
7258 
7259       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
7260 	{
7261 	  if (same_type_p (t, TREE_TYPE (orig_arg)))
7262 	    val = orig_arg;
7263 	  else
7264 	    {
7265 	      /* Not sure if this is reachable, but it doesn't hurt
7266 		 to be robust.  */
7267 	      error ("type mismatch in nontype parameter pack");
7268 	      val = error_mark_node;
7269 	    }
7270 	}
7271       else if (!dependent_template_arg_p (orig_arg)
7272 	       && !uses_template_parms (t))
7273 	/* We used to call digest_init here.  However, digest_init
7274 	   will report errors, which we don't want when complain
7275 	   is zero.  More importantly, digest_init will try too
7276 	   hard to convert things: for example, `0' should not be
7277 	   converted to pointer type at this point according to
7278 	   the standard.  Accepting this is not merely an
7279 	   extension, since deciding whether or not these
7280 	   conversions can occur is part of determining which
7281 	   function template to call, or whether a given explicit
7282 	   argument specification is valid.  */
7283 	val = convert_nontype_argument (t, orig_arg, complain);
7284       else
7285 	{
7286 	  bool removed_attr = false;
7287 	  val = strip_typedefs_expr (orig_arg, &removed_attr);
7288 	}
7289 
7290       if (val == NULL_TREE)
7291 	val = error_mark_node;
7292       else if (val == error_mark_node && (complain & tf_error))
7293 	error ("could not convert template argument %qE to %qT",  orig_arg, t);
7294 
7295       if (INDIRECT_REF_P (val))
7296         {
7297           /* Reject template arguments that are references to built-in
7298              functions with no library fallbacks.  */
7299           const_tree inner = TREE_OPERAND (val, 0);
7300           if (TREE_CODE (TREE_TYPE (inner)) == REFERENCE_TYPE
7301               && TREE_CODE (TREE_TYPE (TREE_TYPE (inner))) == FUNCTION_TYPE
7302               && TREE_CODE (TREE_TYPE (inner)) == REFERENCE_TYPE
7303               && 0 < TREE_OPERAND_LENGTH (inner)
7304               && reject_gcc_builtin (TREE_OPERAND (inner, 0)))
7305               return error_mark_node;
7306         }
7307 
7308       if (TREE_CODE (val) == SCOPE_REF)
7309 	{
7310 	  /* Strip typedefs from the SCOPE_REF.  */
7311 	  tree type = canonicalize_type_argument (TREE_TYPE (val), complain);
7312 	  tree scope = canonicalize_type_argument (TREE_OPERAND (val, 0),
7313 						   complain);
7314 	  val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
7315 				      QUALIFIED_NAME_IS_TEMPLATE (val));
7316 	}
7317     }
7318 
7319   return val;
7320 }
7321 
7322 /* Coerces the remaining template arguments in INNER_ARGS (from
7323    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
7324    Returns the coerced argument pack. PARM_IDX is the position of this
7325    parameter in the template parameter list. ARGS is the original
7326    template argument list.  */
7327 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)7328 coerce_template_parameter_pack (tree parms,
7329                                 int parm_idx,
7330                                 tree args,
7331                                 tree inner_args,
7332                                 int arg_idx,
7333                                 tree new_args,
7334                                 int* lost,
7335                                 tree in_decl,
7336                                 tsubst_flags_t complain)
7337 {
7338   tree parm = TREE_VEC_ELT (parms, parm_idx);
7339   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
7340   tree packed_args;
7341   tree argument_pack;
7342   tree packed_parms = NULL_TREE;
7343 
7344   if (arg_idx > nargs)
7345     arg_idx = nargs;
7346 
7347   if (tree packs = fixed_parameter_pack_p (TREE_VALUE (parm)))
7348     {
7349       /* When the template parameter is a non-type template parameter pack
7350          or template template parameter pack whose type or template
7351          parameters use parameter packs, we know exactly how many arguments
7352          we are looking for.  Build a vector of the instantiated decls for
7353          these template parameters in PACKED_PARMS.  */
7354       /* We can't use make_pack_expansion here because it would interpret a
7355 	 _DECL as a use rather than a declaration.  */
7356       tree decl = TREE_VALUE (parm);
7357       tree exp = cxx_make_type (TYPE_PACK_EXPANSION);
7358       SET_PACK_EXPANSION_PATTERN (exp, decl);
7359       PACK_EXPANSION_PARAMETER_PACKS (exp) = packs;
7360       SET_TYPE_STRUCTURAL_EQUALITY (exp);
7361 
7362       TREE_VEC_LENGTH (args)--;
7363       packed_parms = tsubst_pack_expansion (exp, args, complain, decl);
7364       TREE_VEC_LENGTH (args)++;
7365 
7366       if (packed_parms == error_mark_node)
7367         return error_mark_node;
7368 
7369       /* If we're doing a partial instantiation of a member template,
7370          verify that all of the types used for the non-type
7371          template parameter pack are, in fact, valid for non-type
7372          template parameters.  */
7373       if (arg_idx < nargs
7374           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
7375         {
7376           int j, len = TREE_VEC_LENGTH (packed_parms);
7377           for (j = 0; j < len; ++j)
7378             {
7379               tree t = TREE_TYPE (TREE_VEC_ELT (packed_parms, j));
7380               if (invalid_nontype_parm_type_p (t, complain))
7381                 return error_mark_node;
7382             }
7383 	  /* We don't know how many args we have yet, just
7384 	     use the unconverted ones for now.  */
7385 	  return NULL_TREE;
7386         }
7387 
7388       packed_args = make_tree_vec (TREE_VEC_LENGTH (packed_parms));
7389     }
7390   /* Check if we have a placeholder pack, which indicates we're
7391      in the context of a introduction list.  In that case we want
7392      to match this pack to the single placeholder.  */
7393   else if (arg_idx < nargs
7394            && TREE_CODE (TREE_VEC_ELT (inner_args, arg_idx)) == WILDCARD_DECL
7395            && WILDCARD_PACK_P (TREE_VEC_ELT (inner_args, arg_idx)))
7396     {
7397       nargs = arg_idx + 1;
7398       packed_args = make_tree_vec (1);
7399     }
7400   else
7401     packed_args = make_tree_vec (nargs - arg_idx);
7402 
7403   /* Convert the remaining arguments, which will be a part of the
7404      parameter pack "parm".  */
7405   int first_pack_arg = arg_idx;
7406   for (; arg_idx < nargs; ++arg_idx)
7407     {
7408       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
7409       tree actual_parm = TREE_VALUE (parm);
7410       int pack_idx = arg_idx - first_pack_arg;
7411 
7412       if (packed_parms)
7413         {
7414 	  /* Once we've packed as many args as we have types, stop.  */
7415 	  if (pack_idx >= TREE_VEC_LENGTH (packed_parms))
7416 	    break;
7417 	  else if (PACK_EXPANSION_P (arg))
7418 	    /* We don't know how many args we have yet, just
7419 	       use the unconverted ones for now.  */
7420 	    return NULL_TREE;
7421 	  else
7422 	    actual_parm = TREE_VEC_ELT (packed_parms, pack_idx);
7423         }
7424 
7425       if (arg == error_mark_node)
7426 	{
7427 	  if (complain & tf_error)
7428 	    error ("template argument %d is invalid", arg_idx + 1);
7429 	}
7430       else
7431 	arg = convert_template_argument (actual_parm,
7432 					 arg, new_args, complain, parm_idx,
7433 					 in_decl);
7434       if (arg == error_mark_node)
7435         (*lost)++;
7436       TREE_VEC_ELT (packed_args, pack_idx) = arg;
7437     }
7438 
7439   if (arg_idx - first_pack_arg < TREE_VEC_LENGTH (packed_args)
7440       && TREE_VEC_LENGTH (packed_args) > 0)
7441     {
7442       if (complain & tf_error)
7443 	error ("wrong number of template arguments (%d, should be %d)",
7444 	       arg_idx - first_pack_arg, TREE_VEC_LENGTH (packed_args));
7445       return error_mark_node;
7446     }
7447 
7448   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
7449       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
7450     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
7451   else
7452     {
7453       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
7454       TREE_TYPE (argument_pack)
7455         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
7456       TREE_CONSTANT (argument_pack) = 1;
7457     }
7458 
7459   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
7460   if (CHECKING_P)
7461     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
7462 					 TREE_VEC_LENGTH (packed_args));
7463   return argument_pack;
7464 }
7465 
7466 /* Returns the number of pack expansions in the template argument vector
7467    ARGS.  */
7468 
7469 static int
pack_expansion_args_count(tree args)7470 pack_expansion_args_count (tree args)
7471 {
7472   int i;
7473   int count = 0;
7474   if (args)
7475     for (i = 0; i < TREE_VEC_LENGTH (args); ++i)
7476       {
7477 	tree elt = TREE_VEC_ELT (args, i);
7478 	if (elt && PACK_EXPANSION_P (elt))
7479 	  ++count;
7480       }
7481   return count;
7482 }
7483 
7484 /* Convert all template arguments to their appropriate types, and
7485    return a vector containing the innermost resulting template
7486    arguments.  If any error occurs, return error_mark_node. Error and
7487    warning messages are issued under control of COMPLAIN.
7488 
7489    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
7490    for arguments not specified in ARGS.  Otherwise, if
7491    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
7492    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
7493    USE_DEFAULT_ARGS is false, then all arguments must be specified in
7494    ARGS.  */
7495 
7496 static tree
coerce_template_parms(tree parms,tree args,tree in_decl,tsubst_flags_t complain,bool require_all_args,bool use_default_args)7497 coerce_template_parms (tree parms,
7498 		       tree args,
7499 		       tree in_decl,
7500 		       tsubst_flags_t complain,
7501 		       bool require_all_args,
7502 		       bool use_default_args)
7503 {
7504   int nparms, nargs, parm_idx, arg_idx, lost = 0;
7505   tree orig_inner_args;
7506   tree inner_args;
7507   tree new_args;
7508   tree new_inner_args;
7509   int saved_unevaluated_operand;
7510   int saved_inhibit_evaluation_warnings;
7511 
7512   /* When used as a boolean value, indicates whether this is a
7513      variadic template parameter list. Since it's an int, we can also
7514      subtract it from nparms to get the number of non-variadic
7515      parameters.  */
7516   int variadic_p = 0;
7517   int variadic_args_p = 0;
7518   int post_variadic_parms = 0;
7519 
7520   /* Likewise for parameters with default arguments.  */
7521   int default_p = 0;
7522 
7523   if (args == error_mark_node)
7524     return error_mark_node;
7525 
7526   nparms = TREE_VEC_LENGTH (parms);
7527 
7528   /* Determine if there are any parameter packs or default arguments.  */
7529   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
7530     {
7531       tree parm = TREE_VEC_ELT (parms, parm_idx);
7532       if (variadic_p)
7533 	++post_variadic_parms;
7534       if (template_parameter_pack_p (TREE_VALUE (parm)))
7535 	++variadic_p;
7536       if (TREE_PURPOSE (parm))
7537 	++default_p;
7538     }
7539 
7540   inner_args = orig_inner_args = INNERMOST_TEMPLATE_ARGS (args);
7541   /* If there are no parameters that follow a parameter pack, we need to
7542      expand any argument packs so that we can deduce a parameter pack from
7543      some non-packed args followed by an argument pack, as in variadic85.C.
7544      If there are such parameters, we need to leave argument packs intact
7545      so the arguments are assigned properly.  This can happen when dealing
7546      with a nested class inside a partial specialization of a class
7547      template, as in variadic92.C, or when deducing a template parameter pack
7548      from a sub-declarator, as in variadic114.C.  */
7549   if (!post_variadic_parms)
7550     inner_args = expand_template_argument_pack (inner_args);
7551 
7552   /* Count any pack expansion args.  */
7553   variadic_args_p = pack_expansion_args_count (inner_args);
7554 
7555   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
7556   if ((nargs > nparms && !variadic_p)
7557       || (nargs < nparms - variadic_p
7558 	  && require_all_args
7559 	  && !variadic_args_p
7560 	  && (!use_default_args
7561 	      || (TREE_VEC_ELT (parms, nargs) != error_mark_node
7562                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
7563     {
7564       if (complain & tf_error)
7565 	{
7566           if (variadic_p || default_p)
7567             {
7568               nparms -= variadic_p + default_p;
7569 	      error ("wrong number of template arguments "
7570 		     "(%d, should be at least %d)", nargs, nparms);
7571             }
7572 	  else
7573 	     error ("wrong number of template arguments "
7574 		    "(%d, should be %d)", nargs, nparms);
7575 
7576 	  if (in_decl)
7577 	    inform (DECL_SOURCE_LOCATION (in_decl),
7578 		    "provided for %qD", in_decl);
7579 	}
7580 
7581       return error_mark_node;
7582     }
7583   /* We can't pass a pack expansion to a non-pack parameter of an alias
7584      template (DR 1430).  */
7585   else if (in_decl
7586 	   && (DECL_ALIAS_TEMPLATE_P (in_decl)
7587 	       || concept_template_p (in_decl))
7588 	   && variadic_args_p
7589 	   && nargs - variadic_args_p < nparms - variadic_p)
7590     {
7591       if (complain & tf_error)
7592 	{
7593 	  for (int i = 0; i < TREE_VEC_LENGTH (inner_args); ++i)
7594 	    {
7595 	      tree arg = TREE_VEC_ELT (inner_args, i);
7596 	      tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
7597 
7598 	      if (PACK_EXPANSION_P (arg)
7599 		  && !template_parameter_pack_p (parm))
7600 		{
7601 		  if (DECL_ALIAS_TEMPLATE_P (in_decl))
7602 		    error_at (location_of (arg),
7603 			      "pack expansion argument for non-pack parameter "
7604 			      "%qD of alias template %qD", parm, in_decl);
7605 		  else
7606 		    error_at (location_of (arg),
7607 			      "pack expansion argument for non-pack parameter "
7608 			      "%qD of concept %qD", parm, in_decl);
7609 		  inform (DECL_SOURCE_LOCATION (parm), "declared here");
7610 		  goto found;
7611 		}
7612 	    }
7613 	  gcc_unreachable ();
7614 	found:;
7615 	}
7616       return error_mark_node;
7617     }
7618 
7619   /* We need to evaluate the template arguments, even though this
7620      template-id may be nested within a "sizeof".  */
7621   saved_unevaluated_operand = cp_unevaluated_operand;
7622   cp_unevaluated_operand = 0;
7623   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
7624   c_inhibit_evaluation_warnings = 0;
7625   new_inner_args = make_tree_vec (nparms);
7626   new_args = add_outermost_template_args (args, new_inner_args);
7627   int pack_adjust = 0;
7628   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
7629     {
7630       tree arg;
7631       tree parm;
7632 
7633       /* Get the Ith template parameter.  */
7634       parm = TREE_VEC_ELT (parms, parm_idx);
7635 
7636       if (parm == error_mark_node)
7637       {
7638         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
7639         continue;
7640       }
7641 
7642       /* Calculate the next argument.  */
7643       if (arg_idx < nargs)
7644 	arg = TREE_VEC_ELT (inner_args, arg_idx);
7645       else
7646 	arg = NULL_TREE;
7647 
7648       if (template_parameter_pack_p (TREE_VALUE (parm))
7649 	  && !(arg && ARGUMENT_PACK_P (arg)))
7650         {
7651 	  /* Some arguments will be placed in the
7652 	     template parameter pack PARM.  */
7653 	  arg = coerce_template_parameter_pack (parms, parm_idx, args,
7654 						inner_args, arg_idx,
7655 						new_args, &lost,
7656 						in_decl, complain);
7657 
7658 	  if (arg == NULL_TREE)
7659 	    {
7660 	      /* We don't know how many args we have yet, just use the
7661 		 unconverted (and still packed) ones for now.  */
7662 	      new_inner_args = orig_inner_args;
7663 	      arg_idx = nargs;
7664 	      break;
7665 	    }
7666 
7667           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
7668 
7669           /* Store this argument.  */
7670           if (arg == error_mark_node)
7671 	    {
7672 	      lost++;
7673 	      /* We are done with all of the arguments.  */
7674 	      arg_idx = nargs;
7675 	    }
7676 	  else
7677 	    {
7678 	      pack_adjust = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg)) - 1;
7679 	      arg_idx += pack_adjust;
7680 	    }
7681 
7682           continue;
7683         }
7684       else if (arg)
7685 	{
7686           if (PACK_EXPANSION_P (arg))
7687             {
7688 	      /* "If every valid specialization of a variadic template
7689 		 requires an empty template parameter pack, the template is
7690 		 ill-formed, no diagnostic required."  So check that the
7691 		 pattern works with this parameter.  */
7692 	      tree pattern = PACK_EXPANSION_PATTERN (arg);
7693 	      tree conv = convert_template_argument (TREE_VALUE (parm),
7694 						     pattern, new_args,
7695 						     complain, parm_idx,
7696 						     in_decl);
7697 	      if (conv == error_mark_node)
7698 		{
7699 		  inform (input_location, "so any instantiation with a "
7700 			 "non-empty parameter pack would be ill-formed");
7701 		  ++lost;
7702 		}
7703 	      else if (TYPE_P (conv) && !TYPE_P (pattern))
7704 		/* Recover from missing typename.  */
7705 		TREE_VEC_ELT (inner_args, arg_idx)
7706 		  = make_pack_expansion (conv);
7707 
7708               /* We don't know how many args we have yet, just
7709                  use the unconverted ones for now.  */
7710               new_inner_args = inner_args;
7711 	      arg_idx = nargs;
7712               break;
7713             }
7714         }
7715       else if (require_all_args)
7716 	{
7717 	  /* There must be a default arg in this case.  */
7718 	  arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
7719 				     complain, in_decl);
7720 	  /* The position of the first default template argument,
7721 	     is also the number of non-defaulted arguments in NEW_INNER_ARGS.
7722 	     Record that.  */
7723 	  if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
7724 	    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
7725 						 arg_idx - pack_adjust);
7726 	}
7727       else
7728 	break;
7729 
7730       if (arg == error_mark_node)
7731 	{
7732 	  if (complain & tf_error)
7733 	    error ("template argument %d is invalid", arg_idx + 1);
7734 	}
7735       else if (!arg)
7736         /* This only occurs if there was an error in the template
7737            parameter list itself (which we would already have
7738            reported) that we are trying to recover from, e.g., a class
7739            template with a parameter list such as
7740            template<typename..., typename>.  */
7741 	++lost;
7742       else
7743 	arg = convert_template_argument (TREE_VALUE (parm),
7744 					 arg, new_args, complain,
7745                                          parm_idx, in_decl);
7746 
7747       if (arg == error_mark_node)
7748 	lost++;
7749       TREE_VEC_ELT (new_inner_args, arg_idx - pack_adjust) = arg;
7750     }
7751   cp_unevaluated_operand = saved_unevaluated_operand;
7752   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
7753 
7754   if (variadic_p && arg_idx < nargs)
7755     {
7756       if (complain & tf_error)
7757 	{
7758 	  error ("wrong number of template arguments "
7759 		 "(%d, should be %d)", nargs, arg_idx);
7760 	  if (in_decl)
7761 	    error ("provided for %q+D", in_decl);
7762 	}
7763       return error_mark_node;
7764     }
7765 
7766   if (lost)
7767     return error_mark_node;
7768 
7769   if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
7770     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
7771 					 TREE_VEC_LENGTH (new_inner_args));
7772 
7773   return new_inner_args;
7774 }
7775 
7776 /* Convert all template arguments to their appropriate types, and
7777    return a vector containing the innermost resulting template
7778    arguments.  If any error occurs, return error_mark_node. Error and
7779    warning messages are not issued.
7780 
7781    Note that no function argument deduction is performed, and default
7782    arguments are used to fill in unspecified arguments. */
7783 tree
coerce_template_parms(tree parms,tree args,tree in_decl)7784 coerce_template_parms (tree parms, tree args, tree in_decl)
7785 {
7786   return coerce_template_parms (parms, args, in_decl, tf_none, true, true);
7787 }
7788 
7789 /* Convert all template arguments to their appropriate type, and
7790    instantiate default arguments as needed. This returns a vector
7791    containing the innermost resulting template arguments, or
7792    error_mark_node if unsuccessful.  */
7793 tree
coerce_template_parms(tree parms,tree args,tree in_decl,tsubst_flags_t complain)7794 coerce_template_parms (tree parms, tree args, tree in_decl,
7795                        tsubst_flags_t complain)
7796 {
7797   return coerce_template_parms (parms, args, in_decl, complain, true, true);
7798 }
7799 
7800 /* Like coerce_template_parms.  If PARMS represents all template
7801    parameters levels, this function returns a vector of vectors
7802    representing all the resulting argument levels.  Note that in this
7803    case, only the innermost arguments are coerced because the
7804    outermost ones are supposed to have been coerced already.
7805 
7806    Otherwise, if PARMS represents only (the innermost) vector of
7807    parameters, this function returns a vector containing just the
7808    innermost resulting arguments.  */
7809 
7810 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)7811 coerce_innermost_template_parms (tree parms,
7812 				  tree args,
7813 				  tree in_decl,
7814 				  tsubst_flags_t complain,
7815 				  bool require_all_args,
7816 				  bool use_default_args)
7817 {
7818   int parms_depth = TMPL_PARMS_DEPTH (parms);
7819   int args_depth = TMPL_ARGS_DEPTH (args);
7820   tree coerced_args;
7821 
7822   if (parms_depth > 1)
7823     {
7824       coerced_args = make_tree_vec (parms_depth);
7825       tree level;
7826       int cur_depth;
7827 
7828       for (level = parms, cur_depth = parms_depth;
7829 	   parms_depth > 0 && level != NULL_TREE;
7830 	   level = TREE_CHAIN (level), --cur_depth)
7831 	{
7832 	  tree l;
7833 	  if (cur_depth == args_depth)
7834 	    l = coerce_template_parms (TREE_VALUE (level),
7835 				       args, in_decl, complain,
7836 				       require_all_args,
7837 				       use_default_args);
7838 	  else
7839 	    l = TMPL_ARGS_LEVEL (args, cur_depth);
7840 
7841 	  if (l == error_mark_node)
7842 	    return error_mark_node;
7843 
7844 	  SET_TMPL_ARGS_LEVEL (coerced_args, cur_depth, l);
7845 	}
7846     }
7847   else
7848     coerced_args = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parms),
7849 					  args, in_decl, complain,
7850 					  require_all_args,
7851 					  use_default_args);
7852   return coerced_args;
7853 }
7854 
7855 /* Returns 1 if template args OT and NT are equivalent.  */
7856 
7857 int
template_args_equal(tree ot,tree nt)7858 template_args_equal (tree ot, tree nt)
7859 {
7860   if (nt == ot)
7861     return 1;
7862   if (nt == NULL_TREE || ot == NULL_TREE)
7863     return false;
7864 
7865   if (TREE_CODE (nt) == TREE_VEC)
7866     /* For member templates */
7867     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
7868   else if (PACK_EXPANSION_P (ot))
7869     return (PACK_EXPANSION_P (nt)
7870 	    && template_args_equal (PACK_EXPANSION_PATTERN (ot),
7871 				    PACK_EXPANSION_PATTERN (nt))
7872 	    && template_args_equal (PACK_EXPANSION_EXTRA_ARGS (ot),
7873 				    PACK_EXPANSION_EXTRA_ARGS (nt)));
7874   else if (ARGUMENT_PACK_P (ot))
7875     {
7876       int i, len;
7877       tree opack, npack;
7878 
7879       if (!ARGUMENT_PACK_P (nt))
7880 	return 0;
7881 
7882       opack = ARGUMENT_PACK_ARGS (ot);
7883       npack = ARGUMENT_PACK_ARGS (nt);
7884       len = TREE_VEC_LENGTH (opack);
7885       if (TREE_VEC_LENGTH (npack) != len)
7886 	return 0;
7887       for (i = 0; i < len; ++i)
7888 	if (!template_args_equal (TREE_VEC_ELT (opack, i),
7889 				  TREE_VEC_ELT (npack, i)))
7890 	  return 0;
7891       return 1;
7892     }
7893   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
7894     {
7895       /* We get here probably because we are in the middle of substituting
7896          into the pattern of a pack expansion. In that case the
7897 	 ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
7898 	 interested in. So we want to use the initial pack argument for
7899 	 the comparison.  */
7900       ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
7901       if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
7902 	nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
7903       return template_args_equal (ot, nt);
7904     }
7905   else if (TYPE_P (nt))
7906     {
7907       if (!TYPE_P (ot))
7908 	return false;
7909       /* Don't treat an alias template specialization with dependent
7910 	 arguments as equivalent to its underlying type when used as a
7911 	 template argument; we need them to be distinct so that we
7912 	 substitute into the specialization arguments at instantiation
7913 	 time.  And aliases can't be equivalent without being ==, so
7914 	 we don't need to look any deeper.  */
7915       if (TYPE_ALIAS_P (nt) || TYPE_ALIAS_P (ot))
7916 	return false;
7917       else
7918 	return same_type_p (ot, nt);
7919     }
7920   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
7921     return 0;
7922   else
7923     {
7924       /* Try to treat a template non-type argument that has been converted
7925 	 to the parameter type as equivalent to one that hasn't yet.  */
7926       for (enum tree_code code1 = TREE_CODE (ot);
7927 	   CONVERT_EXPR_CODE_P (code1)
7928 	     || code1 == NON_LVALUE_EXPR;
7929 	   code1 = TREE_CODE (ot))
7930 	ot = TREE_OPERAND (ot, 0);
7931       for (enum tree_code code2 = TREE_CODE (nt);
7932 	   CONVERT_EXPR_CODE_P (code2)
7933 	     || code2 == NON_LVALUE_EXPR;
7934 	   code2 = TREE_CODE (nt))
7935 	nt = TREE_OPERAND (nt, 0);
7936 
7937       return cp_tree_equal (ot, nt);
7938     }
7939 }
7940 
7941 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets of
7942    template arguments.  Returns 0 otherwise, and updates OLDARG_PTR and
7943    NEWARG_PTR with the offending arguments if they are non-NULL.  */
7944 
7945 int
comp_template_args(tree oldargs,tree newargs,tree * oldarg_ptr,tree * newarg_ptr)7946 comp_template_args (tree oldargs, tree newargs,
7947 		    tree *oldarg_ptr, tree *newarg_ptr)
7948 {
7949   int i;
7950 
7951   if (oldargs == newargs)
7952     return 1;
7953 
7954   if (!oldargs || !newargs)
7955     return 0;
7956 
7957   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
7958     return 0;
7959 
7960   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
7961     {
7962       tree nt = TREE_VEC_ELT (newargs, i);
7963       tree ot = TREE_VEC_ELT (oldargs, i);
7964 
7965       if (! template_args_equal (ot, nt))
7966 	{
7967 	  if (oldarg_ptr != NULL)
7968 	    *oldarg_ptr = ot;
7969 	  if (newarg_ptr != NULL)
7970 	    *newarg_ptr = nt;
7971 	  return 0;
7972 	}
7973     }
7974   return 1;
7975 }
7976 
7977 static void
add_pending_template(tree d)7978 add_pending_template (tree d)
7979 {
7980   tree ti = (TYPE_P (d)
7981 	     ? CLASSTYPE_TEMPLATE_INFO (d)
7982 	     : DECL_TEMPLATE_INFO (d));
7983   struct pending_template *pt;
7984   int level;
7985 
7986   if (TI_PENDING_TEMPLATE_FLAG (ti))
7987     return;
7988 
7989   /* We are called both from instantiate_decl, where we've already had a
7990      tinst_level pushed, and instantiate_template, where we haven't.
7991      Compensate.  */
7992   level = !current_tinst_level || current_tinst_level->decl != d;
7993 
7994   if (level)
7995     push_tinst_level (d);
7996 
7997   pt = ggc_alloc<pending_template> ();
7998   pt->next = NULL;
7999   pt->tinst = current_tinst_level;
8000   if (last_pending_template)
8001     last_pending_template->next = pt;
8002   else
8003     pending_templates = pt;
8004 
8005   last_pending_template = pt;
8006 
8007   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
8008 
8009   if (level)
8010     pop_tinst_level ();
8011 }
8012 
8013 
8014 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
8015    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
8016    documentation for TEMPLATE_ID_EXPR.  */
8017 
8018 tree
lookup_template_function(tree fns,tree arglist)8019 lookup_template_function (tree fns, tree arglist)
8020 {
8021   tree type;
8022 
8023   if (fns == error_mark_node || arglist == error_mark_node)
8024     return error_mark_node;
8025 
8026   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
8027 
8028   if (!is_overloaded_fn (fns) && !identifier_p (fns))
8029     {
8030       error ("%q#D is not a function template", fns);
8031       return error_mark_node;
8032     }
8033 
8034   if (BASELINK_P (fns))
8035     {
8036       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
8037 					 unknown_type_node,
8038 					 BASELINK_FUNCTIONS (fns),
8039 					 arglist);
8040       return fns;
8041     }
8042 
8043   type = TREE_TYPE (fns);
8044   if (TREE_CODE (fns) == OVERLOAD || !type)
8045     type = unknown_type_node;
8046 
8047   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
8048 }
8049 
8050 /* Within the scope of a template class S<T>, the name S gets bound
8051    (in build_self_reference) to a TYPE_DECL for the class, not a
8052    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
8053    or one of its enclosing classes, and that type is a template,
8054    return the associated TEMPLATE_DECL.  Otherwise, the original
8055    DECL is returned.
8056 
8057    Also handle the case when DECL is a TREE_LIST of ambiguous
8058    injected-class-names from different bases.  */
8059 
8060 tree
maybe_get_template_decl_from_type_decl(tree decl)8061 maybe_get_template_decl_from_type_decl (tree decl)
8062 {
8063   if (decl == NULL_TREE)
8064     return decl;
8065 
8066   /* DR 176: A lookup that finds an injected-class-name (10.2
8067      [class.member.lookup]) can result in an ambiguity in certain cases
8068      (for example, if it is found in more than one base class). If all of
8069      the injected-class-names that are found refer to specializations of
8070      the same class template, and if the name is followed by a
8071      template-argument-list, the reference refers to the class template
8072      itself and not a specialization thereof, and is not ambiguous.  */
8073   if (TREE_CODE (decl) == TREE_LIST)
8074     {
8075       tree t, tmpl = NULL_TREE;
8076       for (t = decl; t; t = TREE_CHAIN (t))
8077 	{
8078 	  tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
8079 	  if (!tmpl)
8080 	    tmpl = elt;
8081 	  else if (tmpl != elt)
8082 	    break;
8083 	}
8084       if (tmpl && t == NULL_TREE)
8085 	return tmpl;
8086       else
8087 	return decl;
8088     }
8089 
8090   return (decl != NULL_TREE
8091 	  && DECL_SELF_REFERENCE_P (decl)
8092 	  && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
8093     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
8094 }
8095 
8096 /* Given an IDENTIFIER_NODE (or type TEMPLATE_DECL) and a chain of
8097    parameters, find the desired type.
8098 
8099    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
8100 
8101    IN_DECL, if non-NULL, is the template declaration we are trying to
8102    instantiate.
8103 
8104    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
8105    the class we are looking up.
8106 
8107    Issue error and warning messages under control of COMPLAIN.
8108 
8109    If the template class is really a local class in a template
8110    function, then the FUNCTION_CONTEXT is the function in which it is
8111    being instantiated.
8112 
8113    ??? Note that this function is currently called *twice* for each
8114    template-id: the first time from the parser, while creating the
8115    incomplete type (finish_template_type), and the second type during the
8116    real instantiation (instantiate_template_class). This is surely something
8117    that we want to avoid. It also causes some problems with argument
8118    coercion (see convert_nontype_argument for more information on this).  */
8119 
8120 static tree
lookup_template_class_1(tree d1,tree arglist,tree in_decl,tree context,int entering_scope,tsubst_flags_t complain)8121 lookup_template_class_1 (tree d1, tree arglist, tree in_decl, tree context,
8122 			 int entering_scope, tsubst_flags_t complain)
8123 {
8124   tree templ = NULL_TREE, parmlist;
8125   tree t;
8126   spec_entry **slot;
8127   spec_entry *entry;
8128   spec_entry elt;
8129   hashval_t hash;
8130 
8131   if (identifier_p (d1))
8132     {
8133       tree value = innermost_non_namespace_value (d1);
8134       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
8135 	templ = value;
8136       else
8137 	{
8138 	  if (context)
8139 	    push_decl_namespace (context);
8140 	  templ = lookup_name (d1);
8141 	  templ = maybe_get_template_decl_from_type_decl (templ);
8142 	  if (context)
8143 	    pop_decl_namespace ();
8144 	}
8145       if (templ)
8146 	context = DECL_CONTEXT (templ);
8147     }
8148   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
8149     {
8150       tree type = TREE_TYPE (d1);
8151 
8152       /* If we are declaring a constructor, say A<T>::A<T>, we will get
8153 	 an implicit typename for the second A.  Deal with it.  */
8154       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
8155 	type = TREE_TYPE (type);
8156 
8157       if (CLASSTYPE_TEMPLATE_INFO (type))
8158 	{
8159 	  templ = CLASSTYPE_TI_TEMPLATE (type);
8160 	  d1 = DECL_NAME (templ);
8161 	}
8162     }
8163   else if (TREE_CODE (d1) == ENUMERAL_TYPE
8164 	   || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
8165     {
8166       templ = TYPE_TI_TEMPLATE (d1);
8167       d1 = DECL_NAME (templ);
8168     }
8169   else if (DECL_TYPE_TEMPLATE_P (d1))
8170     {
8171       templ = d1;
8172       d1 = DECL_NAME (templ);
8173       context = DECL_CONTEXT (templ);
8174     }
8175   else if (DECL_TEMPLATE_TEMPLATE_PARM_P (d1))
8176     {
8177       templ = d1;
8178       d1 = DECL_NAME (templ);
8179     }
8180 
8181   /* Issue an error message if we didn't find a template.  */
8182   if (! templ)
8183     {
8184       if (complain & tf_error)
8185 	error ("%qT is not a template", d1);
8186       return error_mark_node;
8187     }
8188 
8189   if (TREE_CODE (templ) != TEMPLATE_DECL
8190 	 /* Make sure it's a user visible template, if it was named by
8191 	    the user.  */
8192       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
8193 	  && !PRIMARY_TEMPLATE_P (templ)))
8194     {
8195       if (complain & tf_error)
8196 	{
8197 	  error ("non-template type %qT used as a template", d1);
8198 	  if (in_decl)
8199 	    error ("for template declaration %q+D", in_decl);
8200 	}
8201       return error_mark_node;
8202     }
8203 
8204   complain &= ~tf_user;
8205 
8206   /* An alias that just changes the name of a template is equivalent to the
8207      other template, so if any of the arguments are pack expansions, strip
8208      the alias to avoid problems with a pack expansion passed to a non-pack
8209      alias template parameter (DR 1430).  */
8210   if (pack_expansion_args_count (INNERMOST_TEMPLATE_ARGS (arglist)))
8211     templ = get_underlying_template (templ);
8212 
8213   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
8214     {
8215       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
8216 	 template arguments */
8217 
8218       tree parm;
8219       tree arglist2;
8220       tree outer;
8221 
8222       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
8223 
8224       /* Consider an example where a template template parameter declared as
8225 
8226 	   template <class T, class U = std::allocator<T> > class TT
8227 
8228 	 The template parameter level of T and U are one level larger than
8229 	 of TT.  To proper process the default argument of U, say when an
8230 	 instantiation `TT<int>' is seen, we need to build the full
8231 	 arguments containing {int} as the innermost level.  Outer levels,
8232 	 available when not appearing as default template argument, can be
8233 	 obtained from the arguments of the enclosing template.
8234 
8235 	 Suppose that TT is later substituted with std::vector.  The above
8236 	 instantiation is `TT<int, std::allocator<T> >' with TT at
8237 	 level 1, and T at level 2, while the template arguments at level 1
8238 	 becomes {std::vector} and the inner level 2 is {int}.  */
8239 
8240       outer = DECL_CONTEXT (templ);
8241       if (outer)
8242 	outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
8243       else if (current_template_parms)
8244 	{
8245 	  /* This is an argument of the current template, so we haven't set
8246 	     DECL_CONTEXT yet.  */
8247 	  tree relevant_template_parms;
8248 
8249 	  /* Parameter levels that are greater than the level of the given
8250 	     template template parm are irrelevant.  */
8251 	  relevant_template_parms = current_template_parms;
8252 	  while (TMPL_PARMS_DEPTH (relevant_template_parms)
8253 		 != TEMPLATE_TYPE_LEVEL (TREE_TYPE (templ)))
8254 	    relevant_template_parms = TREE_CHAIN (relevant_template_parms);
8255 
8256 	  outer = template_parms_to_args (relevant_template_parms);
8257 	}
8258 
8259       if (outer)
8260 	arglist = add_to_template_args (outer, arglist);
8261 
8262       arglist2 = coerce_template_parms (parmlist, arglist, templ,
8263 					complain,
8264 					/*require_all_args=*/true,
8265 					/*use_default_args=*/true);
8266       if (arglist2 == error_mark_node
8267 	  || (!uses_template_parms (arglist2)
8268 	      && check_instantiated_args (templ, arglist2, complain)))
8269 	return error_mark_node;
8270 
8271       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
8272       return parm;
8273     }
8274   else
8275     {
8276       tree template_type = TREE_TYPE (templ);
8277       tree gen_tmpl;
8278       tree type_decl;
8279       tree found = NULL_TREE;
8280       int arg_depth;
8281       int parm_depth;
8282       int is_dependent_type;
8283       int use_partial_inst_tmpl = false;
8284 
8285       if (template_type == error_mark_node)
8286 	/* An error occurred while building the template TEMPL, and a
8287 	   diagnostic has most certainly been emitted for that
8288 	   already.  Let's propagate that error.  */
8289 	return error_mark_node;
8290 
8291       gen_tmpl = most_general_template (templ);
8292       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
8293       parm_depth = TMPL_PARMS_DEPTH (parmlist);
8294       arg_depth = TMPL_ARGS_DEPTH (arglist);
8295 
8296       if (arg_depth == 1 && parm_depth > 1)
8297 	{
8298 	  /* We've been given an incomplete set of template arguments.
8299 	     For example, given:
8300 
8301 	       template <class T> struct S1 {
8302 		 template <class U> struct S2 {};
8303 		 template <class U> struct S2<U*> {};
8304 		};
8305 
8306 	     we will be called with an ARGLIST of `U*', but the
8307 	     TEMPLATE will be `template <class T> template
8308 	     <class U> struct S1<T>::S2'.  We must fill in the missing
8309 	     arguments.  */
8310 	  arglist
8311 	    = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
8312 					   arglist);
8313 	  arg_depth = TMPL_ARGS_DEPTH (arglist);
8314 	}
8315 
8316       /* Now we should have enough arguments.  */
8317       gcc_assert (parm_depth == arg_depth);
8318 
8319       /* From here on, we're only interested in the most general
8320 	 template.  */
8321 
8322       /* Calculate the BOUND_ARGS.  These will be the args that are
8323 	 actually tsubst'd into the definition to create the
8324 	 instantiation.  */
8325       arglist = coerce_innermost_template_parms (parmlist, arglist, gen_tmpl,
8326 						 complain,
8327 						 /*require_all_args=*/true,
8328 						 /*use_default_args=*/true);
8329 
8330       if (arglist == error_mark_node)
8331 	/* We were unable to bind the arguments.  */
8332 	return error_mark_node;
8333 
8334       /* In the scope of a template class, explicit references to the
8335 	 template class refer to the type of the template, not any
8336 	 instantiation of it.  For example, in:
8337 
8338 	   template <class T> class C { void f(C<T>); }
8339 
8340 	 the `C<T>' is just the same as `C'.  Outside of the
8341 	 class, however, such a reference is an instantiation.  */
8342       if ((entering_scope
8343 	   || !PRIMARY_TEMPLATE_P (gen_tmpl)
8344 	   || currently_open_class (template_type))
8345 	  /* comp_template_args is expensive, check it last.  */
8346 	  && comp_template_args (TYPE_TI_ARGS (template_type),
8347 				 arglist))
8348 	return template_type;
8349 
8350       /* If we already have this specialization, return it.  */
8351       elt.tmpl = gen_tmpl;
8352       elt.args = arglist;
8353       elt.spec = NULL_TREE;
8354       hash = spec_hasher::hash (&elt);
8355       entry = type_specializations->find_with_hash (&elt, hash);
8356 
8357       if (entry)
8358 	return entry->spec;
8359 
8360       /* If the the template's constraints are not satisfied,
8361          then we cannot form a valid type.
8362 
8363          Note that the check is deferred until after the hash
8364          lookup. This prevents redundant checks on previously
8365          instantiated specializations. */
8366       if (flag_concepts && !constraints_satisfied_p (gen_tmpl, arglist))
8367         {
8368           if (complain & tf_error)
8369             {
8370               error ("template constraint failure");
8371               diagnose_constraints (input_location, gen_tmpl, arglist);
8372             }
8373           return error_mark_node;
8374         }
8375 
8376       is_dependent_type = uses_template_parms (arglist);
8377 
8378       /* If the deduced arguments are invalid, then the binding
8379 	 failed.  */
8380       if (!is_dependent_type
8381 	  && check_instantiated_args (gen_tmpl,
8382 				      INNERMOST_TEMPLATE_ARGS (arglist),
8383 				      complain))
8384 	return error_mark_node;
8385 
8386       if (!is_dependent_type
8387 	  && !PRIMARY_TEMPLATE_P (gen_tmpl)
8388 	  && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
8389 	  && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
8390 	{
8391 	  found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
8392 				      DECL_NAME (gen_tmpl),
8393 				      /*tag_scope=*/ts_global);
8394 	  return found;
8395 	}
8396 
8397       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
8398 			complain, in_decl);
8399       if (context == error_mark_node)
8400 	return error_mark_node;
8401 
8402       if (!context)
8403 	context = global_namespace;
8404 
8405       /* Create the type.  */
8406       if (DECL_ALIAS_TEMPLATE_P (gen_tmpl))
8407 	{
8408 	  /* The user referred to a specialization of an alias
8409 	    template represented by GEN_TMPL.
8410 
8411 	    [temp.alias]/2 says:
8412 
8413 	        When a template-id refers to the specialization of an
8414 		alias template, it is equivalent to the associated
8415 		type obtained by substitution of its
8416 		template-arguments for the template-parameters in the
8417 		type-id of the alias template.  */
8418 
8419 	  t = tsubst (TREE_TYPE (gen_tmpl), arglist, complain, in_decl);
8420 	  /* Note that the call above (by indirectly calling
8421 	     register_specialization in tsubst_decl) registers the
8422 	     TYPE_DECL representing the specialization of the alias
8423 	     template.  So next time someone substitutes ARGLIST for
8424 	     the template parms into the alias template (GEN_TMPL),
8425 	     she'll get that TYPE_DECL back.  */
8426 
8427 	  if (t == error_mark_node)
8428 	    return t;
8429 	}
8430       else if (TREE_CODE (template_type) == ENUMERAL_TYPE)
8431 	{
8432 	  if (!is_dependent_type)
8433 	    {
8434 	      set_current_access_from_decl (TYPE_NAME (template_type));
8435 	      t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
8436 			      tsubst (ENUM_UNDERLYING_TYPE (template_type),
8437 				      arglist, complain, in_decl),
8438 			      tsubst_attributes (TYPE_ATTRIBUTES (template_type),
8439 						 arglist, complain, in_decl),
8440 			      SCOPED_ENUM_P (template_type), NULL);
8441 
8442 	      if (t == error_mark_node)
8443 		return t;
8444 	    }
8445 	  else
8446             {
8447               /* We don't want to call start_enum for this type, since
8448                  the values for the enumeration constants may involve
8449                  template parameters.  And, no one should be interested
8450                  in the enumeration constants for such a type.  */
8451               t = cxx_make_type (ENUMERAL_TYPE);
8452               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
8453             }
8454           SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
8455 	  ENUM_FIXED_UNDERLYING_TYPE_P (t)
8456 	    = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
8457 	}
8458       else if (CLASS_TYPE_P (template_type))
8459 	{
8460 	  t = make_class_type (TREE_CODE (template_type));
8461 	  CLASSTYPE_DECLARED_CLASS (t)
8462 	    = CLASSTYPE_DECLARED_CLASS (template_type);
8463 	  SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
8464 	  TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
8465 
8466 	  /* A local class.  Make sure the decl gets registered properly.  */
8467 	  if (context == current_function_decl)
8468 	    pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
8469 
8470 	  if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
8471 	    /* This instantiation is another name for the primary
8472 	       template type. Set the TYPE_CANONICAL field
8473 	       appropriately. */
8474 	    TYPE_CANONICAL (t) = template_type;
8475 	  else if (any_template_arguments_need_structural_equality_p (arglist))
8476 	    /* Some of the template arguments require structural
8477 	       equality testing, so this template class requires
8478 	       structural equality testing. */
8479 	    SET_TYPE_STRUCTURAL_EQUALITY (t);
8480 	}
8481       else
8482 	gcc_unreachable ();
8483 
8484       /* If we called start_enum or pushtag above, this information
8485 	 will already be set up.  */
8486       if (!TYPE_NAME (t))
8487 	{
8488 	  TYPE_CONTEXT (t) = FROB_CONTEXT (context);
8489 
8490 	  type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
8491 	  DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
8492 	  DECL_SOURCE_LOCATION (type_decl)
8493 	    = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
8494 	}
8495       else
8496 	type_decl = TYPE_NAME (t);
8497 
8498       if (CLASS_TYPE_P (template_type))
8499 	{
8500 	  TREE_PRIVATE (type_decl)
8501 	    = TREE_PRIVATE (TYPE_MAIN_DECL (template_type));
8502 	  TREE_PROTECTED (type_decl)
8503 	    = TREE_PROTECTED (TYPE_MAIN_DECL (template_type));
8504 	  if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
8505 	    {
8506 	      DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
8507 	      DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
8508 	    }
8509 	}
8510 
8511       if (OVERLOAD_TYPE_P (t)
8512 	  && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
8513 	{
8514 	  static const char *tags[] = {"abi_tag", "may_alias"};
8515 
8516 	  for (unsigned ix = 0; ix != 2; ix++)
8517 	    {
8518 	      tree attributes
8519 		= lookup_attribute (tags[ix], TYPE_ATTRIBUTES (template_type));
8520 
8521 	      if (attributes)
8522 		TYPE_ATTRIBUTES (t)
8523 		  = tree_cons (TREE_PURPOSE (attributes),
8524 			       TREE_VALUE (attributes),
8525 			       TYPE_ATTRIBUTES (t));
8526 	    }
8527 	}
8528 
8529       /* Let's consider the explicit specialization of a member
8530          of a class template specialization that is implicitly instantiated,
8531 	 e.g.:
8532 	     template<class T>
8533 	     struct S
8534 	     {
8535 	       template<class U> struct M {}; //#0
8536 	     };
8537 
8538 	     template<>
8539 	     template<>
8540 	     struct S<int>::M<char> //#1
8541 	     {
8542 	       int i;
8543 	     };
8544 	[temp.expl.spec]/4 says this is valid.
8545 
8546 	In this case, when we write:
8547 	S<int>::M<char> m;
8548 
8549 	M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
8550 	the one of #0.
8551 
8552 	When we encounter #1, we want to store the partial instantiation
8553 	of M (template<class T> S<int>::M<T>) in its CLASSTYPE_TI_TEMPLATE.
8554 
8555 	For all cases other than this "explicit specialization of member of a
8556 	class template", we just want to store the most general template into
8557 	the CLASSTYPE_TI_TEMPLATE of M.
8558 
8559 	This case of "explicit specialization of member of a class template"
8560 	only happens when:
8561 	1/ the enclosing class is an instantiation of, and therefore not
8562 	the same as, the context of the most general template, and
8563 	2/ we aren't looking at the partial instantiation itself, i.e.
8564 	the innermost arguments are not the same as the innermost parms of
8565 	the most general template.
8566 
8567 	So it's only when 1/ and 2/ happens that we want to use the partial
8568 	instantiation of the member template in lieu of its most general
8569 	template.  */
8570 
8571       if (PRIMARY_TEMPLATE_P (gen_tmpl)
8572 	  && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
8573 	  /* the enclosing class must be an instantiation...  */
8574 	  && CLASS_TYPE_P (context)
8575 	  && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
8576 	{
8577 	  tree partial_inst_args;
8578 	  TREE_VEC_LENGTH (arglist)--;
8579 	  ++processing_template_decl;
8580 	  partial_inst_args =
8581 	    tsubst (INNERMOST_TEMPLATE_ARGS
8582 			(TYPE_TI_ARGS (TREE_TYPE (gen_tmpl))),
8583 		    arglist, complain, NULL_TREE);
8584 	  --processing_template_decl;
8585 	  TREE_VEC_LENGTH (arglist)++;
8586 	  if (partial_inst_args == error_mark_node)
8587 	    return error_mark_node;
8588 	  use_partial_inst_tmpl =
8589 	    /*...and we must not be looking at the partial instantiation
8590 	     itself. */
8591 	    !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
8592 				 partial_inst_args);
8593 	}
8594 
8595       if (!use_partial_inst_tmpl)
8596 	/* This case is easy; there are no member templates involved.  */
8597 	found = gen_tmpl;
8598       else
8599 	{
8600 	  /* This is a full instantiation of a member template.  Find
8601 	     the partial instantiation of which this is an instance.  */
8602 
8603 	  /* Temporarily reduce by one the number of levels in the ARGLIST
8604 	     so as to avoid comparing the last set of arguments.  */
8605 	  TREE_VEC_LENGTH (arglist)--;
8606 	  found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
8607 	  TREE_VEC_LENGTH (arglist)++;
8608 	  /* FOUND is either a proper class type, or an alias
8609 	     template specialization.  In the later case, it's a
8610 	     TYPE_DECL, resulting from the substituting of arguments
8611 	     for parameters in the TYPE_DECL of the alias template
8612 	     done earlier.  So be careful while getting the template
8613 	     of FOUND.  */
8614 	  found = TREE_CODE (found) == TEMPLATE_DECL
8615 	    ? found
8616 	    : TREE_CODE (found) == TYPE_DECL
8617 	    ? TYPE_TI_TEMPLATE (TREE_TYPE (found))
8618 	    : CLASSTYPE_TI_TEMPLATE (found);
8619 	}
8620 
8621       // Build template info for the new specialization.
8622       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
8623 
8624       elt.spec = t;
8625       slot = type_specializations->find_slot_with_hash (&elt, hash, INSERT);
8626       entry = ggc_alloc<spec_entry> ();
8627       *entry = elt;
8628       *slot = entry;
8629 
8630       /* Note this use of the partial instantiation so we can check it
8631 	 later in maybe_process_partial_specialization.  */
8632       DECL_TEMPLATE_INSTANTIATIONS (found)
8633 	= tree_cons (arglist, t,
8634 		     DECL_TEMPLATE_INSTANTIATIONS (found));
8635 
8636       if (TREE_CODE (template_type) == ENUMERAL_TYPE && !is_dependent_type
8637 	  && !DECL_ALIAS_TEMPLATE_P (gen_tmpl))
8638 	/* Now that the type has been registered on the instantiations
8639 	   list, we set up the enumerators.  Because the enumeration
8640 	   constants may involve the enumeration type itself, we make
8641 	   sure to register the type first, and then create the
8642 	   constants.  That way, doing tsubst_expr for the enumeration
8643 	   constants won't result in recursive calls here; we'll find
8644 	   the instantiation and exit above.  */
8645 	tsubst_enum (template_type, t, arglist);
8646 
8647       if (CLASS_TYPE_P (template_type) && is_dependent_type)
8648 	/* If the type makes use of template parameters, the
8649 	   code that generates debugging information will crash.  */
8650 	DECL_IGNORED_P (TYPE_MAIN_DECL (t)) = 1;
8651 
8652       /* Possibly limit visibility based on template args.  */
8653       TREE_PUBLIC (type_decl) = 1;
8654       determine_visibility (type_decl);
8655 
8656       inherit_targ_abi_tags (t);
8657 
8658       return t;
8659     }
8660 }
8661 
8662 /* Wrapper for lookup_template_class_1.  */
8663 
8664 tree
lookup_template_class(tree d1,tree arglist,tree in_decl,tree context,int entering_scope,tsubst_flags_t complain)8665 lookup_template_class (tree d1, tree arglist, tree in_decl, tree context,
8666                        int entering_scope, tsubst_flags_t complain)
8667 {
8668   tree ret;
8669   timevar_push (TV_TEMPLATE_INST);
8670   ret = lookup_template_class_1 (d1, arglist, in_decl, context,
8671                                  entering_scope, complain);
8672   timevar_pop (TV_TEMPLATE_INST);
8673   return ret;
8674 }
8675 
8676 /* Return a TEMPLATE_ID_EXPR for the given variable template and ARGLIST.  */
8677 
8678 tree
lookup_template_variable(tree templ,tree arglist)8679 lookup_template_variable (tree templ, tree arglist)
8680 {
8681   /* The type of the expression is NULL_TREE since the template-id could refer
8682      to an explicit or partial specialization. */
8683   tree type = NULL_TREE;
8684   if (flag_concepts && variable_concept_p (templ))
8685     /* Except that concepts are always bool.  */
8686     type = boolean_type_node;
8687   return build2 (TEMPLATE_ID_EXPR, type, templ, arglist);
8688 }
8689 
8690 /* Instantiate a variable declaration from a TEMPLATE_ID_EXPR for use. */
8691 
8692 tree
finish_template_variable(tree var,tsubst_flags_t complain)8693 finish_template_variable (tree var, tsubst_flags_t complain)
8694 {
8695   tree templ = TREE_OPERAND (var, 0);
8696   tree arglist = TREE_OPERAND (var, 1);
8697 
8698   /* We never want to return a VAR_DECL for a variable concept, since they
8699      aren't instantiated.  In a template, leave the TEMPLATE_ID_EXPR alone.  */
8700   bool concept_p = flag_concepts && variable_concept_p (templ);
8701   if (concept_p && processing_template_decl)
8702     return var;
8703 
8704   tree tmpl_args = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (templ));
8705   arglist = add_outermost_template_args (tmpl_args, arglist);
8706 
8707   tree parms = DECL_TEMPLATE_PARMS (templ);
8708   arglist = coerce_innermost_template_parms (parms, arglist, templ, complain,
8709 					     /*req_all*/true,
8710 					     /*use_default*/true);
8711 
8712   if (flag_concepts && !constraints_satisfied_p (templ, arglist))
8713     {
8714       if (complain & tf_error)
8715 	{
8716 	  error ("use of invalid variable template %qE", var);
8717 	  diagnose_constraints (location_of (var), templ, arglist);
8718 	}
8719       return error_mark_node;
8720     }
8721 
8722   /* If a template-id refers to a specialization of a variable
8723      concept, then the expression is true if and only if the
8724      concept's constraints are satisfied by the given template
8725      arguments.
8726 
8727      NOTE: This is an extension of Concepts Lite TS that
8728      allows constraints to be used in expressions. */
8729   if (concept_p)
8730     {
8731       tree decl = DECL_TEMPLATE_RESULT (templ);
8732       return evaluate_variable_concept (decl, arglist);
8733     }
8734 
8735   return instantiate_template (templ, arglist, complain);
8736 }
8737 
8738 /* Construct a TEMPLATE_ID_EXPR for the given variable template TEMPL having
8739    TARGS template args, and instantiate it if it's not dependent.  */
8740 
8741 static tree
lookup_and_finish_template_variable(tree templ,tree targs,tsubst_flags_t complain)8742 lookup_and_finish_template_variable (tree templ, tree targs,
8743 				     tsubst_flags_t complain)
8744 {
8745   templ = lookup_template_variable (templ, targs);
8746   if (!any_dependent_template_arguments_p (targs))
8747     {
8748       templ = finish_template_variable (templ, complain);
8749       mark_used (templ);
8750     }
8751 
8752   return convert_from_reference (templ);
8753 }
8754 
8755 
8756 struct pair_fn_data
8757 {
8758   tree_fn_t fn;
8759   void *data;
8760   /* True when we should also visit template parameters that occur in
8761      non-deduced contexts.  */
8762   bool include_nondeduced_p;
8763   hash_set<tree> *visited;
8764 };
8765 
8766 /* Called from for_each_template_parm via walk_tree.  */
8767 
8768 static tree
for_each_template_parm_r(tree * tp,int * walk_subtrees,void * d)8769 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
8770 {
8771   tree t = *tp;
8772   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
8773   tree_fn_t fn = pfd->fn;
8774   void *data = pfd->data;
8775   tree result = NULL_TREE;
8776 
8777 #define WALK_SUBTREE(NODE)						\
8778   do									\
8779     {									\
8780       result = for_each_template_parm (NODE, fn, data, pfd->visited,	\
8781 				       pfd->include_nondeduced_p);	\
8782       if (result) goto out;						\
8783     }									\
8784   while (0)
8785 
8786   if (TYPE_P (t)
8787       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE))
8788     WALK_SUBTREE (TYPE_CONTEXT (t));
8789 
8790   switch (TREE_CODE (t))
8791     {
8792     case RECORD_TYPE:
8793       if (TYPE_PTRMEMFUNC_P (t))
8794 	break;
8795       /* Fall through.  */
8796 
8797     case UNION_TYPE:
8798     case ENUMERAL_TYPE:
8799       if (!TYPE_TEMPLATE_INFO (t))
8800 	*walk_subtrees = 0;
8801       else
8802 	WALK_SUBTREE (TYPE_TI_ARGS (t));
8803       break;
8804 
8805     case INTEGER_TYPE:
8806       WALK_SUBTREE (TYPE_MIN_VALUE (t));
8807       WALK_SUBTREE (TYPE_MAX_VALUE (t));
8808       break;
8809 
8810     case METHOD_TYPE:
8811       /* Since we're not going to walk subtrees, we have to do this
8812 	 explicitly here.  */
8813       WALK_SUBTREE (TYPE_METHOD_BASETYPE (t));
8814       /* Fall through.  */
8815 
8816     case FUNCTION_TYPE:
8817       /* Check the return type.  */
8818       WALK_SUBTREE (TREE_TYPE (t));
8819 
8820       /* Check the parameter types.  Since default arguments are not
8821 	 instantiated until they are needed, the TYPE_ARG_TYPES may
8822 	 contain expressions that involve template parameters.  But,
8823 	 no-one should be looking at them yet.  And, once they're
8824 	 instantiated, they don't contain template parameters, so
8825 	 there's no point in looking at them then, either.  */
8826       {
8827 	tree parm;
8828 
8829 	for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
8830 	  WALK_SUBTREE (TREE_VALUE (parm));
8831 
8832 	/* Since we've already handled the TYPE_ARG_TYPES, we don't
8833 	   want walk_tree walking into them itself.  */
8834 	*walk_subtrees = 0;
8835       }
8836       break;
8837 
8838     case TYPEOF_TYPE:
8839     case UNDERLYING_TYPE:
8840       if (pfd->include_nondeduced_p
8841 	  && for_each_template_parm (TYPE_VALUES_RAW (t), fn, data,
8842 				     pfd->visited,
8843 				     pfd->include_nondeduced_p))
8844 	return error_mark_node;
8845       break;
8846 
8847     case FUNCTION_DECL:
8848     case VAR_DECL:
8849       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
8850 	WALK_SUBTREE (DECL_TI_ARGS (t));
8851       /* Fall through.  */
8852 
8853     case PARM_DECL:
8854     case CONST_DECL:
8855       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t))
8856 	WALK_SUBTREE (DECL_INITIAL (t));
8857       if (DECL_CONTEXT (t)
8858 	  && pfd->include_nondeduced_p)
8859 	WALK_SUBTREE (DECL_CONTEXT (t));
8860       break;
8861 
8862     case BOUND_TEMPLATE_TEMPLATE_PARM:
8863       /* Record template parameters such as `T' inside `TT<T>'.  */
8864       WALK_SUBTREE (TYPE_TI_ARGS (t));
8865       /* Fall through.  */
8866 
8867     case TEMPLATE_TEMPLATE_PARM:
8868     case TEMPLATE_TYPE_PARM:
8869     case TEMPLATE_PARM_INDEX:
8870       if (fn && (*fn)(t, data))
8871 	return t;
8872       else if (!fn)
8873 	return t;
8874       break;
8875 
8876     case TEMPLATE_DECL:
8877       /* A template template parameter is encountered.  */
8878       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
8879 	WALK_SUBTREE (TREE_TYPE (t));
8880 
8881       /* Already substituted template template parameter */
8882       *walk_subtrees = 0;
8883       break;
8884 
8885     case TYPENAME_TYPE:
8886       /* A template-id in a TYPENAME_TYPE might be a deduced context after
8887 	 partial instantiation.  */
8888       WALK_SUBTREE (TYPENAME_TYPE_FULLNAME (t));
8889       break;
8890 
8891     case CONSTRUCTOR:
8892       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
8893 	  && pfd->include_nondeduced_p)
8894 	WALK_SUBTREE (TYPE_PTRMEMFUNC_FN_TYPE (TREE_TYPE (t)));
8895       break;
8896 
8897     case INDIRECT_REF:
8898     case COMPONENT_REF:
8899       /* If there's no type, then this thing must be some expression
8900 	 involving template parameters.  */
8901       if (!fn && !TREE_TYPE (t))
8902 	return error_mark_node;
8903       break;
8904 
8905     case MODOP_EXPR:
8906     case CAST_EXPR:
8907     case IMPLICIT_CONV_EXPR:
8908     case REINTERPRET_CAST_EXPR:
8909     case CONST_CAST_EXPR:
8910     case STATIC_CAST_EXPR:
8911     case DYNAMIC_CAST_EXPR:
8912     case ARROW_EXPR:
8913     case DOTSTAR_EXPR:
8914     case TYPEID_EXPR:
8915     case PSEUDO_DTOR_EXPR:
8916       if (!fn)
8917 	return error_mark_node;
8918       break;
8919 
8920     default:
8921       break;
8922     }
8923 
8924   #undef WALK_SUBTREE
8925 
8926   /* We didn't find any template parameters we liked.  */
8927  out:
8928   return result;
8929 }
8930 
8931 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
8932    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
8933    call FN with the parameter and the DATA.
8934    If FN returns nonzero, the iteration is terminated, and
8935    for_each_template_parm returns 1.  Otherwise, the iteration
8936    continues.  If FN never returns a nonzero value, the value
8937    returned by for_each_template_parm is 0.  If FN is NULL, it is
8938    considered to be the function which always returns 1.
8939 
8940    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
8941    parameters that occur in non-deduced contexts.  When false, only
8942    visits those template parameters that can be deduced.  */
8943 
8944 static tree
for_each_template_parm(tree t,tree_fn_t fn,void * data,hash_set<tree> * visited,bool include_nondeduced_p)8945 for_each_template_parm (tree t, tree_fn_t fn, void* data,
8946 			hash_set<tree> *visited,
8947 			bool include_nondeduced_p)
8948 {
8949   struct pair_fn_data pfd;
8950   tree result;
8951 
8952   /* Set up.  */
8953   pfd.fn = fn;
8954   pfd.data = data;
8955   pfd.include_nondeduced_p = include_nondeduced_p;
8956 
8957   /* Walk the tree.  (Conceptually, we would like to walk without
8958      duplicates, but for_each_template_parm_r recursively calls
8959      for_each_template_parm, so we would need to reorganize a fair
8960      bit to use walk_tree_without_duplicates, so we keep our own
8961      visited list.)  */
8962   if (visited)
8963     pfd.visited = visited;
8964   else
8965     pfd.visited = new hash_set<tree>;
8966   result = cp_walk_tree (&t,
8967 		         for_each_template_parm_r,
8968 		         &pfd,
8969 		         pfd.visited);
8970 
8971   /* Clean up.  */
8972   if (!visited)
8973     {
8974       delete pfd.visited;
8975       pfd.visited = 0;
8976     }
8977 
8978   return result;
8979 }
8980 
8981 /* Returns true if T depends on any template parameter.  */
8982 
8983 int
uses_template_parms(tree t)8984 uses_template_parms (tree t)
8985 {
8986   if (t == NULL_TREE)
8987     return false;
8988 
8989   bool dependent_p;
8990   int saved_processing_template_decl;
8991 
8992   saved_processing_template_decl = processing_template_decl;
8993   if (!saved_processing_template_decl)
8994     processing_template_decl = 1;
8995   if (TYPE_P (t))
8996     dependent_p = dependent_type_p (t);
8997   else if (TREE_CODE (t) == TREE_VEC)
8998     dependent_p = any_dependent_template_arguments_p (t);
8999   else if (TREE_CODE (t) == TREE_LIST)
9000     dependent_p = (uses_template_parms (TREE_VALUE (t))
9001 		   || uses_template_parms (TREE_CHAIN (t)));
9002   else if (TREE_CODE (t) == TYPE_DECL)
9003     dependent_p = dependent_type_p (TREE_TYPE (t));
9004   else if (DECL_P (t)
9005 	   || EXPR_P (t)
9006 	   || TREE_CODE (t) == TEMPLATE_PARM_INDEX
9007 	   || TREE_CODE (t) == OVERLOAD
9008 	   || BASELINK_P (t)
9009 	   || identifier_p (t)
9010 	   || TREE_CODE (t) == TRAIT_EXPR
9011 	   || TREE_CODE (t) == CONSTRUCTOR
9012 	   || CONSTANT_CLASS_P (t))
9013     dependent_p = (type_dependent_expression_p (t)
9014 		   || value_dependent_expression_p (t));
9015   else
9016     {
9017       gcc_assert (t == error_mark_node);
9018       dependent_p = false;
9019     }
9020 
9021   processing_template_decl = saved_processing_template_decl;
9022 
9023   return dependent_p;
9024 }
9025 
9026 /* Returns true iff current_function_decl is an incompletely instantiated
9027    template.  Useful instead of processing_template_decl because the latter
9028    is set to 0 during instantiate_non_dependent_expr.  */
9029 
9030 bool
in_template_function(void)9031 in_template_function (void)
9032 {
9033   tree fn = current_function_decl;
9034   bool ret;
9035   ++processing_template_decl;
9036   ret = (fn && DECL_LANG_SPECIFIC (fn)
9037 	 && DECL_TEMPLATE_INFO (fn)
9038 	 && any_dependent_template_arguments_p (DECL_TI_ARGS (fn)));
9039   --processing_template_decl;
9040   return ret;
9041 }
9042 
9043 /* Returns true if T depends on any template parameter with level LEVEL.  */
9044 
9045 bool
uses_template_parms_level(tree t,int level)9046 uses_template_parms_level (tree t, int level)
9047 {
9048   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
9049 				 /*include_nondeduced_p=*/true);
9050 }
9051 
9052 /* Returns TRUE iff INST is an instantiation we don't need to do in an
9053    ill-formed translation unit, i.e. a variable or function that isn't
9054    usable in a constant expression.  */
9055 
9056 static inline bool
neglectable_inst_p(tree d)9057 neglectable_inst_p (tree d)
9058 {
9059   return (DECL_P (d)
9060 	  && !(TREE_CODE (d) == FUNCTION_DECL ? DECL_DECLARED_CONSTEXPR_P (d)
9061 	       : decl_maybe_constant_var_p (d)));
9062 }
9063 
9064 /* Returns TRUE iff we should refuse to instantiate DECL because it's
9065    neglectable and instantiated from within an erroneous instantiation.  */
9066 
9067 static bool
limit_bad_template_recursion(tree decl)9068 limit_bad_template_recursion (tree decl)
9069 {
9070   struct tinst_level *lev = current_tinst_level;
9071   int errs = errorcount + sorrycount;
9072   if (lev == NULL || errs == 0 || !neglectable_inst_p (decl))
9073     return false;
9074 
9075   for (; lev; lev = lev->next)
9076     if (neglectable_inst_p (lev->decl))
9077       break;
9078 
9079   return (lev && errs > lev->errors);
9080 }
9081 
9082 static int tinst_depth;
9083 extern int max_tinst_depth;
9084 int depth_reached;
9085 
9086 static GTY(()) struct tinst_level *last_error_tinst_level;
9087 
9088 /* We're starting to instantiate D; record the template instantiation context
9089    for diagnostics and to restore it later.  */
9090 
9091 bool
push_tinst_level(tree d)9092 push_tinst_level (tree d)
9093 {
9094   return push_tinst_level_loc (d, input_location);
9095 }
9096 
9097 /* We're starting to instantiate D; record the template instantiation context
9098    at LOC for diagnostics and to restore it later.  */
9099 
9100 bool
push_tinst_level_loc(tree d,location_t loc)9101 push_tinst_level_loc (tree d, location_t loc)
9102 {
9103   struct tinst_level *new_level;
9104 
9105   if (tinst_depth >= max_tinst_depth)
9106     {
9107       /* Tell error.c not to try to instantiate any templates.  */
9108       at_eof = 2;
9109       fatal_error (input_location,
9110 		   "template instantiation depth exceeds maximum of %d"
9111                    " (use -ftemplate-depth= to increase the maximum)",
9112                    max_tinst_depth);
9113       return false;
9114     }
9115 
9116   /* If the current instantiation caused problems, don't let it instantiate
9117      anything else.  Do allow deduction substitution and decls usable in
9118      constant expressions.  */
9119   if (limit_bad_template_recursion (d))
9120     return false;
9121 
9122   new_level = ggc_alloc<tinst_level> ();
9123   new_level->decl = d;
9124   new_level->locus = loc;
9125   new_level->errors = errorcount+sorrycount;
9126   new_level->in_system_header_p = in_system_header_at (input_location);
9127   new_level->next = current_tinst_level;
9128   current_tinst_level = new_level;
9129 
9130   ++tinst_depth;
9131   if (GATHER_STATISTICS && (tinst_depth > depth_reached))
9132     depth_reached = tinst_depth;
9133 
9134   return true;
9135 }
9136 
9137 /* We're done instantiating this template; return to the instantiation
9138    context.  */
9139 
9140 void
pop_tinst_level(void)9141 pop_tinst_level (void)
9142 {
9143   /* Restore the filename and line number stashed away when we started
9144      this instantiation.  */
9145   input_location = current_tinst_level->locus;
9146   current_tinst_level = current_tinst_level->next;
9147   --tinst_depth;
9148 }
9149 
9150 /* We're instantiating a deferred template; restore the template
9151    instantiation context in which the instantiation was requested, which
9152    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
9153 
9154 static tree
reopen_tinst_level(struct tinst_level * level)9155 reopen_tinst_level (struct tinst_level *level)
9156 {
9157   struct tinst_level *t;
9158 
9159   tinst_depth = 0;
9160   for (t = level; t; t = t->next)
9161     ++tinst_depth;
9162 
9163   current_tinst_level = level;
9164   pop_tinst_level ();
9165   if (current_tinst_level)
9166     current_tinst_level->errors = errorcount+sorrycount;
9167   return level->decl;
9168 }
9169 
9170 /* Returns the TINST_LEVEL which gives the original instantiation
9171    context.  */
9172 
9173 struct tinst_level *
outermost_tinst_level(void)9174 outermost_tinst_level (void)
9175 {
9176   struct tinst_level *level = current_tinst_level;
9177   if (level)
9178     while (level->next)
9179       level = level->next;
9180   return level;
9181 }
9182 
9183 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
9184    vector of template arguments, as for tsubst.
9185 
9186    Returns an appropriate tsubst'd friend declaration.  */
9187 
9188 static tree
tsubst_friend_function(tree decl,tree args)9189 tsubst_friend_function (tree decl, tree args)
9190 {
9191   tree new_friend;
9192 
9193   if (TREE_CODE (decl) == FUNCTION_DECL
9194       && DECL_TEMPLATE_INSTANTIATION (decl)
9195       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
9196     /* This was a friend declared with an explicit template
9197        argument list, e.g.:
9198 
9199        friend void f<>(T);
9200 
9201        to indicate that f was a template instantiation, not a new
9202        function declaration.  Now, we have to figure out what
9203        instantiation of what template.  */
9204     {
9205       tree template_id, arglist, fns;
9206       tree new_args;
9207       tree tmpl;
9208       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
9209 
9210       /* Friend functions are looked up in the containing namespace scope.
9211 	 We must enter that scope, to avoid finding member functions of the
9212 	 current class with same name.  */
9213       push_nested_namespace (ns);
9214       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
9215 			 tf_warning_or_error, NULL_TREE,
9216 			 /*integral_constant_expression_p=*/false);
9217       pop_nested_namespace (ns);
9218       arglist = tsubst (DECL_TI_ARGS (decl), args,
9219 			tf_warning_or_error, NULL_TREE);
9220       template_id = lookup_template_function (fns, arglist);
9221 
9222       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
9223       tmpl = determine_specialization (template_id, new_friend,
9224 				       &new_args,
9225 				       /*need_member_template=*/0,
9226 				       TREE_VEC_LENGTH (args),
9227 				       tsk_none);
9228       return instantiate_template (tmpl, new_args, tf_error);
9229     }
9230 
9231   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
9232 
9233   /* The NEW_FRIEND will look like an instantiation, to the
9234      compiler, but is not an instantiation from the point of view of
9235      the language.  For example, we might have had:
9236 
9237      template <class T> struct S {
9238        template <class U> friend void f(T, U);
9239      };
9240 
9241      Then, in S<int>, template <class U> void f(int, U) is not an
9242      instantiation of anything.  */
9243   if (new_friend == error_mark_node)
9244     return error_mark_node;
9245 
9246   DECL_USE_TEMPLATE (new_friend) = 0;
9247   if (TREE_CODE (decl) == TEMPLATE_DECL)
9248     {
9249       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
9250       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
9251 	= DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
9252     }
9253 
9254   /* The mangled name for the NEW_FRIEND is incorrect.  The function
9255      is not a template instantiation and should not be mangled like
9256      one.  Therefore, we forget the mangling here; we'll recompute it
9257      later if we need it.  */
9258   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
9259     {
9260       SET_DECL_RTL (new_friend, NULL);
9261       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
9262     }
9263 
9264   if (DECL_NAMESPACE_SCOPE_P (new_friend))
9265     {
9266       tree old_decl;
9267       tree new_friend_template_info;
9268       tree new_friend_result_template_info;
9269       tree ns;
9270       int  new_friend_is_defn;
9271 
9272       /* We must save some information from NEW_FRIEND before calling
9273 	 duplicate decls since that function will free NEW_FRIEND if
9274 	 possible.  */
9275       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
9276       new_friend_is_defn =
9277 	    (DECL_INITIAL (DECL_TEMPLATE_RESULT
9278 			   (template_for_substitution (new_friend)))
9279 	     != NULL_TREE);
9280       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
9281 	{
9282 	  /* This declaration is a `primary' template.  */
9283 	  DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
9284 
9285 	  new_friend_result_template_info
9286 	    = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
9287 	}
9288       else
9289 	new_friend_result_template_info = NULL_TREE;
9290 
9291       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
9292       if (new_friend_is_defn)
9293 	DECL_INITIAL (new_friend) = error_mark_node;
9294 
9295       /* Inside pushdecl_namespace_level, we will push into the
9296 	 current namespace. However, the friend function should go
9297 	 into the namespace of the template.  */
9298       ns = decl_namespace_context (new_friend);
9299       push_nested_namespace (ns);
9300       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
9301       pop_nested_namespace (ns);
9302 
9303       if (old_decl == error_mark_node)
9304 	return error_mark_node;
9305 
9306       if (old_decl != new_friend)
9307 	{
9308 	  /* This new friend declaration matched an existing
9309 	     declaration.  For example, given:
9310 
9311 	       template <class T> void f(T);
9312 	       template <class U> class C {
9313 		 template <class T> friend void f(T) {}
9314 	       };
9315 
9316 	     the friend declaration actually provides the definition
9317 	     of `f', once C has been instantiated for some type.  So,
9318 	     old_decl will be the out-of-class template declaration,
9319 	     while new_friend is the in-class definition.
9320 
9321 	     But, if `f' was called before this point, the
9322 	     instantiation of `f' will have DECL_TI_ARGS corresponding
9323 	     to `T' but not to `U', references to which might appear
9324 	     in the definition of `f'.  Previously, the most general
9325 	     template for an instantiation of `f' was the out-of-class
9326 	     version; now it is the in-class version.  Therefore, we
9327 	     run through all specialization of `f', adding to their
9328 	     DECL_TI_ARGS appropriately.  In particular, they need a
9329 	     new set of outer arguments, corresponding to the
9330 	     arguments for this class instantiation.
9331 
9332 	     The same situation can arise with something like this:
9333 
9334 	       friend void f(int);
9335 	       template <class T> class C {
9336 		 friend void f(T) {}
9337 	       };
9338 
9339 	     when `C<int>' is instantiated.  Now, `f(int)' is defined
9340 	     in the class.  */
9341 
9342 	  if (!new_friend_is_defn)
9343 	    /* On the other hand, if the in-class declaration does
9344 	       *not* provide a definition, then we don't want to alter
9345 	       existing definitions.  We can just leave everything
9346 	       alone.  */
9347 	    ;
9348 	  else
9349 	    {
9350 	      tree new_template = TI_TEMPLATE (new_friend_template_info);
9351 	      tree new_args = TI_ARGS (new_friend_template_info);
9352 
9353 	      /* Overwrite whatever template info was there before, if
9354 		 any, with the new template information pertaining to
9355 		 the declaration.  */
9356 	      DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
9357 
9358 	      if (TREE_CODE (old_decl) != TEMPLATE_DECL)
9359 		{
9360 		  /* We should have called reregister_specialization in
9361 		     duplicate_decls.  */
9362 		  gcc_assert (retrieve_specialization (new_template,
9363 						       new_args, 0)
9364 			      == old_decl);
9365 
9366 		  /* Instantiate it if the global has already been used.  */
9367 		  if (DECL_ODR_USED (old_decl))
9368 		    instantiate_decl (old_decl, /*defer_ok=*/true,
9369 				      /*expl_inst_class_mem_p=*/false);
9370 		}
9371 	      else
9372 		{
9373 		  tree t;
9374 
9375 		  /* Indicate that the old function template is a partial
9376 		     instantiation.  */
9377 		  DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
9378 		    = new_friend_result_template_info;
9379 
9380 		  gcc_assert (new_template
9381 			      == most_general_template (new_template));
9382 		  gcc_assert (new_template != old_decl);
9383 
9384 		  /* Reassign any specializations already in the hash table
9385 		     to the new more general template, and add the
9386 		     additional template args.  */
9387 		  for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
9388 		       t != NULL_TREE;
9389 		       t = TREE_CHAIN (t))
9390 		    {
9391 		      tree spec = TREE_VALUE (t);
9392 		      spec_entry elt;
9393 
9394 		      elt.tmpl = old_decl;
9395 		      elt.args = DECL_TI_ARGS (spec);
9396 		      elt.spec = NULL_TREE;
9397 
9398 		      decl_specializations->remove_elt (&elt);
9399 
9400 		      DECL_TI_ARGS (spec)
9401 			= add_outermost_template_args (new_args,
9402 						       DECL_TI_ARGS (spec));
9403 
9404 		      register_specialization
9405 			(spec, new_template, DECL_TI_ARGS (spec), true, 0);
9406 
9407 		    }
9408 		  DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
9409 		}
9410 	    }
9411 
9412 	  /* The information from NEW_FRIEND has been merged into OLD_DECL
9413 	     by duplicate_decls.  */
9414 	  new_friend = old_decl;
9415 	}
9416     }
9417   else
9418     {
9419       tree context = DECL_CONTEXT (new_friend);
9420       bool dependent_p;
9421 
9422       /* In the code
9423 	   template <class T> class C {
9424 	     template <class U> friend void C1<U>::f (); // case 1
9425 	     friend void C2<T>::f ();			 // case 2
9426 	   };
9427 	 we only need to make sure CONTEXT is a complete type for
9428 	 case 2.  To distinguish between the two cases, we note that
9429 	 CONTEXT of case 1 remains dependent type after tsubst while
9430 	 this isn't true for case 2.  */
9431       ++processing_template_decl;
9432       dependent_p = dependent_type_p (context);
9433       --processing_template_decl;
9434 
9435       if (!dependent_p
9436 	  && !complete_type_or_else (context, NULL_TREE))
9437 	return error_mark_node;
9438 
9439       if (COMPLETE_TYPE_P (context))
9440 	{
9441 	  tree fn = new_friend;
9442 	  /* do_friend adds the TEMPLATE_DECL for any member friend
9443 	     template even if it isn't a member template, i.e.
9444 	       template <class T> friend A<T>::f();
9445 	     Look through it in that case.  */
9446 	  if (TREE_CODE (fn) == TEMPLATE_DECL
9447 	      && !PRIMARY_TEMPLATE_P (fn))
9448 	    fn = DECL_TEMPLATE_RESULT (fn);
9449 	  /* Check to see that the declaration is really present, and,
9450 	     possibly obtain an improved declaration.  */
9451 	  fn = check_classfn (context, fn, NULL_TREE);
9452 
9453 	  if (fn)
9454 	    new_friend = fn;
9455 	}
9456     }
9457 
9458   return new_friend;
9459 }
9460 
9461 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
9462    template arguments, as for tsubst.
9463 
9464    Returns an appropriate tsubst'd friend type or error_mark_node on
9465    failure.  */
9466 
9467 static tree
tsubst_friend_class(tree friend_tmpl,tree args)9468 tsubst_friend_class (tree friend_tmpl, tree args)
9469 {
9470   tree friend_type;
9471   tree tmpl;
9472   tree context;
9473 
9474   if (DECL_TEMPLATE_TEMPLATE_PARM_P (friend_tmpl))
9475     {
9476       tree t = tsubst (TREE_TYPE (friend_tmpl), args, tf_none, NULL_TREE);
9477       return TREE_TYPE (t);
9478     }
9479 
9480   context = CP_DECL_CONTEXT (friend_tmpl);
9481 
9482   if (context != global_namespace)
9483     {
9484       if (TREE_CODE (context) == NAMESPACE_DECL)
9485 	push_nested_namespace (context);
9486       else
9487 	push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
9488     }
9489 
9490   /* Look for a class template declaration.  We look for hidden names
9491      because two friend declarations of the same template are the
9492      same.  For example, in:
9493 
9494        struct A {
9495          template <typename> friend class F;
9496        };
9497        template <typename> struct B {
9498          template <typename> friend class F;
9499        };
9500 
9501      both F templates are the same.  */
9502   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
9503 			   /*block_p=*/true, 0, LOOKUP_HIDDEN);
9504 
9505   /* But, if we don't find one, it might be because we're in a
9506      situation like this:
9507 
9508        template <class T>
9509        struct S {
9510 	 template <class U>
9511 	 friend struct S;
9512        };
9513 
9514      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
9515      for `S<int>', not the TEMPLATE_DECL.  */
9516   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
9517     {
9518       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
9519       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
9520     }
9521 
9522   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
9523     {
9524       /* The friend template has already been declared.  Just
9525 	 check to see that the declarations match, and install any new
9526 	 default parameters.  We must tsubst the default parameters,
9527 	 of course.  We only need the innermost template parameters
9528 	 because that is all that redeclare_class_template will look
9529 	 at.  */
9530       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
9531 	  > TMPL_ARGS_DEPTH (args))
9532 	{
9533 	  tree parms;
9534           location_t saved_input_location;
9535 	  parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
9536 					 args, tf_warning_or_error);
9537 
9538           saved_input_location = input_location;
9539           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
9540           tree cons = get_constraints (tmpl);
9541           redeclare_class_template (TREE_TYPE (tmpl), parms, cons);
9542           input_location = saved_input_location;
9543 
9544 	}
9545 
9546       friend_type = TREE_TYPE (tmpl);
9547     }
9548   else
9549     {
9550       /* The friend template has not already been declared.  In this
9551 	 case, the instantiation of the template class will cause the
9552 	 injection of this template into the global scope.  */
9553       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
9554       if (tmpl == error_mark_node)
9555 	return error_mark_node;
9556 
9557       /* The new TMPL is not an instantiation of anything, so we
9558 	 forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
9559 	 the new type because that is supposed to be the corresponding
9560 	 template decl, i.e., TMPL.  */
9561       DECL_USE_TEMPLATE (tmpl) = 0;
9562       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
9563       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
9564       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
9565 	= INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
9566 
9567       /* Inject this template into the global scope.  */
9568       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
9569     }
9570 
9571   if (context != global_namespace)
9572     {
9573       if (TREE_CODE (context) == NAMESPACE_DECL)
9574 	pop_nested_namespace (context);
9575       else
9576 	pop_nested_class ();
9577     }
9578 
9579   return friend_type;
9580 }
9581 
9582 /* Returns zero if TYPE cannot be completed later due to circularity.
9583    Otherwise returns one.  */
9584 
9585 static int
can_complete_type_without_circularity(tree type)9586 can_complete_type_without_circularity (tree type)
9587 {
9588   if (type == NULL_TREE || type == error_mark_node)
9589     return 0;
9590   else if (COMPLETE_TYPE_P (type))
9591     return 1;
9592   else if (TREE_CODE (type) == ARRAY_TYPE)
9593     return can_complete_type_without_circularity (TREE_TYPE (type));
9594   else if (CLASS_TYPE_P (type)
9595 	   && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
9596     return 0;
9597   else
9598     return 1;
9599 }
9600 
9601 static tree tsubst_omp_clauses (tree, bool, bool, tree, tsubst_flags_t, tree);
9602 
9603 /* Instantiate a single dependent attribute T (a TREE_LIST), and return either
9604    T or a new TREE_LIST, possibly a chain in the case of a pack expansion.  */
9605 
9606 static tree
tsubst_attribute(tree t,tree * decl_p,tree args,tsubst_flags_t complain,tree in_decl)9607 tsubst_attribute (tree t, tree *decl_p, tree args,
9608 		  tsubst_flags_t complain, tree in_decl)
9609 {
9610   gcc_assert (ATTR_IS_DEPENDENT (t));
9611 
9612   tree val = TREE_VALUE (t);
9613   if (val == NULL_TREE)
9614     /* Nothing to do.  */;
9615   else if ((flag_openmp || flag_openmp_simd || flag_cilkplus)
9616 	   && is_attribute_p ("omp declare simd",
9617 			      get_attribute_name (t)))
9618     {
9619       tree clauses = TREE_VALUE (val);
9620       clauses = tsubst_omp_clauses (clauses, true, false, args,
9621 				    complain, in_decl);
9622       c_omp_declare_simd_clauses_to_decls (*decl_p, clauses);
9623       clauses = finish_omp_clauses (clauses, false, true);
9624       tree parms = DECL_ARGUMENTS (*decl_p);
9625       clauses
9626 	= c_omp_declare_simd_clauses_to_numbers (parms, clauses);
9627       if (clauses)
9628 	val = build_tree_list (NULL_TREE, clauses);
9629       else
9630 	val = NULL_TREE;
9631     }
9632   /* If the first attribute argument is an identifier, don't
9633      pass it through tsubst.  Attributes like mode, format,
9634      cleanup and several target specific attributes expect it
9635      unmodified.  */
9636   else if (attribute_takes_identifier_p (get_attribute_name (t)))
9637     {
9638       tree chain
9639 	= tsubst_expr (TREE_CHAIN (val), args, complain, in_decl,
9640 		       /*integral_constant_expression_p=*/false);
9641       if (chain != TREE_CHAIN (val))
9642 	val = tree_cons (NULL_TREE, TREE_VALUE (val), chain);
9643     }
9644   else if (PACK_EXPANSION_P (val))
9645     {
9646       /* An attribute pack expansion.  */
9647       tree purp = TREE_PURPOSE (t);
9648       tree pack = tsubst_pack_expansion (val, args, complain, in_decl);
9649       int len = TREE_VEC_LENGTH (pack);
9650       tree list = NULL_TREE;
9651       tree *q = &list;
9652       for (int i = 0; i < len; ++i)
9653 	{
9654 	  tree elt = TREE_VEC_ELT (pack, i);
9655 	  *q = build_tree_list (purp, elt);
9656 	  q = &TREE_CHAIN (*q);
9657 	}
9658       return list;
9659     }
9660   else
9661     val = tsubst_expr (val, args, complain, in_decl,
9662 		       /*integral_constant_expression_p=*/false);
9663 
9664   if (val != TREE_VALUE (t))
9665     return build_tree_list (TREE_PURPOSE (t), val);
9666   return t;
9667 }
9668 
9669 /* Instantiate any dependent attributes in ATTRIBUTES, returning either it
9670    unchanged or a new TREE_LIST chain.  */
9671 
9672 static tree
tsubst_attributes(tree attributes,tree args,tsubst_flags_t complain,tree in_decl)9673 tsubst_attributes (tree attributes, tree args,
9674 		   tsubst_flags_t complain, tree in_decl)
9675 {
9676   tree last_dep = NULL_TREE;
9677 
9678   for (tree t = attributes; t; t = TREE_CHAIN (t))
9679     if (ATTR_IS_DEPENDENT (t))
9680       {
9681 	last_dep = t;
9682 	attributes = copy_list (attributes);
9683 	break;
9684       }
9685 
9686   if (last_dep)
9687     for (tree *p = &attributes; *p; )
9688       {
9689 	tree t = *p;
9690 	if (ATTR_IS_DEPENDENT (t))
9691 	  {
9692 	    tree subst = tsubst_attribute (t, NULL, args, complain, in_decl);
9693 	    if (subst != t)
9694 	      {
9695 		*p = subst;
9696 		do
9697 		  p = &TREE_CHAIN (*p);
9698 		while (*p);
9699 		*p = TREE_CHAIN (t);
9700 		continue;
9701 	      }
9702 	  }
9703 	p = &TREE_CHAIN (*p);
9704       }
9705 
9706   return attributes;
9707 }
9708 
9709 /* Apply any attributes which had to be deferred until instantiation
9710    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
9711    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
9712 
9713 static void
apply_late_template_attributes(tree * decl_p,tree attributes,int attr_flags,tree args,tsubst_flags_t complain,tree in_decl)9714 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
9715 				tree args, tsubst_flags_t complain, tree in_decl)
9716 {
9717   tree last_dep = NULL_TREE;
9718   tree t;
9719   tree *p;
9720 
9721   for (t = attributes; t; t = TREE_CHAIN (t))
9722     if (ATTR_IS_DEPENDENT (t))
9723       {
9724 	last_dep = t;
9725 	attributes = copy_list (attributes);
9726 	break;
9727       }
9728 
9729   if (DECL_P (*decl_p))
9730     {
9731       if (TREE_TYPE (*decl_p) == error_mark_node)
9732 	return;
9733       p = &DECL_ATTRIBUTES (*decl_p);
9734     }
9735   else
9736     p = &TYPE_ATTRIBUTES (*decl_p);
9737 
9738   if (last_dep)
9739     {
9740       tree late_attrs = NULL_TREE;
9741       tree *q = &late_attrs;
9742 
9743       for (*p = attributes; *p; )
9744 	{
9745 	  t = *p;
9746 	  if (ATTR_IS_DEPENDENT (t))
9747 	    {
9748 	      *p = TREE_CHAIN (t);
9749 	      TREE_CHAIN (t) = NULL_TREE;
9750 	      *q = tsubst_attribute (t, decl_p, args, complain, in_decl);
9751 	      do
9752 		q = &TREE_CHAIN (*q);
9753 	      while (*q);
9754 	    }
9755 	  else
9756 	    p = &TREE_CHAIN (t);
9757 	}
9758 
9759       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
9760     }
9761 }
9762 
9763 /* Perform (or defer) access check for typedefs that were referenced
9764    from within the template TMPL code.
9765    This is a subroutine of instantiate_decl and instantiate_class_template.
9766    TMPL is the template to consider and TARGS is the list of arguments of
9767    that template.  */
9768 
9769 static void
perform_typedefs_access_check(tree tmpl,tree targs)9770 perform_typedefs_access_check (tree tmpl, tree targs)
9771 {
9772   location_t saved_location;
9773   unsigned i;
9774   qualified_typedef_usage_t *iter;
9775 
9776   if (!tmpl
9777       || (!CLASS_TYPE_P (tmpl)
9778 	  && TREE_CODE (tmpl) != FUNCTION_DECL))
9779     return;
9780 
9781   saved_location = input_location;
9782   FOR_EACH_VEC_SAFE_ELT (get_types_needing_access_check (tmpl), i, iter)
9783     {
9784       tree type_decl = iter->typedef_decl;
9785       tree type_scope = iter->context;
9786 
9787       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
9788 	continue;
9789 
9790       if (uses_template_parms (type_decl))
9791 	type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
9792       if (uses_template_parms (type_scope))
9793 	type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
9794 
9795       /* Make access check error messages point to the location
9796          of the use of the typedef.  */
9797       input_location = iter->locus;
9798       perform_or_defer_access_check (TYPE_BINFO (type_scope),
9799 				     type_decl, type_decl,
9800 				     tf_warning_or_error);
9801     }
9802     input_location = saved_location;
9803 }
9804 
9805 static tree
instantiate_class_template_1(tree type)9806 instantiate_class_template_1 (tree type)
9807 {
9808   tree templ, args, pattern, t, member;
9809   tree typedecl;
9810   tree pbinfo;
9811   tree base_list;
9812   unsigned int saved_maximum_field_alignment;
9813   tree fn_context;
9814 
9815   if (type == error_mark_node)
9816     return error_mark_node;
9817 
9818   if (COMPLETE_OR_OPEN_TYPE_P (type)
9819       || uses_template_parms (type))
9820     return type;
9821 
9822   /* Figure out which template is being instantiated.  */
9823   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
9824   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
9825 
9826   /* Determine what specialization of the original template to
9827      instantiate.  */
9828   t = most_specialized_partial_spec (type, tf_warning_or_error);
9829   if (t == error_mark_node)
9830     {
9831       TYPE_BEING_DEFINED (type) = 1;
9832       return error_mark_node;
9833     }
9834   else if (t)
9835     {
9836       /* This TYPE is actually an instantiation of a partial
9837 	 specialization.  We replace the innermost set of ARGS with
9838 	 the arguments appropriate for substitution.  For example,
9839 	 given:
9840 
9841 	   template <class T> struct S {};
9842 	   template <class T> struct S<T*> {};
9843 
9844 	 and supposing that we are instantiating S<int*>, ARGS will
9845 	 presently be {int*} -- but we need {int}.  */
9846       pattern = TREE_TYPE (t);
9847       args = TREE_PURPOSE (t);
9848     }
9849   else
9850     {
9851       pattern = TREE_TYPE (templ);
9852       args = CLASSTYPE_TI_ARGS (type);
9853     }
9854 
9855   /* If the template we're instantiating is incomplete, then clearly
9856      there's nothing we can do.  */
9857   if (!COMPLETE_TYPE_P (pattern))
9858     return type;
9859 
9860   /* If we've recursively instantiated too many templates, stop.  */
9861   if (! push_tinst_level (type))
9862     return type;
9863 
9864   /* Now we're really doing the instantiation.  Mark the type as in
9865      the process of being defined.  */
9866   TYPE_BEING_DEFINED (type) = 1;
9867 
9868   /* We may be in the middle of deferred access check.  Disable
9869      it now.  */
9870   push_deferring_access_checks (dk_no_deferred);
9871 
9872   int saved_unevaluated_operand = cp_unevaluated_operand;
9873   int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
9874 
9875   fn_context = decl_function_context (TYPE_MAIN_DECL (type));
9876   /* Also avoid push_to_top_level for a lambda in an NSDMI.  */
9877   if (!fn_context && LAMBDA_TYPE_P (type) && TYPE_CLASS_SCOPE_P (type))
9878     fn_context = error_mark_node;
9879   if (!fn_context)
9880     push_to_top_level ();
9881   else
9882     {
9883       cp_unevaluated_operand = 0;
9884       c_inhibit_evaluation_warnings = 0;
9885     }
9886   /* Use #pragma pack from the template context.  */
9887   saved_maximum_field_alignment = maximum_field_alignment;
9888   maximum_field_alignment = TYPE_PRECISION (pattern);
9889 
9890   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
9891 
9892   /* Set the input location to the most specialized template definition.
9893      This is needed if tsubsting causes an error.  */
9894   typedecl = TYPE_MAIN_DECL (pattern);
9895   input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
9896     DECL_SOURCE_LOCATION (typedecl);
9897 
9898   TYPE_PACKED (type) = TYPE_PACKED (pattern);
9899   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
9900   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
9901   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
9902   if (ANON_AGGR_TYPE_P (pattern))
9903     SET_ANON_AGGR_TYPE_P (type);
9904   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
9905     {
9906       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
9907       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
9908       /* Adjust visibility for template arguments.  */
9909       determine_visibility (TYPE_MAIN_DECL (type));
9910     }
9911   if (CLASS_TYPE_P (type))
9912     CLASSTYPE_FINAL (type) = CLASSTYPE_FINAL (pattern);
9913 
9914   pbinfo = TYPE_BINFO (pattern);
9915 
9916   /* We should never instantiate a nested class before its enclosing
9917      class; we need to look up the nested class by name before we can
9918      instantiate it, and that lookup should instantiate the enclosing
9919      class.  */
9920   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
9921 	      || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
9922 
9923   base_list = NULL_TREE;
9924   if (BINFO_N_BASE_BINFOS (pbinfo))
9925     {
9926       tree pbase_binfo;
9927       tree pushed_scope;
9928       int i;
9929 
9930       /* We must enter the scope containing the type, as that is where
9931 	 the accessibility of types named in dependent bases are
9932 	 looked up from.  */
9933       pushed_scope = push_scope (CP_TYPE_CONTEXT (type));
9934 
9935       /* Substitute into each of the bases to determine the actual
9936 	 basetypes.  */
9937       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
9938 	{
9939 	  tree base;
9940 	  tree access = BINFO_BASE_ACCESS (pbinfo, i);
9941           tree expanded_bases = NULL_TREE;
9942           int idx, len = 1;
9943 
9944           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
9945             {
9946               expanded_bases =
9947 		tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
9948 				       args, tf_error, NULL_TREE);
9949               if (expanded_bases == error_mark_node)
9950                 continue;
9951 
9952               len = TREE_VEC_LENGTH (expanded_bases);
9953             }
9954 
9955           for (idx = 0; idx < len; idx++)
9956             {
9957               if (expanded_bases)
9958                 /* Extract the already-expanded base class.  */
9959                 base = TREE_VEC_ELT (expanded_bases, idx);
9960               else
9961                 /* Substitute to figure out the base class.  */
9962                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error,
9963                                NULL_TREE);
9964 
9965               if (base == error_mark_node)
9966                 continue;
9967 
9968               base_list = tree_cons (access, base, base_list);
9969               if (BINFO_VIRTUAL_P (pbase_binfo))
9970                 TREE_TYPE (base_list) = integer_type_node;
9971             }
9972 	}
9973 
9974       /* The list is now in reverse order; correct that.  */
9975       base_list = nreverse (base_list);
9976 
9977       if (pushed_scope)
9978 	pop_scope (pushed_scope);
9979     }
9980   /* Now call xref_basetypes to set up all the base-class
9981      information.  */
9982   xref_basetypes (type, base_list);
9983 
9984   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
9985 				  (int) ATTR_FLAG_TYPE_IN_PLACE,
9986 				  args, tf_error, NULL_TREE);
9987   fixup_attribute_variants (type);
9988 
9989   /* Now that our base classes are set up, enter the scope of the
9990      class, so that name lookups into base classes, etc. will work
9991      correctly.  This is precisely analogous to what we do in
9992      begin_class_definition when defining an ordinary non-template
9993      class, except we also need to push the enclosing classes.  */
9994   push_nested_class (type);
9995 
9996   /* Now members are processed in the order of declaration.  */
9997   for (member = CLASSTYPE_DECL_LIST (pattern);
9998        member; member = TREE_CHAIN (member))
9999     {
10000       tree t = TREE_VALUE (member);
10001 
10002       if (TREE_PURPOSE (member))
10003 	{
10004 	  if (TYPE_P (t))
10005 	    {
10006 	      /* Build new CLASSTYPE_NESTED_UTDS.  */
10007 
10008 	      tree newtag;
10009 	      bool class_template_p;
10010 
10011 	      class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
10012 				  && TYPE_LANG_SPECIFIC (t)
10013 				  && CLASSTYPE_IS_TEMPLATE (t));
10014 	      /* If the member is a class template, then -- even after
10015 		 substitution -- there may be dependent types in the
10016 		 template argument list for the class.  We increment
10017 		 PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
10018 		 that function will assume that no types are dependent
10019 		 when outside of a template.  */
10020 	      if (class_template_p)
10021 		++processing_template_decl;
10022 	      newtag = tsubst (t, args, tf_error, NULL_TREE);
10023 	      if (class_template_p)
10024 		--processing_template_decl;
10025 	      if (newtag == error_mark_node)
10026 		continue;
10027 
10028 	      if (TREE_CODE (newtag) != ENUMERAL_TYPE)
10029 		{
10030 		  tree name = TYPE_IDENTIFIER (t);
10031 
10032 		  if (class_template_p)
10033 		    /* Unfortunately, lookup_template_class sets
10034 		       CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
10035 		       instantiation (i.e., for the type of a member
10036 		       template class nested within a template class.)
10037 		       This behavior is required for
10038 		       maybe_process_partial_specialization to work
10039 		       correctly, but is not accurate in this case;
10040 		       the TAG is not an instantiation of anything.
10041 		       (The corresponding TEMPLATE_DECL is an
10042 		       instantiation, but the TYPE is not.) */
10043 		    CLASSTYPE_USE_TEMPLATE (newtag) = 0;
10044 
10045 		  /* Now, we call pushtag to put this NEWTAG into the scope of
10046 		     TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
10047 		     pushtag calling push_template_decl.  We don't have to do
10048 		     this for enums because it will already have been done in
10049 		     tsubst_enum.  */
10050 		  if (name)
10051 		    SET_IDENTIFIER_TYPE_VALUE (name, newtag);
10052 		  pushtag (name, newtag, /*tag_scope=*/ts_current);
10053 		}
10054 	    }
10055 	  else if (DECL_DECLARES_FUNCTION_P (t))
10056 	    {
10057 	      /* Build new TYPE_METHODS.  */
10058 	      tree r;
10059 
10060 	      if (TREE_CODE (t) == TEMPLATE_DECL)
10061 		++processing_template_decl;
10062 	      r = tsubst (t, args, tf_error, NULL_TREE);
10063 	      if (TREE_CODE (t) == TEMPLATE_DECL)
10064 		--processing_template_decl;
10065 	      set_current_access_from_decl (r);
10066 	      finish_member_declaration (r);
10067 	      /* Instantiate members marked with attribute used.  */
10068 	      if (r != error_mark_node && DECL_PRESERVE_P (r))
10069 		mark_used (r);
10070 	      if (TREE_CODE (r) == FUNCTION_DECL
10071 		  && DECL_OMP_DECLARE_REDUCTION_P (r))
10072 		cp_check_omp_declare_reduction (r);
10073 	    }
10074 	  else if (DECL_CLASS_TEMPLATE_P (t)
10075 		   && LAMBDA_TYPE_P (TREE_TYPE (t)))
10076 	    /* A closure type for a lambda in a default argument for a
10077 	       member template.  Ignore it; it will be instantiated with
10078 	       the default argument.  */;
10079 	  else
10080 	    {
10081 	      /* Build new TYPE_FIELDS.  */
10082               if (TREE_CODE (t) == STATIC_ASSERT)
10083                 {
10084                   tree condition;
10085 
10086 		  ++c_inhibit_evaluation_warnings;
10087 		  condition =
10088 		    tsubst_expr (STATIC_ASSERT_CONDITION (t), args,
10089 				 tf_warning_or_error, NULL_TREE,
10090 				 /*integral_constant_expression_p=*/true);
10091 		  --c_inhibit_evaluation_warnings;
10092 
10093                   finish_static_assert (condition,
10094                                         STATIC_ASSERT_MESSAGE (t),
10095                                         STATIC_ASSERT_SOURCE_LOCATION (t),
10096                                         /*member_p=*/true);
10097                 }
10098 	      else if (TREE_CODE (t) != CONST_DECL)
10099 		{
10100 		  tree r;
10101 		  tree vec = NULL_TREE;
10102 		  int len = 1;
10103 
10104 		  /* The file and line for this declaration, to
10105 		     assist in error message reporting.  Since we
10106 		     called push_tinst_level above, we don't need to
10107 		     restore these.  */
10108 		  input_location = DECL_SOURCE_LOCATION (t);
10109 
10110 		  if (TREE_CODE (t) == TEMPLATE_DECL)
10111 		    ++processing_template_decl;
10112 		  r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
10113 		  if (TREE_CODE (t) == TEMPLATE_DECL)
10114 		    --processing_template_decl;
10115 
10116 		  if (TREE_CODE (r) == TREE_VEC)
10117 		    {
10118 		      /* A capture pack became multiple fields.  */
10119 		      vec = r;
10120 		      len = TREE_VEC_LENGTH (vec);
10121 		    }
10122 
10123 		  for (int i = 0; i < len; ++i)
10124 		    {
10125 		      if (vec)
10126 			r = TREE_VEC_ELT (vec, i);
10127 		      if (VAR_P (r))
10128 			{
10129 			  /* In [temp.inst]:
10130 
10131 			     [t]he initialization (and any associated
10132 			     side-effects) of a static data member does
10133 			     not occur unless the static data member is
10134 			     itself used in a way that requires the
10135 			     definition of the static data member to
10136 			     exist.
10137 
10138 			     Therefore, we do not substitute into the
10139 			     initialized for the static data member here.  */
10140 			  finish_static_data_member_decl
10141 			    (r,
10142 			     /*init=*/NULL_TREE,
10143 			     /*init_const_expr_p=*/false,
10144 			     /*asmspec_tree=*/NULL_TREE,
10145 			     /*flags=*/0);
10146 			  /* Instantiate members marked with attribute used. */
10147 			  if (r != error_mark_node && DECL_PRESERVE_P (r))
10148 			    mark_used (r);
10149 			}
10150 		      else if (TREE_CODE (r) == FIELD_DECL)
10151 			{
10152 			  /* Determine whether R has a valid type and can be
10153 			     completed later.  If R is invalid, then its type
10154 			     is replaced by error_mark_node.  */
10155 			  tree rtype = TREE_TYPE (r);
10156 			  if (can_complete_type_without_circularity (rtype))
10157 			    complete_type (rtype);
10158 
10159 			  if (!complete_or_array_type_p (rtype))
10160 			    {
10161 			      /* If R's type couldn't be completed and
10162 				 it isn't a flexible array member (whose
10163 				 type is incomplete by definition) give
10164 				 an error.  */
10165 			      cxx_incomplete_type_error (r, rtype);
10166 			      TREE_TYPE (r) = error_mark_node;
10167 			    }
10168 			}
10169 
10170 		      /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
10171 			 such a thing will already have been added to the field
10172 			 list by tsubst_enum in finish_member_declaration in the
10173 			 CLASSTYPE_NESTED_UTDS case above.  */
10174 		      if (!(TREE_CODE (r) == TYPE_DECL
10175 			    && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
10176 			    && DECL_ARTIFICIAL (r)))
10177 			{
10178 			  set_current_access_from_decl (r);
10179 			  finish_member_declaration (r);
10180 			}
10181 		    }
10182 		}
10183 	    }
10184 	}
10185       else
10186 	{
10187 	  if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t)
10188 	      || DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10189 	    {
10190 	      /* Build new CLASSTYPE_FRIEND_CLASSES.  */
10191 
10192 	      tree friend_type = t;
10193 	      bool adjust_processing_template_decl = false;
10194 
10195 	      if (TREE_CODE (friend_type) == TEMPLATE_DECL)
10196 		{
10197 		  /* template <class T> friend class C;  */
10198 		  friend_type = tsubst_friend_class (friend_type, args);
10199 		  adjust_processing_template_decl = true;
10200 		}
10201 	      else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
10202 		{
10203 		  /* template <class T> friend class C::D;  */
10204 		  friend_type = tsubst (friend_type, args,
10205 					tf_warning_or_error, NULL_TREE);
10206 		  if (TREE_CODE (friend_type) == TEMPLATE_DECL)
10207 		    friend_type = TREE_TYPE (friend_type);
10208 		  adjust_processing_template_decl = true;
10209 		}
10210 	      else if (TREE_CODE (friend_type) == TYPENAME_TYPE
10211 		       || TREE_CODE (friend_type) == TEMPLATE_TYPE_PARM)
10212 		{
10213 		  /* This could be either
10214 
10215 		       friend class T::C;
10216 
10217 		     when dependent_type_p is false or
10218 
10219 		       template <class U> friend class T::C;
10220 
10221 		     otherwise.  */
10222 		  /* Bump processing_template_decl in case this is something like
10223 		     template <class T> friend struct A<T>::B.  */
10224 		  ++processing_template_decl;
10225 		  friend_type = tsubst (friend_type, args,
10226 					tf_warning_or_error, NULL_TREE);
10227 		  if (dependent_type_p (friend_type))
10228 		    adjust_processing_template_decl = true;
10229 		  --processing_template_decl;
10230 		}
10231 	      else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
10232 		       && hidden_name_p (TYPE_NAME (friend_type)))
10233 		{
10234 		  /* friend class C;
10235 
10236 		     where C hasn't been declared yet.  Let's lookup name
10237 		     from namespace scope directly, bypassing any name that
10238 		     come from dependent base class.  */
10239 		  tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
10240 
10241 		  /* The call to xref_tag_from_type does injection for friend
10242 		     classes.  */
10243 		  push_nested_namespace (ns);
10244 		  friend_type =
10245 		    xref_tag_from_type (friend_type, NULL_TREE,
10246 					/*tag_scope=*/ts_current);
10247 		  pop_nested_namespace (ns);
10248 		}
10249 	      else if (uses_template_parms (friend_type))
10250 		/* friend class C<T>;  */
10251 		friend_type = tsubst (friend_type, args,
10252 				      tf_warning_or_error, NULL_TREE);
10253 	      /* Otherwise it's
10254 
10255 		   friend class C;
10256 
10257 		 where C is already declared or
10258 
10259 		   friend class C<int>;
10260 
10261 		 We don't have to do anything in these cases.  */
10262 
10263 	      if (adjust_processing_template_decl)
10264 		/* Trick make_friend_class into realizing that the friend
10265 		   we're adding is a template, not an ordinary class.  It's
10266 		   important that we use make_friend_class since it will
10267 		   perform some error-checking and output cross-reference
10268 		   information.  */
10269 		++processing_template_decl;
10270 
10271 	      if (friend_type != error_mark_node)
10272 		make_friend_class (type, friend_type, /*complain=*/false);
10273 
10274 	      if (adjust_processing_template_decl)
10275 		--processing_template_decl;
10276 	    }
10277 	  else
10278 	    {
10279 	      /* Build new DECL_FRIENDLIST.  */
10280 	      tree r;
10281 
10282 	      /* The file and line for this declaration, to
10283 		 assist in error message reporting.  Since we
10284 		 called push_tinst_level above, we don't need to
10285 		 restore these.  */
10286 	      input_location = DECL_SOURCE_LOCATION (t);
10287 
10288 	      if (TREE_CODE (t) == TEMPLATE_DECL)
10289 		{
10290 		  ++processing_template_decl;
10291 		  push_deferring_access_checks (dk_no_check);
10292 		}
10293 
10294 	      r = tsubst_friend_function (t, args);
10295 	      add_friend (type, r, /*complain=*/false);
10296 	      if (TREE_CODE (t) == TEMPLATE_DECL)
10297 		{
10298 		  pop_deferring_access_checks ();
10299 		  --processing_template_decl;
10300 		}
10301 	    }
10302 	}
10303     }
10304 
10305   if (fn_context)
10306     {
10307       /* Restore these before substituting into the lambda capture
10308 	 initializers.  */
10309       cp_unevaluated_operand = saved_unevaluated_operand;
10310       c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
10311     }
10312 
10313   if (tree expr = CLASSTYPE_LAMBDA_EXPR (type))
10314     {
10315       tree decl = lambda_function (type);
10316       if (decl)
10317 	{
10318 	  if (!DECL_TEMPLATE_INFO (decl)
10319 	      || DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (decl)) != decl)
10320 	    {
10321 	      /* Set function_depth to avoid garbage collection.  */
10322 	      ++function_depth;
10323 	      instantiate_decl (decl, false, false);
10324 	      --function_depth;
10325 	    }
10326 
10327 	  /* We need to instantiate the capture list from the template
10328 	     after we've instantiated the closure members, but before we
10329 	     consider adding the conversion op.  Also keep any captures
10330 	     that may have been added during instantiation of the op().  */
10331 	  tree tmpl_expr = CLASSTYPE_LAMBDA_EXPR (pattern);
10332 	  tree tmpl_cap
10333 	    = tsubst_copy_and_build (LAMBDA_EXPR_CAPTURE_LIST (tmpl_expr),
10334 				     args, tf_warning_or_error, NULL_TREE,
10335 				     false, false);
10336 
10337 	  LAMBDA_EXPR_CAPTURE_LIST (expr)
10338 	    = chainon (tmpl_cap, nreverse (LAMBDA_EXPR_CAPTURE_LIST (expr)));
10339 
10340 	  maybe_add_lambda_conv_op (type);
10341 	}
10342       else
10343 	gcc_assert (errorcount);
10344     }
10345 
10346   /* Set the file and line number information to whatever is given for
10347      the class itself.  This puts error messages involving generated
10348      implicit functions at a predictable point, and the same point
10349      that would be used for non-template classes.  */
10350   input_location = DECL_SOURCE_LOCATION (typedecl);
10351 
10352   unreverse_member_declarations (type);
10353   finish_struct_1 (type);
10354   TYPE_BEING_DEFINED (type) = 0;
10355 
10356   /* We don't instantiate default arguments for member functions.  14.7.1:
10357 
10358      The implicit instantiation of a class template specialization causes
10359      the implicit instantiation of the declarations, but not of the
10360      definitions or default arguments, of the class member functions,
10361      member classes, static data members and member templates....  */
10362 
10363   /* Some typedefs referenced from within the template code need to be access
10364      checked at template instantiation time, i.e now. These types were
10365      added to the template at parsing time. Let's get those and perform
10366      the access checks then.  */
10367   perform_typedefs_access_check (pattern, args);
10368   perform_deferred_access_checks (tf_warning_or_error);
10369   pop_nested_class ();
10370   maximum_field_alignment = saved_maximum_field_alignment;
10371   if (!fn_context)
10372     pop_from_top_level ();
10373   pop_deferring_access_checks ();
10374   pop_tinst_level ();
10375 
10376   /* The vtable for a template class can be emitted in any translation
10377      unit in which the class is instantiated.  When there is no key
10378      method, however, finish_struct_1 will already have added TYPE to
10379      the keyed_classes list.  */
10380   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
10381     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
10382 
10383   return type;
10384 }
10385 
10386 /* Wrapper for instantiate_class_template_1.  */
10387 
10388 tree
instantiate_class_template(tree type)10389 instantiate_class_template (tree type)
10390 {
10391   tree ret;
10392   timevar_push (TV_TEMPLATE_INST);
10393   ret = instantiate_class_template_1 (type);
10394   timevar_pop (TV_TEMPLATE_INST);
10395   return ret;
10396 }
10397 
10398 static tree
tsubst_template_arg(tree t,tree args,tsubst_flags_t complain,tree in_decl)10399 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10400 {
10401   tree r;
10402 
10403   if (!t)
10404     r = t;
10405   else if (TYPE_P (t))
10406     r = tsubst (t, args, complain, in_decl);
10407   else
10408     {
10409       if (!(complain & tf_warning))
10410 	++c_inhibit_evaluation_warnings;
10411       r = tsubst_expr (t, args, complain, in_decl,
10412 		       /*integral_constant_expression_p=*/true);
10413       if (!(complain & tf_warning))
10414 	--c_inhibit_evaluation_warnings;
10415     }
10416   return r;
10417 }
10418 
10419 /* Given a function parameter pack TMPL_PARM and some function parameters
10420    instantiated from it at *SPEC_P, return a NONTYPE_ARGUMENT_PACK of them
10421    and set *SPEC_P to point at the next point in the list.  */
10422 
10423 tree
extract_fnparm_pack(tree tmpl_parm,tree * spec_p)10424 extract_fnparm_pack (tree tmpl_parm, tree *spec_p)
10425 {
10426   /* Collect all of the extra "packed" parameters into an
10427      argument pack.  */
10428   tree parmvec;
10429   tree parmtypevec;
10430   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
10431   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
10432   tree spec_parm = *spec_p;
10433   int i, len;
10434 
10435   for (len = 0; spec_parm; ++len, spec_parm = TREE_CHAIN (spec_parm))
10436     if (tmpl_parm
10437 	&& !function_parameter_expanded_from_pack_p (spec_parm, tmpl_parm))
10438       break;
10439 
10440   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
10441   parmvec = make_tree_vec (len);
10442   parmtypevec = make_tree_vec (len);
10443   spec_parm = *spec_p;
10444   for (i = 0; i < len; i++, spec_parm = DECL_CHAIN (spec_parm))
10445     {
10446       TREE_VEC_ELT (parmvec, i) = spec_parm;
10447       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
10448     }
10449 
10450   /* Build the argument packs.  */
10451   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
10452   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
10453   TREE_TYPE (argpack) = argtypepack;
10454   *spec_p = spec_parm;
10455 
10456   return argpack;
10457 }
10458 
10459 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
10460    NONTYPE_ARGUMENT_PACK.  */
10461 
10462 static tree
make_fnparm_pack(tree spec_parm)10463 make_fnparm_pack (tree spec_parm)
10464 {
10465   return extract_fnparm_pack (NULL_TREE, &spec_parm);
10466 }
10467 
10468 /* Return 1 if the Ith element of the argument pack ARG_PACK is a
10469    pack expansion with no extra args, 2 if it has extra args, or 0
10470    if it is not a pack expansion.  */
10471 
10472 static int
argument_pack_element_is_expansion_p(tree arg_pack,int i)10473 argument_pack_element_is_expansion_p (tree arg_pack, int i)
10474 {
10475   tree vec = ARGUMENT_PACK_ARGS (arg_pack);
10476   if (i >= TREE_VEC_LENGTH (vec))
10477     return 0;
10478   tree elt = TREE_VEC_ELT (vec, i);
10479   if (DECL_P (elt))
10480     /* A decl pack is itself an expansion.  */
10481     elt = TREE_TYPE (elt);
10482   if (!PACK_EXPANSION_P (elt))
10483     return 0;
10484   if (PACK_EXPANSION_EXTRA_ARGS (elt))
10485     return 2;
10486   return 1;
10487 }
10488 
10489 
10490 /* Creates and return an ARGUMENT_PACK_SELECT tree node.  */
10491 
10492 static tree
make_argument_pack_select(tree arg_pack,unsigned index)10493 make_argument_pack_select (tree arg_pack, unsigned index)
10494 {
10495   tree aps = make_node (ARGUMENT_PACK_SELECT);
10496 
10497   ARGUMENT_PACK_SELECT_FROM_PACK (aps) = arg_pack;
10498   ARGUMENT_PACK_SELECT_INDEX (aps) = index;
10499 
10500   return aps;
10501 }
10502 
10503 /*  This is a subroutine of tsubst_pack_expansion.
10504 
10505     It returns TRUE if we need to use the PACK_EXPANSION_EXTRA_ARGS
10506     mechanism to store the (non complete list of) arguments of the
10507     substitution and return a non substituted pack expansion, in order
10508     to wait for when we have enough arguments to really perform the
10509     substitution.  */
10510 
10511 static bool
use_pack_expansion_extra_args_p(tree parm_packs,int arg_pack_len,bool has_empty_arg)10512 use_pack_expansion_extra_args_p (tree parm_packs,
10513 				 int arg_pack_len,
10514 				 bool has_empty_arg)
10515 {
10516   /* If one pack has an expansion and another pack has a normal
10517      argument or if one pack has an empty argument and an another
10518      one hasn't then tsubst_pack_expansion cannot perform the
10519      substitution and need to fall back on the
10520      PACK_EXPANSION_EXTRA mechanism.  */
10521   if (parm_packs == NULL_TREE)
10522     return false;
10523   else if (has_empty_arg)
10524     return true;
10525 
10526   bool has_expansion_arg = false;
10527   for (int i = 0 ; i < arg_pack_len; ++i)
10528     {
10529       bool has_non_expansion_arg = false;
10530       for (tree parm_pack = parm_packs;
10531 	   parm_pack;
10532 	   parm_pack = TREE_CHAIN (parm_pack))
10533 	{
10534 	  tree arg = TREE_VALUE (parm_pack);
10535 
10536 	  int exp = argument_pack_element_is_expansion_p (arg, i);
10537 	  if (exp == 2)
10538 	    /* We can't substitute a pack expansion with extra args into
10539 	       our pattern.  */
10540 	    return true;
10541 	  else if (exp)
10542 	    has_expansion_arg = true;
10543 	  else
10544 	    has_non_expansion_arg = true;
10545 	}
10546 
10547       if (has_expansion_arg && has_non_expansion_arg)
10548 	return true;
10549     }
10550   return false;
10551 }
10552 
10553 /* [temp.variadic]/6 says that:
10554 
10555        The instantiation of a pack expansion [...]
10556        produces a list E1,E2, ..., En, where N is the number of elements
10557        in the pack expansion parameters.
10558 
10559    This subroutine of tsubst_pack_expansion produces one of these Ei.
10560 
10561    PATTERN is the pattern of the pack expansion.  PARM_PACKS is a
10562    TREE_LIST in which each TREE_PURPOSE is a parameter pack of
10563    PATTERN, and each TREE_VALUE is its corresponding argument pack.
10564    INDEX is the index 'i' of the element Ei to produce.  ARGS,
10565    COMPLAIN, and IN_DECL are the same parameters as for the
10566    tsubst_pack_expansion function.
10567 
10568    The function returns the resulting Ei upon successful completion,
10569    or error_mark_node.
10570 
10571    Note that this function possibly modifies the ARGS parameter, so
10572    it's the responsibility of the caller to restore it.  */
10573 
10574 static tree
gen_elem_of_pack_expansion_instantiation(tree pattern,tree parm_packs,unsigned index,tree args,tsubst_flags_t complain,tree in_decl)10575 gen_elem_of_pack_expansion_instantiation (tree pattern,
10576 					  tree parm_packs,
10577 					  unsigned index,
10578 					  tree args /* This parm gets
10579 						       modified.  */,
10580 					  tsubst_flags_t complain,
10581 					  tree in_decl)
10582 {
10583   tree t;
10584   bool ith_elem_is_expansion = false;
10585 
10586   /* For each parameter pack, change the substitution of the parameter
10587      pack to the ith argument in its argument pack, then expand the
10588      pattern.  */
10589   for (tree pack = parm_packs; pack; pack = TREE_CHAIN (pack))
10590     {
10591       tree parm = TREE_PURPOSE (pack);
10592       tree arg_pack = TREE_VALUE (pack);
10593       tree aps;			/* instance of ARGUMENT_PACK_SELECT.  */
10594 
10595       ith_elem_is_expansion |=
10596 	argument_pack_element_is_expansion_p (arg_pack, index);
10597 
10598       /* Select the Ith argument from the pack.  */
10599       if (TREE_CODE (parm) == PARM_DECL
10600 	  || TREE_CODE (parm) == FIELD_DECL)
10601 	{
10602 	  if (index == 0)
10603 	    {
10604 	      aps = make_argument_pack_select (arg_pack, index);
10605 	      if (!mark_used (parm, complain) && !(complain & tf_error))
10606 		return error_mark_node;
10607 	      register_local_specialization (aps, parm);
10608 	    }
10609 	  else
10610 	    aps = retrieve_local_specialization (parm);
10611 	}
10612       else
10613 	{
10614 	  int idx, level;
10615 	  template_parm_level_and_index (parm, &level, &idx);
10616 
10617 	  if (index == 0)
10618 	    {
10619 	      aps = make_argument_pack_select (arg_pack, index);
10620 	      /* Update the corresponding argument.  */
10621 	      TMPL_ARG (args, level, idx) = aps;
10622 	    }
10623 	  else
10624 	    /* Re-use the ARGUMENT_PACK_SELECT.  */
10625 	    aps = TMPL_ARG (args, level, idx);
10626 	}
10627       ARGUMENT_PACK_SELECT_INDEX (aps) = index;
10628     }
10629 
10630   /* Substitute into the PATTERN with the (possibly altered)
10631      arguments.  */
10632   if (pattern == in_decl)
10633     /* Expanding a fixed parameter pack from
10634        coerce_template_parameter_pack.  */
10635     t = tsubst_decl (pattern, args, complain);
10636   else if (pattern == error_mark_node)
10637     t = error_mark_node;
10638   else if (constraint_p (pattern))
10639     {
10640       if (processing_template_decl)
10641 	t = tsubst_constraint (pattern, args, complain, in_decl);
10642       else
10643 	t = (constraints_satisfied_p (pattern, args)
10644 	     ? boolean_true_node : boolean_false_node);
10645     }
10646   else if (!TYPE_P (pattern))
10647     t = tsubst_expr (pattern, args, complain, in_decl,
10648 		     /*integral_constant_expression_p=*/false);
10649   else
10650     t = tsubst (pattern, args, complain, in_decl);
10651 
10652   /*  If the Ith argument pack element is a pack expansion, then
10653       the Ith element resulting from the substituting is going to
10654       be a pack expansion as well.  */
10655   if (ith_elem_is_expansion)
10656     t = make_pack_expansion (t);
10657 
10658   return t;
10659 }
10660 
10661 /* When the unexpanded parameter pack in a fold expression expands to an empty
10662    sequence, the value of the expression is as follows; the program is
10663    ill-formed if the operator is not listed in this table.
10664 
10665    &&	true
10666    ||	false
10667    ,	void()  */
10668 
10669 tree
expand_empty_fold(tree t,tsubst_flags_t complain)10670 expand_empty_fold (tree t, tsubst_flags_t complain)
10671 {
10672   tree_code code = (tree_code)TREE_INT_CST_LOW (TREE_OPERAND (t, 0));
10673   if (!FOLD_EXPR_MODIFY_P (t))
10674     switch (code)
10675       {
10676       case TRUTH_ANDIF_EXPR:
10677 	return boolean_true_node;
10678       case TRUTH_ORIF_EXPR:
10679 	return boolean_false_node;
10680       case COMPOUND_EXPR:
10681 	return void_node;
10682       default:
10683 	break;
10684       }
10685 
10686   if (complain & tf_error)
10687     error_at (location_of (t),
10688 	      "fold of empty expansion over %O", code);
10689   return error_mark_node;
10690 }
10691 
10692 /* Given a fold-expression T and a current LEFT and RIGHT operand,
10693    form an expression that combines the two terms using the
10694    operator of T. */
10695 
10696 static tree
fold_expression(tree t,tree left,tree right,tsubst_flags_t complain)10697 fold_expression (tree t, tree left, tree right, tsubst_flags_t complain)
10698 {
10699   tree op = FOLD_EXPR_OP (t);
10700   tree_code code = (tree_code)TREE_INT_CST_LOW (op);
10701 
10702   // Handle compound assignment operators.
10703   if (FOLD_EXPR_MODIFY_P (t))
10704     return build_x_modify_expr (input_location, left, code, right, complain);
10705 
10706   switch (code)
10707     {
10708     case COMPOUND_EXPR:
10709       return build_x_compound_expr (input_location, left, right, complain);
10710     case DOTSTAR_EXPR:
10711       return build_m_component_ref (left, right, complain);
10712     default:
10713       return build_x_binary_op (input_location, code,
10714                                 left, TREE_CODE (left),
10715                                 right, TREE_CODE (right),
10716                                 /*overload=*/NULL,
10717                                 complain);
10718     }
10719 }
10720 
10721 /* Substitute ARGS into the pack of a fold expression T. */
10722 
10723 static inline tree
tsubst_fold_expr_pack(tree t,tree args,tsubst_flags_t complain,tree in_decl)10724 tsubst_fold_expr_pack (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10725 {
10726   return tsubst_pack_expansion (FOLD_EXPR_PACK (t), args, complain, in_decl);
10727 }
10728 
10729 /* Substitute ARGS into the pack of a fold expression T. */
10730 
10731 static inline tree
tsubst_fold_expr_init(tree t,tree args,tsubst_flags_t complain,tree in_decl)10732 tsubst_fold_expr_init (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10733 {
10734   return tsubst_expr (FOLD_EXPR_INIT (t), args, complain, in_decl, false);
10735 }
10736 
10737 /* Expand a PACK of arguments into a grouped as left fold.
10738    Given a pack containing elements A0, A1, ..., An and an
10739    operator @, this builds the expression:
10740 
10741       ((A0 @ A1) @ A2) ... @ An
10742 
10743    Note that PACK must not be empty.
10744 
10745    The operator is defined by the original fold expression T. */
10746 
10747 static tree
expand_left_fold(tree t,tree pack,tsubst_flags_t complain)10748 expand_left_fold (tree t, tree pack, tsubst_flags_t complain)
10749 {
10750   tree left = TREE_VEC_ELT (pack, 0);
10751   for (int i = 1; i < TREE_VEC_LENGTH (pack); ++i)
10752     {
10753       tree right = TREE_VEC_ELT (pack, i);
10754       left = fold_expression (t, left, right, complain);
10755     }
10756   return left;
10757 }
10758 
10759 /* Substitute into a unary left fold expression. */
10760 
10761 static tree
tsubst_unary_left_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)10762 tsubst_unary_left_fold (tree t, tree args, tsubst_flags_t complain,
10763                         tree in_decl)
10764 {
10765   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
10766   if (pack == error_mark_node)
10767     return error_mark_node;
10768   if (PACK_EXPANSION_P (pack))
10769     {
10770       tree r = copy_node (t);
10771       FOLD_EXPR_PACK (r) = pack;
10772       return r;
10773     }
10774   if (TREE_VEC_LENGTH (pack) == 0)
10775     return expand_empty_fold (t, complain);
10776   else
10777     return expand_left_fold (t, pack, complain);
10778 }
10779 
10780 /* Substitute into a binary left fold expression.
10781 
10782    Do ths by building a single (non-empty) vector of argumnts and
10783    building the expression from those elements. */
10784 
10785 static tree
tsubst_binary_left_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)10786 tsubst_binary_left_fold (tree t, tree args, tsubst_flags_t complain,
10787                          tree in_decl)
10788 {
10789   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
10790   if (pack == error_mark_node)
10791     return error_mark_node;
10792   tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
10793   if (init == error_mark_node)
10794     return error_mark_node;
10795 
10796   if (PACK_EXPANSION_P (pack))
10797     {
10798       tree r = copy_node (t);
10799       FOLD_EXPR_PACK (r) = pack;
10800       FOLD_EXPR_INIT (r) = init;
10801       return r;
10802     }
10803 
10804   tree vec = make_tree_vec (TREE_VEC_LENGTH (pack) + 1);
10805   TREE_VEC_ELT (vec, 0) = init;
10806   for (int i = 0; i < TREE_VEC_LENGTH (pack); ++i)
10807     TREE_VEC_ELT (vec, i + 1) = TREE_VEC_ELT (pack, i);
10808 
10809   return expand_left_fold (t, vec, complain);
10810 }
10811 
10812 /* Expand a PACK of arguments into a grouped as right fold.
10813    Given a pack containing elementns A0, A1, ..., and an
10814    operator @, this builds the expression:
10815 
10816       A0@ ... (An-2 @ (An-1 @ An))
10817 
10818    Note that PACK must not be empty.
10819 
10820    The operator is defined by the original fold expression T. */
10821 
10822 tree
expand_right_fold(tree t,tree pack,tsubst_flags_t complain)10823 expand_right_fold (tree t, tree pack, tsubst_flags_t complain)
10824 {
10825   // Build the expression.
10826   int n = TREE_VEC_LENGTH (pack);
10827   tree right = TREE_VEC_ELT (pack, n - 1);
10828   for (--n; n != 0; --n)
10829     {
10830       tree left = TREE_VEC_ELT (pack, n - 1);
10831       right = fold_expression (t, left, right, complain);
10832     }
10833   return right;
10834 }
10835 
10836 /* Substitute into a unary right fold expression. */
10837 
10838 static tree
tsubst_unary_right_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)10839 tsubst_unary_right_fold (tree t, tree args, tsubst_flags_t complain,
10840                          tree in_decl)
10841 {
10842   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
10843   if (pack == error_mark_node)
10844     return error_mark_node;
10845   if (PACK_EXPANSION_P (pack))
10846     {
10847       tree r = copy_node (t);
10848       FOLD_EXPR_PACK (r) = pack;
10849       return r;
10850     }
10851   if (TREE_VEC_LENGTH (pack) == 0)
10852     return expand_empty_fold (t, complain);
10853   else
10854     return expand_right_fold (t, pack, complain);
10855 }
10856 
10857 /* Substitute into a binary right fold expression.
10858 
10859    Do ths by building a single (non-empty) vector of arguments and
10860    building the expression from those elements. */
10861 
10862 static tree
tsubst_binary_right_fold(tree t,tree args,tsubst_flags_t complain,tree in_decl)10863 tsubst_binary_right_fold (tree t, tree args, tsubst_flags_t complain,
10864                          tree in_decl)
10865 {
10866   tree pack = tsubst_fold_expr_pack (t, args, complain, in_decl);
10867   if (pack == error_mark_node)
10868     return error_mark_node;
10869   tree init = tsubst_fold_expr_init (t, args, complain, in_decl);
10870   if (init == error_mark_node)
10871     return error_mark_node;
10872 
10873   if (PACK_EXPANSION_P (pack))
10874     {
10875       tree r = copy_node (t);
10876       FOLD_EXPR_PACK (r) = pack;
10877       FOLD_EXPR_INIT (r) = init;
10878       return r;
10879     }
10880 
10881   int n = TREE_VEC_LENGTH (pack);
10882   tree vec = make_tree_vec (n + 1);
10883   for (int i = 0; i < n; ++i)
10884     TREE_VEC_ELT (vec, i) = TREE_VEC_ELT (pack, i);
10885   TREE_VEC_ELT (vec, n) = init;
10886 
10887   return expand_right_fold (t, vec, complain);
10888 }
10889 
10890 
10891 /* Substitute ARGS into T, which is an pack expansion
10892    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
10893    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
10894    (if only a partial substitution could be performed) or
10895    ERROR_MARK_NODE if there was an error.  */
10896 tree
tsubst_pack_expansion(tree t,tree args,tsubst_flags_t complain,tree in_decl)10897 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
10898 		       tree in_decl)
10899 {
10900   tree pattern;
10901   tree pack, packs = NULL_TREE;
10902   bool unsubstituted_packs = false;
10903   int i, len = -1;
10904   tree result;
10905   hash_map<tree, tree> *saved_local_specializations = NULL;
10906   bool need_local_specializations = false;
10907   int levels;
10908 
10909   gcc_assert (PACK_EXPANSION_P (t));
10910   pattern = PACK_EXPANSION_PATTERN (t);
10911 
10912   /* Add in any args remembered from an earlier partial instantiation.  */
10913   args = add_to_template_args (PACK_EXPANSION_EXTRA_ARGS (t), args);
10914 
10915   levels = TMPL_ARGS_DEPTH (args);
10916 
10917   /* Determine the argument packs that will instantiate the parameter
10918      packs used in the expansion expression. While we're at it,
10919      compute the number of arguments to be expanded and make sure it
10920      is consistent.  */
10921   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
10922        pack = TREE_CHAIN (pack))
10923     {
10924       tree parm_pack = TREE_VALUE (pack);
10925       tree arg_pack = NULL_TREE;
10926       tree orig_arg = NULL_TREE;
10927       int level = 0;
10928 
10929       if (TREE_CODE (parm_pack) == BASES)
10930        {
10931          if (BASES_DIRECT (parm_pack))
10932            return calculate_direct_bases (tsubst_expr (BASES_TYPE (parm_pack),
10933                                                         args, complain, in_decl, false));
10934          else
10935            return calculate_bases (tsubst_expr (BASES_TYPE (parm_pack),
10936                                                  args, complain, in_decl, false));
10937        }
10938       if (TREE_CODE (parm_pack) == PARM_DECL)
10939 	{
10940 	  /* We know we have correct local_specializations if this
10941 	     expansion is at function scope, or if we're dealing with a
10942 	     local parameter in a requires expression; for the latter,
10943 	     tsubst_requires_expr set it up appropriately.  */
10944 	  if (PACK_EXPANSION_LOCAL_P (t) || CONSTRAINT_VAR_P (parm_pack))
10945 	    arg_pack = retrieve_local_specialization (parm_pack);
10946 	  else
10947 	    /* We can't rely on local_specializations for a parameter
10948 	       name used later in a function declaration (such as in a
10949 	       late-specified return type).  Even if it exists, it might
10950 	       have the wrong value for a recursive call.  */
10951 	    need_local_specializations = true;
10952 
10953 	  if (!arg_pack)
10954 	    {
10955 	      /* This parameter pack was used in an unevaluated context.  Just
10956 		 make a dummy decl, since it's only used for its type.  */
10957 	      arg_pack = tsubst_decl (parm_pack, args, complain);
10958 	      if (arg_pack && DECL_PACK_P (arg_pack))
10959 		/* Partial instantiation of the parm_pack, we can't build
10960 		   up an argument pack yet.  */
10961 		arg_pack = NULL_TREE;
10962 	      else
10963 		arg_pack = make_fnparm_pack (arg_pack);
10964 	    }
10965 	}
10966       else if (TREE_CODE (parm_pack) == FIELD_DECL)
10967 	arg_pack = tsubst_copy (parm_pack, args, complain, in_decl);
10968       else
10969         {
10970 	  int idx;
10971           template_parm_level_and_index (parm_pack, &level, &idx);
10972 
10973           if (level <= levels)
10974             arg_pack = TMPL_ARG (args, level, idx);
10975         }
10976 
10977       orig_arg = arg_pack;
10978       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
10979 	arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
10980 
10981       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
10982 	/* This can only happen if we forget to expand an argument
10983 	   pack somewhere else. Just return an error, silently.  */
10984 	{
10985 	  result = make_tree_vec (1);
10986 	  TREE_VEC_ELT (result, 0) = error_mark_node;
10987 	  return result;
10988 	}
10989 
10990       if (arg_pack)
10991         {
10992           int my_len =
10993             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
10994 
10995 	  /* Don't bother trying to do a partial substitution with
10996 	     incomplete packs; we'll try again after deduction.  */
10997           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
10998             return t;
10999 
11000           if (len < 0)
11001 	    len = my_len;
11002           else if (len != my_len)
11003             {
11004 	      if (!(complain & tf_error))
11005 		/* Fail quietly.  */;
11006               else if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
11007                 error ("mismatched argument pack lengths while expanding "
11008                        "%<%T%>",
11009                        pattern);
11010               else
11011                 error ("mismatched argument pack lengths while expanding "
11012                        "%<%E%>",
11013                        pattern);
11014               return error_mark_node;
11015             }
11016 
11017           /* Keep track of the parameter packs and their corresponding
11018              argument packs.  */
11019           packs = tree_cons (parm_pack, arg_pack, packs);
11020           TREE_TYPE (packs) = orig_arg;
11021         }
11022       else
11023 	{
11024 	  /* We can't substitute for this parameter pack.  We use a flag as
11025 	     well as the missing_level counter because function parameter
11026 	     packs don't have a level.  */
11027 	  unsubstituted_packs = true;
11028 	}
11029     }
11030 
11031   /* If the expansion is just T..., return the matching argument pack, unless
11032      we need to call convert_from_reference on all the elements.  This is an
11033      important optimization; see c++/68422.  */
11034   if (!unsubstituted_packs
11035       && TREE_PURPOSE (packs) == pattern)
11036     {
11037       tree args = ARGUMENT_PACK_ARGS (TREE_VALUE (packs));
11038       /* Types need no adjustment, nor does sizeof..., and if we still have
11039 	 some pack expansion args we won't do anything yet.  */
11040       if (TREE_CODE (t) == TYPE_PACK_EXPANSION
11041 	  || PACK_EXPANSION_SIZEOF_P (t)
11042 	  || pack_expansion_args_count (args))
11043 	return args;
11044       /* Also optimize expression pack expansions if we can tell that the
11045 	 elements won't have reference type.  */
11046       tree type = TREE_TYPE (pattern);
11047       if (type && TREE_CODE (type) != REFERENCE_TYPE
11048 	  && !PACK_EXPANSION_P (type)
11049 	  && !WILDCARD_TYPE_P (type))
11050 	return args;
11051       /* Otherwise use the normal path so we get convert_from_reference.  */
11052     }
11053 
11054   /* We cannot expand this expansion expression, because we don't have
11055      all of the argument packs we need.  */
11056   if (use_pack_expansion_extra_args_p (packs, len, unsubstituted_packs))
11057     {
11058       /* We got some full packs, but we can't substitute them in until we
11059 	 have values for all the packs.  So remember these until then.  */
11060 
11061       t = make_pack_expansion (pattern);
11062       PACK_EXPANSION_EXTRA_ARGS (t) = args;
11063       return t;
11064     }
11065   else if (unsubstituted_packs)
11066     {
11067       /* There were no real arguments, we're just replacing a parameter
11068 	 pack with another version of itself. Substitute into the
11069 	 pattern and return a PACK_EXPANSION_*. The caller will need to
11070 	 deal with that.  */
11071       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
11072 	t = tsubst_expr (pattern, args, complain, in_decl,
11073 			 /*integral_constant_expression_p=*/false);
11074       else
11075 	t = tsubst (pattern, args, complain, in_decl);
11076       t = make_pack_expansion (t);
11077       return t;
11078     }
11079 
11080   gcc_assert (len >= 0);
11081 
11082   if (need_local_specializations)
11083     {
11084       /* We're in a late-specified return type, so create our own local
11085 	 specializations map; the current map is either NULL or (in the
11086 	 case of recursive unification) might have bindings that we don't
11087 	 want to use or alter.  */
11088       saved_local_specializations = local_specializations;
11089       local_specializations = new hash_map<tree, tree>;
11090     }
11091 
11092   /* For each argument in each argument pack, substitute into the
11093      pattern.  */
11094   result = make_tree_vec (len);
11095   tree elem_args = copy_template_args (args);
11096   for (i = 0; i < len; ++i)
11097     {
11098       t = gen_elem_of_pack_expansion_instantiation (pattern, packs,
11099 						    i,
11100 						    elem_args, complain,
11101 						    in_decl);
11102       TREE_VEC_ELT (result, i) = t;
11103       if (t == error_mark_node)
11104 	{
11105 	  result = error_mark_node;
11106 	  break;
11107 	}
11108     }
11109 
11110   /* Update ARGS to restore the substitution from parameter packs to
11111      their argument packs.  */
11112   for (pack = packs; pack; pack = TREE_CHAIN (pack))
11113     {
11114       tree parm = TREE_PURPOSE (pack);
11115 
11116       if (TREE_CODE (parm) == PARM_DECL
11117 	  || TREE_CODE (parm) == FIELD_DECL)
11118         register_local_specialization (TREE_TYPE (pack), parm);
11119       else
11120         {
11121           int idx, level;
11122 
11123 	  if (TREE_VALUE (pack) == NULL_TREE)
11124 	    continue;
11125 
11126           template_parm_level_and_index (parm, &level, &idx);
11127 
11128           /* Update the corresponding argument.  */
11129           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
11130             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
11131               TREE_TYPE (pack);
11132           else
11133             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
11134         }
11135     }
11136 
11137   if (need_local_specializations)
11138     {
11139       delete local_specializations;
11140       local_specializations = saved_local_specializations;
11141     }
11142 
11143   /* If the dependent pack arguments were such that we end up with only a
11144      single pack expansion again, there's no need to keep it in a TREE_VEC.  */
11145   if (len == 1 && TREE_CODE (result) == TREE_VEC
11146       && PACK_EXPANSION_P (TREE_VEC_ELT (result, 0)))
11147     return TREE_VEC_ELT (result, 0);
11148 
11149   return result;
11150 }
11151 
11152 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
11153    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
11154    parameter packs; all parms generated from a function parameter pack will
11155    have the same DECL_PARM_INDEX.  */
11156 
11157 tree
get_pattern_parm(tree parm,tree tmpl)11158 get_pattern_parm (tree parm, tree tmpl)
11159 {
11160   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
11161   tree patparm;
11162 
11163   if (DECL_ARTIFICIAL (parm))
11164     {
11165       for (patparm = DECL_ARGUMENTS (pattern);
11166 	   patparm; patparm = DECL_CHAIN (patparm))
11167 	if (DECL_ARTIFICIAL (patparm)
11168 	    && DECL_NAME (parm) == DECL_NAME (patparm))
11169 	  break;
11170     }
11171   else
11172     {
11173       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
11174       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
11175       gcc_assert (DECL_PARM_INDEX (patparm)
11176 		  == DECL_PARM_INDEX (parm));
11177     }
11178 
11179   return patparm;
11180 }
11181 
11182 /* Make an argument pack out of the TREE_VEC VEC.  */
11183 
11184 static tree
make_argument_pack(tree vec)11185 make_argument_pack (tree vec)
11186 {
11187   tree pack;
11188   tree elt = TREE_VEC_ELT (vec, 0);
11189   if (TYPE_P (elt))
11190     pack = cxx_make_type (TYPE_ARGUMENT_PACK);
11191   else
11192     {
11193       pack = make_node (NONTYPE_ARGUMENT_PACK);
11194       TREE_TYPE (pack) = TREE_TYPE (elt);
11195       TREE_CONSTANT (pack) = 1;
11196     }
11197   SET_ARGUMENT_PACK_ARGS (pack, vec);
11198   return pack;
11199 }
11200 
11201 /* Return an exact copy of template args T that can be modified
11202    independently.  */
11203 
11204 static tree
copy_template_args(tree t)11205 copy_template_args (tree t)
11206 {
11207   if (t == error_mark_node)
11208     return t;
11209 
11210   int len = TREE_VEC_LENGTH (t);
11211   tree new_vec = make_tree_vec (len);
11212 
11213   for (int i = 0; i < len; ++i)
11214     {
11215       tree elt = TREE_VEC_ELT (t, i);
11216       if (elt && TREE_CODE (elt) == TREE_VEC)
11217 	elt = copy_template_args (elt);
11218       TREE_VEC_ELT (new_vec, i) = elt;
11219     }
11220 
11221   NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_vec)
11222     = NON_DEFAULT_TEMPLATE_ARGS_COUNT (t);
11223 
11224   return new_vec;
11225 }
11226 
11227 /* Substitute ARGS into the vector or list of template arguments T.  */
11228 
11229 static tree
tsubst_template_args(tree t,tree args,tsubst_flags_t complain,tree in_decl)11230 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11231 {
11232   tree orig_t = t;
11233   int len, need_new = 0, i, expanded_len_adjust = 0, out;
11234   tree *elts;
11235 
11236   if (t == error_mark_node)
11237     return error_mark_node;
11238 
11239   len = TREE_VEC_LENGTH (t);
11240   elts = XALLOCAVEC (tree, len);
11241 
11242   for (i = 0; i < len; i++)
11243     {
11244       tree orig_arg = TREE_VEC_ELT (t, i);
11245       tree new_arg;
11246 
11247       if (TREE_CODE (orig_arg) == TREE_VEC)
11248 	new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
11249       else if (PACK_EXPANSION_P (orig_arg))
11250         {
11251           /* Substitute into an expansion expression.  */
11252           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
11253 
11254           if (TREE_CODE (new_arg) == TREE_VEC)
11255             /* Add to the expanded length adjustment the number of
11256                expanded arguments. We subtract one from this
11257                measurement, because the argument pack expression
11258                itself is already counted as 1 in
11259                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
11260                the argument pack is empty.  */
11261             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
11262         }
11263       else if (ARGUMENT_PACK_P (orig_arg))
11264         {
11265           /* Substitute into each of the arguments.  */
11266           new_arg = TYPE_P (orig_arg)
11267             ? cxx_make_type (TREE_CODE (orig_arg))
11268             : make_node (TREE_CODE (orig_arg));
11269 
11270           SET_ARGUMENT_PACK_ARGS (
11271             new_arg,
11272             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
11273                                   args, complain, in_decl));
11274 
11275           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
11276             new_arg = error_mark_node;
11277 
11278           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
11279             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
11280                                           complain, in_decl);
11281             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
11282 
11283             if (TREE_TYPE (new_arg) == error_mark_node)
11284               new_arg = error_mark_node;
11285           }
11286         }
11287       else
11288 	new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
11289 
11290       if (new_arg == error_mark_node)
11291 	return error_mark_node;
11292 
11293       elts[i] = new_arg;
11294       if (new_arg != orig_arg)
11295 	need_new = 1;
11296     }
11297 
11298   if (!need_new)
11299     return t;
11300 
11301   /* Make space for the expanded arguments coming from template
11302      argument packs.  */
11303   t = make_tree_vec (len + expanded_len_adjust);
11304   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
11305      arguments for a member template.
11306      In that case each TREE_VEC in ORIG_T represents a level of template
11307      arguments, and ORIG_T won't carry any non defaulted argument count.
11308      It will rather be the nested TREE_VECs that will carry one.
11309      In other words, ORIG_T carries a non defaulted argument count only
11310      if it doesn't contain any nested TREE_VEC.  */
11311   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
11312     {
11313       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
11314       count += expanded_len_adjust;
11315       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
11316     }
11317   for (i = 0, out = 0; i < len; i++)
11318     {
11319       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
11320            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
11321           && TREE_CODE (elts[i]) == TREE_VEC)
11322         {
11323           int idx;
11324 
11325           /* Now expand the template argument pack "in place".  */
11326           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
11327             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
11328         }
11329       else
11330         {
11331           TREE_VEC_ELT (t, out) = elts[i];
11332           out++;
11333         }
11334     }
11335 
11336   return t;
11337 }
11338 
11339 /* Return the result of substituting ARGS into the template parameters
11340    given by PARMS.  If there are m levels of ARGS and m + n levels of
11341    PARMS, then the result will contain n levels of PARMS.  For
11342    example, if PARMS is `template <class T> template <class U>
11343    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
11344    result will be `template <int*, double, class V>'.  */
11345 
11346 static tree
tsubst_template_parms(tree parms,tree args,tsubst_flags_t complain)11347 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
11348 {
11349   tree r = NULL_TREE;
11350   tree* new_parms;
11351 
11352   /* When substituting into a template, we must set
11353      PROCESSING_TEMPLATE_DECL as the template parameters may be
11354      dependent if they are based on one-another, and the dependency
11355      predicates are short-circuit outside of templates.  */
11356   ++processing_template_decl;
11357 
11358   for (new_parms = &r;
11359        parms && TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
11360        new_parms = &(TREE_CHAIN (*new_parms)),
11361 	 parms = TREE_CHAIN (parms))
11362     {
11363       tree new_vec =
11364 	make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
11365       int i;
11366 
11367       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
11368 	{
11369           tree tuple;
11370 
11371           if (parms == error_mark_node)
11372             continue;
11373 
11374           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
11375 
11376           if (tuple == error_mark_node)
11377             continue;
11378 
11379 	  TREE_VEC_ELT (new_vec, i) =
11380 	    tsubst_template_parm (tuple, args, complain);
11381 	}
11382 
11383       *new_parms =
11384 	tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
11385 			     - TMPL_ARGS_DEPTH (args)),
11386 		   new_vec, NULL_TREE);
11387     }
11388 
11389   --processing_template_decl;
11390 
11391   return r;
11392 }
11393 
11394 /* Return the result of substituting ARGS into one template parameter
11395    given by T. T Must be a TREE_LIST which TREE_VALUE is the template
11396    parameter and which TREE_PURPOSE is the default argument of the
11397    template parameter.  */
11398 
11399 static tree
tsubst_template_parm(tree t,tree args,tsubst_flags_t complain)11400 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
11401 {
11402   tree default_value, parm_decl;
11403 
11404   if (args == NULL_TREE
11405       || t == NULL_TREE
11406       || t == error_mark_node)
11407     return t;
11408 
11409   gcc_assert (TREE_CODE (t) == TREE_LIST);
11410 
11411   default_value = TREE_PURPOSE (t);
11412   parm_decl = TREE_VALUE (t);
11413 
11414   parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
11415   if (TREE_CODE (parm_decl) == PARM_DECL
11416       && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
11417     parm_decl = error_mark_node;
11418   default_value = tsubst_template_arg (default_value, args,
11419 				       complain, NULL_TREE);
11420 
11421   return build_tree_list (default_value, parm_decl);
11422 }
11423 
11424 /* Substitute the ARGS into the indicated aggregate (or enumeration)
11425    type T.  If T is not an aggregate or enumeration type, it is
11426    handled as if by tsubst.  IN_DECL is as for tsubst.  If
11427    ENTERING_SCOPE is nonzero, T is the context for a template which
11428    we are presently tsubst'ing.  Return the substituted value.  */
11429 
11430 static tree
tsubst_aggr_type(tree t,tree args,tsubst_flags_t complain,tree in_decl,int entering_scope)11431 tsubst_aggr_type (tree t,
11432 		  tree args,
11433 		  tsubst_flags_t complain,
11434 		  tree in_decl,
11435 		  int entering_scope)
11436 {
11437   if (t == NULL_TREE)
11438     return NULL_TREE;
11439 
11440   switch (TREE_CODE (t))
11441     {
11442     case RECORD_TYPE:
11443       if (TYPE_PTRMEMFUNC_P (t))
11444 	return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
11445 
11446       /* Else fall through.  */
11447     case ENUMERAL_TYPE:
11448     case UNION_TYPE:
11449       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
11450 	{
11451 	  tree argvec;
11452 	  tree context;
11453 	  tree r;
11454 	  int saved_unevaluated_operand;
11455 	  int saved_inhibit_evaluation_warnings;
11456 
11457 	  /* In "sizeof(X<I>)" we need to evaluate "I".  */
11458 	  saved_unevaluated_operand = cp_unevaluated_operand;
11459 	  cp_unevaluated_operand = 0;
11460 	  saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
11461 	  c_inhibit_evaluation_warnings = 0;
11462 
11463 	  /* First, determine the context for the type we are looking
11464 	     up.  */
11465 	  context = TYPE_CONTEXT (t);
11466 	  if (context && TYPE_P (context))
11467 	    {
11468 	      context = tsubst_aggr_type (context, args, complain,
11469 					  in_decl, /*entering_scope=*/1);
11470 	      /* If context is a nested class inside a class template,
11471 	         it may still need to be instantiated (c++/33959).  */
11472 	      context = complete_type (context);
11473 	    }
11474 
11475 	  /* Then, figure out what arguments are appropriate for the
11476 	     type we are trying to find.  For example, given:
11477 
11478 	       template <class T> struct S;
11479 	       template <class T, class U> void f(T, U) { S<U> su; }
11480 
11481 	     and supposing that we are instantiating f<int, double>,
11482 	     then our ARGS will be {int, double}, but, when looking up
11483 	     S we only want {double}.  */
11484 	  argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
11485 					 complain, in_decl);
11486 	  if (argvec == error_mark_node)
11487 	    r = error_mark_node;
11488 	  else
11489 	    {
11490 	      r = lookup_template_class (t, argvec, in_decl, context,
11491 					 entering_scope, complain);
11492 	      r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
11493 	    }
11494 
11495 	  cp_unevaluated_operand = saved_unevaluated_operand;
11496 	  c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
11497 
11498 	  return r;
11499 	}
11500       else
11501 	/* This is not a template type, so there's nothing to do.  */
11502 	return t;
11503 
11504     default:
11505       return tsubst (t, args, complain, in_decl);
11506     }
11507 }
11508 
11509 /* Substitute into the default argument ARG (a default argument for
11510    FN), which has the indicated TYPE.  */
11511 
11512 tree
tsubst_default_argument(tree fn,tree type,tree arg,tsubst_flags_t complain)11513 tsubst_default_argument (tree fn, tree type, tree arg, tsubst_flags_t complain)
11514 {
11515   tree saved_class_ptr = NULL_TREE;
11516   tree saved_class_ref = NULL_TREE;
11517   int errs = errorcount + sorrycount;
11518 
11519   /* This can happen in invalid code.  */
11520   if (TREE_CODE (arg) == DEFAULT_ARG)
11521     return arg;
11522 
11523   /* This default argument came from a template.  Instantiate the
11524      default argument here, not in tsubst.  In the case of
11525      something like:
11526 
11527        template <class T>
11528        struct S {
11529 	 static T t();
11530 	 void f(T = t());
11531        };
11532 
11533      we must be careful to do name lookup in the scope of S<T>,
11534      rather than in the current class.  */
11535   push_access_scope (fn);
11536   /* The "this" pointer is not valid in a default argument.  */
11537   if (cfun)
11538     {
11539       saved_class_ptr = current_class_ptr;
11540       cp_function_chain->x_current_class_ptr = NULL_TREE;
11541       saved_class_ref = current_class_ref;
11542       cp_function_chain->x_current_class_ref = NULL_TREE;
11543     }
11544 
11545   push_deferring_access_checks(dk_no_deferred);
11546   /* The default argument expression may cause implicitly defined
11547      member functions to be synthesized, which will result in garbage
11548      collection.  We must treat this situation as if we were within
11549      the body of function so as to avoid collecting live data on the
11550      stack.  */
11551   ++function_depth;
11552   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
11553 		     complain, NULL_TREE,
11554 		     /*integral_constant_expression_p=*/false);
11555   --function_depth;
11556   pop_deferring_access_checks();
11557 
11558   /* Restore the "this" pointer.  */
11559   if (cfun)
11560     {
11561       cp_function_chain->x_current_class_ptr = saved_class_ptr;
11562       cp_function_chain->x_current_class_ref = saved_class_ref;
11563     }
11564 
11565   if (errorcount+sorrycount > errs
11566       && (complain & tf_warning_or_error))
11567     inform (input_location,
11568 	    "  when instantiating default argument for call to %D", fn);
11569 
11570   /* Make sure the default argument is reasonable.  */
11571   arg = check_default_argument (type, arg, complain);
11572 
11573   pop_access_scope (fn);
11574 
11575   return arg;
11576 }
11577 
11578 /* Substitute into all the default arguments for FN.  */
11579 
11580 static void
tsubst_default_arguments(tree fn,tsubst_flags_t complain)11581 tsubst_default_arguments (tree fn, tsubst_flags_t complain)
11582 {
11583   tree arg;
11584   tree tmpl_args;
11585 
11586   tmpl_args = DECL_TI_ARGS (fn);
11587 
11588   /* If this function is not yet instantiated, we certainly don't need
11589      its default arguments.  */
11590   if (uses_template_parms (tmpl_args))
11591     return;
11592   /* Don't do this again for clones.  */
11593   if (DECL_CLONED_FUNCTION_P (fn))
11594     return;
11595 
11596   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
11597        arg;
11598        arg = TREE_CHAIN (arg))
11599     if (TREE_PURPOSE (arg))
11600       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
11601 						    TREE_VALUE (arg),
11602 						    TREE_PURPOSE (arg),
11603 						    complain);
11604 }
11605 
11606 /* Substitute the ARGS into the T, which is a _DECL.  Return the
11607    result of the substitution.  Issue error and warning messages under
11608    control of COMPLAIN.  */
11609 
11610 static tree
tsubst_decl(tree t,tree args,tsubst_flags_t complain)11611 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
11612 {
11613 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
11614   location_t saved_loc;
11615   tree r = NULL_TREE;
11616   tree in_decl = t;
11617   hashval_t hash = 0;
11618 
11619   /* Set the filename and linenumber to improve error-reporting.  */
11620   saved_loc = input_location;
11621   input_location = DECL_SOURCE_LOCATION (t);
11622 
11623   switch (TREE_CODE (t))
11624     {
11625     case TEMPLATE_DECL:
11626       {
11627 	/* We can get here when processing a member function template,
11628 	   member class template, or template template parameter.  */
11629 	tree decl = DECL_TEMPLATE_RESULT (t);
11630 	tree spec;
11631 	tree tmpl_args;
11632 	tree full_args;
11633 
11634 	if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
11635 	  {
11636 	    /* Template template parameter is treated here.  */
11637 	    tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11638 	    if (new_type == error_mark_node)
11639 	      r = error_mark_node;
11640 	    /* If we get a real template back, return it.  This can happen in
11641 	       the context of most_specialized_partial_spec.  */
11642 	    else if (TREE_CODE (new_type) == TEMPLATE_DECL)
11643 	      r = new_type;
11644 	    else
11645 	      /* The new TEMPLATE_DECL was built in
11646 		 reduce_template_parm_level.  */
11647 	      r = TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (new_type);
11648 	    break;
11649 	  }
11650 
11651 	/* We might already have an instance of this template.
11652 	   The ARGS are for the surrounding class type, so the
11653 	   full args contain the tsubst'd args for the context,
11654 	   plus the innermost args from the template decl.  */
11655 	tmpl_args = DECL_CLASS_TEMPLATE_P (t)
11656 	  ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
11657 	  : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
11658 	/* Because this is a template, the arguments will still be
11659 	   dependent, even after substitution.  If
11660 	   PROCESSING_TEMPLATE_DECL is not set, the dependency
11661 	   predicates will short-circuit.  */
11662 	++processing_template_decl;
11663 	full_args = tsubst_template_args (tmpl_args, args,
11664 					  complain, in_decl);
11665 	--processing_template_decl;
11666 	if (full_args == error_mark_node)
11667 	  RETURN (error_mark_node);
11668 
11669 	/* If this is a default template template argument,
11670 	   tsubst might not have changed anything.  */
11671 	if (full_args == tmpl_args)
11672 	  RETURN (t);
11673 
11674 	hash = hash_tmpl_and_args (t, full_args);
11675 	spec = retrieve_specialization (t, full_args, hash);
11676 	if (spec != NULL_TREE)
11677 	  {
11678 	    r = spec;
11679 	    break;
11680 	  }
11681 
11682 	/* Make a new template decl.  It will be similar to the
11683 	   original, but will record the current template arguments.
11684 	   We also create a new function declaration, which is just
11685 	   like the old one, but points to this new template, rather
11686 	   than the old one.  */
11687 	r = copy_decl (t);
11688 	gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
11689 	DECL_CHAIN (r) = NULL_TREE;
11690 
11691         // Build new template info linking to the original template decl.
11692 	DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
11693 
11694 	if (TREE_CODE (decl) == TYPE_DECL
11695 	    && !TYPE_DECL_ALIAS_P (decl))
11696 	  {
11697 	    tree new_type;
11698 	    ++processing_template_decl;
11699 	    new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11700 	    --processing_template_decl;
11701 	    if (new_type == error_mark_node)
11702 	      RETURN (error_mark_node);
11703 
11704 	    TREE_TYPE (r) = new_type;
11705 	    /* For a partial specialization, we need to keep pointing to
11706 	       the primary template.  */
11707 	    if (!DECL_TEMPLATE_SPECIALIZATION (t))
11708 	      CLASSTYPE_TI_TEMPLATE (new_type) = r;
11709 	    DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
11710 	    DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
11711 	    DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
11712 	  }
11713 	else
11714 	  {
11715 	    tree new_decl;
11716 	    ++processing_template_decl;
11717 	    new_decl = tsubst (decl, args, complain, in_decl);
11718 	    --processing_template_decl;
11719 	    if (new_decl == error_mark_node)
11720 	      RETURN (error_mark_node);
11721 
11722 	    DECL_TEMPLATE_RESULT (r) = new_decl;
11723 	    DECL_TI_TEMPLATE (new_decl) = r;
11724 	    TREE_TYPE (r) = TREE_TYPE (new_decl);
11725 	    DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
11726 	    DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
11727 	  }
11728 
11729 	SET_DECL_IMPLICIT_INSTANTIATION (r);
11730 	DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
11731 	DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
11732 
11733 	/* The template parameters for this new template are all the
11734 	   template parameters for the old template, except the
11735 	   outermost level of parameters.  */
11736 	DECL_TEMPLATE_PARMS (r)
11737 	  = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
11738 				   complain);
11739 
11740 	if (PRIMARY_TEMPLATE_P (t))
11741 	  DECL_PRIMARY_TEMPLATE (r) = r;
11742 
11743 	if (TREE_CODE (decl) != TYPE_DECL && !VAR_P (decl))
11744 	  /* Record this non-type partial instantiation.  */
11745 	  register_specialization (r, t,
11746 				   DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
11747 				   false, hash);
11748       }
11749       break;
11750 
11751     case FUNCTION_DECL:
11752       {
11753 	tree ctx;
11754 	tree argvec = NULL_TREE;
11755 	tree *friends;
11756 	tree gen_tmpl;
11757 	tree type;
11758 	int member;
11759 	int args_depth;
11760 	int parms_depth;
11761 
11762 	/* Nobody should be tsubst'ing into non-template functions.  */
11763 	gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
11764 
11765 	if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
11766 	  {
11767 	    tree spec;
11768 	    bool dependent_p;
11769 
11770 	    /* If T is not dependent, just return it.  We have to
11771 	       increment PROCESSING_TEMPLATE_DECL because
11772 	       value_dependent_expression_p assumes that nothing is
11773 	       dependent when PROCESSING_TEMPLATE_DECL is zero.  */
11774 	    ++processing_template_decl;
11775 	    dependent_p = value_dependent_expression_p (t);
11776 	    --processing_template_decl;
11777 	    if (!dependent_p)
11778 	      RETURN (t);
11779 
11780 	    /* Calculate the most general template of which R is a
11781 	       specialization, and the complete set of arguments used to
11782 	       specialize R.  */
11783 	    gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
11784 	    argvec = tsubst_template_args (DECL_TI_ARGS
11785                                           (DECL_TEMPLATE_RESULT
11786                                                  (DECL_TI_TEMPLATE (t))),
11787 					   args, complain, in_decl);
11788 	    if (argvec == error_mark_node)
11789 	      RETURN (error_mark_node);
11790 
11791 	    /* Check to see if we already have this specialization.  */
11792 	    hash = hash_tmpl_and_args (gen_tmpl, argvec);
11793 	    spec = retrieve_specialization (gen_tmpl, argvec, hash);
11794 
11795 	    if (spec)
11796 	      {
11797 		r = spec;
11798 		break;
11799 	      }
11800 
11801 	    /* We can see more levels of arguments than parameters if
11802 	       there was a specialization of a member template, like
11803 	       this:
11804 
11805 		 template <class T> struct S { template <class U> void f(); }
11806 		 template <> template <class U> void S<int>::f(U);
11807 
11808 	       Here, we'll be substituting into the specialization,
11809 	       because that's where we can find the code we actually
11810 	       want to generate, but we'll have enough arguments for
11811 	       the most general template.
11812 
11813 	       We also deal with the peculiar case:
11814 
11815 		 template <class T> struct S {
11816 		   template <class U> friend void f();
11817 		 };
11818 		 template <class U> void f() {}
11819 		 template S<int>;
11820 		 template void f<double>();
11821 
11822 	       Here, the ARGS for the instantiation of will be {int,
11823 	       double}.  But, we only need as many ARGS as there are
11824 	       levels of template parameters in CODE_PATTERN.  We are
11825 	       careful not to get fooled into reducing the ARGS in
11826 	       situations like:
11827 
11828 		 template <class T> struct S { template <class U> void f(U); }
11829 		 template <class T> template <> void S<T>::f(int) {}
11830 
11831 	       which we can spot because the pattern will be a
11832 	       specialization in this case.  */
11833 	    args_depth = TMPL_ARGS_DEPTH (args);
11834 	    parms_depth =
11835 	      TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
11836 	    if (args_depth > parms_depth
11837 		&& !DECL_TEMPLATE_SPECIALIZATION (t))
11838 	      args = get_innermost_template_args (args, parms_depth);
11839 	  }
11840 	else
11841 	  {
11842 	    /* This special case arises when we have something like this:
11843 
11844 		 template <class T> struct S {
11845 		   friend void f<int>(int, double);
11846 		 };
11847 
11848 	       Here, the DECL_TI_TEMPLATE for the friend declaration
11849 	       will be an IDENTIFIER_NODE.  We are being called from
11850 	       tsubst_friend_function, and we want only to create a
11851 	       new decl (R) with appropriate types so that we can call
11852 	       determine_specialization.  */
11853 	    gen_tmpl = NULL_TREE;
11854 	  }
11855 
11856 	if (DECL_CLASS_SCOPE_P (t))
11857 	  {
11858 	    if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
11859 	      member = 2;
11860 	    else
11861 	      member = 1;
11862 	    ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
11863 				    complain, t, /*entering_scope=*/1);
11864 	  }
11865 	else
11866 	  {
11867 	    member = 0;
11868 	    ctx = DECL_CONTEXT (t);
11869 	  }
11870 	type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11871 	if (type == error_mark_node)
11872 	  RETURN (error_mark_node);
11873 
11874 	/* If we hit excessive deduction depth, the type is bogus even if
11875 	   it isn't error_mark_node, so don't build a decl.  */
11876 	if (excessive_deduction_depth)
11877 	  RETURN (error_mark_node);
11878 
11879 	/* We do NOT check for matching decls pushed separately at this
11880 	   point, as they may not represent instantiations of this
11881 	   template, and in any case are considered separate under the
11882 	   discrete model.  */
11883 	r = copy_decl (t);
11884 	DECL_USE_TEMPLATE (r) = 0;
11885 	TREE_TYPE (r) = type;
11886 	/* Clear out the mangled name and RTL for the instantiation.  */
11887 	SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
11888 	SET_DECL_RTL (r, NULL);
11889 	/* Leave DECL_INITIAL set on deleted instantiations.  */
11890 	if (!DECL_DELETED_FN (r))
11891 	  DECL_INITIAL (r) = NULL_TREE;
11892 	DECL_CONTEXT (r) = ctx;
11893 
11894 	/* OpenMP UDRs have the only argument a reference to the declared
11895 	   type.  We want to diagnose if the declared type is a reference,
11896 	   which is invalid, but as references to references are usually
11897 	   quietly merged, diagnose it here.  */
11898 	if (DECL_OMP_DECLARE_REDUCTION_P (t))
11899 	  {
11900 	    tree argtype
11901 	      = TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (TREE_TYPE (t))));
11902 	    argtype = tsubst (argtype, args, complain, in_decl);
11903 	    if (TREE_CODE (argtype) == REFERENCE_TYPE)
11904 	      error_at (DECL_SOURCE_LOCATION (t),
11905 			"reference type %qT in "
11906 			"%<#pragma omp declare reduction%>", argtype);
11907 	    if (strchr (IDENTIFIER_POINTER (DECL_NAME (t)), '~') == NULL)
11908 	      DECL_NAME (r) = omp_reduction_id (ERROR_MARK, DECL_NAME (t),
11909 						argtype);
11910 	  }
11911 
11912 	if (member && DECL_CONV_FN_P (r))
11913 	  /* Type-conversion operator.  Reconstruct the name, in
11914 	     case it's the name of one of the template's parameters.  */
11915 	  DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
11916 
11917 	DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
11918 				     complain, t);
11919 	DECL_RESULT (r) = NULL_TREE;
11920 
11921 	TREE_STATIC (r) = 0;
11922 	TREE_PUBLIC (r) = TREE_PUBLIC (t);
11923 	DECL_EXTERNAL (r) = 1;
11924 	/* If this is an instantiation of a function with internal
11925 	   linkage, we already know what object file linkage will be
11926 	   assigned to the instantiation.  */
11927 	DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
11928 	DECL_DEFER_OUTPUT (r) = 0;
11929 	DECL_CHAIN (r) = NULL_TREE;
11930 	DECL_PENDING_INLINE_INFO (r) = 0;
11931 	DECL_PENDING_INLINE_P (r) = 0;
11932 	DECL_SAVED_TREE (r) = NULL_TREE;
11933 	DECL_STRUCT_FUNCTION (r) = NULL;
11934 	TREE_USED (r) = 0;
11935 	/* We'll re-clone as appropriate in instantiate_template.  */
11936 	DECL_CLONED_FUNCTION (r) = NULL_TREE;
11937 
11938 	/* If we aren't complaining now, return on error before we register
11939 	   the specialization so that we'll complain eventually.  */
11940 	if ((complain & tf_error) == 0
11941 	    && IDENTIFIER_OPNAME_P (DECL_NAME (r))
11942 	    && !grok_op_properties (r, /*complain=*/false))
11943 	  RETURN (error_mark_node);
11944 
11945         /* When instantiating a constrained member, substitute
11946            into the constraints to create a new constraint.  */
11947         if (tree ci = get_constraints (t))
11948           if (member)
11949             {
11950               ci = tsubst_constraint_info (ci, argvec, complain, NULL_TREE);
11951               set_constraints (r, ci);
11952             }
11953 
11954 	/* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
11955 	   this in the special friend case mentioned above where
11956 	   GEN_TMPL is NULL.  */
11957 	if (gen_tmpl)
11958 	  {
11959 	    DECL_TEMPLATE_INFO (r)
11960 	      = build_template_info (gen_tmpl, argvec);
11961 	    SET_DECL_IMPLICIT_INSTANTIATION (r);
11962 
11963 	    tree new_r
11964 	      = register_specialization (r, gen_tmpl, argvec, false, hash);
11965 	    if (new_r != r)
11966 	      /* We instantiated this while substituting into
11967 		 the type earlier (template/friend54.C).  */
11968 	      RETURN (new_r);
11969 
11970 	    /* We're not supposed to instantiate default arguments
11971 	       until they are called, for a template.  But, for a
11972 	       declaration like:
11973 
11974 		 template <class T> void f ()
11975 		 { extern void g(int i = T()); }
11976 
11977 	       we should do the substitution when the template is
11978 	       instantiated.  We handle the member function case in
11979 	       instantiate_class_template since the default arguments
11980 	       might refer to other members of the class.  */
11981 	    if (!member
11982 		&& !PRIMARY_TEMPLATE_P (gen_tmpl)
11983 		&& !uses_template_parms (argvec))
11984 	      tsubst_default_arguments (r, complain);
11985 	  }
11986 	else
11987 	  DECL_TEMPLATE_INFO (r) = NULL_TREE;
11988 
11989 	/* Copy the list of befriending classes.  */
11990 	for (friends = &DECL_BEFRIENDING_CLASSES (r);
11991 	     *friends;
11992 	     friends = &TREE_CHAIN (*friends))
11993 	  {
11994 	    *friends = copy_node (*friends);
11995 	    TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
11996 					    args, complain,
11997 					    in_decl);
11998 	  }
11999 
12000 	if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
12001 	  {
12002 	    maybe_retrofit_in_chrg (r);
12003 	    if (DECL_CONSTRUCTOR_P (r))
12004 	      grok_ctor_properties (ctx, r);
12005 	    if (DECL_INHERITED_CTOR_BASE (r))
12006 	      deduce_inheriting_ctor (r);
12007 	    /* If this is an instantiation of a member template, clone it.
12008 	       If it isn't, that'll be handled by
12009 	       clone_constructors_and_destructors.  */
12010 	    if (PRIMARY_TEMPLATE_P (gen_tmpl))
12011 	      clone_function_decl (r, /*update_method_vec_p=*/0);
12012 	  }
12013 	else if ((complain & tf_error) != 0
12014 		 && IDENTIFIER_OPNAME_P (DECL_NAME (r))
12015 		 && !grok_op_properties (r, /*complain=*/true))
12016 	  RETURN (error_mark_node);
12017 
12018 	if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
12019 	  SET_DECL_FRIEND_CONTEXT (r,
12020 				   tsubst (DECL_FRIEND_CONTEXT (t),
12021 					    args, complain, in_decl));
12022 
12023 	/* Possibly limit visibility based on template args.  */
12024 	DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
12025 	if (DECL_VISIBILITY_SPECIFIED (t))
12026 	  {
12027 	    DECL_VISIBILITY_SPECIFIED (r) = 0;
12028 	    DECL_ATTRIBUTES (r)
12029 	      = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
12030 	  }
12031 	determine_visibility (r);
12032 	if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
12033 	    && !processing_template_decl)
12034 	  defaulted_late_check (r);
12035 
12036 	apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
12037 					args, complain, in_decl);
12038       }
12039       break;
12040 
12041     case PARM_DECL:
12042       {
12043 	tree type = NULL_TREE;
12044         int i, len = 1;
12045         tree expanded_types = NULL_TREE;
12046         tree prev_r = NULL_TREE;
12047         tree first_r = NULL_TREE;
12048 
12049         if (DECL_PACK_P (t))
12050           {
12051             /* If there is a local specialization that isn't a
12052                parameter pack, it means that we're doing a "simple"
12053                substitution from inside tsubst_pack_expansion. Just
12054                return the local specialization (which will be a single
12055                parm).  */
12056             tree spec = retrieve_local_specialization (t);
12057             if (spec
12058                 && TREE_CODE (spec) == PARM_DECL
12059                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
12060               RETURN (spec);
12061 
12062             /* Expand the TYPE_PACK_EXPANSION that provides the types for
12063                the parameters in this function parameter pack.  */
12064             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
12065 						    complain, in_decl);
12066             if (TREE_CODE (expanded_types) == TREE_VEC)
12067               {
12068                 len = TREE_VEC_LENGTH (expanded_types);
12069 
12070                 /* Zero-length parameter packs are boring. Just substitute
12071                    into the chain.  */
12072                 if (len == 0)
12073                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
12074 				  TREE_CHAIN (t)));
12075               }
12076             else
12077               {
12078                 /* All we did was update the type. Make a note of that.  */
12079                 type = expanded_types;
12080                 expanded_types = NULL_TREE;
12081               }
12082           }
12083 
12084         /* Loop through all of the parameters we'll build. When T is
12085            a function parameter pack, LEN is the number of expanded
12086            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
12087         r = NULL_TREE;
12088         for (i = 0; i < len; ++i)
12089           {
12090             prev_r = r;
12091             r = copy_node (t);
12092             if (DECL_TEMPLATE_PARM_P (t))
12093               SET_DECL_TEMPLATE_PARM_P (r);
12094 
12095             if (expanded_types)
12096               /* We're on the Ith parameter of the function parameter
12097                  pack.  */
12098               {
12099                 /* Get the Ith type.  */
12100                 type = TREE_VEC_ELT (expanded_types, i);
12101 
12102 		/* Rename the parameter to include the index.  */
12103 		DECL_NAME (r)
12104 		  = make_ith_pack_parameter_name (DECL_NAME (r), i);
12105               }
12106             else if (!type)
12107               /* We're dealing with a normal parameter.  */
12108               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12109 
12110             type = type_decays_to (type);
12111             TREE_TYPE (r) = type;
12112             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
12113 
12114             if (DECL_INITIAL (r))
12115               {
12116                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
12117                   DECL_INITIAL (r) = TREE_TYPE (r);
12118                 else
12119                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
12120                                              complain, in_decl);
12121               }
12122 
12123             DECL_CONTEXT (r) = NULL_TREE;
12124 
12125             if (!DECL_TEMPLATE_PARM_P (r))
12126               DECL_ARG_TYPE (r) = type_passed_as (type);
12127 
12128 	    apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
12129 					    args, complain, in_decl);
12130 
12131             /* Keep track of the first new parameter we
12132                generate. That's what will be returned to the
12133                caller.  */
12134             if (!first_r)
12135               first_r = r;
12136 
12137             /* Build a proper chain of parameters when substituting
12138                into a function parameter pack.  */
12139             if (prev_r)
12140               DECL_CHAIN (prev_r) = r;
12141           }
12142 
12143 	/* If cp_unevaluated_operand is set, we're just looking for a
12144 	   single dummy parameter, so don't keep going.  */
12145 	if (DECL_CHAIN (t) && !cp_unevaluated_operand)
12146 	  DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
12147 				   complain, DECL_CHAIN (t));
12148 
12149         /* FIRST_R contains the start of the chain we've built.  */
12150         r = first_r;
12151       }
12152       break;
12153 
12154     case FIELD_DECL:
12155       {
12156 	tree type = NULL_TREE;
12157 	tree vec = NULL_TREE;
12158 	tree expanded_types = NULL_TREE;
12159 	int len = 1;
12160 
12161 	if (PACK_EXPANSION_P (TREE_TYPE (t)))
12162 	  {
12163 	    /* This field is a lambda capture pack.  Return a TREE_VEC of
12164 	       the expanded fields to instantiate_class_template_1 and
12165 	       store them in the specializations hash table as a
12166 	       NONTYPE_ARGUMENT_PACK so that tsubst_copy can find them.  */
12167             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
12168 						    complain, in_decl);
12169             if (TREE_CODE (expanded_types) == TREE_VEC)
12170               {
12171                 len = TREE_VEC_LENGTH (expanded_types);
12172 		vec = make_tree_vec (len);
12173               }
12174             else
12175               {
12176                 /* All we did was update the type. Make a note of that.  */
12177                 type = expanded_types;
12178                 expanded_types = NULL_TREE;
12179               }
12180 	  }
12181 
12182 	for (int i = 0; i < len; ++i)
12183 	  {
12184 	    r = copy_decl (t);
12185 	    if (expanded_types)
12186 	      {
12187 		type = TREE_VEC_ELT (expanded_types, i);
12188 		DECL_NAME (r)
12189 		  = make_ith_pack_parameter_name (DECL_NAME (r), i);
12190 	      }
12191             else if (!type)
12192               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12193 
12194 	    if (type == error_mark_node)
12195 	      RETURN (error_mark_node);
12196 	    TREE_TYPE (r) = type;
12197 	    cp_apply_type_quals_to_decl (cp_type_quals (type), r);
12198 
12199 	    if (DECL_C_BIT_FIELD (r))
12200 	      /* For bit-fields, DECL_INITIAL gives the number of bits.  For
12201 		 non-bit-fields DECL_INITIAL is a non-static data member
12202 		 initializer, which gets deferred instantiation.  */
12203 	      DECL_INITIAL (r)
12204 		= tsubst_expr (DECL_INITIAL (t), args,
12205 			       complain, in_decl,
12206 			       /*integral_constant_expression_p=*/true);
12207 	    else if (DECL_INITIAL (t))
12208 	      {
12209 		/* Set up DECL_TEMPLATE_INFO so that we can get at the
12210 		   NSDMI in perform_member_init.  Still set DECL_INITIAL
12211 		   so that we know there is one.  */
12212 		DECL_INITIAL (r) = void_node;
12213 		gcc_assert (DECL_LANG_SPECIFIC (r) == NULL);
12214 		retrofit_lang_decl (r);
12215 		DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
12216 	      }
12217 	    /* We don't have to set DECL_CONTEXT here; it is set by
12218 	       finish_member_declaration.  */
12219 	    DECL_CHAIN (r) = NULL_TREE;
12220 
12221 	    apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
12222 					    args, complain, in_decl);
12223 
12224 	    if (vec)
12225 	      TREE_VEC_ELT (vec, i) = r;
12226 	  }
12227 
12228 	if (vec)
12229 	  {
12230 	    r = vec;
12231 	    tree pack = make_node (NONTYPE_ARGUMENT_PACK);
12232 	    tree tpack = cxx_make_type (TYPE_ARGUMENT_PACK);
12233 	    SET_ARGUMENT_PACK_ARGS (pack, vec);
12234 	    SET_ARGUMENT_PACK_ARGS (tpack, expanded_types);
12235 	    TREE_TYPE (pack) = tpack;
12236 	    register_specialization (pack, t, args, false, 0);
12237 	  }
12238       }
12239       break;
12240 
12241     case USING_DECL:
12242       /* We reach here only for member using decls.  We also need to check
12243 	 uses_template_parms because DECL_DEPENDENT_P is not set for a
12244 	 using-declaration that designates a member of the current
12245 	 instantiation (c++/53549).  */
12246       if (DECL_DEPENDENT_P (t)
12247 	  || uses_template_parms (USING_DECL_SCOPE (t)))
12248 	{
12249 	  tree inst_scope = tsubst_copy (USING_DECL_SCOPE (t), args,
12250 					 complain, in_decl);
12251 	  tree name = tsubst_copy (DECL_NAME (t), args, complain, in_decl);
12252 	  r = do_class_using_decl (inst_scope, name);
12253 	  if (!r)
12254 	    r = error_mark_node;
12255 	  else
12256 	    {
12257 	      TREE_PROTECTED (r) = TREE_PROTECTED (t);
12258 	      TREE_PRIVATE (r) = TREE_PRIVATE (t);
12259 	    }
12260 	}
12261       else
12262 	{
12263 	  r = copy_node (t);
12264 	  DECL_CHAIN (r) = NULL_TREE;
12265 	}
12266       break;
12267 
12268     case TYPE_DECL:
12269     case VAR_DECL:
12270       {
12271 	tree argvec = NULL_TREE;
12272 	tree gen_tmpl = NULL_TREE;
12273 	tree spec;
12274 	tree tmpl = NULL_TREE;
12275 	tree ctx;
12276 	tree type = NULL_TREE;
12277 	bool local_p;
12278 
12279 	if (TREE_TYPE (t) == error_mark_node)
12280 	  RETURN (error_mark_node);
12281 
12282 	if (TREE_CODE (t) == TYPE_DECL
12283 	    && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
12284 	  {
12285 	    /* If this is the canonical decl, we don't have to
12286 	       mess with instantiations, and often we can't (for
12287 	       typename, template type parms and such).  Note that
12288 	       TYPE_NAME is not correct for the above test if
12289 	       we've copied the type for a typedef.  */
12290 	    type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12291 	    if (type == error_mark_node)
12292 	      RETURN (error_mark_node);
12293 	    r = TYPE_NAME (type);
12294 	    break;
12295 	  }
12296 
12297 	/* Check to see if we already have the specialization we
12298 	   need.  */
12299 	spec = NULL_TREE;
12300 	if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
12301 	  {
12302 	    /* T is a static data member or namespace-scope entity.
12303 	       We have to substitute into namespace-scope variables
12304 	       (not just variable templates) because of cases like:
12305 
12306 	         template <class T> void f() { extern T t; }
12307 
12308 	       where the entity referenced is not known until
12309 	       instantiation time.  */
12310 	    local_p = false;
12311 	    ctx = DECL_CONTEXT (t);
12312 	    if (DECL_CLASS_SCOPE_P (t))
12313 	      {
12314 		ctx = tsubst_aggr_type (ctx, args,
12315 					complain,
12316 					in_decl, /*entering_scope=*/1);
12317 		/* If CTX is unchanged, then T is in fact the
12318 		   specialization we want.  That situation occurs when
12319 		   referencing a static data member within in its own
12320 		   class.  We can use pointer equality, rather than
12321 		   same_type_p, because DECL_CONTEXT is always
12322 		   canonical...  */
12323 		if (ctx == DECL_CONTEXT (t)
12324 		    /* ... unless T is a member template; in which
12325 		       case our caller can be willing to create a
12326 		       specialization of that template represented
12327 		       by T.  */
12328 		    && !(DECL_TI_TEMPLATE (t)
12329 			 && DECL_MEMBER_TEMPLATE_P (DECL_TI_TEMPLATE (t))))
12330 		  spec = t;
12331 	      }
12332 
12333 	    if (!spec)
12334 	      {
12335 		tmpl = DECL_TI_TEMPLATE (t);
12336 		gen_tmpl = most_general_template (tmpl);
12337 		argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
12338 		if (argvec != error_mark_node)
12339 		  argvec = (coerce_innermost_template_parms
12340 			    (DECL_TEMPLATE_PARMS (gen_tmpl),
12341 			     argvec, t, complain,
12342 			     /*all*/true, /*defarg*/true));
12343 		if (argvec == error_mark_node)
12344 		  RETURN (error_mark_node);
12345 		hash = hash_tmpl_and_args (gen_tmpl, argvec);
12346 		spec = retrieve_specialization (gen_tmpl, argvec, hash);
12347 	      }
12348 	  }
12349 	else
12350 	  {
12351 	    /* A local variable.  */
12352 	    local_p = true;
12353 	    /* Subsequent calls to pushdecl will fill this in.  */
12354 	    ctx = NULL_TREE;
12355 	    /* Unless this is a reference to a static variable from an
12356 	       enclosing function, in which case we need to fill it in now.  */
12357 	    if (TREE_STATIC (t))
12358 	      {
12359 		tree fn = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
12360 		if (fn != current_function_decl)
12361 		  ctx = fn;
12362 	      }
12363 	    spec = retrieve_local_specialization (t);
12364 	  }
12365 	/* If we already have the specialization we need, there is
12366 	   nothing more to do.  */
12367 	if (spec)
12368 	  {
12369 	    r = spec;
12370 	    break;
12371 	  }
12372 
12373 	/* Create a new node for the specialization we need.  */
12374 	r = copy_decl (t);
12375 	if (type == NULL_TREE)
12376 	  {
12377 	    if (is_typedef_decl (t))
12378 	      type = DECL_ORIGINAL_TYPE (t);
12379 	    else
12380 	      type = TREE_TYPE (t);
12381 	    if (VAR_P (t)
12382 		&& VAR_HAD_UNKNOWN_BOUND (t)
12383 		&& type != error_mark_node)
12384 	      type = strip_array_domain (type);
12385 	    type = tsubst (type, args, complain, in_decl);
12386 	  }
12387 	if (VAR_P (r))
12388 	  {
12389 	    /* Even if the original location is out of scope, the
12390 	       newly substituted one is not.  */
12391 	    DECL_DEAD_FOR_LOCAL (r) = 0;
12392 	    DECL_INITIALIZED_P (r) = 0;
12393 	    DECL_TEMPLATE_INSTANTIATED (r) = 0;
12394 	    if (type == error_mark_node)
12395 	      RETURN (error_mark_node);
12396 	    if (TREE_CODE (type) == FUNCTION_TYPE)
12397 	      {
12398 		/* It may seem that this case cannot occur, since:
12399 
12400 		   typedef void f();
12401 		   void g() { f x; }
12402 
12403 		   declares a function, not a variable.  However:
12404 
12405 		   typedef void f();
12406 		   template <typename T> void g() { T t; }
12407 		   template void g<f>();
12408 
12409 		   is an attempt to declare a variable with function
12410 		   type.  */
12411 		error ("variable %qD has function type",
12412 		       /* R is not yet sufficiently initialized, so we
12413 			  just use its name.  */
12414 		       DECL_NAME (r));
12415 		RETURN (error_mark_node);
12416 	      }
12417 	    type = complete_type (type);
12418 	    /* Wait until cp_finish_decl to set this again, to handle
12419 	       circular dependency (template/instantiate6.C). */
12420 	    DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
12421 	    type = check_var_type (DECL_NAME (r), type);
12422 
12423 	    if (DECL_HAS_VALUE_EXPR_P (t))
12424 	      {
12425 		tree ve = DECL_VALUE_EXPR (t);
12426 		ve = tsubst_expr (ve, args, complain, in_decl,
12427 				  /*constant_expression_p=*/false);
12428 		if (REFERENCE_REF_P (ve))
12429 		  {
12430 		    gcc_assert (TREE_CODE (type) == REFERENCE_TYPE);
12431 		    ve = TREE_OPERAND (ve, 0);
12432 		  }
12433 		SET_DECL_VALUE_EXPR (r, ve);
12434 	      }
12435 	    if (CP_DECL_THREAD_LOCAL_P (r)
12436 		&& !processing_template_decl)
12437 	      set_decl_tls_model (r, decl_default_tls_model (r));
12438 	  }
12439 	else if (DECL_SELF_REFERENCE_P (t))
12440 	  SET_DECL_SELF_REFERENCE_P (r);
12441 	TREE_TYPE (r) = type;
12442 	cp_apply_type_quals_to_decl (cp_type_quals (type), r);
12443 	DECL_CONTEXT (r) = ctx;
12444 	/* Clear out the mangled name and RTL for the instantiation.  */
12445 	SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
12446 	if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
12447 	  SET_DECL_RTL (r, NULL);
12448 	/* The initializer must not be expanded until it is required;
12449 	   see [temp.inst].  */
12450 	DECL_INITIAL (r) = NULL_TREE;
12451 	if (VAR_P (r))
12452 	  DECL_MODE (r) = VOIDmode;
12453 	if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
12454 	  SET_DECL_RTL (r, NULL);
12455 	DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
12456 	if (VAR_P (r))
12457 	  {
12458 	    /* Possibly limit visibility based on template args.  */
12459 	    DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
12460 	    if (DECL_VISIBILITY_SPECIFIED (t))
12461 	      {
12462 		DECL_VISIBILITY_SPECIFIED (r) = 0;
12463 		DECL_ATTRIBUTES (r)
12464 		  = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
12465 	      }
12466 	    determine_visibility (r);
12467 	  }
12468 
12469 	if (!local_p)
12470 	  {
12471 	    /* A static data member declaration is always marked
12472 	       external when it is declared in-class, even if an
12473 	       initializer is present.  We mimic the non-template
12474 	       processing here.  */
12475 	    DECL_EXTERNAL (r) = 1;
12476 	    if (DECL_NAMESPACE_SCOPE_P (t))
12477 	      DECL_NOT_REALLY_EXTERN (r) = 1;
12478 
12479 	    DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
12480 	    SET_DECL_IMPLICIT_INSTANTIATION (r);
12481 	    register_specialization (r, gen_tmpl, argvec, false, hash);
12482 	  }
12483 	else
12484 	  {
12485 	    if (DECL_LANG_SPECIFIC (r))
12486 	      DECL_TEMPLATE_INFO (r) = NULL_TREE;
12487 	    if (!cp_unevaluated_operand)
12488 	      register_local_specialization (r, t);
12489 	  }
12490 
12491 	DECL_CHAIN (r) = NULL_TREE;
12492 
12493 	apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
12494 					/*flags=*/0,
12495 					args, complain, in_decl);
12496 
12497 	/* Preserve a typedef that names a type.  */
12498 	if (is_typedef_decl (r))
12499 	  {
12500 	    DECL_ORIGINAL_TYPE (r) = NULL_TREE;
12501 	    set_underlying_type (r);
12502 	    if (TYPE_DECL_ALIAS_P (r) && type != error_mark_node)
12503 	      /* An alias template specialization can be dependent
12504 		 even if its underlying type is not.  */
12505 	      TYPE_DEPENDENT_P_VALID (TREE_TYPE (r)) = false;
12506 	  }
12507 
12508 	layout_decl (r, 0);
12509       }
12510       break;
12511 
12512     default:
12513       gcc_unreachable ();
12514     }
12515 #undef RETURN
12516 
12517  out:
12518   /* Restore the file and line information.  */
12519   input_location = saved_loc;
12520 
12521   return r;
12522 }
12523 
12524 /* Substitute into the ARG_TYPES of a function type.
12525    If END is a TREE_CHAIN, leave it and any following types
12526    un-substituted.  */
12527 
12528 static tree
tsubst_arg_types(tree arg_types,tree args,tree end,tsubst_flags_t complain,tree in_decl)12529 tsubst_arg_types (tree arg_types,
12530 		  tree args,
12531 		  tree end,
12532 		  tsubst_flags_t complain,
12533 		  tree in_decl)
12534 {
12535   tree remaining_arg_types;
12536   tree type = NULL_TREE;
12537   int i = 1;
12538   tree expanded_args = NULL_TREE;
12539   tree default_arg;
12540 
12541   if (!arg_types || arg_types == void_list_node || arg_types == end)
12542     return arg_types;
12543 
12544   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
12545 					  args, end, complain, in_decl);
12546   if (remaining_arg_types == error_mark_node)
12547     return error_mark_node;
12548 
12549   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
12550     {
12551       /* For a pack expansion, perform substitution on the
12552          entire expression. Later on, we'll handle the arguments
12553          one-by-one.  */
12554       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
12555                                             args, complain, in_decl);
12556 
12557       if (TREE_CODE (expanded_args) == TREE_VEC)
12558         /* So that we'll spin through the parameters, one by one.  */
12559         i = TREE_VEC_LENGTH (expanded_args);
12560       else
12561         {
12562           /* We only partially substituted into the parameter
12563              pack. Our type is TYPE_PACK_EXPANSION.  */
12564           type = expanded_args;
12565           expanded_args = NULL_TREE;
12566         }
12567     }
12568 
12569   while (i > 0) {
12570     --i;
12571 
12572     if (expanded_args)
12573       type = TREE_VEC_ELT (expanded_args, i);
12574     else if (!type)
12575       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
12576 
12577     if (type == error_mark_node)
12578       return error_mark_node;
12579     if (VOID_TYPE_P (type))
12580       {
12581         if (complain & tf_error)
12582           {
12583             error ("invalid parameter type %qT", type);
12584             if (in_decl)
12585               error ("in declaration %q+D", in_decl);
12586           }
12587         return error_mark_node;
12588     }
12589     /* DR 657. */
12590     if (abstract_virtuals_error_sfinae (ACU_PARM, type, complain))
12591       return error_mark_node;
12592 
12593     /* Do array-to-pointer, function-to-pointer conversion, and ignore
12594        top-level qualifiers as required.  */
12595     type = cv_unqualified (type_decays_to (type));
12596 
12597     /* We do not substitute into default arguments here.  The standard
12598        mandates that they be instantiated only when needed, which is
12599        done in build_over_call.  */
12600     default_arg = TREE_PURPOSE (arg_types);
12601 
12602     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
12603       {
12604         /* We've instantiated a template before its default arguments
12605            have been parsed.  This can happen for a nested template
12606            class, and is not an error unless we require the default
12607            argument in a call of this function.  */
12608         remaining_arg_types =
12609           tree_cons (default_arg, type, remaining_arg_types);
12610         vec_safe_push (DEFARG_INSTANTIATIONS(default_arg), remaining_arg_types);
12611       }
12612     else
12613       remaining_arg_types =
12614         hash_tree_cons (default_arg, type, remaining_arg_types);
12615   }
12616 
12617   return remaining_arg_types;
12618 }
12619 
12620 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
12621    *not* handle the exception-specification for FNTYPE, because the
12622    initial substitution of explicitly provided template parameters
12623    during argument deduction forbids substitution into the
12624    exception-specification:
12625 
12626      [temp.deduct]
12627 
12628      All references in the function type of the function template to  the
12629      corresponding template parameters are replaced by the specified tem-
12630      plate argument values.  If a substitution in a template parameter or
12631      in  the function type of the function template results in an invalid
12632      type, type deduction fails.  [Note: The equivalent  substitution  in
12633      exception specifications is done only when the function is instanti-
12634      ated, at which point a program is  ill-formed  if  the  substitution
12635      results in an invalid type.]  */
12636 
12637 static tree
tsubst_function_type(tree t,tree args,tsubst_flags_t complain,tree in_decl)12638 tsubst_function_type (tree t,
12639 		      tree args,
12640 		      tsubst_flags_t complain,
12641 		      tree in_decl)
12642 {
12643   tree return_type;
12644   tree arg_types = NULL_TREE;
12645   tree fntype;
12646 
12647   /* The TYPE_CONTEXT is not used for function/method types.  */
12648   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
12649 
12650   /* DR 1227: Mixing immediate and non-immediate contexts in deduction
12651      failure.  */
12652   bool late_return_type_p = TYPE_HAS_LATE_RETURN_TYPE (t);
12653 
12654   if (late_return_type_p)
12655     {
12656       /* Substitute the argument types.  */
12657       arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
12658 				    complain, in_decl);
12659       if (arg_types == error_mark_node)
12660 	return error_mark_node;
12661 
12662       tree save_ccp = current_class_ptr;
12663       tree save_ccr = current_class_ref;
12664       tree this_type = (TREE_CODE (t) == METHOD_TYPE
12665 			? TREE_TYPE (TREE_VALUE (arg_types)) : NULL_TREE);
12666       bool do_inject = this_type && CLASS_TYPE_P (this_type);
12667       if (do_inject)
12668 	{
12669 	  /* DR 1207: 'this' is in scope in the trailing return type.  */
12670 	  inject_this_parameter (this_type, cp_type_quals (this_type));
12671 	}
12672 
12673       /* Substitute the return type.  */
12674       return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12675 
12676       if (do_inject)
12677 	{
12678 	  current_class_ptr = save_ccp;
12679 	  current_class_ref = save_ccr;
12680 	}
12681     }
12682   else
12683     /* Substitute the return type.  */
12684     return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12685 
12686   if (return_type == error_mark_node)
12687     return error_mark_node;
12688   /* DR 486 clarifies that creation of a function type with an
12689      invalid return type is a deduction failure.  */
12690   if (TREE_CODE (return_type) == ARRAY_TYPE
12691       || TREE_CODE (return_type) == FUNCTION_TYPE)
12692     {
12693       if (complain & tf_error)
12694 	{
12695 	  if (TREE_CODE (return_type) == ARRAY_TYPE)
12696 	    error ("function returning an array");
12697 	  else
12698 	    error ("function returning a function");
12699 	}
12700       return error_mark_node;
12701     }
12702   /* And DR 657. */
12703   if (abstract_virtuals_error_sfinae (ACU_RETURN, return_type, complain))
12704     return error_mark_node;
12705 
12706   if (!late_return_type_p)
12707     {
12708       /* Substitute the argument types.  */
12709       arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args, NULL_TREE,
12710 				    complain, in_decl);
12711       if (arg_types == error_mark_node)
12712 	return error_mark_node;
12713     }
12714 
12715   /* Construct a new type node and return it.  */
12716   if (TREE_CODE (t) == FUNCTION_TYPE)
12717     {
12718       fntype = build_function_type (return_type, arg_types);
12719       fntype = apply_memfn_quals (fntype,
12720 				  type_memfn_quals (t),
12721 				  type_memfn_rqual (t));
12722     }
12723   else
12724     {
12725       tree r = TREE_TYPE (TREE_VALUE (arg_types));
12726       /* Don't pick up extra function qualifiers from the basetype.  */
12727       r = cp_build_qualified_type_real (r, type_memfn_quals (t), complain);
12728       if (! MAYBE_CLASS_TYPE_P (r))
12729 	{
12730 	  /* [temp.deduct]
12731 
12732 	     Type deduction may fail for any of the following
12733 	     reasons:
12734 
12735 	     -- Attempting to create "pointer to member of T" when T
12736 	     is not a class type.  */
12737 	  if (complain & tf_error)
12738 	    error ("creating pointer to member function of non-class type %qT",
12739 		      r);
12740 	  return error_mark_node;
12741 	}
12742 
12743       fntype = build_method_type_directly (r, return_type,
12744 					   TREE_CHAIN (arg_types));
12745       fntype = build_ref_qualified_type (fntype, type_memfn_rqual (t));
12746     }
12747   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
12748 
12749   if (late_return_type_p)
12750     TYPE_HAS_LATE_RETURN_TYPE (fntype) = 1;
12751 
12752   return fntype;
12753 }
12754 
12755 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
12756    ARGS into that specification, and return the substituted
12757    specification.  If there is no specification, return NULL_TREE.  */
12758 
12759 static tree
tsubst_exception_specification(tree fntype,tree args,tsubst_flags_t complain,tree in_decl,bool defer_ok)12760 tsubst_exception_specification (tree fntype,
12761 				tree args,
12762 				tsubst_flags_t complain,
12763 				tree in_decl,
12764 				bool defer_ok)
12765 {
12766   tree specs;
12767   tree new_specs;
12768 
12769   specs = TYPE_RAISES_EXCEPTIONS (fntype);
12770   new_specs = NULL_TREE;
12771   if (specs && TREE_PURPOSE (specs))
12772     {
12773       /* A noexcept-specifier.  */
12774       tree expr = TREE_PURPOSE (specs);
12775       if (TREE_CODE (expr) == INTEGER_CST)
12776 	new_specs = expr;
12777       else if (defer_ok)
12778 	{
12779 	  /* Defer instantiation of noexcept-specifiers to avoid
12780 	     excessive instantiations (c++/49107).  */
12781 	  new_specs = make_node (DEFERRED_NOEXCEPT);
12782 	  if (DEFERRED_NOEXCEPT_SPEC_P (specs))
12783 	    {
12784 	      /* We already partially instantiated this member template,
12785 		 so combine the new args with the old.  */
12786 	      DEFERRED_NOEXCEPT_PATTERN (new_specs)
12787 		= DEFERRED_NOEXCEPT_PATTERN (expr);
12788 	      DEFERRED_NOEXCEPT_ARGS (new_specs)
12789 		= add_to_template_args (DEFERRED_NOEXCEPT_ARGS (expr), args);
12790 	    }
12791 	  else
12792 	    {
12793 	      DEFERRED_NOEXCEPT_PATTERN (new_specs) = expr;
12794 	      DEFERRED_NOEXCEPT_ARGS (new_specs) = args;
12795 	    }
12796 	}
12797       else
12798 	new_specs = tsubst_copy_and_build
12799 	  (expr, args, complain, in_decl, /*function_p=*/false,
12800 	   /*integral_constant_expression_p=*/true);
12801       new_specs = build_noexcept_spec (new_specs, complain);
12802     }
12803   else if (specs)
12804     {
12805       if (! TREE_VALUE (specs))
12806 	new_specs = specs;
12807       else
12808 	while (specs)
12809 	  {
12810 	    tree spec;
12811             int i, len = 1;
12812             tree expanded_specs = NULL_TREE;
12813 
12814             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
12815               {
12816                 /* Expand the pack expansion type.  */
12817                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
12818                                                        args, complain,
12819                                                        in_decl);
12820 
12821 		if (expanded_specs == error_mark_node)
12822 		  return error_mark_node;
12823 		else if (TREE_CODE (expanded_specs) == TREE_VEC)
12824 		  len = TREE_VEC_LENGTH (expanded_specs);
12825 		else
12826 		  {
12827 		    /* We're substituting into a member template, so
12828 		       we got a TYPE_PACK_EXPANSION back.  Add that
12829 		       expansion and move on.  */
12830 		    gcc_assert (TREE_CODE (expanded_specs)
12831 				== TYPE_PACK_EXPANSION);
12832 		    new_specs = add_exception_specifier (new_specs,
12833 							 expanded_specs,
12834 							 complain);
12835 		    specs = TREE_CHAIN (specs);
12836 		    continue;
12837 		  }
12838               }
12839 
12840             for (i = 0; i < len; ++i)
12841               {
12842                 if (expanded_specs)
12843                   spec = TREE_VEC_ELT (expanded_specs, i);
12844                 else
12845                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
12846                 if (spec == error_mark_node)
12847                   return spec;
12848                 new_specs = add_exception_specifier (new_specs, spec,
12849                                                      complain);
12850               }
12851 
12852             specs = TREE_CHAIN (specs);
12853 	  }
12854     }
12855   return new_specs;
12856 }
12857 
12858 /* Take the tree structure T and replace template parameters used
12859    therein with the argument vector ARGS.  IN_DECL is an associated
12860    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
12861    Issue error and warning messages under control of COMPLAIN.  Note
12862    that we must be relatively non-tolerant of extensions here, in
12863    order to preserve conformance; if we allow substitutions that
12864    should not be allowed, we may allow argument deductions that should
12865    not succeed, and therefore report ambiguous overload situations
12866    where there are none.  In theory, we could allow the substitution,
12867    but indicate that it should have failed, and allow our caller to
12868    make sure that the right thing happens, but we don't try to do this
12869    yet.
12870 
12871    This function is used for dealing with types, decls and the like;
12872    for expressions, use tsubst_expr or tsubst_copy.  */
12873 
12874 tree
tsubst(tree t,tree args,tsubst_flags_t complain,tree in_decl)12875 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
12876 {
12877   enum tree_code code;
12878   tree type, r = NULL_TREE;
12879 
12880   if (t == NULL_TREE || t == error_mark_node
12881       || t == integer_type_node
12882       || t == void_type_node
12883       || t == char_type_node
12884       || t == unknown_type_node
12885       || TREE_CODE (t) == NAMESPACE_DECL
12886       || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
12887     return t;
12888 
12889   if (DECL_P (t))
12890     return tsubst_decl (t, args, complain);
12891 
12892   if (args == NULL_TREE)
12893     return t;
12894 
12895   code = TREE_CODE (t);
12896 
12897   if (code == IDENTIFIER_NODE)
12898     type = IDENTIFIER_TYPE_VALUE (t);
12899   else
12900     type = TREE_TYPE (t);
12901 
12902   gcc_assert (type != unknown_type_node);
12903 
12904   /* Reuse typedefs.  We need to do this to handle dependent attributes,
12905      such as attribute aligned.  */
12906   if (TYPE_P (t)
12907       && typedef_variant_p (t))
12908     {
12909       tree decl = TYPE_NAME (t);
12910 
12911       if (alias_template_specialization_p (t))
12912 	{
12913 	  /* DECL represents an alias template and we want to
12914 	     instantiate it.  */
12915 	  tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
12916 	  tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
12917 	  r = instantiate_alias_template (tmpl, gen_args, complain);
12918 	}
12919       else if (DECL_CLASS_SCOPE_P (decl)
12920 	       && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
12921 	       && uses_template_parms (DECL_CONTEXT (decl)))
12922 	{
12923 	  tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
12924 	  tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
12925 	  r = retrieve_specialization (tmpl, gen_args, 0);
12926 	}
12927       else if (DECL_FUNCTION_SCOPE_P (decl)
12928 	       && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
12929 	       && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
12930 	r = retrieve_local_specialization (decl);
12931       else
12932 	/* The typedef is from a non-template context.  */
12933 	return t;
12934 
12935       if (r)
12936 	{
12937 	  r = TREE_TYPE (r);
12938 	  r = cp_build_qualified_type_real
12939 	    (r, cp_type_quals (t) | cp_type_quals (r),
12940 	     complain | tf_ignore_bad_quals);
12941 	  return r;
12942 	}
12943       else
12944 	{
12945 	  /* We don't have an instantiation yet, so drop the typedef.  */
12946 	  int quals = cp_type_quals (t);
12947 	  t = DECL_ORIGINAL_TYPE (decl);
12948 	  t = cp_build_qualified_type_real (t, quals,
12949 					    complain | tf_ignore_bad_quals);
12950 	}
12951     }
12952 
12953   if (type
12954       && code != TYPENAME_TYPE
12955       && code != TEMPLATE_TYPE_PARM
12956       && code != IDENTIFIER_NODE
12957       && code != FUNCTION_TYPE
12958       && code != METHOD_TYPE)
12959     type = tsubst (type, args, complain, in_decl);
12960   if (type == error_mark_node)
12961     return error_mark_node;
12962 
12963   switch (code)
12964     {
12965     case RECORD_TYPE:
12966     case UNION_TYPE:
12967     case ENUMERAL_TYPE:
12968       return tsubst_aggr_type (t, args, complain, in_decl,
12969 			       /*entering_scope=*/0);
12970 
12971     case ERROR_MARK:
12972     case IDENTIFIER_NODE:
12973     case VOID_TYPE:
12974     case REAL_TYPE:
12975     case COMPLEX_TYPE:
12976     case VECTOR_TYPE:
12977     case BOOLEAN_TYPE:
12978     case NULLPTR_TYPE:
12979     case LANG_TYPE:
12980       return t;
12981 
12982     case INTEGER_TYPE:
12983       if (t == integer_type_node)
12984 	return t;
12985 
12986       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
12987           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
12988         return t;
12989 
12990       {
12991 	tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
12992 
12993 	max = tsubst_expr (omax, args, complain, in_decl,
12994 			   /*integral_constant_expression_p=*/false);
12995 
12996 	/* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
12997 	   needed.  */
12998 	if (TREE_CODE (max) == NOP_EXPR
12999 	    && TREE_SIDE_EFFECTS (omax)
13000 	    && !TREE_TYPE (max))
13001 	  TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
13002 
13003 	/* If we're in a partial instantiation, preserve the magic NOP_EXPR
13004 	   with TREE_SIDE_EFFECTS that indicates this is not an integral
13005 	   constant expression.  */
13006 	if (processing_template_decl
13007 	    && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
13008 	  {
13009 	    gcc_assert (TREE_CODE (max) == NOP_EXPR);
13010 	    TREE_SIDE_EFFECTS (max) = 1;
13011 	  }
13012 
13013 	return compute_array_index_type (NULL_TREE, max, complain);
13014       }
13015 
13016     case TEMPLATE_TYPE_PARM:
13017     case TEMPLATE_TEMPLATE_PARM:
13018     case BOUND_TEMPLATE_TEMPLATE_PARM:
13019     case TEMPLATE_PARM_INDEX:
13020       {
13021 	int idx;
13022 	int level;
13023 	int levels;
13024 	tree arg = NULL_TREE;
13025 
13026 	/* Early in template argument deduction substitution, we don't
13027 	   want to reduce the level of 'auto', or it will be confused
13028 	   with a normal template parm in subsequent deduction.  */
13029 	if (is_auto (t) && (complain & tf_partial))
13030 	  return t;
13031 
13032 	r = NULL_TREE;
13033 
13034 	gcc_assert (TREE_VEC_LENGTH (args) > 0);
13035 	template_parm_level_and_index (t, &level, &idx);
13036 
13037 	levels = TMPL_ARGS_DEPTH (args);
13038 	if (level <= levels
13039 	    && TREE_VEC_LENGTH (TMPL_ARGS_LEVEL (args, level)) > 0)
13040 	  {
13041 	    arg = TMPL_ARG (args, level, idx);
13042 
13043 	    if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
13044 	      {
13045 		/* See through ARGUMENT_PACK_SELECT arguments. */
13046 		arg = ARGUMENT_PACK_SELECT_ARG (arg);
13047 		/* If the selected argument is an expansion E, that most
13048 		   likely means we were called from
13049 		   gen_elem_of_pack_expansion_instantiation during the
13050 		   substituting of pack an argument pack (which Ith
13051 		   element is a pack expansion, where I is
13052 		   ARGUMENT_PACK_SELECT_INDEX) into a pack expansion.
13053 		   In this case, the Ith element resulting from this
13054 		   substituting is going to be a pack expansion, which
13055 		   pattern is the pattern of E.  Let's return the
13056 		   pattern of E, and
13057 		   gen_elem_of_pack_expansion_instantiation will
13058 		   build the resulting pack expansion from it.  */
13059 		if (PACK_EXPANSION_P (arg))
13060 		  {
13061 		    /* Make sure we aren't throwing away arg info.  */
13062 		    gcc_assert (!PACK_EXPANSION_EXTRA_ARGS (arg));
13063 		    arg = PACK_EXPANSION_PATTERN (arg);
13064 		  }
13065 	      }
13066 	  }
13067 
13068 	if (arg == error_mark_node)
13069 	  return error_mark_node;
13070 	else if (arg != NULL_TREE)
13071 	  {
13072 	    if (ARGUMENT_PACK_P (arg))
13073 	      /* If ARG is an argument pack, we don't actually want to
13074 		 perform a substitution here, because substitutions
13075 		 for argument packs are only done
13076 		 element-by-element. We can get to this point when
13077 		 substituting the type of a non-type template
13078 		 parameter pack, when that type actually contains
13079 		 template parameter packs from an outer template, e.g.,
13080 
13081 	         template<typename... Types> struct A {
13082 		   template<Types... Values> struct B { };
13083                  };  */
13084 	      return t;
13085 
13086 	    if (code == TEMPLATE_TYPE_PARM)
13087 	      {
13088 		int quals;
13089 		gcc_assert (TYPE_P (arg));
13090 
13091 		quals = cp_type_quals (arg) | cp_type_quals (t);
13092 
13093 		return cp_build_qualified_type_real
13094 		  (arg, quals, complain | tf_ignore_bad_quals);
13095 	      }
13096 	    else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
13097 	      {
13098 		/* We are processing a type constructed from a
13099 		   template template parameter.  */
13100 		tree argvec = tsubst (TYPE_TI_ARGS (t),
13101 				      args, complain, in_decl);
13102 		if (argvec == error_mark_node)
13103 		  return error_mark_node;
13104 
13105 		gcc_assert (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
13106 			    || TREE_CODE (arg) == TEMPLATE_DECL
13107 			    || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
13108 
13109 		if (TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE)
13110 		  /* Consider this code:
13111 
13112 			template <template <class> class Template>
13113 			struct Internal {
13114 			template <class Arg> using Bind = Template<Arg>;
13115 			};
13116 
13117 			template <template <class> class Template, class Arg>
13118 			using Instantiate = Template<Arg>; //#0
13119 
13120 			template <template <class> class Template,
13121                                   class Argument>
13122 			using Bind =
13123 			  Instantiate<Internal<Template>::template Bind,
13124 				      Argument>; //#1
13125 
13126 		     When #1 is parsed, the
13127 		     BOUND_TEMPLATE_TEMPLATE_PARM representing the
13128 		     parameter `Template' in #0 matches the
13129 		     UNBOUND_CLASS_TEMPLATE representing the argument
13130 		     `Internal<Template>::template Bind'; We then want
13131 		     to assemble the type `Bind<Argument>' that can't
13132 		     be fully created right now, because
13133 		     `Internal<Template>' not being complete, the Bind
13134 		     template cannot be looked up in that context.  So
13135 		     we need to "store" `Bind<Argument>' for later
13136 		     when the context of Bind becomes complete.  Let's
13137 		     store that in a TYPENAME_TYPE.  */
13138 		  return make_typename_type (TYPE_CONTEXT (arg),
13139 					     build_nt (TEMPLATE_ID_EXPR,
13140 						       TYPE_IDENTIFIER (arg),
13141 						       argvec),
13142 					     typename_type,
13143 					     complain);
13144 
13145 		/* We can get a TEMPLATE_TEMPLATE_PARM here when we
13146 		   are resolving nested-types in the signature of a
13147 		   member function templates.  Otherwise ARG is a
13148 		   TEMPLATE_DECL and is the real template to be
13149 		   instantiated.  */
13150 		if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
13151 		  arg = TYPE_NAME (arg);
13152 
13153 		r = lookup_template_class (arg,
13154 					   argvec, in_decl,
13155 					   DECL_CONTEXT (arg),
13156 					    /*entering_scope=*/0,
13157 					   complain);
13158 		return cp_build_qualified_type_real
13159 		  (r, cp_type_quals (t) | cp_type_quals (r), complain);
13160 	      }
13161 	    else
13162 	      /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
13163 	      return convert_from_reference (unshare_expr (arg));
13164 	  }
13165 
13166 	if (level == 1)
13167 	  /* This can happen during the attempted tsubst'ing in
13168 	     unify.  This means that we don't yet have any information
13169 	     about the template parameter in question.  */
13170 	  return t;
13171 
13172 	/* If we get here, we must have been looking at a parm for a
13173 	   more deeply nested template.  Make a new version of this
13174 	   template parameter, but with a lower level.  */
13175 	switch (code)
13176 	  {
13177 	  case TEMPLATE_TYPE_PARM:
13178 	  case TEMPLATE_TEMPLATE_PARM:
13179 	  case BOUND_TEMPLATE_TEMPLATE_PARM:
13180 	    if (cp_type_quals (t))
13181 	      {
13182 		r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
13183 		r = cp_build_qualified_type_real
13184 		  (r, cp_type_quals (t),
13185 		   complain | (code == TEMPLATE_TYPE_PARM
13186 			       ? tf_ignore_bad_quals : 0));
13187 	      }
13188 	    else if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
13189 		     && PLACEHOLDER_TYPE_CONSTRAINTS (t)
13190 		     && (r = (TEMPLATE_PARM_DESCENDANTS
13191 			      (TEMPLATE_TYPE_PARM_INDEX (t))))
13192 		     && (r = TREE_TYPE (r))
13193 		     && !PLACEHOLDER_TYPE_CONSTRAINTS (r))
13194 	      /* Break infinite recursion when substituting the constraints
13195 		 of a constrained placeholder.  */;
13196 	    else
13197 	      {
13198 		r = copy_type (t);
13199 		TEMPLATE_TYPE_PARM_INDEX (r)
13200 		  = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
13201 						r, levels, args, complain);
13202 		TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
13203 		TYPE_MAIN_VARIANT (r) = r;
13204 		TYPE_POINTER_TO (r) = NULL_TREE;
13205 		TYPE_REFERENCE_TO (r) = NULL_TREE;
13206 
13207 		/* Propagate constraints on placeholders.  */
13208                 if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
13209                   if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (t))
13210 		    PLACEHOLDER_TYPE_CONSTRAINTS (r)
13211 		      = tsubst_constraint (constr, args, complain, in_decl);
13212 
13213 		if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
13214 		  /* We have reduced the level of the template
13215 		     template parameter, but not the levels of its
13216 		     template parameters, so canonical_type_parameter
13217 		     will not be able to find the canonical template
13218 		     template parameter for this level. Thus, we
13219 		     require structural equality checking to compare
13220 		     TEMPLATE_TEMPLATE_PARMs. */
13221 		  SET_TYPE_STRUCTURAL_EQUALITY (r);
13222 		else if (TYPE_STRUCTURAL_EQUALITY_P (t))
13223 		  SET_TYPE_STRUCTURAL_EQUALITY (r);
13224 		else
13225 		  TYPE_CANONICAL (r) = canonical_type_parameter (r);
13226 
13227 		if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
13228 		  {
13229 		    tree tinfo = TYPE_TEMPLATE_INFO (t);
13230 		    /* We might need to substitute into the types of non-type
13231 		       template parameters.  */
13232 		    tree tmpl = tsubst (TI_TEMPLATE (tinfo), args,
13233 					complain, in_decl);
13234 		    if (tmpl == error_mark_node)
13235 		      return error_mark_node;
13236 		    tree argvec = tsubst (TI_ARGS (tinfo), args,
13237 					  complain, in_decl);
13238 		    if (argvec == error_mark_node)
13239 		      return error_mark_node;
13240 
13241 		    TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
13242 		      = build_template_info (tmpl, argvec);
13243 		  }
13244 	      }
13245 	    break;
13246 
13247 	  case TEMPLATE_PARM_INDEX:
13248 	    r = reduce_template_parm_level (t, type, levels, args, complain);
13249 	    break;
13250 
13251 	  default:
13252 	    gcc_unreachable ();
13253 	  }
13254 
13255 	return r;
13256       }
13257 
13258     case TREE_LIST:
13259       {
13260 	tree purpose, value, chain;
13261 
13262 	if (t == void_list_node)
13263 	  return t;
13264 
13265 	purpose = TREE_PURPOSE (t);
13266 	if (purpose)
13267 	  {
13268 	    purpose = tsubst (purpose, args, complain, in_decl);
13269 	    if (purpose == error_mark_node)
13270 	      return error_mark_node;
13271 	  }
13272 	value = TREE_VALUE (t);
13273 	if (value)
13274 	  {
13275 	    value = tsubst (value, args, complain, in_decl);
13276 	    if (value == error_mark_node)
13277 	      return error_mark_node;
13278 	  }
13279 	chain = TREE_CHAIN (t);
13280 	if (chain && chain != void_type_node)
13281 	  {
13282 	    chain = tsubst (chain, args, complain, in_decl);
13283 	    if (chain == error_mark_node)
13284 	      return error_mark_node;
13285 	  }
13286 	if (purpose == TREE_PURPOSE (t)
13287 	    && value == TREE_VALUE (t)
13288 	    && chain == TREE_CHAIN (t))
13289 	  return t;
13290 	return hash_tree_cons (purpose, value, chain);
13291       }
13292 
13293     case TREE_BINFO:
13294       /* We should never be tsubsting a binfo.  */
13295       gcc_unreachable ();
13296 
13297     case TREE_VEC:
13298       /* A vector of template arguments.  */
13299       gcc_assert (!type);
13300       return tsubst_template_args (t, args, complain, in_decl);
13301 
13302     case POINTER_TYPE:
13303     case REFERENCE_TYPE:
13304       {
13305 	if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
13306 	  return t;
13307 
13308 	/* [temp.deduct]
13309 
13310 	   Type deduction may fail for any of the following
13311 	   reasons:
13312 
13313 	   -- Attempting to create a pointer to reference type.
13314 	   -- Attempting to create a reference to a reference type or
13315 	      a reference to void.
13316 
13317 	  Core issue 106 says that creating a reference to a reference
13318 	  during instantiation is no longer a cause for failure. We
13319 	  only enforce this check in strict C++98 mode.  */
13320 	if ((TREE_CODE (type) == REFERENCE_TYPE
13321 	     && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
13322 	    || (code == REFERENCE_TYPE && VOID_TYPE_P (type)))
13323 	  {
13324 	    static location_t last_loc;
13325 
13326 	    /* We keep track of the last time we issued this error
13327 	       message to avoid spewing a ton of messages during a
13328 	       single bad template instantiation.  */
13329 	    if (complain & tf_error
13330 		&& last_loc != input_location)
13331 	      {
13332 		if (VOID_TYPE_P (type))
13333 		  error ("forming reference to void");
13334                else if (code == POINTER_TYPE)
13335                  error ("forming pointer to reference type %qT", type);
13336                else
13337 		  error ("forming reference to reference type %qT", type);
13338 		last_loc = input_location;
13339 	      }
13340 
13341 	    return error_mark_node;
13342 	  }
13343 	else if (TREE_CODE (type) == FUNCTION_TYPE
13344 		 && (type_memfn_quals (type) != TYPE_UNQUALIFIED
13345 		     || type_memfn_rqual (type) != REF_QUAL_NONE))
13346 	  {
13347 	    if (complain & tf_error)
13348 	      {
13349 		if (code == POINTER_TYPE)
13350 		  error ("forming pointer to qualified function type %qT",
13351 			 type);
13352 		else
13353 		  error ("forming reference to qualified function type %qT",
13354 			 type);
13355 	      }
13356 	    return error_mark_node;
13357 	  }
13358 	else if (code == POINTER_TYPE)
13359 	  {
13360 	    r = build_pointer_type (type);
13361 	    if (TREE_CODE (type) == METHOD_TYPE)
13362 	      r = build_ptrmemfunc_type (r);
13363 	  }
13364 	else if (TREE_CODE (type) == REFERENCE_TYPE)
13365 	  /* In C++0x, during template argument substitution, when there is an
13366 	     attempt to create a reference to a reference type, reference
13367 	     collapsing is applied as described in [14.3.1/4 temp.arg.type]:
13368 
13369 	     "If a template-argument for a template-parameter T names a type
13370 	     that is a reference to a type A, an attempt to create the type
13371 	     'lvalue reference to cv T' creates the type 'lvalue reference to
13372 	     A,' while an attempt to create the type type rvalue reference to
13373 	     cv T' creates the type T"
13374 	  */
13375 	  r = cp_build_reference_type
13376 	      (TREE_TYPE (type),
13377 	       TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
13378 	else
13379 	  r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
13380 	r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
13381 
13382 	if (r != error_mark_node)
13383 	  /* Will this ever be needed for TYPE_..._TO values?  */
13384 	  layout_type (r);
13385 
13386 	return r;
13387       }
13388     case OFFSET_TYPE:
13389       {
13390 	r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
13391 	if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
13392 	  {
13393 	    /* [temp.deduct]
13394 
13395 	       Type deduction may fail for any of the following
13396 	       reasons:
13397 
13398 	       -- Attempting to create "pointer to member of T" when T
13399 		  is not a class type.  */
13400 	    if (complain & tf_error)
13401 	      error ("creating pointer to member of non-class type %qT", r);
13402 	    return error_mark_node;
13403 	  }
13404 	if (TREE_CODE (type) == REFERENCE_TYPE)
13405 	  {
13406 	    if (complain & tf_error)
13407 	      error ("creating pointer to member reference type %qT", type);
13408 	    return error_mark_node;
13409 	  }
13410 	if (VOID_TYPE_P (type))
13411 	  {
13412 	    if (complain & tf_error)
13413 	      error ("creating pointer to member of type void");
13414 	    return error_mark_node;
13415 	  }
13416 	gcc_assert (TREE_CODE (type) != METHOD_TYPE);
13417 	if (TREE_CODE (type) == FUNCTION_TYPE)
13418 	  {
13419 	    /* The type of the implicit object parameter gets its
13420 	       cv-qualifiers from the FUNCTION_TYPE. */
13421 	    tree memptr;
13422 	    tree method_type
13423 	      = build_memfn_type (type, r, type_memfn_quals (type),
13424 				  type_memfn_rqual (type));
13425 	    memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
13426 	    return cp_build_qualified_type_real (memptr, cp_type_quals (t),
13427 						 complain);
13428 	  }
13429 	else
13430 	  return cp_build_qualified_type_real (build_ptrmem_type (r, type),
13431 					       cp_type_quals (t),
13432 					       complain);
13433       }
13434     case FUNCTION_TYPE:
13435     case METHOD_TYPE:
13436       {
13437 	tree fntype;
13438 	tree specs;
13439 	fntype = tsubst_function_type (t, args, complain, in_decl);
13440 	if (fntype == error_mark_node)
13441 	  return error_mark_node;
13442 
13443 	/* Substitute the exception specification.  */
13444 	specs = tsubst_exception_specification (t, args, complain,
13445 						in_decl, /*defer_ok*/true);
13446 	if (specs == error_mark_node)
13447 	  return error_mark_node;
13448 	if (specs)
13449 	  fntype = build_exception_variant (fntype, specs);
13450 	return fntype;
13451       }
13452     case ARRAY_TYPE:
13453       {
13454 	tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
13455 	if (domain == error_mark_node)
13456 	  return error_mark_node;
13457 
13458 	/* As an optimization, we avoid regenerating the array type if
13459 	   it will obviously be the same as T.  */
13460 	if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
13461 	  return t;
13462 
13463 	/* These checks should match the ones in create_array_type_for_decl.
13464 
13465 	   [temp.deduct]
13466 
13467 	   The deduction may fail for any of the following reasons:
13468 
13469 	   -- Attempting to create an array with an element type that
13470 	      is void, a function type, or a reference type, or [DR337]
13471 	      an abstract class type.  */
13472 	if (VOID_TYPE_P (type)
13473 	    || TREE_CODE (type) == FUNCTION_TYPE
13474 	    || (TREE_CODE (type) == ARRAY_TYPE
13475 		&& TYPE_DOMAIN (type) == NULL_TREE)
13476 	    || TREE_CODE (type) == REFERENCE_TYPE)
13477 	  {
13478 	    if (complain & tf_error)
13479 	      error ("creating array of %qT", type);
13480 	    return error_mark_node;
13481 	  }
13482 
13483 	if (abstract_virtuals_error_sfinae (ACU_ARRAY, type, complain))
13484 	  return error_mark_node;
13485 
13486 	r = build_cplus_array_type (type, domain);
13487 
13488 	if (TYPE_USER_ALIGN (t))
13489 	  {
13490 	    TYPE_ALIGN (r) = TYPE_ALIGN (t);
13491 	    TYPE_USER_ALIGN (r) = 1;
13492 	  }
13493 
13494 	return r;
13495       }
13496 
13497     case TYPENAME_TYPE:
13498       {
13499 	tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
13500 				     in_decl, /*entering_scope=*/1);
13501 	tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
13502 			      complain, in_decl);
13503 
13504 	if (ctx == error_mark_node || f == error_mark_node)
13505 	  return error_mark_node;
13506 
13507 	if (!MAYBE_CLASS_TYPE_P (ctx))
13508 	  {
13509 	    if (complain & tf_error)
13510 	      error ("%qT is not a class, struct, or union type", ctx);
13511 	    return error_mark_node;
13512 	  }
13513 	else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
13514 	  {
13515 	    /* Normally, make_typename_type does not require that the CTX
13516 	       have complete type in order to allow things like:
13517 
13518 		 template <class T> struct S { typename S<T>::X Y; };
13519 
13520 	       But, such constructs have already been resolved by this
13521 	       point, so here CTX really should have complete type, unless
13522 	       it's a partial instantiation.  */
13523 	    ctx = complete_type (ctx);
13524 	    if (!COMPLETE_TYPE_P (ctx))
13525 	      {
13526 		if (complain & tf_error)
13527 		  cxx_incomplete_type_error (NULL_TREE, ctx);
13528 		return error_mark_node;
13529 	      }
13530 	  }
13531 
13532 	f = make_typename_type (ctx, f, typename_type,
13533 				complain | tf_keep_type_decl);
13534 	if (f == error_mark_node)
13535 	  return f;
13536 	if (TREE_CODE (f) == TYPE_DECL)
13537 	  {
13538 	    complain |= tf_ignore_bad_quals;
13539 	    f = TREE_TYPE (f);
13540 	  }
13541 
13542 	if (TREE_CODE (f) != TYPENAME_TYPE)
13543 	  {
13544 	    if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
13545 	      {
13546 		if (complain & tf_error)
13547 		  error ("%qT resolves to %qT, which is not an enumeration type",
13548 			 t, f);
13549 		else
13550 		  return error_mark_node;
13551 	      }
13552 	    else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
13553 	      {
13554 		if (complain & tf_error)
13555 		  error ("%qT resolves to %qT, which is is not a class type",
13556 			 t, f);
13557 		else
13558 		  return error_mark_node;
13559 	      }
13560 	  }
13561 
13562 	return cp_build_qualified_type_real
13563 	  (f, cp_type_quals (f) | cp_type_quals (t), complain);
13564       }
13565 
13566     case UNBOUND_CLASS_TEMPLATE:
13567       {
13568 	tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
13569 				     in_decl, /*entering_scope=*/1);
13570 	tree name = TYPE_IDENTIFIER (t);
13571 	tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
13572 
13573 	if (ctx == error_mark_node || name == error_mark_node)
13574 	  return error_mark_node;
13575 
13576 	if (parm_list)
13577 	  parm_list = tsubst_template_parms (parm_list, args, complain);
13578 	return make_unbound_class_template (ctx, name, parm_list, complain);
13579       }
13580 
13581     case TYPEOF_TYPE:
13582       {
13583 	tree type;
13584 
13585 	++cp_unevaluated_operand;
13586 	++c_inhibit_evaluation_warnings;
13587 
13588 	type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
13589 			    complain, in_decl,
13590 			    /*integral_constant_expression_p=*/false);
13591 
13592 	--cp_unevaluated_operand;
13593 	--c_inhibit_evaluation_warnings;
13594 
13595 	type = finish_typeof (type);
13596 	return cp_build_qualified_type_real (type,
13597 					     cp_type_quals (t)
13598 					     | cp_type_quals (type),
13599 					     complain);
13600       }
13601 
13602     case DECLTYPE_TYPE:
13603       {
13604 	tree type;
13605 
13606 	++cp_unevaluated_operand;
13607 	++c_inhibit_evaluation_warnings;
13608 
13609 	type = tsubst_copy_and_build (DECLTYPE_TYPE_EXPR (t), args,
13610 				      complain|tf_decltype, in_decl,
13611 				      /*function_p*/false,
13612 				      /*integral_constant_expression*/false);
13613 
13614 	--cp_unevaluated_operand;
13615 	--c_inhibit_evaluation_warnings;
13616 
13617 	if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
13618 	  type = lambda_capture_field_type (type,
13619 					    DECLTYPE_FOR_INIT_CAPTURE (t));
13620 	else if (DECLTYPE_FOR_LAMBDA_PROXY (t))
13621 	  type = lambda_proxy_type (type);
13622 	else
13623 	  {
13624 	    bool id = DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t);
13625 	    if (id && TREE_CODE (DECLTYPE_TYPE_EXPR (t)) == BIT_NOT_EXPR
13626 		&& EXPR_P (type))
13627 	      /* In a template ~id could be either a complement expression
13628 		 or an unqualified-id naming a destructor; if instantiating
13629 		 it produces an expression, it's not an id-expression or
13630 		 member access.  */
13631 	      id = false;
13632 	    type = finish_decltype_type (type, id, complain);
13633 	  }
13634 	return cp_build_qualified_type_real (type,
13635 					     cp_type_quals (t)
13636 					     | cp_type_quals (type),
13637 					     complain | tf_ignore_bad_quals);
13638       }
13639 
13640     case UNDERLYING_TYPE:
13641       {
13642 	tree type = tsubst (UNDERLYING_TYPE_TYPE (t), args,
13643 			    complain, in_decl);
13644 	return finish_underlying_type (type);
13645       }
13646 
13647     case TYPE_ARGUMENT_PACK:
13648     case NONTYPE_ARGUMENT_PACK:
13649       {
13650         tree r = TYPE_P (t) ? cxx_make_type (code) : make_node (code);
13651         tree packed_out =
13652           tsubst_template_args (ARGUMENT_PACK_ARGS (t),
13653                                 args,
13654                                 complain,
13655                                 in_decl);
13656         SET_ARGUMENT_PACK_ARGS (r, packed_out);
13657 
13658         /* For template nontype argument packs, also substitute into
13659            the type.  */
13660         if (code == NONTYPE_ARGUMENT_PACK)
13661           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
13662 
13663         return r;
13664       }
13665       break;
13666 
13667     case VOID_CST:
13668     case INTEGER_CST:
13669     case REAL_CST:
13670     case STRING_CST:
13671     case PLUS_EXPR:
13672     case MINUS_EXPR:
13673     case NEGATE_EXPR:
13674     case NOP_EXPR:
13675     case INDIRECT_REF:
13676     case ADDR_EXPR:
13677     case CALL_EXPR:
13678     case ARRAY_REF:
13679     case SCOPE_REF:
13680       /* We should use one of the expression tsubsts for these codes.  */
13681       gcc_unreachable ();
13682 
13683     default:
13684       sorry ("use of %qs in template", get_tree_code_name (code));
13685       return error_mark_node;
13686     }
13687 }
13688 
13689 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
13690    type of the expression on the left-hand side of the "." or "->"
13691    operator.  */
13692 
13693 static tree
tsubst_baselink(tree baselink,tree object_type,tree args,tsubst_flags_t complain,tree in_decl)13694 tsubst_baselink (tree baselink, tree object_type,
13695 		 tree args, tsubst_flags_t complain, tree in_decl)
13696 {
13697     tree name;
13698     tree qualifying_scope;
13699     tree fns;
13700     tree optype;
13701     tree template_args = 0;
13702     bool template_id_p = false;
13703     bool qualified = BASELINK_QUALIFIED_P (baselink);
13704 
13705     /* A baselink indicates a function from a base class.  Both the
13706        BASELINK_ACCESS_BINFO and the base class referenced may
13707        indicate bases of the template class, rather than the
13708        instantiated class.  In addition, lookups that were not
13709        ambiguous before may be ambiguous now.  Therefore, we perform
13710        the lookup again.  */
13711     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
13712     qualifying_scope = tsubst (qualifying_scope, args,
13713 			       complain, in_decl);
13714     fns = BASELINK_FUNCTIONS (baselink);
13715     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
13716     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
13717       {
13718 	template_id_p = true;
13719 	template_args = TREE_OPERAND (fns, 1);
13720 	fns = TREE_OPERAND (fns, 0);
13721 	if (template_args)
13722 	  template_args = tsubst_template_args (template_args, args,
13723 						complain, in_decl);
13724       }
13725     name = DECL_NAME (get_first_fn (fns));
13726     if (IDENTIFIER_TYPENAME_P (name))
13727       name = mangle_conv_op_name_for_type (optype);
13728     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
13729     if (!baselink)
13730       {
13731 	if (constructor_name_p (name, qualifying_scope))
13732 	  {
13733 	    if (complain & tf_error)
13734 	      error ("cannot call constructor %<%T::%D%> directly",
13735 		     qualifying_scope, name);
13736 	  }
13737 	return error_mark_node;
13738       }
13739 
13740     /* If lookup found a single function, mark it as used at this
13741        point.  (If it lookup found multiple functions the one selected
13742        later by overload resolution will be marked as used at that
13743        point.)  */
13744     if (BASELINK_P (baselink))
13745       fns = BASELINK_FUNCTIONS (baselink);
13746     if (!template_id_p && !really_overloaded_fn (fns)
13747 	&& !mark_used (OVL_CURRENT (fns), complain) && !(complain & tf_error))
13748       return error_mark_node;
13749 
13750     /* Add back the template arguments, if present.  */
13751     if (BASELINK_P (baselink) && template_id_p)
13752       BASELINK_FUNCTIONS (baselink)
13753 	= build2 (TEMPLATE_ID_EXPR,
13754 		  unknown_type_node,
13755 		  BASELINK_FUNCTIONS (baselink),
13756 		  template_args);
13757     /* Update the conversion operator type.  */
13758     BASELINK_OPTYPE (baselink) = optype;
13759 
13760     if (!object_type)
13761       object_type = current_class_type;
13762 
13763     if (qualified || name == complete_dtor_identifier)
13764       {
13765 	baselink = adjust_result_of_qualified_name_lookup (baselink,
13766 							   qualifying_scope,
13767 							   object_type);
13768 	if (!qualified)
13769 	  /* We need to call adjust_result_of_qualified_name_lookup in case the
13770 	     destructor names a base class, but we unset BASELINK_QUALIFIED_P
13771 	     so that we still get virtual function binding.  */
13772 	  BASELINK_QUALIFIED_P (baselink) = false;
13773       }
13774     return baselink;
13775 }
13776 
13777 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
13778    true if the qualified-id will be a postfix-expression in-and-of
13779    itself; false if more of the postfix-expression follows the
13780    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
13781    of "&".  */
13782 
13783 static tree
tsubst_qualified_id(tree qualified_id,tree args,tsubst_flags_t complain,tree in_decl,bool done,bool address_p)13784 tsubst_qualified_id (tree qualified_id, tree args,
13785 		     tsubst_flags_t complain, tree in_decl,
13786 		     bool done, bool address_p)
13787 {
13788   tree expr;
13789   tree scope;
13790   tree name;
13791   bool is_template;
13792   tree template_args;
13793   location_t loc = UNKNOWN_LOCATION;
13794 
13795   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
13796 
13797   /* Figure out what name to look up.  */
13798   name = TREE_OPERAND (qualified_id, 1);
13799   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
13800     {
13801       is_template = true;
13802       loc = EXPR_LOCATION (name);
13803       template_args = TREE_OPERAND (name, 1);
13804       if (template_args)
13805 	template_args = tsubst_template_args (template_args, args,
13806 					      complain, in_decl);
13807       name = TREE_OPERAND (name, 0);
13808     }
13809   else
13810     {
13811       is_template = false;
13812       template_args = NULL_TREE;
13813     }
13814 
13815   /* Substitute into the qualifying scope.  When there are no ARGS, we
13816      are just trying to simplify a non-dependent expression.  In that
13817      case the qualifying scope may be dependent, and, in any case,
13818      substituting will not help.  */
13819   scope = TREE_OPERAND (qualified_id, 0);
13820   if (args)
13821     {
13822       scope = tsubst (scope, args, complain, in_decl);
13823       expr = tsubst_copy (name, args, complain, in_decl);
13824     }
13825   else
13826     expr = name;
13827 
13828   if (dependent_scope_p (scope))
13829     {
13830       if (is_template)
13831 	expr = build_min_nt_loc (loc, TEMPLATE_ID_EXPR, expr, template_args);
13832       tree r = build_qualified_name (NULL_TREE, scope, expr,
13833 				     QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
13834       REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (qualified_id);
13835       return r;
13836     }
13837 
13838   if (!BASELINK_P (name) && !DECL_P (expr))
13839     {
13840       if (TREE_CODE (expr) == BIT_NOT_EXPR)
13841 	{
13842 	  /* A BIT_NOT_EXPR is used to represent a destructor.  */
13843 	  if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
13844 	    {
13845 	      error ("qualifying type %qT does not match destructor name ~%qT",
13846 		     scope, TREE_OPERAND (expr, 0));
13847 	      expr = error_mark_node;
13848 	    }
13849 	  else
13850 	    expr = lookup_qualified_name (scope, complete_dtor_identifier,
13851 					  /*is_type_p=*/0, false);
13852 	}
13853       else
13854 	expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
13855       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
13856 		     ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
13857 	{
13858 	  if (complain & tf_error)
13859 	    {
13860 	      error ("dependent-name %qE is parsed as a non-type, but "
13861 		     "instantiation yields a type", qualified_id);
13862 	      inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
13863 	    }
13864 	  return error_mark_node;
13865 	}
13866     }
13867 
13868   if (DECL_P (expr))
13869     {
13870       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
13871 					   scope);
13872       /* Remember that there was a reference to this entity.  */
13873       if (!mark_used (expr, complain) && !(complain & tf_error))
13874 	return error_mark_node;
13875     }
13876 
13877   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
13878     {
13879       if (complain & tf_error)
13880 	qualified_name_lookup_error (scope,
13881 				     TREE_OPERAND (qualified_id, 1),
13882 				     expr, input_location);
13883       return error_mark_node;
13884     }
13885 
13886   if (is_template)
13887     {
13888       if (variable_template_p (expr))
13889 	expr = lookup_and_finish_template_variable (expr, template_args,
13890 						    complain);
13891       else
13892 	expr = lookup_template_function (expr, template_args);
13893     }
13894 
13895   if (expr == error_mark_node && complain & tf_error)
13896     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
13897 				 expr, input_location);
13898   else if (TYPE_P (scope))
13899     {
13900       expr = (adjust_result_of_qualified_name_lookup
13901 	      (expr, scope, current_nonlambda_class_type ()));
13902       expr = (finish_qualified_id_expr
13903 	      (scope, expr, done, address_p && PTRMEM_OK_P (qualified_id),
13904 	       QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
13905 	       /*template_arg_p=*/false, complain));
13906     }
13907 
13908   /* Expressions do not generally have reference type.  */
13909   if (TREE_CODE (expr) != SCOPE_REF
13910       /* However, if we're about to form a pointer-to-member, we just
13911 	 want the referenced member referenced.  */
13912       && TREE_CODE (expr) != OFFSET_REF)
13913     expr = convert_from_reference (expr);
13914 
13915   if (REF_PARENTHESIZED_P (qualified_id))
13916     expr = force_paren_expr (expr);
13917 
13918   return expr;
13919 }
13920 
13921 /* tsubst the initializer for a VAR_DECL.  INIT is the unsubstituted
13922    initializer, DECL is the substituted VAR_DECL.  Other arguments are as
13923    for tsubst.  */
13924 
13925 static tree
tsubst_init(tree init,tree decl,tree args,tsubst_flags_t complain,tree in_decl)13926 tsubst_init (tree init, tree decl, tree args,
13927 	     tsubst_flags_t complain, tree in_decl)
13928 {
13929   if (!init)
13930     return NULL_TREE;
13931 
13932   init = tsubst_expr (init, args, complain, in_decl, false);
13933 
13934   if (!init && TREE_TYPE (decl) != error_mark_node)
13935     {
13936       /* If we had an initializer but it
13937 	 instantiated to nothing,
13938 	 value-initialize the object.  This will
13939 	 only occur when the initializer was a
13940 	 pack expansion where the parameter packs
13941 	 used in that expansion were of length
13942 	 zero.  */
13943       init = build_value_init (TREE_TYPE (decl),
13944 			       complain);
13945       if (TREE_CODE (init) == AGGR_INIT_EXPR)
13946 	init = get_target_expr_sfinae (init, complain);
13947     }
13948 
13949   return init;
13950 }
13951 
13952 /* Like tsubst, but deals with expressions.  This function just replaces
13953    template parms; to finish processing the resultant expression, use
13954    tsubst_copy_and_build or tsubst_expr.  */
13955 
13956 static tree
tsubst_copy(tree t,tree args,tsubst_flags_t complain,tree in_decl)13957 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
13958 {
13959   enum tree_code code;
13960   tree r;
13961 
13962   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
13963     return t;
13964 
13965   code = TREE_CODE (t);
13966 
13967   switch (code)
13968     {
13969     case PARM_DECL:
13970       r = retrieve_local_specialization (t);
13971 
13972       if (r == NULL_TREE)
13973 	{
13974 	  /* We get here for a use of 'this' in an NSDMI as part of a
13975 	     constructor call or as part of an aggregate initialization.  */
13976 	  if (DECL_NAME (t) == this_identifier
13977 	      && ((current_function_decl
13978 		   && DECL_CONSTRUCTOR_P (current_function_decl))
13979 		  || (current_class_ref
13980 		      && TREE_CODE (current_class_ref) == PLACEHOLDER_EXPR)))
13981 	    return current_class_ptr;
13982 
13983 	  /* This can happen for a parameter name used later in a function
13984 	     declaration (such as in a late-specified return type).  Just
13985 	     make a dummy decl, since it's only used for its type.  */
13986 	  gcc_assert (cp_unevaluated_operand != 0);
13987 	  r = tsubst_decl (t, args, complain);
13988 	  /* Give it the template pattern as its context; its true context
13989 	     hasn't been instantiated yet and this is good enough for
13990 	     mangling.  */
13991 	  DECL_CONTEXT (r) = DECL_CONTEXT (t);
13992 	}
13993 
13994       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
13995 	r = ARGUMENT_PACK_SELECT_ARG (r);
13996       if (!mark_used (r, complain) && !(complain & tf_error))
13997 	return error_mark_node;
13998       return r;
13999 
14000     case CONST_DECL:
14001       {
14002 	tree enum_type;
14003 	tree v;
14004 
14005 	if (DECL_TEMPLATE_PARM_P (t))
14006 	  return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
14007 	/* There is no need to substitute into namespace-scope
14008 	   enumerators.  */
14009 	if (DECL_NAMESPACE_SCOPE_P (t))
14010 	  return t;
14011 	/* If ARGS is NULL, then T is known to be non-dependent.  */
14012 	if (args == NULL_TREE)
14013 	  return scalar_constant_value (t);
14014 
14015 	/* Unfortunately, we cannot just call lookup_name here.
14016 	   Consider:
14017 
14018 	     template <int I> int f() {
14019 	     enum E { a = I };
14020 	     struct S { void g() { E e = a; } };
14021 	     };
14022 
14023 	   When we instantiate f<7>::S::g(), say, lookup_name is not
14024 	   clever enough to find f<7>::a.  */
14025 	enum_type
14026 	  = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
14027 			      /*entering_scope=*/0);
14028 
14029 	for (v = TYPE_VALUES (enum_type);
14030 	     v != NULL_TREE;
14031 	     v = TREE_CHAIN (v))
14032 	  if (TREE_PURPOSE (v) == DECL_NAME (t))
14033 	    return TREE_VALUE (v);
14034 
14035 	  /* We didn't find the name.  That should never happen; if
14036 	     name-lookup found it during preliminary parsing, we
14037 	     should find it again here during instantiation.  */
14038 	gcc_unreachable ();
14039       }
14040       return t;
14041 
14042     case FIELD_DECL:
14043       if (PACK_EXPANSION_P (TREE_TYPE (t)))
14044 	{
14045 	  /* Check for a local specialization set up by
14046 	     tsubst_pack_expansion.  */
14047 	  if (tree r = retrieve_local_specialization (t))
14048 	    {
14049 	      if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
14050 		r = ARGUMENT_PACK_SELECT_ARG (r);
14051 	      return r;
14052 	    }
14053 
14054 	  /* When retrieving a capture pack from a generic lambda, remove the
14055 	     lambda call op's own template argument list from ARGS.  Only the
14056 	     template arguments active for the closure type should be used to
14057 	     retrieve the pack specialization.  */
14058 	  if (LAMBDA_FUNCTION_P (current_function_decl)
14059 	      && (template_class_depth (DECL_CONTEXT (t))
14060 		  != TMPL_ARGS_DEPTH (args)))
14061 	    args = strip_innermost_template_args (args, 1);
14062 
14063 	  /* Otherwise return the full NONTYPE_ARGUMENT_PACK that
14064 	     tsubst_decl put in the hash table.  */
14065 	  return retrieve_specialization (t, args, 0);
14066 	}
14067 
14068       if (DECL_CONTEXT (t))
14069 	{
14070 	  tree ctx;
14071 
14072 	  ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
14073 				  /*entering_scope=*/1);
14074 	  if (ctx != DECL_CONTEXT (t))
14075 	    {
14076 	      tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
14077 	      if (!r)
14078 		{
14079 		  if (complain & tf_error)
14080 		    error ("using invalid field %qD", t);
14081 		  return error_mark_node;
14082 		}
14083 	      return r;
14084 	    }
14085 	}
14086 
14087       return t;
14088 
14089     case VAR_DECL:
14090     case FUNCTION_DECL:
14091       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
14092 	r = tsubst (t, args, complain, in_decl);
14093       else if (local_variable_p (t)
14094 	       && uses_template_parms (DECL_CONTEXT (t)))
14095 	{
14096 	  r = retrieve_local_specialization (t);
14097 	  if (r == NULL_TREE)
14098 	    {
14099 	      /* First try name lookup to find the instantiation.  */
14100 	      r = lookup_name (DECL_NAME (t));
14101 	      if (r && !is_capture_proxy (r))
14102 		{
14103 		  /* Make sure that the one we found is the one we want.  */
14104 		  tree ctx = DECL_CONTEXT (t);
14105 		  if (DECL_LANG_SPECIFIC (ctx) && DECL_TEMPLATE_INFO (ctx))
14106 		    ctx = tsubst (ctx, args, complain, in_decl);
14107 		  if (ctx != DECL_CONTEXT (r))
14108 		    r = NULL_TREE;
14109 		}
14110 
14111 	      if (r)
14112 		/* OK */;
14113 	      else
14114 		{
14115 		  /* This can happen for a variable used in a
14116 		     late-specified return type of a local lambda, or for a
14117 		     local static or constant.  Building a new VAR_DECL
14118 		     should be OK in all those cases.  */
14119 		  r = tsubst_decl (t, args, complain);
14120 		  if (local_specializations)
14121 		    /* Avoid infinite recursion (79640).  */
14122 		    register_local_specialization (r, t);
14123 		  if (decl_maybe_constant_var_p (r))
14124 		    {
14125 		      /* We can't call cp_finish_decl, so handle the
14126 			 initializer by hand.  */
14127 		      tree init = tsubst_init (DECL_INITIAL (t), r, args,
14128 					       complain, in_decl);
14129 		      if (!processing_template_decl)
14130 			init = maybe_constant_init (init);
14131 		      if (processing_template_decl
14132 			  ? potential_constant_expression (init)
14133 			  : reduced_constant_expression_p (init))
14134 			DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
14135 			  = TREE_CONSTANT (r) = true;
14136 		      DECL_INITIAL (r) = init;
14137 		    }
14138 		  gcc_assert (cp_unevaluated_operand || TREE_STATIC (r)
14139 			      || decl_constant_var_p (r)
14140 			      || errorcount || sorrycount);
14141 		  if (!processing_template_decl
14142 		      && !TREE_STATIC (r))
14143 		    r = process_outer_var_ref (r, complain);
14144 		}
14145 	      /* Remember this for subsequent uses.  */
14146 	      if (local_specializations)
14147 		register_local_specialization (r, t);
14148 	    }
14149 	}
14150       else
14151 	r = t;
14152       if (!mark_used (r, complain) && !(complain & tf_error))
14153 	return error_mark_node;
14154       return r;
14155 
14156     case NAMESPACE_DECL:
14157       return t;
14158 
14159     case OVERLOAD:
14160       /* An OVERLOAD will always be a non-dependent overload set; an
14161 	 overload set from function scope will just be represented with an
14162 	 IDENTIFIER_NODE, and from class scope with a BASELINK.  */
14163       gcc_assert (!uses_template_parms (t));
14164       return t;
14165 
14166     case BASELINK:
14167       return tsubst_baselink (t, current_nonlambda_class_type (),
14168 			      args, complain, in_decl);
14169 
14170     case TEMPLATE_DECL:
14171       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
14172 	return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
14173 		       args, complain, in_decl);
14174       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
14175 	return tsubst (t, args, complain, in_decl);
14176       else if (DECL_CLASS_SCOPE_P (t)
14177 	       && uses_template_parms (DECL_CONTEXT (t)))
14178 	{
14179 	  /* Template template argument like the following example need
14180 	     special treatment:
14181 
14182 	       template <template <class> class TT> struct C {};
14183 	       template <class T> struct D {
14184 		 template <class U> struct E {};
14185 		 C<E> c;				// #1
14186 	       };
14187 	       D<int> d;				// #2
14188 
14189 	     We are processing the template argument `E' in #1 for
14190 	     the template instantiation #2.  Originally, `E' is a
14191 	     TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
14192 	     have to substitute this with one having context `D<int>'.  */
14193 
14194 	  tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
14195 	  return lookup_field (context, DECL_NAME(t), 0, false);
14196 	}
14197       else
14198 	/* Ordinary template template argument.  */
14199 	return t;
14200 
14201     case CAST_EXPR:
14202     case REINTERPRET_CAST_EXPR:
14203     case CONST_CAST_EXPR:
14204     case STATIC_CAST_EXPR:
14205     case DYNAMIC_CAST_EXPR:
14206     case IMPLICIT_CONV_EXPR:
14207     case CONVERT_EXPR:
14208     case NOP_EXPR:
14209       {
14210 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14211 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
14212 	return build1 (code, type, op0);
14213       }
14214 
14215     case SIZEOF_EXPR:
14216       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
14217 	  || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
14218         {
14219           tree expanded, op = TREE_OPERAND (t, 0);
14220 	  int len = 0;
14221 
14222 	  if (SIZEOF_EXPR_TYPE_P (t))
14223 	    op = TREE_TYPE (op);
14224 
14225 	  ++cp_unevaluated_operand;
14226 	  ++c_inhibit_evaluation_warnings;
14227 	  /* We only want to compute the number of arguments.  */
14228 	  if (PACK_EXPANSION_P (op))
14229 	    expanded = tsubst_pack_expansion (op, args, complain, in_decl);
14230 	  else
14231 	    expanded = tsubst_template_args (ARGUMENT_PACK_ARGS (op),
14232 					     args, complain, in_decl);
14233 	  --cp_unevaluated_operand;
14234 	  --c_inhibit_evaluation_warnings;
14235 
14236 	  if (TREE_CODE (expanded) == TREE_VEC)
14237 	    {
14238 	      len = TREE_VEC_LENGTH (expanded);
14239 	      /* Set TREE_USED for the benefit of -Wunused.  */
14240 	      for (int i = 0; i < len; i++)
14241 		if (DECL_P (TREE_VEC_ELT (expanded, i)))
14242 		  TREE_USED (TREE_VEC_ELT (expanded, i)) = true;
14243 	    }
14244 
14245 	  if (expanded == error_mark_node)
14246 	    return error_mark_node;
14247 	  else if (PACK_EXPANSION_P (expanded)
14248 		   || (TREE_CODE (expanded) == TREE_VEC
14249 		       && pack_expansion_args_count (expanded)))
14250 
14251 	    {
14252 	      if (PACK_EXPANSION_P (expanded))
14253 		/* OK.  */;
14254 	      else if (TREE_VEC_LENGTH (expanded) == 1)
14255 		expanded = TREE_VEC_ELT (expanded, 0);
14256 	      else
14257 		expanded = make_argument_pack (expanded);
14258 
14259 	      if (TYPE_P (expanded))
14260 		return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR,
14261 						   complain & tf_error);
14262 	      else
14263 		return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
14264                                                    complain & tf_error);
14265 	    }
14266 	  else
14267 	    return build_int_cst (size_type_node, len);
14268         }
14269       if (SIZEOF_EXPR_TYPE_P (t))
14270 	{
14271 	  r = tsubst (TREE_TYPE (TREE_OPERAND (t, 0)),
14272 		      args, complain, in_decl);
14273 	  r = build1 (NOP_EXPR, r, error_mark_node);
14274 	  r = build1 (SIZEOF_EXPR,
14275 		      tsubst (TREE_TYPE (t), args, complain, in_decl), r);
14276 	  SIZEOF_EXPR_TYPE_P (r) = 1;
14277 	  return r;
14278 	}
14279       /* Fall through */
14280 
14281     case INDIRECT_REF:
14282     case NEGATE_EXPR:
14283     case TRUTH_NOT_EXPR:
14284     case BIT_NOT_EXPR:
14285     case ADDR_EXPR:
14286     case UNARY_PLUS_EXPR:      /* Unary + */
14287     case ALIGNOF_EXPR:
14288     case AT_ENCODE_EXPR:
14289     case ARROW_EXPR:
14290     case THROW_EXPR:
14291     case TYPEID_EXPR:
14292     case REALPART_EXPR:
14293     case IMAGPART_EXPR:
14294     case PAREN_EXPR:
14295       {
14296 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14297 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
14298 	return build1 (code, type, op0);
14299       }
14300 
14301     case COMPONENT_REF:
14302       {
14303 	tree object;
14304 	tree name;
14305 
14306 	object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
14307 	name = TREE_OPERAND (t, 1);
14308 	if (TREE_CODE (name) == BIT_NOT_EXPR)
14309 	  {
14310 	    name = tsubst_copy (TREE_OPERAND (name, 0), args,
14311 				complain, in_decl);
14312 	    name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
14313 	  }
14314 	else if (TREE_CODE (name) == SCOPE_REF
14315 		 && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
14316 	  {
14317 	    tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
14318 				     complain, in_decl);
14319 	    name = TREE_OPERAND (name, 1);
14320 	    name = tsubst_copy (TREE_OPERAND (name, 0), args,
14321 				complain, in_decl);
14322 	    name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
14323 	    name = build_qualified_name (/*type=*/NULL_TREE,
14324 					 base, name,
14325 					 /*template_p=*/false);
14326 	  }
14327 	else if (BASELINK_P (name))
14328 	  name = tsubst_baselink (name,
14329 				  non_reference (TREE_TYPE (object)),
14330 				  args, complain,
14331 				  in_decl);
14332 	else
14333 	  name = tsubst_copy (name, args, complain, in_decl);
14334 	return build_nt (COMPONENT_REF, object, name, NULL_TREE);
14335       }
14336 
14337     case PLUS_EXPR:
14338     case MINUS_EXPR:
14339     case MULT_EXPR:
14340     case TRUNC_DIV_EXPR:
14341     case CEIL_DIV_EXPR:
14342     case FLOOR_DIV_EXPR:
14343     case ROUND_DIV_EXPR:
14344     case EXACT_DIV_EXPR:
14345     case BIT_AND_EXPR:
14346     case BIT_IOR_EXPR:
14347     case BIT_XOR_EXPR:
14348     case TRUNC_MOD_EXPR:
14349     case FLOOR_MOD_EXPR:
14350     case TRUTH_ANDIF_EXPR:
14351     case TRUTH_ORIF_EXPR:
14352     case TRUTH_AND_EXPR:
14353     case TRUTH_OR_EXPR:
14354     case RSHIFT_EXPR:
14355     case LSHIFT_EXPR:
14356     case RROTATE_EXPR:
14357     case LROTATE_EXPR:
14358     case EQ_EXPR:
14359     case NE_EXPR:
14360     case MAX_EXPR:
14361     case MIN_EXPR:
14362     case LE_EXPR:
14363     case GE_EXPR:
14364     case LT_EXPR:
14365     case GT_EXPR:
14366     case COMPOUND_EXPR:
14367     case DOTSTAR_EXPR:
14368     case MEMBER_REF:
14369     case PREDECREMENT_EXPR:
14370     case PREINCREMENT_EXPR:
14371     case POSTDECREMENT_EXPR:
14372     case POSTINCREMENT_EXPR:
14373       {
14374 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
14375 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
14376 	return build_nt (code, op0, op1);
14377       }
14378 
14379     case SCOPE_REF:
14380       {
14381 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
14382 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
14383 	return build_qualified_name (/*type=*/NULL_TREE, op0, op1,
14384 				     QUALIFIED_NAME_IS_TEMPLATE (t));
14385       }
14386 
14387     case ARRAY_REF:
14388       {
14389 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
14390 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
14391 	return build_nt (ARRAY_REF, op0, op1, NULL_TREE, NULL_TREE);
14392       }
14393 
14394     case CALL_EXPR:
14395       {
14396 	int n = VL_EXP_OPERAND_LENGTH (t);
14397 	tree result = build_vl_exp (CALL_EXPR, n);
14398 	int i;
14399 	for (i = 0; i < n; i++)
14400 	  TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
14401 					     complain, in_decl);
14402 	return result;
14403       }
14404 
14405     case COND_EXPR:
14406     case MODOP_EXPR:
14407     case PSEUDO_DTOR_EXPR:
14408     case VEC_PERM_EXPR:
14409       {
14410 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
14411 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
14412 	tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
14413 	r = build_nt (code, op0, op1, op2);
14414 	TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
14415 	return r;
14416       }
14417 
14418     case NEW_EXPR:
14419       {
14420 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
14421 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
14422 	tree op2 = tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl);
14423 	r = build_nt (code, op0, op1, op2);
14424 	NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
14425 	return r;
14426       }
14427 
14428     case DELETE_EXPR:
14429       {
14430 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
14431 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
14432 	r = build_nt (code, op0, op1);
14433 	DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
14434 	DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
14435 	return r;
14436       }
14437 
14438     case TEMPLATE_ID_EXPR:
14439       {
14440 	/* Substituted template arguments */
14441 	tree fn = TREE_OPERAND (t, 0);
14442 	tree targs = TREE_OPERAND (t, 1);
14443 
14444 	fn = tsubst_copy (fn, args, complain, in_decl);
14445 	if (targs)
14446 	  targs = tsubst_template_args (targs, args, complain, in_decl);
14447 
14448 	return lookup_template_function (fn, targs);
14449       }
14450 
14451     case TREE_LIST:
14452       {
14453 	tree purpose, value, chain;
14454 
14455 	if (t == void_list_node)
14456 	  return t;
14457 
14458 	purpose = TREE_PURPOSE (t);
14459 	if (purpose)
14460 	  purpose = tsubst_copy (purpose, args, complain, in_decl);
14461 	value = TREE_VALUE (t);
14462 	if (value)
14463 	  value = tsubst_copy (value, args, complain, in_decl);
14464 	chain = TREE_CHAIN (t);
14465 	if (chain && chain != void_type_node)
14466 	  chain = tsubst_copy (chain, args, complain, in_decl);
14467 	if (purpose == TREE_PURPOSE (t)
14468 	    && value == TREE_VALUE (t)
14469 	    && chain == TREE_CHAIN (t))
14470 	  return t;
14471 	return tree_cons (purpose, value, chain);
14472       }
14473 
14474     case RECORD_TYPE:
14475     case UNION_TYPE:
14476     case ENUMERAL_TYPE:
14477     case INTEGER_TYPE:
14478     case TEMPLATE_TYPE_PARM:
14479     case TEMPLATE_TEMPLATE_PARM:
14480     case BOUND_TEMPLATE_TEMPLATE_PARM:
14481     case TEMPLATE_PARM_INDEX:
14482     case POINTER_TYPE:
14483     case REFERENCE_TYPE:
14484     case OFFSET_TYPE:
14485     case FUNCTION_TYPE:
14486     case METHOD_TYPE:
14487     case ARRAY_TYPE:
14488     case TYPENAME_TYPE:
14489     case UNBOUND_CLASS_TEMPLATE:
14490     case TYPEOF_TYPE:
14491     case DECLTYPE_TYPE:
14492     case TYPE_DECL:
14493       return tsubst (t, args, complain, in_decl);
14494 
14495     case USING_DECL:
14496       t = DECL_NAME (t);
14497       /* Fall through.  */
14498     case IDENTIFIER_NODE:
14499       if (IDENTIFIER_TYPENAME_P (t))
14500 	{
14501 	  tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14502 	  return mangle_conv_op_name_for_type (new_type);
14503 	}
14504       else
14505 	return t;
14506 
14507     case CONSTRUCTOR:
14508       /* This is handled by tsubst_copy_and_build.  */
14509       gcc_unreachable ();
14510 
14511     case VA_ARG_EXPR:
14512       {
14513 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
14514 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14515 	return build_x_va_arg (EXPR_LOCATION (t), op0, type);
14516       }
14517 
14518     case CLEANUP_POINT_EXPR:
14519       /* We shouldn't have built any of these during initial template
14520 	 generation.  Instead, they should be built during instantiation
14521 	 in response to the saved STMT_IS_FULL_EXPR_P setting.  */
14522       gcc_unreachable ();
14523 
14524     case OFFSET_REF:
14525       {
14526 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14527 	tree op0 = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
14528 	tree op1 = tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl);
14529 	r = build2 (code, type, op0, op1);
14530 	PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
14531 	if (!mark_used (TREE_OPERAND (r, 1), complain)
14532 	    && !(complain & tf_error))
14533 	  return error_mark_node;
14534 	return r;
14535       }
14536 
14537     case EXPR_PACK_EXPANSION:
14538       error ("invalid use of pack expansion expression");
14539       return error_mark_node;
14540 
14541     case NONTYPE_ARGUMENT_PACK:
14542       error ("use %<...%> to expand argument pack");
14543       return error_mark_node;
14544 
14545     case VOID_CST:
14546       gcc_checking_assert (t == void_node && VOID_TYPE_P (TREE_TYPE (t)));
14547       return t;
14548 
14549     case INTEGER_CST:
14550     case REAL_CST:
14551     case STRING_CST:
14552     case COMPLEX_CST:
14553       {
14554 	/* Instantiate any typedefs in the type.  */
14555 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
14556 	r = fold_convert (type, t);
14557 	gcc_assert (TREE_CODE (r) == code);
14558 	return r;
14559       }
14560 
14561     case PTRMEM_CST:
14562       /* These can sometimes show up in a partial instantiation, but never
14563 	 involve template parms.  */
14564       gcc_assert (!uses_template_parms (t));
14565       return t;
14566 
14567     case UNARY_LEFT_FOLD_EXPR:
14568       return tsubst_unary_left_fold (t, args, complain, in_decl);
14569     case UNARY_RIGHT_FOLD_EXPR:
14570       return tsubst_unary_right_fold (t, args, complain, in_decl);
14571     case BINARY_LEFT_FOLD_EXPR:
14572       return tsubst_binary_left_fold (t, args, complain, in_decl);
14573     case BINARY_RIGHT_FOLD_EXPR:
14574       return tsubst_binary_right_fold (t, args, complain, in_decl);
14575 
14576     default:
14577       /* We shouldn't get here, but keep going if !flag_checking.  */
14578       if (flag_checking)
14579 	gcc_unreachable ();
14580       return t;
14581     }
14582 }
14583 
14584 /* Helper function for tsubst_omp_clauses, used for instantiation of
14585    OMP_CLAUSE_DECL of clauses.  */
14586 
14587 static tree
tsubst_omp_clause_decl(tree decl,tree args,tsubst_flags_t complain,tree in_decl)14588 tsubst_omp_clause_decl (tree decl, tree args, tsubst_flags_t complain,
14589 			tree in_decl)
14590 {
14591   if (decl == NULL_TREE)
14592     return NULL_TREE;
14593 
14594   /* Handle an OpenMP array section represented as a TREE_LIST (or
14595      OMP_CLAUSE_DEPEND_KIND).  An OMP_CLAUSE_DEPEND (with a depend
14596      kind of OMP_CLAUSE_DEPEND_SINK) can also be represented as a
14597      TREE_LIST.  We can handle it exactly the same as an array section
14598      (purpose, value, and a chain), even though the nomenclature
14599      (low_bound, length, etc) is different.  */
14600   if (TREE_CODE (decl) == TREE_LIST)
14601     {
14602       tree low_bound
14603 	= tsubst_expr (TREE_PURPOSE (decl), args, complain, in_decl,
14604 		       /*integral_constant_expression_p=*/false);
14605       tree length = tsubst_expr (TREE_VALUE (decl), args, complain, in_decl,
14606 				 /*integral_constant_expression_p=*/false);
14607       tree chain = tsubst_omp_clause_decl (TREE_CHAIN (decl), args, complain,
14608 					   in_decl);
14609       if (TREE_PURPOSE (decl) == low_bound
14610 	  && TREE_VALUE (decl) == length
14611 	  && TREE_CHAIN (decl) == chain)
14612 	return decl;
14613       tree ret = tree_cons (low_bound, length, chain);
14614       OMP_CLAUSE_DEPEND_SINK_NEGATIVE (ret)
14615 	= OMP_CLAUSE_DEPEND_SINK_NEGATIVE (decl);
14616       return ret;
14617     }
14618   tree ret = tsubst_expr (decl, args, complain, in_decl,
14619 			  /*integral_constant_expression_p=*/false);
14620   /* Undo convert_from_reference tsubst_expr could have called.  */
14621   if (decl
14622       && REFERENCE_REF_P (ret)
14623       && !REFERENCE_REF_P (decl))
14624     ret = TREE_OPERAND (ret, 0);
14625   return ret;
14626 }
14627 
14628 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
14629 
14630 static tree
tsubst_omp_clauses(tree clauses,bool declare_simd,bool allow_fields,tree args,tsubst_flags_t complain,tree in_decl)14631 tsubst_omp_clauses (tree clauses, bool declare_simd, bool allow_fields,
14632 		    tree args, tsubst_flags_t complain, tree in_decl)
14633 {
14634   tree new_clauses = NULL_TREE, nc, oc;
14635   tree linear_no_step = NULL_TREE;
14636 
14637   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
14638     {
14639       nc = copy_node (oc);
14640       OMP_CLAUSE_CHAIN (nc) = new_clauses;
14641       new_clauses = nc;
14642 
14643       switch (OMP_CLAUSE_CODE (nc))
14644 	{
14645 	case OMP_CLAUSE_LASTPRIVATE:
14646 	  if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
14647 	    {
14648 	      OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
14649 	      tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
14650 			   in_decl, /*integral_constant_expression_p=*/false);
14651 	      OMP_CLAUSE_LASTPRIVATE_STMT (nc)
14652 		= pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
14653 	    }
14654 	  /* FALLTHRU */
14655 	case OMP_CLAUSE_PRIVATE:
14656 	case OMP_CLAUSE_SHARED:
14657 	case OMP_CLAUSE_FIRSTPRIVATE:
14658 	case OMP_CLAUSE_COPYIN:
14659 	case OMP_CLAUSE_COPYPRIVATE:
14660 	case OMP_CLAUSE_UNIFORM:
14661 	case OMP_CLAUSE_DEPEND:
14662 	case OMP_CLAUSE_FROM:
14663 	case OMP_CLAUSE_TO:
14664 	case OMP_CLAUSE_MAP:
14665 	case OMP_CLAUSE_USE_DEVICE_PTR:
14666 	case OMP_CLAUSE_IS_DEVICE_PTR:
14667 	  OMP_CLAUSE_DECL (nc)
14668 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
14669 				      in_decl);
14670 	  break;
14671 	case OMP_CLAUSE_IF:
14672 	case OMP_CLAUSE_NUM_THREADS:
14673 	case OMP_CLAUSE_SCHEDULE:
14674 	case OMP_CLAUSE_COLLAPSE:
14675 	case OMP_CLAUSE_FINAL:
14676 	case OMP_CLAUSE_DEVICE:
14677 	case OMP_CLAUSE_DIST_SCHEDULE:
14678 	case OMP_CLAUSE_NUM_TEAMS:
14679 	case OMP_CLAUSE_THREAD_LIMIT:
14680 	case OMP_CLAUSE_SAFELEN:
14681 	case OMP_CLAUSE_SIMDLEN:
14682 	case OMP_CLAUSE_NUM_TASKS:
14683 	case OMP_CLAUSE_GRAINSIZE:
14684 	case OMP_CLAUSE_PRIORITY:
14685 	case OMP_CLAUSE_ORDERED:
14686 	case OMP_CLAUSE_HINT:
14687 	case OMP_CLAUSE_NUM_GANGS:
14688 	case OMP_CLAUSE_NUM_WORKERS:
14689 	case OMP_CLAUSE_VECTOR_LENGTH:
14690 	case OMP_CLAUSE_WORKER:
14691 	case OMP_CLAUSE_VECTOR:
14692 	case OMP_CLAUSE_ASYNC:
14693 	case OMP_CLAUSE_WAIT:
14694 	  OMP_CLAUSE_OPERAND (nc, 0)
14695 	    = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain,
14696 			   in_decl, /*integral_constant_expression_p=*/false);
14697 	  break;
14698 	case OMP_CLAUSE_REDUCTION:
14699 	  if (OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc))
14700 	    {
14701 	      tree placeholder = OMP_CLAUSE_REDUCTION_PLACEHOLDER (oc);
14702 	      if (TREE_CODE (placeholder) == SCOPE_REF)
14703 		{
14704 		  tree scope = tsubst (TREE_OPERAND (placeholder, 0), args,
14705 				       complain, in_decl);
14706 		  OMP_CLAUSE_REDUCTION_PLACEHOLDER (nc)
14707 		    = build_qualified_name (NULL_TREE, scope,
14708 					    TREE_OPERAND (placeholder, 1),
14709 					    false);
14710 		}
14711 	      else
14712 		gcc_assert (identifier_p (placeholder));
14713 	    }
14714 	  OMP_CLAUSE_DECL (nc)
14715 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
14716 				      in_decl);
14717 	  break;
14718 	case OMP_CLAUSE_GANG:
14719 	case OMP_CLAUSE_ALIGNED:
14720 	  OMP_CLAUSE_DECL (nc)
14721 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
14722 				      in_decl);
14723 	  OMP_CLAUSE_OPERAND (nc, 1)
14724 	    = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 1), args, complain,
14725 			   in_decl, /*integral_constant_expression_p=*/false);
14726 	  break;
14727 	case OMP_CLAUSE_LINEAR:
14728 	  OMP_CLAUSE_DECL (nc)
14729 	    = tsubst_omp_clause_decl (OMP_CLAUSE_DECL (oc), args, complain,
14730 				      in_decl);
14731 	  if (OMP_CLAUSE_LINEAR_STEP (oc) == NULL_TREE)
14732 	    {
14733 	      gcc_assert (!linear_no_step);
14734 	      linear_no_step = nc;
14735 	    }
14736 	  else if (OMP_CLAUSE_LINEAR_VARIABLE_STRIDE (oc))
14737 	    OMP_CLAUSE_LINEAR_STEP (nc)
14738 	      = tsubst_omp_clause_decl (OMP_CLAUSE_LINEAR_STEP (oc), args,
14739 					complain, in_decl);
14740 	  else
14741 	    OMP_CLAUSE_LINEAR_STEP (nc)
14742 	      = tsubst_expr (OMP_CLAUSE_LINEAR_STEP (oc), args, complain,
14743 			     in_decl,
14744 			     /*integral_constant_expression_p=*/false);
14745 	  break;
14746 	case OMP_CLAUSE_NOWAIT:
14747 	case OMP_CLAUSE_DEFAULT:
14748 	case OMP_CLAUSE_UNTIED:
14749 	case OMP_CLAUSE_MERGEABLE:
14750 	case OMP_CLAUSE_INBRANCH:
14751 	case OMP_CLAUSE_NOTINBRANCH:
14752 	case OMP_CLAUSE_PROC_BIND:
14753 	case OMP_CLAUSE_FOR:
14754 	case OMP_CLAUSE_PARALLEL:
14755 	case OMP_CLAUSE_SECTIONS:
14756 	case OMP_CLAUSE_TASKGROUP:
14757 	case OMP_CLAUSE_NOGROUP:
14758 	case OMP_CLAUSE_THREADS:
14759 	case OMP_CLAUSE_SIMD:
14760 	case OMP_CLAUSE_DEFAULTMAP:
14761 	case OMP_CLAUSE_INDEPENDENT:
14762 	case OMP_CLAUSE_AUTO:
14763 	case OMP_CLAUSE_SEQ:
14764 	  break;
14765 	case OMP_CLAUSE_TILE:
14766 	  {
14767 	    tree lnc, loc;
14768 	    for (lnc = OMP_CLAUSE_TILE_LIST (nc),
14769 		   loc = OMP_CLAUSE_TILE_LIST (oc);
14770 		 loc;
14771 		 loc = TREE_CHAIN (loc), lnc = TREE_CHAIN (lnc))
14772 	      {
14773 		TREE_VALUE (lnc) = tsubst_expr (TREE_VALUE (loc), args,
14774 						complain, in_decl, false);
14775 	      }
14776 	  }
14777 	  break;
14778 	default:
14779 	  gcc_unreachable ();
14780 	}
14781       if (allow_fields)
14782 	switch (OMP_CLAUSE_CODE (nc))
14783 	  {
14784 	  case OMP_CLAUSE_SHARED:
14785 	  case OMP_CLAUSE_PRIVATE:
14786 	  case OMP_CLAUSE_FIRSTPRIVATE:
14787 	  case OMP_CLAUSE_LASTPRIVATE:
14788 	  case OMP_CLAUSE_COPYPRIVATE:
14789 	  case OMP_CLAUSE_LINEAR:
14790 	  case OMP_CLAUSE_REDUCTION:
14791 	  case OMP_CLAUSE_USE_DEVICE_PTR:
14792 	  case OMP_CLAUSE_IS_DEVICE_PTR:
14793 	    /* tsubst_expr on SCOPE_REF results in returning
14794 	       finish_non_static_data_member result.  Undo that here.  */
14795 	    if (TREE_CODE (OMP_CLAUSE_DECL (oc)) == SCOPE_REF
14796 		&& (TREE_CODE (TREE_OPERAND (OMP_CLAUSE_DECL (oc), 1))
14797 		    == IDENTIFIER_NODE))
14798 	      {
14799 		tree t = OMP_CLAUSE_DECL (nc);
14800 		tree v = t;
14801 		while (v)
14802 		  switch (TREE_CODE (v))
14803 		    {
14804 		    case COMPONENT_REF:
14805 		    case MEM_REF:
14806 		    case INDIRECT_REF:
14807 		    CASE_CONVERT:
14808 		    case POINTER_PLUS_EXPR:
14809 		      v = TREE_OPERAND (v, 0);
14810 		      continue;
14811 		    case PARM_DECL:
14812 		      if (DECL_CONTEXT (v) == current_function_decl
14813 			  && DECL_ARTIFICIAL (v)
14814 			  && DECL_NAME (v) == this_identifier)
14815 			OMP_CLAUSE_DECL (nc) = TREE_OPERAND (t, 1);
14816 		      /* FALLTHRU */
14817 		    default:
14818 		      v = NULL_TREE;
14819 		      break;
14820 		    }
14821 	      }
14822 	    else if (VAR_P (OMP_CLAUSE_DECL (oc))
14823 		     && DECL_HAS_VALUE_EXPR_P (OMP_CLAUSE_DECL (oc))
14824 		     && DECL_ARTIFICIAL (OMP_CLAUSE_DECL (oc))
14825 		     && DECL_LANG_SPECIFIC (OMP_CLAUSE_DECL (oc))
14826 		     && DECL_OMP_PRIVATIZED_MEMBER (OMP_CLAUSE_DECL (oc)))
14827 	      {
14828 		tree decl = OMP_CLAUSE_DECL (nc);
14829 		if (VAR_P (decl))
14830 		  {
14831 		    if (!DECL_LANG_SPECIFIC (decl))
14832 		      retrofit_lang_decl (decl);
14833 		    DECL_OMP_PRIVATIZED_MEMBER (decl) = 1;
14834 		  }
14835 	      }
14836 	    break;
14837 	  default:
14838 	    break;
14839 	  }
14840     }
14841 
14842   new_clauses = nreverse (new_clauses);
14843   if (!declare_simd)
14844     {
14845       new_clauses = finish_omp_clauses (new_clauses, allow_fields);
14846       if (linear_no_step)
14847 	for (nc = new_clauses; nc; nc = OMP_CLAUSE_CHAIN (nc))
14848 	  if (nc == linear_no_step)
14849 	    {
14850 	      OMP_CLAUSE_LINEAR_STEP (nc) = NULL_TREE;
14851 	      break;
14852 	    }
14853     }
14854   return new_clauses;
14855 }
14856 
14857 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
14858 
14859 static tree
tsubst_copy_asm_operands(tree t,tree args,tsubst_flags_t complain,tree in_decl)14860 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
14861 			  tree in_decl)
14862 {
14863 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
14864 
14865   tree purpose, value, chain;
14866 
14867   if (t == NULL)
14868     return t;
14869 
14870   if (TREE_CODE (t) != TREE_LIST)
14871     return tsubst_copy_and_build (t, args, complain, in_decl,
14872 				  /*function_p=*/false,
14873 				  /*integral_constant_expression_p=*/false);
14874 
14875   if (t == void_list_node)
14876     return t;
14877 
14878   purpose = TREE_PURPOSE (t);
14879   if (purpose)
14880     purpose = RECUR (purpose);
14881   value = TREE_VALUE (t);
14882   if (value)
14883     {
14884       if (TREE_CODE (value) != LABEL_DECL)
14885 	value = RECUR (value);
14886       else
14887 	{
14888 	  value = lookup_label (DECL_NAME (value));
14889 	  gcc_assert (TREE_CODE (value) == LABEL_DECL);
14890 	  TREE_USED (value) = 1;
14891 	}
14892     }
14893   chain = TREE_CHAIN (t);
14894   if (chain && chain != void_type_node)
14895     chain = RECUR (chain);
14896   return tree_cons (purpose, value, chain);
14897 #undef RECUR
14898 }
14899 
14900 /* Used to temporarily communicate the list of #pragma omp parallel
14901    clauses to #pragma omp for instantiation if they are combined
14902    together.  */
14903 
14904 static tree *omp_parallel_combined_clauses;
14905 
14906 /* Substitute one OMP_FOR iterator.  */
14907 
14908 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)14909 tsubst_omp_for_iterator (tree t, int i, tree declv, tree orig_declv,
14910 			 tree initv, tree condv, tree incrv, tree *clauses,
14911 			 tree args, tsubst_flags_t complain, tree in_decl,
14912 			 bool integral_constant_expression_p)
14913 {
14914 #define RECUR(NODE)				\
14915   tsubst_expr ((NODE), args, complain, in_decl,	\
14916 	       integral_constant_expression_p)
14917   tree decl, init, cond, incr;
14918 
14919   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
14920   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
14921 
14922   if (orig_declv && OMP_FOR_ORIG_DECLS (t))
14923     {
14924       tree o = TREE_VEC_ELT (OMP_FOR_ORIG_DECLS (t), i);
14925       TREE_VEC_ELT (orig_declv, i) = RECUR (o);
14926     }
14927 
14928   decl = TREE_OPERAND (init, 0);
14929   init = TREE_OPERAND (init, 1);
14930   tree decl_expr = NULL_TREE;
14931   if (init && TREE_CODE (init) == DECL_EXPR)
14932     {
14933       /* We need to jump through some hoops to handle declarations in the
14934 	 for-init-statement, since we might need to handle auto deduction,
14935 	 but we need to keep control of initialization.  */
14936       decl_expr = init;
14937       init = DECL_INITIAL (DECL_EXPR_DECL (init));
14938       decl = tsubst_decl (decl, args, complain);
14939     }
14940   else
14941     {
14942       if (TREE_CODE (decl) == SCOPE_REF)
14943 	{
14944 	  decl = RECUR (decl);
14945 	  if (TREE_CODE (decl) == COMPONENT_REF)
14946 	    {
14947 	      tree v = decl;
14948 	      while (v)
14949 		switch (TREE_CODE (v))
14950 		  {
14951 		  case COMPONENT_REF:
14952 		  case MEM_REF:
14953 		  case INDIRECT_REF:
14954 		  CASE_CONVERT:
14955 		  case POINTER_PLUS_EXPR:
14956 		    v = TREE_OPERAND (v, 0);
14957 		    continue;
14958 		  case PARM_DECL:
14959 		    if (DECL_CONTEXT (v) == current_function_decl
14960 			&& DECL_ARTIFICIAL (v)
14961 			&& DECL_NAME (v) == this_identifier)
14962 		      {
14963 			decl = TREE_OPERAND (decl, 1);
14964 			decl = omp_privatize_field (decl, false);
14965 		      }
14966 		    /* FALLTHRU */
14967 		  default:
14968 		    v = NULL_TREE;
14969 		    break;
14970 		  }
14971 	    }
14972 	}
14973       else
14974 	decl = RECUR (decl);
14975     }
14976   init = RECUR (init);
14977 
14978   tree auto_node = type_uses_auto (TREE_TYPE (decl));
14979   if (auto_node && init)
14980     TREE_TYPE (decl)
14981       = do_auto_deduction (TREE_TYPE (decl), init, auto_node);
14982 
14983   gcc_assert (!type_dependent_expression_p (decl));
14984 
14985   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
14986     {
14987       if (decl_expr)
14988 	{
14989 	  /* Declare the variable, but don't let that initialize it.  */
14990 	  tree init_sav = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
14991 	  DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL_TREE;
14992 	  RECUR (decl_expr);
14993 	  DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init_sav;
14994 	}
14995 
14996       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
14997       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
14998       if (TREE_CODE (incr) == MODIFY_EXPR)
14999 	{
15000 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
15001 	  tree rhs = RECUR (TREE_OPERAND (incr, 1));
15002 	  incr = build_x_modify_expr (EXPR_LOCATION (incr), lhs,
15003 				      NOP_EXPR, rhs, complain);
15004 	}
15005       else
15006 	incr = RECUR (incr);
15007       TREE_VEC_ELT (declv, i) = decl;
15008       TREE_VEC_ELT (initv, i) = init;
15009       TREE_VEC_ELT (condv, i) = cond;
15010       TREE_VEC_ELT (incrv, i) = incr;
15011       return;
15012     }
15013 
15014   if (decl_expr)
15015     {
15016       /* Declare and initialize the variable.  */
15017       RECUR (decl_expr);
15018       init = NULL_TREE;
15019     }
15020   else if (init)
15021     {
15022       tree *pc;
15023       int j;
15024       for (j = (omp_parallel_combined_clauses == NULL ? 1 : 0); j < 2; j++)
15025 	{
15026 	  for (pc = j ? clauses : omp_parallel_combined_clauses; *pc; )
15027 	    {
15028 	      if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_PRIVATE
15029 		  && OMP_CLAUSE_DECL (*pc) == decl)
15030 		break;
15031 	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_LASTPRIVATE
15032 		       && OMP_CLAUSE_DECL (*pc) == decl)
15033 		{
15034 		  if (j)
15035 		    break;
15036 		  /* Move lastprivate (decl) clause to OMP_FOR_CLAUSES.  */
15037 		  tree c = *pc;
15038 		  *pc = OMP_CLAUSE_CHAIN (c);
15039 		  OMP_CLAUSE_CHAIN (c) = *clauses;
15040 		  *clauses = c;
15041 		}
15042 	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_FIRSTPRIVATE
15043 		       && OMP_CLAUSE_DECL (*pc) == decl)
15044 		{
15045 		  error ("iteration variable %qD should not be firstprivate",
15046 			 decl);
15047 		  *pc = OMP_CLAUSE_CHAIN (*pc);
15048 		}
15049 	      else if (OMP_CLAUSE_CODE (*pc) == OMP_CLAUSE_REDUCTION
15050 		       && OMP_CLAUSE_DECL (*pc) == decl)
15051 		{
15052 		  error ("iteration variable %qD should not be reduction",
15053 			 decl);
15054 		  *pc = OMP_CLAUSE_CHAIN (*pc);
15055 		}
15056 	      else
15057 		pc = &OMP_CLAUSE_CHAIN (*pc);
15058 	    }
15059 	  if (*pc)
15060 	    break;
15061 	}
15062       if (*pc == NULL_TREE)
15063 	{
15064 	  tree c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
15065 	  OMP_CLAUSE_DECL (c) = decl;
15066 	  c = finish_omp_clauses (c, true);
15067 	  if (c)
15068 	    {
15069 	      OMP_CLAUSE_CHAIN (c) = *clauses;
15070 	      *clauses = c;
15071 	    }
15072 	}
15073     }
15074   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
15075   if (COMPARISON_CLASS_P (cond))
15076     {
15077       tree op0 = RECUR (TREE_OPERAND (cond, 0));
15078       tree op1 = RECUR (TREE_OPERAND (cond, 1));
15079       cond = build2 (TREE_CODE (cond), boolean_type_node, op0, op1);
15080     }
15081   else
15082     cond = RECUR (cond);
15083   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
15084   switch (TREE_CODE (incr))
15085     {
15086     case PREINCREMENT_EXPR:
15087     case PREDECREMENT_EXPR:
15088     case POSTINCREMENT_EXPR:
15089     case POSTDECREMENT_EXPR:
15090       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
15091 		     RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
15092       break;
15093     case MODIFY_EXPR:
15094       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
15095 	  || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
15096 	{
15097 	  tree rhs = TREE_OPERAND (incr, 1);
15098 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
15099 	  tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
15100 	  tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
15101 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
15102 			 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
15103 				 rhs0, rhs1));
15104 	}
15105       else
15106 	incr = RECUR (incr);
15107       break;
15108     case MODOP_EXPR:
15109       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
15110 	  || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
15111 	{
15112 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
15113 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
15114 			 build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
15115 				 TREE_TYPE (decl), lhs,
15116 				 RECUR (TREE_OPERAND (incr, 2))));
15117 	}
15118       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
15119 	       && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
15120 		   || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
15121 	{
15122 	  tree rhs = TREE_OPERAND (incr, 2);
15123 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
15124 	  tree rhs0 = RECUR (TREE_OPERAND (rhs, 0));
15125 	  tree rhs1 = RECUR (TREE_OPERAND (rhs, 1));
15126 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
15127 			 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
15128 				 rhs0, rhs1));
15129 	}
15130       else
15131 	incr = RECUR (incr);
15132       break;
15133     default:
15134       incr = RECUR (incr);
15135       break;
15136     }
15137 
15138   TREE_VEC_ELT (declv, i) = decl;
15139   TREE_VEC_ELT (initv, i) = init;
15140   TREE_VEC_ELT (condv, i) = cond;
15141   TREE_VEC_ELT (incrv, i) = incr;
15142 #undef RECUR
15143 }
15144 
15145 /* Helper function of tsubst_expr, find OMP_TEAMS inside
15146    of OMP_TARGET's body.  */
15147 
15148 static tree
tsubst_find_omp_teams(tree * tp,int * walk_subtrees,void *)15149 tsubst_find_omp_teams (tree *tp, int *walk_subtrees, void *)
15150 {
15151   *walk_subtrees = 0;
15152   switch (TREE_CODE (*tp))
15153     {
15154     case OMP_TEAMS:
15155       return *tp;
15156     case BIND_EXPR:
15157     case STATEMENT_LIST:
15158       *walk_subtrees = 1;
15159       break;
15160     default:
15161       break;
15162     }
15163   return NULL_TREE;
15164 }
15165 
15166 /* Like tsubst_copy for expressions, etc. but also does semantic
15167    processing.  */
15168 
15169 tree
tsubst_expr(tree t,tree args,tsubst_flags_t complain,tree in_decl,bool integral_constant_expression_p)15170 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
15171 	     bool integral_constant_expression_p)
15172 {
15173 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
15174 #define RECUR(NODE)				\
15175   tsubst_expr ((NODE), args, complain, in_decl,	\
15176 	       integral_constant_expression_p)
15177 
15178   tree stmt, tmp;
15179   tree r;
15180   location_t loc;
15181 
15182   if (t == NULL_TREE || t == error_mark_node)
15183     return t;
15184 
15185   loc = input_location;
15186   if (EXPR_HAS_LOCATION (t))
15187     input_location = EXPR_LOCATION (t);
15188   if (STATEMENT_CODE_P (TREE_CODE (t)))
15189     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
15190 
15191   switch (TREE_CODE (t))
15192     {
15193     case STATEMENT_LIST:
15194       {
15195 	tree_stmt_iterator i;
15196 	for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
15197 	  RECUR (tsi_stmt (i));
15198 	break;
15199       }
15200 
15201     case CTOR_INITIALIZER:
15202       finish_mem_initializers (tsubst_initializer_list
15203 			       (TREE_OPERAND (t, 0), args));
15204       break;
15205 
15206     case RETURN_EXPR:
15207       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
15208       break;
15209 
15210     case EXPR_STMT:
15211       tmp = RECUR (EXPR_STMT_EXPR (t));
15212       if (EXPR_STMT_STMT_EXPR_RESULT (t))
15213 	finish_stmt_expr_expr (tmp, cur_stmt_expr);
15214       else
15215 	finish_expr_stmt (tmp);
15216       break;
15217 
15218     case USING_STMT:
15219       do_using_directive (USING_STMT_NAMESPACE (t));
15220       break;
15221 
15222     case DECL_EXPR:
15223       {
15224 	tree decl, pattern_decl;
15225 	tree init;
15226 
15227 	pattern_decl = decl = DECL_EXPR_DECL (t);
15228 	if (TREE_CODE (decl) == LABEL_DECL)
15229 	  finish_label_decl (DECL_NAME (decl));
15230 	else if (TREE_CODE (decl) == USING_DECL)
15231 	  {
15232 	    tree scope = USING_DECL_SCOPE (decl);
15233 	    tree name = DECL_NAME (decl);
15234 	    tree decl;
15235 
15236 	    scope = tsubst (scope, args, complain, in_decl);
15237 	    decl = lookup_qualified_name (scope, name,
15238 					  /*is_type_p=*/false,
15239 					  /*complain=*/false);
15240 	    if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
15241 	      qualified_name_lookup_error (scope, name, decl, input_location);
15242 	    else
15243 	      do_local_using_decl (decl, scope, name);
15244 	  }
15245 	else if (DECL_PACK_P (decl))
15246 	  {
15247 	    /* Don't build up decls for a variadic capture proxy, we'll
15248 	       instantiate the elements directly as needed.  */
15249 	    break;
15250 	  }
15251 	else
15252 	  {
15253 	    init = DECL_INITIAL (decl);
15254 	    decl = tsubst (decl, args, complain, in_decl);
15255 	    if (decl != error_mark_node)
15256 	      {
15257 		/* By marking the declaration as instantiated, we avoid
15258 		   trying to instantiate it.  Since instantiate_decl can't
15259 		   handle local variables, and since we've already done
15260 		   all that needs to be done, that's the right thing to
15261 		   do.  */
15262 		if (VAR_P (decl))
15263 		  DECL_TEMPLATE_INSTANTIATED (decl) = 1;
15264 		if (VAR_P (decl)
15265 		    && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
15266 		  /* Anonymous aggregates are a special case.  */
15267 		  finish_anon_union (decl);
15268 		else if (is_capture_proxy (DECL_EXPR_DECL (t)))
15269 		  {
15270 		    DECL_CONTEXT (decl) = current_function_decl;
15271 		    if (DECL_NAME (decl) == this_identifier)
15272 		      {
15273 			tree lam = DECL_CONTEXT (current_function_decl);
15274 			lam = CLASSTYPE_LAMBDA_EXPR (lam);
15275 			LAMBDA_EXPR_THIS_CAPTURE (lam) = decl;
15276 		      }
15277 		    insert_capture_proxy (decl);
15278 		  }
15279 		else if (DECL_IMPLICIT_TYPEDEF_P (t))
15280 		  /* We already did a pushtag.  */;
15281 		else if (TREE_CODE (decl) == FUNCTION_DECL
15282 			 && DECL_OMP_DECLARE_REDUCTION_P (decl)
15283 			 && DECL_FUNCTION_SCOPE_P (pattern_decl))
15284 		  {
15285 		    DECL_CONTEXT (decl) = NULL_TREE;
15286 		    pushdecl (decl);
15287 		    DECL_CONTEXT (decl) = current_function_decl;
15288 		    cp_check_omp_declare_reduction (decl);
15289 		  }
15290 		else
15291 		  {
15292 		    int const_init = false;
15293 		    maybe_push_decl (decl);
15294 		    if (VAR_P (decl)
15295 			&& DECL_PRETTY_FUNCTION_P (decl))
15296 		      {
15297 			/* For __PRETTY_FUNCTION__ we have to adjust the
15298 			   initializer.  */
15299 			const char *const name
15300 			  = cxx_printable_name (current_function_decl, 2);
15301 			init = cp_fname_init (name, &TREE_TYPE (decl));
15302 		      }
15303 		    else
15304 		      init = tsubst_init (init, decl, args, complain, in_decl);
15305 
15306 		    if (VAR_P (decl))
15307 		      const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
15308 				    (pattern_decl));
15309 		    cp_finish_decl (decl, init, const_init, NULL_TREE, 0);
15310 		  }
15311 	      }
15312 	  }
15313 
15314 	break;
15315       }
15316 
15317     case FOR_STMT:
15318       stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
15319       RECUR (FOR_INIT_STMT (t));
15320       finish_for_init_stmt (stmt);
15321       tmp = RECUR (FOR_COND (t));
15322       finish_for_cond (tmp, stmt, false);
15323       tmp = RECUR (FOR_EXPR (t));
15324       finish_for_expr (tmp, stmt);
15325       RECUR (FOR_BODY (t));
15326       finish_for_stmt (stmt);
15327       break;
15328 
15329     case RANGE_FOR_STMT:
15330       {
15331         tree decl, expr;
15332         stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
15333         decl = RANGE_FOR_DECL (t);
15334         decl = tsubst (decl, args, complain, in_decl);
15335         maybe_push_decl (decl);
15336         expr = RECUR (RANGE_FOR_EXPR (t));
15337         stmt = cp_convert_range_for (stmt, decl, expr, RANGE_FOR_IVDEP (t));
15338         RECUR (RANGE_FOR_BODY (t));
15339         finish_for_stmt (stmt);
15340       }
15341       break;
15342 
15343     case WHILE_STMT:
15344       stmt = begin_while_stmt ();
15345       tmp = RECUR (WHILE_COND (t));
15346       finish_while_stmt_cond (tmp, stmt, false);
15347       RECUR (WHILE_BODY (t));
15348       finish_while_stmt (stmt);
15349       break;
15350 
15351     case DO_STMT:
15352       stmt = begin_do_stmt ();
15353       RECUR (DO_BODY (t));
15354       finish_do_body (stmt);
15355       tmp = RECUR (DO_COND (t));
15356       finish_do_stmt (tmp, stmt, false);
15357       break;
15358 
15359     case IF_STMT:
15360       stmt = begin_if_stmt ();
15361       tmp = RECUR (IF_COND (t));
15362       finish_if_stmt_cond (tmp, stmt);
15363       RECUR (THEN_CLAUSE (t));
15364       finish_then_clause (stmt);
15365 
15366       if (ELSE_CLAUSE (t))
15367 	{
15368 	  begin_else_clause (stmt);
15369 	  RECUR (ELSE_CLAUSE (t));
15370 	  finish_else_clause (stmt);
15371 	}
15372 
15373       finish_if_stmt (stmt);
15374       break;
15375 
15376     case BIND_EXPR:
15377       if (BIND_EXPR_BODY_BLOCK (t))
15378 	stmt = begin_function_body ();
15379       else
15380 	stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
15381 				    ? BCS_TRY_BLOCK : 0);
15382 
15383       RECUR (BIND_EXPR_BODY (t));
15384 
15385       if (BIND_EXPR_BODY_BLOCK (t))
15386 	finish_function_body (stmt);
15387       else
15388 	finish_compound_stmt (stmt);
15389       break;
15390 
15391     case BREAK_STMT:
15392       finish_break_stmt ();
15393       break;
15394 
15395     case CONTINUE_STMT:
15396       finish_continue_stmt ();
15397       break;
15398 
15399     case SWITCH_STMT:
15400       stmt = begin_switch_stmt ();
15401       tmp = RECUR (SWITCH_STMT_COND (t));
15402       finish_switch_cond (tmp, stmt);
15403       RECUR (SWITCH_STMT_BODY (t));
15404       finish_switch_stmt (stmt);
15405       break;
15406 
15407     case CASE_LABEL_EXPR:
15408       {
15409 	tree low = RECUR (CASE_LOW (t));
15410 	tree high = RECUR (CASE_HIGH (t));
15411 	finish_case_label (EXPR_LOCATION (t), low, high);
15412       }
15413       break;
15414 
15415     case LABEL_EXPR:
15416       {
15417 	tree decl = LABEL_EXPR_LABEL (t);
15418 	tree label;
15419 
15420 	label = finish_label_stmt (DECL_NAME (decl));
15421 	if (DECL_ATTRIBUTES (decl) != NULL_TREE)
15422 	  cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
15423       }
15424       break;
15425 
15426     case GOTO_EXPR:
15427       tmp = GOTO_DESTINATION (t);
15428       if (TREE_CODE (tmp) != LABEL_DECL)
15429 	/* Computed goto's must be tsubst'd into.  On the other hand,
15430 	   non-computed gotos must not be; the identifier in question
15431 	   will have no binding.  */
15432 	tmp = RECUR (tmp);
15433       else
15434 	tmp = DECL_NAME (tmp);
15435       finish_goto_stmt (tmp);
15436       break;
15437 
15438     case ASM_EXPR:
15439       {
15440 	tree string = RECUR (ASM_STRING (t));
15441 	tree outputs = tsubst_copy_asm_operands (ASM_OUTPUTS (t), args,
15442 						 complain, in_decl);
15443 	tree inputs = tsubst_copy_asm_operands (ASM_INPUTS (t), args,
15444 						complain, in_decl);
15445 	tree clobbers = tsubst_copy_asm_operands (ASM_CLOBBERS (t), args,
15446 	 					  complain, in_decl);
15447 	tree labels = tsubst_copy_asm_operands (ASM_LABELS (t), args,
15448 						complain, in_decl);
15449 	tmp = finish_asm_stmt (ASM_VOLATILE_P (t), string, outputs, inputs,
15450 			       clobbers, labels);
15451 	tree asm_expr = tmp;
15452 	if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
15453 	  asm_expr = TREE_OPERAND (asm_expr, 0);
15454 	ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
15455       }
15456       break;
15457 
15458     case TRY_BLOCK:
15459       if (CLEANUP_P (t))
15460 	{
15461 	  stmt = begin_try_block ();
15462 	  RECUR (TRY_STMTS (t));
15463 	  finish_cleanup_try_block (stmt);
15464 	  finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
15465 	}
15466       else
15467 	{
15468 	  tree compound_stmt = NULL_TREE;
15469 
15470 	  if (FN_TRY_BLOCK_P (t))
15471 	    stmt = begin_function_try_block (&compound_stmt);
15472 	  else
15473 	    stmt = begin_try_block ();
15474 
15475 	  RECUR (TRY_STMTS (t));
15476 
15477 	  if (FN_TRY_BLOCK_P (t))
15478 	    finish_function_try_block (stmt);
15479 	  else
15480 	    finish_try_block (stmt);
15481 
15482 	  RECUR (TRY_HANDLERS (t));
15483 	  if (FN_TRY_BLOCK_P (t))
15484 	    finish_function_handler_sequence (stmt, compound_stmt);
15485 	  else
15486 	    finish_handler_sequence (stmt);
15487 	}
15488       break;
15489 
15490     case HANDLER:
15491       {
15492 	tree decl = HANDLER_PARMS (t);
15493 
15494 	if (decl)
15495 	  {
15496 	    decl = tsubst (decl, args, complain, in_decl);
15497 	    /* Prevent instantiate_decl from trying to instantiate
15498 	       this variable.  We've already done all that needs to be
15499 	       done.  */
15500 	    if (decl != error_mark_node)
15501 	      DECL_TEMPLATE_INSTANTIATED (decl) = 1;
15502 	  }
15503 	stmt = begin_handler ();
15504 	finish_handler_parms (decl, stmt);
15505 	RECUR (HANDLER_BODY (t));
15506 	finish_handler (stmt);
15507       }
15508       break;
15509 
15510     case TAG_DEFN:
15511       tmp = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
15512       if (CLASS_TYPE_P (tmp))
15513 	{
15514 	  /* Local classes are not independent templates; they are
15515 	     instantiated along with their containing function.  And this
15516 	     way we don't have to deal with pushing out of one local class
15517 	     to instantiate a member of another local class.  */
15518 	  tree fn;
15519 	  /* Closures are handled by the LAMBDA_EXPR.  */
15520 	  gcc_assert (!LAMBDA_TYPE_P (TREE_TYPE (t)));
15521 	  complete_type (tmp);
15522 	  for (fn = TYPE_METHODS (tmp); fn; fn = DECL_CHAIN (fn))
15523 	    if (!DECL_ARTIFICIAL (fn))
15524 	      instantiate_decl (fn, /*defer_ok*/0, /*expl_inst_class*/false);
15525 	}
15526       break;
15527 
15528     case STATIC_ASSERT:
15529       {
15530 	tree condition;
15531 
15532 	++c_inhibit_evaluation_warnings;
15533         condition =
15534           tsubst_expr (STATIC_ASSERT_CONDITION (t),
15535                        args,
15536                        complain, in_decl,
15537                        /*integral_constant_expression_p=*/true);
15538 	--c_inhibit_evaluation_warnings;
15539 
15540         finish_static_assert (condition,
15541                               STATIC_ASSERT_MESSAGE (t),
15542                               STATIC_ASSERT_SOURCE_LOCATION (t),
15543                               /*member_p=*/false);
15544       }
15545       break;
15546 
15547     case OACC_KERNELS:
15548     case OACC_PARALLEL:
15549       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), false, false, args, complain,
15550 				in_decl);
15551       stmt = begin_omp_parallel ();
15552       RECUR (OMP_BODY (t));
15553       finish_omp_construct (TREE_CODE (t), stmt, tmp);
15554       break;
15555 
15556     case OMP_PARALLEL:
15557       r = push_omp_privatization_clauses (OMP_PARALLEL_COMBINED (t));
15558       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t), false, true,
15559 				args, complain, in_decl);
15560       if (OMP_PARALLEL_COMBINED (t))
15561 	omp_parallel_combined_clauses = &tmp;
15562       stmt = begin_omp_parallel ();
15563       RECUR (OMP_PARALLEL_BODY (t));
15564       gcc_assert (omp_parallel_combined_clauses == NULL);
15565       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
15566 	= OMP_PARALLEL_COMBINED (t);
15567       pop_omp_privatization_clauses (r);
15568       break;
15569 
15570     case OMP_TASK:
15571       r = push_omp_privatization_clauses (false);
15572       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t), false, true,
15573 				args, complain, in_decl);
15574       stmt = begin_omp_task ();
15575       RECUR (OMP_TASK_BODY (t));
15576       finish_omp_task (tmp, stmt);
15577       pop_omp_privatization_clauses (r);
15578       break;
15579 
15580     case OMP_FOR:
15581     case OMP_SIMD:
15582     case CILK_SIMD:
15583     case CILK_FOR:
15584     case OMP_DISTRIBUTE:
15585     case OMP_TASKLOOP:
15586     case OACC_LOOP:
15587       {
15588 	tree clauses, body, pre_body;
15589 	tree declv = NULL_TREE, initv = NULL_TREE, condv = NULL_TREE;
15590 	tree orig_declv = NULL_TREE;
15591 	tree incrv = NULL_TREE;
15592 	int i;
15593 
15594 	r = push_omp_privatization_clauses (OMP_FOR_INIT (t) == NULL_TREE);
15595 	clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t), false,
15596 				      TREE_CODE (t) != OACC_LOOP,
15597 				      args, complain, in_decl);
15598 	if (OMP_FOR_INIT (t) != NULL_TREE)
15599 	  {
15600 	    declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
15601 	    if (OMP_FOR_ORIG_DECLS (t))
15602 	      orig_declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
15603 	    initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
15604 	    condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
15605 	    incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
15606 	  }
15607 
15608 	stmt = begin_omp_structured_block ();
15609 
15610 	pre_body = push_stmt_list ();
15611 	RECUR (OMP_FOR_PRE_BODY (t));
15612 	pre_body = pop_stmt_list (pre_body);
15613 
15614 	if (OMP_FOR_INIT (t) != NULL_TREE)
15615 	  for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
15616 	    tsubst_omp_for_iterator (t, i, declv, orig_declv, initv, condv,
15617 				     incrv, &clauses, args, complain, in_decl,
15618 				     integral_constant_expression_p);
15619 	omp_parallel_combined_clauses = NULL;
15620 
15621 	body = push_stmt_list ();
15622 	RECUR (OMP_FOR_BODY (t));
15623 	body = pop_stmt_list (body);
15624 
15625 	if (OMP_FOR_INIT (t) != NULL_TREE)
15626 	  t = finish_omp_for (EXPR_LOCATION (t), TREE_CODE (t), declv,
15627 			      orig_declv, initv, condv, incrv, body, pre_body,
15628 			      NULL, clauses);
15629 	else
15630 	  {
15631 	    t = make_node (TREE_CODE (t));
15632 	    TREE_TYPE (t) = void_type_node;
15633 	    OMP_FOR_BODY (t) = body;
15634 	    OMP_FOR_PRE_BODY (t) = pre_body;
15635 	    OMP_FOR_CLAUSES (t) = clauses;
15636 	    SET_EXPR_LOCATION (t, EXPR_LOCATION (t));
15637 	    add_stmt (t);
15638 	  }
15639 
15640 	add_stmt (finish_omp_structured_block (stmt));
15641 	pop_omp_privatization_clauses (r);
15642       }
15643       break;
15644 
15645     case OMP_SECTIONS:
15646       omp_parallel_combined_clauses = NULL;
15647       /* FALLTHRU */
15648     case OMP_SINGLE:
15649     case OMP_TEAMS:
15650     case OMP_CRITICAL:
15651       r = push_omp_privatization_clauses (TREE_CODE (t) == OMP_TEAMS
15652 					  && OMP_TEAMS_COMBINED (t));
15653       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), false, true,
15654 				args, complain, in_decl);
15655       stmt = push_stmt_list ();
15656       RECUR (OMP_BODY (t));
15657       stmt = pop_stmt_list (stmt);
15658 
15659       t = copy_node (t);
15660       OMP_BODY (t) = stmt;
15661       OMP_CLAUSES (t) = tmp;
15662       add_stmt (t);
15663       pop_omp_privatization_clauses (r);
15664       break;
15665 
15666     case OACC_DATA:
15667     case OMP_TARGET_DATA:
15668     case OMP_TARGET:
15669       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), false,
15670 				TREE_CODE (t) != OACC_DATA,
15671 				args, complain, in_decl);
15672       keep_next_level (true);
15673       stmt = begin_omp_structured_block ();
15674 
15675       RECUR (OMP_BODY (t));
15676       stmt = finish_omp_structured_block (stmt);
15677 
15678       t = copy_node (t);
15679       OMP_BODY (t) = stmt;
15680       OMP_CLAUSES (t) = tmp;
15681       if (TREE_CODE (t) == OMP_TARGET && OMP_TARGET_COMBINED (t))
15682 	{
15683 	  tree teams = cp_walk_tree (&stmt, tsubst_find_omp_teams, NULL, NULL);
15684 	  if (teams)
15685 	    {
15686 	      /* For combined target teams, ensure the num_teams and
15687 		 thread_limit clause expressions are evaluated on the host,
15688 		 before entering the target construct.  */
15689 	      tree c;
15690 	      for (c = OMP_TEAMS_CLAUSES (teams);
15691 		   c; c = OMP_CLAUSE_CHAIN (c))
15692 		if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_NUM_TEAMS
15693 		     || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_THREAD_LIMIT)
15694 		    && TREE_CODE (OMP_CLAUSE_OPERAND (c, 0)) != INTEGER_CST)
15695 		  {
15696 		    tree expr = OMP_CLAUSE_OPERAND (c, 0);
15697 		    expr = force_target_expr (TREE_TYPE (expr), expr, tf_none);
15698 		    if (expr == error_mark_node)
15699 		      continue;
15700 		    tmp = TARGET_EXPR_SLOT (expr);
15701 		    add_stmt (expr);
15702 		    OMP_CLAUSE_OPERAND (c, 0) = expr;
15703 		    tree tc = build_omp_clause (OMP_CLAUSE_LOCATION (c),
15704 						OMP_CLAUSE_FIRSTPRIVATE);
15705 		    OMP_CLAUSE_DECL (tc) = tmp;
15706 		    OMP_CLAUSE_CHAIN (tc) = OMP_TARGET_CLAUSES (t);
15707 		    OMP_TARGET_CLAUSES (t) = tc;
15708 		  }
15709 	    }
15710 	}
15711       add_stmt (t);
15712       break;
15713 
15714     case OACC_DECLARE:
15715       t = copy_node (t);
15716       tmp = tsubst_omp_clauses (OACC_DECLARE_CLAUSES (t), false, false,
15717 				args, complain, in_decl);
15718       OACC_DECLARE_CLAUSES (t) = tmp;
15719       add_stmt (t);
15720       break;
15721 
15722     case OMP_TARGET_UPDATE:
15723     case OMP_TARGET_ENTER_DATA:
15724     case OMP_TARGET_EXIT_DATA:
15725       tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), false, true,
15726 				args, complain, in_decl);
15727       t = copy_node (t);
15728       OMP_STANDALONE_CLAUSES (t) = tmp;
15729       add_stmt (t);
15730       break;
15731 
15732     case OACC_ENTER_DATA:
15733     case OACC_EXIT_DATA:
15734     case OACC_UPDATE:
15735       tmp = tsubst_omp_clauses (OMP_STANDALONE_CLAUSES (t), false, false,
15736 				args, complain, in_decl);
15737       t = copy_node (t);
15738       OMP_STANDALONE_CLAUSES (t) = tmp;
15739       add_stmt (t);
15740       break;
15741 
15742     case OMP_ORDERED:
15743       tmp = tsubst_omp_clauses (OMP_ORDERED_CLAUSES (t), false, true,
15744 				args, complain, in_decl);
15745       stmt = push_stmt_list ();
15746       RECUR (OMP_BODY (t));
15747       stmt = pop_stmt_list (stmt);
15748 
15749       t = copy_node (t);
15750       OMP_BODY (t) = stmt;
15751       OMP_ORDERED_CLAUSES (t) = tmp;
15752       add_stmt (t);
15753       break;
15754 
15755     case OMP_SECTION:
15756     case OMP_MASTER:
15757     case OMP_TASKGROUP:
15758       stmt = push_stmt_list ();
15759       RECUR (OMP_BODY (t));
15760       stmt = pop_stmt_list (stmt);
15761 
15762       t = copy_node (t);
15763       OMP_BODY (t) = stmt;
15764       add_stmt (t);
15765       break;
15766 
15767     case OMP_ATOMIC:
15768       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
15769       if (TREE_CODE (TREE_OPERAND (t, 1)) != MODIFY_EXPR)
15770 	{
15771 	  tree op1 = TREE_OPERAND (t, 1);
15772 	  tree rhs1 = NULL_TREE;
15773 	  tree lhs, rhs;
15774 	  if (TREE_CODE (op1) == COMPOUND_EXPR)
15775 	    {
15776 	      rhs1 = RECUR (TREE_OPERAND (op1, 0));
15777 	      op1 = TREE_OPERAND (op1, 1);
15778 	    }
15779 	  lhs = RECUR (TREE_OPERAND (op1, 0));
15780 	  rhs = RECUR (TREE_OPERAND (op1, 1));
15781 	  finish_omp_atomic (OMP_ATOMIC, TREE_CODE (op1), lhs, rhs,
15782 			     NULL_TREE, NULL_TREE, rhs1,
15783 			     OMP_ATOMIC_SEQ_CST (t));
15784 	}
15785       else
15786 	{
15787 	  tree op1 = TREE_OPERAND (t, 1);
15788 	  tree v = NULL_TREE, lhs, rhs = NULL_TREE, lhs1 = NULL_TREE;
15789 	  tree rhs1 = NULL_TREE;
15790 	  enum tree_code code = TREE_CODE (TREE_OPERAND (op1, 1));
15791 	  enum tree_code opcode = NOP_EXPR;
15792 	  if (code == OMP_ATOMIC_READ)
15793 	    {
15794 	      v = RECUR (TREE_OPERAND (op1, 0));
15795 	      lhs = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
15796 	    }
15797 	  else if (code == OMP_ATOMIC_CAPTURE_OLD
15798 		   || code == OMP_ATOMIC_CAPTURE_NEW)
15799 	    {
15800 	      tree op11 = TREE_OPERAND (TREE_OPERAND (op1, 1), 1);
15801 	      v = RECUR (TREE_OPERAND (op1, 0));
15802 	      lhs1 = RECUR (TREE_OPERAND (TREE_OPERAND (op1, 1), 0));
15803 	      if (TREE_CODE (op11) == COMPOUND_EXPR)
15804 		{
15805 		  rhs1 = RECUR (TREE_OPERAND (op11, 0));
15806 		  op11 = TREE_OPERAND (op11, 1);
15807 		}
15808 	      lhs = RECUR (TREE_OPERAND (op11, 0));
15809 	      rhs = RECUR (TREE_OPERAND (op11, 1));
15810 	      opcode = TREE_CODE (op11);
15811 	      if (opcode == MODIFY_EXPR)
15812 		opcode = NOP_EXPR;
15813 	    }
15814 	  else
15815 	    {
15816 	      code = OMP_ATOMIC;
15817 	      lhs = RECUR (TREE_OPERAND (op1, 0));
15818 	      rhs = RECUR (TREE_OPERAND (op1, 1));
15819 	    }
15820 	  finish_omp_atomic (code, opcode, lhs, rhs, v, lhs1, rhs1,
15821 			     OMP_ATOMIC_SEQ_CST (t));
15822 	}
15823       break;
15824 
15825     case TRANSACTION_EXPR:
15826       {
15827 	int flags = 0;
15828 	flags |= (TRANSACTION_EXPR_OUTER (t) ? TM_STMT_ATTR_OUTER : 0);
15829 	flags |= (TRANSACTION_EXPR_RELAXED (t) ? TM_STMT_ATTR_RELAXED : 0);
15830 
15831         if (TRANSACTION_EXPR_IS_STMT (t))
15832           {
15833 	    tree body = TRANSACTION_EXPR_BODY (t);
15834 	    tree noex = NULL_TREE;
15835 	    if (TREE_CODE (body) == MUST_NOT_THROW_EXPR)
15836 	      {
15837 		noex = MUST_NOT_THROW_COND (body);
15838 		if (noex == NULL_TREE)
15839 		  noex = boolean_true_node;
15840 		body = TREE_OPERAND (body, 0);
15841 	      }
15842             stmt = begin_transaction_stmt (input_location, NULL, flags);
15843             RECUR (body);
15844             finish_transaction_stmt (stmt, NULL, flags, RECUR (noex));
15845           }
15846         else
15847           {
15848             stmt = build_transaction_expr (EXPR_LOCATION (t),
15849 					   RECUR (TRANSACTION_EXPR_BODY (t)),
15850 					   flags, NULL_TREE);
15851             RETURN (stmt);
15852           }
15853       }
15854       break;
15855 
15856     case MUST_NOT_THROW_EXPR:
15857       {
15858 	tree op0 = RECUR (TREE_OPERAND (t, 0));
15859 	tree cond = RECUR (MUST_NOT_THROW_COND (t));
15860 	RETURN (build_must_not_throw_expr (op0, cond));
15861       }
15862 
15863     case EXPR_PACK_EXPANSION:
15864       error ("invalid use of pack expansion expression");
15865       RETURN (error_mark_node);
15866 
15867     case NONTYPE_ARGUMENT_PACK:
15868       error ("use %<...%> to expand argument pack");
15869       RETURN (error_mark_node);
15870 
15871     case CILK_SPAWN_STMT:
15872       cfun->calls_cilk_spawn = 1;
15873       RETURN (build_cilk_spawn (EXPR_LOCATION (t), RECUR (CILK_SPAWN_FN (t))));
15874 
15875     case CILK_SYNC_STMT:
15876       RETURN (build_cilk_sync ());
15877 
15878     case COMPOUND_EXPR:
15879       tmp = RECUR (TREE_OPERAND (t, 0));
15880       if (tmp == NULL_TREE)
15881 	/* If the first operand was a statement, we're done with it.  */
15882 	RETURN (RECUR (TREE_OPERAND (t, 1)));
15883       RETURN (build_x_compound_expr (EXPR_LOCATION (t), tmp,
15884 				    RECUR (TREE_OPERAND (t, 1)),
15885 				    complain));
15886 
15887     case ANNOTATE_EXPR:
15888       tmp = RECUR (TREE_OPERAND (t, 0));
15889       RETURN (build2_loc (EXPR_LOCATION (t), ANNOTATE_EXPR,
15890 			  TREE_TYPE (tmp), tmp, RECUR (TREE_OPERAND (t, 1))));
15891 
15892     default:
15893       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
15894 
15895       RETURN (tsubst_copy_and_build (t, args, complain, in_decl,
15896 				    /*function_p=*/false,
15897 				    integral_constant_expression_p));
15898     }
15899 
15900   RETURN (NULL_TREE);
15901  out:
15902   input_location = loc;
15903   return r;
15904 #undef RECUR
15905 #undef RETURN
15906 }
15907 
15908 /* Instantiate the special body of the artificial DECL_OMP_DECLARE_REDUCTION
15909    function.  For description of the body see comment above
15910    cp_parser_omp_declare_reduction_exprs.  */
15911 
15912 static void
tsubst_omp_udr(tree t,tree args,tsubst_flags_t complain,tree in_decl)15913 tsubst_omp_udr (tree t, tree args, tsubst_flags_t complain, tree in_decl)
15914 {
15915   if (t == NULL_TREE || t == error_mark_node)
15916     return;
15917 
15918   gcc_assert (TREE_CODE (t) == STATEMENT_LIST);
15919 
15920   tree_stmt_iterator tsi;
15921   int i;
15922   tree stmts[7];
15923   memset (stmts, 0, sizeof stmts);
15924   for (i = 0, tsi = tsi_start (t);
15925        i < 7 && !tsi_end_p (tsi);
15926        i++, tsi_next (&tsi))
15927     stmts[i] = tsi_stmt (tsi);
15928   gcc_assert (tsi_end_p (tsi));
15929 
15930   if (i >= 3)
15931     {
15932       gcc_assert (TREE_CODE (stmts[0]) == DECL_EXPR
15933 		  && TREE_CODE (stmts[1]) == DECL_EXPR);
15934       tree omp_out = tsubst (DECL_EXPR_DECL (stmts[0]),
15935 			     args, complain, in_decl);
15936       tree omp_in = tsubst (DECL_EXPR_DECL (stmts[1]),
15937 			    args, complain, in_decl);
15938       DECL_CONTEXT (omp_out) = current_function_decl;
15939       DECL_CONTEXT (omp_in) = current_function_decl;
15940       keep_next_level (true);
15941       tree block = begin_omp_structured_block ();
15942       tsubst_expr (stmts[2], args, complain, in_decl, false);
15943       block = finish_omp_structured_block (block);
15944       block = maybe_cleanup_point_expr_void (block);
15945       add_decl_expr (omp_out);
15946       if (TREE_NO_WARNING (DECL_EXPR_DECL (stmts[0])))
15947 	TREE_NO_WARNING (omp_out) = 1;
15948       add_decl_expr (omp_in);
15949       finish_expr_stmt (block);
15950     }
15951   if (i >= 6)
15952     {
15953       gcc_assert (TREE_CODE (stmts[3]) == DECL_EXPR
15954 		  && TREE_CODE (stmts[4]) == DECL_EXPR);
15955       tree omp_priv = tsubst (DECL_EXPR_DECL (stmts[3]),
15956 			      args, complain, in_decl);
15957       tree omp_orig = tsubst (DECL_EXPR_DECL (stmts[4]),
15958 			      args, complain, in_decl);
15959       DECL_CONTEXT (omp_priv) = current_function_decl;
15960       DECL_CONTEXT (omp_orig) = current_function_decl;
15961       keep_next_level (true);
15962       tree block = begin_omp_structured_block ();
15963       tsubst_expr (stmts[5], args, complain, in_decl, false);
15964       block = finish_omp_structured_block (block);
15965       block = maybe_cleanup_point_expr_void (block);
15966       cp_walk_tree (&block, cp_remove_omp_priv_cleanup_stmt, omp_priv, NULL);
15967       add_decl_expr (omp_priv);
15968       add_decl_expr (omp_orig);
15969       finish_expr_stmt (block);
15970       if (i == 7)
15971 	add_decl_expr (omp_orig);
15972     }
15973 }
15974 
15975 /* T is a postfix-expression that is not being used in a function
15976    call.  Return the substituted version of T.  */
15977 
15978 static tree
tsubst_non_call_postfix_expression(tree t,tree args,tsubst_flags_t complain,tree in_decl)15979 tsubst_non_call_postfix_expression (tree t, tree args,
15980 				    tsubst_flags_t complain,
15981 				    tree in_decl)
15982 {
15983   if (TREE_CODE (t) == SCOPE_REF)
15984     t = tsubst_qualified_id (t, args, complain, in_decl,
15985 			     /*done=*/false, /*address_p=*/false);
15986   else
15987     t = tsubst_copy_and_build (t, args, complain, in_decl,
15988 			       /*function_p=*/false,
15989 			       /*integral_constant_expression_p=*/false);
15990 
15991   return t;
15992 }
15993 
15994 /* Like tsubst but deals with expressions and performs semantic
15995    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
15996 
15997 tree
tsubst_copy_and_build(tree t,tree args,tsubst_flags_t complain,tree in_decl,bool function_p,bool integral_constant_expression_p)15998 tsubst_copy_and_build (tree t,
15999 		       tree args,
16000 		       tsubst_flags_t complain,
16001 		       tree in_decl,
16002 		       bool function_p,
16003 		       bool integral_constant_expression_p)
16004 {
16005 #define RETURN(EXP) do { retval = (EXP); goto out; } while(0)
16006 #define RECUR(NODE)						\
16007   tsubst_copy_and_build (NODE, args, complain, in_decl, 	\
16008 			 /*function_p=*/false,			\
16009 			 integral_constant_expression_p)
16010 
16011   tree retval, op1;
16012   location_t loc;
16013 
16014   if (t == NULL_TREE || t == error_mark_node)
16015     return t;
16016 
16017   loc = input_location;
16018   if (EXPR_HAS_LOCATION (t))
16019     input_location = EXPR_LOCATION (t);
16020 
16021   /* N3276 decltype magic only applies to calls at the top level or on the
16022      right side of a comma.  */
16023   tsubst_flags_t decltype_flag = (complain & tf_decltype);
16024   complain &= ~tf_decltype;
16025 
16026   switch (TREE_CODE (t))
16027     {
16028     case USING_DECL:
16029       t = DECL_NAME (t);
16030       /* Fall through.  */
16031     case IDENTIFIER_NODE:
16032       {
16033 	tree decl;
16034 	cp_id_kind idk;
16035 	bool non_integral_constant_expression_p;
16036 	const char *error_msg;
16037 
16038 	if (IDENTIFIER_TYPENAME_P (t))
16039 	  {
16040 	    tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16041 	    t = mangle_conv_op_name_for_type (new_type);
16042 	  }
16043 
16044 	/* Look up the name.  */
16045 	decl = lookup_name (t);
16046 
16047 	/* By convention, expressions use ERROR_MARK_NODE to indicate
16048 	   failure, not NULL_TREE.  */
16049 	if (decl == NULL_TREE)
16050 	  decl = error_mark_node;
16051 
16052 	decl = finish_id_expression (t, decl, NULL_TREE,
16053 				     &idk,
16054 				     integral_constant_expression_p,
16055           /*allow_non_integral_constant_expression_p=*/(cxx_dialect >= cxx11),
16056 				     &non_integral_constant_expression_p,
16057 				     /*template_p=*/false,
16058 				     /*done=*/true,
16059 				     /*address_p=*/false,
16060 				     /*template_arg_p=*/false,
16061 				     &error_msg,
16062 				     input_location);
16063 	if (error_msg)
16064 	  error (error_msg);
16065 	if (!function_p && identifier_p (decl))
16066 	  {
16067 	    if (complain & tf_error)
16068 	      unqualified_name_lookup_error (decl);
16069 	    decl = error_mark_node;
16070 	  }
16071 	RETURN (decl);
16072       }
16073 
16074     case TEMPLATE_ID_EXPR:
16075       {
16076 	tree object;
16077 	tree templ = RECUR (TREE_OPERAND (t, 0));
16078 	tree targs = TREE_OPERAND (t, 1);
16079 
16080 	if (targs)
16081 	  targs = tsubst_template_args (targs, args, complain, in_decl);
16082 	if (targs == error_mark_node)
16083 	  return error_mark_node;
16084 
16085 	if (variable_template_p (templ))
16086 	  RETURN (lookup_and_finish_template_variable (templ, targs, complain));
16087 
16088 	if (TREE_CODE (templ) == COMPONENT_REF)
16089 	  {
16090 	    object = TREE_OPERAND (templ, 0);
16091 	    templ = TREE_OPERAND (templ, 1);
16092 	  }
16093 	else
16094 	  object = NULL_TREE;
16095 	templ = lookup_template_function (templ, targs);
16096 
16097 	if (object)
16098 	  RETURN (build3 (COMPONENT_REF, TREE_TYPE (templ),
16099 			 object, templ, NULL_TREE));
16100 	else
16101 	  RETURN (baselink_for_fns (templ));
16102       }
16103 
16104     case INDIRECT_REF:
16105       {
16106 	tree r = RECUR (TREE_OPERAND (t, 0));
16107 
16108 	if (REFERENCE_REF_P (t))
16109 	  {
16110 	    /* A type conversion to reference type will be enclosed in
16111 	       such an indirect ref, but the substitution of the cast
16112 	       will have also added such an indirect ref.  */
16113 	    if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
16114 	      r = convert_from_reference (r);
16115 	  }
16116 	else
16117 	  r = build_x_indirect_ref (input_location, r, RO_UNARY_STAR,
16118 				    complain|decltype_flag);
16119 
16120 	if (TREE_CODE (r) == INDIRECT_REF)
16121 	  REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
16122 
16123 	RETURN (r);
16124       }
16125 
16126     case NOP_EXPR:
16127       {
16128 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16129 	tree op0 = RECUR (TREE_OPERAND (t, 0));
16130 	RETURN (build_nop (type, op0));
16131       }
16132 
16133     case IMPLICIT_CONV_EXPR:
16134       {
16135 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16136 	tree expr = RECUR (TREE_OPERAND (t, 0));
16137 	int flags = LOOKUP_IMPLICIT;
16138 	if (IMPLICIT_CONV_EXPR_DIRECT_INIT (t))
16139 	  flags = LOOKUP_NORMAL;
16140 	RETURN (perform_implicit_conversion_flags (type, expr, complain,
16141 						  flags));
16142       }
16143 
16144     case CONVERT_EXPR:
16145       {
16146 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16147 	tree op0 = RECUR (TREE_OPERAND (t, 0));
16148 	RETURN (build1 (CONVERT_EXPR, type, op0));
16149       }
16150 
16151     case CAST_EXPR:
16152     case REINTERPRET_CAST_EXPR:
16153     case CONST_CAST_EXPR:
16154     case DYNAMIC_CAST_EXPR:
16155     case STATIC_CAST_EXPR:
16156       {
16157 	tree type;
16158 	tree op, r = NULL_TREE;
16159 
16160 	type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16161 	if (integral_constant_expression_p
16162 	    && !cast_valid_in_integral_constant_expression_p (type))
16163 	  {
16164             if (complain & tf_error)
16165               error ("a cast to a type other than an integral or "
16166                      "enumeration type cannot appear in a constant-expression");
16167 	    RETURN (error_mark_node);
16168 	  }
16169 
16170 	op = RECUR (TREE_OPERAND (t, 0));
16171 
16172 	warning_sentinel s(warn_useless_cast);
16173 	switch (TREE_CODE (t))
16174 	  {
16175 	  case CAST_EXPR:
16176 	    r = build_functional_cast (type, op, complain);
16177 	    break;
16178 	  case REINTERPRET_CAST_EXPR:
16179 	    r = build_reinterpret_cast (type, op, complain);
16180 	    break;
16181 	  case CONST_CAST_EXPR:
16182 	    r = build_const_cast (type, op, complain);
16183 	    break;
16184 	  case DYNAMIC_CAST_EXPR:
16185 	    r = build_dynamic_cast (type, op, complain);
16186 	    break;
16187 	  case STATIC_CAST_EXPR:
16188 	    r = build_static_cast (type, op, complain);
16189 	    break;
16190 	  default:
16191 	    gcc_unreachable ();
16192 	  }
16193 
16194 	RETURN (r);
16195       }
16196 
16197     case POSTDECREMENT_EXPR:
16198     case POSTINCREMENT_EXPR:
16199       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
16200 						args, complain, in_decl);
16201       RETURN (build_x_unary_op (input_location, TREE_CODE (t), op1,
16202 				complain|decltype_flag));
16203 
16204     case PREDECREMENT_EXPR:
16205     case PREINCREMENT_EXPR:
16206     case NEGATE_EXPR:
16207     case BIT_NOT_EXPR:
16208     case ABS_EXPR:
16209     case TRUTH_NOT_EXPR:
16210     case UNARY_PLUS_EXPR:  /* Unary + */
16211     case REALPART_EXPR:
16212     case IMAGPART_EXPR:
16213       RETURN (build_x_unary_op (input_location, TREE_CODE (t),
16214 				RECUR (TREE_OPERAND (t, 0)),
16215 				complain|decltype_flag));
16216 
16217     case FIX_TRUNC_EXPR:
16218       RETURN (cp_build_unary_op (FIX_TRUNC_EXPR, RECUR (TREE_OPERAND (t, 0)),
16219 				 0, complain));
16220 
16221     case ADDR_EXPR:
16222       op1 = TREE_OPERAND (t, 0);
16223       if (TREE_CODE (op1) == LABEL_DECL)
16224 	RETURN (finish_label_address_expr (DECL_NAME (op1),
16225 					  EXPR_LOCATION (op1)));
16226       if (TREE_CODE (op1) == SCOPE_REF)
16227 	op1 = tsubst_qualified_id (op1, args, complain, in_decl,
16228 				   /*done=*/true, /*address_p=*/true);
16229       else
16230 	op1 = tsubst_non_call_postfix_expression (op1, args, complain,
16231 						  in_decl);
16232       RETURN (build_x_unary_op (input_location, ADDR_EXPR, op1,
16233 				complain|decltype_flag));
16234 
16235     case PLUS_EXPR:
16236     case MINUS_EXPR:
16237     case MULT_EXPR:
16238     case TRUNC_DIV_EXPR:
16239     case CEIL_DIV_EXPR:
16240     case FLOOR_DIV_EXPR:
16241     case ROUND_DIV_EXPR:
16242     case EXACT_DIV_EXPR:
16243     case BIT_AND_EXPR:
16244     case BIT_IOR_EXPR:
16245     case BIT_XOR_EXPR:
16246     case TRUNC_MOD_EXPR:
16247     case FLOOR_MOD_EXPR:
16248     case TRUTH_ANDIF_EXPR:
16249     case TRUTH_ORIF_EXPR:
16250     case TRUTH_AND_EXPR:
16251     case TRUTH_OR_EXPR:
16252     case RSHIFT_EXPR:
16253     case LSHIFT_EXPR:
16254     case RROTATE_EXPR:
16255     case LROTATE_EXPR:
16256     case EQ_EXPR:
16257     case NE_EXPR:
16258     case MAX_EXPR:
16259     case MIN_EXPR:
16260     case LE_EXPR:
16261     case GE_EXPR:
16262     case LT_EXPR:
16263     case GT_EXPR:
16264     case MEMBER_REF:
16265     case DOTSTAR_EXPR:
16266       {
16267 	warning_sentinel s1(warn_type_limits);
16268 	warning_sentinel s2(warn_div_by_zero);
16269 	warning_sentinel s3(warn_logical_op);
16270 	warning_sentinel s4(warn_tautological_compare);
16271 	tree op0 = RECUR (TREE_OPERAND (t, 0));
16272 	tree op1 = RECUR (TREE_OPERAND (t, 1));
16273 	tree r = build_x_binary_op
16274 	  (input_location, TREE_CODE (t),
16275 	   op0,
16276 	   (TREE_NO_WARNING (TREE_OPERAND (t, 0))
16277 	    ? ERROR_MARK
16278 	    : TREE_CODE (TREE_OPERAND (t, 0))),
16279 	   op1,
16280 	   (TREE_NO_WARNING (TREE_OPERAND (t, 1))
16281 	    ? ERROR_MARK
16282 	    : TREE_CODE (TREE_OPERAND (t, 1))),
16283 	   /*overload=*/NULL,
16284 	   complain|decltype_flag);
16285 	if (EXPR_P (r) && TREE_NO_WARNING (t))
16286 	  TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
16287 
16288 	RETURN (r);
16289       }
16290 
16291     case POINTER_PLUS_EXPR:
16292       {
16293 	tree op0 = RECUR (TREE_OPERAND (t, 0));
16294 	tree op1 = RECUR (TREE_OPERAND (t, 1));
16295 	return fold_build_pointer_plus (op0, op1);
16296       }
16297 
16298     case SCOPE_REF:
16299       RETURN (tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
16300 				  /*address_p=*/false));
16301     case ARRAY_REF:
16302       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
16303 						args, complain, in_decl);
16304       RETURN (build_x_array_ref (EXPR_LOCATION (t), op1,
16305 				 RECUR (TREE_OPERAND (t, 1)),
16306 				 complain|decltype_flag));
16307 
16308     case ARRAY_NOTATION_REF:
16309       {
16310 	tree start_index, length, stride;
16311 	op1 = tsubst_non_call_postfix_expression (ARRAY_NOTATION_ARRAY (t),
16312 						  args, complain, in_decl);
16313 	start_index = RECUR (ARRAY_NOTATION_START (t));
16314 	length = RECUR (ARRAY_NOTATION_LENGTH (t));
16315 	stride = RECUR (ARRAY_NOTATION_STRIDE (t));
16316 	RETURN (build_array_notation_ref (EXPR_LOCATION (t), op1, start_index,
16317 					  length, stride, TREE_TYPE (op1)));
16318       }
16319     case SIZEOF_EXPR:
16320       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0))
16321 	  || ARGUMENT_PACK_P (TREE_OPERAND (t, 0)))
16322 	RETURN (tsubst_copy (t, args, complain, in_decl));
16323       /* Fall through */
16324 
16325     case ALIGNOF_EXPR:
16326       {
16327 	tree r;
16328 
16329 	op1 = TREE_OPERAND (t, 0);
16330 	if (TREE_CODE (t) == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (t))
16331 	  op1 = TREE_TYPE (op1);
16332         if (!args)
16333 	  {
16334 	    /* When there are no ARGS, we are trying to evaluate a
16335 	       non-dependent expression from the parser.  Trying to do
16336 	       the substitutions may not work.  */
16337 	    if (!TYPE_P (op1))
16338 	      op1 = TREE_TYPE (op1);
16339 	  }
16340 	else
16341 	  {
16342 	    ++cp_unevaluated_operand;
16343 	    ++c_inhibit_evaluation_warnings;
16344 	    if (TYPE_P (op1))
16345 	      op1 = tsubst (op1, args, complain, in_decl);
16346 	    else
16347 	      op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
16348 					   /*function_p=*/false,
16349 					   /*integral_constant_expression_p=*/
16350 					   false);
16351 	    --cp_unevaluated_operand;
16352 	    --c_inhibit_evaluation_warnings;
16353 	  }
16354         if (TYPE_P (op1))
16355 	  r = cxx_sizeof_or_alignof_type (op1, TREE_CODE (t),
16356 					  complain & tf_error);
16357 	else
16358 	  r = cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t),
16359 					  complain & tf_error);
16360 	if (TREE_CODE (t) == SIZEOF_EXPR && r != error_mark_node)
16361 	  {
16362 	    if (TREE_CODE (r) != SIZEOF_EXPR || TYPE_P (op1))
16363 	      {
16364 		if (!processing_template_decl && TYPE_P (op1))
16365 		  {
16366 		    r = build_min (SIZEOF_EXPR, size_type_node,
16367 				   build1 (NOP_EXPR, op1, error_mark_node));
16368 		    SIZEOF_EXPR_TYPE_P (r) = 1;
16369 		  }
16370 		else
16371 		  r = build_min (SIZEOF_EXPR, size_type_node, op1);
16372 		TREE_SIDE_EFFECTS (r) = 0;
16373 		TREE_READONLY (r) = 1;
16374 	      }
16375 	    SET_EXPR_LOCATION (r, EXPR_LOCATION (t));
16376 	  }
16377 	RETURN (r);
16378       }
16379 
16380     case AT_ENCODE_EXPR:
16381       {
16382 	op1 = TREE_OPERAND (t, 0);
16383 	++cp_unevaluated_operand;
16384 	++c_inhibit_evaluation_warnings;
16385 	op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
16386 				     /*function_p=*/false,
16387 				     /*integral_constant_expression_p=*/false);
16388 	--cp_unevaluated_operand;
16389 	--c_inhibit_evaluation_warnings;
16390 	RETURN (objc_build_encode_expr (op1));
16391       }
16392 
16393     case NOEXCEPT_EXPR:
16394       op1 = TREE_OPERAND (t, 0);
16395       ++cp_unevaluated_operand;
16396       ++c_inhibit_evaluation_warnings;
16397       ++cp_noexcept_operand;
16398       op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
16399 				   /*function_p=*/false,
16400 				   /*integral_constant_expression_p=*/false);
16401       --cp_unevaluated_operand;
16402       --c_inhibit_evaluation_warnings;
16403       --cp_noexcept_operand;
16404       RETURN (finish_noexcept_expr (op1, complain));
16405 
16406     case MODOP_EXPR:
16407       {
16408 	warning_sentinel s(warn_div_by_zero);
16409 	tree lhs = RECUR (TREE_OPERAND (t, 0));
16410 	tree rhs = RECUR (TREE_OPERAND (t, 2));
16411 	tree r = build_x_modify_expr
16412 	  (EXPR_LOCATION (t), lhs, TREE_CODE (TREE_OPERAND (t, 1)), rhs,
16413 	   complain|decltype_flag);
16414 	/* TREE_NO_WARNING must be set if either the expression was
16415 	   parenthesized or it uses an operator such as >>= rather
16416 	   than plain assignment.  In the former case, it was already
16417 	   set and must be copied.  In the latter case,
16418 	   build_x_modify_expr sets it and it must not be reset
16419 	   here.  */
16420 	if (TREE_NO_WARNING (t))
16421 	  TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
16422 
16423 	RETURN (r);
16424       }
16425 
16426     case ARROW_EXPR:
16427       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
16428 						args, complain, in_decl);
16429       /* Remember that there was a reference to this entity.  */
16430       if (DECL_P (op1)
16431 	  && !mark_used (op1, complain) && !(complain & tf_error))
16432 	RETURN (error_mark_node);
16433       RETURN (build_x_arrow (input_location, op1, complain));
16434 
16435     case NEW_EXPR:
16436       {
16437 	tree placement = RECUR (TREE_OPERAND (t, 0));
16438 	tree init = RECUR (TREE_OPERAND (t, 3));
16439 	vec<tree, va_gc> *placement_vec;
16440 	vec<tree, va_gc> *init_vec;
16441 	tree ret;
16442 
16443 	if (placement == NULL_TREE)
16444 	  placement_vec = NULL;
16445 	else
16446 	  {
16447 	    placement_vec = make_tree_vector ();
16448 	    for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
16449 	      vec_safe_push (placement_vec, TREE_VALUE (placement));
16450 	  }
16451 
16452 	/* If there was an initializer in the original tree, but it
16453 	   instantiated to an empty list, then we should pass a
16454 	   non-NULL empty vector to tell build_new that it was an
16455 	   empty initializer() rather than no initializer.  This can
16456 	   only happen when the initializer is a pack expansion whose
16457 	   parameter packs are of length zero.  */
16458 	if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
16459 	  init_vec = NULL;
16460 	else
16461 	  {
16462 	    init_vec = make_tree_vector ();
16463 	    if (init == void_node)
16464 	      gcc_assert (init_vec != NULL);
16465 	    else
16466 	      {
16467 		for (; init != NULL_TREE; init = TREE_CHAIN (init))
16468 		  vec_safe_push (init_vec, TREE_VALUE (init));
16469 	      }
16470 	  }
16471 
16472 	tree op1 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
16473 	tree op2 = RECUR (TREE_OPERAND (t, 2));
16474 	ret = build_new (&placement_vec, op1, op2, &init_vec,
16475 			 NEW_EXPR_USE_GLOBAL (t),
16476 			 complain);
16477 
16478 	if (placement_vec != NULL)
16479 	  release_tree_vector (placement_vec);
16480 	if (init_vec != NULL)
16481 	  release_tree_vector (init_vec);
16482 
16483 	RETURN (ret);
16484       }
16485 
16486     case DELETE_EXPR:
16487       {
16488 	tree op0 = RECUR (TREE_OPERAND (t, 0));
16489 	tree op1 = RECUR (TREE_OPERAND (t, 1));
16490 	RETURN (delete_sanity (op0, op1,
16491 			       DELETE_EXPR_USE_VEC (t),
16492 			       DELETE_EXPR_USE_GLOBAL (t),
16493 			       complain));
16494       }
16495 
16496     case COMPOUND_EXPR:
16497       {
16498 	tree op0 = tsubst_copy_and_build (TREE_OPERAND (t, 0), args,
16499 					  complain & ~tf_decltype, in_decl,
16500 					  /*function_p=*/false,
16501 					  integral_constant_expression_p);
16502 	RETURN (build_x_compound_expr (EXPR_LOCATION (t),
16503 				       op0,
16504 				       RECUR (TREE_OPERAND (t, 1)),
16505 				       complain|decltype_flag));
16506       }
16507 
16508     case CALL_EXPR:
16509       {
16510 	tree function;
16511 	vec<tree, va_gc> *call_args;
16512 	unsigned int nargs, i;
16513 	bool qualified_p;
16514 	bool koenig_p;
16515 	tree ret;
16516 
16517 	function = CALL_EXPR_FN (t);
16518 	/* When we parsed the expression,  we determined whether or
16519 	   not Koenig lookup should be performed.  */
16520 	koenig_p = KOENIG_LOOKUP_P (t);
16521 	if (TREE_CODE (function) == SCOPE_REF)
16522 	  {
16523 	    qualified_p = true;
16524 	    function = tsubst_qualified_id (function, args, complain, in_decl,
16525 					    /*done=*/false,
16526 					    /*address_p=*/false);
16527 	  }
16528 	else if (koenig_p && identifier_p (function))
16529 	  {
16530 	    /* Do nothing; calling tsubst_copy_and_build on an identifier
16531 	       would incorrectly perform unqualified lookup again.
16532 
16533 	       Note that we can also have an IDENTIFIER_NODE if the earlier
16534 	       unqualified lookup found a member function; in that case
16535 	       koenig_p will be false and we do want to do the lookup
16536 	       again to find the instantiated member function.
16537 
16538 	       FIXME but doing that causes c++/15272, so we need to stop
16539 	       using IDENTIFIER_NODE in that situation.  */
16540 	    qualified_p = false;
16541 	  }
16542 	else
16543 	  {
16544 	    if (TREE_CODE (function) == COMPONENT_REF)
16545 	      {
16546 		tree op = TREE_OPERAND (function, 1);
16547 
16548 		qualified_p = (TREE_CODE (op) == SCOPE_REF
16549 			       || (BASELINK_P (op)
16550 				   && BASELINK_QUALIFIED_P (op)));
16551 	      }
16552 	    else
16553 	      qualified_p = false;
16554 
16555 	    if (TREE_CODE (function) == ADDR_EXPR
16556 		&& TREE_CODE (TREE_OPERAND (function, 0)) == FUNCTION_DECL)
16557 	      /* Avoid error about taking the address of a constructor.  */
16558 	      function = TREE_OPERAND (function, 0);
16559 
16560 	    function = tsubst_copy_and_build (function, args, complain,
16561 					      in_decl,
16562 					      !qualified_p,
16563 					      integral_constant_expression_p);
16564 
16565 	    if (BASELINK_P (function))
16566 	      qualified_p = true;
16567 	  }
16568 
16569 	nargs = call_expr_nargs (t);
16570 	call_args = make_tree_vector ();
16571 	for (i = 0; i < nargs; ++i)
16572 	  {
16573 	    tree arg = CALL_EXPR_ARG (t, i);
16574 
16575 	    if (!PACK_EXPANSION_P (arg))
16576 	      vec_safe_push (call_args, RECUR (CALL_EXPR_ARG (t, i)));
16577 	    else
16578 	      {
16579 		/* Expand the pack expansion and push each entry onto
16580 		   CALL_ARGS.  */
16581 		arg = tsubst_pack_expansion (arg, args, complain, in_decl);
16582 		if (TREE_CODE (arg) == TREE_VEC)
16583 		  {
16584 		    unsigned int len, j;
16585 
16586 		    len = TREE_VEC_LENGTH (arg);
16587 		    for (j = 0; j < len; ++j)
16588 		      {
16589 			tree value = TREE_VEC_ELT (arg, j);
16590 			if (value != NULL_TREE)
16591 			  value = convert_from_reference (value);
16592 			vec_safe_push (call_args, value);
16593 		      }
16594 		  }
16595 		else
16596 		  {
16597 		    /* A partial substitution.  Add one entry.  */
16598 		    vec_safe_push (call_args, arg);
16599 		  }
16600 	      }
16601 	  }
16602 
16603 	/* We do not perform argument-dependent lookup if normal
16604 	   lookup finds a non-function, in accordance with the
16605 	   expected resolution of DR 218.  */
16606 	if (koenig_p
16607 	    && ((is_overloaded_fn (function)
16608 		 /* If lookup found a member function, the Koenig lookup is
16609 		    not appropriate, even if an unqualified-name was used
16610 		    to denote the function.  */
16611 		 && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
16612 		|| identifier_p (function))
16613 	    /* Only do this when substitution turns a dependent call
16614 	       into a non-dependent call.  */
16615 	    && type_dependent_expression_p_push (t)
16616 	    && !any_type_dependent_arguments_p (call_args))
16617 	  function = perform_koenig_lookup (function, call_args, tf_none);
16618 
16619 	if (identifier_p (function)
16620 	    && !any_type_dependent_arguments_p (call_args))
16621 	  {
16622 	    if (koenig_p && (complain & tf_warning_or_error))
16623 	      {
16624 		/* For backwards compatibility and good diagnostics, try
16625 		   the unqualified lookup again if we aren't in SFINAE
16626 		   context.  */
16627 		tree unq = (tsubst_copy_and_build
16628 			    (function, args, complain, in_decl, true,
16629 			     integral_constant_expression_p));
16630 		if (unq == error_mark_node)
16631 		  RETURN (error_mark_node);
16632 
16633 		if (unq != function)
16634 		  {
16635 		    /* In a lambda fn, we have to be careful to not
16636 		       introduce new this captures.  Legacy code can't
16637 		       be using lambdas anyway, so it's ok to be
16638 		       stricter.  */
16639 		    bool in_lambda = (current_class_type
16640 				      && LAMBDA_TYPE_P (current_class_type));
16641 		    char const *msg = "%qD was not declared in this scope, "
16642 		      "and no declarations were found by "
16643 		      "argument-dependent lookup at the point "
16644 		      "of instantiation";
16645 
16646 		    bool diag = true;
16647 		    if (in_lambda)
16648 		      error_at (EXPR_LOC_OR_LOC (t, input_location),
16649 				msg, function);
16650 		    else
16651 		      diag = permerror (EXPR_LOC_OR_LOC (t, input_location),
16652 					msg, function);
16653 		    if (diag)
16654 		      {
16655 			tree fn = unq;
16656 			if (INDIRECT_REF_P (fn))
16657 			  fn = TREE_OPERAND (fn, 0);
16658 			if (TREE_CODE (fn) == COMPONENT_REF)
16659 			  fn = TREE_OPERAND (fn, 1);
16660 			if (is_overloaded_fn (fn))
16661 			  fn = get_first_fn (fn);
16662 
16663 			if (!DECL_P (fn))
16664 			  /* Can't say anything more.  */;
16665 			else if (DECL_CLASS_SCOPE_P (fn))
16666 			  {
16667 			    location_t loc = EXPR_LOC_OR_LOC (t,
16668 							      input_location);
16669 			    inform (loc,
16670 				    "declarations in dependent base %qT are "
16671 				    "not found by unqualified lookup",
16672 				    DECL_CLASS_CONTEXT (fn));
16673 			    if (current_class_ptr)
16674 			      inform (loc,
16675 				      "use %<this->%D%> instead", function);
16676 			    else
16677 			      inform (loc,
16678 				      "use %<%T::%D%> instead",
16679 				      current_class_name, function);
16680 			  }
16681 			else
16682 			  inform (DECL_SOURCE_LOCATION (fn),
16683 				  "%qD declared here, later in the "
16684 				  "translation unit", fn);
16685 			if (in_lambda)
16686 			  {
16687 			    release_tree_vector (call_args);
16688 			    RETURN (error_mark_node);
16689 			  }
16690 		      }
16691 
16692 		    function = unq;
16693 		  }
16694 	      }
16695 	    if (identifier_p (function))
16696 	      {
16697 		if (complain & tf_error)
16698 		  unqualified_name_lookup_error (function);
16699 		release_tree_vector (call_args);
16700 		RETURN (error_mark_node);
16701 	      }
16702 	  }
16703 
16704 	/* Remember that there was a reference to this entity.  */
16705 	if (DECL_P (function)
16706 	    && !mark_used (function, complain) && !(complain & tf_error))
16707 	  RETURN (error_mark_node);
16708 
16709 	/* Put back tf_decltype for the actual call.  */
16710 	complain |= decltype_flag;
16711 
16712 	if (TREE_CODE (function) == OFFSET_REF)
16713 	  ret = build_offset_ref_call_from_tree (function, &call_args,
16714 						 complain);
16715 	else if (TREE_CODE (function) == COMPONENT_REF)
16716 	  {
16717 	    tree instance = TREE_OPERAND (function, 0);
16718 	    tree fn = TREE_OPERAND (function, 1);
16719 
16720 	    if (processing_template_decl
16721 		&& (type_dependent_expression_p (instance)
16722 		    || (!BASELINK_P (fn)
16723 			&& TREE_CODE (fn) != FIELD_DECL)
16724 		    || type_dependent_expression_p (fn)
16725 		    || any_type_dependent_arguments_p (call_args)))
16726 	      ret = build_nt_call_vec (function, call_args);
16727 	    else if (!BASELINK_P (fn))
16728 	      ret = finish_call_expr (function, &call_args,
16729 				       /*disallow_virtual=*/false,
16730 				       /*koenig_p=*/false,
16731 				       complain);
16732 	    else
16733 	      ret = (build_new_method_call
16734 		      (instance, fn,
16735 		       &call_args, NULL_TREE,
16736 		       qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
16737 		       /*fn_p=*/NULL,
16738 		       complain));
16739 	  }
16740 	else
16741 	  ret = finish_call_expr (function, &call_args,
16742 				  /*disallow_virtual=*/qualified_p,
16743 				  koenig_p,
16744 				  complain);
16745 
16746 	release_tree_vector (call_args);
16747 
16748 	RETURN (ret);
16749       }
16750 
16751     case COND_EXPR:
16752       {
16753 	tree cond = RECUR (TREE_OPERAND (t, 0));
16754 	tree folded_cond = fold_non_dependent_expr (cond);
16755 	tree exp1, exp2;
16756 
16757 	if (TREE_CODE (folded_cond) == INTEGER_CST)
16758 	  {
16759 	    if (integer_zerop (folded_cond))
16760 	      {
16761 		++c_inhibit_evaluation_warnings;
16762 		exp1 = RECUR (TREE_OPERAND (t, 1));
16763 		--c_inhibit_evaluation_warnings;
16764 		exp2 = RECUR (TREE_OPERAND (t, 2));
16765 	      }
16766 	    else
16767 	      {
16768 		exp1 = RECUR (TREE_OPERAND (t, 1));
16769 		++c_inhibit_evaluation_warnings;
16770 		exp2 = RECUR (TREE_OPERAND (t, 2));
16771 		--c_inhibit_evaluation_warnings;
16772 	      }
16773 	    cond = folded_cond;
16774 	  }
16775 	else
16776 	  {
16777 	    exp1 = RECUR (TREE_OPERAND (t, 1));
16778 	    exp2 = RECUR (TREE_OPERAND (t, 2));
16779 	  }
16780 
16781 	RETURN (build_x_conditional_expr (EXPR_LOCATION (t),
16782 					 cond, exp1, exp2, complain));
16783       }
16784 
16785     case PSEUDO_DTOR_EXPR:
16786       {
16787 	tree op0 = RECUR (TREE_OPERAND (t, 0));
16788 	tree op1 = RECUR (TREE_OPERAND (t, 1));
16789 	tree op2 = tsubst (TREE_OPERAND (t, 2), args, complain, in_decl);
16790 	RETURN (finish_pseudo_destructor_expr (op0, op1, op2,
16791 					       input_location));
16792       }
16793 
16794     case TREE_LIST:
16795       {
16796 	tree purpose, value, chain;
16797 
16798 	if (t == void_list_node)
16799 	  RETURN (t);
16800 
16801         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
16802             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
16803           {
16804             /* We have pack expansions, so expand those and
16805                create a new list out of it.  */
16806             tree purposevec = NULL_TREE;
16807             tree valuevec = NULL_TREE;
16808             tree chain;
16809             int i, len = -1;
16810 
16811             /* Expand the argument expressions.  */
16812             if (TREE_PURPOSE (t))
16813               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
16814                                                  complain, in_decl);
16815             if (TREE_VALUE (t))
16816               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
16817                                                complain, in_decl);
16818 
16819             /* Build the rest of the list.  */
16820             chain = TREE_CHAIN (t);
16821             if (chain && chain != void_type_node)
16822               chain = RECUR (chain);
16823 
16824             /* Determine the number of arguments.  */
16825             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
16826               {
16827                 len = TREE_VEC_LENGTH (purposevec);
16828                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
16829               }
16830             else if (TREE_CODE (valuevec) == TREE_VEC)
16831               len = TREE_VEC_LENGTH (valuevec);
16832             else
16833               {
16834                 /* Since we only performed a partial substitution into
16835                    the argument pack, we only RETURN (a single list
16836                    node.  */
16837                 if (purposevec == TREE_PURPOSE (t)
16838                     && valuevec == TREE_VALUE (t)
16839                     && chain == TREE_CHAIN (t))
16840                   RETURN (t);
16841 
16842                 RETURN (tree_cons (purposevec, valuevec, chain));
16843               }
16844 
16845             /* Convert the argument vectors into a TREE_LIST */
16846             i = len;
16847             while (i > 0)
16848               {
16849                 /* Grab the Ith values.  */
16850                 i--;
16851                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i)
16852 		                     : NULL_TREE;
16853                 value
16854 		  = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i))
16855                              : NULL_TREE;
16856 
16857                 /* Build the list (backwards).  */
16858                 chain = tree_cons (purpose, value, chain);
16859               }
16860 
16861             RETURN (chain);
16862           }
16863 
16864 	purpose = TREE_PURPOSE (t);
16865 	if (purpose)
16866 	  purpose = RECUR (purpose);
16867 	value = TREE_VALUE (t);
16868 	if (value)
16869 	  value = RECUR (value);
16870 	chain = TREE_CHAIN (t);
16871 	if (chain && chain != void_type_node)
16872 	  chain = RECUR (chain);
16873 	if (purpose == TREE_PURPOSE (t)
16874 	    && value == TREE_VALUE (t)
16875 	    && chain == TREE_CHAIN (t))
16876 	  RETURN (t);
16877 	RETURN (tree_cons (purpose, value, chain));
16878       }
16879 
16880     case COMPONENT_REF:
16881       {
16882 	tree object;
16883 	tree object_type;
16884 	tree member;
16885 	tree r;
16886 
16887 	object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
16888 						     args, complain, in_decl);
16889 	/* Remember that there was a reference to this entity.  */
16890 	if (DECL_P (object)
16891 	    && !mark_used (object, complain) && !(complain & tf_error))
16892 	  RETURN (error_mark_node);
16893 	object_type = TREE_TYPE (object);
16894 
16895 	member = TREE_OPERAND (t, 1);
16896 	if (BASELINK_P (member))
16897 	  member = tsubst_baselink (member,
16898 				    non_reference (TREE_TYPE (object)),
16899 				    args, complain, in_decl);
16900 	else
16901 	  member = tsubst_copy (member, args, complain, in_decl);
16902 	if (member == error_mark_node)
16903 	  RETURN (error_mark_node);
16904 
16905 	if (type_dependent_expression_p (object))
16906 	  /* We can't do much here.  */;
16907 	else if (!CLASS_TYPE_P (object_type))
16908 	  {
16909 	    if (scalarish_type_p (object_type))
16910 	      {
16911 		tree s = NULL_TREE;
16912 		tree dtor = member;
16913 
16914 		if (TREE_CODE (dtor) == SCOPE_REF)
16915 		  {
16916 		    s = TREE_OPERAND (dtor, 0);
16917 		    dtor = TREE_OPERAND (dtor, 1);
16918 		  }
16919 		if (TREE_CODE (dtor) == BIT_NOT_EXPR)
16920 		  {
16921 		    dtor = TREE_OPERAND (dtor, 0);
16922 		    if (TYPE_P (dtor))
16923 		      RETURN (finish_pseudo_destructor_expr
16924 			      (object, s, dtor, input_location));
16925 		  }
16926 	      }
16927 	  }
16928 	else if (TREE_CODE (member) == SCOPE_REF
16929 		 && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
16930 	  {
16931 	    /* Lookup the template functions now that we know what the
16932 	       scope is.  */
16933 	    tree scope = TREE_OPERAND (member, 0);
16934 	    tree tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
16935 	    tree args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
16936 	    member = lookup_qualified_name (scope, tmpl,
16937 					    /*is_type_p=*/false,
16938 					    /*complain=*/false);
16939 	    if (BASELINK_P (member))
16940 	      {
16941 		BASELINK_FUNCTIONS (member)
16942 		  = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
16943 			      args);
16944 		member = (adjust_result_of_qualified_name_lookup
16945 			  (member, BINFO_TYPE (BASELINK_BINFO (member)),
16946 			   object_type));
16947 	      }
16948 	    else
16949 	      {
16950 		qualified_name_lookup_error (scope, tmpl, member,
16951 					     input_location);
16952 		RETURN (error_mark_node);
16953 	      }
16954 	  }
16955 	else if (TREE_CODE (member) == SCOPE_REF
16956 		 && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
16957 		 && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
16958 	  {
16959 	    if (complain & tf_error)
16960 	      {
16961 		if (TYPE_P (TREE_OPERAND (member, 0)))
16962 		  error ("%qT is not a class or namespace",
16963 			 TREE_OPERAND (member, 0));
16964 		else
16965 		  error ("%qD is not a class or namespace",
16966 			 TREE_OPERAND (member, 0));
16967 	      }
16968 	    RETURN (error_mark_node);
16969 	  }
16970 	else if (TREE_CODE (member) == FIELD_DECL)
16971 	  {
16972 	    r = finish_non_static_data_member (member, object, NULL_TREE);
16973 	    if (TREE_CODE (r) == COMPONENT_REF)
16974 	      REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
16975 	    RETURN (r);
16976 	  }
16977 
16978 	r = finish_class_member_access_expr (object, member,
16979 					     /*template_p=*/false,
16980 					     complain);
16981 	if (TREE_CODE (r) == COMPONENT_REF)
16982 	  REF_PARENTHESIZED_P (r) = REF_PARENTHESIZED_P (t);
16983 	RETURN (r);
16984       }
16985 
16986     case THROW_EXPR:
16987       RETURN (build_throw
16988 	(RECUR (TREE_OPERAND (t, 0))));
16989 
16990     case CONSTRUCTOR:
16991       {
16992 	vec<constructor_elt, va_gc> *n;
16993 	constructor_elt *ce;
16994 	unsigned HOST_WIDE_INT idx;
16995 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
16996 	bool process_index_p;
16997         int newlen;
16998         bool need_copy_p = false;
16999 	tree r;
17000 
17001 	if (type == error_mark_node)
17002 	  RETURN (error_mark_node);
17003 
17004 	/* digest_init will do the wrong thing if we let it.  */
17005 	if (type && TYPE_PTRMEMFUNC_P (type))
17006 	  RETURN (t);
17007 
17008 	/* We do not want to process the index of aggregate
17009 	   initializers as they are identifier nodes which will be
17010 	   looked up by digest_init.  */
17011 	process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
17012 
17013 	n = vec_safe_copy (CONSTRUCTOR_ELTS (t));
17014         newlen = vec_safe_length (n);
17015 	FOR_EACH_VEC_SAFE_ELT (n, idx, ce)
17016 	  {
17017 	    if (ce->index && process_index_p
17018 		/* An identifier index is looked up in the type
17019 		   being initialized, not the current scope.  */
17020 		&& TREE_CODE (ce->index) != IDENTIFIER_NODE)
17021 	      ce->index = RECUR (ce->index);
17022 
17023             if (PACK_EXPANSION_P (ce->value))
17024               {
17025                 /* Substitute into the pack expansion.  */
17026                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
17027                                                   in_decl);
17028 
17029 		if (ce->value == error_mark_node
17030 		    || PACK_EXPANSION_P (ce->value))
17031 		  ;
17032 		else if (TREE_VEC_LENGTH (ce->value) == 1)
17033                   /* Just move the argument into place.  */
17034                   ce->value = TREE_VEC_ELT (ce->value, 0);
17035                 else
17036                   {
17037                     /* Update the length of the final CONSTRUCTOR
17038                        arguments vector, and note that we will need to
17039                        copy.*/
17040                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
17041                     need_copy_p = true;
17042                   }
17043               }
17044             else
17045               ce->value = RECUR (ce->value);
17046 	  }
17047 
17048         if (need_copy_p)
17049           {
17050             vec<constructor_elt, va_gc> *old_n = n;
17051 
17052             vec_alloc (n, newlen);
17053             FOR_EACH_VEC_ELT (*old_n, idx, ce)
17054               {
17055                 if (TREE_CODE (ce->value) == TREE_VEC)
17056                   {
17057                     int i, len = TREE_VEC_LENGTH (ce->value);
17058                     for (i = 0; i < len; ++i)
17059                       CONSTRUCTOR_APPEND_ELT (n, 0,
17060                                               TREE_VEC_ELT (ce->value, i));
17061                   }
17062                 else
17063                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
17064               }
17065           }
17066 
17067 	r = build_constructor (init_list_type_node, n);
17068 	CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
17069 
17070 	if (TREE_HAS_CONSTRUCTOR (t))
17071 	  RETURN (finish_compound_literal (type, r, complain));
17072 
17073 	TREE_TYPE (r) = type;
17074 	RETURN (r);
17075       }
17076 
17077     case TYPEID_EXPR:
17078       {
17079 	tree operand_0 = TREE_OPERAND (t, 0);
17080 	if (TYPE_P (operand_0))
17081 	  {
17082 	    operand_0 = tsubst (operand_0, args, complain, in_decl);
17083 	    RETURN (get_typeid (operand_0, complain));
17084 	  }
17085 	else
17086 	  {
17087 	    operand_0 = RECUR (operand_0);
17088 	    RETURN (build_typeid (operand_0, complain));
17089 	  }
17090       }
17091 
17092     case VAR_DECL:
17093       if (!args)
17094 	RETURN (t);
17095       else if (DECL_PACK_P (t))
17096 	{
17097 	  /* We don't build decls for an instantiation of a
17098 	     variadic capture proxy, we instantiate the elements
17099 	     when needed.  */
17100 	  gcc_assert (DECL_HAS_VALUE_EXPR_P (t));
17101 	  return RECUR (DECL_VALUE_EXPR (t));
17102 	}
17103       /* Fall through */
17104 
17105     case PARM_DECL:
17106       {
17107 	tree r = tsubst_copy (t, args, complain, in_decl);
17108 	/* ??? We're doing a subset of finish_id_expression here.  */
17109 	if (VAR_P (r)
17110 	    && !processing_template_decl
17111 	    && !cp_unevaluated_operand
17112 	    && (TREE_STATIC (r) || DECL_EXTERNAL (r))
17113 	    && CP_DECL_THREAD_LOCAL_P (r))
17114 	  {
17115 	    if (tree wrap = get_tls_wrapper_fn (r))
17116 	      /* Replace an evaluated use of the thread_local variable with
17117 		 a call to its wrapper.  */
17118 	      r = build_cxx_call (wrap, 0, NULL, tf_warning_or_error);
17119 	  }
17120 	else if (outer_automatic_var_p (r))
17121 	  {
17122 	    r = process_outer_var_ref (r, complain);
17123 	    if (is_capture_proxy (r))
17124 	      register_local_specialization (r, t);
17125 	  }
17126 
17127 	if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
17128 	  /* If the original type was a reference, we'll be wrapped in
17129 	     the appropriate INDIRECT_REF.  */
17130 	  r = convert_from_reference (r);
17131 	RETURN (r);
17132       }
17133 
17134     case VA_ARG_EXPR:
17135       {
17136 	tree op0 = RECUR (TREE_OPERAND (t, 0));
17137 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
17138 	RETURN (build_x_va_arg (EXPR_LOCATION (t), op0, type));
17139       }
17140 
17141     case OFFSETOF_EXPR:
17142       RETURN (finish_offsetof (RECUR (TREE_OPERAND (t, 0)),
17143 			       EXPR_LOCATION (t)));
17144 
17145     case TRAIT_EXPR:
17146       {
17147 	tree type1 = tsubst (TRAIT_EXPR_TYPE1 (t), args,
17148 			     complain, in_decl);
17149 
17150 	tree type2 = TRAIT_EXPR_TYPE2 (t);
17151 	if (type2 && TREE_CODE (type2) == TREE_LIST)
17152 	  type2 = RECUR (type2);
17153 	else if (type2)
17154 	  type2 = tsubst (type2, args, complain, in_decl);
17155 
17156 	RETURN (finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2));
17157       }
17158 
17159     case STMT_EXPR:
17160       {
17161 	tree old_stmt_expr = cur_stmt_expr;
17162 	tree stmt_expr = begin_stmt_expr ();
17163 
17164 	cur_stmt_expr = stmt_expr;
17165 	tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
17166 		     integral_constant_expression_p);
17167 	stmt_expr = finish_stmt_expr (stmt_expr, false);
17168 	cur_stmt_expr = old_stmt_expr;
17169 
17170 	/* If the resulting list of expression statement is empty,
17171 	   fold it further into void_node.  */
17172 	if (empty_expr_stmt_p (stmt_expr))
17173 	  stmt_expr = void_node;
17174 
17175 	RETURN (stmt_expr);
17176       }
17177 
17178     case LAMBDA_EXPR:
17179       {
17180 	tree r = build_lambda_expr ();
17181 
17182 	tree type = tsubst (LAMBDA_EXPR_CLOSURE (t), args, complain, NULL_TREE);
17183 	LAMBDA_EXPR_CLOSURE (r) = type;
17184 	CLASSTYPE_LAMBDA_EXPR (type) = r;
17185 
17186 	LAMBDA_EXPR_LOCATION (r)
17187 	  = LAMBDA_EXPR_LOCATION (t);
17188 	LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
17189 	  = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
17190 	LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
17191 	LAMBDA_EXPR_DISCRIMINATOR (r)
17192 	  = (LAMBDA_EXPR_DISCRIMINATOR (t));
17193 	tree scope = LAMBDA_EXPR_EXTRA_SCOPE (t);
17194 	if (!scope)
17195 	  /* No substitution needed.  */;
17196 	else if (VAR_OR_FUNCTION_DECL_P (scope))
17197 	  /* For a function or variable scope, we want to use tsubst so that we
17198 	     don't complain about referring to an auto before deduction.  */
17199 	  scope = tsubst (scope, args, complain, in_decl);
17200 	else if (TREE_CODE (scope) == PARM_DECL)
17201 	  {
17202 	    /* Look up the parameter we want directly, as tsubst_copy
17203 	       doesn't do what we need.  */
17204 	    tree fn = tsubst (DECL_CONTEXT (scope), args, complain, in_decl);
17205 	    tree parm = FUNCTION_FIRST_USER_PARM (fn);
17206 	    while (DECL_PARM_INDEX (parm) != DECL_PARM_INDEX (scope))
17207 	      parm = DECL_CHAIN (parm);
17208 	    scope = parm;
17209 	    /* FIXME Work around the parm not having DECL_CONTEXT set.  */
17210 	    if (DECL_CONTEXT (scope) == NULL_TREE)
17211 	      DECL_CONTEXT (scope) = fn;
17212 	  }
17213 	else if (TREE_CODE (scope) == FIELD_DECL)
17214 	  /* For a field, use tsubst_copy so that we look up the existing field
17215 	     rather than build a new one.  */
17216 	  scope = RECUR (scope);
17217 	else
17218 	  gcc_unreachable ();
17219 	LAMBDA_EXPR_EXTRA_SCOPE (r) = scope;
17220 
17221 	gcc_assert (LAMBDA_EXPR_THIS_CAPTURE (t) == NULL_TREE
17222 		    && LAMBDA_EXPR_PENDING_PROXIES (t) == NULL);
17223 
17224 	/* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
17225 	determine_visibility (TYPE_NAME (type));
17226 	/* Now that we know visibility, instantiate the type so we have a
17227 	   declaration of the op() for later calls to lambda_function.  */
17228 	complete_type (type);
17229 
17230 	if (tree fn = lambda_function (type))
17231 	  LAMBDA_EXPR_RETURN_TYPE (r) = TREE_TYPE (TREE_TYPE (fn));
17232 
17233 	LAMBDA_EXPR_THIS_CAPTURE (r) = NULL_TREE;
17234 
17235 	insert_pending_capture_proxies ();
17236 
17237 	RETURN (build_lambda_object (r));
17238       }
17239 
17240     case TARGET_EXPR:
17241       /* We can get here for a constant initializer of non-dependent type.
17242          FIXME stop folding in cp_parser_initializer_clause.  */
17243       {
17244 	tree r = get_target_expr_sfinae (RECUR (TARGET_EXPR_INITIAL (t)),
17245 					 complain);
17246 	RETURN (r);
17247       }
17248 
17249     case TRANSACTION_EXPR:
17250       RETURN (tsubst_expr(t, args, complain, in_decl,
17251 	     integral_constant_expression_p));
17252 
17253     case PAREN_EXPR:
17254       RETURN (finish_parenthesized_expr (RECUR (TREE_OPERAND (t, 0))));
17255 
17256     case VEC_PERM_EXPR:
17257       {
17258 	tree op0 = RECUR (TREE_OPERAND (t, 0));
17259 	tree op1 = RECUR (TREE_OPERAND (t, 1));
17260 	tree op2 = RECUR (TREE_OPERAND (t, 2));
17261 	RETURN (build_x_vec_perm_expr (input_location, op0, op1, op2,
17262 				       complain));
17263       }
17264 
17265     case REQUIRES_EXPR:
17266       RETURN (tsubst_requires_expr (t, args, complain, in_decl));
17267 
17268     default:
17269       /* Handle Objective-C++ constructs, if appropriate.  */
17270       {
17271 	tree subst
17272 	  = objcp_tsubst_copy_and_build (t, args, complain,
17273 					 in_decl, /*function_p=*/false);
17274 	if (subst)
17275 	  RETURN (subst);
17276       }
17277       RETURN (tsubst_copy (t, args, complain, in_decl));
17278     }
17279 
17280 #undef RECUR
17281 #undef RETURN
17282  out:
17283   input_location = loc;
17284   return retval;
17285 }
17286 
17287 /* Verify that the instantiated ARGS are valid. For type arguments,
17288    make sure that the type's linkage is ok. For non-type arguments,
17289    make sure they are constants if they are integral or enumerations.
17290    Emit an error under control of COMPLAIN, and return TRUE on error.  */
17291 
17292 static bool
check_instantiated_arg(tree tmpl,tree t,tsubst_flags_t complain)17293 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
17294 {
17295   if (dependent_template_arg_p (t))
17296     return false;
17297   if (ARGUMENT_PACK_P (t))
17298     {
17299       tree vec = ARGUMENT_PACK_ARGS (t);
17300       int len = TREE_VEC_LENGTH (vec);
17301       bool result = false;
17302       int i;
17303 
17304       for (i = 0; i < len; ++i)
17305 	if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
17306 	  result = true;
17307       return result;
17308     }
17309   else if (TYPE_P (t))
17310     {
17311       /* [basic.link]: A name with no linkage (notably, the name
17312 	 of a class or enumeration declared in a local scope)
17313 	 shall not be used to declare an entity with linkage.
17314 	 This implies that names with no linkage cannot be used as
17315 	 template arguments
17316 
17317 	 DR 757 relaxes this restriction for C++0x.  */
17318       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
17319 		 : no_linkage_check (t, /*relaxed_p=*/false));
17320 
17321       if (nt)
17322 	{
17323 	  /* DR 488 makes use of a type with no linkage cause
17324 	     type deduction to fail.  */
17325 	  if (complain & tf_error)
17326 	    {
17327 	      if (TYPE_ANONYMOUS_P (nt))
17328 		error ("%qT is/uses anonymous type", t);
17329 	      else
17330 		error ("template argument for %qD uses local type %qT",
17331 		       tmpl, t);
17332 	    }
17333 	  return true;
17334 	}
17335       /* In order to avoid all sorts of complications, we do not
17336 	 allow variably-modified types as template arguments.  */
17337       else if (variably_modified_type_p (t, NULL_TREE))
17338 	{
17339 	  if (complain & tf_error)
17340 	    error ("%qT is a variably modified type", t);
17341 	  return true;
17342 	}
17343     }
17344   /* Class template and alias template arguments should be OK.  */
17345   else if (DECL_TYPE_TEMPLATE_P (t))
17346     ;
17347   /* A non-type argument of integral or enumerated type must be a
17348      constant.  */
17349   else if (TREE_TYPE (t)
17350 	   && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
17351 	   && !REFERENCE_REF_P (t)
17352 	   && !TREE_CONSTANT (t))
17353     {
17354       if (complain & tf_error)
17355 	error ("integral expression %qE is not constant", t);
17356       return true;
17357     }
17358   return false;
17359 }
17360 
17361 static bool
check_instantiated_args(tree tmpl,tree args,tsubst_flags_t complain)17362 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
17363 {
17364   int ix, len = DECL_NTPARMS (tmpl);
17365   bool result = false;
17366 
17367   for (ix = 0; ix != len; ix++)
17368     {
17369       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
17370 	result = true;
17371     }
17372   if (result && (complain & tf_error))
17373     error ("  trying to instantiate %qD", tmpl);
17374   return result;
17375 }
17376 
17377 /* We're out of SFINAE context now, so generate diagnostics for the access
17378    errors we saw earlier when instantiating D from TMPL and ARGS.  */
17379 
17380 static void
recheck_decl_substitution(tree d,tree tmpl,tree args)17381 recheck_decl_substitution (tree d, tree tmpl, tree args)
17382 {
17383   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
17384   tree type = TREE_TYPE (pattern);
17385   location_t loc = input_location;
17386 
17387   push_access_scope (d);
17388   push_deferring_access_checks (dk_no_deferred);
17389   input_location = DECL_SOURCE_LOCATION (pattern);
17390   tsubst (type, args, tf_warning_or_error, d);
17391   input_location = loc;
17392   pop_deferring_access_checks ();
17393   pop_access_scope (d);
17394 }
17395 
17396 /* Instantiate the indicated variable, function, or alias template TMPL with
17397    the template arguments in TARG_PTR.  */
17398 
17399 static tree
instantiate_template_1(tree tmpl,tree orig_args,tsubst_flags_t complain)17400 instantiate_template_1 (tree tmpl, tree orig_args, tsubst_flags_t complain)
17401 {
17402   tree targ_ptr = orig_args;
17403   tree fndecl;
17404   tree gen_tmpl;
17405   tree spec;
17406   bool access_ok = true;
17407 
17408   if (tmpl == error_mark_node)
17409     return error_mark_node;
17410 
17411   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
17412 
17413   /* If this function is a clone, handle it specially.  */
17414   if (DECL_CLONED_FUNCTION_P (tmpl))
17415     {
17416       tree spec;
17417       tree clone;
17418 
17419       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
17420 	 DECL_CLONED_FUNCTION.  */
17421       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
17422 				   targ_ptr, complain);
17423       if (spec == error_mark_node)
17424 	return error_mark_node;
17425 
17426       /* Look for the clone.  */
17427       FOR_EACH_CLONE (clone, spec)
17428 	if (DECL_NAME (clone) == DECL_NAME (tmpl))
17429 	  return clone;
17430       /* We should always have found the clone by now.  */
17431       gcc_unreachable ();
17432       return NULL_TREE;
17433     }
17434 
17435   if (targ_ptr == error_mark_node)
17436     return error_mark_node;
17437 
17438   /* Check to see if we already have this specialization.  */
17439   gen_tmpl = most_general_template (tmpl);
17440   if (tmpl != gen_tmpl)
17441     /* The TMPL is a partial instantiation.  To get a full set of
17442        arguments we must add the arguments used to perform the
17443        partial instantiation.  */
17444     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
17445 					    targ_ptr);
17446 
17447   /* It would be nice to avoid hashing here and then again in tsubst_decl,
17448      but it doesn't seem to be on the hot path.  */
17449   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
17450 
17451   gcc_assert (tmpl == gen_tmpl
17452 	      || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
17453 		  == spec)
17454 	      || fndecl == NULL_TREE);
17455 
17456   if (spec != NULL_TREE)
17457     {
17458       if (FNDECL_HAS_ACCESS_ERRORS (spec))
17459 	{
17460 	  if (complain & tf_error)
17461 	    recheck_decl_substitution (spec, gen_tmpl, targ_ptr);
17462 	  return error_mark_node;
17463 	}
17464       return spec;
17465     }
17466 
17467   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
17468 			       complain))
17469     return error_mark_node;
17470 
17471   /* We are building a FUNCTION_DECL, during which the access of its
17472      parameters and return types have to be checked.  However this
17473      FUNCTION_DECL which is the desired context for access checking
17474      is not built yet.  We solve this chicken-and-egg problem by
17475      deferring all checks until we have the FUNCTION_DECL.  */
17476   push_deferring_access_checks (dk_deferred);
17477 
17478   /* Instantiation of the function happens in the context of the function
17479      template, not the context of the overload resolution we're doing.  */
17480   push_to_top_level ();
17481   /* If there are dependent arguments, e.g. because we're doing partial
17482      ordering, make sure processing_template_decl stays set.  */
17483   if (uses_template_parms (targ_ptr))
17484     ++processing_template_decl;
17485   if (DECL_CLASS_SCOPE_P (gen_tmpl))
17486     {
17487       tree ctx = tsubst_aggr_type (DECL_CONTEXT (gen_tmpl), targ_ptr,
17488 				   complain, gen_tmpl, true);
17489       push_nested_class (ctx);
17490     }
17491 
17492   tree pattern = DECL_TEMPLATE_RESULT (gen_tmpl);
17493 
17494   fndecl = NULL_TREE;
17495   if (VAR_P (pattern))
17496     {
17497       /* We need to determine if we're using a partial or explicit
17498 	 specialization now, because the type of the variable could be
17499 	 different.  */
17500       tree tid = lookup_template_variable (gen_tmpl, targ_ptr);
17501       tree elt = most_specialized_partial_spec (tid, complain);
17502       if (elt == error_mark_node)
17503 	pattern = error_mark_node;
17504       else if (elt)
17505 	{
17506 	  tree partial_tmpl = TREE_VALUE (elt);
17507 	  tree partial_args = TREE_PURPOSE (elt);
17508 	  tree partial_pat = DECL_TEMPLATE_RESULT (partial_tmpl);
17509 	  fndecl = tsubst (partial_pat, partial_args, complain, gen_tmpl);
17510 	}
17511     }
17512 
17513   /* Substitute template parameters to obtain the specialization.  */
17514   if (fndecl == NULL_TREE)
17515     fndecl = tsubst (pattern, targ_ptr, complain, gen_tmpl);
17516   if (DECL_CLASS_SCOPE_P (gen_tmpl))
17517     pop_nested_class ();
17518   pop_from_top_level ();
17519 
17520   if (fndecl == error_mark_node)
17521     {
17522       pop_deferring_access_checks ();
17523       return error_mark_node;
17524     }
17525 
17526   /* The DECL_TI_TEMPLATE should always be the immediate parent
17527      template, not the most general template.  */
17528   DECL_TI_TEMPLATE (fndecl) = tmpl;
17529   DECL_TI_ARGS (fndecl) = targ_ptr;
17530 
17531   /* Now we know the specialization, compute access previously
17532      deferred.  */
17533   push_access_scope (fndecl);
17534   if (!perform_deferred_access_checks (complain))
17535     access_ok = false;
17536   pop_access_scope (fndecl);
17537   pop_deferring_access_checks ();
17538 
17539   /* If we've just instantiated the main entry point for a function,
17540      instantiate all the alternate entry points as well.  We do this
17541      by cloning the instantiation of the main entry point, not by
17542      instantiating the template clones.  */
17543   if (DECL_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (DECL_CHAIN (gen_tmpl)))
17544     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
17545 
17546   if (!access_ok)
17547     {
17548       if (!(complain & tf_error))
17549 	{
17550 	  /* Remember to reinstantiate when we're out of SFINAE so the user
17551 	     can see the errors.  */
17552 	  FNDECL_HAS_ACCESS_ERRORS (fndecl) = true;
17553 	}
17554       return error_mark_node;
17555     }
17556   return fndecl;
17557 }
17558 
17559 /* Wrapper for instantiate_template_1.  */
17560 
17561 tree
instantiate_template(tree tmpl,tree orig_args,tsubst_flags_t complain)17562 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
17563 {
17564   tree ret;
17565   timevar_push (TV_TEMPLATE_INST);
17566   ret = instantiate_template_1 (tmpl, orig_args,  complain);
17567   timevar_pop (TV_TEMPLATE_INST);
17568   return ret;
17569 }
17570 
17571 /* Instantiate the alias template TMPL with ARGS.  Also push a template
17572    instantiation level, which instantiate_template doesn't do because
17573    functions and variables have sufficient context established by the
17574    callers.  */
17575 
17576 static tree
instantiate_alias_template(tree tmpl,tree args,tsubst_flags_t complain)17577 instantiate_alias_template (tree tmpl, tree args, tsubst_flags_t complain)
17578 {
17579   struct pending_template *old_last_pend = last_pending_template;
17580   struct tinst_level *old_error_tinst = last_error_tinst_level;
17581   if (tmpl == error_mark_node || args == error_mark_node)
17582     return error_mark_node;
17583   tree tinst = build_tree_list (tmpl, args);
17584   if (!push_tinst_level (tinst))
17585     {
17586       ggc_free (tinst);
17587       return error_mark_node;
17588     }
17589 
17590   args =
17591     coerce_innermost_template_parms (DECL_TEMPLATE_PARMS (tmpl),
17592 				     args, tmpl, complain,
17593 				     /*require_all_args=*/true,
17594 				     /*use_default_args=*/true);
17595 
17596   tree r = instantiate_template (tmpl, args, complain);
17597   pop_tinst_level ();
17598   /* We can't free this if a pending_template entry or last_error_tinst_level
17599      is pointing at it.  */
17600   if (last_pending_template == old_last_pend
17601       && last_error_tinst_level == old_error_tinst)
17602     ggc_free (tinst);
17603 
17604   return r;
17605 }
17606 
17607 /* PARM is a template parameter pack for FN.  Returns true iff
17608    PARM is used in a deducible way in the argument list of FN.  */
17609 
17610 static bool
pack_deducible_p(tree parm,tree fn)17611 pack_deducible_p (tree parm, tree fn)
17612 {
17613   tree t = FUNCTION_FIRST_USER_PARMTYPE (fn);
17614   for (; t; t = TREE_CHAIN (t))
17615     {
17616       tree type = TREE_VALUE (t);
17617       tree packs;
17618       if (!PACK_EXPANSION_P (type))
17619 	continue;
17620       for (packs = PACK_EXPANSION_PARAMETER_PACKS (type);
17621 	   packs; packs = TREE_CHAIN (packs))
17622 	if (template_args_equal (TREE_VALUE (packs), parm))
17623 	  {
17624 	    /* The template parameter pack is used in a function parameter
17625 	       pack.  If this is the end of the parameter list, the
17626 	       template parameter pack is deducible.  */
17627 	    if (TREE_CHAIN (t) == void_list_node)
17628 	      return true;
17629 	    else
17630 	      /* Otherwise, not.  Well, it could be deduced from
17631 		 a non-pack parameter, but doing so would end up with
17632 		 a deduction mismatch, so don't bother.  */
17633 	      return false;
17634 	  }
17635     }
17636   /* The template parameter pack isn't used in any function parameter
17637      packs, but it might be used deeper, e.g. tuple<Args...>.  */
17638   return true;
17639 }
17640 
17641 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
17642    NARGS elements of the arguments that are being used when calling
17643    it.  TARGS is a vector into which the deduced template arguments
17644    are placed.
17645 
17646    Returns either a FUNCTION_DECL for the matching specialization of FN or
17647    NULL_TREE if no suitable specialization can be found.  If EXPLAIN_P is
17648    true, diagnostics will be printed to explain why it failed.
17649 
17650    If FN is a conversion operator, or we are trying to produce a specific
17651    specialization, RETURN_TYPE is the return type desired.
17652 
17653    The EXPLICIT_TARGS are explicit template arguments provided via a
17654    template-id.
17655 
17656    The parameter STRICT is one of:
17657 
17658    DEDUCE_CALL:
17659      We are deducing arguments for a function call, as in
17660      [temp.deduct.call].  If RETURN_TYPE is non-null, we are
17661      deducing arguments for a call to the result of a conversion
17662      function template, as in [over.call.object].
17663 
17664    DEDUCE_CONV:
17665      We are deducing arguments for a conversion function, as in
17666      [temp.deduct.conv].
17667 
17668    DEDUCE_EXACT:
17669      We are deducing arguments when doing an explicit instantiation
17670      as in [temp.explicit], when determining an explicit specialization
17671      as in [temp.expl.spec], or when taking the address of a function
17672      template, as in [temp.deduct.funcaddr].  */
17673 
17674 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)17675 fn_type_unification (tree fn,
17676 		     tree explicit_targs,
17677 		     tree targs,
17678 		     const tree *args,
17679 		     unsigned int nargs,
17680 		     tree return_type,
17681 		     unification_kind_t strict,
17682 		     int flags,
17683 		     bool explain_p,
17684 		     bool decltype_p)
17685 {
17686   tree parms;
17687   tree fntype;
17688   tree decl = NULL_TREE;
17689   tsubst_flags_t complain = (explain_p ? tf_warning_or_error : tf_none);
17690   bool ok;
17691   static int deduction_depth;
17692   struct pending_template *old_last_pend = last_pending_template;
17693   struct tinst_level *old_error_tinst = last_error_tinst_level;
17694   tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
17695   tree tinst;
17696   tree r = error_mark_node;
17697 
17698   if (decltype_p)
17699     complain |= tf_decltype;
17700 
17701   /* In C++0x, it's possible to have a function template whose type depends
17702      on itself recursively.  This is most obvious with decltype, but can also
17703      occur with enumeration scope (c++/48969).  So we need to catch infinite
17704      recursion and reject the substitution at deduction time; this function
17705      will return error_mark_node for any repeated substitution.
17706 
17707      This also catches excessive recursion such as when f<N> depends on
17708      f<N-1> across all integers, and returns error_mark_node for all the
17709      substitutions back up to the initial one.
17710 
17711      This is, of course, not reentrant.  */
17712   if (excessive_deduction_depth)
17713     return error_mark_node;
17714   tinst = build_tree_list (fn, NULL_TREE);
17715   ++deduction_depth;
17716 
17717   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
17718 
17719   fntype = TREE_TYPE (fn);
17720   if (explicit_targs)
17721     {
17722       /* [temp.deduct]
17723 
17724 	 The specified template arguments must match the template
17725 	 parameters in kind (i.e., type, nontype, template), and there
17726 	 must not be more arguments than there are parameters;
17727 	 otherwise type deduction fails.
17728 
17729 	 Nontype arguments must match the types of the corresponding
17730 	 nontype template parameters, or must be convertible to the
17731 	 types of the corresponding nontype parameters as specified in
17732 	 _temp.arg.nontype_, otherwise type deduction fails.
17733 
17734 	 All references in the function type of the function template
17735 	 to the corresponding template parameters are replaced by the
17736 	 specified template argument values.  If a substitution in a
17737 	 template parameter or in the function type of the function
17738 	 template results in an invalid type, type deduction fails.  */
17739       int i, len = TREE_VEC_LENGTH (tparms);
17740       location_t loc = input_location;
17741       bool incomplete = false;
17742 
17743       /* Adjust any explicit template arguments before entering the
17744 	 substitution context.  */
17745       explicit_targs
17746 	= (coerce_template_parms (tparms, explicit_targs, NULL_TREE,
17747 				  complain,
17748 				  /*require_all_args=*/false,
17749 				  /*use_default_args=*/false));
17750       if (explicit_targs == error_mark_node)
17751 	goto fail;
17752 
17753       /* Substitute the explicit args into the function type.  This is
17754 	 necessary so that, for instance, explicitly declared function
17755 	 arguments can match null pointed constants.  If we were given
17756 	 an incomplete set of explicit args, we must not do semantic
17757 	 processing during substitution as we could create partial
17758 	 instantiations.  */
17759       for (i = 0; i < len; i++)
17760         {
17761           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
17762           bool parameter_pack = false;
17763 	  tree targ = TREE_VEC_ELT (explicit_targs, i);
17764 
17765           /* Dig out the actual parm.  */
17766           if (TREE_CODE (parm) == TYPE_DECL
17767               || TREE_CODE (parm) == TEMPLATE_DECL)
17768             {
17769               parm = TREE_TYPE (parm);
17770               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
17771             }
17772           else if (TREE_CODE (parm) == PARM_DECL)
17773             {
17774               parm = DECL_INITIAL (parm);
17775               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
17776             }
17777 
17778 	  if (!parameter_pack && targ == NULL_TREE)
17779 	    /* No explicit argument for this template parameter.  */
17780 	    incomplete = true;
17781 
17782           if (parameter_pack && pack_deducible_p (parm, fn))
17783             {
17784               /* Mark the argument pack as "incomplete". We could
17785                  still deduce more arguments during unification.
17786 	         We remove this mark in type_unification_real.  */
17787               if (targ)
17788                 {
17789                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
17790                   ARGUMENT_PACK_EXPLICIT_ARGS (targ)
17791                     = ARGUMENT_PACK_ARGS (targ);
17792                 }
17793 
17794               /* We have some incomplete argument packs.  */
17795               incomplete = true;
17796             }
17797         }
17798 
17799       TREE_VALUE (tinst) = explicit_targs;
17800       if (!push_tinst_level (tinst))
17801 	{
17802 	  excessive_deduction_depth = true;
17803 	  goto fail;
17804 	}
17805       processing_template_decl += incomplete;
17806       input_location = DECL_SOURCE_LOCATION (fn);
17807       /* Ignore any access checks; we'll see them again in
17808 	 instantiate_template and they might have the wrong
17809 	 access path at this point.  */
17810       push_deferring_access_checks (dk_deferred);
17811       fntype = tsubst (TREE_TYPE (fn), explicit_targs,
17812 		       complain | tf_partial, NULL_TREE);
17813       pop_deferring_access_checks ();
17814       input_location = loc;
17815       processing_template_decl -= incomplete;
17816       pop_tinst_level ();
17817 
17818       if (fntype == error_mark_node)
17819 	goto fail;
17820 
17821       /* Place the explicitly specified arguments in TARGS.  */
17822       for (i = NUM_TMPL_ARGS (explicit_targs); i--;)
17823 	TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (explicit_targs, i);
17824     }
17825 
17826   /* Never do unification on the 'this' parameter.  */
17827   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
17828 
17829   if (return_type && strict == DEDUCE_CALL)
17830     {
17831       /* We're deducing for a call to the result of a template conversion
17832          function.  The parms we really want are in return_type.  */
17833       if (POINTER_TYPE_P (return_type))
17834 	return_type = TREE_TYPE (return_type);
17835       parms = TYPE_ARG_TYPES (return_type);
17836     }
17837   else if (return_type)
17838     {
17839       tree *new_args;
17840 
17841       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
17842       new_args = XALLOCAVEC (tree, nargs + 1);
17843       new_args[0] = return_type;
17844       memcpy (new_args + 1, args, nargs * sizeof (tree));
17845       args = new_args;
17846       ++nargs;
17847     }
17848 
17849   /* We allow incomplete unification without an error message here
17850      because the standard doesn't seem to explicitly prohibit it.  Our
17851      callers must be ready to deal with unification failures in any
17852      event.  */
17853 
17854   TREE_VALUE (tinst) = targs;
17855   /* If we aren't explaining yet, push tinst context so we can see where
17856      any errors (e.g. from class instantiations triggered by instantiation
17857      of default template arguments) come from.  If we are explaining, this
17858      context is redundant.  */
17859   if (!explain_p && !push_tinst_level (tinst))
17860     {
17861       excessive_deduction_depth = true;
17862       goto fail;
17863     }
17864 
17865   /* type_unification_real will pass back any access checks from default
17866      template argument substitution.  */
17867   vec<deferred_access_check, va_gc> *checks;
17868   checks = NULL;
17869 
17870   ok = !type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
17871 			       targs, parms, args, nargs, /*subr=*/0,
17872 			       strict, flags, &checks, explain_p);
17873   if (!explain_p)
17874     pop_tinst_level ();
17875   if (!ok)
17876     goto fail;
17877 
17878   /* Now that we have bindings for all of the template arguments,
17879      ensure that the arguments deduced for the template template
17880      parameters have compatible template parameter lists.  We cannot
17881      check this property before we have deduced all template
17882      arguments, because the template parameter types of a template
17883      template parameter might depend on prior template parameters
17884      deduced after the template template parameter.  The following
17885      ill-formed example illustrates this issue:
17886 
17887        template<typename T, template<T> class C> void f(C<5>, T);
17888 
17889        template<int N> struct X {};
17890 
17891        void g() {
17892          f(X<5>(), 5l); // error: template argument deduction fails
17893        }
17894 
17895      The template parameter list of 'C' depends on the template type
17896      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
17897      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
17898      time that we deduce 'C'.  */
17899   if (!template_template_parm_bindings_ok_p
17900            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
17901     {
17902       unify_inconsistent_template_template_parameters (explain_p);
17903       goto fail;
17904     }
17905 
17906   /* All is well so far.  Now, check:
17907 
17908      [temp.deduct]
17909 
17910      When all template arguments have been deduced, all uses of
17911      template parameters in nondeduced contexts are replaced with
17912      the corresponding deduced argument values.  If the
17913      substitution results in an invalid type, as described above,
17914      type deduction fails.  */
17915   TREE_VALUE (tinst) = targs;
17916   if (!push_tinst_level (tinst))
17917     {
17918       excessive_deduction_depth = true;
17919       goto fail;
17920     }
17921 
17922   /* Also collect access checks from the instantiation.  */
17923   reopen_deferring_access_checks (checks);
17924 
17925   decl = instantiate_template (fn, targs, complain);
17926 
17927   checks = get_deferred_access_checks ();
17928   pop_deferring_access_checks ();
17929 
17930   pop_tinst_level ();
17931 
17932   if (decl == error_mark_node)
17933     goto fail;
17934 
17935   /* Now perform any access checks encountered during substitution.  */
17936   push_access_scope (decl);
17937   ok = perform_access_checks (checks, complain);
17938   pop_access_scope (decl);
17939   if (!ok)
17940     goto fail;
17941 
17942   /* If we're looking for an exact match, check that what we got
17943      is indeed an exact match.  It might not be if some template
17944      parameters are used in non-deduced contexts.  But don't check
17945      for an exact match if we have dependent template arguments;
17946      in that case we're doing partial ordering, and we already know
17947      that we have two candidates that will provide the actual type.  */
17948   if (strict == DEDUCE_EXACT && !any_dependent_template_arguments_p (targs))
17949     {
17950       tree substed = TREE_TYPE (decl);
17951       unsigned int i;
17952 
17953       tree sarg
17954 	= skip_artificial_parms_for (decl, TYPE_ARG_TYPES (substed));
17955       if (return_type)
17956 	sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
17957       for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
17958 	if (!same_type_p (args[i], TREE_VALUE (sarg)))
17959 	  {
17960 	    unify_type_mismatch (explain_p, args[i],
17961 				 TREE_VALUE (sarg));
17962 	    goto fail;
17963 	  }
17964     }
17965 
17966   r = decl;
17967 
17968  fail:
17969   --deduction_depth;
17970   if (excessive_deduction_depth)
17971     {
17972       if (deduction_depth == 0)
17973 	/* Reset once we're all the way out.  */
17974 	excessive_deduction_depth = false;
17975     }
17976 
17977   /* We can't free this if a pending_template entry or last_error_tinst_level
17978      is pointing at it.  */
17979   if (last_pending_template == old_last_pend
17980       && last_error_tinst_level == old_error_tinst)
17981     ggc_free (tinst);
17982 
17983   return r;
17984 }
17985 
17986 /* Adjust types before performing type deduction, as described in
17987    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
17988    sections are symmetric.  PARM is the type of a function parameter
17989    or the return type of the conversion function.  ARG is the type of
17990    the argument passed to the call, or the type of the value
17991    initialized with the result of the conversion function.
17992    ARG_EXPR is the original argument expression, which may be null.  */
17993 
17994 static int
maybe_adjust_types_for_deduction(unification_kind_t strict,tree * parm,tree * arg,tree arg_expr)17995 maybe_adjust_types_for_deduction (unification_kind_t strict,
17996 				  tree* parm,
17997 				  tree* arg,
17998 				  tree arg_expr)
17999 {
18000   int result = 0;
18001 
18002   switch (strict)
18003     {
18004     case DEDUCE_CALL:
18005       break;
18006 
18007     case DEDUCE_CONV:
18008       /* Swap PARM and ARG throughout the remainder of this
18009 	 function; the handling is precisely symmetric since PARM
18010 	 will initialize ARG rather than vice versa.  */
18011       std::swap (parm, arg);
18012       break;
18013 
18014     case DEDUCE_EXACT:
18015       /* Core issue #873: Do the DR606 thing (see below) for these cases,
18016 	 too, but here handle it by stripping the reference from PARM
18017 	 rather than by adding it to ARG.  */
18018       if (TREE_CODE (*parm) == REFERENCE_TYPE
18019 	  && TYPE_REF_IS_RVALUE (*parm)
18020 	  && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
18021 	  && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
18022 	  && TREE_CODE (*arg) == REFERENCE_TYPE
18023 	  && !TYPE_REF_IS_RVALUE (*arg))
18024 	*parm = TREE_TYPE (*parm);
18025       /* Nothing else to do in this case.  */
18026       return 0;
18027 
18028     default:
18029       gcc_unreachable ();
18030     }
18031 
18032   if (TREE_CODE (*parm) != REFERENCE_TYPE)
18033     {
18034       /* [temp.deduct.call]
18035 
18036 	 If P is not a reference type:
18037 
18038 	 --If A is an array type, the pointer type produced by the
18039 	 array-to-pointer standard conversion (_conv.array_) is
18040 	 used in place of A for type deduction; otherwise,
18041 
18042 	 --If A is a function type, the pointer type produced by
18043 	 the function-to-pointer standard conversion
18044 	 (_conv.func_) is used in place of A for type deduction;
18045 	 otherwise,
18046 
18047 	 --If A is a cv-qualified type, the top level
18048 	 cv-qualifiers of A's type are ignored for type
18049 	 deduction.  */
18050       if (TREE_CODE (*arg) == ARRAY_TYPE)
18051 	*arg = build_pointer_type (TREE_TYPE (*arg));
18052       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
18053 	*arg = build_pointer_type (*arg);
18054       else
18055 	*arg = TYPE_MAIN_VARIANT (*arg);
18056     }
18057 
18058   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
18059      of the form T&&, where T is a template parameter, and the argument
18060      is an lvalue, T is deduced as A& */
18061   if (TREE_CODE (*parm) == REFERENCE_TYPE
18062       && TYPE_REF_IS_RVALUE (*parm)
18063       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
18064       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
18065       && (arg_expr ? real_lvalue_p (arg_expr)
18066 	  /* try_one_overload doesn't provide an arg_expr, but
18067 	     functions are always lvalues.  */
18068 	  : TREE_CODE (*arg) == FUNCTION_TYPE))
18069     *arg = build_reference_type (*arg);
18070 
18071   /* [temp.deduct.call]
18072 
18073      If P is a cv-qualified type, the top level cv-qualifiers
18074      of P's type are ignored for type deduction.  If P is a
18075      reference type, the type referred to by P is used for
18076      type deduction.  */
18077   *parm = TYPE_MAIN_VARIANT (*parm);
18078   if (TREE_CODE (*parm) == REFERENCE_TYPE)
18079     {
18080       *parm = TREE_TYPE (*parm);
18081       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
18082     }
18083 
18084   /* DR 322. For conversion deduction, remove a reference type on parm
18085      too (which has been swapped into ARG).  */
18086   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
18087     *arg = TREE_TYPE (*arg);
18088 
18089   return result;
18090 }
18091 
18092 /* Subroutine of unify_one_argument.  PARM is a function parameter of a
18093    template which does contain any deducible template parameters; check if
18094    ARG is a suitable match for it.  STRICT, FLAGS and EXPLAIN_P are as in
18095    unify_one_argument.  */
18096 
18097 static int
check_non_deducible_conversion(tree parm,tree arg,int strict,int flags,bool explain_p)18098 check_non_deducible_conversion (tree parm, tree arg, int strict,
18099 				int flags, bool explain_p)
18100 {
18101   tree type;
18102 
18103   if (!TYPE_P (arg))
18104     type = TREE_TYPE (arg);
18105   else
18106     type = arg;
18107 
18108   if (same_type_p (parm, type))
18109     return unify_success (explain_p);
18110 
18111   if (strict == DEDUCE_CONV)
18112     {
18113       if (can_convert_arg (type, parm, NULL_TREE, flags,
18114 			   explain_p ? tf_warning_or_error : tf_none))
18115 	return unify_success (explain_p);
18116     }
18117   else if (strict != DEDUCE_EXACT)
18118     {
18119       if (can_convert_arg (parm, type,
18120 			   TYPE_P (arg) ? NULL_TREE : arg,
18121 			   flags, explain_p ? tf_warning_or_error : tf_none))
18122 	return unify_success (explain_p);
18123     }
18124 
18125   if (strict == DEDUCE_EXACT)
18126     return unify_type_mismatch (explain_p, parm, arg);
18127   else
18128     return unify_arg_conversion (explain_p, parm, type, arg);
18129 }
18130 
18131 static bool uses_deducible_template_parms (tree type);
18132 
18133 /* Returns true iff the expression EXPR is one from which a template
18134    argument can be deduced.  In other words, if it's an undecorated
18135    use of a template non-type parameter.  */
18136 
18137 static bool
deducible_expression(tree expr)18138 deducible_expression (tree expr)
18139 {
18140   return (TREE_CODE (expr) == TEMPLATE_PARM_INDEX);
18141 }
18142 
18143 /* Returns true iff the array domain DOMAIN uses a template parameter in a
18144    deducible way; that is, if it has a max value of <PARM> - 1.  */
18145 
18146 static bool
deducible_array_bound(tree domain)18147 deducible_array_bound (tree domain)
18148 {
18149   if (domain == NULL_TREE)
18150     return false;
18151 
18152   tree max = TYPE_MAX_VALUE (domain);
18153   if (TREE_CODE (max) != MINUS_EXPR)
18154     return false;
18155 
18156   return deducible_expression (TREE_OPERAND (max, 0));
18157 }
18158 
18159 /* Returns true iff the template arguments ARGS use a template parameter
18160    in a deducible way.  */
18161 
18162 static bool
deducible_template_args(tree args)18163 deducible_template_args (tree args)
18164 {
18165   for (int i = 0; i < TREE_VEC_LENGTH (args); ++i)
18166     {
18167       bool deducible;
18168       tree elt = TREE_VEC_ELT (args, i);
18169       if (ARGUMENT_PACK_P (elt))
18170 	deducible = deducible_template_args (ARGUMENT_PACK_ARGS (elt));
18171       else
18172 	{
18173 	  if (PACK_EXPANSION_P (elt))
18174 	    elt = PACK_EXPANSION_PATTERN (elt);
18175 	  if (TREE_CODE (elt) == TEMPLATE_TEMPLATE_PARM)
18176 	    deducible = true;
18177 	  else if (TYPE_P (elt))
18178 	    deducible = uses_deducible_template_parms (elt);
18179 	  else
18180 	    deducible = deducible_expression (elt);
18181 	}
18182       if (deducible)
18183 	return true;
18184     }
18185   return false;
18186 }
18187 
18188 /* Returns true iff TYPE contains any deducible references to template
18189    parameters, as per 14.8.2.5.  */
18190 
18191 static bool
uses_deducible_template_parms(tree type)18192 uses_deducible_template_parms (tree type)
18193 {
18194   if (PACK_EXPANSION_P (type))
18195     type = PACK_EXPANSION_PATTERN (type);
18196 
18197   /* T
18198      cv-list T
18199      TT<T>
18200      TT<i>
18201      TT<> */
18202   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
18203       || TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
18204     return true;
18205 
18206   /* T*
18207      T&
18208      T&&  */
18209   if (POINTER_TYPE_P (type))
18210     return uses_deducible_template_parms (TREE_TYPE (type));
18211 
18212   /* T[integer-constant ]
18213      type [i]  */
18214   if (TREE_CODE (type) == ARRAY_TYPE)
18215     return (uses_deducible_template_parms (TREE_TYPE (type))
18216 	    || deducible_array_bound (TYPE_DOMAIN (type)));
18217 
18218   /* T type ::*
18219      type T::*
18220      T T::*
18221      T (type ::*)()
18222      type (T::*)()
18223      type (type ::*)(T)
18224      type (T::*)(T)
18225      T (type ::*)(T)
18226      T (T::*)()
18227      T (T::*)(T) */
18228   if (TYPE_PTRMEM_P (type))
18229     return (uses_deducible_template_parms (TYPE_PTRMEM_CLASS_TYPE (type))
18230 	    || (uses_deducible_template_parms
18231 		(TYPE_PTRMEM_POINTED_TO_TYPE (type))));
18232 
18233   /* template-name <T> (where template-name refers to a class template)
18234      template-name <i> (where template-name refers to a class template) */
18235   if (CLASS_TYPE_P (type)
18236       && CLASSTYPE_TEMPLATE_INFO (type)
18237       && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type)))
18238     return deducible_template_args (INNERMOST_TEMPLATE_ARGS
18239 				    (CLASSTYPE_TI_ARGS (type)));
18240 
18241   /* type (T)
18242      T()
18243      T(T)  */
18244   if (TREE_CODE (type) == FUNCTION_TYPE
18245       || TREE_CODE (type) == METHOD_TYPE)
18246     {
18247       if (uses_deducible_template_parms (TREE_TYPE (type)))
18248 	return true;
18249       tree parm = TYPE_ARG_TYPES (type);
18250       if (TREE_CODE (type) == METHOD_TYPE)
18251 	parm = TREE_CHAIN (parm);
18252       for (; parm; parm = TREE_CHAIN (parm))
18253 	if (uses_deducible_template_parms (TREE_VALUE (parm)))
18254 	  return true;
18255     }
18256 
18257   return false;
18258 }
18259 
18260 /* Subroutine of type_unification_real and unify_pack_expansion to
18261    handle unification of a single P/A pair.  Parameters are as
18262    for those functions.  */
18263 
18264 static int
unify_one_argument(tree tparms,tree targs,tree parm,tree arg,int subr,unification_kind_t strict,bool explain_p)18265 unify_one_argument (tree tparms, tree targs, tree parm, tree arg,
18266 		    int subr, unification_kind_t strict,
18267 		    bool explain_p)
18268 {
18269   tree arg_expr = NULL_TREE;
18270   int arg_strict;
18271 
18272   if (arg == error_mark_node || parm == error_mark_node)
18273     return unify_invalid (explain_p);
18274   if (arg == unknown_type_node)
18275     /* We can't deduce anything from this, but we might get all the
18276        template args from other function args.  */
18277     return unify_success (explain_p);
18278 
18279   /* Implicit conversions (Clause 4) will be performed on a function
18280      argument to convert it to the type of the corresponding function
18281      parameter if the parameter type contains no template-parameters that
18282      participate in template argument deduction.  */
18283   if (strict != DEDUCE_EXACT
18284       && TYPE_P (parm) && !uses_deducible_template_parms (parm))
18285     /* For function parameters with no deducible template parameters,
18286        just return.  We'll check non-dependent conversions later.  */
18287     return unify_success (explain_p);
18288 
18289   switch (strict)
18290     {
18291     case DEDUCE_CALL:
18292       arg_strict = (UNIFY_ALLOW_OUTER_LEVEL
18293 		    | UNIFY_ALLOW_MORE_CV_QUAL
18294 		    | UNIFY_ALLOW_DERIVED);
18295       break;
18296 
18297     case DEDUCE_CONV:
18298       arg_strict = UNIFY_ALLOW_LESS_CV_QUAL;
18299       break;
18300 
18301     case DEDUCE_EXACT:
18302       arg_strict = UNIFY_ALLOW_NONE;
18303       break;
18304 
18305     default:
18306       gcc_unreachable ();
18307     }
18308 
18309   /* We only do these transformations if this is the top-level
18310      parameter_type_list in a call or declaration matching; in other
18311      situations (nested function declarators, template argument lists) we
18312      won't be comparing a type to an expression, and we don't do any type
18313      adjustments.  */
18314   if (!subr)
18315     {
18316       if (!TYPE_P (arg))
18317 	{
18318 	  gcc_assert (TREE_TYPE (arg) != NULL_TREE);
18319 	  if (type_unknown_p (arg))
18320 	    {
18321 	      /* [temp.deduct.type] A template-argument can be
18322 		 deduced from a pointer to function or pointer
18323 		 to member function argument if the set of
18324 		 overloaded functions does not contain function
18325 		 templates and at most one of a set of
18326 		 overloaded functions provides a unique
18327 		 match.  */
18328 
18329 	      if (resolve_overloaded_unification
18330 		  (tparms, targs, parm, arg, strict,
18331 		   arg_strict, explain_p))
18332 		return unify_success (explain_p);
18333 	      return unify_overload_resolution_failure (explain_p, arg);
18334 	    }
18335 
18336 	  arg_expr = arg;
18337 	  arg = unlowered_expr_type (arg);
18338 	  if (arg == error_mark_node)
18339 	    return unify_invalid (explain_p);
18340 	}
18341 
18342       arg_strict |=
18343 	maybe_adjust_types_for_deduction (strict, &parm, &arg, arg_expr);
18344     }
18345   else
18346     if ((TYPE_P (parm) || TREE_CODE (parm) == TEMPLATE_DECL)
18347 	!= (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL))
18348       return unify_template_argument_mismatch (explain_p, parm, arg);
18349 
18350   /* For deduction from an init-list we need the actual list.  */
18351   if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
18352     arg = arg_expr;
18353   return unify (tparms, targs, parm, arg, arg_strict, explain_p);
18354 }
18355 
18356 /* Most parms like fn_type_unification.
18357 
18358    If SUBR is 1, we're being called recursively (to unify the
18359    arguments of a function or method parameter of a function
18360    template).
18361 
18362    CHECKS is a pointer to a vector of access checks encountered while
18363    substituting default template arguments.  */
18364 
18365 static int
type_unification_real(tree tparms,tree 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)18366 type_unification_real (tree tparms,
18367 		       tree targs,
18368 		       tree xparms,
18369 		       const tree *xargs,
18370 		       unsigned int xnargs,
18371 		       int subr,
18372 		       unification_kind_t strict,
18373 		       int flags,
18374 		       vec<deferred_access_check, va_gc> **checks,
18375 		       bool explain_p)
18376 {
18377   tree parm, arg;
18378   int i;
18379   int ntparms = TREE_VEC_LENGTH (tparms);
18380   int saw_undeduced = 0;
18381   tree parms;
18382   const tree *args;
18383   unsigned int nargs;
18384   unsigned int ia;
18385 
18386   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
18387   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
18388   gcc_assert (ntparms > 0);
18389 
18390   /* Reset the number of non-defaulted template arguments contained
18391      in TARGS.  */
18392   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
18393 
18394  again:
18395   parms = xparms;
18396   args = xargs;
18397   nargs = xnargs;
18398 
18399   ia = 0;
18400   while (parms && parms != void_list_node
18401 	 && ia < nargs)
18402     {
18403       parm = TREE_VALUE (parms);
18404 
18405       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
18406 	  && (!TREE_CHAIN (parms) || TREE_CHAIN (parms) == void_list_node))
18407 	/* For a function parameter pack that occurs at the end of the
18408 	   parameter-declaration-list, the type A of each remaining
18409 	   argument of the call is compared with the type P of the
18410 	   declarator-id of the function parameter pack.  */
18411 	break;
18412 
18413       parms = TREE_CHAIN (parms);
18414 
18415       if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
18416 	/* For a function parameter pack that does not occur at the
18417 	   end of the parameter-declaration-list, the type of the
18418 	   parameter pack is a non-deduced context.  */
18419 	continue;
18420 
18421       arg = args[ia];
18422       ++ia;
18423 
18424       if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
18425 			      explain_p))
18426 	return 1;
18427     }
18428 
18429   if (parms
18430       && parms != void_list_node
18431       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
18432     {
18433       /* Unify the remaining arguments with the pack expansion type.  */
18434       tree argvec;
18435       tree parmvec = make_tree_vec (1);
18436 
18437       /* Allocate a TREE_VEC and copy in all of the arguments */
18438       argvec = make_tree_vec (nargs - ia);
18439       for (i = 0; ia < nargs; ++ia, ++i)
18440 	TREE_VEC_ELT (argvec, i) = args[ia];
18441 
18442       /* Copy the parameter into parmvec.  */
18443       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
18444       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
18445                                 /*subr=*/subr, explain_p))
18446         return 1;
18447 
18448       /* Advance to the end of the list of parameters.  */
18449       parms = TREE_CHAIN (parms);
18450     }
18451 
18452   /* Fail if we've reached the end of the parm list, and more args
18453      are present, and the parm list isn't variadic.  */
18454   if (ia < nargs && parms == void_list_node)
18455     return unify_too_many_arguments (explain_p, nargs, ia);
18456   /* Fail if parms are left and they don't have default values and
18457      they aren't all deduced as empty packs (c++/57397).  This is
18458      consistent with sufficient_parms_p.  */
18459   if (parms && parms != void_list_node
18460       && TREE_PURPOSE (parms) == NULL_TREE)
18461     {
18462       unsigned int count = nargs;
18463       tree p = parms;
18464       bool type_pack_p;
18465       do
18466 	{
18467 	  type_pack_p = TREE_CODE (TREE_VALUE (p)) == TYPE_PACK_EXPANSION;
18468 	  if (!type_pack_p)
18469 	    count++;
18470 	  p = TREE_CHAIN (p);
18471 	}
18472       while (p && p != void_list_node);
18473       if (count != nargs)
18474 	return unify_too_few_arguments (explain_p, ia, count,
18475 					type_pack_p);
18476     }
18477 
18478   if (!subr)
18479     {
18480       tsubst_flags_t complain = (explain_p
18481 				 ? tf_warning_or_error
18482 				 : tf_none);
18483 
18484       for (i = 0; i < ntparms; i++)
18485 	{
18486 	  tree targ = TREE_VEC_ELT (targs, i);
18487 	  tree tparm = TREE_VEC_ELT (tparms, i);
18488 
18489 	  /* Clear the "incomplete" flags on all argument packs now so that
18490 	     substituting them into later default arguments works.  */
18491 	  if (targ && ARGUMENT_PACK_P (targ))
18492             {
18493               ARGUMENT_PACK_INCOMPLETE_P (targ) = 0;
18494               ARGUMENT_PACK_EXPLICIT_ARGS (targ) = NULL_TREE;
18495             }
18496 
18497 	  if (targ || tparm == error_mark_node)
18498 	    continue;
18499 	  tparm = TREE_VALUE (tparm);
18500 
18501 	  /* If this is an undeduced nontype parameter that depends on
18502 	     a type parameter, try another pass; its type may have been
18503 	     deduced from a later argument than the one from which
18504 	     this parameter can be deduced.  */
18505 	  if (TREE_CODE (tparm) == PARM_DECL
18506 	      && uses_template_parms (TREE_TYPE (tparm))
18507 	      && saw_undeduced < 2)
18508 	    {
18509 	      saw_undeduced = 1;
18510 	      continue;
18511 	    }
18512 
18513 	  /* Core issue #226 (C++0x) [temp.deduct]:
18514 
18515 	     If a template argument has not been deduced, its
18516 	     default template argument, if any, is used.
18517 
18518 	     When we are in C++98 mode, TREE_PURPOSE will either
18519 	     be NULL_TREE or ERROR_MARK_NODE, so we do not need
18520 	     to explicitly check cxx_dialect here.  */
18521 	  if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
18522 	    /* OK, there is a default argument.  Wait until after the
18523 	       conversion check to do substitution.  */
18524 	    continue;
18525 
18526 	  /* If the type parameter is a parameter pack, then it will
18527 	     be deduced to an empty parameter pack.  */
18528 	  if (template_parameter_pack_p (tparm))
18529 	    {
18530 	      tree arg;
18531 
18532 	      if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
18533 		{
18534 		  arg = make_node (NONTYPE_ARGUMENT_PACK);
18535 		  TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
18536 		  TREE_CONSTANT (arg) = 1;
18537 		}
18538 	      else
18539 		arg = cxx_make_type (TYPE_ARGUMENT_PACK);
18540 
18541 	      SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
18542 
18543 	      TREE_VEC_ELT (targs, i) = arg;
18544 	      continue;
18545 	    }
18546 
18547 	  return unify_parameter_deduction_failure (explain_p, tparm);
18548 	}
18549 
18550       /* DR 1391: All parameters have args, now check non-dependent parms for
18551 	 convertibility.  */
18552       if (saw_undeduced < 2)
18553 	for (ia = 0, parms = xparms, args = xargs, nargs = xnargs;
18554 	     parms && parms != void_list_node && ia < nargs; )
18555 	  {
18556 	    parm = TREE_VALUE (parms);
18557 
18558 	    if (TREE_CODE (parm) == TYPE_PACK_EXPANSION
18559 		&& (!TREE_CHAIN (parms)
18560 		    || TREE_CHAIN (parms) == void_list_node))
18561 	      /* For a function parameter pack that occurs at the end of the
18562 		 parameter-declaration-list, the type A of each remaining
18563 		 argument of the call is compared with the type P of the
18564 		 declarator-id of the function parameter pack.  */
18565 	      break;
18566 
18567 	    parms = TREE_CHAIN (parms);
18568 
18569 	    if (TREE_CODE (parm) == TYPE_PACK_EXPANSION)
18570 	      /* For a function parameter pack that does not occur at the
18571 		 end of the parameter-declaration-list, the type of the
18572 		 parameter pack is a non-deduced context.  */
18573 	      continue;
18574 
18575 	    arg = args[ia];
18576 	    ++ia;
18577 
18578 	    if (uses_template_parms (parm))
18579 	      continue;
18580 	    if (check_non_deducible_conversion (parm, arg, strict, flags,
18581 						explain_p))
18582 	      return 1;
18583 	  }
18584 
18585       /* Now substitute into the default template arguments.  */
18586       for (i = 0; i < ntparms; i++)
18587 	{
18588 	  tree targ = TREE_VEC_ELT (targs, i);
18589 	  tree tparm = TREE_VEC_ELT (tparms, i);
18590 
18591 	  if (targ || tparm == error_mark_node)
18592 	    continue;
18593 	  tree parm = TREE_VALUE (tparm);
18594 
18595 	  if (TREE_CODE (parm) == PARM_DECL
18596 	      && uses_template_parms (TREE_TYPE (parm))
18597 	      && saw_undeduced < 2)
18598 	    continue;
18599 
18600 	  tree arg = TREE_PURPOSE (tparm);
18601 	  reopen_deferring_access_checks (*checks);
18602 	  location_t save_loc = input_location;
18603 	  if (DECL_P (parm))
18604 	    input_location = DECL_SOURCE_LOCATION (parm);
18605 	  arg = tsubst_template_arg (arg, targs, complain, NULL_TREE);
18606 	  if (!uses_template_parms (arg))
18607 	    arg = convert_template_argument (parm, arg, targs, complain,
18608 					     i, NULL_TREE);
18609 	  else if (saw_undeduced < 2)
18610 	    arg = NULL_TREE;
18611 	  else
18612 	    arg = error_mark_node;
18613 	  input_location = save_loc;
18614 	  *checks = get_deferred_access_checks ();
18615 	  pop_deferring_access_checks ();
18616 	  if (arg == error_mark_node)
18617 	    return 1;
18618 	  else if (arg)
18619 	    {
18620 	      TREE_VEC_ELT (targs, i) = arg;
18621 	      /* The position of the first default template argument,
18622 		 is also the number of non-defaulted arguments in TARGS.
18623 		 Record that.  */
18624 	      if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
18625 		SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
18626 	    }
18627 	}
18628 
18629       if (saw_undeduced++ == 1)
18630 	goto again;
18631     }
18632 
18633   if (CHECKING_P && !NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
18634     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
18635 
18636   return unify_success (explain_p);
18637 }
18638 
18639 /* Subroutine of type_unification_real.  Args are like the variables
18640    at the call site.  ARG is an overloaded function (or template-id);
18641    we try deducing template args from each of the overloads, and if
18642    only one succeeds, we go with that.  Modifies TARGS and returns
18643    true on success.  */
18644 
18645 static bool
resolve_overloaded_unification(tree tparms,tree targs,tree parm,tree arg,unification_kind_t strict,int sub_strict,bool explain_p)18646 resolve_overloaded_unification (tree tparms,
18647 				tree targs,
18648 				tree parm,
18649 				tree arg,
18650 				unification_kind_t strict,
18651 				int sub_strict,
18652 			        bool explain_p)
18653 {
18654   tree tempargs = copy_node (targs);
18655   int good = 0;
18656   tree goodfn = NULL_TREE;
18657   bool addr_p;
18658 
18659   if (TREE_CODE (arg) == ADDR_EXPR)
18660     {
18661       arg = TREE_OPERAND (arg, 0);
18662       addr_p = true;
18663     }
18664   else
18665     addr_p = false;
18666 
18667   if (TREE_CODE (arg) == COMPONENT_REF)
18668     /* Handle `&x' where `x' is some static or non-static member
18669        function name.  */
18670     arg = TREE_OPERAND (arg, 1);
18671 
18672   if (TREE_CODE (arg) == OFFSET_REF)
18673     arg = TREE_OPERAND (arg, 1);
18674 
18675   /* Strip baselink information.  */
18676   if (BASELINK_P (arg))
18677     arg = BASELINK_FUNCTIONS (arg);
18678 
18679   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
18680     {
18681       /* If we got some explicit template args, we need to plug them into
18682 	 the affected templates before we try to unify, in case the
18683 	 explicit args will completely resolve the templates in question.  */
18684 
18685       int ok = 0;
18686       tree expl_subargs = TREE_OPERAND (arg, 1);
18687       arg = TREE_OPERAND (arg, 0);
18688 
18689       for (; arg; arg = OVL_NEXT (arg))
18690 	{
18691 	  tree fn = OVL_CURRENT (arg);
18692 	  tree subargs, elem;
18693 
18694 	  if (TREE_CODE (fn) != TEMPLATE_DECL)
18695 	    continue;
18696 
18697 	  subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
18698 					   expl_subargs, NULL_TREE, tf_none,
18699 					   /*require_all_args=*/true,
18700 					   /*use_default_args=*/true);
18701 	  if (subargs != error_mark_node
18702 	      && !any_dependent_template_arguments_p (subargs))
18703 	    {
18704 	      elem = TREE_TYPE (instantiate_template (fn, subargs, tf_none));
18705 	      if (try_one_overload (tparms, targs, tempargs, parm,
18706 				    elem, strict, sub_strict, addr_p, explain_p)
18707 		  && (!goodfn || !same_type_p (goodfn, elem)))
18708 		{
18709 		  goodfn = elem;
18710 		  ++good;
18711 		}
18712 	    }
18713 	  else if (subargs)
18714 	    ++ok;
18715 	}
18716       /* If no templates (or more than one) are fully resolved by the
18717 	 explicit arguments, this template-id is a non-deduced context; it
18718 	 could still be OK if we deduce all template arguments for the
18719 	 enclosing call through other arguments.  */
18720       if (good != 1)
18721 	good = ok;
18722     }
18723   else if (TREE_CODE (arg) != OVERLOAD
18724 	   && TREE_CODE (arg) != FUNCTION_DECL)
18725     /* If ARG is, for example, "(0, &f)" then its type will be unknown
18726        -- but the deduction does not succeed because the expression is
18727        not just the function on its own.  */
18728     return false;
18729   else
18730     for (; arg; arg = OVL_NEXT (arg))
18731       if (try_one_overload (tparms, targs, tempargs, parm,
18732 			    TREE_TYPE (OVL_CURRENT (arg)),
18733 			    strict, sub_strict, addr_p, explain_p)
18734 	  && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
18735 	{
18736 	  goodfn = OVL_CURRENT (arg);
18737 	  ++good;
18738 	}
18739 
18740   /* [temp.deduct.type] A template-argument can be deduced from a pointer
18741      to function or pointer to member function argument if the set of
18742      overloaded functions does not contain function templates and at most
18743      one of a set of overloaded functions provides a unique match.
18744 
18745      So if we found multiple possibilities, we return success but don't
18746      deduce anything.  */
18747 
18748   if (good == 1)
18749     {
18750       int i = TREE_VEC_LENGTH (targs);
18751       for (; i--; )
18752 	if (TREE_VEC_ELT (tempargs, i))
18753 	  {
18754 	    tree old = TREE_VEC_ELT (targs, i);
18755 	    tree new_ = TREE_VEC_ELT (tempargs, i);
18756 	    if (new_ && old && ARGUMENT_PACK_P (old)
18757 		&& ARGUMENT_PACK_EXPLICIT_ARGS (old))
18758 	      /* Don't forget explicit template arguments in a pack.  */
18759 	      ARGUMENT_PACK_EXPLICIT_ARGS (new_)
18760 		= ARGUMENT_PACK_EXPLICIT_ARGS (old);
18761 	    TREE_VEC_ELT (targs, i) = new_;
18762 	  }
18763     }
18764   if (good)
18765     return true;
18766 
18767   return false;
18768 }
18769 
18770 /* Core DR 115: In contexts where deduction is done and fails, or in
18771    contexts where deduction is not done, if a template argument list is
18772    specified and it, along with any default template arguments, identifies
18773    a single function template specialization, then the template-id is an
18774    lvalue for the function template specialization.  */
18775 
18776 tree
resolve_nondeduced_context(tree orig_expr,tsubst_flags_t complain)18777 resolve_nondeduced_context (tree orig_expr, tsubst_flags_t complain)
18778 {
18779   tree expr, offset, baselink;
18780   bool addr;
18781 
18782   if (!type_unknown_p (orig_expr))
18783     return orig_expr;
18784 
18785   expr = orig_expr;
18786   addr = false;
18787   offset = NULL_TREE;
18788   baselink = NULL_TREE;
18789 
18790   if (TREE_CODE (expr) == ADDR_EXPR)
18791     {
18792       expr = TREE_OPERAND (expr, 0);
18793       addr = true;
18794     }
18795   if (TREE_CODE (expr) == OFFSET_REF)
18796     {
18797       offset = expr;
18798       expr = TREE_OPERAND (expr, 1);
18799     }
18800   if (BASELINK_P (expr))
18801     {
18802       baselink = expr;
18803       expr = BASELINK_FUNCTIONS (expr);
18804     }
18805 
18806   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
18807     {
18808       int good = 0;
18809       tree goodfn = NULL_TREE;
18810 
18811       /* If we got some explicit template args, we need to plug them into
18812 	 the affected templates before we try to unify, in case the
18813 	 explicit args will completely resolve the templates in question.  */
18814 
18815       tree expl_subargs = TREE_OPERAND (expr, 1);
18816       tree arg = TREE_OPERAND (expr, 0);
18817       tree badfn = NULL_TREE;
18818       tree badargs = NULL_TREE;
18819 
18820       for (; arg; arg = OVL_NEXT (arg))
18821 	{
18822 	  tree fn = OVL_CURRENT (arg);
18823 	  tree subargs, elem;
18824 
18825 	  if (TREE_CODE (fn) != TEMPLATE_DECL)
18826 	    continue;
18827 
18828 	  subargs = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
18829 					   expl_subargs, NULL_TREE, tf_none,
18830 					   /*require_all_args=*/true,
18831 					   /*use_default_args=*/true);
18832 	  if (subargs != error_mark_node
18833 	      && !any_dependent_template_arguments_p (subargs))
18834 	    {
18835 	      elem = instantiate_template (fn, subargs, tf_none);
18836 	      if (elem == error_mark_node)
18837 		{
18838 		  badfn = fn;
18839 		  badargs = subargs;
18840 		}
18841 	      else if (elem && (!goodfn || !decls_match (goodfn, elem)))
18842 		{
18843 		  goodfn = elem;
18844 		  ++good;
18845 		}
18846 	    }
18847 	}
18848       if (good == 1)
18849 	{
18850 	  mark_used (goodfn);
18851 	  expr = goodfn;
18852 	  if (baselink)
18853 	    expr = build_baselink (BASELINK_BINFO (baselink),
18854 				   BASELINK_ACCESS_BINFO (baselink),
18855 				   expr, BASELINK_OPTYPE (baselink));
18856 	  if (offset)
18857 	    {
18858 	      tree base
18859 		= TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
18860 	      expr = build_offset_ref (base, expr, addr, complain);
18861 	    }
18862 	  if (addr)
18863 	    expr = cp_build_addr_expr (expr, complain);
18864 	  return expr;
18865 	}
18866       else if (good == 0 && badargs && (complain & tf_error))
18867 	/* There were no good options and at least one bad one, so let the
18868 	   user know what the problem is.  */
18869 	instantiate_template (badfn, badargs, complain);
18870     }
18871   return orig_expr;
18872 }
18873 
18874 /* Subroutine of resolve_overloaded_unification; does deduction for a single
18875    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
18876    different overloads deduce different arguments for a given parm.
18877    ADDR_P is true if the expression for which deduction is being
18878    performed was of the form "& fn" rather than simply "fn".
18879 
18880    Returns 1 on success.  */
18881 
18882 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)18883 try_one_overload (tree tparms,
18884 		  tree orig_targs,
18885 		  tree targs,
18886 		  tree parm,
18887 		  tree arg,
18888 		  unification_kind_t strict,
18889 		  int sub_strict,
18890 		  bool addr_p,
18891 		  bool explain_p)
18892 {
18893   int nargs;
18894   tree tempargs;
18895   int i;
18896 
18897   if (arg == error_mark_node)
18898     return 0;
18899 
18900   /* [temp.deduct.type] A template-argument can be deduced from a pointer
18901      to function or pointer to member function argument if the set of
18902      overloaded functions does not contain function templates and at most
18903      one of a set of overloaded functions provides a unique match.
18904 
18905      So if this is a template, just return success.  */
18906 
18907   if (uses_template_parms (arg))
18908     return 1;
18909 
18910   if (TREE_CODE (arg) == METHOD_TYPE)
18911     arg = build_ptrmemfunc_type (build_pointer_type (arg));
18912   else if (addr_p)
18913     arg = build_pointer_type (arg);
18914 
18915   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
18916 
18917   /* We don't copy orig_targs for this because if we have already deduced
18918      some template args from previous args, unify would complain when we
18919      try to deduce a template parameter for the same argument, even though
18920      there isn't really a conflict.  */
18921   nargs = TREE_VEC_LENGTH (targs);
18922   tempargs = make_tree_vec (nargs);
18923 
18924   if (unify (tparms, tempargs, parm, arg, sub_strict, explain_p))
18925     return 0;
18926 
18927   /* First make sure we didn't deduce anything that conflicts with
18928      explicitly specified args.  */
18929   for (i = nargs; i--; )
18930     {
18931       tree elt = TREE_VEC_ELT (tempargs, i);
18932       tree oldelt = TREE_VEC_ELT (orig_targs, i);
18933 
18934       if (!elt)
18935 	/*NOP*/;
18936       else if (uses_template_parms (elt))
18937 	/* Since we're unifying against ourselves, we will fill in
18938 	   template args used in the function parm list with our own
18939 	   template parms.  Discard them.  */
18940 	TREE_VEC_ELT (tempargs, i) = NULL_TREE;
18941       else if (oldelt && ARGUMENT_PACK_P (oldelt))
18942 	{
18943 	  /* Check that the argument at each index of the deduced argument pack
18944 	     is equivalent to the corresponding explicitly specified argument.
18945 	     We may have deduced more arguments than were explicitly specified,
18946 	     and that's OK.  */
18947 
18948 	  /* We used to assert ARGUMENT_PACK_INCOMPLETE_P (oldelt) here, but
18949 	     that's wrong if we deduce the same argument pack from multiple
18950 	     function arguments: it's only incomplete the first time.  */
18951 
18952 	  tree explicit_pack = ARGUMENT_PACK_ARGS (oldelt);
18953 	  tree deduced_pack = ARGUMENT_PACK_ARGS (elt);
18954 
18955 	  if (TREE_VEC_LENGTH (deduced_pack)
18956 	      < TREE_VEC_LENGTH (explicit_pack))
18957 	    return 0;
18958 
18959 	  for (int j = 0; j < TREE_VEC_LENGTH (explicit_pack); j++)
18960 	    if (!template_args_equal (TREE_VEC_ELT (explicit_pack, j),
18961 				      TREE_VEC_ELT (deduced_pack, j)))
18962 	      return 0;
18963 	}
18964       else if (oldelt && !template_args_equal (oldelt, elt))
18965 	return 0;
18966     }
18967 
18968   for (i = nargs; i--; )
18969     {
18970       tree elt = TREE_VEC_ELT (tempargs, i);
18971 
18972       if (elt)
18973 	TREE_VEC_ELT (targs, i) = elt;
18974     }
18975 
18976   return 1;
18977 }
18978 
18979 /* PARM is a template class (perhaps with unbound template
18980    parameters).  ARG is a fully instantiated type.  If ARG can be
18981    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
18982    TARGS are as for unify.  */
18983 
18984 static tree
try_class_unification(tree tparms,tree targs,tree parm,tree arg,bool explain_p)18985 try_class_unification (tree tparms, tree targs, tree parm, tree arg,
18986 		       bool explain_p)
18987 {
18988   tree copy_of_targs;
18989 
18990   if (!CLASSTYPE_TEMPLATE_INFO (arg)
18991       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
18992 	  != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
18993     return NULL_TREE;
18994 
18995   /* We need to make a new template argument vector for the call to
18996      unify.  If we used TARGS, we'd clutter it up with the result of
18997      the attempted unification, even if this class didn't work out.
18998      We also don't want to commit ourselves to all the unifications
18999      we've already done, since unification is supposed to be done on
19000      an argument-by-argument basis.  In other words, consider the
19001      following pathological case:
19002 
19003        template <int I, int J, int K>
19004        struct S {};
19005 
19006        template <int I, int J>
19007        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
19008 
19009        template <int I, int J, int K>
19010        void f(S<I, J, K>, S<I, I, I>);
19011 
19012        void g() {
19013 	 S<0, 0, 0> s0;
19014 	 S<0, 1, 2> s2;
19015 
19016 	 f(s0, s2);
19017        }
19018 
19019      Now, by the time we consider the unification involving `s2', we
19020      already know that we must have `f<0, 0, 0>'.  But, even though
19021      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
19022      because there are two ways to unify base classes of S<0, 1, 2>
19023      with S<I, I, I>.  If we kept the already deduced knowledge, we
19024      would reject the possibility I=1.  */
19025   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
19026 
19027   /* If unification failed, we're done.  */
19028   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
19029 	     CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE, explain_p))
19030     return NULL_TREE;
19031 
19032   return arg;
19033 }
19034 
19035 /* Given a template type PARM and a class type ARG, find the unique
19036    base type in ARG that is an instance of PARM.  We do not examine
19037    ARG itself; only its base-classes.  If there is not exactly one
19038    appropriate base class, return NULL_TREE.  PARM may be the type of
19039    a partial specialization, as well as a plain template type.  Used
19040    by unify.  */
19041 
19042 static enum template_base_result
get_template_base(tree tparms,tree targs,tree parm,tree arg,bool explain_p,tree * result)19043 get_template_base (tree tparms, tree targs, tree parm, tree arg,
19044 		   bool explain_p, tree *result)
19045 {
19046   tree rval = NULL_TREE;
19047   tree binfo;
19048 
19049   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
19050 
19051   binfo = TYPE_BINFO (complete_type (arg));
19052   if (!binfo)
19053     {
19054       /* The type could not be completed.  */
19055       *result = NULL_TREE;
19056       return tbr_incomplete_type;
19057     }
19058 
19059   /* Walk in inheritance graph order.  The search order is not
19060      important, and this avoids multiple walks of virtual bases.  */
19061   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
19062     {
19063       tree r = try_class_unification (tparms, targs, parm,
19064 				      BINFO_TYPE (binfo), explain_p);
19065 
19066       if (r)
19067 	{
19068 	  /* If there is more than one satisfactory baseclass, then:
19069 
19070 	       [temp.deduct.call]
19071 
19072 	      If they yield more than one possible deduced A, the type
19073 	      deduction fails.
19074 
19075 	     applies.  */
19076 	  if (rval && !same_type_p (r, rval))
19077 	    {
19078 	      *result = NULL_TREE;
19079 	      return tbr_ambiguous_baseclass;
19080 	    }
19081 
19082 	  rval = r;
19083 	}
19084     }
19085 
19086   *result = rval;
19087   return tbr_success;
19088 }
19089 
19090 /* Returns the level of DECL, which declares a template parameter.  */
19091 
19092 static int
template_decl_level(tree decl)19093 template_decl_level (tree decl)
19094 {
19095   switch (TREE_CODE (decl))
19096     {
19097     case TYPE_DECL:
19098     case TEMPLATE_DECL:
19099       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
19100 
19101     case PARM_DECL:
19102       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
19103 
19104     default:
19105       gcc_unreachable ();
19106     }
19107   return 0;
19108 }
19109 
19110 /* Decide whether ARG can be unified with PARM, considering only the
19111    cv-qualifiers of each type, given STRICT as documented for unify.
19112    Returns nonzero iff the unification is OK on that basis.  */
19113 
19114 static int
check_cv_quals_for_unify(int strict,tree arg,tree parm)19115 check_cv_quals_for_unify (int strict, tree arg, tree parm)
19116 {
19117   int arg_quals = cp_type_quals (arg);
19118   int parm_quals = cp_type_quals (parm);
19119 
19120   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
19121       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
19122     {
19123       /*  Although a CVR qualifier is ignored when being applied to a
19124 	  substituted template parameter ([8.3.2]/1 for example), that
19125 	  does not allow us to unify "const T" with "int&" because both
19126 	  types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
19127 	  It is ok when we're allowing additional CV qualifiers
19128 	  at the outer level [14.8.2.1]/3,1st bullet.  */
19129       if ((TREE_CODE (arg) == REFERENCE_TYPE
19130 	   || TREE_CODE (arg) == FUNCTION_TYPE
19131 	   || TREE_CODE (arg) == METHOD_TYPE)
19132 	  && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
19133 	return 0;
19134 
19135       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
19136 	  && (parm_quals & TYPE_QUAL_RESTRICT))
19137 	return 0;
19138     }
19139 
19140   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
19141       && (arg_quals & parm_quals) != parm_quals)
19142     return 0;
19143 
19144   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
19145       && (parm_quals & arg_quals) != arg_quals)
19146     return 0;
19147 
19148   return 1;
19149 }
19150 
19151 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
19152 void
template_parm_level_and_index(tree parm,int * level,int * index)19153 template_parm_level_and_index (tree parm, int* level, int* index)
19154 {
19155   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
19156       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
19157       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
19158     {
19159       *index = TEMPLATE_TYPE_IDX (parm);
19160       *level = TEMPLATE_TYPE_LEVEL (parm);
19161     }
19162   else
19163     {
19164       *index = TEMPLATE_PARM_IDX (parm);
19165       *level = TEMPLATE_PARM_LEVEL (parm);
19166     }
19167 }
19168 
19169 #define RECUR_AND_CHECK_FAILURE(TP, TA, P, A, S, EP)			\
19170   do {									\
19171     if (unify (TP, TA, P, A, S, EP))					\
19172       return 1;								\
19173   } while (0);
19174 
19175 /* Unifies the remaining arguments in PACKED_ARGS with the pack
19176    expansion at the end of PACKED_PARMS. Returns 0 if the type
19177    deduction succeeds, 1 otherwise. STRICT is the same as in
19178    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
19179    call argument list. We'll need to adjust the arguments to make them
19180    types. SUBR tells us if this is from a recursive call to
19181    type_unification_real, or for comparing two template argument
19182    lists. */
19183 
19184 static int
unify_pack_expansion(tree tparms,tree targs,tree packed_parms,tree packed_args,unification_kind_t strict,bool subr,bool explain_p)19185 unify_pack_expansion (tree tparms, tree targs, tree packed_parms,
19186                       tree packed_args, unification_kind_t strict,
19187                       bool subr, bool explain_p)
19188 {
19189   tree parm
19190     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
19191   tree pattern = PACK_EXPANSION_PATTERN (parm);
19192   tree pack, packs = NULL_TREE;
19193   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
19194 
19195   packed_args = expand_template_argument_pack (packed_args);
19196 
19197   int len = TREE_VEC_LENGTH (packed_args);
19198 
19199   /* Determine the parameter packs we will be deducing from the
19200      pattern, and record their current deductions.  */
19201   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm);
19202        pack; pack = TREE_CHAIN (pack))
19203     {
19204       tree parm_pack = TREE_VALUE (pack);
19205       int idx, level;
19206 
19207       /* Determine the index and level of this parameter pack.  */
19208       template_parm_level_and_index (parm_pack, &level, &idx);
19209 
19210       /* Keep track of the parameter packs and their corresponding
19211          argument packs.  */
19212       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
19213       TREE_TYPE (packs) = make_tree_vec (len - start);
19214     }
19215 
19216   /* Loop through all of the arguments that have not yet been
19217      unified and unify each with the pattern.  */
19218   for (i = start; i < len; i++)
19219     {
19220       tree parm;
19221       bool any_explicit = false;
19222       tree arg = TREE_VEC_ELT (packed_args, i);
19223 
19224       /* For each parameter pack, set its TMPL_ARG to either NULL_TREE
19225 	 or the element of its argument pack at the current index if
19226 	 this argument was explicitly specified.  */
19227       for (pack = packs; pack; pack = TREE_CHAIN (pack))
19228         {
19229           int idx, level;
19230           tree arg, pargs;
19231           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
19232 
19233           arg = NULL_TREE;
19234           if (TREE_VALUE (pack)
19235               && (pargs = ARGUMENT_PACK_EXPLICIT_ARGS (TREE_VALUE (pack)))
19236               && (i - start < TREE_VEC_LENGTH (pargs)))
19237             {
19238               any_explicit = true;
19239               arg = TREE_VEC_ELT (pargs, i - start);
19240             }
19241           TMPL_ARG (targs, level, idx) = arg;
19242         }
19243 
19244       /* If we had explicit template arguments, substitute them into the
19245 	 pattern before deduction.  */
19246       if (any_explicit)
19247 	{
19248 	  /* Some arguments might still be unspecified or dependent.  */
19249 	  bool dependent;
19250 	  ++processing_template_decl;
19251 	  dependent = any_dependent_template_arguments_p (targs);
19252 	  if (!dependent)
19253 	    --processing_template_decl;
19254 	  parm = tsubst (pattern, targs,
19255 			 explain_p ? tf_warning_or_error : tf_none,
19256 			 NULL_TREE);
19257 	  if (dependent)
19258 	    --processing_template_decl;
19259 	  if (parm == error_mark_node)
19260 	    return 1;
19261 	}
19262       else
19263 	parm = pattern;
19264 
19265       /* Unify the pattern with the current argument.  */
19266       if (unify_one_argument (tparms, targs, parm, arg, subr, strict,
19267 			      explain_p))
19268 	return 1;
19269 
19270       /* For each parameter pack, collect the deduced value.  */
19271       for (pack = packs; pack; pack = TREE_CHAIN (pack))
19272         {
19273           int idx, level;
19274           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
19275 
19276           TREE_VEC_ELT (TREE_TYPE (pack), i - start) =
19277             TMPL_ARG (targs, level, idx);
19278         }
19279     }
19280 
19281   /* Verify that the results of unification with the parameter packs
19282      produce results consistent with what we've seen before, and make
19283      the deduced argument packs available.  */
19284   for (pack = packs; pack; pack = TREE_CHAIN (pack))
19285     {
19286       tree old_pack = TREE_VALUE (pack);
19287       tree new_args = TREE_TYPE (pack);
19288       int i, len = TREE_VEC_LENGTH (new_args);
19289       int idx, level;
19290       bool nondeduced_p = false;
19291 
19292       /* By default keep the original deduced argument pack.
19293 	 If necessary, more specific code is going to update the
19294 	 resulting deduced argument later down in this function.  */
19295       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
19296       TMPL_ARG (targs, level, idx) = old_pack;
19297 
19298       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
19299 	 actually deduce anything.  */
19300       for (i = 0; i < len && !nondeduced_p; ++i)
19301 	if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
19302 	  nondeduced_p = true;
19303       if (nondeduced_p)
19304 	continue;
19305 
19306       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
19307         {
19308           /* If we had fewer function args than explicit template args,
19309              just use the explicits.  */
19310           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
19311           int explicit_len = TREE_VEC_LENGTH (explicit_args);
19312           if (len < explicit_len)
19313             new_args = explicit_args;
19314         }
19315 
19316       if (!old_pack)
19317         {
19318           tree result;
19319           /* Build the deduced *_ARGUMENT_PACK.  */
19320           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
19321             {
19322               result = make_node (NONTYPE_ARGUMENT_PACK);
19323               TREE_TYPE (result) =
19324                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
19325               TREE_CONSTANT (result) = 1;
19326             }
19327           else
19328             result = cxx_make_type (TYPE_ARGUMENT_PACK);
19329 
19330           SET_ARGUMENT_PACK_ARGS (result, new_args);
19331 
19332           /* Note the deduced argument packs for this parameter
19333              pack.  */
19334           TMPL_ARG (targs, level, idx) = result;
19335         }
19336       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
19337                && (ARGUMENT_PACK_ARGS (old_pack)
19338                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
19339         {
19340           /* We only had the explicitly-provided arguments before, but
19341              now we have a complete set of arguments.  */
19342           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
19343 
19344           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
19345           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
19346           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
19347         }
19348       else
19349 	{
19350 	  tree bad_old_arg = NULL_TREE, bad_new_arg = NULL_TREE;
19351 	  tree old_args = ARGUMENT_PACK_ARGS (old_pack);
19352 
19353 	  if (!comp_template_args (old_args, new_args,
19354 				   &bad_old_arg, &bad_new_arg))
19355 	    /* Inconsistent unification of this parameter pack.  */
19356 	    return unify_parameter_pack_inconsistent (explain_p,
19357 						      bad_old_arg,
19358 						      bad_new_arg);
19359 	}
19360     }
19361 
19362   return unify_success (explain_p);
19363 }
19364 
19365 /* Handle unification of the domain of an array.  PARM_DOM and ARG_DOM are
19366    INTEGER_TYPEs representing the TYPE_DOMAIN of ARRAY_TYPEs.  The other
19367    parameters and return value are as for unify.  */
19368 
19369 static int
unify_array_domain(tree tparms,tree targs,tree parm_dom,tree arg_dom,bool explain_p)19370 unify_array_domain (tree tparms, tree targs,
19371 		    tree parm_dom, tree arg_dom,
19372 		    bool explain_p)
19373 {
19374   tree parm_max;
19375   tree arg_max;
19376   bool parm_cst;
19377   bool arg_cst;
19378 
19379   /* Our representation of array types uses "N - 1" as the
19380      TYPE_MAX_VALUE for an array with "N" elements, if "N" is
19381      not an integer constant.  We cannot unify arbitrarily
19382      complex expressions, so we eliminate the MINUS_EXPRs
19383      here.  */
19384   parm_max = TYPE_MAX_VALUE (parm_dom);
19385   parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
19386   if (!parm_cst)
19387     {
19388       gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
19389       parm_max = TREE_OPERAND (parm_max, 0);
19390     }
19391   arg_max = TYPE_MAX_VALUE (arg_dom);
19392   arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
19393   if (!arg_cst)
19394     {
19395       /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
19396 	 trying to unify the type of a variable with the type
19397 	 of a template parameter.  For example:
19398 
19399 	   template <unsigned int N>
19400 	   void f (char (&) [N]);
19401 	   int g();
19402 	   void h(int i) {
19403 	     char a[g(i)];
19404 	     f(a);
19405 	   }
19406 
19407 	 Here, the type of the ARG will be "int [g(i)]", and
19408 	 may be a SAVE_EXPR, etc.  */
19409       if (TREE_CODE (arg_max) != MINUS_EXPR)
19410 	return unify_vla_arg (explain_p, arg_dom);
19411       arg_max = TREE_OPERAND (arg_max, 0);
19412     }
19413 
19414   /* If only one of the bounds used a MINUS_EXPR, compensate
19415      by adding one to the other bound.  */
19416   if (parm_cst && !arg_cst)
19417     parm_max = fold_build2_loc (input_location, PLUS_EXPR,
19418 				integer_type_node,
19419 				parm_max,
19420 				integer_one_node);
19421   else if (arg_cst && !parm_cst)
19422     arg_max = fold_build2_loc (input_location, PLUS_EXPR,
19423 			       integer_type_node,
19424 			       arg_max,
19425 			       integer_one_node);
19426 
19427   return unify (tparms, targs, parm_max, arg_max,
19428 		UNIFY_ALLOW_INTEGER, explain_p);
19429 }
19430 
19431 /* Deduce the value of template parameters.  TPARMS is the (innermost)
19432    set of template parameters to a template.  TARGS is the bindings
19433    for those template parameters, as determined thus far; TARGS may
19434    include template arguments for outer levels of template parameters
19435    as well.  PARM is a parameter to a template function, or a
19436    subcomponent of that parameter; ARG is the corresponding argument.
19437    This function attempts to match PARM with ARG in a manner
19438    consistent with the existing assignments in TARGS.  If more values
19439    are deduced, then TARGS is updated.
19440 
19441    Returns 0 if the type deduction succeeds, 1 otherwise.  The
19442    parameter STRICT is a bitwise or of the following flags:
19443 
19444      UNIFY_ALLOW_NONE:
19445        Require an exact match between PARM and ARG.
19446      UNIFY_ALLOW_MORE_CV_QUAL:
19447        Allow the deduced ARG to be more cv-qualified (by qualification
19448        conversion) than ARG.
19449      UNIFY_ALLOW_LESS_CV_QUAL:
19450        Allow the deduced ARG to be less cv-qualified than ARG.
19451      UNIFY_ALLOW_DERIVED:
19452        Allow the deduced ARG to be a template base class of ARG,
19453        or a pointer to a template base class of the type pointed to by
19454        ARG.
19455      UNIFY_ALLOW_INTEGER:
19456        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
19457        case for more information.
19458      UNIFY_ALLOW_OUTER_LEVEL:
19459        This is the outermost level of a deduction. Used to determine validity
19460        of qualification conversions. A valid qualification conversion must
19461        have const qualified pointers leading up to the inner type which
19462        requires additional CV quals, except at the outer level, where const
19463        is not required [conv.qual]. It would be normal to set this flag in
19464        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
19465      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
19466        This is the outermost level of a deduction, and PARM can be more CV
19467        qualified at this point.
19468      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
19469        This is the outermost level of a deduction, and PARM can be less CV
19470        qualified at this point.  */
19471 
19472 static int
unify(tree tparms,tree targs,tree parm,tree arg,int strict,bool explain_p)19473 unify (tree tparms, tree targs, tree parm, tree arg, int strict,
19474        bool explain_p)
19475 {
19476   int idx;
19477   tree targ;
19478   tree tparm;
19479   int strict_in = strict;
19480 
19481   /* I don't think this will do the right thing with respect to types.
19482      But the only case I've seen it in so far has been array bounds, where
19483      signedness is the only information lost, and I think that will be
19484      okay.  */
19485   while (TREE_CODE (parm) == NOP_EXPR)
19486     parm = TREE_OPERAND (parm, 0);
19487 
19488   if (arg == error_mark_node)
19489     return unify_invalid (explain_p);
19490   if (arg == unknown_type_node
19491       || arg == init_list_type_node)
19492     /* We can't deduce anything from this, but we might get all the
19493        template args from other function args.  */
19494     return unify_success (explain_p);
19495 
19496   /* If PARM uses template parameters, then we can't bail out here,
19497      even if ARG == PARM, since we won't record unifications for the
19498      template parameters.  We might need them if we're trying to
19499      figure out which of two things is more specialized.  */
19500   if (arg == parm && !uses_template_parms (parm))
19501     return unify_success (explain_p);
19502 
19503   /* Handle init lists early, so the rest of the function can assume
19504      we're dealing with a type. */
19505   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
19506     {
19507       tree elt, elttype;
19508       unsigned i;
19509       tree orig_parm = parm;
19510 
19511       /* Replace T with std::initializer_list<T> for deduction.  */
19512       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
19513 	  && flag_deduce_init_list)
19514 	parm = listify (parm);
19515 
19516       if (!is_std_init_list (parm)
19517 	  && TREE_CODE (parm) != ARRAY_TYPE)
19518 	/* We can only deduce from an initializer list argument if the
19519 	   parameter is std::initializer_list or an array; otherwise this
19520 	   is a non-deduced context. */
19521 	return unify_success (explain_p);
19522 
19523       if (TREE_CODE (parm) == ARRAY_TYPE)
19524 	elttype = TREE_TYPE (parm);
19525       else
19526 	{
19527 	  elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
19528 	  /* Deduction is defined in terms of a single type, so just punt
19529 	     on the (bizarre) std::initializer_list<T...>.  */
19530 	  if (PACK_EXPANSION_P (elttype))
19531 	    return unify_success (explain_p);
19532 	}
19533 
19534       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
19535 	{
19536 	  int elt_strict = strict;
19537 
19538 	  if (elt == error_mark_node)
19539 	    return unify_invalid (explain_p);
19540 
19541 	  if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
19542 	    {
19543 	      tree type = TREE_TYPE (elt);
19544 	      if (type == error_mark_node)
19545 		return unify_invalid (explain_p);
19546 	      /* It should only be possible to get here for a call.  */
19547 	      gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
19548 	      elt_strict |= maybe_adjust_types_for_deduction
19549 		(DEDUCE_CALL, &elttype, &type, elt);
19550 	      elt = type;
19551 	    }
19552 
19553 	  RECUR_AND_CHECK_FAILURE (tparms, targs, elttype, elt, elt_strict,
19554 				   explain_p);
19555 	}
19556 
19557       if (TREE_CODE (parm) == ARRAY_TYPE
19558 	  && deducible_array_bound (TYPE_DOMAIN (parm)))
19559 	{
19560 	  /* Also deduce from the length of the initializer list.  */
19561 	  tree max = size_int (CONSTRUCTOR_NELTS (arg));
19562 	  tree idx = compute_array_index_type (NULL_TREE, max, tf_none);
19563 	  if (idx == error_mark_node)
19564 	    return unify_invalid (explain_p);
19565 	  return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
19566 				     idx, explain_p);
19567 	}
19568 
19569       /* If the std::initializer_list<T> deduction worked, replace the
19570 	 deduced A with std::initializer_list<A>.  */
19571       if (orig_parm != parm)
19572 	{
19573 	  idx = TEMPLATE_TYPE_IDX (orig_parm);
19574 	  targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
19575 	  targ = listify (targ);
19576 	  TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
19577 	}
19578       return unify_success (explain_p);
19579     }
19580 
19581   /* Immediately reject some pairs that won't unify because of
19582      cv-qualification mismatches.  */
19583   if (TREE_CODE (arg) == TREE_CODE (parm)
19584       && TYPE_P (arg)
19585       /* It is the elements of the array which hold the cv quals of an array
19586 	 type, and the elements might be template type parms. We'll check
19587 	 when we recurse.  */
19588       && TREE_CODE (arg) != ARRAY_TYPE
19589       /* We check the cv-qualifiers when unifying with template type
19590 	 parameters below.  We want to allow ARG `const T' to unify with
19591 	 PARM `T' for example, when computing which of two templates
19592 	 is more specialized, for example.  */
19593       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
19594       && !check_cv_quals_for_unify (strict_in, arg, parm))
19595     return unify_cv_qual_mismatch (explain_p, parm, arg);
19596 
19597   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
19598       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
19599     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
19600   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
19601   strict &= ~UNIFY_ALLOW_DERIVED;
19602   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
19603   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
19604 
19605   switch (TREE_CODE (parm))
19606     {
19607     case TYPENAME_TYPE:
19608     case SCOPE_REF:
19609     case UNBOUND_CLASS_TEMPLATE:
19610       /* In a type which contains a nested-name-specifier, template
19611 	 argument values cannot be deduced for template parameters used
19612 	 within the nested-name-specifier.  */
19613       return unify_success (explain_p);
19614 
19615     case TEMPLATE_TYPE_PARM:
19616     case TEMPLATE_TEMPLATE_PARM:
19617     case BOUND_TEMPLATE_TEMPLATE_PARM:
19618       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
19619       if (error_operand_p (tparm))
19620 	return unify_invalid (explain_p);
19621 
19622       if (TEMPLATE_TYPE_LEVEL (parm)
19623 	  != template_decl_level (tparm))
19624 	/* The PARM is not one we're trying to unify.  Just check
19625 	   to see if it matches ARG.  */
19626 	{
19627 	  if (TREE_CODE (arg) == TREE_CODE (parm)
19628 	      && (is_auto (parm) ? is_auto (arg)
19629 		  : same_type_p (parm, arg)))
19630 	    return unify_success (explain_p);
19631 	  else
19632 	    return unify_type_mismatch (explain_p, parm, arg);
19633 	}
19634       idx = TEMPLATE_TYPE_IDX (parm);
19635       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
19636       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
19637       if (error_operand_p (tparm))
19638 	return unify_invalid (explain_p);
19639 
19640       /* Check for mixed types and values.  */
19641       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
19642 	   && TREE_CODE (tparm) != TYPE_DECL)
19643 	  || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
19644 	      && TREE_CODE (tparm) != TEMPLATE_DECL))
19645 	gcc_unreachable ();
19646 
19647       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
19648 	{
19649 	  /* ARG must be constructed from a template class or a template
19650 	     template parameter.  */
19651 	  if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
19652 	      && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
19653 	    return unify_template_deduction_failure (explain_p, parm, arg);
19654 	  {
19655 	    tree parmvec = TYPE_TI_ARGS (parm);
19656 	    /* An alias template name is never deduced.  */
19657 	    if (TYPE_ALIAS_P (arg))
19658 	      arg = strip_typedefs (arg);
19659 	    tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
19660 	    tree full_argvec = add_to_template_args (targs, argvec);
19661 	    tree parm_parms
19662               = DECL_INNERMOST_TEMPLATE_PARMS
19663 	          (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
19664 	    int i, len;
19665             int parm_variadic_p = 0;
19666 
19667 	    /* The resolution to DR150 makes clear that default
19668 	       arguments for an N-argument may not be used to bind T
19669 	       to a template template parameter with fewer than N
19670 	       parameters.  It is not safe to permit the binding of
19671 	       default arguments as an extension, as that may change
19672 	       the meaning of a conforming program.  Consider:
19673 
19674 		  struct Dense { static const unsigned int dim = 1; };
19675 
19676 		  template <template <typename> class View,
19677 			    typename Block>
19678 		  void operator+(float, View<Block> const&);
19679 
19680 		  template <typename Block,
19681 			    unsigned int Dim = Block::dim>
19682 		  struct Lvalue_proxy { operator float() const; };
19683 
19684 		  void
19685 		  test_1d (void) {
19686 		    Lvalue_proxy<Dense> p;
19687 		    float b;
19688 		    b + p;
19689 		  }
19690 
19691 	      Here, if Lvalue_proxy is permitted to bind to View, then
19692 	      the global operator+ will be used; if they are not, the
19693 	      Lvalue_proxy will be converted to float.  */
19694 	    if (coerce_template_parms (parm_parms,
19695                                        full_argvec,
19696 				       TYPE_TI_TEMPLATE (parm),
19697 				       (explain_p
19698 					? tf_warning_or_error
19699 					: tf_none),
19700 				       /*require_all_args=*/true,
19701 				       /*use_default_args=*/false)
19702 		== error_mark_node)
19703 	      return 1;
19704 
19705 	    /* Deduce arguments T, i from TT<T> or TT<i>.
19706 	       We check each element of PARMVEC and ARGVEC individually
19707 	       rather than the whole TREE_VEC since they can have
19708 	       different number of elements.  */
19709 
19710             parmvec = expand_template_argument_pack (parmvec);
19711             argvec = expand_template_argument_pack (argvec);
19712 
19713             len = TREE_VEC_LENGTH (parmvec);
19714 
19715             /* Check if the parameters end in a pack, making them
19716                variadic.  */
19717             if (len > 0
19718                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
19719               parm_variadic_p = 1;
19720 
19721              for (i = 0; i < len - parm_variadic_p; ++i)
19722 	       /* If the template argument list of P contains a pack
19723 		  expansion that is not the last template argument, the
19724 		  entire template argument list is a non-deduced
19725 		  context.  */
19726 	       if (PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, i)))
19727 		 return unify_success (explain_p);
19728 
19729             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
19730               return unify_too_few_arguments (explain_p,
19731 					      TREE_VEC_LENGTH (argvec), len);
19732 
19733              for (i = 0; i < len - parm_variadic_p; ++i)
19734 	      {
19735 		RECUR_AND_CHECK_FAILURE (tparms, targs,
19736 					 TREE_VEC_ELT (parmvec, i),
19737 					 TREE_VEC_ELT (argvec, i),
19738 					 UNIFY_ALLOW_NONE, explain_p);
19739 	      }
19740 
19741 	    if (parm_variadic_p
19742 		&& unify_pack_expansion (tparms, targs,
19743 					 parmvec, argvec,
19744 					 DEDUCE_EXACT,
19745 					 /*subr=*/true, explain_p))
19746 	      return 1;
19747 	  }
19748 	  arg = TYPE_TI_TEMPLATE (arg);
19749 
19750 	  /* Fall through to deduce template name.  */
19751 	}
19752 
19753       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
19754 	  || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
19755 	{
19756 	  /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
19757 
19758 	  /* Simple cases: Value already set, does match or doesn't.  */
19759 	  if (targ != NULL_TREE && template_args_equal (targ, arg))
19760 	    return unify_success (explain_p);
19761 	  else if (targ)
19762 	    return unify_inconsistency (explain_p, parm, targ, arg);
19763 	}
19764       else
19765 	{
19766 	  /* If PARM is `const T' and ARG is only `int', we don't have
19767 	     a match unless we are allowing additional qualification.
19768 	     If ARG is `const int' and PARM is just `T' that's OK;
19769 	     that binds `const int' to `T'.  */
19770 	  if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
19771 					 arg, parm))
19772 	    return unify_cv_qual_mismatch (explain_p, parm, arg);
19773 
19774 	  /* Consider the case where ARG is `const volatile int' and
19775 	     PARM is `const T'.  Then, T should be `volatile int'.  */
19776 	  arg = cp_build_qualified_type_real
19777 	    (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
19778 	  if (arg == error_mark_node)
19779 	    return unify_invalid (explain_p);
19780 
19781 	  /* Simple cases: Value already set, does match or doesn't.  */
19782 	  if (targ != NULL_TREE && same_type_p (targ, arg))
19783 	    return unify_success (explain_p);
19784 	  else if (targ)
19785 	    return unify_inconsistency (explain_p, parm, targ, arg);
19786 
19787 	  /* Make sure that ARG is not a variable-sized array.  (Note
19788 	     that were talking about variable-sized arrays (like
19789 	     `int[n]'), rather than arrays of unknown size (like
19790 	     `int[]').)  We'll get very confused by such a type since
19791 	     the bound of the array is not constant, and therefore
19792 	     not mangleable.  Besides, such types are not allowed in
19793 	     ISO C++, so we can do as we please here.  We do allow
19794 	     them for 'auto' deduction, since that isn't ABI-exposed.  */
19795 	  if (!is_auto (parm) && variably_modified_type_p (arg, NULL_TREE))
19796 	    return unify_vla_arg (explain_p, arg);
19797 
19798 	  /* Strip typedefs as in convert_template_argument.  */
19799 	  arg = canonicalize_type_argument (arg, tf_none);
19800 	}
19801 
19802       /* If ARG is a parameter pack or an expansion, we cannot unify
19803 	 against it unless PARM is also a parameter pack.  */
19804       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
19805 	  && !template_parameter_pack_p (parm))
19806 	return unify_parameter_pack_mismatch (explain_p, parm, arg);
19807 
19808       /* If the argument deduction results is a METHOD_TYPE,
19809          then there is a problem.
19810          METHOD_TYPE doesn't map to any real C++ type the result of
19811 	 the deduction can not be of that type.  */
19812       if (TREE_CODE (arg) == METHOD_TYPE)
19813 	return unify_method_type_error (explain_p, arg);
19814 
19815       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
19816       return unify_success (explain_p);
19817 
19818     case TEMPLATE_PARM_INDEX:
19819       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
19820       if (error_operand_p (tparm))
19821 	return unify_invalid (explain_p);
19822 
19823       if (TEMPLATE_PARM_LEVEL (parm)
19824 	  != template_decl_level (tparm))
19825 	{
19826 	  /* The PARM is not one we're trying to unify.  Just check
19827 	     to see if it matches ARG.  */
19828 	  int result = !(TREE_CODE (arg) == TREE_CODE (parm)
19829 			 && cp_tree_equal (parm, arg));
19830 	  if (result)
19831 	    unify_expression_unequal (explain_p, parm, arg);
19832 	  return result;
19833 	}
19834 
19835       idx = TEMPLATE_PARM_IDX (parm);
19836       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
19837 
19838       if (targ)
19839 	{
19840 	  int x = !cp_tree_equal (targ, arg);
19841 	  if (x)
19842 	    unify_inconsistency (explain_p, parm, targ, arg);
19843 	  return x;
19844 	}
19845 
19846       /* [temp.deduct.type] If, in the declaration of a function template
19847 	 with a non-type template-parameter, the non-type
19848 	 template-parameter is used in an expression in the function
19849 	 parameter-list and, if the corresponding template-argument is
19850 	 deduced, the template-argument type shall match the type of the
19851 	 template-parameter exactly, except that a template-argument
19852 	 deduced from an array bound may be of any integral type.
19853 	 The non-type parameter might use already deduced type parameters.  */
19854       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
19855       if (!TREE_TYPE (arg))
19856 	/* Template-parameter dependent expression.  Just accept it for now.
19857 	   It will later be processed in convert_template_argument.  */
19858 	;
19859       else if (same_type_p (TREE_TYPE (arg), tparm))
19860 	/* OK */;
19861       else if ((strict & UNIFY_ALLOW_INTEGER)
19862 	       && CP_INTEGRAL_TYPE_P (tparm))
19863 	/* Convert the ARG to the type of PARM; the deduced non-type
19864 	   template argument must exactly match the types of the
19865 	   corresponding parameter.  */
19866 	arg = fold (build_nop (tparm, arg));
19867       else if (uses_template_parms (tparm))
19868 	/* We haven't deduced the type of this parameter yet.  Try again
19869 	   later.  */
19870 	return unify_success (explain_p);
19871       else
19872 	return unify_type_mismatch (explain_p, tparm, TREE_TYPE (arg));
19873 
19874       /* If ARG is a parameter pack or an expansion, we cannot unify
19875 	 against it unless PARM is also a parameter pack.  */
19876       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
19877 	  && !TEMPLATE_PARM_PARAMETER_PACK (parm))
19878 	return unify_parameter_pack_mismatch (explain_p, parm, arg);
19879 
19880       {
19881 	bool removed_attr = false;
19882 	arg = strip_typedefs_expr (arg, &removed_attr);
19883       }
19884       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
19885       return unify_success (explain_p);
19886 
19887     case PTRMEM_CST:
19888      {
19889 	/* A pointer-to-member constant can be unified only with
19890 	 another constant.  */
19891       if (TREE_CODE (arg) != PTRMEM_CST)
19892 	return unify_ptrmem_cst_mismatch (explain_p, parm, arg);
19893 
19894       /* Just unify the class member. It would be useless (and possibly
19895 	 wrong, depending on the strict flags) to unify also
19896 	 PTRMEM_CST_CLASS, because we want to be sure that both parm and
19897 	 arg refer to the same variable, even if through different
19898 	 classes. For instance:
19899 
19900 	 struct A { int x; };
19901 	 struct B : A { };
19902 
19903 	 Unification of &A::x and &B::x must succeed.  */
19904       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
19905 		    PTRMEM_CST_MEMBER (arg), strict, explain_p);
19906      }
19907 
19908     case POINTER_TYPE:
19909       {
19910 	if (!TYPE_PTR_P (arg))
19911 	  return unify_type_mismatch (explain_p, parm, arg);
19912 
19913 	/* [temp.deduct.call]
19914 
19915 	   A can be another pointer or pointer to member type that can
19916 	   be converted to the deduced A via a qualification
19917 	   conversion (_conv.qual_).
19918 
19919 	   We pass down STRICT here rather than UNIFY_ALLOW_NONE.
19920 	   This will allow for additional cv-qualification of the
19921 	   pointed-to types if appropriate.  */
19922 
19923 	if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
19924 	  /* The derived-to-base conversion only persists through one
19925 	     level of pointers.  */
19926 	  strict |= (strict_in & UNIFY_ALLOW_DERIVED);
19927 
19928 	return unify (tparms, targs, TREE_TYPE (parm),
19929 		      TREE_TYPE (arg), strict, explain_p);
19930       }
19931 
19932     case REFERENCE_TYPE:
19933       if (TREE_CODE (arg) != REFERENCE_TYPE)
19934 	return unify_type_mismatch (explain_p, parm, arg);
19935       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
19936 		    strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
19937 
19938     case ARRAY_TYPE:
19939       if (TREE_CODE (arg) != ARRAY_TYPE)
19940 	return unify_type_mismatch (explain_p, parm, arg);
19941       if ((TYPE_DOMAIN (parm) == NULL_TREE)
19942 	  != (TYPE_DOMAIN (arg) == NULL_TREE))
19943 	return unify_type_mismatch (explain_p, parm, arg);
19944       RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
19945 			       strict & UNIFY_ALLOW_MORE_CV_QUAL, explain_p);
19946       if (TYPE_DOMAIN (parm) != NULL_TREE)
19947 	return unify_array_domain (tparms, targs, TYPE_DOMAIN (parm),
19948 				   TYPE_DOMAIN (arg), explain_p);
19949       return unify_success (explain_p);
19950 
19951     case REAL_TYPE:
19952     case COMPLEX_TYPE:
19953     case VECTOR_TYPE:
19954     case INTEGER_TYPE:
19955     case BOOLEAN_TYPE:
19956     case ENUMERAL_TYPE:
19957     case VOID_TYPE:
19958     case NULLPTR_TYPE:
19959       if (TREE_CODE (arg) != TREE_CODE (parm))
19960 	return unify_type_mismatch (explain_p, parm, arg);
19961 
19962       /* We have already checked cv-qualification at the top of the
19963 	 function.  */
19964       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
19965 	return unify_type_mismatch (explain_p, parm, arg);
19966 
19967       /* As far as unification is concerned, this wins.	 Later checks
19968 	 will invalidate it if necessary.  */
19969       return unify_success (explain_p);
19970 
19971       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
19972       /* Type INTEGER_CST can come from ordinary constant template args.  */
19973     case INTEGER_CST:
19974       while (TREE_CODE (arg) == NOP_EXPR)
19975 	arg = TREE_OPERAND (arg, 0);
19976 
19977       if (TREE_CODE (arg) != INTEGER_CST)
19978 	return unify_template_argument_mismatch (explain_p, parm, arg);
19979       return (tree_int_cst_equal (parm, arg)
19980 	      ? unify_success (explain_p)
19981 	      : unify_template_argument_mismatch (explain_p, parm, arg));
19982 
19983     case TREE_VEC:
19984       {
19985 	int i, len, argslen;
19986 	int parm_variadic_p = 0;
19987 
19988 	if (TREE_CODE (arg) != TREE_VEC)
19989 	  return unify_template_argument_mismatch (explain_p, parm, arg);
19990 
19991 	len = TREE_VEC_LENGTH (parm);
19992 	argslen = TREE_VEC_LENGTH (arg);
19993 
19994 	/* Check for pack expansions in the parameters.  */
19995 	for (i = 0; i < len; ++i)
19996 	  {
19997 	    if (PACK_EXPANSION_P (TREE_VEC_ELT (parm, i)))
19998 	      {
19999 		if (i == len - 1)
20000 		  /* We can unify against something with a trailing
20001 		     parameter pack.  */
20002 		  parm_variadic_p = 1;
20003 		else
20004 		  /* [temp.deduct.type]/9: If the template argument list of
20005 		     P contains a pack expansion that is not the last
20006 		     template argument, the entire template argument list
20007 		     is a non-deduced context.  */
20008 		  return unify_success (explain_p);
20009 	      }
20010 	  }
20011 
20012         /* If we don't have enough arguments to satisfy the parameters
20013            (not counting the pack expression at the end), or we have
20014            too many arguments for a parameter list that doesn't end in
20015            a pack expression, we can't unify.  */
20016 	if (parm_variadic_p
20017 	    ? argslen < len - parm_variadic_p
20018 	    : argslen != len)
20019 	  return unify_arity (explain_p, TREE_VEC_LENGTH (arg), len);
20020 
20021 	/* Unify all of the parameters that precede the (optional)
20022 	   pack expression.  */
20023 	for (i = 0; i < len - parm_variadic_p; ++i)
20024 	  {
20025 	    RECUR_AND_CHECK_FAILURE (tparms, targs,
20026 				     TREE_VEC_ELT (parm, i),
20027 				     TREE_VEC_ELT (arg, i),
20028 				     UNIFY_ALLOW_NONE, explain_p);
20029 	  }
20030 	if (parm_variadic_p)
20031 	  return unify_pack_expansion (tparms, targs, parm, arg,
20032 				       DEDUCE_EXACT,
20033 				       /*subr=*/true, explain_p);
20034 	return unify_success (explain_p);
20035       }
20036 
20037     case RECORD_TYPE:
20038     case UNION_TYPE:
20039       if (TREE_CODE (arg) != TREE_CODE (parm))
20040 	return unify_type_mismatch (explain_p, parm, arg);
20041 
20042       if (TYPE_PTRMEMFUNC_P (parm))
20043 	{
20044 	  if (!TYPE_PTRMEMFUNC_P (arg))
20045 	    return unify_type_mismatch (explain_p, parm, arg);
20046 
20047 	  return unify (tparms, targs,
20048 			TYPE_PTRMEMFUNC_FN_TYPE (parm),
20049 			TYPE_PTRMEMFUNC_FN_TYPE (arg),
20050 			strict, explain_p);
20051 	}
20052       else if (TYPE_PTRMEMFUNC_P (arg))
20053 	return unify_type_mismatch (explain_p, parm, arg);
20054 
20055       if (CLASSTYPE_TEMPLATE_INFO (parm))
20056 	{
20057 	  tree t = NULL_TREE;
20058 
20059 	  if (strict_in & UNIFY_ALLOW_DERIVED)
20060 	    {
20061 	      /* First, we try to unify the PARM and ARG directly.  */
20062 	      t = try_class_unification (tparms, targs,
20063 					 parm, arg, explain_p);
20064 
20065 	      if (!t)
20066 		{
20067 		  /* Fallback to the special case allowed in
20068 		     [temp.deduct.call]:
20069 
20070 		       If P is a class, and P has the form
20071 		       template-id, then A can be a derived class of
20072 		       the deduced A.  Likewise, if P is a pointer to
20073 		       a class of the form template-id, A can be a
20074 		       pointer to a derived class pointed to by the
20075 		       deduced A.  */
20076 		  enum template_base_result r;
20077 		  r = get_template_base (tparms, targs, parm, arg,
20078 					 explain_p, &t);
20079 
20080 		  if (!t)
20081 		    {
20082 		      /* Don't give the derived diagnostic if we're
20083 			 already dealing with the same template.  */
20084 		      bool same_template
20085 			= (CLASSTYPE_TEMPLATE_INFO (arg)
20086 			   && (CLASSTYPE_TI_TEMPLATE (parm)
20087 			       == CLASSTYPE_TI_TEMPLATE (arg)));
20088 		      return unify_no_common_base (explain_p && !same_template,
20089 						   r, parm, arg);
20090 		    }
20091 		}
20092 	    }
20093 	  else if (CLASSTYPE_TEMPLATE_INFO (arg)
20094 		   && (CLASSTYPE_TI_TEMPLATE (parm)
20095 		       == CLASSTYPE_TI_TEMPLATE (arg)))
20096 	    /* Perhaps PARM is something like S<U> and ARG is S<int>.
20097 	       Then, we should unify `int' and `U'.  */
20098 	    t = arg;
20099 	  else
20100 	    /* There's no chance of unification succeeding.  */
20101 	    return unify_type_mismatch (explain_p, parm, arg);
20102 
20103 	  return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
20104 			CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE, explain_p);
20105 	}
20106       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
20107 	return unify_type_mismatch (explain_p, parm, arg);
20108       return unify_success (explain_p);
20109 
20110     case METHOD_TYPE:
20111     case FUNCTION_TYPE:
20112       {
20113 	unsigned int nargs;
20114 	tree *args;
20115 	tree a;
20116 	unsigned int i;
20117 
20118 	if (TREE_CODE (arg) != TREE_CODE (parm))
20119 	  return unify_type_mismatch (explain_p, parm, arg);
20120 
20121 	/* CV qualifications for methods can never be deduced, they must
20122 	   match exactly.  We need to check them explicitly here,
20123 	   because type_unification_real treats them as any other
20124 	   cv-qualified parameter.  */
20125 	if (TREE_CODE (parm) == METHOD_TYPE
20126 	    && (!check_cv_quals_for_unify
20127 		(UNIFY_ALLOW_NONE,
20128 		 class_of_this_parm (arg),
20129 		 class_of_this_parm (parm))))
20130 	  return unify_cv_qual_mismatch (explain_p, parm, arg);
20131 
20132 	RECUR_AND_CHECK_FAILURE (tparms, targs, TREE_TYPE (parm),
20133 				 TREE_TYPE (arg), UNIFY_ALLOW_NONE, explain_p);
20134 
20135 	nargs = list_length (TYPE_ARG_TYPES (arg));
20136 	args = XALLOCAVEC (tree, nargs);
20137 	for (a = TYPE_ARG_TYPES (arg), i = 0;
20138 	     a != NULL_TREE && a != void_list_node;
20139 	     a = TREE_CHAIN (a), ++i)
20140 	  args[i] = TREE_VALUE (a);
20141 	nargs = i;
20142 
20143 	return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
20144 				      args, nargs, 1, DEDUCE_EXACT,
20145 				      LOOKUP_NORMAL, NULL, explain_p);
20146       }
20147 
20148     case OFFSET_TYPE:
20149       /* Unify a pointer to member with a pointer to member function, which
20150 	 deduces the type of the member as a function type. */
20151       if (TYPE_PTRMEMFUNC_P (arg))
20152 	{
20153 	  /* Check top-level cv qualifiers */
20154 	  if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
20155 	    return unify_cv_qual_mismatch (explain_p, parm, arg);
20156 
20157 	  RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
20158 				   TYPE_PTRMEMFUNC_OBJECT_TYPE (arg),
20159 				   UNIFY_ALLOW_NONE, explain_p);
20160 
20161 	  /* Determine the type of the function we are unifying against. */
20162 	  tree fntype = static_fn_type (arg);
20163 
20164 	  return unify (tparms, targs, TREE_TYPE (parm), fntype, strict, explain_p);
20165 	}
20166 
20167       if (TREE_CODE (arg) != OFFSET_TYPE)
20168 	return unify_type_mismatch (explain_p, parm, arg);
20169       RECUR_AND_CHECK_FAILURE (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
20170 			       TYPE_OFFSET_BASETYPE (arg),
20171 			       UNIFY_ALLOW_NONE, explain_p);
20172       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
20173 		    strict, explain_p);
20174 
20175     case CONST_DECL:
20176       if (DECL_TEMPLATE_PARM_P (parm))
20177 	return unify (tparms, targs, DECL_INITIAL (parm), arg, strict, explain_p);
20178       if (arg != scalar_constant_value (parm))
20179 	return unify_template_argument_mismatch (explain_p, parm, arg);
20180       return unify_success (explain_p);
20181 
20182     case FIELD_DECL:
20183     case TEMPLATE_DECL:
20184       /* Matched cases are handled by the ARG == PARM test above.  */
20185       return unify_template_argument_mismatch (explain_p, parm, arg);
20186 
20187     case VAR_DECL:
20188       /* We might get a variable as a non-type template argument in parm if the
20189 	 corresponding parameter is type-dependent.  Make any necessary
20190 	 adjustments based on whether arg is a reference.  */
20191       if (CONSTANT_CLASS_P (arg))
20192 	parm = fold_non_dependent_expr (parm);
20193       else if (REFERENCE_REF_P (arg))
20194 	{
20195 	  tree sub = TREE_OPERAND (arg, 0);
20196 	  STRIP_NOPS (sub);
20197 	  if (TREE_CODE (sub) == ADDR_EXPR)
20198 	    arg = TREE_OPERAND (sub, 0);
20199 	}
20200       /* Now use the normal expression code to check whether they match.  */
20201       goto expr;
20202 
20203     case TYPE_ARGUMENT_PACK:
20204     case NONTYPE_ARGUMENT_PACK:
20205       return unify (tparms, targs, ARGUMENT_PACK_ARGS (parm),
20206 		    ARGUMENT_PACK_ARGS (arg), strict, explain_p);
20207 
20208     case TYPEOF_TYPE:
20209     case DECLTYPE_TYPE:
20210     case UNDERLYING_TYPE:
20211       /* Cannot deduce anything from TYPEOF_TYPE, DECLTYPE_TYPE,
20212 	 or UNDERLYING_TYPE nodes.  */
20213       return unify_success (explain_p);
20214 
20215     case ERROR_MARK:
20216       /* Unification fails if we hit an error node.  */
20217       return unify_invalid (explain_p);
20218 
20219     case INDIRECT_REF:
20220       if (REFERENCE_REF_P (parm))
20221 	{
20222 	  if (REFERENCE_REF_P (arg))
20223 	    arg = TREE_OPERAND (arg, 0);
20224 	  return unify (tparms, targs, TREE_OPERAND (parm, 0), arg,
20225 			strict, explain_p);
20226 	}
20227       /* FALLTHRU */
20228 
20229     default:
20230       /* An unresolved overload is a nondeduced context.  */
20231       if (is_overloaded_fn (parm) || type_unknown_p (parm))
20232 	return unify_success (explain_p);
20233       gcc_assert (EXPR_P (parm) || TREE_CODE (parm) == TRAIT_EXPR);
20234     expr:
20235       /* We must be looking at an expression.  This can happen with
20236 	 something like:
20237 
20238 	   template <int I>
20239 	   void foo(S<I>, S<I + 2>);
20240 
20241 	 This is a "nondeduced context":
20242 
20243 	   [deduct.type]
20244 
20245 	   The nondeduced contexts are:
20246 
20247 	   --A type that is a template-id in which one or more of
20248 	     the template-arguments is an expression that references
20249 	     a template-parameter.
20250 
20251 	 In these cases, we assume deduction succeeded, but don't
20252 	 actually infer any unifications.  */
20253 
20254       if (!uses_template_parms (parm)
20255 	  && !template_args_equal (parm, arg))
20256 	return unify_expression_unequal (explain_p, parm, arg);
20257       else
20258 	return unify_success (explain_p);
20259     }
20260 }
20261 #undef RECUR_AND_CHECK_FAILURE
20262 
20263 /* Note that DECL can be defined in this translation unit, if
20264    required.  */
20265 
20266 static void
mark_definable(tree decl)20267 mark_definable (tree decl)
20268 {
20269   tree clone;
20270   DECL_NOT_REALLY_EXTERN (decl) = 1;
20271   FOR_EACH_CLONE (clone, decl)
20272     DECL_NOT_REALLY_EXTERN (clone) = 1;
20273 }
20274 
20275 /* Called if RESULT is explicitly instantiated, or is a member of an
20276    explicitly instantiated class.  */
20277 
20278 void
mark_decl_instantiated(tree result,int extern_p)20279 mark_decl_instantiated (tree result, int extern_p)
20280 {
20281   SET_DECL_EXPLICIT_INSTANTIATION (result);
20282 
20283   /* If this entity has already been written out, it's too late to
20284      make any modifications.  */
20285   if (TREE_ASM_WRITTEN (result))
20286     return;
20287 
20288   /* For anonymous namespace we don't need to do anything.  */
20289   if (decl_anon_ns_mem_p (result))
20290     {
20291       gcc_assert (!TREE_PUBLIC (result));
20292       return;
20293     }
20294 
20295   if (TREE_CODE (result) != FUNCTION_DECL)
20296     /* The TREE_PUBLIC flag for function declarations will have been
20297        set correctly by tsubst.  */
20298     TREE_PUBLIC (result) = 1;
20299 
20300   /* This might have been set by an earlier implicit instantiation.  */
20301   DECL_COMDAT (result) = 0;
20302 
20303   if (extern_p)
20304     DECL_NOT_REALLY_EXTERN (result) = 0;
20305   else
20306     {
20307       mark_definable (result);
20308       mark_needed (result);
20309       /* Always make artificials weak.  */
20310       if (DECL_ARTIFICIAL (result) && flag_weak)
20311 	comdat_linkage (result);
20312       /* For WIN32 we also want to put explicit instantiations in
20313 	 linkonce sections.  */
20314       else if (TREE_PUBLIC (result))
20315 	maybe_make_one_only (result);
20316     }
20317 
20318   /* If EXTERN_P, then this function will not be emitted -- unless
20319      followed by an explicit instantiation, at which point its linkage
20320      will be adjusted.  If !EXTERN_P, then this function will be
20321      emitted here.  In neither circumstance do we want
20322      import_export_decl to adjust the linkage.  */
20323   DECL_INTERFACE_KNOWN (result) = 1;
20324 }
20325 
20326 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
20327    important template arguments.  If any are missing, we check whether
20328    they're important by using error_mark_node for substituting into any
20329    args that were used for partial ordering (the ones between ARGS and END)
20330    and seeing if it bubbles up.  */
20331 
20332 static bool
check_undeduced_parms(tree targs,tree args,tree end)20333 check_undeduced_parms (tree targs, tree args, tree end)
20334 {
20335   bool found = false;
20336   int i;
20337   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
20338     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
20339       {
20340 	found = true;
20341 	TREE_VEC_ELT (targs, i) = error_mark_node;
20342       }
20343   if (found)
20344     {
20345       tree substed = tsubst_arg_types (args, targs, end, tf_none, NULL_TREE);
20346       if (substed == error_mark_node)
20347 	return true;
20348     }
20349   return false;
20350 }
20351 
20352 /* Given two function templates PAT1 and PAT2, return:
20353 
20354    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
20355    -1 if PAT2 is more specialized than PAT1.
20356    0 if neither is more specialized.
20357 
20358    LEN indicates the number of parameters we should consider
20359    (defaulted parameters should not be considered).
20360 
20361    The 1998 std underspecified function template partial ordering, and
20362    DR214 addresses the issue.  We take pairs of arguments, one from
20363    each of the templates, and deduce them against each other.  One of
20364    the templates will be more specialized if all the *other*
20365    template's arguments deduce against its arguments and at least one
20366    of its arguments *does* *not* deduce against the other template's
20367    corresponding argument.  Deduction is done as for class templates.
20368    The arguments used in deduction have reference and top level cv
20369    qualifiers removed.  Iff both arguments were originally reference
20370    types *and* deduction succeeds in both directions, an lvalue reference
20371    wins against an rvalue reference and otherwise the template
20372    with the more cv-qualified argument wins for that pairing (if
20373    neither is more cv-qualified, they both are equal).  Unlike regular
20374    deduction, after all the arguments have been deduced in this way,
20375    we do *not* verify the deduced template argument values can be
20376    substituted into non-deduced contexts.
20377 
20378    The logic can be a bit confusing here, because we look at deduce1 and
20379    targs1 to see if pat2 is at least as specialized, and vice versa; if we
20380    can find template arguments for pat1 to make arg1 look like arg2, that
20381    means that arg2 is at least as specialized as arg1.  */
20382 
20383 int
more_specialized_fn(tree pat1,tree pat2,int len)20384 more_specialized_fn (tree pat1, tree pat2, int len)
20385 {
20386   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
20387   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
20388   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
20389   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
20390   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
20391   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
20392   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
20393   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
20394   tree origs1, origs2;
20395   bool lose1 = false;
20396   bool lose2 = false;
20397 
20398   /* Remove the this parameter from non-static member functions.  If
20399      one is a non-static member function and the other is not a static
20400      member function, remove the first parameter from that function
20401      also.  This situation occurs for operator functions where we
20402      locate both a member function (with this pointer) and non-member
20403      operator (with explicit first operand).  */
20404   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
20405     {
20406       len--; /* LEN is the number of significant arguments for DECL1 */
20407       args1 = TREE_CHAIN (args1);
20408       if (!DECL_STATIC_FUNCTION_P (decl2))
20409 	args2 = TREE_CHAIN (args2);
20410     }
20411   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
20412     {
20413       args2 = TREE_CHAIN (args2);
20414       if (!DECL_STATIC_FUNCTION_P (decl1))
20415 	{
20416 	  len--;
20417 	  args1 = TREE_CHAIN (args1);
20418 	}
20419     }
20420 
20421   /* If only one is a conversion operator, they are unordered.  */
20422   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
20423     return 0;
20424 
20425   /* Consider the return type for a conversion function */
20426   if (DECL_CONV_FN_P (decl1))
20427     {
20428       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
20429       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
20430       len++;
20431     }
20432 
20433   processing_template_decl++;
20434 
20435   origs1 = args1;
20436   origs2 = args2;
20437 
20438   while (len--
20439 	 /* Stop when an ellipsis is seen.  */
20440 	 && args1 != NULL_TREE && args2 != NULL_TREE)
20441     {
20442       tree arg1 = TREE_VALUE (args1);
20443       tree arg2 = TREE_VALUE (args2);
20444       int deduce1, deduce2;
20445       int quals1 = -1;
20446       int quals2 = -1;
20447       int ref1 = 0;
20448       int ref2 = 0;
20449 
20450       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
20451           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
20452         {
20453           /* When both arguments are pack expansions, we need only
20454              unify the patterns themselves.  */
20455           arg1 = PACK_EXPANSION_PATTERN (arg1);
20456           arg2 = PACK_EXPANSION_PATTERN (arg2);
20457 
20458           /* This is the last comparison we need to do.  */
20459           len = 0;
20460         }
20461 
20462       if (TREE_CODE (arg1) == REFERENCE_TYPE)
20463 	{
20464 	  ref1 = TYPE_REF_IS_RVALUE (arg1) + 1;
20465 	  arg1 = TREE_TYPE (arg1);
20466 	  quals1 = cp_type_quals (arg1);
20467 	}
20468 
20469       if (TREE_CODE (arg2) == REFERENCE_TYPE)
20470 	{
20471 	  ref2 = TYPE_REF_IS_RVALUE (arg2) + 1;
20472 	  arg2 = TREE_TYPE (arg2);
20473 	  quals2 = cp_type_quals (arg2);
20474 	}
20475 
20476       arg1 = TYPE_MAIN_VARIANT (arg1);
20477       arg2 = TYPE_MAIN_VARIANT (arg2);
20478 
20479       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
20480         {
20481           int i, len2 = remaining_arguments (args2);
20482           tree parmvec = make_tree_vec (1);
20483           tree argvec = make_tree_vec (len2);
20484           tree ta = args2;
20485 
20486           /* Setup the parameter vector, which contains only ARG1.  */
20487           TREE_VEC_ELT (parmvec, 0) = arg1;
20488 
20489           /* Setup the argument vector, which contains the remaining
20490              arguments.  */
20491           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
20492             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
20493 
20494           deduce1 = (unify_pack_expansion (tparms1, targs1, parmvec,
20495 					   argvec, DEDUCE_EXACT,
20496 					   /*subr=*/true, /*explain_p=*/false)
20497 		     == 0);
20498 
20499           /* We cannot deduce in the other direction, because ARG1 is
20500              a pack expansion but ARG2 is not.  */
20501           deduce2 = 0;
20502         }
20503       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
20504         {
20505           int i, len1 = remaining_arguments (args1);
20506           tree parmvec = make_tree_vec (1);
20507           tree argvec = make_tree_vec (len1);
20508           tree ta = args1;
20509 
20510           /* Setup the parameter vector, which contains only ARG1.  */
20511           TREE_VEC_ELT (parmvec, 0) = arg2;
20512 
20513           /* Setup the argument vector, which contains the remaining
20514              arguments.  */
20515           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
20516             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
20517 
20518           deduce2 = (unify_pack_expansion (tparms2, targs2, parmvec,
20519 					   argvec, DEDUCE_EXACT,
20520 					   /*subr=*/true, /*explain_p=*/false)
20521 		     == 0);
20522 
20523           /* We cannot deduce in the other direction, because ARG2 is
20524              a pack expansion but ARG1 is not.*/
20525           deduce1 = 0;
20526         }
20527 
20528       else
20529         {
20530           /* The normal case, where neither argument is a pack
20531              expansion.  */
20532           deduce1 = (unify (tparms1, targs1, arg1, arg2,
20533 			    UNIFY_ALLOW_NONE, /*explain_p=*/false)
20534 		     == 0);
20535           deduce2 = (unify (tparms2, targs2, arg2, arg1,
20536 			    UNIFY_ALLOW_NONE, /*explain_p=*/false)
20537 		     == 0);
20538         }
20539 
20540       /* If we couldn't deduce arguments for tparms1 to make arg1 match
20541 	 arg2, then arg2 is not as specialized as arg1.  */
20542       if (!deduce1)
20543 	lose2 = true;
20544       if (!deduce2)
20545 	lose1 = true;
20546 
20547       /* "If, for a given type, deduction succeeds in both directions
20548 	 (i.e., the types are identical after the transformations above)
20549 	 and both P and A were reference types (before being replaced with
20550 	 the type referred to above):
20551 	 - if the type from the argument template was an lvalue reference and
20552 	 the type from the parameter template was not, the argument type is
20553 	 considered to be more specialized than the other; otherwise,
20554 	 - if the type from the argument template is more cv-qualified
20555 	 than the type from the parameter template (as described above),
20556 	 the argument type is considered to be more specialized than the other;
20557 	 otherwise,
20558 	 - neither type is more specialized than the other."  */
20559 
20560       if (deduce1 && deduce2)
20561 	{
20562 	  if (ref1 && ref2 && ref1 != ref2)
20563 	    {
20564 	      if (ref1 > ref2)
20565 		lose1 = true;
20566 	      else
20567 		lose2 = true;
20568 	    }
20569 	  else if (quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
20570 	    {
20571 	      if ((quals1 & quals2) == quals2)
20572 		lose2 = true;
20573 	      if ((quals1 & quals2) == quals1)
20574 		lose1 = true;
20575 	    }
20576 	}
20577 
20578       if (lose1 && lose2)
20579 	/* We've failed to deduce something in either direction.
20580 	   These must be unordered.  */
20581 	break;
20582 
20583       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
20584           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
20585         /* We have already processed all of the arguments in our
20586            handing of the pack expansion type.  */
20587         len = 0;
20588 
20589       args1 = TREE_CHAIN (args1);
20590       args2 = TREE_CHAIN (args2);
20591     }
20592 
20593   /* "In most cases, all template parameters must have values in order for
20594      deduction to succeed, but for partial ordering purposes a template
20595      parameter may remain without a value provided it is not used in the
20596      types being used for partial ordering."
20597 
20598      Thus, if we are missing any of the targs1 we need to substitute into
20599      origs1, then pat2 is not as specialized as pat1.  This can happen when
20600      there is a nondeduced context.  */
20601   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
20602     lose2 = true;
20603   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
20604     lose1 = true;
20605 
20606   processing_template_decl--;
20607 
20608   /* If both deductions succeed, the partial ordering selects the more
20609      constrained template.  */
20610   if (!lose1 && !lose2)
20611     {
20612       tree c1 = get_constraints (DECL_TEMPLATE_RESULT (pat1));
20613       tree c2 = get_constraints (DECL_TEMPLATE_RESULT (pat2));
20614       lose1 = !subsumes_constraints (c1, c2);
20615       lose2 = !subsumes_constraints (c2, c1);
20616     }
20617 
20618   /* All things being equal, if the next argument is a pack expansion
20619      for one function but not for the other, prefer the
20620      non-variadic function.  FIXME this is bogus; see c++/41958.  */
20621   if (lose1 == lose2
20622       && args1 && TREE_VALUE (args1)
20623       && args2 && TREE_VALUE (args2))
20624     {
20625       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
20626       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
20627     }
20628 
20629   if (lose1 == lose2)
20630     return 0;
20631   else if (!lose1)
20632     return 1;
20633   else
20634     return -1;
20635 }
20636 
20637 /* Determine which of two partial specializations of TMPL is more
20638    specialized.
20639 
20640    PAT1 is a TREE_LIST whose TREE_VALUE is the TEMPLATE_DECL corresponding
20641    to the first partial specialization.  The TREE_PURPOSE is the
20642    innermost set of template parameters for the partial
20643    specialization.  PAT2 is similar, but for the second template.
20644 
20645    Return 1 if the first partial specialization is more specialized;
20646    -1 if the second is more specialized; 0 if neither is more
20647    specialized.
20648 
20649    See [temp.class.order] for information about determining which of
20650    two templates is more specialized.  */
20651 
20652 static int
more_specialized_partial_spec(tree tmpl,tree pat1,tree pat2)20653 more_specialized_partial_spec (tree tmpl, tree pat1, tree pat2)
20654 {
20655   tree targs;
20656   int winner = 0;
20657   bool any_deductions = false;
20658 
20659   tree tmpl1 = TREE_VALUE (pat1);
20660   tree tmpl2 = TREE_VALUE (pat2);
20661   tree parms1 = DECL_INNERMOST_TEMPLATE_PARMS (tmpl1);
20662   tree parms2 = DECL_INNERMOST_TEMPLATE_PARMS (tmpl2);
20663   tree specargs1 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl1)));
20664   tree specargs2 = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl2)));
20665 
20666   /* Just like what happens for functions, if we are ordering between
20667      different template specializations, we may encounter dependent
20668      types in the arguments, and we need our dependency check functions
20669      to behave correctly.  */
20670   ++processing_template_decl;
20671   targs = get_partial_spec_bindings (tmpl, parms1, specargs1, specargs2);
20672   if (targs)
20673     {
20674       --winner;
20675       any_deductions = true;
20676     }
20677 
20678   targs = get_partial_spec_bindings (tmpl, parms2, specargs2, specargs1);
20679   if (targs)
20680     {
20681       ++winner;
20682       any_deductions = true;
20683     }
20684   --processing_template_decl;
20685 
20686   /* If both deductions succeed, the partial ordering selects the more
20687      constrained template.  */
20688   if (!winner && any_deductions)
20689     return more_constrained (tmpl1, tmpl2);
20690 
20691   /* In the case of a tie where at least one of the templates
20692      has a parameter pack at the end, the template with the most
20693      non-packed parameters wins.  */
20694   if (winner == 0
20695       && any_deductions
20696       && (template_args_variadic_p (TREE_PURPOSE (pat1))
20697           || template_args_variadic_p (TREE_PURPOSE (pat2))))
20698     {
20699       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
20700       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
20701       int len1 = TREE_VEC_LENGTH (args1);
20702       int len2 = TREE_VEC_LENGTH (args2);
20703 
20704       /* We don't count the pack expansion at the end.  */
20705       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
20706         --len1;
20707       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
20708         --len2;
20709 
20710       if (len1 > len2)
20711         return 1;
20712       else if (len1 < len2)
20713         return -1;
20714     }
20715 
20716   return winner;
20717 }
20718 
20719 /* Return the template arguments that will produce the function signature
20720    DECL from the function template FN, with the explicit template
20721    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
20722    also match.  Return NULL_TREE if no satisfactory arguments could be
20723    found.  */
20724 
20725 static tree
get_bindings(tree fn,tree decl,tree explicit_args,bool check_rettype)20726 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
20727 {
20728   int ntparms = DECL_NTPARMS (fn);
20729   tree targs = make_tree_vec (ntparms);
20730   tree decl_type = TREE_TYPE (decl);
20731   tree decl_arg_types;
20732   tree *args;
20733   unsigned int nargs, ix;
20734   tree arg;
20735 
20736   gcc_assert (decl != DECL_TEMPLATE_RESULT (fn));
20737 
20738   /* Never do unification on the 'this' parameter.  */
20739   decl_arg_types = skip_artificial_parms_for (decl,
20740 					      TYPE_ARG_TYPES (decl_type));
20741 
20742   nargs = list_length (decl_arg_types);
20743   args = XALLOCAVEC (tree, nargs);
20744   for (arg = decl_arg_types, ix = 0;
20745        arg != NULL_TREE && arg != void_list_node;
20746        arg = TREE_CHAIN (arg), ++ix)
20747     args[ix] = TREE_VALUE (arg);
20748 
20749   if (fn_type_unification (fn, explicit_args, targs,
20750 			   args, ix,
20751 			   (check_rettype || DECL_CONV_FN_P (fn)
20752 			    ? TREE_TYPE (decl_type) : NULL_TREE),
20753 			   DEDUCE_EXACT, LOOKUP_NORMAL, /*explain_p=*/false,
20754 			   /*decltype*/false)
20755       == error_mark_node)
20756     return NULL_TREE;
20757 
20758   return targs;
20759 }
20760 
20761 /* Return the innermost template arguments that, when applied to a partial
20762    specialization of TMPL whose innermost template parameters are
20763    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
20764    ARGS.
20765 
20766    For example, suppose we have:
20767 
20768      template <class T, class U> struct S {};
20769      template <class T> struct S<T*, int> {};
20770 
20771    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
20772    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
20773    int}.  The resulting vector will be {double}, indicating that `T'
20774    is bound to `double'.  */
20775 
20776 static tree
get_partial_spec_bindings(tree tmpl,tree tparms,tree spec_args,tree args)20777 get_partial_spec_bindings (tree tmpl, tree tparms, tree spec_args, tree args)
20778 {
20779   int i, ntparms = TREE_VEC_LENGTH (tparms);
20780   tree deduced_args;
20781   tree innermost_deduced_args;
20782 
20783   innermost_deduced_args = make_tree_vec (ntparms);
20784   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
20785     {
20786       deduced_args = copy_node (args);
20787       SET_TMPL_ARGS_LEVEL (deduced_args,
20788 			   TMPL_ARGS_DEPTH (deduced_args),
20789 			   innermost_deduced_args);
20790     }
20791   else
20792     deduced_args = innermost_deduced_args;
20793 
20794   if (unify (tparms, deduced_args,
20795 	     INNERMOST_TEMPLATE_ARGS (spec_args),
20796 	     INNERMOST_TEMPLATE_ARGS (args),
20797 	     UNIFY_ALLOW_NONE, /*explain_p=*/false))
20798     return NULL_TREE;
20799 
20800   for (i =  0; i < ntparms; ++i)
20801     if (! TREE_VEC_ELT (innermost_deduced_args, i))
20802       return NULL_TREE;
20803 
20804   /* Verify that nondeduced template arguments agree with the type
20805      obtained from argument deduction.
20806 
20807      For example:
20808 
20809        struct A { typedef int X; };
20810        template <class T, class U> struct C {};
20811        template <class T> struct C<T, typename T::X> {};
20812 
20813      Then with the instantiation `C<A, int>', we can deduce that
20814      `T' is `A' but unify () does not check whether `typename T::X'
20815      is `int'.  */
20816   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
20817   spec_args = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
20818 				     spec_args, tmpl,
20819 				     tf_none, false, false);
20820   if (spec_args == error_mark_node
20821       /* We only need to check the innermost arguments; the other
20822 	 arguments will always agree.  */
20823       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
20824 			      INNERMOST_TEMPLATE_ARGS (args)))
20825     return NULL_TREE;
20826 
20827   /* Now that we have bindings for all of the template arguments,
20828      ensure that the arguments deduced for the template template
20829      parameters have compatible template parameter lists.  See the use
20830      of template_template_parm_bindings_ok_p in fn_type_unification
20831      for more information.  */
20832   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
20833     return NULL_TREE;
20834 
20835   return deduced_args;
20836 }
20837 
20838 // Compare two function templates T1 and T2 by deducing bindings
20839 // from one against the other. If both deductions succeed, compare
20840 // constraints to see which is more constrained.
20841 static int
more_specialized_inst(tree t1,tree t2)20842 more_specialized_inst (tree t1, tree t2)
20843 {
20844   int fate = 0;
20845   int count = 0;
20846 
20847   if (get_bindings (t1, DECL_TEMPLATE_RESULT (t2), NULL_TREE, true))
20848     {
20849       --fate;
20850       ++count;
20851     }
20852 
20853   if (get_bindings (t2, DECL_TEMPLATE_RESULT (t1), NULL_TREE, true))
20854     {
20855       ++fate;
20856       ++count;
20857     }
20858 
20859   // If both deductions succeed, then one may be more constrained.
20860   if (count == 2 && fate == 0)
20861     fate = more_constrained (t1, t2);
20862 
20863   return fate;
20864 }
20865 
20866 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
20867    Return the TREE_LIST node with the most specialized template, if
20868    any.  If there is no most specialized template, the error_mark_node
20869    is returned.
20870 
20871    Note that this function does not look at, or modify, the
20872    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
20873    returned is one of the elements of INSTANTIATIONS, callers may
20874    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
20875    and retrieve it from the value returned.  */
20876 
20877 tree
most_specialized_instantiation(tree templates)20878 most_specialized_instantiation (tree templates)
20879 {
20880   tree fn, champ;
20881 
20882   ++processing_template_decl;
20883 
20884   champ = templates;
20885   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
20886     {
20887       int fate = more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn));
20888       if (fate == -1)
20889 	champ = fn;
20890       else if (!fate)
20891 	{
20892 	  /* Equally specialized, move to next function.  If there
20893 	     is no next function, nothing's most specialized.  */
20894 	  fn = TREE_CHAIN (fn);
20895 	  champ = fn;
20896 	  if (!fn)
20897 	    break;
20898 	}
20899     }
20900 
20901   if (champ)
20902     /* Now verify that champ is better than everything earlier in the
20903        instantiation list.  */
20904     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn)) {
20905       if (more_specialized_inst (TREE_VALUE (champ), TREE_VALUE (fn)) != 1)
20906       {
20907         champ = NULL_TREE;
20908         break;
20909       }
20910     }
20911 
20912   processing_template_decl--;
20913 
20914   if (!champ)
20915     return error_mark_node;
20916 
20917   return champ;
20918 }
20919 
20920 /* If DECL is a specialization of some template, return the most
20921    general such template.  Otherwise, returns NULL_TREE.
20922 
20923    For example, given:
20924 
20925      template <class T> struct S { template <class U> void f(U); };
20926 
20927    if TMPL is `template <class U> void S<int>::f(U)' this will return
20928    the full template.  This function will not trace past partial
20929    specializations, however.  For example, given in addition:
20930 
20931      template <class T> struct S<T*> { template <class U> void f(U); };
20932 
20933    if TMPL is `template <class U> void S<int*>::f(U)' this will return
20934    `template <class T> template <class U> S<T*>::f(U)'.  */
20935 
20936 tree
most_general_template(tree decl)20937 most_general_template (tree decl)
20938 {
20939   if (TREE_CODE (decl) != TEMPLATE_DECL)
20940     {
20941       if (tree tinfo = get_template_info (decl))
20942 	decl = TI_TEMPLATE (tinfo);
20943       /* The TI_TEMPLATE can be an IDENTIFIER_NODE for a
20944 	 template friend, or a FIELD_DECL for a capture pack.  */
20945       if (TREE_CODE (decl) != TEMPLATE_DECL)
20946 	return NULL_TREE;
20947     }
20948 
20949   /* Look for more and more general templates.  */
20950   while (DECL_LANG_SPECIFIC (decl) && DECL_TEMPLATE_INFO (decl))
20951     {
20952       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
20953 	 (See cp-tree.h for details.)  */
20954       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
20955 	break;
20956 
20957       if (CLASS_TYPE_P (TREE_TYPE (decl))
20958 	  && !TYPE_DECL_ALIAS_P (TYPE_NAME (TREE_TYPE (decl)))
20959 	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
20960 	break;
20961 
20962       /* Stop if we run into an explicitly specialized class template.  */
20963       if (!DECL_NAMESPACE_SCOPE_P (decl)
20964 	  && DECL_CONTEXT (decl)
20965 	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
20966 	break;
20967 
20968       decl = DECL_TI_TEMPLATE (decl);
20969     }
20970 
20971   return decl;
20972 }
20973 
20974 /* Return the most specialized of the template partial specializations
20975    which can produce TARGET, a specialization of some class or variable
20976    template.  The value returned is actually a TREE_LIST; the TREE_VALUE is
20977    a TEMPLATE_DECL node corresponding to the partial specialization, while
20978    the TREE_PURPOSE is the set of template arguments that must be
20979    substituted into the template pattern in order to generate TARGET.
20980 
20981    If the choice of partial specialization is ambiguous, a diagnostic
20982    is issued, and the error_mark_node is returned.  If there are no
20983    partial specializations matching TARGET, then NULL_TREE is
20984    returned, indicating that the primary template should be used.  */
20985 
20986 static tree
most_specialized_partial_spec(tree target,tsubst_flags_t complain)20987 most_specialized_partial_spec (tree target, tsubst_flags_t complain)
20988 {
20989   tree list = NULL_TREE;
20990   tree t;
20991   tree champ;
20992   int fate;
20993   bool ambiguous_p;
20994   tree outer_args = NULL_TREE;
20995   tree tmpl, args;
20996 
20997   if (TYPE_P (target))
20998     {
20999       tree tinfo = CLASSTYPE_TEMPLATE_INFO (target);
21000       tmpl = TI_TEMPLATE (tinfo);
21001       args = TI_ARGS (tinfo);
21002     }
21003   else if (TREE_CODE (target) == TEMPLATE_ID_EXPR)
21004     {
21005       tmpl = TREE_OPERAND (target, 0);
21006       args = TREE_OPERAND (target, 1);
21007     }
21008   else if (VAR_P (target))
21009     {
21010       tree tinfo = DECL_TEMPLATE_INFO (target);
21011       tmpl = TI_TEMPLATE (tinfo);
21012       args = TI_ARGS (tinfo);
21013     }
21014   else
21015     gcc_unreachable ();
21016 
21017   tree main_tmpl = most_general_template (tmpl);
21018 
21019   /* For determining which partial specialization to use, only the
21020      innermost args are interesting.  */
21021   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
21022     {
21023       outer_args = strip_innermost_template_args (args, 1);
21024       args = INNERMOST_TEMPLATE_ARGS (args);
21025     }
21026 
21027   for (t = DECL_TEMPLATE_SPECIALIZATIONS (main_tmpl); t; t = TREE_CHAIN (t))
21028     {
21029       tree partial_spec_args;
21030       tree spec_args;
21031       tree spec_tmpl = TREE_VALUE (t);
21032 
21033       partial_spec_args = TREE_PURPOSE (t);
21034 
21035       ++processing_template_decl;
21036 
21037       if (outer_args)
21038 	{
21039 	  /* Discard the outer levels of args, and then substitute in the
21040 	     template args from the enclosing class.  */
21041 	  partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
21042 	  partial_spec_args = tsubst_template_args
21043 	    (partial_spec_args, outer_args, tf_none, NULL_TREE);
21044 
21045 	  /* And the same for the partial specialization TEMPLATE_DECL.  */
21046 	  spec_tmpl = tsubst (spec_tmpl, outer_args, tf_none, NULL_TREE);
21047 	}
21048 
21049       partial_spec_args =
21050 	  coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
21051 				 partial_spec_args,
21052 				 tmpl, tf_none,
21053 				 /*require_all_args=*/true,
21054 				 /*use_default_args=*/true);
21055 
21056       --processing_template_decl;
21057 
21058       if (partial_spec_args == error_mark_node)
21059 	return error_mark_node;
21060       if (spec_tmpl == error_mark_node)
21061 	return error_mark_node;
21062 
21063       tree parms = DECL_INNERMOST_TEMPLATE_PARMS (spec_tmpl);
21064       spec_args = get_partial_spec_bindings (tmpl, parms,
21065 				      partial_spec_args,
21066 				      args);
21067       if (spec_args)
21068 	{
21069 	  if (outer_args)
21070 	    spec_args = add_to_template_args (outer_args, spec_args);
21071 
21072           /* Keep the candidate only if the constraints are satisfied,
21073              or if we're not compiling with concepts.  */
21074           if (!flag_concepts
21075               || constraints_satisfied_p (spec_tmpl, spec_args))
21076             {
21077               list = tree_cons (spec_args, TREE_VALUE (t), list);
21078               TREE_TYPE (list) = TREE_TYPE (t);
21079             }
21080 	}
21081     }
21082 
21083   if (! list)
21084     return NULL_TREE;
21085 
21086   ambiguous_p = false;
21087   t = list;
21088   champ = t;
21089   t = TREE_CHAIN (t);
21090   for (; t; t = TREE_CHAIN (t))
21091     {
21092       fate = more_specialized_partial_spec (tmpl, champ, t);
21093       if (fate == 1)
21094 	;
21095       else
21096 	{
21097 	  if (fate == 0)
21098 	    {
21099 	      t = TREE_CHAIN (t);
21100 	      if (! t)
21101 		{
21102 		  ambiguous_p = true;
21103 		  break;
21104 		}
21105 	    }
21106 	  champ = t;
21107 	}
21108     }
21109 
21110   if (!ambiguous_p)
21111     for (t = list; t && t != champ; t = TREE_CHAIN (t))
21112       {
21113 	fate = more_specialized_partial_spec (tmpl, champ, t);
21114 	if (fate != 1)
21115 	  {
21116 	    ambiguous_p = true;
21117 	    break;
21118 	  }
21119       }
21120 
21121   if (ambiguous_p)
21122     {
21123       const char *str;
21124       char *spaces = NULL;
21125       if (!(complain & tf_error))
21126 	return error_mark_node;
21127       if (TYPE_P (target))
21128 	error ("ambiguous template instantiation for %q#T", target);
21129       else
21130 	error ("ambiguous template instantiation for %q#D", target);
21131       str = ngettext ("candidate is:", "candidates are:", list_length (list));
21132       for (t = list; t; t = TREE_CHAIN (t))
21133         {
21134 	  tree subst = build_tree_list (TREE_VALUE (t), TREE_PURPOSE (t));
21135           inform (DECL_SOURCE_LOCATION (TREE_VALUE (t)),
21136 		  "%s %#S", spaces ? spaces : str, subst);
21137           spaces = spaces ? spaces : get_spaces (str);
21138         }
21139       free (spaces);
21140       return error_mark_node;
21141     }
21142 
21143   return champ;
21144 }
21145 
21146 /* Explicitly instantiate DECL.  */
21147 
21148 void
do_decl_instantiation(tree decl,tree storage)21149 do_decl_instantiation (tree decl, tree storage)
21150 {
21151   tree result = NULL_TREE;
21152   int extern_p = 0;
21153 
21154   if (!decl || decl == error_mark_node)
21155     /* An error occurred, for which grokdeclarator has already issued
21156        an appropriate message.  */
21157     return;
21158   else if (! DECL_LANG_SPECIFIC (decl))
21159     {
21160       error ("explicit instantiation of non-template %q#D", decl);
21161       return;
21162     }
21163 
21164   bool var_templ = (DECL_TEMPLATE_INFO (decl)
21165                     && variable_template_p (DECL_TI_TEMPLATE (decl)));
21166 
21167   if (VAR_P (decl) && !var_templ)
21168     {
21169       /* There is an asymmetry here in the way VAR_DECLs and
21170 	 FUNCTION_DECLs are handled by grokdeclarator.  In the case of
21171 	 the latter, the DECL we get back will be marked as a
21172 	 template instantiation, and the appropriate
21173 	 DECL_TEMPLATE_INFO will be set up.  This does not happen for
21174 	 VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
21175 	 should handle VAR_DECLs as it currently handles
21176 	 FUNCTION_DECLs.  */
21177       if (!DECL_CLASS_SCOPE_P (decl))
21178 	{
21179 	  error ("%qD is not a static data member of a class template", decl);
21180 	  return;
21181 	}
21182       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
21183       if (!result || !VAR_P (result))
21184 	{
21185 	  error ("no matching template for %qD found", decl);
21186 	  return;
21187 	}
21188       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
21189 	{
21190 	  error ("type %qT for explicit instantiation %qD does not match "
21191 		 "declared type %qT", TREE_TYPE (result), decl,
21192 		 TREE_TYPE (decl));
21193 	  return;
21194 	}
21195     }
21196   else if (TREE_CODE (decl) != FUNCTION_DECL && !var_templ)
21197     {
21198       error ("explicit instantiation of %q#D", decl);
21199       return;
21200     }
21201   else
21202     result = decl;
21203 
21204   /* Check for various error cases.  Note that if the explicit
21205      instantiation is valid the RESULT will currently be marked as an
21206      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
21207      until we get here.  */
21208 
21209   if (DECL_TEMPLATE_SPECIALIZATION (result))
21210     {
21211       /* DR 259 [temp.spec].
21212 
21213 	 Both an explicit instantiation and a declaration of an explicit
21214 	 specialization shall not appear in a program unless the explicit
21215 	 instantiation follows a declaration of the explicit specialization.
21216 
21217 	 For a given set of template parameters, if an explicit
21218 	 instantiation of a template appears after a declaration of an
21219 	 explicit specialization for that template, the explicit
21220 	 instantiation has no effect.  */
21221       return;
21222     }
21223   else if (DECL_EXPLICIT_INSTANTIATION (result))
21224     {
21225       /* [temp.spec]
21226 
21227 	 No program shall explicitly instantiate any template more
21228 	 than once.
21229 
21230 	 We check DECL_NOT_REALLY_EXTERN so as not to complain when
21231 	 the first instantiation was `extern' and the second is not,
21232 	 and EXTERN_P for the opposite case.  */
21233       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
21234 	permerror (input_location, "duplicate explicit instantiation of %q#D", result);
21235       /* If an "extern" explicit instantiation follows an ordinary
21236 	 explicit instantiation, the template is instantiated.  */
21237       if (extern_p)
21238 	return;
21239     }
21240   else if (!DECL_IMPLICIT_INSTANTIATION (result))
21241     {
21242       error ("no matching template for %qD found", result);
21243       return;
21244     }
21245   else if (!DECL_TEMPLATE_INFO (result))
21246     {
21247       permerror (input_location, "explicit instantiation of non-template %q#D", result);
21248       return;
21249     }
21250 
21251   if (storage == NULL_TREE)
21252     ;
21253   else if (storage == ridpointers[(int) RID_EXTERN])
21254     {
21255       if (!in_system_header_at (input_location) && (cxx_dialect == cxx98))
21256 	pedwarn (input_location, OPT_Wpedantic,
21257 		 "ISO C++ 1998 forbids the use of %<extern%> on explicit "
21258 		 "instantiations");
21259       extern_p = 1;
21260     }
21261   else
21262     error ("storage class %qD applied to template instantiation", storage);
21263 
21264   check_explicit_instantiation_namespace (result);
21265   mark_decl_instantiated (result, extern_p);
21266   if (! extern_p)
21267     instantiate_decl (result, /*defer_ok=*/1,
21268 		      /*expl_inst_class_mem_p=*/false);
21269 }
21270 
21271 static void
mark_class_instantiated(tree t,int extern_p)21272 mark_class_instantiated (tree t, int extern_p)
21273 {
21274   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
21275   SET_CLASSTYPE_INTERFACE_KNOWN (t);
21276   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
21277   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
21278   if (! extern_p)
21279     {
21280       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
21281       rest_of_type_compilation (t, 1);
21282     }
21283 }
21284 
21285 /* Called from do_type_instantiation through binding_table_foreach to
21286    do recursive instantiation for the type bound in ENTRY.  */
21287 static void
bt_instantiate_type_proc(binding_entry entry,void * data)21288 bt_instantiate_type_proc (binding_entry entry, void *data)
21289 {
21290   tree storage = *(tree *) data;
21291 
21292   if (MAYBE_CLASS_TYPE_P (entry->type)
21293       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
21294     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
21295 }
21296 
21297 /* Called from do_type_instantiation to instantiate a member
21298    (a member function or a static member variable) of an
21299    explicitly instantiated class template.  */
21300 static void
instantiate_class_member(tree decl,int extern_p)21301 instantiate_class_member (tree decl, int extern_p)
21302 {
21303   mark_decl_instantiated (decl, extern_p);
21304   if (! extern_p)
21305     instantiate_decl (decl, /*defer_ok=*/1,
21306 		      /*expl_inst_class_mem_p=*/true);
21307 }
21308 
21309 /* Perform an explicit instantiation of template class T.  STORAGE, if
21310    non-null, is the RID for extern, inline or static.  COMPLAIN is
21311    nonzero if this is called from the parser, zero if called recursively,
21312    since the standard is unclear (as detailed below).  */
21313 
21314 void
do_type_instantiation(tree t,tree storage,tsubst_flags_t complain)21315 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
21316 {
21317   int extern_p = 0;
21318   int nomem_p = 0;
21319   int static_p = 0;
21320   int previous_instantiation_extern_p = 0;
21321 
21322   if (TREE_CODE (t) == TYPE_DECL)
21323     t = TREE_TYPE (t);
21324 
21325   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
21326     {
21327       tree tmpl =
21328 	(TYPE_TEMPLATE_INFO (t)) ? TYPE_TI_TEMPLATE (t) : NULL;
21329       if (tmpl)
21330 	error ("explicit instantiation of non-class template %qD", tmpl);
21331       else
21332 	error ("explicit instantiation of non-template type %qT", t);
21333       return;
21334     }
21335 
21336   complete_type (t);
21337 
21338   if (!COMPLETE_TYPE_P (t))
21339     {
21340       if (complain & tf_error)
21341 	error ("explicit instantiation of %q#T before definition of template",
21342 	       t);
21343       return;
21344     }
21345 
21346   if (storage != NULL_TREE)
21347     {
21348       if (!in_system_header_at (input_location))
21349 	{
21350 	  if (storage == ridpointers[(int) RID_EXTERN])
21351 	    {
21352 	      if (cxx_dialect == cxx98)
21353 		pedwarn (input_location, OPT_Wpedantic,
21354 			 "ISO C++ 1998 forbids the use of %<extern%> on "
21355 			 "explicit instantiations");
21356 	    }
21357 	  else
21358 	    pedwarn (input_location, OPT_Wpedantic,
21359 		     "ISO C++ forbids the use of %qE"
21360 		     " on explicit instantiations", storage);
21361 	}
21362 
21363       if (storage == ridpointers[(int) RID_INLINE])
21364 	nomem_p = 1;
21365       else if (storage == ridpointers[(int) RID_EXTERN])
21366 	extern_p = 1;
21367       else if (storage == ridpointers[(int) RID_STATIC])
21368 	static_p = 1;
21369       else
21370 	{
21371 	  error ("storage class %qD applied to template instantiation",
21372 		 storage);
21373 	  extern_p = 0;
21374 	}
21375     }
21376 
21377   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
21378     {
21379       /* DR 259 [temp.spec].
21380 
21381 	 Both an explicit instantiation and a declaration of an explicit
21382 	 specialization shall not appear in a program unless the explicit
21383 	 instantiation follows a declaration of the explicit specialization.
21384 
21385 	 For a given set of template parameters, if an explicit
21386 	 instantiation of a template appears after a declaration of an
21387 	 explicit specialization for that template, the explicit
21388 	 instantiation has no effect.  */
21389       return;
21390     }
21391   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
21392     {
21393       /* [temp.spec]
21394 
21395 	 No program shall explicitly instantiate any template more
21396 	 than once.
21397 
21398 	 If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
21399 	 instantiation was `extern'.  If EXTERN_P then the second is.
21400 	 These cases are OK.  */
21401       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
21402 
21403       if (!previous_instantiation_extern_p && !extern_p
21404 	  && (complain & tf_error))
21405 	permerror (input_location, "duplicate explicit instantiation of %q#T", t);
21406 
21407       /* If we've already instantiated the template, just return now.  */
21408       if (!CLASSTYPE_INTERFACE_ONLY (t))
21409 	return;
21410     }
21411 
21412   check_explicit_instantiation_namespace (TYPE_NAME (t));
21413   mark_class_instantiated (t, extern_p);
21414 
21415   if (nomem_p)
21416     return;
21417 
21418   {
21419     tree tmp;
21420 
21421     /* In contrast to implicit instantiation, where only the
21422        declarations, and not the definitions, of members are
21423        instantiated, we have here:
21424 
21425 	 [temp.explicit]
21426 
21427 	 The explicit instantiation of a class template specialization
21428 	 implies the instantiation of all of its members not
21429 	 previously explicitly specialized in the translation unit
21430 	 containing the explicit instantiation.
21431 
21432        Of course, we can't instantiate member template classes, since
21433        we don't have any arguments for them.  Note that the standard
21434        is unclear on whether the instantiation of the members are
21435        *explicit* instantiations or not.  However, the most natural
21436        interpretation is that it should be an explicit instantiation.  */
21437 
21438     if (! static_p)
21439       for (tmp = TYPE_METHODS (t); tmp; tmp = DECL_CHAIN (tmp))
21440 	if (TREE_CODE (tmp) == FUNCTION_DECL
21441 	    && DECL_TEMPLATE_INSTANTIATION (tmp)
21442 	    && (!extern_p || user_provided_p (tmp)))
21443 	  instantiate_class_member (tmp, extern_p);
21444 
21445     for (tmp = TYPE_FIELDS (t); tmp; tmp = DECL_CHAIN (tmp))
21446       if (VAR_P (tmp) && DECL_TEMPLATE_INSTANTIATION (tmp))
21447 	instantiate_class_member (tmp, extern_p);
21448 
21449     if (CLASSTYPE_NESTED_UTDS (t))
21450       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
21451 			     bt_instantiate_type_proc, &storage);
21452   }
21453 }
21454 
21455 /* Given a function DECL, which is a specialization of TMPL, modify
21456    DECL to be a re-instantiation of TMPL with the same template
21457    arguments.  TMPL should be the template into which tsubst'ing
21458    should occur for DECL, not the most general template.
21459 
21460    One reason for doing this is a scenario like this:
21461 
21462      template <class T>
21463      void f(const T&, int i);
21464 
21465      void g() { f(3, 7); }
21466 
21467      template <class T>
21468      void f(const T& t, const int i) { }
21469 
21470    Note that when the template is first instantiated, with
21471    instantiate_template, the resulting DECL will have no name for the
21472    first parameter, and the wrong type for the second.  So, when we go
21473    to instantiate the DECL, we regenerate it.  */
21474 
21475 static void
regenerate_decl_from_template(tree decl,tree tmpl,tree args)21476 regenerate_decl_from_template (tree decl, tree tmpl, tree args)
21477 {
21478   /* The arguments used to instantiate DECL, from the most general
21479      template.  */
21480   tree code_pattern;
21481 
21482   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
21483 
21484   /* Make sure that we can see identifiers, and compute access
21485      correctly.  */
21486   push_access_scope (decl);
21487 
21488   if (TREE_CODE (decl) == FUNCTION_DECL)
21489     {
21490       tree decl_parm;
21491       tree pattern_parm;
21492       tree specs;
21493       int args_depth;
21494       int parms_depth;
21495 
21496       args_depth = TMPL_ARGS_DEPTH (args);
21497       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
21498       if (args_depth > parms_depth)
21499 	args = get_innermost_template_args (args, parms_depth);
21500 
21501       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
21502 					      args, tf_error, NULL_TREE,
21503 					      /*defer_ok*/false);
21504       if (specs && specs != error_mark_node)
21505 	TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
21506 						    specs);
21507 
21508       /* Merge parameter declarations.  */
21509       decl_parm = skip_artificial_parms_for (decl,
21510 					     DECL_ARGUMENTS (decl));
21511       pattern_parm
21512 	= skip_artificial_parms_for (code_pattern,
21513 				     DECL_ARGUMENTS (code_pattern));
21514       while (decl_parm && !DECL_PACK_P (pattern_parm))
21515 	{
21516 	  tree parm_type;
21517 	  tree attributes;
21518 
21519 	  if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
21520 	    DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
21521 	  parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
21522 			      NULL_TREE);
21523 	  parm_type = type_decays_to (parm_type);
21524 	  if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
21525 	    TREE_TYPE (decl_parm) = parm_type;
21526 	  attributes = DECL_ATTRIBUTES (pattern_parm);
21527 	  if (DECL_ATTRIBUTES (decl_parm) != attributes)
21528 	    {
21529 	      DECL_ATTRIBUTES (decl_parm) = attributes;
21530 	      cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
21531 	    }
21532 	  decl_parm = DECL_CHAIN (decl_parm);
21533 	  pattern_parm = DECL_CHAIN (pattern_parm);
21534 	}
21535       /* Merge any parameters that match with the function parameter
21536          pack.  */
21537       if (pattern_parm && DECL_PACK_P (pattern_parm))
21538         {
21539           int i, len;
21540           tree expanded_types;
21541           /* Expand the TYPE_PACK_EXPANSION that provides the types for
21542              the parameters in this function parameter pack.  */
21543           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm),
21544                                                  args, tf_error, NULL_TREE);
21545           len = TREE_VEC_LENGTH (expanded_types);
21546           for (i = 0; i < len; i++)
21547             {
21548               tree parm_type;
21549               tree attributes;
21550 
21551               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
21552                 /* Rename the parameter to include the index.  */
21553                 DECL_NAME (decl_parm) =
21554                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
21555               parm_type = TREE_VEC_ELT (expanded_types, i);
21556               parm_type = type_decays_to (parm_type);
21557               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
21558                 TREE_TYPE (decl_parm) = parm_type;
21559               attributes = DECL_ATTRIBUTES (pattern_parm);
21560               if (DECL_ATTRIBUTES (decl_parm) != attributes)
21561                 {
21562                   DECL_ATTRIBUTES (decl_parm) = attributes;
21563                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
21564                 }
21565               decl_parm = DECL_CHAIN (decl_parm);
21566             }
21567         }
21568       /* Merge additional specifiers from the CODE_PATTERN.  */
21569       if (DECL_DECLARED_INLINE_P (code_pattern)
21570 	  && !DECL_DECLARED_INLINE_P (decl))
21571 	DECL_DECLARED_INLINE_P (decl) = 1;
21572     }
21573   else if (VAR_P (decl))
21574     {
21575       DECL_INITIAL (decl) =
21576 	tsubst_expr (DECL_INITIAL (code_pattern), args,
21577 		     tf_error, DECL_TI_TEMPLATE (decl),
21578 		     /*integral_constant_expression_p=*/false);
21579       if (VAR_HAD_UNKNOWN_BOUND (decl))
21580 	TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
21581 				   tf_error, DECL_TI_TEMPLATE (decl));
21582     }
21583   else
21584     gcc_unreachable ();
21585 
21586   pop_access_scope (decl);
21587 }
21588 
21589 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
21590    substituted to get DECL.  */
21591 
21592 tree
template_for_substitution(tree decl)21593 template_for_substitution (tree decl)
21594 {
21595   tree tmpl = DECL_TI_TEMPLATE (decl);
21596 
21597   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
21598      for the instantiation.  This is not always the most general
21599      template.  Consider, for example:
21600 
21601 	template <class T>
21602 	struct S { template <class U> void f();
21603 		   template <> void f<int>(); };
21604 
21605      and an instantiation of S<double>::f<int>.  We want TD to be the
21606      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
21607   while (/* An instantiation cannot have a definition, so we need a
21608 	    more general template.  */
21609 	 DECL_TEMPLATE_INSTANTIATION (tmpl)
21610 	   /* We must also deal with friend templates.  Given:
21611 
21612 		template <class T> struct S {
21613 		  template <class U> friend void f() {};
21614 		};
21615 
21616 	      S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
21617 	      so far as the language is concerned, but that's still
21618 	      where we get the pattern for the instantiation from.  On
21619 	      other hand, if the definition comes outside the class, say:
21620 
21621 		template <class T> struct S {
21622 		  template <class U> friend void f();
21623 		};
21624 		template <class U> friend void f() {}
21625 
21626 	      we don't need to look any further.  That's what the check for
21627 	      DECL_INITIAL is for.  */
21628 	  || (TREE_CODE (decl) == FUNCTION_DECL
21629 	      && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
21630 	      && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
21631     {
21632       /* The present template, TD, should not be a definition.  If it
21633 	 were a definition, we should be using it!  Note that we
21634 	 cannot restructure the loop to just keep going until we find
21635 	 a template with a definition, since that might go too far if
21636 	 a specialization was declared, but not defined.  */
21637 
21638       /* Fetch the more general template.  */
21639       tmpl = DECL_TI_TEMPLATE (tmpl);
21640     }
21641 
21642   return tmpl;
21643 }
21644 
21645 /* Returns true if we need to instantiate this template instance even if we
21646    know we aren't going to emit it.  */
21647 
21648 bool
always_instantiate_p(tree decl)21649 always_instantiate_p (tree decl)
21650 {
21651   /* We always instantiate inline functions so that we can inline them.  An
21652      explicit instantiation declaration prohibits implicit instantiation of
21653      non-inline functions.  With high levels of optimization, we would
21654      normally inline non-inline functions -- but we're not allowed to do
21655      that for "extern template" functions.  Therefore, we check
21656      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
21657   return ((TREE_CODE (decl) == FUNCTION_DECL
21658 	   && (DECL_DECLARED_INLINE_P (decl)
21659 	       || type_uses_auto (TREE_TYPE (TREE_TYPE (decl)))))
21660 	  /* And we need to instantiate static data members so that
21661 	     their initializers are available in integral constant
21662 	     expressions.  */
21663 	  || (VAR_P (decl)
21664 	      && decl_maybe_constant_var_p (decl)));
21665 }
21666 
21667 /* If FN has a noexcept-specifier that hasn't been instantiated yet,
21668    instantiate it now, modifying TREE_TYPE (fn).  */
21669 
21670 void
maybe_instantiate_noexcept(tree fn)21671 maybe_instantiate_noexcept (tree fn)
21672 {
21673   tree fntype, spec, noex, clone;
21674 
21675   /* Don't instantiate a noexcept-specification from template context.  */
21676   if (processing_template_decl)
21677     return;
21678 
21679   if (DECL_CLONED_FUNCTION_P (fn))
21680     fn = DECL_CLONED_FUNCTION (fn);
21681   fntype = TREE_TYPE (fn);
21682   spec = TYPE_RAISES_EXCEPTIONS (fntype);
21683 
21684   if (!spec || !TREE_PURPOSE (spec))
21685     return;
21686 
21687   noex = TREE_PURPOSE (spec);
21688 
21689   if (TREE_CODE (noex) == DEFERRED_NOEXCEPT)
21690     {
21691       if (DEFERRED_NOEXCEPT_PATTERN (noex) == NULL_TREE)
21692 	spec = get_defaulted_eh_spec (fn);
21693       else if (push_tinst_level (fn))
21694 	{
21695 	  push_access_scope (fn);
21696 	  push_deferring_access_checks (dk_no_deferred);
21697 	  input_location = DECL_SOURCE_LOCATION (fn);
21698 	  noex = tsubst_copy_and_build (DEFERRED_NOEXCEPT_PATTERN (noex),
21699 					DEFERRED_NOEXCEPT_ARGS (noex),
21700 					tf_warning_or_error, fn,
21701 					/*function_p=*/false,
21702 					/*integral_constant_expression_p=*/true);
21703 	  pop_deferring_access_checks ();
21704 	  pop_access_scope (fn);
21705 	  pop_tinst_level ();
21706 	  spec = build_noexcept_spec (noex, tf_warning_or_error);
21707 	  if (spec == error_mark_node)
21708 	    spec = noexcept_false_spec;
21709 	}
21710       else
21711 	spec = noexcept_false_spec;
21712 
21713       TREE_TYPE (fn) = build_exception_variant (fntype, spec);
21714     }
21715 
21716   FOR_EACH_CLONE (clone, fn)
21717     {
21718       if (TREE_TYPE (clone) == fntype)
21719 	TREE_TYPE (clone) = TREE_TYPE (fn);
21720       else
21721 	TREE_TYPE (clone) = build_exception_variant (TREE_TYPE (clone), spec);
21722     }
21723 }
21724 
21725 /* Produce the definition of D, a _DECL generated from a template.  If
21726    DEFER_OK is nonzero, then we don't have to actually do the
21727    instantiation now; we just have to do it sometime.  Normally it is
21728    an error if this is an explicit instantiation but D is undefined.
21729    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
21730    explicitly instantiated class template.  */
21731 
21732 tree
instantiate_decl(tree d,int defer_ok,bool expl_inst_class_mem_p)21733 instantiate_decl (tree d, int defer_ok,
21734 		  bool expl_inst_class_mem_p)
21735 {
21736   tree tmpl = DECL_TI_TEMPLATE (d);
21737   tree gen_args;
21738   tree args;
21739   tree td;
21740   tree code_pattern;
21741   tree spec;
21742   tree gen_tmpl;
21743   bool pattern_defined;
21744   location_t saved_loc = input_location;
21745   int saved_unevaluated_operand = cp_unevaluated_operand;
21746   int saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
21747   bool external_p;
21748   bool deleted_p;
21749   tree fn_context;
21750   bool nested = false;
21751 
21752   /* This function should only be used to instantiate templates for
21753      functions and static member variables.  */
21754   gcc_assert (VAR_OR_FUNCTION_DECL_P (d));
21755 
21756   /* A concept is never instantiated. */
21757   gcc_assert (!DECL_DECLARED_CONCEPT_P (d));
21758 
21759   /* Variables are never deferred; if instantiation is required, they
21760      are instantiated right away.  That allows for better code in the
21761      case that an expression refers to the value of the variable --
21762      if the variable has a constant value the referring expression can
21763      take advantage of that fact.  */
21764   if (VAR_P (d)
21765       || DECL_DECLARED_CONSTEXPR_P (d))
21766     defer_ok = 0;
21767 
21768   /* Don't instantiate cloned functions.  Instead, instantiate the
21769      functions they cloned.  */
21770   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
21771     d = DECL_CLONED_FUNCTION (d);
21772 
21773   if (DECL_TEMPLATE_INSTANTIATED (d)
21774       || (TREE_CODE (d) == FUNCTION_DECL
21775 	  && DECL_DEFAULTED_FN (d) && DECL_INITIAL (d))
21776       || DECL_TEMPLATE_SPECIALIZATION (d))
21777     /* D has already been instantiated or explicitly specialized, so
21778        there's nothing for us to do here.
21779 
21780        It might seem reasonable to check whether or not D is an explicit
21781        instantiation, and, if so, stop here.  But when an explicit
21782        instantiation is deferred until the end of the compilation,
21783        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
21784        the instantiation.  */
21785     return d;
21786 
21787   /* Check to see whether we know that this template will be
21788      instantiated in some other file, as with "extern template"
21789      extension.  */
21790   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
21791 
21792   /* In general, we do not instantiate such templates.  */
21793   if (external_p && !always_instantiate_p (d))
21794     return d;
21795 
21796   gen_tmpl = most_general_template (tmpl);
21797   gen_args = DECL_TI_ARGS (d);
21798 
21799   if (tmpl != gen_tmpl)
21800     /* We should already have the extra args.  */
21801     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
21802 		== TMPL_ARGS_DEPTH (gen_args));
21803   /* And what's in the hash table should match D.  */
21804   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
21805 	      || spec == NULL_TREE);
21806 
21807   /* This needs to happen before any tsubsting.  */
21808   if (! push_tinst_level (d))
21809     return d;
21810 
21811   timevar_push (TV_TEMPLATE_INST);
21812 
21813   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
21814      for the instantiation.  */
21815   td = template_for_substitution (d);
21816   args = gen_args;
21817 
21818   if (VAR_P (d))
21819     {
21820       /* Look up an explicit specialization, if any.  */
21821       tree tid = lookup_template_variable (gen_tmpl, gen_args);
21822       tree elt = most_specialized_partial_spec (tid, tf_warning_or_error);
21823       if (elt && elt != error_mark_node)
21824 	{
21825 	  td = TREE_VALUE (elt);
21826 	  args = TREE_PURPOSE (elt);
21827 	}
21828     }
21829 
21830   code_pattern = DECL_TEMPLATE_RESULT (td);
21831 
21832   /* We should never be trying to instantiate a member of a class
21833      template or partial specialization.  */
21834   gcc_assert (d != code_pattern);
21835 
21836   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
21837       || DECL_TEMPLATE_SPECIALIZATION (td))
21838     /* In the case of a friend template whose definition is provided
21839        outside the class, we may have too many arguments.  Drop the
21840        ones we don't need.  The same is true for specializations.  */
21841     args = get_innermost_template_args
21842       (args, TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (td)));
21843 
21844   if (TREE_CODE (d) == FUNCTION_DECL)
21845     {
21846       deleted_p = DECL_DELETED_FN (code_pattern);
21847       pattern_defined = ((DECL_SAVED_TREE (code_pattern) != NULL_TREE
21848 			  && DECL_INITIAL (code_pattern) != error_mark_node)
21849 			 || DECL_DEFAULTED_OUTSIDE_CLASS_P (code_pattern)
21850 			 || deleted_p);
21851     }
21852   else
21853     {
21854       deleted_p = false;
21855       if (DECL_CLASS_SCOPE_P (code_pattern))
21856 	pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
21857       else
21858 	pattern_defined = ! DECL_EXTERNAL (code_pattern);
21859     }
21860 
21861   /* We may be in the middle of deferred access check.  Disable it now.  */
21862   push_deferring_access_checks (dk_no_deferred);
21863 
21864   /* Unless an explicit instantiation directive has already determined
21865      the linkage of D, remember that a definition is available for
21866      this entity.  */
21867   if (pattern_defined
21868       && !DECL_INTERFACE_KNOWN (d)
21869       && !DECL_NOT_REALLY_EXTERN (d))
21870     mark_definable (d);
21871 
21872   DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
21873   DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
21874   input_location = DECL_SOURCE_LOCATION (d);
21875 
21876   /* If D is a member of an explicitly instantiated class template,
21877      and no definition is available, treat it like an implicit
21878      instantiation.  */
21879   if (!pattern_defined && expl_inst_class_mem_p
21880       && DECL_EXPLICIT_INSTANTIATION (d))
21881     {
21882       /* Leave linkage flags alone on instantiations with anonymous
21883 	 visibility.  */
21884       if (TREE_PUBLIC (d))
21885 	{
21886 	  DECL_NOT_REALLY_EXTERN (d) = 0;
21887 	  DECL_INTERFACE_KNOWN (d) = 0;
21888 	}
21889       SET_DECL_IMPLICIT_INSTANTIATION (d);
21890     }
21891 
21892   /* Defer all other templates, unless we have been explicitly
21893      forbidden from doing so.  */
21894   if (/* If there is no definition, we cannot instantiate the
21895 	 template.  */
21896       ! pattern_defined
21897       /* If it's OK to postpone instantiation, do so.  */
21898       || defer_ok
21899       /* If this is a static data member that will be defined
21900 	 elsewhere, we don't want to instantiate the entire data
21901 	 member, but we do want to instantiate the initializer so that
21902 	 we can substitute that elsewhere.  */
21903       || (external_p && VAR_P (d))
21904       /* Handle here a deleted function too, avoid generating
21905 	 its body (c++/61080).  */
21906       || deleted_p)
21907     {
21908       /* The definition of the static data member is now required so
21909 	 we must substitute the initializer.  */
21910       if (VAR_P (d)
21911 	  && !DECL_INITIAL (d)
21912 	  && DECL_INITIAL (code_pattern))
21913 	{
21914 	  tree ns;
21915 	  tree init;
21916 	  bool const_init = false;
21917 	  bool enter_context = DECL_CLASS_SCOPE_P (d);
21918 
21919 	  ns = decl_namespace_context (d);
21920 	  push_nested_namespace (ns);
21921 	  if (enter_context)
21922 	    push_nested_class (DECL_CONTEXT (d));
21923 	  init = tsubst_expr (DECL_INITIAL (code_pattern),
21924 			      args,
21925 			      tf_warning_or_error, NULL_TREE,
21926 			      /*integral_constant_expression_p=*/false);
21927 	  /* If instantiating the initializer involved instantiating this
21928 	     again, don't call cp_finish_decl twice.  */
21929 	  if (!DECL_INITIAL (d))
21930 	    {
21931 	      /* Make sure the initializer is still constant, in case of
21932 		 circular dependency (template/instantiate6.C). */
21933 	      const_init
21934 		= DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
21935 	      cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
21936 			      /*asmspec_tree=*/NULL_TREE,
21937 			      LOOKUP_ONLYCONVERTING);
21938 	    }
21939 	  if (enter_context)
21940 	    pop_nested_class ();
21941 	  pop_nested_namespace (ns);
21942 	}
21943 
21944       /* We restore the source position here because it's used by
21945 	 add_pending_template.  */
21946       input_location = saved_loc;
21947 
21948       if (at_eof && !pattern_defined
21949 	  && DECL_EXPLICIT_INSTANTIATION (d)
21950 	  && DECL_NOT_REALLY_EXTERN (d))
21951 	/* [temp.explicit]
21952 
21953 	   The definition of a non-exported function template, a
21954 	   non-exported member function template, or a non-exported
21955 	   member function or static data member of a class template
21956 	   shall be present in every translation unit in which it is
21957 	   explicitly instantiated.  */
21958 	permerror (input_location,  "explicit instantiation of %qD "
21959 		   "but no definition available", d);
21960 
21961       /* If we're in unevaluated context, we just wanted to get the
21962 	 constant value; this isn't an odr use, so don't queue
21963 	 a full instantiation.  */
21964       if (cp_unevaluated_operand != 0)
21965 	goto out;
21966       /* ??? Historically, we have instantiated inline functions, even
21967 	 when marked as "extern template".  */
21968       if (!(external_p && VAR_P (d)))
21969 	add_pending_template (d);
21970       goto out;
21971     }
21972   /* Tell the repository that D is available in this translation unit
21973      -- and see if it is supposed to be instantiated here.  */
21974   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
21975     {
21976       /* In a PCH file, despite the fact that the repository hasn't
21977 	 requested instantiation in the PCH it is still possible that
21978 	 an instantiation will be required in a file that includes the
21979 	 PCH.  */
21980       if (pch_file)
21981 	add_pending_template (d);
21982       /* Instantiate inline functions so that the inliner can do its
21983 	 job, even though we'll not be emitting a copy of this
21984 	 function.  */
21985       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
21986 	goto out;
21987     }
21988 
21989   fn_context = decl_function_context (d);
21990   nested = (current_function_decl != NULL_TREE);
21991   vec<tree> omp_privatization_save;
21992   if (nested)
21993     save_omp_privatization_clauses (omp_privatization_save);
21994 
21995   if (!fn_context)
21996     push_to_top_level ();
21997   else
21998     {
21999       if (nested)
22000 	push_function_context ();
22001       cp_unevaluated_operand = 0;
22002       c_inhibit_evaluation_warnings = 0;
22003     }
22004 
22005   /* Mark D as instantiated so that recursive calls to
22006      instantiate_decl do not try to instantiate it again.  */
22007   DECL_TEMPLATE_INSTANTIATED (d) = 1;
22008 
22009   /* Regenerate the declaration in case the template has been modified
22010      by a subsequent redeclaration.  */
22011   regenerate_decl_from_template (d, td, args);
22012 
22013   /* We already set the file and line above.  Reset them now in case
22014      they changed as a result of calling regenerate_decl_from_template.  */
22015   input_location = DECL_SOURCE_LOCATION (d);
22016 
22017   if (VAR_P (d))
22018     {
22019       tree init;
22020       bool const_init = false;
22021 
22022       /* Clear out DECL_RTL; whatever was there before may not be right
22023 	 since we've reset the type of the declaration.  */
22024       SET_DECL_RTL (d, NULL);
22025       DECL_IN_AGGR_P (d) = 0;
22026 
22027       /* The initializer is placed in DECL_INITIAL by
22028 	 regenerate_decl_from_template so we don't need to
22029 	 push/pop_access_scope again here.  Pull it out so that
22030 	 cp_finish_decl can process it.  */
22031       init = DECL_INITIAL (d);
22032       DECL_INITIAL (d) = NULL_TREE;
22033       DECL_INITIALIZED_P (d) = 0;
22034 
22035       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
22036 	 initializer.  That function will defer actual emission until
22037 	 we have a chance to determine linkage.  */
22038       DECL_EXTERNAL (d) = 0;
22039 
22040       /* Enter the scope of D so that access-checking works correctly.  */
22041       bool enter_context = DECL_CLASS_SCOPE_P (d);
22042       if (enter_context)
22043         push_nested_class (DECL_CONTEXT (d));
22044 
22045       const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
22046       cp_finish_decl (d, init, const_init, NULL_TREE, 0);
22047 
22048       if (enter_context)
22049         pop_nested_class ();
22050 
22051       if (variable_template_p (gen_tmpl))
22052 	note_variable_template_instantiation (d);
22053     }
22054   else if (TREE_CODE (d) == FUNCTION_DECL && DECL_DEFAULTED_FN (code_pattern))
22055     synthesize_method (d);
22056   else if (TREE_CODE (d) == FUNCTION_DECL)
22057     {
22058       hash_map<tree, tree> *saved_local_specializations;
22059       tree subst_decl;
22060       tree tmpl_parm;
22061       tree spec_parm;
22062       tree block = NULL_TREE;
22063 
22064       /* Save away the current list, in case we are instantiating one
22065 	 template from within the body of another.  */
22066       saved_local_specializations = local_specializations;
22067 
22068       /* Set up the list of local specializations.  */
22069       local_specializations = new hash_map<tree, tree>;
22070 
22071       /* Set up context.  */
22072       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern)
22073 	  && TREE_CODE (DECL_CONTEXT (code_pattern)) == FUNCTION_DECL)
22074 	block = push_stmt_list ();
22075       else
22076 	start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
22077 
22078       /* Some typedefs referenced from within the template code need to be
22079 	 access checked at template instantiation time, i.e now. These
22080 	 types were added to the template at parsing time. Let's get those
22081 	 and perform the access checks then.  */
22082       perform_typedefs_access_check (DECL_TEMPLATE_RESULT (gen_tmpl),
22083 				     gen_args);
22084 
22085       /* Create substitution entries for the parameters.  */
22086       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
22087       tmpl_parm = DECL_ARGUMENTS (subst_decl);
22088       spec_parm = DECL_ARGUMENTS (d);
22089       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
22090 	{
22091 	  register_local_specialization (spec_parm, tmpl_parm);
22092 	  spec_parm = skip_artificial_parms_for (d, spec_parm);
22093 	  tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
22094 	}
22095       for (; tmpl_parm; tmpl_parm = DECL_CHAIN (tmpl_parm))
22096 	{
22097 	  if (!DECL_PACK_P (tmpl_parm))
22098 	    {
22099 	      register_local_specialization (spec_parm, tmpl_parm);
22100 	      spec_parm = DECL_CHAIN (spec_parm);
22101 	    }
22102 	  else
22103 	    {
22104 	      /* Register the (value) argument pack as a specialization of
22105 		 TMPL_PARM, then move on.  */
22106 	      tree argpack = extract_fnparm_pack (tmpl_parm, &spec_parm);
22107 	      register_local_specialization (argpack, tmpl_parm);
22108 	    }
22109 	}
22110       gcc_assert (!spec_parm);
22111 
22112       /* Substitute into the body of the function.  */
22113       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
22114 	tsubst_omp_udr (DECL_SAVED_TREE (code_pattern), args,
22115 			tf_warning_or_error, tmpl);
22116       else
22117 	{
22118 	  tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
22119 		       tf_warning_or_error, tmpl,
22120 		       /*integral_constant_expression_p=*/false);
22121 
22122 	  /* Set the current input_location to the end of the function
22123 	     so that finish_function knows where we are.  */
22124 	  input_location
22125 	    = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
22126 
22127 	  /* Remember if we saw an infinite loop in the template.  */
22128 	  current_function_infinite_loop
22129 	    = DECL_STRUCT_FUNCTION (code_pattern)->language->infinite_loop;
22130 	}
22131 
22132       /* We don't need the local specializations any more.  */
22133       delete local_specializations;
22134       local_specializations = saved_local_specializations;
22135 
22136       /* Finish the function.  */
22137       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern)
22138 	  && TREE_CODE (DECL_CONTEXT (code_pattern)) == FUNCTION_DECL)
22139 	DECL_SAVED_TREE (d) = pop_stmt_list (block);
22140       else
22141 	{
22142 	  d = finish_function (0);
22143 	  expand_or_defer_fn (d);
22144 	}
22145 
22146       if (DECL_OMP_DECLARE_REDUCTION_P (code_pattern))
22147 	cp_check_omp_declare_reduction (d);
22148     }
22149 
22150   /* We're not deferring instantiation any more.  */
22151   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
22152 
22153   if (!fn_context)
22154     pop_from_top_level ();
22155   else if (nested)
22156     pop_function_context ();
22157 
22158 out:
22159   input_location = saved_loc;
22160   cp_unevaluated_operand = saved_unevaluated_operand;
22161   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
22162   pop_deferring_access_checks ();
22163   pop_tinst_level ();
22164   if (nested)
22165     restore_omp_privatization_clauses (omp_privatization_save);
22166 
22167   timevar_pop (TV_TEMPLATE_INST);
22168 
22169   return d;
22170 }
22171 
22172 /* Run through the list of templates that we wish we could
22173    instantiate, and instantiate any we can.  RETRIES is the
22174    number of times we retry pending template instantiation.  */
22175 
22176 void
instantiate_pending_templates(int retries)22177 instantiate_pending_templates (int retries)
22178 {
22179   int reconsider;
22180   location_t saved_loc = input_location;
22181 
22182   /* Instantiating templates may trigger vtable generation.  This in turn
22183      may require further template instantiations.  We place a limit here
22184      to avoid infinite loop.  */
22185   if (pending_templates && retries >= max_tinst_depth)
22186     {
22187       tree decl = pending_templates->tinst->decl;
22188 
22189       fatal_error (input_location,
22190 		   "template instantiation depth exceeds maximum of %d"
22191                    " instantiating %q+D, possibly from virtual table generation"
22192                    " (use -ftemplate-depth= to increase the maximum)",
22193                    max_tinst_depth, decl);
22194       if (TREE_CODE (decl) == FUNCTION_DECL)
22195 	/* Pretend that we defined it.  */
22196 	DECL_INITIAL (decl) = error_mark_node;
22197       return;
22198     }
22199 
22200   do
22201     {
22202       struct pending_template **t = &pending_templates;
22203       struct pending_template *last = NULL;
22204       reconsider = 0;
22205       while (*t)
22206 	{
22207 	  tree instantiation = reopen_tinst_level ((*t)->tinst);
22208 	  bool complete = false;
22209 
22210 	  if (TYPE_P (instantiation))
22211 	    {
22212 	      tree fn;
22213 
22214 	      if (!COMPLETE_TYPE_P (instantiation))
22215 		{
22216 		  instantiate_class_template (instantiation);
22217 		  if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
22218 		    for (fn = TYPE_METHODS (instantiation);
22219 			 fn;
22220 			 fn = TREE_CHAIN (fn))
22221 		      if (! DECL_ARTIFICIAL (fn))
22222 			instantiate_decl (fn,
22223 					  /*defer_ok=*/0,
22224 					  /*expl_inst_class_mem_p=*/false);
22225 		  if (COMPLETE_TYPE_P (instantiation))
22226 		    reconsider = 1;
22227 		}
22228 
22229 	      complete = COMPLETE_TYPE_P (instantiation);
22230 	    }
22231 	  else
22232 	    {
22233 	      if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
22234 		  && !DECL_TEMPLATE_INSTANTIATED (instantiation))
22235 		{
22236 		  instantiation
22237 		    = instantiate_decl (instantiation,
22238 					/*defer_ok=*/0,
22239 					/*expl_inst_class_mem_p=*/false);
22240 		  if (DECL_TEMPLATE_INSTANTIATED (instantiation))
22241 		    reconsider = 1;
22242 		}
22243 
22244 	      complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
22245 			  || DECL_TEMPLATE_INSTANTIATED (instantiation));
22246 	    }
22247 
22248 	  if (complete)
22249 	    /* If INSTANTIATION has been instantiated, then we don't
22250 	       need to consider it again in the future.  */
22251 	    *t = (*t)->next;
22252 	  else
22253 	    {
22254 	      last = *t;
22255 	      t = &(*t)->next;
22256 	    }
22257 	  tinst_depth = 0;
22258 	  current_tinst_level = NULL;
22259 	}
22260       last_pending_template = last;
22261     }
22262   while (reconsider);
22263 
22264   input_location = saved_loc;
22265 }
22266 
22267 /* Substitute ARGVEC into T, which is a list of initializers for
22268    either base class or a non-static data member.  The TREE_PURPOSEs
22269    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
22270    instantiate_decl.  */
22271 
22272 static tree
tsubst_initializer_list(tree t,tree argvec)22273 tsubst_initializer_list (tree t, tree argvec)
22274 {
22275   tree inits = NULL_TREE;
22276 
22277   for (; t; t = TREE_CHAIN (t))
22278     {
22279       tree decl;
22280       tree init;
22281       tree expanded_bases = NULL_TREE;
22282       tree expanded_arguments = NULL_TREE;
22283       int i, len = 1;
22284 
22285       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
22286         {
22287           tree expr;
22288           tree arg;
22289 
22290           /* Expand the base class expansion type into separate base
22291              classes.  */
22292           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
22293                                                  tf_warning_or_error,
22294                                                  NULL_TREE);
22295           if (expanded_bases == error_mark_node)
22296             continue;
22297 
22298           /* We'll be building separate TREE_LISTs of arguments for
22299              each base.  */
22300           len = TREE_VEC_LENGTH (expanded_bases);
22301           expanded_arguments = make_tree_vec (len);
22302           for (i = 0; i < len; i++)
22303             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
22304 
22305           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
22306              expand each argument in the TREE_VALUE of t.  */
22307           expr = make_node (EXPR_PACK_EXPANSION);
22308 	  PACK_EXPANSION_LOCAL_P (expr) = true;
22309           PACK_EXPANSION_PARAMETER_PACKS (expr) =
22310             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
22311 
22312 	  if (TREE_VALUE (t) == void_type_node)
22313 	    /* VOID_TYPE_NODE is used to indicate
22314 	       value-initialization.  */
22315 	    {
22316 	      for (i = 0; i < len; i++)
22317 		TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
22318 	    }
22319 	  else
22320 	    {
22321 	      /* Substitute parameter packs into each argument in the
22322 		 TREE_LIST.  */
22323 	      in_base_initializer = 1;
22324 	      for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
22325 		{
22326 		  tree expanded_exprs;
22327 
22328 		  /* Expand the argument.  */
22329 		  SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
22330 		  expanded_exprs
22331 		    = tsubst_pack_expansion (expr, argvec,
22332 					     tf_warning_or_error,
22333 					     NULL_TREE);
22334 		  if (expanded_exprs == error_mark_node)
22335 		    continue;
22336 
22337 		  /* Prepend each of the expanded expressions to the
22338 		     corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
22339 		  for (i = 0; i < len; i++)
22340 		    {
22341 		      TREE_VEC_ELT (expanded_arguments, i) =
22342 			tree_cons (NULL_TREE,
22343 				   TREE_VEC_ELT (expanded_exprs, i),
22344 				   TREE_VEC_ELT (expanded_arguments, i));
22345 		    }
22346 		}
22347 	      in_base_initializer = 0;
22348 
22349 	      /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
22350 		 since we built them backwards.  */
22351 	      for (i = 0; i < len; i++)
22352 		{
22353 		  TREE_VEC_ELT (expanded_arguments, i) =
22354 		    nreverse (TREE_VEC_ELT (expanded_arguments, i));
22355 		}
22356 	    }
22357         }
22358 
22359       for (i = 0; i < len; ++i)
22360         {
22361           if (expanded_bases)
22362             {
22363               decl = TREE_VEC_ELT (expanded_bases, i);
22364               decl = expand_member_init (decl);
22365               init = TREE_VEC_ELT (expanded_arguments, i);
22366             }
22367           else
22368             {
22369 	      tree tmp;
22370               decl = tsubst_copy (TREE_PURPOSE (t), argvec,
22371                                   tf_warning_or_error, NULL_TREE);
22372 
22373               decl = expand_member_init (decl);
22374               if (decl && !DECL_P (decl))
22375                 in_base_initializer = 1;
22376 
22377 	      init = TREE_VALUE (t);
22378 	      tmp = init;
22379 	      if (init != void_type_node)
22380 		init = tsubst_expr (init, argvec,
22381 				    tf_warning_or_error, NULL_TREE,
22382 				    /*integral_constant_expression_p=*/false);
22383 	      if (init == NULL_TREE && tmp != NULL_TREE)
22384 		/* If we had an initializer but it instantiated to nothing,
22385 		   value-initialize the object.  This will only occur when
22386 		   the initializer was a pack expansion where the parameter
22387 		   packs used in that expansion were of length zero.  */
22388 		init = void_type_node;
22389               in_base_initializer = 0;
22390             }
22391 
22392           if (decl)
22393             {
22394               init = build_tree_list (decl, init);
22395               TREE_CHAIN (init) = inits;
22396               inits = init;
22397             }
22398         }
22399     }
22400   return inits;
22401 }
22402 
22403 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
22404 
22405 static void
set_current_access_from_decl(tree decl)22406 set_current_access_from_decl (tree decl)
22407 {
22408   if (TREE_PRIVATE (decl))
22409     current_access_specifier = access_private_node;
22410   else if (TREE_PROTECTED (decl))
22411     current_access_specifier = access_protected_node;
22412   else
22413     current_access_specifier = access_public_node;
22414 }
22415 
22416 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
22417    is the instantiation (which should have been created with
22418    start_enum) and ARGS are the template arguments to use.  */
22419 
22420 static void
tsubst_enum(tree tag,tree newtag,tree args)22421 tsubst_enum (tree tag, tree newtag, tree args)
22422 {
22423   tree e;
22424 
22425   if (SCOPED_ENUM_P (newtag))
22426     begin_scope (sk_scoped_enum, newtag);
22427 
22428   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
22429     {
22430       tree value;
22431       tree decl;
22432 
22433       decl = TREE_VALUE (e);
22434       /* Note that in a template enum, the TREE_VALUE is the
22435 	 CONST_DECL, not the corresponding INTEGER_CST.  */
22436       value = tsubst_expr (DECL_INITIAL (decl),
22437 			   args, tf_warning_or_error, NULL_TREE,
22438 			   /*integral_constant_expression_p=*/true);
22439 
22440       /* Give this enumeration constant the correct access.  */
22441       set_current_access_from_decl (decl);
22442 
22443       /* Actually build the enumerator itself.  Here we're assuming that
22444 	 enumerators can't have dependent attributes.  */
22445       build_enumerator (DECL_NAME (decl), value, newtag,
22446 			DECL_ATTRIBUTES (decl), DECL_SOURCE_LOCATION (decl));
22447     }
22448 
22449   if (SCOPED_ENUM_P (newtag))
22450     finish_scope ();
22451 
22452   finish_enum_value_list (newtag);
22453   finish_enum (newtag);
22454 
22455   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
22456     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
22457 }
22458 
22459 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
22460    its type -- but without substituting the innermost set of template
22461    arguments.  So, innermost set of template parameters will appear in
22462    the type.  */
22463 
22464 tree
get_mostly_instantiated_function_type(tree decl)22465 get_mostly_instantiated_function_type (tree decl)
22466 {
22467   /* For a function, DECL_TI_TEMPLATE is partially instantiated.  */
22468   return TREE_TYPE (DECL_TI_TEMPLATE (decl));
22469 }
22470 
22471 /* Return truthvalue if we're processing a template different from
22472    the last one involved in diagnostics.  */
22473 bool
problematic_instantiation_changed(void)22474 problematic_instantiation_changed (void)
22475 {
22476   return current_tinst_level != last_error_tinst_level;
22477 }
22478 
22479 /* Remember current template involved in diagnostics.  */
22480 void
record_last_problematic_instantiation(void)22481 record_last_problematic_instantiation (void)
22482 {
22483   last_error_tinst_level = current_tinst_level;
22484 }
22485 
22486 struct tinst_level *
current_instantiation(void)22487 current_instantiation (void)
22488 {
22489   return current_tinst_level;
22490 }
22491 
22492 /* Return TRUE if current_function_decl is being instantiated, false
22493    otherwise.  */
22494 
22495 bool
instantiating_current_function_p(void)22496 instantiating_current_function_p (void)
22497 {
22498   return (current_instantiation ()
22499 	  && current_instantiation ()->decl == current_function_decl);
22500 }
22501 
22502 /* [temp.param] Check that template non-type parm TYPE is of an allowable
22503    type. Return zero for ok, nonzero for disallowed. Issue error and
22504    warning messages under control of COMPLAIN.  */
22505 
22506 static int
invalid_nontype_parm_type_p(tree type,tsubst_flags_t complain)22507 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
22508 {
22509   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
22510     return 0;
22511   else if (POINTER_TYPE_P (type))
22512     return 0;
22513   else if (TYPE_PTRMEM_P (type))
22514     return 0;
22515   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
22516     return 0;
22517   else if (TREE_CODE (type) == TYPENAME_TYPE)
22518     return 0;
22519   else if (TREE_CODE (type) == DECLTYPE_TYPE)
22520     return 0;
22521   else if (TREE_CODE (type) == NULLPTR_TYPE)
22522     return 0;
22523   /* A bound template template parm could later be instantiated to have a valid
22524      nontype parm type via an alias template.  */
22525   else if (cxx_dialect >= cxx11
22526 	   && TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
22527     return 0;
22528 
22529   if (complain & tf_error)
22530     {
22531       if (type == error_mark_node)
22532 	inform (input_location, "invalid template non-type parameter");
22533       else
22534 	error ("%q#T is not a valid type for a template non-type parameter",
22535 	       type);
22536     }
22537   return 1;
22538 }
22539 
22540 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
22541    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
22542 
22543 static bool
dependent_type_p_r(tree type)22544 dependent_type_p_r (tree type)
22545 {
22546   tree scope;
22547 
22548   /* [temp.dep.type]
22549 
22550      A type is dependent if it is:
22551 
22552      -- a template parameter. Template template parameters are types
22553 	for us (since TYPE_P holds true for them) so we handle
22554 	them here.  */
22555   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
22556       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
22557     return true;
22558   /* -- a qualified-id with a nested-name-specifier which contains a
22559 	class-name that names a dependent type or whose unqualified-id
22560 	names a dependent type.  */
22561   if (TREE_CODE (type) == TYPENAME_TYPE)
22562     return true;
22563 
22564   /* An alias template specialization can be dependent even if the
22565      resulting type is not.  */
22566   if (dependent_alias_template_spec_p (type))
22567     return true;
22568 
22569   /* -- a cv-qualified type where the cv-unqualified type is
22570 	dependent.
22571      No code is necessary for this bullet; the code below handles
22572      cv-qualified types, and we don't want to strip aliases with
22573      TYPE_MAIN_VARIANT because of DR 1558.  */
22574   /* -- a compound type constructed from any dependent type.  */
22575   if (TYPE_PTRMEM_P (type))
22576     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
22577 	    || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
22578 					   (type)));
22579   else if (TYPE_PTR_P (type)
22580 	   || TREE_CODE (type) == REFERENCE_TYPE)
22581     return dependent_type_p (TREE_TYPE (type));
22582   else if (TREE_CODE (type) == FUNCTION_TYPE
22583 	   || TREE_CODE (type) == METHOD_TYPE)
22584     {
22585       tree arg_type;
22586 
22587       if (dependent_type_p (TREE_TYPE (type)))
22588 	return true;
22589       for (arg_type = TYPE_ARG_TYPES (type);
22590 	   arg_type;
22591 	   arg_type = TREE_CHAIN (arg_type))
22592 	if (dependent_type_p (TREE_VALUE (arg_type)))
22593 	  return true;
22594       return false;
22595     }
22596   /* -- an array type constructed from any dependent type or whose
22597 	size is specified by a constant expression that is
22598 	value-dependent.
22599 
22600         We checked for type- and value-dependence of the bounds in
22601         compute_array_index_type, so TYPE_DEPENDENT_P is already set.  */
22602   if (TREE_CODE (type) == ARRAY_TYPE)
22603     {
22604       if (TYPE_DOMAIN (type)
22605 	  && dependent_type_p (TYPE_DOMAIN (type)))
22606 	return true;
22607       return dependent_type_p (TREE_TYPE (type));
22608     }
22609 
22610   /* -- a template-id in which either the template name is a template
22611      parameter ...  */
22612   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
22613     return true;
22614   /* ... or any of the template arguments is a dependent type or
22615 	an expression that is type-dependent or value-dependent.  */
22616   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
22617 	   && (any_dependent_template_arguments_p
22618 	       (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
22619     return true;
22620 
22621   /* All TYPEOF_TYPEs, DECLTYPE_TYPEs, and UNDERLYING_TYPEs are
22622      dependent; if the argument of the `typeof' expression is not
22623      type-dependent, then it should already been have resolved.  */
22624   if (TREE_CODE (type) == TYPEOF_TYPE
22625       || TREE_CODE (type) == DECLTYPE_TYPE
22626       || TREE_CODE (type) == UNDERLYING_TYPE)
22627     return true;
22628 
22629   /* A template argument pack is dependent if any of its packed
22630      arguments are.  */
22631   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
22632     {
22633       tree args = ARGUMENT_PACK_ARGS (type);
22634       int i, len = TREE_VEC_LENGTH (args);
22635       for (i = 0; i < len; ++i)
22636         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
22637           return true;
22638     }
22639 
22640   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
22641      be template parameters.  */
22642   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
22643     return true;
22644 
22645   /* The standard does not specifically mention types that are local
22646      to template functions or local classes, but they should be
22647      considered dependent too.  For example:
22648 
22649        template <int I> void f() {
22650 	 enum E { a = I };
22651 	 S<sizeof (E)> s;
22652        }
22653 
22654      The size of `E' cannot be known until the value of `I' has been
22655      determined.  Therefore, `E' must be considered dependent.  */
22656   scope = TYPE_CONTEXT (type);
22657   if (scope && TYPE_P (scope))
22658     return dependent_type_p (scope);
22659   /* Don't use type_dependent_expression_p here, as it can lead
22660      to infinite recursion trying to determine whether a lambda
22661      nested in a lambda is dependent (c++/47687).  */
22662   else if (scope && TREE_CODE (scope) == FUNCTION_DECL
22663 	   && DECL_LANG_SPECIFIC (scope)
22664 	   && DECL_TEMPLATE_INFO (scope)
22665 	   && (any_dependent_template_arguments_p
22666 	       (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (scope)))))
22667     return true;
22668 
22669   /* Other types are non-dependent.  */
22670   return false;
22671 }
22672 
22673 /* Returns TRUE if TYPE is dependent, in the sense of
22674    [temp.dep.type].  Note that a NULL type is considered dependent.  */
22675 
22676 bool
dependent_type_p(tree type)22677 dependent_type_p (tree type)
22678 {
22679   /* If there are no template parameters in scope, then there can't be
22680      any dependent types.  */
22681   if (!processing_template_decl)
22682     {
22683       /* If we are not processing a template, then nobody should be
22684 	 providing us with a dependent type.  */
22685       gcc_assert (type);
22686       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
22687       return false;
22688     }
22689 
22690   /* If the type is NULL, we have not computed a type for the entity
22691      in question; in that case, the type is dependent.  */
22692   if (!type)
22693     return true;
22694 
22695   /* Erroneous types can be considered non-dependent.  */
22696   if (type == error_mark_node)
22697     return false;
22698 
22699   /* If we have not already computed the appropriate value for TYPE,
22700      do so now.  */
22701   if (!TYPE_DEPENDENT_P_VALID (type))
22702     {
22703       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
22704       TYPE_DEPENDENT_P_VALID (type) = 1;
22705     }
22706 
22707   return TYPE_DEPENDENT_P (type);
22708 }
22709 
22710 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
22711    lookup.  In other words, a dependent type that is not the current
22712    instantiation.  */
22713 
22714 bool
dependent_scope_p(tree scope)22715 dependent_scope_p (tree scope)
22716 {
22717   return (scope && TYPE_P (scope) && dependent_type_p (scope)
22718 	  && !currently_open_class (scope));
22719 }
22720 
22721 /* T is a SCOPE_REF; return whether we need to consider it
22722     instantiation-dependent so that we can check access at instantiation
22723     time even though we know which member it resolves to.  */
22724 
22725 static bool
instantiation_dependent_scope_ref_p(tree t)22726 instantiation_dependent_scope_ref_p (tree t)
22727 {
22728   if (DECL_P (TREE_OPERAND (t, 1))
22729       && CLASS_TYPE_P (TREE_OPERAND (t, 0))
22730       && accessible_in_template_p (TREE_OPERAND (t, 0),
22731 				   TREE_OPERAND (t, 1)))
22732     return false;
22733   else
22734     return true;
22735 }
22736 
22737 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
22738    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
22739    expression.  */
22740 
22741 /* Note that this predicate is not appropriate for general expressions;
22742    only constant expressions (that satisfy potential_constant_expression)
22743    can be tested for value dependence.  */
22744 
22745 bool
value_dependent_expression_p(tree expression)22746 value_dependent_expression_p (tree expression)
22747 {
22748   if (!processing_template_decl)
22749     return false;
22750 
22751   /* A name declared with a dependent type.  */
22752   if (DECL_P (expression) && type_dependent_expression_p (expression))
22753     return true;
22754 
22755   switch (TREE_CODE (expression))
22756     {
22757     case IDENTIFIER_NODE:
22758       /* A name that has not been looked up -- must be dependent.  */
22759       return true;
22760 
22761     case TEMPLATE_PARM_INDEX:
22762       /* A non-type template parm.  */
22763       return true;
22764 
22765     case CONST_DECL:
22766       /* A non-type template parm.  */
22767       if (DECL_TEMPLATE_PARM_P (expression))
22768 	return true;
22769       return value_dependent_expression_p (DECL_INITIAL (expression));
22770 
22771     case VAR_DECL:
22772        /* A constant with literal type and is initialized
22773 	  with an expression that is value-dependent.
22774 
22775           Note that a non-dependent parenthesized initializer will have
22776           already been replaced with its constant value, so if we see
22777           a TREE_LIST it must be dependent.  */
22778       if (DECL_INITIAL (expression)
22779 	  && decl_constant_var_p (expression)
22780 	  && (TREE_CODE (DECL_INITIAL (expression)) == TREE_LIST
22781 	      /* cp_finish_decl doesn't fold reference initializers.  */
22782 	      || TREE_CODE (TREE_TYPE (expression)) == REFERENCE_TYPE
22783 	      || type_dependent_expression_p (DECL_INITIAL (expression))
22784 	      || value_dependent_expression_p (DECL_INITIAL (expression))))
22785 	return true;
22786       return false;
22787 
22788     case DYNAMIC_CAST_EXPR:
22789     case STATIC_CAST_EXPR:
22790     case CONST_CAST_EXPR:
22791     case REINTERPRET_CAST_EXPR:
22792     case CAST_EXPR:
22793       /* These expressions are value-dependent if the type to which
22794 	 the cast occurs is dependent or the expression being casted
22795 	 is value-dependent.  */
22796       {
22797 	tree type = TREE_TYPE (expression);
22798 
22799 	if (dependent_type_p (type))
22800 	  return true;
22801 
22802 	/* A functional cast has a list of operands.  */
22803 	expression = TREE_OPERAND (expression, 0);
22804 	if (!expression)
22805 	  {
22806 	    /* If there are no operands, it must be an expression such
22807 	       as "int()". This should not happen for aggregate types
22808 	       because it would form non-constant expressions.  */
22809 	    gcc_assert (cxx_dialect >= cxx11
22810 			|| INTEGRAL_OR_ENUMERATION_TYPE_P (type));
22811 
22812 	    return false;
22813 	  }
22814 
22815 	if (TREE_CODE (expression) == TREE_LIST)
22816 	  return any_value_dependent_elements_p (expression);
22817 
22818 	return value_dependent_expression_p (expression);
22819       }
22820 
22821     case SIZEOF_EXPR:
22822       if (SIZEOF_EXPR_TYPE_P (expression))
22823 	return dependent_type_p (TREE_TYPE (TREE_OPERAND (expression, 0)));
22824       /* FALLTHRU */
22825     case ALIGNOF_EXPR:
22826     case TYPEID_EXPR:
22827       /* A `sizeof' expression is value-dependent if the operand is
22828 	 type-dependent or is a pack expansion.  */
22829       expression = TREE_OPERAND (expression, 0);
22830       if (PACK_EXPANSION_P (expression))
22831         return true;
22832       else if (TYPE_P (expression))
22833 	return dependent_type_p (expression);
22834       return instantiation_dependent_uneval_expression_p (expression);
22835 
22836     case AT_ENCODE_EXPR:
22837       /* An 'encode' expression is value-dependent if the operand is
22838 	 type-dependent.  */
22839       expression = TREE_OPERAND (expression, 0);
22840       return dependent_type_p (expression);
22841 
22842     case NOEXCEPT_EXPR:
22843       expression = TREE_OPERAND (expression, 0);
22844       return instantiation_dependent_uneval_expression_p (expression);
22845 
22846     case SCOPE_REF:
22847       /* All instantiation-dependent expressions should also be considered
22848 	 value-dependent.  */
22849       return instantiation_dependent_scope_ref_p (expression);
22850 
22851     case COMPONENT_REF:
22852       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
22853 	      || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
22854 
22855     case NONTYPE_ARGUMENT_PACK:
22856       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
22857          is value-dependent.  */
22858       {
22859         tree values = ARGUMENT_PACK_ARGS (expression);
22860         int i, len = TREE_VEC_LENGTH (values);
22861 
22862         for (i = 0; i < len; ++i)
22863           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
22864             return true;
22865 
22866         return false;
22867       }
22868 
22869     case TRAIT_EXPR:
22870       {
22871 	tree type2 = TRAIT_EXPR_TYPE2 (expression);
22872 	return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
22873 		|| (type2 ? dependent_type_p (type2) : false));
22874       }
22875 
22876     case MODOP_EXPR:
22877       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
22878 	      || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
22879 
22880     case ARRAY_REF:
22881       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
22882 	      || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
22883 
22884     case ADDR_EXPR:
22885       {
22886 	tree op = TREE_OPERAND (expression, 0);
22887 	return (value_dependent_expression_p (op)
22888 		|| has_value_dependent_address (op));
22889       }
22890 
22891     case REQUIRES_EXPR:
22892       /* Treat all requires-expressions as value-dependent so
22893          we don't try to fold them.  */
22894       return true;
22895 
22896     case TYPE_REQ:
22897       return dependent_type_p (TREE_OPERAND (expression, 0));
22898 
22899     case CALL_EXPR:
22900       {
22901 	tree fn = get_callee_fndecl (expression);
22902 	int i, nargs;
22903 	if (!fn && value_dependent_expression_p (CALL_EXPR_FN (expression)))
22904 	  return true;
22905 	nargs = call_expr_nargs (expression);
22906 	for (i = 0; i < nargs; ++i)
22907 	  {
22908 	    tree op = CALL_EXPR_ARG (expression, i);
22909 	    /* In a call to a constexpr member function, look through the
22910 	       implicit ADDR_EXPR on the object argument so that it doesn't
22911 	       cause the call to be considered value-dependent.  We also
22912 	       look through it in potential_constant_expression.  */
22913 	    if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
22914 		&& DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
22915 		&& TREE_CODE (op) == ADDR_EXPR)
22916 	      op = TREE_OPERAND (op, 0);
22917 	    if (value_dependent_expression_p (op))
22918 	      return true;
22919 	  }
22920 	return false;
22921       }
22922 
22923     case TEMPLATE_ID_EXPR:
22924       /* If a TEMPLATE_ID_EXPR involves a dependent name, it will be
22925 	 type-dependent.  */
22926       return type_dependent_expression_p (expression)
22927 	|| variable_concept_p (TREE_OPERAND (expression, 0));
22928 
22929     case CONSTRUCTOR:
22930       {
22931 	unsigned ix;
22932 	tree val;
22933 	if (dependent_type_p (TREE_TYPE (expression)))
22934 	  return true;
22935 	FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), ix, val)
22936 	  if (value_dependent_expression_p (val))
22937 	    return true;
22938 	return false;
22939       }
22940 
22941     case STMT_EXPR:
22942       /* Treat a GNU statement expression as dependent to avoid crashing
22943 	 under instantiate_non_dependent_expr; it can't be constant.  */
22944       return true;
22945 
22946     default:
22947       /* A constant expression is value-dependent if any subexpression is
22948 	 value-dependent.  */
22949       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
22950 	{
22951 	case tcc_reference:
22952 	case tcc_unary:
22953 	case tcc_comparison:
22954 	case tcc_binary:
22955 	case tcc_expression:
22956 	case tcc_vl_exp:
22957 	  {
22958 	    int i, len = cp_tree_operand_length (expression);
22959 
22960 	    for (i = 0; i < len; i++)
22961 	      {
22962 		tree t = TREE_OPERAND (expression, i);
22963 
22964 		/* In some cases, some of the operands may be missing.l
22965 		   (For example, in the case of PREDECREMENT_EXPR, the
22966 		   amount to increment by may be missing.)  That doesn't
22967 		   make the expression dependent.  */
22968 		if (t && value_dependent_expression_p (t))
22969 		  return true;
22970 	      }
22971 	  }
22972 	  break;
22973 	default:
22974 	  break;
22975 	}
22976       break;
22977     }
22978 
22979   /* The expression is not value-dependent.  */
22980   return false;
22981 }
22982 
22983 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
22984    [temp.dep.expr].  Note that an expression with no type is
22985    considered dependent.  Other parts of the compiler arrange for an
22986    expression with type-dependent subexpressions to have no type, so
22987    this function doesn't have to be fully recursive.  */
22988 
22989 bool
type_dependent_expression_p(tree expression)22990 type_dependent_expression_p (tree expression)
22991 {
22992   if (!processing_template_decl)
22993     return false;
22994 
22995   if (expression == NULL_TREE || expression == error_mark_node)
22996     return false;
22997 
22998   /* An unresolved name is always dependent.  */
22999   if (identifier_p (expression)
23000       || TREE_CODE (expression) == USING_DECL
23001       || TREE_CODE (expression) == WILDCARD_DECL)
23002     return true;
23003 
23004   /* A fold expression is type-dependent. */
23005   if (TREE_CODE (expression) == UNARY_LEFT_FOLD_EXPR
23006       || TREE_CODE (expression) == UNARY_RIGHT_FOLD_EXPR
23007       || TREE_CODE (expression) == BINARY_LEFT_FOLD_EXPR
23008       || TREE_CODE (expression) == BINARY_RIGHT_FOLD_EXPR)
23009     return true;
23010 
23011   /* Some expression forms are never type-dependent.  */
23012   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
23013       || TREE_CODE (expression) == SIZEOF_EXPR
23014       || TREE_CODE (expression) == ALIGNOF_EXPR
23015       || TREE_CODE (expression) == AT_ENCODE_EXPR
23016       || TREE_CODE (expression) == NOEXCEPT_EXPR
23017       || TREE_CODE (expression) == TRAIT_EXPR
23018       || TREE_CODE (expression) == TYPEID_EXPR
23019       || TREE_CODE (expression) == DELETE_EXPR
23020       || TREE_CODE (expression) == VEC_DELETE_EXPR
23021       || TREE_CODE (expression) == THROW_EXPR
23022       || TREE_CODE (expression) == REQUIRES_EXPR)
23023     return false;
23024 
23025   /* The types of these expressions depends only on the type to which
23026      the cast occurs.  */
23027   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
23028       || TREE_CODE (expression) == STATIC_CAST_EXPR
23029       || TREE_CODE (expression) == CONST_CAST_EXPR
23030       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
23031       || TREE_CODE (expression) == IMPLICIT_CONV_EXPR
23032       || TREE_CODE (expression) == CAST_EXPR)
23033     return dependent_type_p (TREE_TYPE (expression));
23034 
23035   /* The types of these expressions depends only on the type created
23036      by the expression.  */
23037   if (TREE_CODE (expression) == NEW_EXPR
23038       || TREE_CODE (expression) == VEC_NEW_EXPR)
23039     {
23040       /* For NEW_EXPR tree nodes created inside a template, either
23041 	 the object type itself or a TREE_LIST may appear as the
23042 	 operand 1.  */
23043       tree type = TREE_OPERAND (expression, 1);
23044       if (TREE_CODE (type) == TREE_LIST)
23045 	/* This is an array type.  We need to check array dimensions
23046 	   as well.  */
23047 	return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
23048 	       || value_dependent_expression_p
23049 		    (TREE_OPERAND (TREE_VALUE (type), 1));
23050       else
23051 	return dependent_type_p (type);
23052     }
23053 
23054   if (TREE_CODE (expression) == SCOPE_REF)
23055     {
23056       tree scope = TREE_OPERAND (expression, 0);
23057       tree name = TREE_OPERAND (expression, 1);
23058 
23059       /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
23060 	 contains an identifier associated by name lookup with one or more
23061 	 declarations declared with a dependent type, or...a
23062 	 nested-name-specifier or qualified-id that names a member of an
23063 	 unknown specialization.  */
23064       return (type_dependent_expression_p (name)
23065 	      || dependent_scope_p (scope));
23066     }
23067 
23068   /* A function template specialization is type-dependent if it has any
23069      dependent template arguments.  */
23070   if (TREE_CODE (expression) == FUNCTION_DECL
23071       && DECL_LANG_SPECIFIC (expression)
23072       && DECL_TEMPLATE_INFO (expression))
23073     return any_dependent_template_arguments_p (DECL_TI_ARGS (expression));
23074 
23075   if (TREE_CODE (expression) == TEMPLATE_DECL
23076       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
23077     return false;
23078 
23079   if (TREE_CODE (expression) == STMT_EXPR)
23080     expression = stmt_expr_value_expr (expression);
23081 
23082   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
23083     {
23084       tree elt;
23085       unsigned i;
23086 
23087       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
23088 	{
23089 	  if (type_dependent_expression_p (elt))
23090 	    return true;
23091 	}
23092       return false;
23093     }
23094 
23095   /* A static data member of the current instantiation with incomplete
23096      array type is type-dependent, as the definition and specializations
23097      can have different bounds.  */
23098   if (VAR_P (expression)
23099       && DECL_CLASS_SCOPE_P (expression)
23100       && dependent_type_p (DECL_CONTEXT (expression))
23101       && VAR_HAD_UNKNOWN_BOUND (expression))
23102     return true;
23103 
23104   /* An array of unknown bound depending on a variadic parameter, eg:
23105 
23106      template<typename... Args>
23107        void foo (Args... args)
23108        {
23109          int arr[] = { args... };
23110        }
23111 
23112      template<int... vals>
23113        void bar ()
23114        {
23115          int arr[] = { vals... };
23116        }
23117 
23118      If the array has no length and has an initializer, it must be that
23119      we couldn't determine its length in cp_complete_array_type because
23120      it is dependent.  */
23121   if (VAR_P (expression)
23122       && TREE_CODE (TREE_TYPE (expression)) == ARRAY_TYPE
23123       && !TYPE_DOMAIN (TREE_TYPE (expression))
23124       && DECL_INITIAL (expression))
23125    return true;
23126 
23127   /* A variable template specialization is type-dependent if it has any
23128      dependent template arguments.  */
23129   if (VAR_P (expression)
23130       && DECL_LANG_SPECIFIC (expression)
23131       && DECL_TEMPLATE_INFO (expression)
23132       && variable_template_p (DECL_TI_TEMPLATE (expression)))
23133     return any_dependent_template_arguments_p (DECL_TI_ARGS (expression));
23134 
23135   /* Always dependent, on the number of arguments if nothing else.  */
23136   if (TREE_CODE (expression) == EXPR_PACK_EXPANSION)
23137     return true;
23138 
23139   if (TREE_TYPE (expression) == unknown_type_node)
23140     {
23141       if (TREE_CODE (expression) == ADDR_EXPR)
23142 	return type_dependent_expression_p (TREE_OPERAND (expression, 0));
23143       if (TREE_CODE (expression) == COMPONENT_REF
23144 	  || TREE_CODE (expression) == OFFSET_REF)
23145 	{
23146 	  if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
23147 	    return true;
23148 	  expression = TREE_OPERAND (expression, 1);
23149 	  if (identifier_p (expression))
23150 	    return false;
23151 	}
23152       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
23153       if (TREE_CODE (expression) == SCOPE_REF)
23154 	return false;
23155 
23156       if (BASELINK_P (expression))
23157 	{
23158 	  if (BASELINK_OPTYPE (expression)
23159 	      && dependent_type_p (BASELINK_OPTYPE (expression)))
23160 	    return true;
23161 	  expression = BASELINK_FUNCTIONS (expression);
23162 	}
23163 
23164       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
23165 	{
23166 	  if (any_dependent_template_arguments_p
23167 	      (TREE_OPERAND (expression, 1)))
23168 	    return true;
23169 	  expression = TREE_OPERAND (expression, 0);
23170 	  if (identifier_p (expression))
23171 	    return true;
23172 	}
23173 
23174       gcc_assert (TREE_CODE (expression) == OVERLOAD
23175 		  || TREE_CODE (expression) == FUNCTION_DECL);
23176 
23177       while (expression)
23178 	{
23179 	  if (type_dependent_expression_p (OVL_CURRENT (expression)))
23180 	    return true;
23181 	  expression = OVL_NEXT (expression);
23182 	}
23183       return false;
23184     }
23185 
23186   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
23187 
23188   return (dependent_type_p (TREE_TYPE (expression)));
23189 }
23190 
23191 /* walk_tree callback function for instantiation_dependent_expression_p,
23192    below.  Returns non-zero if a dependent subexpression is found.  */
23193 
23194 static tree
instantiation_dependent_r(tree * tp,int * walk_subtrees,void *)23195 instantiation_dependent_r (tree *tp, int *walk_subtrees,
23196 			   void * /*data*/)
23197 {
23198   if (TYPE_P (*tp))
23199     {
23200       /* We don't have to worry about decltype currently because decltype
23201 	 of an instantiation-dependent expr is a dependent type.  This
23202 	 might change depending on the resolution of DR 1172.  */
23203       *walk_subtrees = false;
23204       return NULL_TREE;
23205     }
23206   enum tree_code code = TREE_CODE (*tp);
23207   switch (code)
23208     {
23209       /* Don't treat an argument list as dependent just because it has no
23210 	 TREE_TYPE.  */
23211     case TREE_LIST:
23212     case TREE_VEC:
23213       return NULL_TREE;
23214 
23215     case TEMPLATE_PARM_INDEX:
23216       return *tp;
23217 
23218       /* Handle expressions with type operands.  */
23219     case SIZEOF_EXPR:
23220     case ALIGNOF_EXPR:
23221     case TYPEID_EXPR:
23222     case AT_ENCODE_EXPR:
23223       {
23224 	tree op = TREE_OPERAND (*tp, 0);
23225 	if (code == SIZEOF_EXPR && SIZEOF_EXPR_TYPE_P (*tp))
23226 	  op = TREE_TYPE (op);
23227 	if (TYPE_P (op))
23228 	  {
23229 	    if (dependent_type_p (op))
23230 	      return *tp;
23231 	    else
23232 	      {
23233 		*walk_subtrees = false;
23234 		return NULL_TREE;
23235 	      }
23236 	  }
23237 	break;
23238       }
23239 
23240     case COMPONENT_REF:
23241       if (identifier_p (TREE_OPERAND (*tp, 1)))
23242 	/* In a template, finish_class_member_access_expr creates a
23243 	   COMPONENT_REF with an IDENTIFIER_NODE for op1 even if it isn't
23244 	   type-dependent, so that we can check access control at
23245 	   instantiation time (PR 42277).  See also Core issue 1273.  */
23246 	return *tp;
23247       break;
23248 
23249     case SCOPE_REF:
23250       if (instantiation_dependent_scope_ref_p (*tp))
23251 	return *tp;
23252       else
23253 	break;
23254 
23255       /* Treat statement-expressions as dependent.  */
23256     case BIND_EXPR:
23257       return *tp;
23258 
23259       /* Treat requires-expressions as dependent. */
23260     case REQUIRES_EXPR:
23261       return *tp;
23262 
23263     case CALL_EXPR:
23264       /* Treat calls to function concepts as dependent. */
23265       if (function_concept_check_p (*tp))
23266         return *tp;
23267       break;
23268 
23269     case TEMPLATE_ID_EXPR:
23270       /* And variable concepts.  */
23271       if (variable_concept_p (TREE_OPERAND (*tp, 0)))
23272 	return *tp;
23273       break;
23274 
23275     default:
23276       break;
23277     }
23278 
23279   if (type_dependent_expression_p (*tp))
23280     return *tp;
23281   else
23282     return NULL_TREE;
23283 }
23284 
23285 /* Returns TRUE if the EXPRESSION is instantiation-dependent, in the
23286    sense defined by the ABI:
23287 
23288    "An expression is instantiation-dependent if it is type-dependent
23289    or value-dependent, or it has a subexpression that is type-dependent
23290    or value-dependent."
23291 
23292    Except don't actually check value-dependence for unevaluated expressions,
23293    because in sizeof(i) we don't care about the value of i.  Checking
23294    type-dependence will in turn check value-dependence of array bounds/template
23295    arguments as needed.  */
23296 
23297 bool
instantiation_dependent_uneval_expression_p(tree expression)23298 instantiation_dependent_uneval_expression_p (tree expression)
23299 {
23300   tree result;
23301 
23302   if (!processing_template_decl)
23303     return false;
23304 
23305   if (expression == error_mark_node)
23306     return false;
23307 
23308   result = cp_walk_tree_without_duplicates (&expression,
23309 					    instantiation_dependent_r, NULL);
23310   return result != NULL_TREE;
23311 }
23312 
23313 /* As above, but also check value-dependence of the expression as a whole.  */
23314 
23315 bool
instantiation_dependent_expression_p(tree expression)23316 instantiation_dependent_expression_p (tree expression)
23317 {
23318   return (instantiation_dependent_uneval_expression_p (expression)
23319 	  || value_dependent_expression_p (expression));
23320 }
23321 
23322 /* Like type_dependent_expression_p, but it also works while not processing
23323    a template definition, i.e. during substitution or mangling.  */
23324 
23325 bool
type_dependent_expression_p_push(tree expr)23326 type_dependent_expression_p_push (tree expr)
23327 {
23328   bool b;
23329   ++processing_template_decl;
23330   b = type_dependent_expression_p (expr);
23331   --processing_template_decl;
23332   return b;
23333 }
23334 
23335 /* Returns TRUE if ARGS contains a type-dependent expression.  */
23336 
23337 bool
any_type_dependent_arguments_p(const vec<tree,va_gc> * args)23338 any_type_dependent_arguments_p (const vec<tree, va_gc> *args)
23339 {
23340   unsigned int i;
23341   tree arg;
23342 
23343   FOR_EACH_VEC_SAFE_ELT (args, i, arg)
23344     {
23345       if (type_dependent_expression_p (arg))
23346 	return true;
23347     }
23348   return false;
23349 }
23350 
23351 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
23352    expressions) contains any type-dependent expressions.  */
23353 
23354 bool
any_type_dependent_elements_p(const_tree list)23355 any_type_dependent_elements_p (const_tree list)
23356 {
23357   for (; list; list = TREE_CHAIN (list))
23358     if (type_dependent_expression_p (TREE_VALUE (list)))
23359       return true;
23360 
23361   return false;
23362 }
23363 
23364 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
23365    expressions) contains any value-dependent expressions.  */
23366 
23367 bool
any_value_dependent_elements_p(const_tree list)23368 any_value_dependent_elements_p (const_tree list)
23369 {
23370   for (; list; list = TREE_CHAIN (list))
23371     if (value_dependent_expression_p (TREE_VALUE (list)))
23372       return true;
23373 
23374   return false;
23375 }
23376 
23377 /* Returns TRUE if the ARG (a template argument) is dependent.  */
23378 
23379 bool
dependent_template_arg_p(tree arg)23380 dependent_template_arg_p (tree arg)
23381 {
23382   if (!processing_template_decl)
23383     return false;
23384 
23385   /* Assume a template argument that was wrongly written by the user
23386      is dependent. This is consistent with what
23387      any_dependent_template_arguments_p [that calls this function]
23388      does.  */
23389   if (!arg || arg == error_mark_node)
23390     return true;
23391 
23392   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
23393     arg = ARGUMENT_PACK_SELECT_ARG (arg);
23394 
23395   if (TREE_CODE (arg) == TEMPLATE_DECL
23396       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
23397     return dependent_template_p (arg);
23398   else if (ARGUMENT_PACK_P (arg))
23399     {
23400       tree args = ARGUMENT_PACK_ARGS (arg);
23401       int i, len = TREE_VEC_LENGTH (args);
23402       for (i = 0; i < len; ++i)
23403         {
23404           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
23405             return true;
23406         }
23407 
23408       return false;
23409     }
23410   else if (TYPE_P (arg))
23411     return dependent_type_p (arg);
23412   else
23413     return (type_dependent_expression_p (arg)
23414 	    || value_dependent_expression_p (arg));
23415 }
23416 
23417 /* Returns true if ARGS (a collection of template arguments) contains
23418    any types that require structural equality testing.  */
23419 
23420 bool
any_template_arguments_need_structural_equality_p(tree args)23421 any_template_arguments_need_structural_equality_p (tree args)
23422 {
23423   int i;
23424   int j;
23425 
23426   if (!args)
23427     return false;
23428   if (args == error_mark_node)
23429     return true;
23430 
23431   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
23432     {
23433       tree level = TMPL_ARGS_LEVEL (args, i + 1);
23434       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
23435 	{
23436 	  tree arg = TREE_VEC_ELT (level, j);
23437 	  tree packed_args = NULL_TREE;
23438 	  int k, len = 1;
23439 
23440 	  if (ARGUMENT_PACK_P (arg))
23441 	    {
23442 	      /* Look inside the argument pack.  */
23443 	      packed_args = ARGUMENT_PACK_ARGS (arg);
23444 	      len = TREE_VEC_LENGTH (packed_args);
23445 	    }
23446 
23447 	  for (k = 0; k < len; ++k)
23448 	    {
23449 	      if (packed_args)
23450 		arg = TREE_VEC_ELT (packed_args, k);
23451 
23452 	      if (error_operand_p (arg))
23453 		return true;
23454 	      else if (TREE_CODE (arg) == TEMPLATE_DECL)
23455 		continue;
23456 	      else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
23457 		return true;
23458 	      else if (!TYPE_P (arg) && TREE_TYPE (arg)
23459 		       && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
23460 		return true;
23461 	    }
23462 	}
23463     }
23464 
23465   return false;
23466 }
23467 
23468 /* Returns true if ARGS (a collection of template arguments) contains
23469    any dependent arguments.  */
23470 
23471 bool
any_dependent_template_arguments_p(const_tree args)23472 any_dependent_template_arguments_p (const_tree args)
23473 {
23474   int i;
23475   int j;
23476 
23477   if (!args)
23478     return false;
23479   if (args == error_mark_node)
23480     return true;
23481 
23482   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
23483     {
23484       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
23485       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
23486 	if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
23487 	  return true;
23488     }
23489 
23490   return false;
23491 }
23492 
23493 /* Returns TRUE if the template TMPL is dependent.  */
23494 
23495 bool
dependent_template_p(tree tmpl)23496 dependent_template_p (tree tmpl)
23497 {
23498   if (TREE_CODE (tmpl) == OVERLOAD)
23499     {
23500       while (tmpl)
23501 	{
23502 	  if (dependent_template_p (OVL_CURRENT (tmpl)))
23503 	    return true;
23504 	  tmpl = OVL_NEXT (tmpl);
23505 	}
23506       return false;
23507     }
23508 
23509   /* Template template parameters are dependent.  */
23510   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
23511       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
23512     return true;
23513   /* So are names that have not been looked up.  */
23514   if (TREE_CODE (tmpl) == SCOPE_REF || identifier_p (tmpl))
23515     return true;
23516   /* So are member templates of dependent classes.  */
23517   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
23518     return dependent_type_p (DECL_CONTEXT (tmpl));
23519   return false;
23520 }
23521 
23522 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
23523 
23524 bool
dependent_template_id_p(tree tmpl,tree args)23525 dependent_template_id_p (tree tmpl, tree args)
23526 {
23527   return (dependent_template_p (tmpl)
23528 	  || any_dependent_template_arguments_p (args));
23529 }
23530 
23531 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
23532    are dependent.  */
23533 
23534 bool
dependent_omp_for_p(tree declv,tree initv,tree condv,tree incrv)23535 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
23536 {
23537   int i;
23538 
23539   if (!processing_template_decl)
23540     return false;
23541 
23542   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
23543     {
23544       tree decl = TREE_VEC_ELT (declv, i);
23545       tree init = TREE_VEC_ELT (initv, i);
23546       tree cond = TREE_VEC_ELT (condv, i);
23547       tree incr = TREE_VEC_ELT (incrv, i);
23548 
23549       if (type_dependent_expression_p (decl)
23550 	  || TREE_CODE (decl) == SCOPE_REF)
23551 	return true;
23552 
23553       if (init && type_dependent_expression_p (init))
23554 	return true;
23555 
23556       if (type_dependent_expression_p (cond))
23557 	return true;
23558 
23559       if (COMPARISON_CLASS_P (cond)
23560 	  && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
23561 	      || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
23562 	return true;
23563 
23564       if (TREE_CODE (incr) == MODOP_EXPR)
23565 	{
23566 	  if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
23567 	      || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
23568 	    return true;
23569 	}
23570       else if (type_dependent_expression_p (incr))
23571 	return true;
23572       else if (TREE_CODE (incr) == MODIFY_EXPR)
23573 	{
23574 	  if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
23575 	    return true;
23576 	  else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
23577 	    {
23578 	      tree t = TREE_OPERAND (incr, 1);
23579 	      if (type_dependent_expression_p (TREE_OPERAND (t, 0))
23580 		  || type_dependent_expression_p (TREE_OPERAND (t, 1)))
23581 		return true;
23582 	    }
23583 	}
23584     }
23585 
23586   return false;
23587 }
23588 
23589 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
23590    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
23591    no such TYPE can be found.  Note that this function peers inside
23592    uninstantiated templates and therefore should be used only in
23593    extremely limited situations.  ONLY_CURRENT_P restricts this
23594    peering to the currently open classes hierarchy (which is required
23595    when comparing types).  */
23596 
23597 tree
resolve_typename_type(tree type,bool only_current_p)23598 resolve_typename_type (tree type, bool only_current_p)
23599 {
23600   tree scope;
23601   tree name;
23602   tree decl;
23603   int quals;
23604   tree pushed_scope;
23605   tree result;
23606 
23607   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
23608 
23609   scope = TYPE_CONTEXT (type);
23610   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
23611      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
23612      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
23613      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
23614      identifier  of the TYPENAME_TYPE anymore.
23615      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
23616      TYPENAME_TYPE instead, we avoid messing up with a possible
23617      typedef variant case.  */
23618   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
23619 
23620   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
23621      it first before we can figure out what NAME refers to.  */
23622   if (TREE_CODE (scope) == TYPENAME_TYPE)
23623     {
23624       if (TYPENAME_IS_RESOLVING_P (scope))
23625 	/* Given a class template A with a dependent base with nested type C,
23626 	   typedef typename A::C::C C will land us here, as trying to resolve
23627 	   the initial A::C leads to the local C typedef, which leads back to
23628 	   A::C::C.  So we break the recursion now.  */
23629 	return type;
23630       else
23631 	scope = resolve_typename_type (scope, only_current_p);
23632     }
23633   /* If we don't know what SCOPE refers to, then we cannot resolve the
23634      TYPENAME_TYPE.  */
23635   if (!CLASS_TYPE_P (scope))
23636     return type;
23637   /* If this is a typedef, we don't want to look inside (c++/11987).  */
23638   if (typedef_variant_p (type))
23639     return type;
23640   /* If SCOPE isn't the template itself, it will not have a valid
23641      TYPE_FIELDS list.  */
23642   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
23643     /* scope is either the template itself or a compatible instantiation
23644        like X<T>, so look up the name in the original template.  */
23645     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
23646   /* We shouldn't have built a TYPENAME_TYPE with a non-dependent scope.  */
23647   gcc_checking_assert (uses_template_parms (scope));
23648   /* If scope has no fields, it can't be a current instantiation.  Check this
23649      before currently_open_class to avoid infinite recursion (71515).  */
23650   if (!TYPE_FIELDS (scope))
23651     return type;
23652   /* If the SCOPE is not the current instantiation, there's no reason
23653      to look inside it.  */
23654   if (only_current_p && !currently_open_class (scope))
23655     return type;
23656   /* Enter the SCOPE so that name lookup will be resolved as if we
23657      were in the class definition.  In particular, SCOPE will no
23658      longer be considered a dependent type.  */
23659   pushed_scope = push_scope (scope);
23660   /* Look up the declaration.  */
23661   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true,
23662 			tf_warning_or_error);
23663 
23664   result = NULL_TREE;
23665 
23666   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
23667      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
23668   if (!decl)
23669     /*nop*/;
23670   else if (identifier_p (TYPENAME_TYPE_FULLNAME (type))
23671 	   && TREE_CODE (decl) == TYPE_DECL)
23672     {
23673       result = TREE_TYPE (decl);
23674       if (result == error_mark_node)
23675 	result = NULL_TREE;
23676     }
23677   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
23678 	   && DECL_CLASS_TEMPLATE_P (decl))
23679     {
23680       tree tmpl;
23681       tree args;
23682       /* Obtain the template and the arguments.  */
23683       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
23684       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
23685       /* Instantiate the template.  */
23686       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
23687 				      /*entering_scope=*/0,
23688 				      tf_error | tf_user);
23689       if (result == error_mark_node)
23690 	result = NULL_TREE;
23691     }
23692 
23693   /* Leave the SCOPE.  */
23694   if (pushed_scope)
23695     pop_scope (pushed_scope);
23696 
23697   /* If we failed to resolve it, return the original typename.  */
23698   if (!result)
23699     return type;
23700 
23701   /* If lookup found a typename type, resolve that too.  */
23702   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
23703     {
23704       /* Ill-formed programs can cause infinite recursion here, so we
23705 	 must catch that.  */
23706       TYPENAME_IS_RESOLVING_P (result) = 1;
23707       result = resolve_typename_type (result, only_current_p);
23708       TYPENAME_IS_RESOLVING_P (result) = 0;
23709     }
23710 
23711   /* Qualify the resulting type.  */
23712   quals = cp_type_quals (type);
23713   if (quals)
23714     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
23715 
23716   return result;
23717 }
23718 
23719 /* EXPR is an expression which is not type-dependent.  Return a proxy
23720    for EXPR that can be used to compute the types of larger
23721    expressions containing EXPR.  */
23722 
23723 tree
build_non_dependent_expr(tree expr)23724 build_non_dependent_expr (tree expr)
23725 {
23726   tree inner_expr;
23727 
23728   /* When checking, try to get a constant value for all non-dependent
23729      expressions in order to expose bugs in *_dependent_expression_p
23730      and constexpr.  This checking can change code generation, temporarily
23731      disabled.  See PR70704.  */
23732   if (0 && flag_checking && cxx_dialect >= cxx11
23733       /* Don't do this during nsdmi parsing as it can lead to
23734 	 unexpected recursive instantiations.  */
23735       && !parsing_nsdmi ()
23736       /* Don't do this during concept expansion either and for
23737          the same reason.  */
23738       && !expanding_concept ())
23739     fold_non_dependent_expr (expr);
23740 
23741   /* Preserve OVERLOADs; the functions must be available to resolve
23742      types.  */
23743   inner_expr = expr;
23744   if (TREE_CODE (inner_expr) == STMT_EXPR)
23745     inner_expr = stmt_expr_value_expr (inner_expr);
23746   if (TREE_CODE (inner_expr) == ADDR_EXPR)
23747     inner_expr = TREE_OPERAND (inner_expr, 0);
23748   if (TREE_CODE (inner_expr) == COMPONENT_REF)
23749     inner_expr = TREE_OPERAND (inner_expr, 1);
23750   if (is_overloaded_fn (inner_expr)
23751       || TREE_CODE (inner_expr) == OFFSET_REF)
23752     return expr;
23753   /* There is no need to return a proxy for a variable.  */
23754   if (VAR_P (expr))
23755     return expr;
23756   /* Preserve string constants; conversions from string constants to
23757      "char *" are allowed, even though normally a "const char *"
23758      cannot be used to initialize a "char *".  */
23759   if (TREE_CODE (expr) == STRING_CST)
23760     return expr;
23761   /* Preserve void and arithmetic constants, as an optimization -- there is no
23762      reason to create a new node.  */
23763   if (TREE_CODE (expr) == VOID_CST
23764       || TREE_CODE (expr) == INTEGER_CST
23765       || TREE_CODE (expr) == REAL_CST)
23766     return expr;
23767   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
23768      There is at least one place where we want to know that a
23769      particular expression is a throw-expression: when checking a ?:
23770      expression, there are special rules if the second or third
23771      argument is a throw-expression.  */
23772   if (TREE_CODE (expr) == THROW_EXPR)
23773     return expr;
23774 
23775   /* Don't wrap an initializer list, we need to be able to look inside.  */
23776   if (BRACE_ENCLOSED_INITIALIZER_P (expr))
23777     return expr;
23778 
23779   /* Don't wrap a dummy object, we need to be able to test for it.  */
23780   if (is_dummy_object (expr))
23781     return expr;
23782 
23783   if (TREE_CODE (expr) == COND_EXPR)
23784     return build3 (COND_EXPR,
23785 		   TREE_TYPE (expr),
23786 		   TREE_OPERAND (expr, 0),
23787 		   (TREE_OPERAND (expr, 1)
23788 		    ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
23789 		    : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
23790 		   build_non_dependent_expr (TREE_OPERAND (expr, 2)));
23791   if (TREE_CODE (expr) == COMPOUND_EXPR
23792       && !COMPOUND_EXPR_OVERLOADED (expr))
23793     return build2 (COMPOUND_EXPR,
23794 		   TREE_TYPE (expr),
23795 		   TREE_OPERAND (expr, 0),
23796 		   build_non_dependent_expr (TREE_OPERAND (expr, 1)));
23797 
23798   /* If the type is unknown, it can't really be non-dependent */
23799   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
23800 
23801   /* Otherwise, build a NON_DEPENDENT_EXPR.  */
23802   return build1 (NON_DEPENDENT_EXPR, TREE_TYPE (expr), expr);
23803 }
23804 
23805 /* ARGS is a vector of expressions as arguments to a function call.
23806    Replace the arguments with equivalent non-dependent expressions.
23807    This modifies ARGS in place.  */
23808 
23809 void
make_args_non_dependent(vec<tree,va_gc> * args)23810 make_args_non_dependent (vec<tree, va_gc> *args)
23811 {
23812   unsigned int ix;
23813   tree arg;
23814 
23815   FOR_EACH_VEC_SAFE_ELT (args, ix, arg)
23816     {
23817       tree newarg = build_non_dependent_expr (arg);
23818       if (newarg != arg)
23819 	(*args)[ix] = newarg;
23820     }
23821 }
23822 
23823 /* Returns a type which represents 'auto' or 'decltype(auto)'.  We use a
23824    TEMPLATE_TYPE_PARM with a level one deeper than the actual template
23825    parms.  If set_canonical is true, we set TYPE_CANONICAL on it.  */
23826 
23827 static tree
make_auto_1(tree name,bool set_canonical)23828 make_auto_1 (tree name, bool set_canonical)
23829 {
23830   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
23831   TYPE_NAME (au) = build_decl (input_location,
23832 			       TYPE_DECL, name, au);
23833   TYPE_STUB_DECL (au) = TYPE_NAME (au);
23834   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
23835     (0, processing_template_decl + 1, processing_template_decl + 1,
23836      TYPE_NAME (au), NULL_TREE);
23837   if (set_canonical)
23838     TYPE_CANONICAL (au) = canonical_type_parameter (au);
23839   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
23840   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
23841 
23842   return au;
23843 }
23844 
23845 tree
make_decltype_auto(void)23846 make_decltype_auto (void)
23847 {
23848   return make_auto_1 (get_identifier ("decltype(auto)"), true);
23849 }
23850 
23851 tree
make_auto(void)23852 make_auto (void)
23853 {
23854   return make_auto_1 (get_identifier ("auto"), true);
23855 }
23856 
23857 /* Make a "constrained auto" type-specifier. This is an
23858    auto type with constraints that must be associated after
23859    deduction.  The constraint is formed from the given
23860    CONC and its optional sequence of arguments, which are
23861    non-null if written as partial-concept-id.  */
23862 
23863 tree
make_constrained_auto(tree con,tree args)23864 make_constrained_auto (tree con, tree args)
23865 {
23866   tree type = make_auto_1 (get_identifier ("auto"), false);
23867 
23868   /* Build the constraint. */
23869   tree tmpl = DECL_TI_TEMPLATE (con);
23870   tree expr;
23871   if (VAR_P (con))
23872     expr = build_concept_check (tmpl, type, args);
23873   else
23874     expr = build_concept_check (build_overload (tmpl, NULL_TREE), type, args);
23875 
23876   tree constr = normalize_expression (expr);
23877   PLACEHOLDER_TYPE_CONSTRAINTS (type) = constr;
23878 
23879   /* Our canonical type depends on the constraint.  */
23880   TYPE_CANONICAL (type) = canonical_type_parameter (type);
23881 
23882   /* Attach the constraint to the type declaration. */
23883   tree decl = TYPE_NAME (type);
23884   return decl;
23885 }
23886 
23887 /* Given type ARG, return std::initializer_list<ARG>.  */
23888 
23889 static tree
listify(tree arg)23890 listify (tree arg)
23891 {
23892   tree std_init_list = namespace_binding
23893     (get_identifier ("initializer_list"), std_node);
23894   tree argvec;
23895   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
23896     {
23897       error ("deducing from brace-enclosed initializer list requires "
23898 	     "#include <initializer_list>");
23899       return error_mark_node;
23900     }
23901   argvec = make_tree_vec (1);
23902   TREE_VEC_ELT (argvec, 0) = arg;
23903   return lookup_template_class (std_init_list, argvec, NULL_TREE,
23904 				NULL_TREE, 0, tf_warning_or_error);
23905 }
23906 
23907 /* Replace auto in TYPE with std::initializer_list<auto>.  */
23908 
23909 static tree
listify_autos(tree type,tree auto_node)23910 listify_autos (tree type, tree auto_node)
23911 {
23912   tree init_auto = listify (auto_node);
23913   tree argvec = make_tree_vec (1);
23914   TREE_VEC_ELT (argvec, 0) = init_auto;
23915   if (processing_template_decl)
23916     argvec = add_to_template_args (current_template_args (), argvec);
23917   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
23918 }
23919 
23920 /* Hash traits for hashing possibly constrained 'auto'
23921    TEMPLATE_TYPE_PARMs for use by do_auto_deduction.  */
23922 
23923 struct auto_hash : default_hash_traits<tree>
23924 {
23925   static inline hashval_t hash (tree);
23926   static inline bool equal (tree, tree);
23927 };
23928 
23929 /* Hash the 'auto' T.  */
23930 
23931 inline hashval_t
hash(tree t)23932 auto_hash::hash (tree t)
23933 {
23934   if (tree c = PLACEHOLDER_TYPE_CONSTRAINTS (t))
23935     /* Matching constrained-type-specifiers denote the same template
23936        parameter, so hash the constraint.  */
23937     return hash_placeholder_constraint (c);
23938   else
23939     /* But unconstrained autos are all separate, so just hash the pointer.  */
23940     return iterative_hash_object (t, 0);
23941 }
23942 
23943 /* Compare two 'auto's.  */
23944 
23945 inline bool
equal(tree t1,tree t2)23946 auto_hash::equal (tree t1, tree t2)
23947 {
23948   if (t1 == t2)
23949     return true;
23950 
23951   tree c1 = PLACEHOLDER_TYPE_CONSTRAINTS (t1);
23952   tree c2 = PLACEHOLDER_TYPE_CONSTRAINTS (t2);
23953 
23954   /* Two unconstrained autos are distinct.  */
23955   if (!c1 || !c2)
23956     return false;
23957 
23958   return equivalent_placeholder_constraints (c1, c2);
23959 }
23960 
23961 /* for_each_template_parm callback for extract_autos: if t is a (possibly
23962    constrained) auto, add it to the vector.  */
23963 
23964 static int
extract_autos_r(tree t,void * data)23965 extract_autos_r (tree t, void *data)
23966 {
23967   hash_table<auto_hash> &hash = *(hash_table<auto_hash>*)data;
23968   if (is_auto_or_concept (t))
23969     {
23970       /* All the autos were built with index 0; fix that up now.  */
23971       tree *p = hash.find_slot (t, INSERT);
23972       unsigned idx;
23973       if (*p)
23974 	/* If this is a repeated constrained-type-specifier, use the index we
23975 	   chose before.  */
23976 	idx = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (*p));
23977       else
23978 	{
23979 	  /* Otherwise this is new, so use the current count.  */
23980 	  *p = t;
23981 	  idx = hash.elements () - 1;
23982 	}
23983       TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (t)) = idx;
23984     }
23985 
23986   /* Always keep walking.  */
23987   return 0;
23988 }
23989 
23990 /* Return a TREE_VEC of the 'auto's used in type under the Concepts TS, which
23991    says they can appear anywhere in the type.  */
23992 
23993 static tree
extract_autos(tree type)23994 extract_autos (tree type)
23995 {
23996   hash_set<tree> visited;
23997   hash_table<auto_hash> hash (2);
23998 
23999   for_each_template_parm (type, extract_autos_r, &hash, &visited, true);
24000 
24001   tree tree_vec = make_tree_vec (hash.elements());
24002   for (hash_table<auto_hash>::iterator iter = hash.begin();
24003        iter != hash.end(); ++iter)
24004     {
24005       tree elt = *iter;
24006       unsigned i = TEMPLATE_PARM_IDX (TEMPLATE_TYPE_PARM_INDEX (elt));
24007       TREE_VEC_ELT (tree_vec, i)
24008 	= build_tree_list (NULL_TREE, TYPE_NAME (elt));
24009     }
24010 
24011   return tree_vec;
24012 }
24013 
24014 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
24015    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
24016 
24017 tree
do_auto_deduction(tree type,tree init,tree auto_node)24018 do_auto_deduction (tree type, tree init, tree auto_node)
24019 {
24020   return do_auto_deduction (type, init, auto_node,
24021                             tf_warning_or_error,
24022                             adc_unspecified);
24023 }
24024 
24025 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
24026    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.
24027    The CONTEXT determines the context in which auto deduction is performed
24028    and is used to control error diagnostics.
24029 
24030    For partial-concept-ids, extra args may be appended to the list of deduced
24031    template arguments prior to determining constraint satisfaction.  */
24032 
24033 tree
do_auto_deduction(tree type,tree init,tree auto_node,tsubst_flags_t complain,auto_deduction_context context)24034 do_auto_deduction (tree type, tree init, tree auto_node,
24035                    tsubst_flags_t complain, auto_deduction_context context)
24036 {
24037   tree targs;
24038 
24039   if (init == error_mark_node)
24040     return error_mark_node;
24041 
24042   if (type_dependent_expression_p (init))
24043     /* Defining a subset of type-dependent expressions that we can deduce
24044        from ahead of time isn't worth the trouble.  */
24045     return type;
24046 
24047   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
24048      with either a new invented type template parameter U or, if the
24049      initializer is a braced-init-list (8.5.4), with
24050      std::initializer_list<U>.  */
24051   if (BRACE_ENCLOSED_INITIALIZER_P (init))
24052     {
24053       if (!DIRECT_LIST_INIT_P (init))
24054 	type = listify_autos (type, auto_node);
24055       else if (CONSTRUCTOR_NELTS (init) == 1)
24056 	init = CONSTRUCTOR_ELT (init, 0)->value;
24057       else
24058 	{
24059           if (complain & tf_warning_or_error)
24060             {
24061 	      if (permerror (input_location, "direct-list-initialization of "
24062 			     "%<auto%> requires exactly one element"))
24063 	        inform (input_location,
24064 		        "for deduction to %<std::initializer_list%>, use copy-"
24065 		        "list-initialization (i.e. add %<=%> before the %<{%>)");
24066             }
24067 	  type = listify_autos (type, auto_node);
24068 	}
24069     }
24070 
24071   if (type == error_mark_node)
24072     return error_mark_node;
24073 
24074   init = resolve_nondeduced_context (init, complain);
24075 
24076   if (AUTO_IS_DECLTYPE (auto_node))
24077     {
24078       bool id = (DECL_P (init)
24079 		 || ((TREE_CODE (init) == COMPONENT_REF
24080 		      || TREE_CODE (init) == SCOPE_REF)
24081 		     && !REF_PARENTHESIZED_P (init)));
24082       targs = make_tree_vec (1);
24083       TREE_VEC_ELT (targs, 0)
24084 	= finish_decltype_type (init, id, tf_warning_or_error);
24085       if (type != auto_node)
24086 	{
24087           if (complain & tf_error)
24088 	    error ("%qT as type rather than plain %<decltype(auto)%>", type);
24089 	  return error_mark_node;
24090 	}
24091     }
24092   else
24093     {
24094       tree parms = build_tree_list (NULL_TREE, type);
24095       tree tparms;
24096 
24097       if (flag_concepts)
24098 	tparms = extract_autos (type);
24099       else
24100 	{
24101 	  tparms = make_tree_vec (1);
24102 	  TREE_VEC_ELT (tparms, 0)
24103 	    = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
24104 	}
24105 
24106       targs = make_tree_vec (TREE_VEC_LENGTH (tparms));
24107       int val = type_unification_real (tparms, targs, parms, &init, 1, 0,
24108 				       DEDUCE_CALL, LOOKUP_NORMAL,
24109 				       NULL, /*explain_p=*/false);
24110       if (val > 0)
24111 	{
24112 	  if (processing_template_decl)
24113 	    /* Try again at instantiation time.  */
24114 	    return type;
24115 	  if (type && type != error_mark_node
24116 	      && (complain & tf_error))
24117 	    /* If type is error_mark_node a diagnostic must have been
24118 	       emitted by now.  Also, having a mention to '<type error>'
24119 	       in the diagnostic is not really useful to the user.  */
24120 	    {
24121 	      if (cfun && auto_node == current_function_auto_return_pattern
24122 		  && LAMBDA_FUNCTION_P (current_function_decl))
24123 		error ("unable to deduce lambda return type from %qE", init);
24124 	      else
24125 		error ("unable to deduce %qT from %qE", type, init);
24126 	      type_unification_real (tparms, targs, parms, &init, 1, 0,
24127 				     DEDUCE_CALL, LOOKUP_NORMAL,
24128 				     NULL, /*explain_p=*/true);
24129 	    }
24130 	  return error_mark_node;
24131 	}
24132     }
24133 
24134   /* Check any placeholder constraints against the deduced type. */
24135   if (flag_concepts && !processing_template_decl)
24136     if (tree constr = PLACEHOLDER_TYPE_CONSTRAINTS (auto_node))
24137       {
24138         /* Use the deduced type to check the associated constraints. If we
24139            have a partial-concept-id, rebuild the argument list so that
24140            we check using the extra arguments. */
24141         gcc_assert (TREE_CODE (constr) == CHECK_CONSTR);
24142         tree cargs = CHECK_CONSTR_ARGS (constr);
24143         if (TREE_VEC_LENGTH (cargs) > 1)
24144           {
24145             cargs = copy_node (cargs);
24146             TREE_VEC_ELT (cargs, 0) = TREE_VEC_ELT (targs, 0);
24147           }
24148         else
24149           cargs = targs;
24150         if (!constraints_satisfied_p (constr, cargs))
24151           {
24152             if (complain & tf_warning_or_error)
24153               {
24154                 switch (context)
24155                   {
24156                   case adc_unspecified:
24157                     error("placeholder constraints not satisfied");
24158                     break;
24159                   case adc_variable_type:
24160                     error ("deduced initializer does not satisfy "
24161                            "placeholder constraints");
24162                     break;
24163                   case adc_return_type:
24164                     error ("deduced return type does not satisfy "
24165                            "placeholder constraints");
24166                     break;
24167                   case adc_requirement:
24168                     error ("deduced expression type does not saatisy "
24169                            "placeholder constraints");
24170                     break;
24171                   }
24172                 diagnose_constraints (input_location, constr, targs);
24173               }
24174             return error_mark_node;
24175           }
24176       }
24177 
24178   if (processing_template_decl)
24179     targs = add_to_template_args (current_template_args (), targs);
24180   return tsubst (type, targs, complain, NULL_TREE);
24181 }
24182 
24183 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
24184    result.  */
24185 
24186 tree
splice_late_return_type(tree type,tree late_return_type)24187 splice_late_return_type (tree type, tree late_return_type)
24188 {
24189   if (is_auto (type))
24190     {
24191       if (late_return_type)
24192 	return late_return_type;
24193 
24194       tree idx = get_template_parm_index (type);
24195       if (TEMPLATE_PARM_LEVEL (idx) <= processing_template_decl)
24196 	/* In an abbreviated function template we didn't know we were dealing
24197 	   with a function template when we saw the auto return type, so update
24198 	   it to have the correct level.  */
24199 	return make_auto_1 (TYPE_IDENTIFIER (type), true);
24200     }
24201   return type;
24202 }
24203 
24204 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto' or
24205    'decltype(auto)'.  */
24206 
24207 bool
is_auto(const_tree type)24208 is_auto (const_tree type)
24209 {
24210   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
24211       && (TYPE_IDENTIFIER (type) == get_identifier ("auto")
24212 	  || TYPE_IDENTIFIER (type) == get_identifier ("decltype(auto)")))
24213     return true;
24214   else
24215     return false;
24216 }
24217 
24218 /* for_each_template_parm callback for type_uses_auto.  */
24219 
24220 int
is_auto_r(tree tp,void *)24221 is_auto_r (tree tp, void */*data*/)
24222 {
24223   return is_auto_or_concept (tp);
24224 }
24225 
24226 /* Returns the TEMPLATE_TYPE_PARM in TYPE representing `auto' iff TYPE contains
24227    a use of `auto'.  Returns NULL_TREE otherwise.  */
24228 
24229 tree
type_uses_auto(tree type)24230 type_uses_auto (tree type)
24231 {
24232   if (type == NULL_TREE)
24233     return NULL_TREE;
24234   else if (flag_concepts)
24235     {
24236       /* The Concepts TS allows multiple autos in one type-specifier; just
24237 	 return the first one we find, do_auto_deduction will collect all of
24238 	 them.  */
24239       if (uses_template_parms (type))
24240 	return for_each_template_parm (type, is_auto_r, /*data*/NULL,
24241 				       /*visited*/NULL, /*nondeduced*/true);
24242       else
24243 	return NULL_TREE;
24244     }
24245   else
24246     return find_type_usage (type, is_auto);
24247 }
24248 
24249 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto',
24250    'decltype(auto)' or a concept.  */
24251 
24252 bool
is_auto_or_concept(const_tree type)24253 is_auto_or_concept (const_tree type)
24254 {
24255   return is_auto (type); // or concept
24256 }
24257 
24258 /* Returns the TEMPLATE_TYPE_PARM in TYPE representing a generic type (`auto' or
24259    a concept identifier) iff TYPE contains a use of a generic type.  Returns
24260    NULL_TREE otherwise.  */
24261 
24262 tree
type_uses_auto_or_concept(tree type)24263 type_uses_auto_or_concept (tree type)
24264 {
24265   return find_type_usage (type, is_auto_or_concept);
24266 }
24267 
24268 
24269 /* For a given template T, return the vector of typedefs referenced
24270    in T for which access check is needed at T instantiation time.
24271    T is either  a FUNCTION_DECL or a RECORD_TYPE.
24272    Those typedefs were added to T by the function
24273    append_type_to_template_for_access_check.  */
24274 
24275 vec<qualified_typedef_usage_t, va_gc> *
get_types_needing_access_check(tree t)24276 get_types_needing_access_check (tree t)
24277 {
24278   tree ti;
24279   vec<qualified_typedef_usage_t, va_gc> *result = NULL;
24280 
24281   if (!t || t == error_mark_node)
24282     return NULL;
24283 
24284   if (!(ti = get_template_info (t)))
24285     return NULL;
24286 
24287   if (CLASS_TYPE_P (t)
24288       || TREE_CODE (t) == FUNCTION_DECL)
24289     {
24290       if (!TI_TEMPLATE (ti))
24291 	return NULL;
24292 
24293       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
24294     }
24295 
24296   return result;
24297 }
24298 
24299 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
24300    tied to T. That list of typedefs will be access checked at
24301    T instantiation time.
24302    T is either a FUNCTION_DECL or a RECORD_TYPE.
24303    TYPE_DECL is a TYPE_DECL node representing a typedef.
24304    SCOPE is the scope through which TYPE_DECL is accessed.
24305    LOCATION is the location of the usage point of TYPE_DECL.
24306 
24307    This function is a subroutine of
24308    append_type_to_template_for_access_check.  */
24309 
24310 static void
append_type_to_template_for_access_check_1(tree t,tree type_decl,tree scope,location_t location)24311 append_type_to_template_for_access_check_1 (tree t,
24312 					    tree type_decl,
24313 					    tree scope,
24314 					    location_t location)
24315 {
24316   qualified_typedef_usage_t typedef_usage;
24317   tree ti;
24318 
24319   if (!t || t == error_mark_node)
24320     return;
24321 
24322   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
24323 	       || CLASS_TYPE_P (t))
24324 	      && type_decl
24325 	      && TREE_CODE (type_decl) == TYPE_DECL
24326 	      && scope);
24327 
24328   if (!(ti = get_template_info (t)))
24329     return;
24330 
24331   gcc_assert (TI_TEMPLATE (ti));
24332 
24333   typedef_usage.typedef_decl = type_decl;
24334   typedef_usage.context = scope;
24335   typedef_usage.locus = location;
24336 
24337   vec_safe_push (TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti), typedef_usage);
24338 }
24339 
24340 /* Append TYPE_DECL to the template TEMPL.
24341    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
24342    At TEMPL instanciation time, TYPE_DECL will be checked to see
24343    if it can be accessed through SCOPE.
24344    LOCATION is the location of the usage point of TYPE_DECL.
24345 
24346    e.g. consider the following code snippet:
24347 
24348      class C
24349      {
24350        typedef int myint;
24351      };
24352 
24353      template<class U> struct S
24354      {
24355        C::myint mi; // <-- usage point of the typedef C::myint
24356      };
24357 
24358      S<char> s;
24359 
24360    At S<char> instantiation time, we need to check the access of C::myint
24361    In other words, we need to check the access of the myint typedef through
24362    the C scope. For that purpose, this function will add the myint typedef
24363    and the scope C through which its being accessed to a list of typedefs
24364    tied to the template S. That list will be walked at template instantiation
24365    time and access check performed on each typedefs it contains.
24366    Note that this particular code snippet should yield an error because
24367    myint is private to C.  */
24368 
24369 void
append_type_to_template_for_access_check(tree templ,tree type_decl,tree scope,location_t location)24370 append_type_to_template_for_access_check (tree templ,
24371                                           tree type_decl,
24372 					  tree scope,
24373 					  location_t location)
24374 {
24375   qualified_typedef_usage_t *iter;
24376   unsigned i;
24377 
24378   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
24379 
24380   /* Make sure we don't append the type to the template twice.  */
24381   FOR_EACH_VEC_SAFE_ELT (get_types_needing_access_check (templ), i, iter)
24382     if (iter->typedef_decl == type_decl && scope == iter->context)
24383       return;
24384 
24385   append_type_to_template_for_access_check_1 (templ, type_decl,
24386 					      scope, location);
24387 }
24388 
24389 /* Convert the generic type parameters in PARM that match the types given in the
24390    range [START_IDX, END_IDX) from the current_template_parms into generic type
24391    packs.  */
24392 
24393 tree
convert_generic_types_to_packs(tree parm,int start_idx,int end_idx)24394 convert_generic_types_to_packs (tree parm, int start_idx, int end_idx)
24395 {
24396   tree current = current_template_parms;
24397   int depth = TMPL_PARMS_DEPTH (current);
24398   current = INNERMOST_TEMPLATE_PARMS (current);
24399   tree replacement = make_tree_vec (TREE_VEC_LENGTH (current));
24400 
24401   for (int i = 0; i < start_idx; ++i)
24402     TREE_VEC_ELT (replacement, i)
24403       = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
24404 
24405   for (int i = start_idx; i < end_idx; ++i)
24406     {
24407       /* Create a distinct parameter pack type from the current parm and add it
24408 	 to the replacement args to tsubst below into the generic function
24409 	 parameter.  */
24410 
24411       tree o = TREE_TYPE (TREE_VALUE
24412 			  (TREE_VEC_ELT (current, i)));
24413       tree t = copy_type (o);
24414       TEMPLATE_TYPE_PARM_INDEX (t)
24415 	= reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (o),
24416 				      o, 0, 0, tf_none);
24417       TREE_TYPE (TEMPLATE_TYPE_DECL (t)) = t;
24418       TYPE_STUB_DECL (t) = TYPE_NAME (t) = TEMPLATE_TYPE_DECL (t);
24419       TYPE_MAIN_VARIANT (t) = t;
24420       TEMPLATE_TYPE_PARAMETER_PACK (t) = true;
24421       TYPE_CANONICAL (t) = canonical_type_parameter (t);
24422       TREE_VEC_ELT (replacement, i) = t;
24423       TREE_VALUE (TREE_VEC_ELT (current, i)) = TREE_CHAIN (t);
24424     }
24425 
24426   for (int i = end_idx, e = TREE_VEC_LENGTH (current); i < e; ++i)
24427     TREE_VEC_ELT (replacement, i)
24428       = TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (current, i)));
24429 
24430   /* If there are more levels then build up the replacement with the outer
24431      template parms.  */
24432   if (depth > 1)
24433     replacement = add_to_template_args (template_parms_to_args
24434 					(TREE_CHAIN (current_template_parms)),
24435 					replacement);
24436 
24437   return tsubst (parm, replacement, tf_none, NULL_TREE);
24438 }
24439 
24440 /* Entries in the decl_constraint hash table. */
24441 struct GTY((for_user)) constr_entry
24442 {
24443   tree decl;
24444   tree ci;
24445 };
24446 
24447 /* Hashing function and equality for constraint entries. */
24448 struct constr_hasher : ggc_ptr_hash<constr_entry>
24449 {
hashconstr_hasher24450   static hashval_t hash (constr_entry *e)
24451   {
24452     return (hashval_t)DECL_UID (e->decl);
24453   }
24454 
equalconstr_hasher24455   static bool equal (constr_entry *e1, constr_entry *e2)
24456   {
24457     return e1->decl == e2->decl;
24458   }
24459 };
24460 
24461 /* A mapping from declarations to constraint information. Note that
24462    both templates and their underlying declarations are mapped to the
24463    same constraint information.
24464 
24465    FIXME: This is defined in pt.c because garbage collection
24466    code is not being generated for constraint.cc. */
24467 
24468 static GTY (()) hash_table<constr_hasher> *decl_constraints;
24469 
24470 /* Returns the template constraints of declaration T. If T is not
24471    constrained, return NULL_TREE. Note that T must be non-null. */
24472 
24473 tree
get_constraints(tree t)24474 get_constraints (tree t)
24475 {
24476   if (!flag_concepts)
24477     return NULL_TREE;
24478 
24479   gcc_assert (DECL_P (t));
24480   if (TREE_CODE (t) == TEMPLATE_DECL)
24481     t = DECL_TEMPLATE_RESULT (t);
24482   constr_entry elt = { t, NULL_TREE };
24483   constr_entry* found = decl_constraints->find (&elt);
24484   if (found)
24485     return found->ci;
24486   else
24487     return NULL_TREE;
24488 }
24489 
24490 /* Associate the given constraint information CI with the declaration
24491    T. If T is a template, then the constraints are associated with
24492    its underlying declaration. Don't build associations if CI is
24493    NULL_TREE.  */
24494 
24495 void
set_constraints(tree t,tree ci)24496 set_constraints (tree t, tree ci)
24497 {
24498   if (!ci)
24499     return;
24500   gcc_assert (t && flag_concepts);
24501   if (TREE_CODE (t) == TEMPLATE_DECL)
24502     t = DECL_TEMPLATE_RESULT (t);
24503   gcc_assert (!get_constraints (t));
24504   constr_entry elt = {t, ci};
24505   constr_entry** slot = decl_constraints->find_slot (&elt, INSERT);
24506   constr_entry* entry = ggc_alloc<constr_entry> ();
24507   *entry = elt;
24508   *slot = entry;
24509 }
24510 
24511 /* Remove the associated constraints of the declaration T.  */
24512 
24513 void
remove_constraints(tree t)24514 remove_constraints (tree t)
24515 {
24516   gcc_assert (DECL_P (t));
24517   if (TREE_CODE (t) == TEMPLATE_DECL)
24518     t = DECL_TEMPLATE_RESULT (t);
24519 
24520   constr_entry elt = {t, NULL_TREE};
24521   constr_entry** slot = decl_constraints->find_slot (&elt, NO_INSERT);
24522   if (slot)
24523     decl_constraints->clear_slot (slot);
24524 }
24525 
24526 /* Memoized satisfaction results for declarations. This
24527    maps the pair (constraint_info, arguments) to the result computed
24528    by constraints_satisfied_p.  */
24529 
24530 struct GTY((for_user)) constraint_sat_entry
24531 {
24532   tree ci;
24533   tree args;
24534   tree result;
24535 };
24536 
24537 /* Hashing function and equality for constraint entries. */
24538 
24539 struct constraint_sat_hasher : ggc_ptr_hash<constraint_sat_entry>
24540 {
hashconstraint_sat_hasher24541   static hashval_t hash (constraint_sat_entry *e)
24542   {
24543     hashval_t val = iterative_hash_object(e->ci, 0);
24544     return iterative_hash_template_arg (e->args, val);
24545   }
24546 
equalconstraint_sat_hasher24547   static bool equal (constraint_sat_entry *e1, constraint_sat_entry *e2)
24548   {
24549     return e1->ci == e2->ci && comp_template_args (e1->args, e2->args);
24550   }
24551 };
24552 
24553 /* Memoized satisfaction results for concept checks. */
24554 
24555 struct GTY((for_user)) concept_spec_entry
24556 {
24557   tree tmpl;
24558   tree args;
24559   tree result;
24560 };
24561 
24562 /* Hashing function and equality for constraint entries.  */
24563 
24564 struct concept_spec_hasher : ggc_ptr_hash<concept_spec_entry>
24565 {
hashconcept_spec_hasher24566   static hashval_t hash (concept_spec_entry *e)
24567   {
24568     return hash_tmpl_and_args (e->tmpl, e->args);
24569   }
24570 
equalconcept_spec_hasher24571   static bool equal (concept_spec_entry *e1, concept_spec_entry *e2)
24572   {
24573     ++comparing_specializations;
24574     bool eq = e1->tmpl == e2->tmpl && comp_template_args (e1->args, e2->args);
24575     --comparing_specializations;
24576     return eq;
24577   }
24578 };
24579 
24580 static GTY (()) hash_table<constraint_sat_hasher> *constraint_memos;
24581 static GTY (()) hash_table<concept_spec_hasher> *concept_memos;
24582 
24583 /* Search for a memoized satisfaction result. Returns one of the
24584    truth value nodes if previously memoized, or NULL_TREE otherwise.   */
24585 
24586 tree
lookup_constraint_satisfaction(tree ci,tree args)24587 lookup_constraint_satisfaction (tree ci, tree args)
24588 {
24589   constraint_sat_entry elt = { ci, args, NULL_TREE };
24590   constraint_sat_entry* found = constraint_memos->find (&elt);
24591   if (found)
24592     return found->result;
24593   else
24594     return NULL_TREE;
24595 }
24596 
24597 /* Memoize the result of a satisfication test. Returns the saved result.  */
24598 
24599 tree
memoize_constraint_satisfaction(tree ci,tree args,tree result)24600 memoize_constraint_satisfaction (tree ci, tree args, tree result)
24601 {
24602   constraint_sat_entry elt = {ci, args, result};
24603   constraint_sat_entry** slot = constraint_memos->find_slot (&elt, INSERT);
24604   constraint_sat_entry* entry = ggc_alloc<constraint_sat_entry> ();
24605   *entry = elt;
24606   *slot = entry;
24607   return result;
24608 }
24609 
24610 /* Search for a memoized satisfaction result for a concept. */
24611 
24612 tree
lookup_concept_satisfaction(tree tmpl,tree args)24613 lookup_concept_satisfaction (tree tmpl, tree args)
24614 {
24615   concept_spec_entry elt = { tmpl, args, NULL_TREE };
24616   concept_spec_entry* found = concept_memos->find (&elt);
24617   if (found)
24618     return found->result;
24619   else
24620     return NULL_TREE;
24621 }
24622 
24623 /* Memoize the result of a concept check. Returns the saved result.  */
24624 
24625 tree
memoize_concept_satisfaction(tree tmpl,tree args,tree result)24626 memoize_concept_satisfaction (tree tmpl, tree args, tree result)
24627 {
24628   concept_spec_entry elt = {tmpl, args, result};
24629   concept_spec_entry** slot = concept_memos->find_slot (&elt, INSERT);
24630   concept_spec_entry* entry = ggc_alloc<concept_spec_entry> ();
24631   *entry = elt;
24632   *slot = entry;
24633   return result;
24634 }
24635 
24636 static GTY (()) hash_table<concept_spec_hasher> *concept_expansions;
24637 
24638 /* Returns a prior concept specialization. This returns the substituted
24639    and normalized constraints defined by the concept.  */
24640 
24641 tree
get_concept_expansion(tree tmpl,tree args)24642 get_concept_expansion (tree tmpl, tree args)
24643 {
24644   concept_spec_entry elt = { tmpl, args, NULL_TREE };
24645   concept_spec_entry* found = concept_expansions->find (&elt);
24646   if (found)
24647     return found->result;
24648   else
24649     return NULL_TREE;
24650 }
24651 
24652 /* Save a concept expansion for later.  */
24653 
24654 tree
save_concept_expansion(tree tmpl,tree args,tree def)24655 save_concept_expansion (tree tmpl, tree args, tree def)
24656 {
24657   concept_spec_entry elt = {tmpl, args, def};
24658   concept_spec_entry** slot = concept_expansions->find_slot (&elt, INSERT);
24659   concept_spec_entry* entry = ggc_alloc<concept_spec_entry> ();
24660   *entry = elt;
24661   *slot = entry;
24662   return def;
24663 }
24664 
24665 static hashval_t
hash_subsumption_args(tree t1,tree t2)24666 hash_subsumption_args (tree t1, tree t2)
24667 {
24668   gcc_assert (TREE_CODE (t1) == CHECK_CONSTR);
24669   gcc_assert (TREE_CODE (t2) == CHECK_CONSTR);
24670   int val = 0;
24671   val = iterative_hash_object (CHECK_CONSTR_CONCEPT (t1), val);
24672   val = iterative_hash_template_arg (CHECK_CONSTR_ARGS (t1), val);
24673   val = iterative_hash_object (CHECK_CONSTR_CONCEPT (t2), val);
24674   val = iterative_hash_template_arg (CHECK_CONSTR_ARGS (t2), val);
24675   return val;
24676 }
24677 
24678 /* Compare the constraints of two subsumption entries.  The LEFT1 and
24679    LEFT2 arguments comprise the first subsumption pair and the RIGHT1
24680    and RIGHT2 arguments comprise the second. These are all CHECK_CONSTRs. */
24681 
24682 static bool
comp_subsumption_args(tree left1,tree left2,tree right1,tree right2)24683 comp_subsumption_args (tree left1, tree left2, tree right1, tree right2)
24684 {
24685   if (CHECK_CONSTR_CONCEPT (left1) == CHECK_CONSTR_CONCEPT (right1))
24686     if (CHECK_CONSTR_CONCEPT (left2) == CHECK_CONSTR_CONCEPT (right2))
24687       if (comp_template_args (CHECK_CONSTR_ARGS (left1),
24688                              CHECK_CONSTR_ARGS (right1)))
24689         return comp_template_args (CHECK_CONSTR_ARGS (left2),
24690                                   CHECK_CONSTR_ARGS (right2));
24691   return false;
24692 }
24693 
24694 /* Key/value pair for learning and memoizing subsumption results. This
24695    associates a pair of check constraints (including arguments) with
24696    a boolean value indicating the result.  */
24697 
24698 struct GTY((for_user)) subsumption_entry
24699 {
24700   tree t1;
24701   tree t2;
24702   bool result;
24703 };
24704 
24705 /* Hashing function and equality for constraint entries.  */
24706 
24707 struct subsumption_hasher : ggc_ptr_hash<subsumption_entry>
24708 {
hashsubsumption_hasher24709   static hashval_t hash (subsumption_entry *e)
24710   {
24711     return hash_subsumption_args (e->t1, e->t2);
24712   }
24713 
equalsubsumption_hasher24714   static bool equal (subsumption_entry *e1, subsumption_entry *e2)
24715   {
24716     ++comparing_specializations;
24717     bool eq = comp_subsumption_args(e1->t1, e1->t2, e2->t1, e2->t2);
24718     --comparing_specializations;
24719     return eq;
24720   }
24721 };
24722 
24723 static GTY (()) hash_table<subsumption_hasher> *subsumption_table;
24724 
24725 /* Search for a previously cached subsumption result. */
24726 
24727 bool*
lookup_subsumption_result(tree t1,tree t2)24728 lookup_subsumption_result (tree t1, tree t2)
24729 {
24730   subsumption_entry elt = { t1, t2, false };
24731   subsumption_entry* found = subsumption_table->find (&elt);
24732   if (found)
24733     return &found->result;
24734   else
24735     return 0;
24736 }
24737 
24738 /* Save a subsumption result. */
24739 
24740 bool
save_subsumption_result(tree t1,tree t2,bool result)24741 save_subsumption_result (tree t1, tree t2, bool result)
24742 {
24743   subsumption_entry elt = {t1, t2, result};
24744   subsumption_entry** slot = subsumption_table->find_slot (&elt, INSERT);
24745   subsumption_entry* entry = ggc_alloc<subsumption_entry> ();
24746   *entry = elt;
24747   *slot = entry;
24748   return result;
24749 }
24750 
24751 /* Set up the hash table for constraint association. */
24752 
24753 void
init_constraint_processing(void)24754 init_constraint_processing (void)
24755 {
24756   if (!flag_concepts)
24757     return;
24758 
24759   decl_constraints = hash_table<constr_hasher>::create_ggc(37);
24760   constraint_memos = hash_table<constraint_sat_hasher>::create_ggc(37);
24761   concept_memos = hash_table<concept_spec_hasher>::create_ggc(37);
24762   concept_expansions = hash_table<concept_spec_hasher>::create_ggc(37);
24763   subsumption_table = hash_table<subsumption_hasher>::create_ggc(37);
24764 }
24765 
24766 /* Set up the hash tables for template instantiations.  */
24767 
24768 void
init_template_processing(void)24769 init_template_processing (void)
24770 {
24771   decl_specializations = hash_table<spec_hasher>::create_ggc (37);
24772   type_specializations = hash_table<spec_hasher>::create_ggc (37);
24773 }
24774 
24775 /* Print stats about the template hash tables for -fstats.  */
24776 
24777 void
print_template_statistics(void)24778 print_template_statistics (void)
24779 {
24780   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
24781 	   "%f collisions\n", (long) decl_specializations->size (),
24782 	   (long) decl_specializations->elements (),
24783 	   decl_specializations->collisions ());
24784   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
24785 	   "%f collisions\n", (long) type_specializations->size (),
24786 	   (long) type_specializations->elements (),
24787 	   type_specializations->collisions ());
24788 }
24789 
24790 #include "gt-cp-pt.h"
24791