xref: /netbsd-src/external/gpl3/gcc.old/dist/gcc/cp/pt.c (revision b7b7574d3bf8eeb51a1fa3977b59142ec6434a55)
1 /* Handle parameterized types (templates) for GNU C++.
2    Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
3    2001, 2002, 2003, 2004, 2005, 2007, 2008, 2009
4    Free Software Foundation, Inc.
5    Written by Ken Raeburn (raeburn@cygnus.com) while at Watchmaker Computing.
6    Rewritten by Jason Merrill (jason@cygnus.com).
7 
8 This file is part of GCC.
9 
10 GCC is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 3, or (at your option)
13 any later version.
14 
15 GCC is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 GNU General Public License for more details.
19 
20 You should have received a copy of the GNU General Public License
21 along with GCC; see the file COPYING3.  If not see
22 <http://www.gnu.org/licenses/>.  */
23 
24 /* Known bugs or deficiencies include:
25 
26      all methods must be provided in header files; can't use a source
27      file that contains only the method templates and "just win".  */
28 
29 #include "config.h"
30 #include "system.h"
31 #include "coretypes.h"
32 #include "tm.h"
33 #include "obstack.h"
34 #include "tree.h"
35 #include "intl.h"
36 #include "pointer-set.h"
37 #include "flags.h"
38 #include "c-common.h"
39 #include "cp-tree.h"
40 #include "cp-objcp-common.h"
41 #include "tree-inline.h"
42 #include "decl.h"
43 #include "output.h"
44 #include "except.h"
45 #include "toplev.h"
46 #include "rtl.h"
47 #include "timevar.h"
48 #include "tree-iterator.h"
49 #include "vecprim.h"
50 
51 /* The type of functions taking a tree, and some additional data, and
52    returning an int.  */
53 typedef int (*tree_fn_t) (tree, void*);
54 
55 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
56    instantiations have been deferred, either because their definitions
57    were not yet available, or because we were putting off doing the work.  */
58 struct GTY (()) pending_template {
59   struct pending_template *next;
60   struct tinst_level *tinst;
61 };
62 
63 static GTY(()) struct pending_template *pending_templates;
64 static GTY(()) struct pending_template *last_pending_template;
65 
66 int processing_template_parmlist;
67 static int template_header_count;
68 
69 static GTY(()) tree saved_trees;
70 static VEC(int,heap) *inline_parm_levels;
71 
72 static GTY(()) struct tinst_level *current_tinst_level;
73 
74 static GTY(()) tree saved_access_scope;
75 
76 /* Live only within one (recursive) call to tsubst_expr.  We use
77    this to pass the statement expression node from the STMT_EXPR
78    to the EXPR_STMT that is its result.  */
79 static tree cur_stmt_expr;
80 
81 /* A map from local variable declarations in the body of the template
82    presently being instantiated to the corresponding instantiated
83    local variables.  */
84 static htab_t local_specializations;
85 
86 typedef struct GTY(()) spec_entry
87 {
88   tree tmpl;
89   tree args;
90   tree spec;
91 } spec_entry;
92 
93 static GTY ((param_is (spec_entry)))
94   htab_t decl_specializations;
95 
96 static GTY ((param_is (spec_entry)))
97   htab_t type_specializations;
98 
99 /* Contains canonical template parameter types. The vector is indexed by
100    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
101    TREE_LIST, whose TREE_VALUEs contain the canonical template
102    parameters of various types and levels.  */
103 static GTY(()) VEC(tree,gc) *canonical_template_parms;
104 
105 #define UNIFY_ALLOW_NONE 0
106 #define UNIFY_ALLOW_MORE_CV_QUAL 1
107 #define UNIFY_ALLOW_LESS_CV_QUAL 2
108 #define UNIFY_ALLOW_DERIVED 4
109 #define UNIFY_ALLOW_INTEGER 8
110 #define UNIFY_ALLOW_OUTER_LEVEL 16
111 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
112 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
113 
114 static void push_access_scope (tree);
115 static void pop_access_scope (tree);
116 static bool resolve_overloaded_unification (tree, tree, tree, tree,
117 					    unification_kind_t, int);
118 static int try_one_overload (tree, tree, tree, tree, tree,
119 			     unification_kind_t, int, bool);
120 static int unify (tree, tree, tree, tree, int);
121 static void add_pending_template (tree);
122 static tree reopen_tinst_level (struct tinst_level *);
123 static tree tsubst_initializer_list (tree, tree);
124 static tree get_class_bindings (tree, tree, tree);
125 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
126 				   bool, bool);
127 static void tsubst_enum	(tree, tree, tree);
128 static tree add_to_template_args (tree, tree);
129 static tree add_outermost_template_args (tree, tree);
130 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
131 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
132 					     tree);
133 static int type_unification_real (tree, tree, tree, const tree *,
134 				  unsigned int, int, unification_kind_t, int);
135 static void note_template_header (int);
136 static tree convert_nontype_argument_function (tree, tree);
137 static tree convert_nontype_argument (tree, tree);
138 static tree convert_template_argument (tree, tree, tree,
139 				       tsubst_flags_t, int, tree);
140 static int for_each_template_parm (tree, tree_fn_t, void*,
141 				   struct pointer_set_t*, bool);
142 static tree expand_template_argument_pack (tree);
143 static tree build_template_parm_index (int, int, int, tree, tree);
144 static bool inline_needs_template_parms (tree);
145 static void push_inline_template_parms_recursive (tree, int);
146 static tree retrieve_local_specialization (tree);
147 static void register_local_specialization (tree, tree);
148 static hashval_t hash_specialization (const void *p);
149 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
150 static int mark_template_parm (tree, void *);
151 static int template_parm_this_level_p (tree, void *);
152 static tree tsubst_friend_function (tree, tree);
153 static tree tsubst_friend_class (tree, tree);
154 static int can_complete_type_without_circularity (tree);
155 static tree get_bindings (tree, tree, tree, bool);
156 static int template_decl_level (tree);
157 static int check_cv_quals_for_unify (int, tree, tree);
158 static void template_parm_level_and_index (tree, int*, int*);
159 static int unify_pack_expansion (tree, tree, tree, tree, int, bool, bool);
160 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
161 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
162 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
163 static void regenerate_decl_from_template (tree, tree);
164 static tree most_specialized_class (tree, tree);
165 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
166 static tree tsubst_arg_types (tree, tree, tsubst_flags_t, tree);
167 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
168 static bool check_specialization_scope (void);
169 static tree process_partial_specialization (tree);
170 static void set_current_access_from_decl (tree);
171 static tree get_template_base (tree, tree, tree, tree);
172 static tree try_class_unification (tree, tree, tree, tree);
173 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
174 					   tree, tree);
175 static bool template_template_parm_bindings_ok_p (tree, tree);
176 static int template_args_equal (tree, tree);
177 static void tsubst_default_arguments (tree);
178 static tree for_each_template_parm_r (tree *, int *, void *);
179 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
180 static void copy_default_args_to_explicit_spec (tree);
181 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
182 static int eq_local_specializations (const void *, const void *);
183 static bool dependent_template_arg_p (tree);
184 static bool any_template_arguments_need_structural_equality_p (tree);
185 static bool dependent_type_p_r (tree);
186 static tree tsubst_expr	(tree, tree, tsubst_flags_t, tree, bool);
187 static tree tsubst_copy	(tree, tree, tsubst_flags_t, tree);
188 static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
189 static tree tsubst_decl (tree, tree, tsubst_flags_t);
190 static void perform_typedefs_access_check (tree tmpl, tree targs);
191 static void append_type_to_template_for_access_check_1 (tree, tree, tree,
192 							location_t);
193 static hashval_t iterative_hash_template_arg (tree arg, hashval_t val);
194 static tree listify (tree);
195 static tree listify_autos (tree, tree);
196 
197 /* Make the current scope suitable for access checking when we are
198    processing T.  T can be FUNCTION_DECL for instantiated function
199    template, or VAR_DECL for static member variable (need by
200    instantiate_decl).  */
201 
202 static void
203 push_access_scope (tree t)
204 {
205   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
206 	      || TREE_CODE (t) == VAR_DECL);
207 
208   if (DECL_FRIEND_CONTEXT (t))
209     push_nested_class (DECL_FRIEND_CONTEXT (t));
210   else if (DECL_CLASS_SCOPE_P (t))
211     push_nested_class (DECL_CONTEXT (t));
212   else
213     push_to_top_level ();
214 
215   if (TREE_CODE (t) == FUNCTION_DECL)
216     {
217       saved_access_scope = tree_cons
218 	(NULL_TREE, current_function_decl, saved_access_scope);
219       current_function_decl = t;
220     }
221 }
222 
223 /* Restore the scope set up by push_access_scope.  T is the node we
224    are processing.  */
225 
226 static void
227 pop_access_scope (tree t)
228 {
229   if (TREE_CODE (t) == FUNCTION_DECL)
230     {
231       current_function_decl = TREE_VALUE (saved_access_scope);
232       saved_access_scope = TREE_CHAIN (saved_access_scope);
233     }
234 
235   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
236     pop_nested_class ();
237   else
238     pop_from_top_level ();
239 }
240 
241 /* Do any processing required when DECL (a member template
242    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
243    to DECL, unless it is a specialization, in which case the DECL
244    itself is returned.  */
245 
246 tree
247 finish_member_template_decl (tree decl)
248 {
249   if (decl == error_mark_node)
250     return error_mark_node;
251 
252   gcc_assert (DECL_P (decl));
253 
254   if (TREE_CODE (decl) == TYPE_DECL)
255     {
256       tree type;
257 
258       type = TREE_TYPE (decl);
259       if (type == error_mark_node)
260 	return error_mark_node;
261       if (MAYBE_CLASS_TYPE_P (type)
262 	  && CLASSTYPE_TEMPLATE_INFO (type)
263 	  && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
264 	{
265 	  tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
266 	  check_member_template (tmpl);
267 	  return tmpl;
268 	}
269       return NULL_TREE;
270     }
271   else if (TREE_CODE (decl) == FIELD_DECL)
272     error ("data member %qD cannot be a member template", decl);
273   else if (DECL_TEMPLATE_INFO (decl))
274     {
275       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
276 	{
277 	  check_member_template (DECL_TI_TEMPLATE (decl));
278 	  return DECL_TI_TEMPLATE (decl);
279 	}
280       else
281 	return decl;
282     }
283   else
284     error ("invalid member template declaration %qD", decl);
285 
286   return error_mark_node;
287 }
288 
289 /* Create a template info node.  */
290 
291 tree
292 build_template_info (tree template_decl, tree template_args)
293 {
294   tree result = make_node (TEMPLATE_INFO);
295   TI_TEMPLATE (result) = template_decl;
296   TI_ARGS (result) = template_args;
297   return result;
298 }
299 
300 /* Return the template info node corresponding to T, whatever T is.  */
301 
302 tree
303 get_template_info (const_tree t)
304 {
305   tree tinfo = NULL_TREE;
306 
307   if (!t || t == error_mark_node)
308     return NULL;
309 
310   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
311     tinfo = DECL_TEMPLATE_INFO (t);
312 
313   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
314     t = TREE_TYPE (t);
315 
316   if (TAGGED_TYPE_P (t))
317     tinfo = TYPE_TEMPLATE_INFO (t);
318   else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
319     tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
320 
321   return tinfo;
322 }
323 
324 /* Returns the template nesting level of the indicated class TYPE.
325 
326    For example, in:
327      template <class T>
328      struct A
329      {
330        template <class U>
331        struct B {};
332      };
333 
334    A<T>::B<U> has depth two, while A<T> has depth one.
335    Both A<T>::B<int> and A<int>::B<U> have depth one, if
336    they are instantiations, not specializations.
337 
338    This function is guaranteed to return 0 if passed NULL_TREE so
339    that, for example, `template_class_depth (current_class_type)' is
340    always safe.  */
341 
342 int
343 template_class_depth (tree type)
344 {
345   int depth;
346 
347   for (depth = 0;
348        type && TREE_CODE (type) != NAMESPACE_DECL;
349        type = (TREE_CODE (type) == FUNCTION_DECL)
350 	 ? CP_DECL_CONTEXT (type) : TYPE_CONTEXT (type))
351     {
352       tree tinfo = get_template_info (type);
353 
354       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
355 	  && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
356 	++depth;
357     }
358 
359   return depth;
360 }
361 
362 /* Subroutine of maybe_begin_member_template_processing.
363    Returns true if processing DECL needs us to push template parms.  */
364 
365 static bool
366 inline_needs_template_parms (tree decl)
367 {
368   if (! DECL_TEMPLATE_INFO (decl))
369     return false;
370 
371   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
372 	  > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
373 }
374 
375 /* Subroutine of maybe_begin_member_template_processing.
376    Push the template parms in PARMS, starting from LEVELS steps into the
377    chain, and ending at the beginning, since template parms are listed
378    innermost first.  */
379 
380 static void
381 push_inline_template_parms_recursive (tree parmlist, int levels)
382 {
383   tree parms = TREE_VALUE (parmlist);
384   int i;
385 
386   if (levels > 1)
387     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
388 
389   ++processing_template_decl;
390   current_template_parms
391     = tree_cons (size_int (processing_template_decl),
392 		 parms, current_template_parms);
393   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
394 
395   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
396 	       NULL);
397   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
398     {
399       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
400 
401       if (parm == error_mark_node)
402 	continue;
403 
404       gcc_assert (DECL_P (parm));
405 
406       switch (TREE_CODE (parm))
407 	{
408 	case TYPE_DECL:
409 	case TEMPLATE_DECL:
410 	  pushdecl (parm);
411 	  break;
412 
413 	case PARM_DECL:
414 	  {
415 	    /* Make a CONST_DECL as is done in process_template_parm.
416 	       It is ugly that we recreate this here; the original
417 	       version built in process_template_parm is no longer
418 	       available.  */
419 	    tree decl = build_decl (DECL_SOURCE_LOCATION (parm),
420 				    CONST_DECL, DECL_NAME (parm),
421 				    TREE_TYPE (parm));
422 	    DECL_ARTIFICIAL (decl) = 1;
423 	    TREE_CONSTANT (decl) = 1;
424 	    TREE_READONLY (decl) = 1;
425 	    DECL_INITIAL (decl) = DECL_INITIAL (parm);
426 	    SET_DECL_TEMPLATE_PARM_P (decl);
427 	    pushdecl (decl);
428 	  }
429 	  break;
430 
431 	default:
432 	  gcc_unreachable ();
433 	}
434     }
435 }
436 
437 /* Restore the template parameter context for a member template or
438    a friend template defined in a class definition.  */
439 
440 void
441 maybe_begin_member_template_processing (tree decl)
442 {
443   tree parms;
444   int levels = 0;
445 
446   if (inline_needs_template_parms (decl))
447     {
448       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
449       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
450 
451       if (DECL_TEMPLATE_SPECIALIZATION (decl))
452 	{
453 	  --levels;
454 	  parms = TREE_CHAIN (parms);
455 	}
456 
457       push_inline_template_parms_recursive (parms, levels);
458     }
459 
460   /* Remember how many levels of template parameters we pushed so that
461      we can pop them later.  */
462   VEC_safe_push (int, heap, inline_parm_levels, levels);
463 }
464 
465 /* Undo the effects of maybe_begin_member_template_processing.  */
466 
467 void
468 maybe_end_member_template_processing (void)
469 {
470   int i;
471   int last;
472 
473   if (VEC_length (int, inline_parm_levels) == 0)
474     return;
475 
476   last = VEC_pop (int, inline_parm_levels);
477   for (i = 0; i < last; ++i)
478     {
479       --processing_template_decl;
480       current_template_parms = TREE_CHAIN (current_template_parms);
481       poplevel (0, 0, 0);
482     }
483 }
484 
485 /* Return a new template argument vector which contains all of ARGS,
486    but has as its innermost set of arguments the EXTRA_ARGS.  */
487 
488 static tree
489 add_to_template_args (tree args, tree extra_args)
490 {
491   tree new_args;
492   int extra_depth;
493   int i;
494   int j;
495 
496   if (args == NULL_TREE)
497     return extra_args;
498 
499   extra_depth = TMPL_ARGS_DEPTH (extra_args);
500   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
501 
502   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
503     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
504 
505   for (j = 1; j <= extra_depth; ++j, ++i)
506     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
507 
508   return new_args;
509 }
510 
511 /* Like add_to_template_args, but only the outermost ARGS are added to
512    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
513    (EXTRA_ARGS) levels are added.  This function is used to combine
514    the template arguments from a partial instantiation with the
515    template arguments used to attain the full instantiation from the
516    partial instantiation.  */
517 
518 static tree
519 add_outermost_template_args (tree args, tree extra_args)
520 {
521   tree new_args;
522 
523   /* If there are more levels of EXTRA_ARGS than there are ARGS,
524      something very fishy is going on.  */
525   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
526 
527   /* If *all* the new arguments will be the EXTRA_ARGS, just return
528      them.  */
529   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
530     return extra_args;
531 
532   /* For the moment, we make ARGS look like it contains fewer levels.  */
533   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
534 
535   new_args = add_to_template_args (args, extra_args);
536 
537   /* Now, we restore ARGS to its full dimensions.  */
538   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
539 
540   return new_args;
541 }
542 
543 /* Return the N levels of innermost template arguments from the ARGS.  */
544 
545 tree
546 get_innermost_template_args (tree args, int n)
547 {
548   tree new_args;
549   int extra_levels;
550   int i;
551 
552   gcc_assert (n >= 0);
553 
554   /* If N is 1, just return the innermost set of template arguments.  */
555   if (n == 1)
556     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
557 
558   /* If we're not removing anything, just return the arguments we were
559      given.  */
560   extra_levels = TMPL_ARGS_DEPTH (args) - n;
561   gcc_assert (extra_levels >= 0);
562   if (extra_levels == 0)
563     return args;
564 
565   /* Make a new set of arguments, not containing the outer arguments.  */
566   new_args = make_tree_vec (n);
567   for (i = 1; i <= n; ++i)
568     SET_TMPL_ARGS_LEVEL (new_args, i,
569 			 TMPL_ARGS_LEVEL (args, i + extra_levels));
570 
571   return new_args;
572 }
573 
574 /* The inverse of get_innermost_template_args: Return all but the innermost
575    EXTRA_LEVELS levels of template arguments from the ARGS.  */
576 
577 static tree
578 strip_innermost_template_args (tree args, int extra_levels)
579 {
580   tree new_args;
581   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
582   int i;
583 
584   gcc_assert (n >= 0);
585 
586   /* If N is 1, just return the outermost set of template arguments.  */
587   if (n == 1)
588     return TMPL_ARGS_LEVEL (args, 1);
589 
590   /* If we're not removing anything, just return the arguments we were
591      given.  */
592   gcc_assert (extra_levels >= 0);
593   if (extra_levels == 0)
594     return args;
595 
596   /* Make a new set of arguments, not containing the inner arguments.  */
597   new_args = make_tree_vec (n);
598   for (i = 1; i <= n; ++i)
599     SET_TMPL_ARGS_LEVEL (new_args, i,
600 			 TMPL_ARGS_LEVEL (args, i));
601 
602   return new_args;
603 }
604 
605 /* We've got a template header coming up; push to a new level for storing
606    the parms.  */
607 
608 void
609 begin_template_parm_list (void)
610 {
611   /* We use a non-tag-transparent scope here, which causes pushtag to
612      put tags in this scope, rather than in the enclosing class or
613      namespace scope.  This is the right thing, since we want
614      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
615      global template class, push_template_decl handles putting the
616      TEMPLATE_DECL into top-level scope.  For a nested template class,
617      e.g.:
618 
619        template <class T> struct S1 {
620 	 template <class T> struct S2 {};
621        };
622 
623      pushtag contains special code to call pushdecl_with_scope on the
624      TEMPLATE_DECL for S2.  */
625   begin_scope (sk_template_parms, NULL);
626   ++processing_template_decl;
627   ++processing_template_parmlist;
628   note_template_header (0);
629 }
630 
631 /* This routine is called when a specialization is declared.  If it is
632    invalid to declare a specialization here, an error is reported and
633    false is returned, otherwise this routine will return true.  */
634 
635 static bool
636 check_specialization_scope (void)
637 {
638   tree scope = current_scope ();
639 
640   /* [temp.expl.spec]
641 
642      An explicit specialization shall be declared in the namespace of
643      which the template is a member, or, for member templates, in the
644      namespace of which the enclosing class or enclosing class
645      template is a member.  An explicit specialization of a member
646      function, member class or static data member of a class template
647      shall be declared in the namespace of which the class template
648      is a member.  */
649   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
650     {
651       error ("explicit specialization in non-namespace scope %qD", scope);
652       return false;
653     }
654 
655   /* [temp.expl.spec]
656 
657      In an explicit specialization declaration for a member of a class
658      template or a member template that appears in namespace scope,
659      the member template and some of its enclosing class templates may
660      remain unspecialized, except that the declaration shall not
661      explicitly specialize a class member template if its enclosing
662      class templates are not explicitly specialized as well.  */
663   if (current_template_parms)
664     {
665       error ("enclosing class templates are not explicitly specialized");
666       return false;
667     }
668 
669   return true;
670 }
671 
672 /* We've just seen template <>.  */
673 
674 bool
675 begin_specialization (void)
676 {
677   begin_scope (sk_template_spec, NULL);
678   note_template_header (1);
679   return check_specialization_scope ();
680 }
681 
682 /* Called at then end of processing a declaration preceded by
683    template<>.  */
684 
685 void
686 end_specialization (void)
687 {
688   finish_scope ();
689   reset_specialization ();
690 }
691 
692 /* Any template <>'s that we have seen thus far are not referring to a
693    function specialization.  */
694 
695 void
696 reset_specialization (void)
697 {
698   processing_specialization = 0;
699   template_header_count = 0;
700 }
701 
702 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
703    it was of the form template <>.  */
704 
705 static void
706 note_template_header (int specialization)
707 {
708   processing_specialization = specialization;
709   template_header_count++;
710 }
711 
712 /* We're beginning an explicit instantiation.  */
713 
714 void
715 begin_explicit_instantiation (void)
716 {
717   gcc_assert (!processing_explicit_instantiation);
718   processing_explicit_instantiation = true;
719 }
720 
721 
722 void
723 end_explicit_instantiation (void)
724 {
725   gcc_assert (processing_explicit_instantiation);
726   processing_explicit_instantiation = false;
727 }
728 
729 /* An explicit specialization or partial specialization TMPL is being
730    declared.  Check that the namespace in which the specialization is
731    occurring is permissible.  Returns false iff it is invalid to
732    specialize TMPL in the current namespace.  */
733 
734 static bool
735 check_specialization_namespace (tree tmpl)
736 {
737   tree tpl_ns = decl_namespace_context (tmpl);
738 
739   /* [tmpl.expl.spec]
740 
741      An explicit specialization shall be declared in the namespace of
742      which the template is a member, or, for member templates, in the
743      namespace of which the enclosing class or enclosing class
744      template is a member.  An explicit specialization of a member
745      function, member class or static data member of a class template
746      shall be declared in the namespace of which the class template is
747      a member.  */
748   if (current_scope() != DECL_CONTEXT (tmpl)
749       && !at_namespace_scope_p ())
750     {
751       error ("specialization of %qD must appear at namespace scope", tmpl);
752       return false;
753     }
754   if (is_associated_namespace (current_namespace, tpl_ns))
755     /* Same or super-using namespace.  */
756     return true;
757   else
758     {
759       permerror (input_location, "specialization of %qD in different namespace", tmpl);
760       permerror (input_location, "  from definition of %q+#D", tmpl);
761       return false;
762     }
763 }
764 
765 /* SPEC is an explicit instantiation.  Check that it is valid to
766    perform this explicit instantiation in the current namespace.  */
767 
768 static void
769 check_explicit_instantiation_namespace (tree spec)
770 {
771   tree ns;
772 
773   /* DR 275: An explicit instantiation shall appear in an enclosing
774      namespace of its template.  */
775   ns = decl_namespace_context (spec);
776   if (!is_ancestor (current_namespace, ns))
777     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
778 	       "(which does not enclose namespace %qD)",
779 	       spec, current_namespace, ns);
780 }
781 
782 /* The TYPE is being declared.  If it is a template type, that means it
783    is a partial specialization.  Do appropriate error-checking.  */
784 
785 tree
786 maybe_process_partial_specialization (tree type)
787 {
788   tree context;
789 
790   if (type == error_mark_node)
791     return error_mark_node;
792 
793   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
794     {
795       error ("name of class shadows template template parameter %qD",
796 	     TYPE_NAME (type));
797       return error_mark_node;
798     }
799 
800   context = TYPE_CONTEXT (type);
801 
802   if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
803     {
804       /* This is for ordinary explicit specialization and partial
805 	 specialization of a template class such as:
806 
807 	   template <> class C<int>;
808 
809 	 or:
810 
811 	   template <class T> class C<T*>;
812 
813 	 Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
814 
815       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
816 	  && !COMPLETE_TYPE_P (type))
817 	{
818 	  check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
819 	  SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
820 	  if (processing_template_decl)
821 	    {
822 	      if (push_template_decl (TYPE_MAIN_DECL (type))
823 		  == error_mark_node)
824 		return error_mark_node;
825 	    }
826 	}
827       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
828 	error ("specialization of %qT after instantiation", type);
829     }
830   else if (CLASS_TYPE_P (type)
831 	   && !CLASSTYPE_USE_TEMPLATE (type)
832 	   && CLASSTYPE_TEMPLATE_INFO (type)
833 	   && context && CLASS_TYPE_P (context)
834 	   && CLASSTYPE_TEMPLATE_INFO (context))
835     {
836       /* This is for an explicit specialization of member class
837 	 template according to [temp.expl.spec/18]:
838 
839 	   template <> template <class U> class C<int>::D;
840 
841 	 The context `C<int>' must be an implicit instantiation.
842 	 Otherwise this is just a member class template declared
843 	 earlier like:
844 
845 	   template <> class C<int> { template <class U> class D; };
846 	   template <> template <class U> class C<int>::D;
847 
848 	 In the first case, `C<int>::D' is a specialization of `C<T>::D'
849 	 while in the second case, `C<int>::D' is a primary template
850 	 and `C<T>::D' may not exist.  */
851 
852       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
853 	  && !COMPLETE_TYPE_P (type))
854 	{
855 	  tree t;
856 	  tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
857 
858 	  if (current_namespace
859 	      != decl_namespace_context (tmpl))
860 	    {
861 	      permerror (input_location, "specializing %q#T in different namespace", type);
862 	      permerror (input_location, "  from definition of %q+#D", tmpl);
863 	    }
864 
865 	  /* Check for invalid specialization after instantiation:
866 
867 	       template <> template <> class C<int>::D<int>;
868 	       template <> template <class U> class C<int>::D;  */
869 
870 	  for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
871 	       t; t = TREE_CHAIN (t))
872 	    {
873 	      tree inst = TREE_VALUE (t);
874 	      if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst))
875 		{
876 		  /* We already have a full specialization of this partial
877 		     instantiation.  Reassign it to the new member
878 		     specialization template.  */
879 		  spec_entry elt;
880 		  spec_entry **slot;
881 
882 		  elt.tmpl = most_general_template (tmpl);
883 		  elt.args = CLASSTYPE_TI_ARGS (inst);
884 		  elt.spec = inst;
885 
886 		  htab_remove_elt (type_specializations, &elt);
887 
888 		  elt.tmpl = tmpl;
889 		  elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
890 
891 		  slot = (spec_entry **)
892 		    htab_find_slot (type_specializations, &elt, INSERT);
893 		  *slot = GGC_NEW (spec_entry);
894 		  **slot = elt;
895 		}
896 	      else if (COMPLETE_TYPE_P (inst) || TYPE_BEING_DEFINED (inst))
897 		/* But if we've had an implicit instantiation, that's a
898 		   problem ([temp.expl.spec]/6).  */
899 		error ("specialization %qT after instantiation %qT",
900 		       type, inst);
901 	    }
902 
903 	  /* Mark TYPE as a specialization.  And as a result, we only
904 	     have one level of template argument for the innermost
905 	     class template.  */
906 	  SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
907 	  CLASSTYPE_TI_ARGS (type)
908 	    = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
909 	}
910     }
911   else if (processing_specialization)
912     {
913       error ("explicit specialization of non-template %qT", type);
914       return error_mark_node;
915     }
916 
917   return type;
918 }
919 
920 /* Returns nonzero if we can optimize the retrieval of specializations
921    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
922    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
923 
924 static inline bool
925 optimize_specialization_lookup_p (tree tmpl)
926 {
927   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
928 	  && DECL_CLASS_SCOPE_P (tmpl)
929 	  /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
930 	     parameter.  */
931 	  && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
932 	  /* The optimized lookup depends on the fact that the
933 	     template arguments for the member function template apply
934 	     purely to the containing class, which is not true if the
935 	     containing class is an explicit or partial
936 	     specialization.  */
937 	  && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
938 	  && !DECL_MEMBER_TEMPLATE_P (tmpl)
939 	  && !DECL_CONV_FN_P (tmpl)
940 	  /* It is possible to have a template that is not a member
941 	     template and is not a member of a template class:
942 
943 	     template <typename T>
944 	     struct S { friend A::f(); };
945 
946 	     Here, the friend function is a template, but the context does
947 	     not have template information.  The optimized lookup relies
948 	     on having ARGS be the template arguments for both the class
949 	     and the function template.  */
950 	  && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
951 }
952 
953 /* Retrieve the specialization (in the sense of [temp.spec] - a
954    specialization is either an instantiation or an explicit
955    specialization) of TMPL for the given template ARGS.  If there is
956    no such specialization, return NULL_TREE.  The ARGS are a vector of
957    arguments, or a vector of vectors of arguments, in the case of
958    templates with more than one level of parameters.
959 
960    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
961    then we search for a partial specialization matching ARGS.  This
962    parameter is ignored if TMPL is not a class template.  */
963 
964 static tree
965 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
966 {
967   if (args == error_mark_node)
968     return NULL_TREE;
969 
970   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
971 
972   /* There should be as many levels of arguments as there are
973      levels of parameters.  */
974   gcc_assert (TMPL_ARGS_DEPTH (args)
975 	      == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
976 
977   if (optimize_specialization_lookup_p (tmpl))
978     {
979       tree class_template;
980       tree class_specialization;
981       VEC(tree,gc) *methods;
982       tree fns;
983       int idx;
984 
985       /* The template arguments actually apply to the containing
986 	 class.  Find the class specialization with those
987 	 arguments.  */
988       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
989       class_specialization
990 	= retrieve_specialization (class_template, args, 0);
991       if (!class_specialization)
992 	return NULL_TREE;
993       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
994 	 for the specialization.  */
995       idx = class_method_index_for_fn (class_specialization, tmpl);
996       if (idx == -1)
997 	return NULL_TREE;
998       /* Iterate through the methods with the indicated name, looking
999 	 for the one that has an instance of TMPL.  */
1000       methods = CLASSTYPE_METHOD_VEC (class_specialization);
1001       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
1002 	{
1003 	  tree fn = OVL_CURRENT (fns);
1004 	  if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl
1005 	      /* using-declarations can add base methods to the method vec,
1006 		 and we don't want those here.  */
1007 	      && DECL_CONTEXT (fn) == class_specialization)
1008 	    return fn;
1009 	}
1010       return NULL_TREE;
1011     }
1012   else
1013     {
1014       spec_entry *found;
1015       spec_entry elt;
1016       htab_t specializations;
1017 
1018       elt.tmpl = tmpl;
1019       elt.args = args;
1020       elt.spec = NULL_TREE;
1021 
1022       if (DECL_CLASS_TEMPLATE_P (tmpl))
1023 	specializations = type_specializations;
1024       else
1025 	specializations = decl_specializations;
1026 
1027       if (hash == 0)
1028 	hash = hash_specialization (&elt);
1029       found = (spec_entry *) htab_find_with_hash (specializations, &elt, hash);
1030       if (found)
1031 	return found->spec;
1032     }
1033 
1034   return NULL_TREE;
1035 }
1036 
1037 /* Like retrieve_specialization, but for local declarations.  */
1038 
1039 static tree
1040 retrieve_local_specialization (tree tmpl)
1041 {
1042   tree spec;
1043 
1044   if (local_specializations == NULL)
1045     return NULL_TREE;
1046 
1047   spec = (tree) htab_find_with_hash (local_specializations, tmpl,
1048 				     htab_hash_pointer (tmpl));
1049   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
1050 }
1051 
1052 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1053 
1054 int
1055 is_specialization_of (tree decl, tree tmpl)
1056 {
1057   tree t;
1058 
1059   if (TREE_CODE (decl) == FUNCTION_DECL)
1060     {
1061       for (t = decl;
1062 	   t != NULL_TREE;
1063 	   t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1064 	if (t == tmpl)
1065 	  return 1;
1066     }
1067   else
1068     {
1069       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1070 
1071       for (t = TREE_TYPE (decl);
1072 	   t != NULL_TREE;
1073 	   t = CLASSTYPE_USE_TEMPLATE (t)
1074 	     ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1075 	if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1076 	  return 1;
1077     }
1078 
1079   return 0;
1080 }
1081 
1082 /* Returns nonzero iff DECL is a specialization of friend declaration
1083    FRIEND_DECL according to [temp.friend].  */
1084 
1085 bool
1086 is_specialization_of_friend (tree decl, tree friend_decl)
1087 {
1088   bool need_template = true;
1089   int template_depth;
1090 
1091   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1092 	      || TREE_CODE (decl) == TYPE_DECL);
1093 
1094   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1095      of a template class, we want to check if DECL is a specialization
1096      if this.  */
1097   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1098       && DECL_TEMPLATE_INFO (friend_decl)
1099       && !DECL_USE_TEMPLATE (friend_decl))
1100     {
1101       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1102       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1103       need_template = false;
1104     }
1105   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1106 	   && !PRIMARY_TEMPLATE_P (friend_decl))
1107     need_template = false;
1108 
1109   /* There is nothing to do if this is not a template friend.  */
1110   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1111     return false;
1112 
1113   if (is_specialization_of (decl, friend_decl))
1114     return true;
1115 
1116   /* [temp.friend/6]
1117      A member of a class template may be declared to be a friend of a
1118      non-template class.  In this case, the corresponding member of
1119      every specialization of the class template is a friend of the
1120      class granting friendship.
1121 
1122      For example, given a template friend declaration
1123 
1124        template <class T> friend void A<T>::f();
1125 
1126      the member function below is considered a friend
1127 
1128        template <> struct A<int> {
1129 	 void f();
1130        };
1131 
1132      For this type of template friend, TEMPLATE_DEPTH below will be
1133      nonzero.  To determine if DECL is a friend of FRIEND, we first
1134      check if the enclosing class is a specialization of another.  */
1135 
1136   template_depth = template_class_depth (DECL_CONTEXT (friend_decl));
1137   if (template_depth
1138       && DECL_CLASS_SCOPE_P (decl)
1139       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1140 			       CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1141     {
1142       /* Next, we check the members themselves.  In order to handle
1143 	 a few tricky cases, such as when FRIEND_DECL's are
1144 
1145 	   template <class T> friend void A<T>::g(T t);
1146 	   template <class T> template <T t> friend void A<T>::h();
1147 
1148 	 and DECL's are
1149 
1150 	   void A<int>::g(int);
1151 	   template <int> void A<int>::h();
1152 
1153 	 we need to figure out ARGS, the template arguments from
1154 	 the context of DECL.  This is required for template substitution
1155 	 of `T' in the function parameter of `g' and template parameter
1156 	 of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1157 
1158       tree context = DECL_CONTEXT (decl);
1159       tree args = NULL_TREE;
1160       int current_depth = 0;
1161 
1162       while (current_depth < template_depth)
1163 	{
1164 	  if (CLASSTYPE_TEMPLATE_INFO (context))
1165 	    {
1166 	      if (current_depth == 0)
1167 		args = TYPE_TI_ARGS (context);
1168 	      else
1169 		args = add_to_template_args (TYPE_TI_ARGS (context), args);
1170 	      current_depth++;
1171 	    }
1172 	  context = TYPE_CONTEXT (context);
1173 	}
1174 
1175       if (TREE_CODE (decl) == FUNCTION_DECL)
1176 	{
1177 	  bool is_template;
1178 	  tree friend_type;
1179 	  tree decl_type;
1180 	  tree friend_args_type;
1181 	  tree decl_args_type;
1182 
1183 	  /* Make sure that both DECL and FRIEND_DECL are templates or
1184 	     non-templates.  */
1185 	  is_template = DECL_TEMPLATE_INFO (decl)
1186 			&& PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1187 	  if (need_template ^ is_template)
1188 	    return false;
1189 	  else if (is_template)
1190 	    {
1191 	      /* If both are templates, check template parameter list.  */
1192 	      tree friend_parms
1193 		= tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1194 					 args, tf_none);
1195 	      if (!comp_template_parms
1196 		     (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1197 		      friend_parms))
1198 		return false;
1199 
1200 	      decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1201 	    }
1202 	  else
1203 	    decl_type = TREE_TYPE (decl);
1204 
1205 	  friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1206 					      tf_none, NULL_TREE);
1207 	  if (friend_type == error_mark_node)
1208 	    return false;
1209 
1210 	  /* Check if return types match.  */
1211 	  if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1212 	    return false;
1213 
1214 	  /* Check if function parameter types match, ignoring the
1215 	     `this' parameter.  */
1216 	  friend_args_type = TYPE_ARG_TYPES (friend_type);
1217 	  decl_args_type = TYPE_ARG_TYPES (decl_type);
1218 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1219 	    friend_args_type = TREE_CHAIN (friend_args_type);
1220 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1221 	    decl_args_type = TREE_CHAIN (decl_args_type);
1222 
1223 	  return compparms (decl_args_type, friend_args_type);
1224 	}
1225       else
1226 	{
1227 	  /* DECL is a TYPE_DECL */
1228 	  bool is_template;
1229 	  tree decl_type = TREE_TYPE (decl);
1230 
1231 	  /* Make sure that both DECL and FRIEND_DECL are templates or
1232 	     non-templates.  */
1233 	  is_template
1234 	    = CLASSTYPE_TEMPLATE_INFO (decl_type)
1235 	      && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1236 
1237 	  if (need_template ^ is_template)
1238 	    return false;
1239 	  else if (is_template)
1240 	    {
1241 	      tree friend_parms;
1242 	      /* If both are templates, check the name of the two
1243 		 TEMPLATE_DECL's first because is_friend didn't.  */
1244 	      if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1245 		  != DECL_NAME (friend_decl))
1246 		return false;
1247 
1248 	      /* Now check template parameter list.  */
1249 	      friend_parms
1250 		= tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1251 					 args, tf_none);
1252 	      return comp_template_parms
1253 		(DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1254 		 friend_parms);
1255 	    }
1256 	  else
1257 	    return (DECL_NAME (decl)
1258 		    == DECL_NAME (friend_decl));
1259 	}
1260     }
1261   return false;
1262 }
1263 
1264 /* Register the specialization SPEC as a specialization of TMPL with
1265    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1266    is actually just a friend declaration.  Returns SPEC, or an
1267    equivalent prior declaration, if available.  */
1268 
1269 static tree
1270 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1271 			 hashval_t hash)
1272 {
1273   tree fn;
1274   spec_entry **slot = NULL;
1275   spec_entry elt;
1276 
1277   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec));
1278 
1279   if (TREE_CODE (spec) == FUNCTION_DECL
1280       && uses_template_parms (DECL_TI_ARGS (spec)))
1281     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1282        register it; we want the corresponding TEMPLATE_DECL instead.
1283        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1284        the more obvious `uses_template_parms (spec)' to avoid problems
1285        with default function arguments.  In particular, given
1286        something like this:
1287 
1288 	  template <class T> void f(T t1, T t = T())
1289 
1290        the default argument expression is not substituted for in an
1291        instantiation unless and until it is actually needed.  */
1292     return spec;
1293 
1294   if (optimize_specialization_lookup_p (tmpl))
1295     /* We don't put these specializations in the hash table, but we might
1296        want to give an error about a mismatch.  */
1297     fn = retrieve_specialization (tmpl, args, 0);
1298   else
1299     {
1300       elt.tmpl = tmpl;
1301       elt.args = args;
1302       elt.spec = spec;
1303 
1304       if (hash == 0)
1305 	hash = hash_specialization (&elt);
1306 
1307       slot = (spec_entry **)
1308 	htab_find_slot_with_hash (decl_specializations, &elt, hash, INSERT);
1309       if (*slot)
1310 	fn = (*slot)->spec;
1311       else
1312 	fn = NULL_TREE;
1313     }
1314 
1315   /* We can sometimes try to re-register a specialization that we've
1316      already got.  In particular, regenerate_decl_from_template calls
1317      duplicate_decls which will update the specialization list.  But,
1318      we'll still get called again here anyhow.  It's more convenient
1319      to simply allow this than to try to prevent it.  */
1320   if (fn == spec)
1321     return spec;
1322   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1323     {
1324       if (DECL_TEMPLATE_INSTANTIATION (fn))
1325 	{
1326 	  if (DECL_ODR_USED (fn)
1327 	      || DECL_EXPLICIT_INSTANTIATION (fn))
1328 	    {
1329 	      error ("specialization of %qD after instantiation",
1330 		     fn);
1331 	      return error_mark_node;
1332 	    }
1333 	  else
1334 	    {
1335 	      tree clone;
1336 	      /* This situation should occur only if the first
1337 		 specialization is an implicit instantiation, the
1338 		 second is an explicit specialization, and the
1339 		 implicit instantiation has not yet been used.  That
1340 		 situation can occur if we have implicitly
1341 		 instantiated a member function and then specialized
1342 		 it later.
1343 
1344 		 We can also wind up here if a friend declaration that
1345 		 looked like an instantiation turns out to be a
1346 		 specialization:
1347 
1348 		   template <class T> void foo(T);
1349 		   class S { friend void foo<>(int) };
1350 		   template <> void foo(int);
1351 
1352 		 We transform the existing DECL in place so that any
1353 		 pointers to it become pointers to the updated
1354 		 declaration.
1355 
1356 		 If there was a definition for the template, but not
1357 		 for the specialization, we want this to look as if
1358 		 there were no definition, and vice versa.  */
1359 	      DECL_INITIAL (fn) = NULL_TREE;
1360 	      duplicate_decls (spec, fn, is_friend);
1361 	      /* The call to duplicate_decls will have applied
1362 		 [temp.expl.spec]:
1363 
1364 		   An explicit specialization of a function template
1365 		   is inline only if it is explicitly declared to be,
1366 		   and independently of whether its function template
1367 		   is.
1368 
1369 		to the primary function; now copy the inline bits to
1370 		the various clones.  */
1371 	      FOR_EACH_CLONE (clone, fn)
1372 		{
1373 		  DECL_DECLARED_INLINE_P (clone)
1374 		    = DECL_DECLARED_INLINE_P (fn);
1375 		  DECL_SOURCE_LOCATION (clone)
1376 		    = DECL_SOURCE_LOCATION (fn);
1377 		}
1378 	      check_specialization_namespace (fn);
1379 
1380 	      return fn;
1381 	    }
1382 	}
1383       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1384 	{
1385 	  if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1386 	    /* Dup decl failed, but this is a new definition. Set the
1387 	       line number so any errors match this new
1388 	       definition.  */
1389 	    DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1390 
1391 	  return fn;
1392 	}
1393     }
1394   else if (fn)
1395     return duplicate_decls (spec, fn, is_friend);
1396 
1397   /* A specialization must be declared in the same namespace as the
1398      template it is specializing.  */
1399   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1400       && !check_specialization_namespace (tmpl))
1401     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1402 
1403   if (!optimize_specialization_lookup_p (tmpl))
1404     {
1405       gcc_assert (tmpl && args && spec);
1406       *slot = GGC_NEW (spec_entry);
1407       **slot = elt;
1408       if (TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1409 	  && PRIMARY_TEMPLATE_P (tmpl)
1410 	  && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1411 	/* TMPL is a forward declaration of a template function; keep a list
1412 	   of all specializations in case we need to reassign them to a friend
1413 	   template later in tsubst_friend_function.  */
1414 	DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1415 	  = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1416     }
1417 
1418   return spec;
1419 }
1420 
1421 /* Returns true iff two spec_entry nodes are equivalent.  Only compares the
1422    TMPL and ARGS members, ignores SPEC.  */
1423 
1424 static int
1425 eq_specializations (const void *p1, const void *p2)
1426 {
1427   const spec_entry *e1 = (const spec_entry *)p1;
1428   const spec_entry *e2 = (const spec_entry *)p2;
1429 
1430   return (e1->tmpl == e2->tmpl
1431 	  && comp_template_args (e1->args, e2->args));
1432 }
1433 
1434 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1435 
1436 static hashval_t
1437 hash_tmpl_and_args (tree tmpl, tree args)
1438 {
1439   hashval_t val = DECL_UID (tmpl);
1440   return iterative_hash_template_arg (args, val);
1441 }
1442 
1443 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1444    ignoring SPEC.  */
1445 
1446 static hashval_t
1447 hash_specialization (const void *p)
1448 {
1449   const spec_entry *e = (const spec_entry *)p;
1450   return hash_tmpl_and_args (e->tmpl, e->args);
1451 }
1452 
1453 /* Recursively calculate a hash value for a template argument ARG, for use
1454    in the hash tables of template specializations.  */
1455 
1456 static hashval_t
1457 iterative_hash_template_arg (tree arg, hashval_t val)
1458 {
1459   unsigned HOST_WIDE_INT i;
1460   enum tree_code code;
1461   char tclass;
1462 
1463   if (arg == NULL_TREE)
1464     return iterative_hash_object (arg, val);
1465 
1466   if (!TYPE_P (arg))
1467     STRIP_NOPS (arg);
1468 
1469   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
1470     /* We can get one of these when re-hashing a previous entry in the middle
1471        of substituting into a pack expansion.  Just look through it.  */
1472     arg = ARGUMENT_PACK_SELECT_FROM_PACK (arg);
1473 
1474   code = TREE_CODE (arg);
1475   tclass = TREE_CODE_CLASS (code);
1476 
1477   val = iterative_hash_object (code, val);
1478 
1479   switch (code)
1480     {
1481     case ERROR_MARK:
1482       return val;
1483 
1484     case IDENTIFIER_NODE:
1485       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1486 
1487     case TREE_VEC:
1488       {
1489 	int i, len = TREE_VEC_LENGTH (arg);
1490 	for (i = 0; i < len; ++i)
1491 	  val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1492 	return val;
1493       }
1494 
1495     case TYPE_PACK_EXPANSION:
1496     case EXPR_PACK_EXPANSION:
1497       return iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1498 
1499     case TYPE_ARGUMENT_PACK:
1500     case NONTYPE_ARGUMENT_PACK:
1501       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1502 
1503     case TREE_LIST:
1504       for (; arg; arg = TREE_CHAIN (arg))
1505 	val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1506       return val;
1507 
1508     case OVERLOAD:
1509       for (; arg; arg = OVL_CHAIN (arg))
1510 	val = iterative_hash_template_arg (OVL_FUNCTION (arg), val);
1511       return val;
1512 
1513     case CONSTRUCTOR:
1514       {
1515 	tree field, value;
1516 	FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1517 	  {
1518 	    val = iterative_hash_template_arg (field, val);
1519 	    val = iterative_hash_template_arg (value, val);
1520 	  }
1521 	return val;
1522       }
1523 
1524     case PARM_DECL:
1525       if (!DECL_ARTIFICIAL (arg))
1526 	val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1527       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1528 
1529     case TARGET_EXPR:
1530       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1531 
1532     case PTRMEM_CST:
1533       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1534       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1535 
1536     case TEMPLATE_PARM_INDEX:
1537       val = iterative_hash_template_arg
1538 	(TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1539       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1540       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1541 
1542     case TRAIT_EXPR:
1543       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1544       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1545       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1546 
1547     case BASELINK:
1548       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1549 					 val);
1550       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1551 					  val);
1552 
1553     case MODOP_EXPR:
1554       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1555       code = TREE_CODE (TREE_OPERAND (arg, 1));
1556       val = iterative_hash_object (code, val);
1557       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1558 
1559     case LAMBDA_EXPR:
1560       /* A lambda can't appear in a template arg, but don't crash on
1561 	 erroneous input.  */
1562       gcc_assert (errorcount > 0);
1563       return val;
1564 
1565     default:
1566       switch (tclass)
1567 	{
1568 	case tcc_type:
1569 	  if (TYPE_CANONICAL (arg))
1570 	    return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1571 					  val);
1572 	  else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1573 	    return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1574 	  /* Otherwise just compare the types during lookup.  */
1575 	  return val;
1576 
1577 	case tcc_declaration:
1578 	case tcc_constant:
1579 	  return iterative_hash_expr (arg, val);
1580 
1581 	default:
1582 	  gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1583 	  {
1584 	    unsigned n = TREE_OPERAND_LENGTH (arg);
1585 	    for (i = 0; i < n; ++i)
1586 	      val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1587 	    return val;
1588 	  }
1589 	}
1590     }
1591   gcc_unreachable ();
1592   return 0;
1593 }
1594 
1595 /* Unregister the specialization SPEC as a specialization of TMPL.
1596    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1597    if the SPEC was listed as a specialization of TMPL.
1598 
1599    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1600 
1601 bool
1602 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1603 {
1604   spec_entry **slot;
1605   spec_entry elt;
1606 
1607   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1608   elt.args = TI_ARGS (tinfo);
1609   elt.spec = NULL_TREE;
1610 
1611   slot = (spec_entry **) htab_find_slot (decl_specializations, &elt, INSERT);
1612   if (*slot)
1613     {
1614       gcc_assert ((*slot)->spec == spec || (*slot)->spec == new_spec);
1615       gcc_assert (new_spec != NULL_TREE);
1616       (*slot)->spec = new_spec;
1617       return 1;
1618     }
1619 
1620   return 0;
1621 }
1622 
1623 /* Compare an entry in the local specializations hash table P1 (which
1624    is really a pointer to a TREE_LIST) with P2 (which is really a
1625    DECL).  */
1626 
1627 static int
1628 eq_local_specializations (const void *p1, const void *p2)
1629 {
1630   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1631 }
1632 
1633 /* Hash P1, an entry in the local specializations table.  */
1634 
1635 static hashval_t
1636 hash_local_specialization (const void* p1)
1637 {
1638   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1639 }
1640 
1641 /* Like register_specialization, but for local declarations.  We are
1642    registering SPEC, an instantiation of TMPL.  */
1643 
1644 static void
1645 register_local_specialization (tree spec, tree tmpl)
1646 {
1647   void **slot;
1648 
1649   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1650 				   htab_hash_pointer (tmpl), INSERT);
1651   *slot = build_tree_list (spec, tmpl);
1652 }
1653 
1654 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1655    specialized class.  */
1656 
1657 bool
1658 explicit_class_specialization_p (tree type)
1659 {
1660   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1661     return false;
1662   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1663 }
1664 
1665 /* Print the list of functions at FNS, going through all the overloads
1666    for each element of the list.  Alternatively, FNS can not be a
1667    TREE_LIST, in which case it will be printed together with all the
1668    overloads.
1669 
1670    MORE and *STR should respectively be FALSE and NULL when the function
1671    is called from the outside.  They are used internally on recursive
1672    calls.  print_candidates manages the two parameters and leaves NULL
1673    in *STR when it ends.  */
1674 
1675 static void
1676 print_candidates_1 (tree fns, bool more, const char **str)
1677 {
1678   tree fn, fn2;
1679   char *spaces = NULL;
1680 
1681   for (fn = fns; fn; fn = OVL_NEXT (fn))
1682     if (TREE_CODE (fn) == TREE_LIST)
1683       {
1684         gcc_assert (!OVL_NEXT (fn) && !is_overloaded_fn (fn));
1685         for (fn2 = fn; fn2 != NULL_TREE; fn2 = TREE_CHAIN (fn2))
1686           print_candidates_1 (TREE_VALUE (fn2),
1687                               TREE_CHAIN (fn2) || more, str);
1688       }
1689     else
1690       {
1691         if (!*str)
1692           {
1693             /* Pick the prefix string.  */
1694             if (!more && !OVL_NEXT (fns))
1695               {
1696                 error ("candidate is: %+#D", OVL_CURRENT (fn));
1697                 continue;
1698               }
1699 
1700             *str = _("candidates are:");
1701             spaces = get_spaces (*str);
1702           }
1703         error ("%s %+#D", *str, OVL_CURRENT (fn));
1704         *str = spaces ? spaces : *str;
1705       }
1706 
1707   if (!more)
1708     {
1709       free (spaces);
1710       *str = NULL;
1711     }
1712 }
1713 
1714 /* Print the list of candidate FNS in an error message.  */
1715 
1716 void
1717 print_candidates (tree fns)
1718 {
1719   const char *str = NULL;
1720   print_candidates_1 (fns, false, &str);
1721   gcc_assert (str == NULL);
1722 }
1723 
1724 /* Returns the template (one of the functions given by TEMPLATE_ID)
1725    which can be specialized to match the indicated DECL with the
1726    explicit template args given in TEMPLATE_ID.  The DECL may be
1727    NULL_TREE if none is available.  In that case, the functions in
1728    TEMPLATE_ID are non-members.
1729 
1730    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1731    specialization of a member template.
1732 
1733    The TEMPLATE_COUNT is the number of references to qualifying
1734    template classes that appeared in the name of the function. See
1735    check_explicit_specialization for a more accurate description.
1736 
1737    TSK indicates what kind of template declaration (if any) is being
1738    declared.  TSK_TEMPLATE indicates that the declaration given by
1739    DECL, though a FUNCTION_DECL, has template parameters, and is
1740    therefore a template function.
1741 
1742    The template args (those explicitly specified and those deduced)
1743    are output in a newly created vector *TARGS_OUT.
1744 
1745    If it is impossible to determine the result, an error message is
1746    issued.  The error_mark_node is returned to indicate failure.  */
1747 
1748 static tree
1749 determine_specialization (tree template_id,
1750 			  tree decl,
1751 			  tree* targs_out,
1752 			  int need_member_template,
1753 			  int template_count,
1754 			  tmpl_spec_kind tsk)
1755 {
1756   tree fns;
1757   tree targs;
1758   tree explicit_targs;
1759   tree candidates = NULL_TREE;
1760   /* A TREE_LIST of templates of which DECL may be a specialization.
1761      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1762      corresponding TREE_PURPOSE is the set of template arguments that,
1763      when used to instantiate the template, would produce a function
1764      with the signature of DECL.  */
1765   tree templates = NULL_TREE;
1766   int header_count;
1767   struct cp_binding_level *b;
1768 
1769   *targs_out = NULL_TREE;
1770 
1771   if (template_id == error_mark_node || decl == error_mark_node)
1772     return error_mark_node;
1773 
1774   fns = TREE_OPERAND (template_id, 0);
1775   explicit_targs = TREE_OPERAND (template_id, 1);
1776 
1777   if (fns == error_mark_node)
1778     return error_mark_node;
1779 
1780   /* Check for baselinks.  */
1781   if (BASELINK_P (fns))
1782     fns = BASELINK_FUNCTIONS (fns);
1783 
1784   if (!is_overloaded_fn (fns))
1785     {
1786       error ("%qD is not a function template", fns);
1787       return error_mark_node;
1788     }
1789 
1790   /* Count the number of template headers specified for this
1791      specialization.  */
1792   header_count = 0;
1793   for (b = current_binding_level;
1794        b->kind == sk_template_parms;
1795        b = b->level_chain)
1796     ++header_count;
1797 
1798   for (; fns; fns = OVL_NEXT (fns))
1799     {
1800       tree fn = OVL_CURRENT (fns);
1801 
1802       if (TREE_CODE (fn) == TEMPLATE_DECL)
1803 	{
1804 	  tree decl_arg_types;
1805 	  tree fn_arg_types;
1806 
1807 	  /* In case of explicit specialization, we need to check if
1808 	     the number of template headers appearing in the specialization
1809 	     is correct. This is usually done in check_explicit_specialization,
1810 	     but the check done there cannot be exhaustive when specializing
1811 	     member functions. Consider the following code:
1812 
1813 	     template <> void A<int>::f(int);
1814 	     template <> template <> void A<int>::f(int);
1815 
1816 	     Assuming that A<int> is not itself an explicit specialization
1817 	     already, the first line specializes "f" which is a non-template
1818 	     member function, whilst the second line specializes "f" which
1819 	     is a template member function. So both lines are syntactically
1820 	     correct, and check_explicit_specialization does not reject
1821 	     them.
1822 
1823 	     Here, we can do better, as we are matching the specialization
1824 	     against the declarations. We count the number of template
1825 	     headers, and we check if they match TEMPLATE_COUNT + 1
1826 	     (TEMPLATE_COUNT is the number of qualifying template classes,
1827 	     plus there must be another header for the member template
1828 	     itself).
1829 
1830 	     Notice that if header_count is zero, this is not a
1831 	     specialization but rather a template instantiation, so there
1832 	     is no check we can perform here.  */
1833 	  if (header_count && header_count != template_count + 1)
1834 	    continue;
1835 
1836 	  /* Check that the number of template arguments at the
1837 	     innermost level for DECL is the same as for FN.  */
1838 	  if (current_binding_level->kind == sk_template_parms
1839 	      && !current_binding_level->explicit_spec_p
1840 	      && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1841 		  != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1842 				      (current_template_parms))))
1843 	    continue;
1844 
1845 	  /* DECL might be a specialization of FN.  */
1846 	  decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1847 	  fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1848 
1849 	  /* For a non-static member function, we need to make sure
1850 	     that the const qualification is the same.  Since
1851 	     get_bindings does not try to merge the "this" parameter,
1852 	     we must do the comparison explicitly.  */
1853 	  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1854 	      && !same_type_p (TREE_VALUE (fn_arg_types),
1855 			       TREE_VALUE (decl_arg_types)))
1856 	    continue;
1857 
1858 	  /* Skip the "this" parameter and, for constructors of
1859 	     classes with virtual bases, the VTT parameter.  A
1860 	     full specialization of a constructor will have a VTT
1861 	     parameter, but a template never will.  */
1862 	  decl_arg_types
1863 	    = skip_artificial_parms_for (decl, decl_arg_types);
1864 	  fn_arg_types
1865 	    = skip_artificial_parms_for (fn, fn_arg_types);
1866 
1867 	  /* Check that the number of function parameters matches.
1868 	     For example,
1869 	       template <class T> void f(int i = 0);
1870 	       template <> void f<int>();
1871 	     The specialization f<int> is invalid but is not caught
1872 	     by get_bindings below.  */
1873 	  if (list_length (fn_arg_types) != list_length (decl_arg_types))
1874 	    continue;
1875 
1876 	  /* Function templates cannot be specializations; there are
1877 	     no partial specializations of functions.  Therefore, if
1878 	     the type of DECL does not match FN, there is no
1879 	     match.  */
1880 	  if (tsk == tsk_template)
1881 	    {
1882 	      if (compparms (fn_arg_types, decl_arg_types))
1883 		candidates = tree_cons (NULL_TREE, fn, candidates);
1884 	      continue;
1885 	    }
1886 
1887 	  /* See whether this function might be a specialization of this
1888 	     template.  */
1889 	  targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1890 
1891 	  if (!targs)
1892 	    /* We cannot deduce template arguments that when used to
1893 	       specialize TMPL will produce DECL.  */
1894 	    continue;
1895 
1896 	  /* Save this template, and the arguments deduced.  */
1897 	  templates = tree_cons (targs, fn, templates);
1898 	}
1899       else if (need_member_template)
1900 	/* FN is an ordinary member function, and we need a
1901 	   specialization of a member template.  */
1902 	;
1903       else if (TREE_CODE (fn) != FUNCTION_DECL)
1904 	/* We can get IDENTIFIER_NODEs here in certain erroneous
1905 	   cases.  */
1906 	;
1907       else if (!DECL_FUNCTION_MEMBER_P (fn))
1908 	/* This is just an ordinary non-member function.  Nothing can
1909 	   be a specialization of that.  */
1910 	;
1911       else if (DECL_ARTIFICIAL (fn))
1912 	/* Cannot specialize functions that are created implicitly.  */
1913 	;
1914       else
1915 	{
1916 	  tree decl_arg_types;
1917 
1918 	  /* This is an ordinary member function.  However, since
1919 	     we're here, we can assume it's enclosing class is a
1920 	     template class.  For example,
1921 
1922 	       template <typename T> struct S { void f(); };
1923 	       template <> void S<int>::f() {}
1924 
1925 	     Here, S<int>::f is a non-template, but S<int> is a
1926 	     template class.  If FN has the same type as DECL, we
1927 	     might be in business.  */
1928 
1929 	  if (!DECL_TEMPLATE_INFO (fn))
1930 	    /* Its enclosing class is an explicit specialization
1931 	       of a template class.  This is not a candidate.  */
1932 	    continue;
1933 
1934 	  if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1935 			    TREE_TYPE (TREE_TYPE (fn))))
1936 	    /* The return types differ.  */
1937 	    continue;
1938 
1939 	  /* Adjust the type of DECL in case FN is a static member.  */
1940 	  decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1941 	  if (DECL_STATIC_FUNCTION_P (fn)
1942 	      && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1943 	    decl_arg_types = TREE_CHAIN (decl_arg_types);
1944 
1945 	  if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1946 			 decl_arg_types))
1947 	    /* They match!  */
1948 	    candidates = tree_cons (NULL_TREE, fn, candidates);
1949 	}
1950     }
1951 
1952   if (templates && TREE_CHAIN (templates))
1953     {
1954       /* We have:
1955 
1956 	   [temp.expl.spec]
1957 
1958 	   It is possible for a specialization with a given function
1959 	   signature to be instantiated from more than one function
1960 	   template.  In such cases, explicit specification of the
1961 	   template arguments must be used to uniquely identify the
1962 	   function template specialization being specialized.
1963 
1964 	 Note that here, there's no suggestion that we're supposed to
1965 	 determine which of the candidate templates is most
1966 	 specialized.  However, we, also have:
1967 
1968 	   [temp.func.order]
1969 
1970 	   Partial ordering of overloaded function template
1971 	   declarations is used in the following contexts to select
1972 	   the function template to which a function template
1973 	   specialization refers:
1974 
1975 	   -- when an explicit specialization refers to a function
1976 	      template.
1977 
1978 	 So, we do use the partial ordering rules, at least for now.
1979 	 This extension can only serve to make invalid programs valid,
1980 	 so it's safe.  And, there is strong anecdotal evidence that
1981 	 the committee intended the partial ordering rules to apply;
1982 	 the EDG front end has that behavior, and John Spicer claims
1983 	 that the committee simply forgot to delete the wording in
1984 	 [temp.expl.spec].  */
1985       tree tmpl = most_specialized_instantiation (templates);
1986       if (tmpl != error_mark_node)
1987 	{
1988 	  templates = tmpl;
1989 	  TREE_CHAIN (templates) = NULL_TREE;
1990 	}
1991     }
1992 
1993   if (templates == NULL_TREE && candidates == NULL_TREE)
1994     {
1995       error ("template-id %qD for %q+D does not match any template "
1996 	     "declaration", template_id, decl);
1997       if (header_count && header_count != template_count + 1)
1998 	inform (input_location, "saw %d %<template<>%>, need %d for "
1999 		"specializing a member function template",
2000 		header_count, template_count + 1);
2001       return error_mark_node;
2002     }
2003   else if ((templates && TREE_CHAIN (templates))
2004 	   || (candidates && TREE_CHAIN (candidates))
2005 	   || (templates && candidates))
2006     {
2007       error ("ambiguous template specialization %qD for %q+D",
2008 	     template_id, decl);
2009       candidates = chainon (candidates, templates);
2010       print_candidates (candidates);
2011       return error_mark_node;
2012     }
2013 
2014   /* We have one, and exactly one, match.  */
2015   if (candidates)
2016     {
2017       tree fn = TREE_VALUE (candidates);
2018       *targs_out = copy_node (DECL_TI_ARGS (fn));
2019       /* DECL is a re-declaration or partial instantiation of a template
2020 	 function.  */
2021       if (TREE_CODE (fn) == TEMPLATE_DECL)
2022 	return fn;
2023       /* It was a specialization of an ordinary member function in a
2024 	 template class.  */
2025       return DECL_TI_TEMPLATE (fn);
2026     }
2027 
2028   /* It was a specialization of a template.  */
2029   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2030   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2031     {
2032       *targs_out = copy_node (targs);
2033       SET_TMPL_ARGS_LEVEL (*targs_out,
2034 			   TMPL_ARGS_DEPTH (*targs_out),
2035 			   TREE_PURPOSE (templates));
2036     }
2037   else
2038     *targs_out = TREE_PURPOSE (templates);
2039   return TREE_VALUE (templates);
2040 }
2041 
2042 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2043    but with the default argument values filled in from those in the
2044    TMPL_TYPES.  */
2045 
2046 static tree
2047 copy_default_args_to_explicit_spec_1 (tree spec_types,
2048 				      tree tmpl_types)
2049 {
2050   tree new_spec_types;
2051 
2052   if (!spec_types)
2053     return NULL_TREE;
2054 
2055   if (spec_types == void_list_node)
2056     return void_list_node;
2057 
2058   /* Substitute into the rest of the list.  */
2059   new_spec_types =
2060     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2061 					  TREE_CHAIN (tmpl_types));
2062 
2063   /* Add the default argument for this parameter.  */
2064   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2065 			 TREE_VALUE (spec_types),
2066 			 new_spec_types);
2067 }
2068 
2069 /* DECL is an explicit specialization.  Replicate default arguments
2070    from the template it specializes.  (That way, code like:
2071 
2072      template <class T> void f(T = 3);
2073      template <> void f(double);
2074      void g () { f (); }
2075 
2076    works, as required.)  An alternative approach would be to look up
2077    the correct default arguments at the call-site, but this approach
2078    is consistent with how implicit instantiations are handled.  */
2079 
2080 static void
2081 copy_default_args_to_explicit_spec (tree decl)
2082 {
2083   tree tmpl;
2084   tree spec_types;
2085   tree tmpl_types;
2086   tree new_spec_types;
2087   tree old_type;
2088   tree new_type;
2089   tree t;
2090   tree object_type = NULL_TREE;
2091   tree in_charge = NULL_TREE;
2092   tree vtt = NULL_TREE;
2093 
2094   /* See if there's anything we need to do.  */
2095   tmpl = DECL_TI_TEMPLATE (decl);
2096   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2097   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2098     if (TREE_PURPOSE (t))
2099       break;
2100   if (!t)
2101     return;
2102 
2103   old_type = TREE_TYPE (decl);
2104   spec_types = TYPE_ARG_TYPES (old_type);
2105 
2106   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2107     {
2108       /* Remove the this pointer, but remember the object's type for
2109 	 CV quals.  */
2110       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2111       spec_types = TREE_CHAIN (spec_types);
2112       tmpl_types = TREE_CHAIN (tmpl_types);
2113 
2114       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2115 	{
2116 	  /* DECL may contain more parameters than TMPL due to the extra
2117 	     in-charge parameter in constructors and destructors.  */
2118 	  in_charge = spec_types;
2119 	  spec_types = TREE_CHAIN (spec_types);
2120 	}
2121       if (DECL_HAS_VTT_PARM_P (decl))
2122 	{
2123 	  vtt = spec_types;
2124 	  spec_types = TREE_CHAIN (spec_types);
2125 	}
2126     }
2127 
2128   /* Compute the merged default arguments.  */
2129   new_spec_types =
2130     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2131 
2132   /* Compute the new FUNCTION_TYPE.  */
2133   if (object_type)
2134     {
2135       if (vtt)
2136 	new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2137 					 TREE_VALUE (vtt),
2138 					 new_spec_types);
2139 
2140       if (in_charge)
2141 	/* Put the in-charge parameter back.  */
2142 	new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2143 					 TREE_VALUE (in_charge),
2144 					 new_spec_types);
2145 
2146       new_type = build_method_type_directly (object_type,
2147 					     TREE_TYPE (old_type),
2148 					     new_spec_types);
2149     }
2150   else
2151     new_type = build_function_type (TREE_TYPE (old_type),
2152 				    new_spec_types);
2153   new_type = cp_build_type_attribute_variant (new_type,
2154 					      TYPE_ATTRIBUTES (old_type));
2155   new_type = build_exception_variant (new_type,
2156 				      TYPE_RAISES_EXCEPTIONS (old_type));
2157   TREE_TYPE (decl) = new_type;
2158 }
2159 
2160 /* Check to see if the function just declared, as indicated in
2161    DECLARATOR, and in DECL, is a specialization of a function
2162    template.  We may also discover that the declaration is an explicit
2163    instantiation at this point.
2164 
2165    Returns DECL, or an equivalent declaration that should be used
2166    instead if all goes well.  Issues an error message if something is
2167    amiss.  Returns error_mark_node if the error is not easily
2168    recoverable.
2169 
2170    FLAGS is a bitmask consisting of the following flags:
2171 
2172    2: The function has a definition.
2173    4: The function is a friend.
2174 
2175    The TEMPLATE_COUNT is the number of references to qualifying
2176    template classes that appeared in the name of the function.  For
2177    example, in
2178 
2179      template <class T> struct S { void f(); };
2180      void S<int>::f();
2181 
2182    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2183    classes are not counted in the TEMPLATE_COUNT, so that in
2184 
2185      template <class T> struct S {};
2186      template <> struct S<int> { void f(); }
2187      template <> void S<int>::f();
2188 
2189    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2190    invalid; there should be no template <>.)
2191 
2192    If the function is a specialization, it is marked as such via
2193    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2194    is set up correctly, and it is added to the list of specializations
2195    for that template.  */
2196 
2197 tree
2198 check_explicit_specialization (tree declarator,
2199 			       tree decl,
2200 			       int template_count,
2201 			       int flags)
2202 {
2203   int have_def = flags & 2;
2204   int is_friend = flags & 4;
2205   int specialization = 0;
2206   int explicit_instantiation = 0;
2207   int member_specialization = 0;
2208   tree ctype = DECL_CLASS_CONTEXT (decl);
2209   tree dname = DECL_NAME (decl);
2210   tmpl_spec_kind tsk;
2211 
2212   if (is_friend)
2213     {
2214       if (!processing_specialization)
2215 	tsk = tsk_none;
2216       else
2217 	tsk = tsk_excessive_parms;
2218     }
2219   else
2220     tsk = current_tmpl_spec_kind (template_count);
2221 
2222   switch (tsk)
2223     {
2224     case tsk_none:
2225       if (processing_specialization)
2226 	{
2227 	  specialization = 1;
2228 	  SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2229 	}
2230       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2231 	{
2232 	  if (is_friend)
2233 	    /* This could be something like:
2234 
2235 	       template <class T> void f(T);
2236 	       class S { friend void f<>(int); }  */
2237 	    specialization = 1;
2238 	  else
2239 	    {
2240 	      /* This case handles bogus declarations like template <>
2241 		 template <class T> void f<int>(); */
2242 
2243 	      error ("template-id %qD in declaration of primary template",
2244 		     declarator);
2245 	      return decl;
2246 	    }
2247 	}
2248       break;
2249 
2250     case tsk_invalid_member_spec:
2251       /* The error has already been reported in
2252 	 check_specialization_scope.  */
2253       return error_mark_node;
2254 
2255     case tsk_invalid_expl_inst:
2256       error ("template parameter list used in explicit instantiation");
2257 
2258       /* Fall through.  */
2259 
2260     case tsk_expl_inst:
2261       if (have_def)
2262 	error ("definition provided for explicit instantiation");
2263 
2264       explicit_instantiation = 1;
2265       break;
2266 
2267     case tsk_excessive_parms:
2268     case tsk_insufficient_parms:
2269       if (tsk == tsk_excessive_parms)
2270 	error ("too many template parameter lists in declaration of %qD",
2271 	       decl);
2272       else if (template_header_count)
2273 	error("too few template parameter lists in declaration of %qD", decl);
2274       else
2275 	error("explicit specialization of %qD must be introduced by "
2276 	      "%<template <>%>", decl);
2277 
2278       /* Fall through.  */
2279     case tsk_expl_spec:
2280       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2281       if (ctype)
2282 	member_specialization = 1;
2283       else
2284 	specialization = 1;
2285       break;
2286 
2287     case tsk_template:
2288       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2289 	{
2290 	  /* This case handles bogus declarations like template <>
2291 	     template <class T> void f<int>(); */
2292 
2293 	  if (uses_template_parms (declarator))
2294 	    error ("function template partial specialization %qD "
2295 		   "is not allowed", declarator);
2296 	  else
2297 	    error ("template-id %qD in declaration of primary template",
2298 		   declarator);
2299 	  return decl;
2300 	}
2301 
2302       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2303 	/* This is a specialization of a member template, without
2304 	   specialization the containing class.  Something like:
2305 
2306 	     template <class T> struct S {
2307 	       template <class U> void f (U);
2308 	     };
2309 	     template <> template <class U> void S<int>::f(U) {}
2310 
2311 	   That's a specialization -- but of the entire template.  */
2312 	specialization = 1;
2313       break;
2314 
2315     default:
2316       gcc_unreachable ();
2317     }
2318 
2319   if (specialization || member_specialization)
2320     {
2321       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2322       for (; t; t = TREE_CHAIN (t))
2323 	if (TREE_PURPOSE (t))
2324 	  {
2325 	    permerror (input_location,
2326 		       "default argument specified in explicit specialization");
2327 	    break;
2328 	  }
2329     }
2330 
2331   if (specialization || member_specialization || explicit_instantiation)
2332     {
2333       tree tmpl = NULL_TREE;
2334       tree targs = NULL_TREE;
2335 
2336       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2337       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2338 	{
2339 	  tree fns;
2340 
2341 	  gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2342 	  if (ctype)
2343 	    fns = dname;
2344 	  else
2345 	    {
2346 	      /* If there is no class context, the explicit instantiation
2347 		 must be at namespace scope.  */
2348 	      gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2349 
2350 	      /* Find the namespace binding, using the declaration
2351 		 context.  */
2352 	      fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2353 					   false, true);
2354 	      if (fns == error_mark_node || !is_overloaded_fn (fns))
2355 		{
2356 		  error ("%qD is not a template function", dname);
2357 		  fns = error_mark_node;
2358 		}
2359 	      else
2360 		{
2361 		  tree fn = OVL_CURRENT (fns);
2362 		  if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2363 						CP_DECL_CONTEXT (fn)))
2364 		    error ("%qD is not declared in %qD",
2365 			   decl, current_namespace);
2366 		}
2367 	    }
2368 
2369 	  declarator = lookup_template_function (fns, NULL_TREE);
2370 	}
2371 
2372       if (declarator == error_mark_node)
2373 	return error_mark_node;
2374 
2375       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2376 	{
2377 	  if (!explicit_instantiation)
2378 	    /* A specialization in class scope.  This is invalid,
2379 	       but the error will already have been flagged by
2380 	       check_specialization_scope.  */
2381 	    return error_mark_node;
2382 	  else
2383 	    {
2384 	      /* It's not valid to write an explicit instantiation in
2385 		 class scope, e.g.:
2386 
2387 		   class C { template void f(); }
2388 
2389 		   This case is caught by the parser.  However, on
2390 		   something like:
2391 
2392 		   template class C { void f(); };
2393 
2394 		   (which is invalid) we can get here.  The error will be
2395 		   issued later.  */
2396 	      ;
2397 	    }
2398 
2399 	  return decl;
2400 	}
2401       else if (ctype != NULL_TREE
2402 	       && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2403 		   IDENTIFIER_NODE))
2404 	{
2405 	  /* Find the list of functions in ctype that have the same
2406 	     name as the declared function.  */
2407 	  tree name = TREE_OPERAND (declarator, 0);
2408 	  tree fns = NULL_TREE;
2409 	  int idx;
2410 
2411 	  if (constructor_name_p (name, ctype))
2412 	    {
2413 	      int is_constructor = DECL_CONSTRUCTOR_P (decl);
2414 
2415 	      if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2416 		  : !CLASSTYPE_DESTRUCTORS (ctype))
2417 		{
2418 		  /* From [temp.expl.spec]:
2419 
2420 		     If such an explicit specialization for the member
2421 		     of a class template names an implicitly-declared
2422 		     special member function (clause _special_), the
2423 		     program is ill-formed.
2424 
2425 		     Similar language is found in [temp.explicit].  */
2426 		  error ("specialization of implicitly-declared special member function");
2427 		  return error_mark_node;
2428 		}
2429 
2430 	      name = is_constructor ? ctor_identifier : dtor_identifier;
2431 	    }
2432 
2433 	  if (!DECL_CONV_FN_P (decl))
2434 	    {
2435 	      idx = lookup_fnfields_1 (ctype, name);
2436 	      if (idx >= 0)
2437 		fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2438 	    }
2439 	  else
2440 	    {
2441 	      VEC(tree,gc) *methods;
2442 	      tree ovl;
2443 
2444 	      /* For a type-conversion operator, we cannot do a
2445 		 name-based lookup.  We might be looking for `operator
2446 		 int' which will be a specialization of `operator T'.
2447 		 So, we find *all* the conversion operators, and then
2448 		 select from them.  */
2449 	      fns = NULL_TREE;
2450 
2451 	      methods = CLASSTYPE_METHOD_VEC (ctype);
2452 	      if (methods)
2453 		for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2454 		     VEC_iterate (tree, methods, idx, ovl);
2455 		     ++idx)
2456 		  {
2457 		    if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2458 		      /* There are no more conversion functions.  */
2459 		      break;
2460 
2461 		    /* Glue all these conversion functions together
2462 		       with those we already have.  */
2463 		    for (; ovl; ovl = OVL_NEXT (ovl))
2464 		      fns = ovl_cons (OVL_CURRENT (ovl), fns);
2465 		  }
2466 	    }
2467 
2468 	  if (fns == NULL_TREE)
2469 	    {
2470 	      error ("no member function %qD declared in %qT", name, ctype);
2471 	      return error_mark_node;
2472 	    }
2473 	  else
2474 	    TREE_OPERAND (declarator, 0) = fns;
2475 	}
2476 
2477       /* Figure out what exactly is being specialized at this point.
2478 	 Note that for an explicit instantiation, even one for a
2479 	 member function, we cannot tell apriori whether the
2480 	 instantiation is for a member template, or just a member
2481 	 function of a template class.  Even if a member template is
2482 	 being instantiated, the member template arguments may be
2483 	 elided if they can be deduced from the rest of the
2484 	 declaration.  */
2485       tmpl = determine_specialization (declarator, decl,
2486 				       &targs,
2487 				       member_specialization,
2488 				       template_count,
2489 				       tsk);
2490 
2491       if (!tmpl || tmpl == error_mark_node)
2492 	/* We couldn't figure out what this declaration was
2493 	   specializing.  */
2494 	return error_mark_node;
2495       else
2496 	{
2497 	  tree gen_tmpl = most_general_template (tmpl);
2498 
2499 	  if (explicit_instantiation)
2500 	    {
2501 	      /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2502 		 is done by do_decl_instantiation later.  */
2503 
2504 	      int arg_depth = TMPL_ARGS_DEPTH (targs);
2505 	      int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2506 
2507 	      if (arg_depth > parm_depth)
2508 		{
2509 		  /* If TMPL is not the most general template (for
2510 		     example, if TMPL is a friend template that is
2511 		     injected into namespace scope), then there will
2512 		     be too many levels of TARGS.  Remove some of them
2513 		     here.  */
2514 		  int i;
2515 		  tree new_targs;
2516 
2517 		  new_targs = make_tree_vec (parm_depth);
2518 		  for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2519 		    TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2520 		      = TREE_VEC_ELT (targs, i);
2521 		  targs = new_targs;
2522 		}
2523 
2524 	      return instantiate_template (tmpl, targs, tf_error);
2525 	    }
2526 
2527 	  /* If we thought that the DECL was a member function, but it
2528 	     turns out to be specializing a static member function,
2529 	     make DECL a static member function as well.  */
2530 	  if (DECL_STATIC_FUNCTION_P (tmpl)
2531 	      && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2532 	    revert_static_member_fn (decl);
2533 
2534 	  /* If this is a specialization of a member template of a
2535 	     template class, we want to return the TEMPLATE_DECL, not
2536 	     the specialization of it.  */
2537 	  if (tsk == tsk_template)
2538 	    {
2539 	      tree result = DECL_TEMPLATE_RESULT (tmpl);
2540 	      SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2541 	      DECL_INITIAL (result) = NULL_TREE;
2542 	      if (have_def)
2543 		{
2544 		  tree parm;
2545 		  DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2546 		  DECL_SOURCE_LOCATION (result)
2547 		    = DECL_SOURCE_LOCATION (decl);
2548 		  /* We want to use the argument list specified in the
2549 		     definition, not in the original declaration.  */
2550 		  DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2551 		  for (parm = DECL_ARGUMENTS (result); parm;
2552 		       parm = TREE_CHAIN (parm))
2553 		    DECL_CONTEXT (parm) = result;
2554 		}
2555 	      return register_specialization (tmpl, gen_tmpl, targs,
2556 					      is_friend, 0);
2557 	    }
2558 
2559 	  /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2560 	  DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
2561 
2562 	  /* Inherit default function arguments from the template
2563 	     DECL is specializing.  */
2564 	  copy_default_args_to_explicit_spec (decl);
2565 
2566 	  /* This specialization has the same protection as the
2567 	     template it specializes.  */
2568 	  TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2569 	  TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2570 
2571           /* 7.1.1-1 [dcl.stc]
2572 
2573              A storage-class-specifier shall not be specified in an
2574              explicit specialization...
2575 
2576              The parser rejects these, so unless action is taken here,
2577              explicit function specializations will always appear with
2578              global linkage.
2579 
2580              The action recommended by the C++ CWG in response to C++
2581              defect report 605 is to make the storage class and linkage
2582              of the explicit specialization match the templated function:
2583 
2584              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2585            */
2586           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2587             {
2588               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2589               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2590 
2591               /* This specialization has the same linkage and visibility as
2592                  the function template it specializes.  */
2593               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2594 	      if (! TREE_PUBLIC (decl))
2595 		{
2596 		  DECL_INTERFACE_KNOWN (decl) = 1;
2597 		  DECL_NOT_REALLY_EXTERN (decl) = 1;
2598 		}
2599               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2600               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2601                 {
2602                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2603                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2604                 }
2605             }
2606 
2607 	  /* If DECL is a friend declaration, declared using an
2608 	     unqualified name, the namespace associated with DECL may
2609 	     have been set incorrectly.  For example, in:
2610 
2611 	       template <typename T> void f(T);
2612 	       namespace N {
2613 		 struct S { friend void f<int>(int); }
2614 	       }
2615 
2616 	     we will have set the DECL_CONTEXT for the friend
2617 	     declaration to N, rather than to the global namespace.  */
2618 	  if (DECL_NAMESPACE_SCOPE_P (decl))
2619 	    DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2620 
2621 	  if (is_friend && !have_def)
2622 	    /* This is not really a declaration of a specialization.
2623 	       It's just the name of an instantiation.  But, it's not
2624 	       a request for an instantiation, either.  */
2625 	    SET_DECL_IMPLICIT_INSTANTIATION (decl);
2626 	  else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2627 	    /* This is indeed a specialization.  In case of constructors
2628 	       and destructors, we need in-charge and not-in-charge
2629 	       versions in V3 ABI.  */
2630 	    clone_function_decl (decl, /*update_method_vec_p=*/0);
2631 
2632 	  /* Register this specialization so that we can find it
2633 	     again.  */
2634 	  decl = register_specialization (decl, gen_tmpl, targs, is_friend, 0);
2635 	}
2636     }
2637 
2638   return decl;
2639 }
2640 
2641 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2642    parameters.  These are represented in the same format used for
2643    DECL_TEMPLATE_PARMS.  */
2644 
2645 int
2646 comp_template_parms (const_tree parms1, const_tree parms2)
2647 {
2648   const_tree p1;
2649   const_tree p2;
2650 
2651   if (parms1 == parms2)
2652     return 1;
2653 
2654   for (p1 = parms1, p2 = parms2;
2655        p1 != NULL_TREE && p2 != NULL_TREE;
2656        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2657     {
2658       tree t1 = TREE_VALUE (p1);
2659       tree t2 = TREE_VALUE (p2);
2660       int i;
2661 
2662       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2663       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2664 
2665       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2666 	return 0;
2667 
2668       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2669 	{
2670           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2671           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2672 
2673           /* If either of the template parameters are invalid, assume
2674              they match for the sake of error recovery. */
2675           if (parm1 == error_mark_node || parm2 == error_mark_node)
2676             return 1;
2677 
2678 	  if (TREE_CODE (parm1) != TREE_CODE (parm2))
2679 	    return 0;
2680 
2681 	  if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2682               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2683                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2684 	    continue;
2685 	  else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2686 	    return 0;
2687 	}
2688     }
2689 
2690   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2691     /* One set of parameters has more parameters lists than the
2692        other.  */
2693     return 0;
2694 
2695   return 1;
2696 }
2697 
2698 /* Determine whether PARM is a parameter pack.  */
2699 
2700 bool
2701 template_parameter_pack_p (const_tree parm)
2702 {
2703   /* Determine if we have a non-type template parameter pack.  */
2704   if (TREE_CODE (parm) == PARM_DECL)
2705     return (DECL_TEMPLATE_PARM_P (parm)
2706             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2707 
2708   /* If this is a list of template parameters, we could get a
2709      TYPE_DECL or a TEMPLATE_DECL.  */
2710   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2711     parm = TREE_TYPE (parm);
2712 
2713   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2714 	   || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2715 	  && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2716 }
2717 
2718 /* Determine if T is a function parameter pack.  */
2719 
2720 bool
2721 function_parameter_pack_p (const_tree t)
2722 {
2723   if (t && TREE_CODE (t) == PARM_DECL)
2724     return FUNCTION_PARAMETER_PACK_P (t);
2725   return false;
2726 }
2727 
2728 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
2729    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
2730 
2731 tree
2732 get_function_template_decl (const_tree primary_func_tmpl_inst)
2733 {
2734   if (! primary_func_tmpl_inst
2735       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
2736       || ! primary_template_instantiation_p (primary_func_tmpl_inst))
2737     return NULL;
2738 
2739   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
2740 }
2741 
2742 /* Return true iff the function parameter PARAM_DECL was expanded
2743    from the function parameter pack PACK.  */
2744 
2745 bool
2746 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
2747 {
2748   if (DECL_ARTIFICIAL (param_decl)
2749       || !function_parameter_pack_p (pack))
2750     return false;
2751 
2752   /* The parameter pack and its pack arguments have the same
2753      DECL_PARM_INDEX.  */
2754   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
2755 }
2756 
2757 /* Determine whether ARGS describes a variadic template args list,
2758    i.e., one that is terminated by a template argument pack.  */
2759 
2760 static bool
2761 template_args_variadic_p (tree args)
2762 {
2763   int nargs;
2764   tree last_parm;
2765 
2766   if (args == NULL_TREE)
2767     return false;
2768 
2769   args = INNERMOST_TEMPLATE_ARGS (args);
2770   nargs = TREE_VEC_LENGTH (args);
2771 
2772   if (nargs == 0)
2773     return false;
2774 
2775   last_parm = TREE_VEC_ELT (args, nargs - 1);
2776 
2777   return ARGUMENT_PACK_P (last_parm);
2778 }
2779 
2780 /* Generate a new name for the parameter pack name NAME (an
2781    IDENTIFIER_NODE) that incorporates its */
2782 
2783 static tree
2784 make_ith_pack_parameter_name (tree name, int i)
2785 {
2786   /* Munge the name to include the parameter index.  */
2787 #define NUMBUF_LEN 128
2788   char numbuf[NUMBUF_LEN];
2789   char* newname;
2790   int newname_len;
2791 
2792   snprintf (numbuf, NUMBUF_LEN, "%i", i);
2793   newname_len = IDENTIFIER_LENGTH (name)
2794 	        + strlen (numbuf) + 2;
2795   newname = (char*)alloca (newname_len);
2796   snprintf (newname, newname_len,
2797 	    "%s#%i", IDENTIFIER_POINTER (name), i);
2798   return get_identifier (newname);
2799 }
2800 
2801 /* Return true if T is a primary function
2802    or class template instantiation.  */
2803 
2804 bool
2805 primary_template_instantiation_p (const_tree t)
2806 {
2807   if (!t)
2808     return false;
2809 
2810   if (TREE_CODE (t) == FUNCTION_DECL)
2811     return DECL_LANG_SPECIFIC (t)
2812 	   && DECL_TEMPLATE_INSTANTIATION (t)
2813 	   && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t));
2814   else if (CLASS_TYPE_P (t))
2815     return CLASSTYPE_TEMPLATE_INSTANTIATION (t)
2816 	   && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t));
2817   return false;
2818 }
2819 
2820 /* Return true if PARM is a template template parameter.  */
2821 
2822 bool
2823 template_template_parameter_p (const_tree parm)
2824 {
2825   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
2826 }
2827 
2828 /* Return the template parameters of T if T is a
2829    primary template instantiation, NULL otherwise.  */
2830 
2831 tree
2832 get_primary_template_innermost_parameters (const_tree t)
2833 {
2834   tree parms = NULL, template_info = NULL;
2835 
2836   if ((template_info = get_template_info (t))
2837       && primary_template_instantiation_p (t))
2838     parms = INNERMOST_TEMPLATE_PARMS
2839 	(DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
2840 
2841   return parms;
2842 }
2843 
2844 /* Return the template parameters of the LEVELth level from the full list
2845    of template parameters PARMS.  */
2846 
2847 tree
2848 get_template_parms_at_level (tree parms, int level)
2849 {
2850   tree p;
2851   if (!parms
2852       || TREE_CODE (parms) != TREE_LIST
2853       || level > TMPL_PARMS_DEPTH (parms))
2854     return NULL_TREE;
2855 
2856   for (p = parms; p; p = TREE_CHAIN (p))
2857     if (TMPL_PARMS_DEPTH (p) == level)
2858       return p;
2859 
2860   return NULL_TREE;
2861 }
2862 
2863 /* Returns the template arguments of T if T is a template instantiation,
2864    NULL otherwise.  */
2865 
2866 tree
2867 get_template_innermost_arguments (const_tree t)
2868 {
2869   tree args = NULL, template_info = NULL;
2870 
2871   if ((template_info = get_template_info (t))
2872       && TI_ARGS (template_info))
2873     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
2874 
2875   return args;
2876 }
2877 
2878 /* Return the argument pack elements of T if T is a template argument pack,
2879    NULL otherwise.  */
2880 
2881 tree
2882 get_template_argument_pack_elems (const_tree t)
2883 {
2884   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
2885       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
2886     return NULL;
2887 
2888   return ARGUMENT_PACK_ARGS (t);
2889 }
2890 
2891 /* Structure used to track the progress of find_parameter_packs_r.  */
2892 struct find_parameter_pack_data
2893 {
2894   /* TREE_LIST that will contain all of the parameter packs found by
2895      the traversal.  */
2896   tree* parameter_packs;
2897 
2898   /* Set of AST nodes that have been visited by the traversal.  */
2899   struct pointer_set_t *visited;
2900 };
2901 
2902 /* Identifies all of the argument packs that occur in a template
2903    argument and appends them to the TREE_LIST inside DATA, which is a
2904    find_parameter_pack_data structure. This is a subroutine of
2905    make_pack_expansion and uses_parameter_packs.  */
2906 static tree
2907 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2908 {
2909   tree t = *tp;
2910   struct find_parameter_pack_data* ppd =
2911     (struct find_parameter_pack_data*)data;
2912   bool parameter_pack_p = false;
2913 
2914   /* Identify whether this is a parameter pack or not.  */
2915   switch (TREE_CODE (t))
2916     {
2917     case TEMPLATE_PARM_INDEX:
2918       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2919         parameter_pack_p = true;
2920       break;
2921 
2922     case TEMPLATE_TYPE_PARM:
2923     case TEMPLATE_TEMPLATE_PARM:
2924       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2925         parameter_pack_p = true;
2926       break;
2927 
2928     case PARM_DECL:
2929       if (FUNCTION_PARAMETER_PACK_P (t))
2930         {
2931           /* We don't want to walk into the type of a PARM_DECL,
2932              because we don't want to see the type parameter pack.  */
2933           *walk_subtrees = 0;
2934 	  parameter_pack_p = true;
2935         }
2936       break;
2937 
2938     default:
2939       /* Not a parameter pack.  */
2940       break;
2941     }
2942 
2943   if (parameter_pack_p)
2944     {
2945       /* Add this parameter pack to the list.  */
2946       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2947     }
2948 
2949   if (TYPE_P (t))
2950     cp_walk_tree (&TYPE_CONTEXT (t),
2951 		  &find_parameter_packs_r, ppd, ppd->visited);
2952 
2953   /* This switch statement will return immediately if we don't find a
2954      parameter pack.  */
2955   switch (TREE_CODE (t))
2956     {
2957     case TEMPLATE_PARM_INDEX:
2958       return NULL_TREE;
2959 
2960     case BOUND_TEMPLATE_TEMPLATE_PARM:
2961       /* Check the template itself.  */
2962       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)),
2963 		    &find_parameter_packs_r, ppd, ppd->visited);
2964       /* Check the template arguments.  */
2965       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd,
2966 		    ppd->visited);
2967       *walk_subtrees = 0;
2968       return NULL_TREE;
2969 
2970     case TEMPLATE_TYPE_PARM:
2971     case TEMPLATE_TEMPLATE_PARM:
2972       return NULL_TREE;
2973 
2974     case PARM_DECL:
2975       return NULL_TREE;
2976 
2977     case RECORD_TYPE:
2978       if (TYPE_PTRMEMFUNC_P (t))
2979 	return NULL_TREE;
2980       /* Fall through.  */
2981 
2982     case UNION_TYPE:
2983     case ENUMERAL_TYPE:
2984       if (TYPE_TEMPLATE_INFO (t))
2985 	cp_walk_tree (&TI_ARGS (TYPE_TEMPLATE_INFO (t)),
2986 		      &find_parameter_packs_r, ppd, ppd->visited);
2987 
2988       *walk_subtrees = 0;
2989       return NULL_TREE;
2990 
2991     case TEMPLATE_DECL:
2992       cp_walk_tree (&TREE_TYPE (t),
2993 		    &find_parameter_packs_r, ppd, ppd->visited);
2994       return NULL_TREE;
2995 
2996     case TYPENAME_TYPE:
2997       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
2998                    ppd, ppd->visited);
2999       *walk_subtrees = 0;
3000       return NULL_TREE;
3001 
3002     case TYPE_PACK_EXPANSION:
3003     case EXPR_PACK_EXPANSION:
3004       *walk_subtrees = 0;
3005       return NULL_TREE;
3006 
3007     case INTEGER_TYPE:
3008       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r,
3009 		    ppd, ppd->visited);
3010       *walk_subtrees = 0;
3011       return NULL_TREE;
3012 
3013     case IDENTIFIER_NODE:
3014       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd,
3015 		    ppd->visited);
3016       *walk_subtrees = 0;
3017       return NULL_TREE;
3018 
3019     default:
3020       return NULL_TREE;
3021     }
3022 
3023   return NULL_TREE;
3024 }
3025 
3026 /* Determines if the expression or type T uses any parameter packs.  */
3027 bool
3028 uses_parameter_packs (tree t)
3029 {
3030   tree parameter_packs = NULL_TREE;
3031   struct find_parameter_pack_data ppd;
3032   ppd.parameter_packs = &parameter_packs;
3033   ppd.visited = pointer_set_create ();
3034   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3035   pointer_set_destroy (ppd.visited);
3036   return parameter_packs != NULL_TREE;
3037 }
3038 
3039 /* Turn ARG, which may be an expression, type, or a TREE_LIST
3040    representation a base-class initializer into a parameter pack
3041    expansion. If all goes well, the resulting node will be an
3042    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
3043    respectively.  */
3044 tree
3045 make_pack_expansion (tree arg)
3046 {
3047   tree result;
3048   tree parameter_packs = NULL_TREE;
3049   bool for_types = false;
3050   struct find_parameter_pack_data ppd;
3051 
3052   if (!arg || arg == error_mark_node)
3053     return arg;
3054 
3055   if (TREE_CODE (arg) == TREE_LIST)
3056     {
3057       /* The only time we will see a TREE_LIST here is for a base
3058          class initializer.  In this case, the TREE_PURPOSE will be a
3059          _TYPE node (representing the base class expansion we're
3060          initializing) and the TREE_VALUE will be a TREE_LIST
3061          containing the initialization arguments.
3062 
3063          The resulting expansion looks somewhat different from most
3064          expansions. Rather than returning just one _EXPANSION, we
3065          return a TREE_LIST whose TREE_PURPOSE is a
3066          TYPE_PACK_EXPANSION containing the bases that will be
3067          initialized.  The TREE_VALUE will be identical to the
3068          original TREE_VALUE, which is a list of arguments that will
3069          be passed to each base.  We do not introduce any new pack
3070          expansion nodes into the TREE_VALUE (although it is possible
3071          that some already exist), because the TREE_PURPOSE and
3072          TREE_VALUE all need to be expanded together with the same
3073          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3074          resulting TREE_PURPOSE will mention the parameter packs in
3075          both the bases and the arguments to the bases.  */
3076       tree purpose;
3077       tree value;
3078       tree parameter_packs = NULL_TREE;
3079 
3080       /* Determine which parameter packs will be used by the base
3081          class expansion.  */
3082       ppd.visited = pointer_set_create ();
3083       ppd.parameter_packs = &parameter_packs;
3084       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r,
3085                     &ppd, ppd.visited);
3086 
3087       if (parameter_packs == NULL_TREE)
3088         {
3089           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
3090           pointer_set_destroy (ppd.visited);
3091           return error_mark_node;
3092         }
3093 
3094       if (TREE_VALUE (arg) != void_type_node)
3095         {
3096           /* Collect the sets of parameter packs used in each of the
3097              initialization arguments.  */
3098           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3099             {
3100               /* Determine which parameter packs will be expanded in this
3101                  argument.  */
3102               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r,
3103                             &ppd, ppd.visited);
3104             }
3105         }
3106 
3107       pointer_set_destroy (ppd.visited);
3108 
3109       /* Create the pack expansion type for the base type.  */
3110       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3111       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3112       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3113 
3114       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3115 	 they will rarely be compared to anything.  */
3116       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3117 
3118       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3119     }
3120 
3121   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3122     for_types = true;
3123 
3124   /* Build the PACK_EXPANSION_* node.  */
3125   result = for_types
3126      ? cxx_make_type (TYPE_PACK_EXPANSION)
3127      : make_node (EXPR_PACK_EXPANSION);
3128   SET_PACK_EXPANSION_PATTERN (result, arg);
3129   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3130     {
3131       /* Propagate type and const-expression information.  */
3132       TREE_TYPE (result) = TREE_TYPE (arg);
3133       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3134     }
3135   else
3136     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3137        they will rarely be compared to anything.  */
3138     SET_TYPE_STRUCTURAL_EQUALITY (result);
3139 
3140   /* Determine which parameter packs will be expanded.  */
3141   ppd.parameter_packs = &parameter_packs;
3142   ppd.visited = pointer_set_create ();
3143   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3144   pointer_set_destroy (ppd.visited);
3145 
3146   /* Make sure we found some parameter packs.  */
3147   if (parameter_packs == NULL_TREE)
3148     {
3149       if (TYPE_P (arg))
3150         error ("expansion pattern %<%T%> contains no argument packs", arg);
3151       else
3152         error ("expansion pattern %<%E%> contains no argument packs", arg);
3153       return error_mark_node;
3154     }
3155   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
3156 
3157   return result;
3158 }
3159 
3160 /* Checks T for any "bare" parameter packs, which have not yet been
3161    expanded, and issues an error if any are found. This operation can
3162    only be done on full expressions or types (e.g., an expression
3163    statement, "if" condition, etc.), because we could have expressions like:
3164 
3165      foo(f(g(h(args)))...)
3166 
3167    where "args" is a parameter pack. check_for_bare_parameter_packs
3168    should not be called for the subexpressions args, h(args),
3169    g(h(args)), or f(g(h(args))), because we would produce erroneous
3170    error messages.
3171 
3172    Returns TRUE and emits an error if there were bare parameter packs,
3173    returns FALSE otherwise.  */
3174 bool
3175 check_for_bare_parameter_packs (tree t)
3176 {
3177   tree parameter_packs = NULL_TREE;
3178   struct find_parameter_pack_data ppd;
3179 
3180   if (!processing_template_decl || !t || t == error_mark_node)
3181     return false;
3182 
3183   if (TREE_CODE (t) == TYPE_DECL)
3184     t = TREE_TYPE (t);
3185 
3186   ppd.parameter_packs = &parameter_packs;
3187   ppd.visited = pointer_set_create ();
3188   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3189   pointer_set_destroy (ppd.visited);
3190 
3191   if (parameter_packs)
3192     {
3193       error ("parameter packs not expanded with %<...%>:");
3194       while (parameter_packs)
3195         {
3196           tree pack = TREE_VALUE (parameter_packs);
3197           tree name = NULL_TREE;
3198 
3199           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
3200               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
3201             name = TYPE_NAME (pack);
3202           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
3203             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
3204           else
3205             name = DECL_NAME (pack);
3206 
3207 	  if (name)
3208 	    inform (input_location, "        %qD", name);
3209 	  else
3210 	    inform (input_location, "        <anonymous>");
3211 
3212           parameter_packs = TREE_CHAIN (parameter_packs);
3213         }
3214 
3215       return true;
3216     }
3217 
3218   return false;
3219 }
3220 
3221 /* Expand any parameter packs that occur in the template arguments in
3222    ARGS.  */
3223 tree
3224 expand_template_argument_pack (tree args)
3225 {
3226   tree result_args = NULL_TREE;
3227   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3228   int num_result_args = -1;
3229   int non_default_args_count = -1;
3230 
3231   /* First, determine if we need to expand anything, and the number of
3232      slots we'll need.  */
3233   for (in_arg = 0; in_arg < nargs; ++in_arg)
3234     {
3235       tree arg = TREE_VEC_ELT (args, in_arg);
3236       if (arg == NULL_TREE)
3237 	return args;
3238       if (ARGUMENT_PACK_P (arg))
3239         {
3240           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3241           if (num_result_args < 0)
3242             num_result_args = in_arg + num_packed;
3243           else
3244             num_result_args += num_packed;
3245         }
3246       else
3247         {
3248           if (num_result_args >= 0)
3249             num_result_args++;
3250         }
3251     }
3252 
3253   /* If no expansion is necessary, we're done.  */
3254   if (num_result_args < 0)
3255     return args;
3256 
3257   /* Expand arguments.  */
3258   result_args = make_tree_vec (num_result_args);
3259   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
3260     non_default_args_count =
3261       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
3262   for (in_arg = 0; in_arg < nargs; ++in_arg)
3263     {
3264       tree arg = TREE_VEC_ELT (args, in_arg);
3265       if (ARGUMENT_PACK_P (arg))
3266         {
3267           tree packed = ARGUMENT_PACK_ARGS (arg);
3268           int i, num_packed = TREE_VEC_LENGTH (packed);
3269           for (i = 0; i < num_packed; ++i, ++out_arg)
3270             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3271 	  if (non_default_args_count > 0)
3272 	    non_default_args_count += num_packed;
3273         }
3274       else
3275         {
3276           TREE_VEC_ELT (result_args, out_arg) = arg;
3277           ++out_arg;
3278         }
3279     }
3280   if (non_default_args_count >= 0)
3281     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
3282   return result_args;
3283 }
3284 
3285 /* Checks if DECL shadows a template parameter.
3286 
3287    [temp.local]: A template-parameter shall not be redeclared within its
3288    scope (including nested scopes).
3289 
3290    Emits an error and returns TRUE if the DECL shadows a parameter,
3291    returns FALSE otherwise.  */
3292 
3293 bool
3294 check_template_shadow (tree decl)
3295 {
3296   tree olddecl;
3297 
3298   /* If we're not in a template, we can't possibly shadow a template
3299      parameter.  */
3300   if (!current_template_parms)
3301     return true;
3302 
3303   /* Figure out what we're shadowing.  */
3304   if (TREE_CODE (decl) == OVERLOAD)
3305     decl = OVL_CURRENT (decl);
3306   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3307 
3308   /* If there's no previous binding for this name, we're not shadowing
3309      anything, let alone a template parameter.  */
3310   if (!olddecl)
3311     return true;
3312 
3313   /* If we're not shadowing a template parameter, we're done.  Note
3314      that OLDDECL might be an OVERLOAD (or perhaps even an
3315      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3316      node.  */
3317   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3318     return true;
3319 
3320   /* We check for decl != olddecl to avoid bogus errors for using a
3321      name inside a class.  We check TPFI to avoid duplicate errors for
3322      inline member templates.  */
3323   if (decl == olddecl
3324       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
3325     return true;
3326 
3327   error ("declaration of %q+#D", decl);
3328   error (" shadows template parm %q+#D", olddecl);
3329   return false;
3330 }
3331 
3332 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3333    ORIG_LEVEL, DECL, and TYPE.  */
3334 
3335 static tree
3336 build_template_parm_index (int index,
3337 			   int level,
3338 			   int orig_level,
3339 			   tree decl,
3340 			   tree type)
3341 {
3342   tree t = make_node (TEMPLATE_PARM_INDEX);
3343   TEMPLATE_PARM_IDX (t) = index;
3344   TEMPLATE_PARM_LEVEL (t) = level;
3345   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3346   TEMPLATE_PARM_DECL (t) = decl;
3347   TREE_TYPE (t) = type;
3348   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3349   TREE_READONLY (t) = TREE_READONLY (decl);
3350 
3351   return t;
3352 }
3353 
3354 /* Find the canonical type parameter for the given template type
3355    parameter.  Returns the canonical type parameter, which may be TYPE
3356    if no such parameter existed.  */
3357 static tree
3358 canonical_type_parameter (tree type)
3359 {
3360   tree list;
3361   int idx = TEMPLATE_TYPE_IDX (type);
3362   if (!canonical_template_parms)
3363     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
3364 
3365   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
3366     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
3367 
3368   list = VEC_index (tree, canonical_template_parms, idx);
3369   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3370     list = TREE_CHAIN (list);
3371 
3372   if (list)
3373     return TREE_VALUE (list);
3374   else
3375     {
3376       VEC_replace(tree, canonical_template_parms, idx,
3377 		  tree_cons (NULL_TREE, type,
3378 			     VEC_index (tree, canonical_template_parms, idx)));
3379       return type;
3380     }
3381 }
3382 
3383 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3384    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3385    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3386    new one is created.  */
3387 
3388 static tree
3389 reduce_template_parm_level (tree index, tree type, int levels, tree args,
3390 			    tsubst_flags_t complain)
3391 {
3392   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3393       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3394 	  != TEMPLATE_PARM_LEVEL (index) - levels)
3395       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
3396     {
3397       tree orig_decl = TEMPLATE_PARM_DECL (index);
3398       tree decl, t;
3399 
3400       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3401 			 TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3402       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
3403       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
3404       DECL_ARTIFICIAL (decl) = 1;
3405       SET_DECL_TEMPLATE_PARM_P (decl);
3406 
3407       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
3408 				     TEMPLATE_PARM_LEVEL (index) - levels,
3409 				     TEMPLATE_PARM_ORIG_LEVEL (index),
3410 				     decl, type);
3411       TEMPLATE_PARM_DESCENDANTS (index) = t;
3412       TEMPLATE_PARM_PARAMETER_PACK (t)
3413 	= TEMPLATE_PARM_PARAMETER_PACK (index);
3414 
3415 	/* Template template parameters need this.  */
3416       if (TREE_CODE (decl) == TEMPLATE_DECL)
3417 	DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
3418 	  (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
3419 	   args, complain);
3420     }
3421 
3422   return TEMPLATE_PARM_DESCENDANTS (index);
3423 }
3424 
3425 /* Process information from new template parameter PARM and append it to the
3426    LIST being built.  This new parameter is a non-type parameter iff
3427    IS_NON_TYPE is true. This new parameter is a parameter
3428    pack iff IS_PARAMETER_PACK is true.  The location of PARM is in
3429    PARM_LOC.  */
3430 
3431 tree
3432 process_template_parm (tree list, location_t parm_loc, tree parm, bool is_non_type,
3433                        bool is_parameter_pack)
3434 {
3435   tree decl = 0;
3436   tree defval;
3437   tree err_parm_list;
3438   int idx = 0;
3439 
3440   gcc_assert (TREE_CODE (parm) == TREE_LIST);
3441   defval = TREE_PURPOSE (parm);
3442 
3443   if (list)
3444     {
3445       tree p = tree_last (list);
3446 
3447       if (p && TREE_VALUE (p) != error_mark_node)
3448         {
3449           p = TREE_VALUE (p);
3450           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3451             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3452           else
3453             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3454         }
3455 
3456       ++idx;
3457     }
3458   else
3459     idx = 0;
3460 
3461   if (is_non_type)
3462     {
3463       parm = TREE_VALUE (parm);
3464 
3465       SET_DECL_TEMPLATE_PARM_P (parm);
3466 
3467       if (TREE_TYPE (parm) == error_mark_node)
3468         {
3469           err_parm_list = build_tree_list (defval, parm);
3470           TREE_VALUE (err_parm_list) = error_mark_node;
3471 	   return chainon (list, err_parm_list);
3472         }
3473       else
3474       {
3475 	/* [temp.param]
3476 
3477 	   The top-level cv-qualifiers on the template-parameter are
3478 	   ignored when determining its type.  */
3479 	TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3480 	if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3481           {
3482             err_parm_list = build_tree_list (defval, parm);
3483             TREE_VALUE (err_parm_list) = error_mark_node;
3484 	     return chainon (list, err_parm_list);
3485           }
3486 
3487         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3488 	  {
3489 	    /* This template parameter is not a parameter pack, but it
3490 	       should be. Complain about "bare" parameter packs.  */
3491 	    check_for_bare_parameter_packs (TREE_TYPE (parm));
3492 
3493 	    /* Recover by calling this a parameter pack.  */
3494 	    is_parameter_pack = true;
3495 	  }
3496       }
3497 
3498       /* A template parameter is not modifiable.  */
3499       TREE_CONSTANT (parm) = 1;
3500       TREE_READONLY (parm) = 1;
3501       decl = build_decl (parm_loc,
3502 			 CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3503       TREE_CONSTANT (decl) = 1;
3504       TREE_READONLY (decl) = 1;
3505       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3506 	= build_template_parm_index (idx, processing_template_decl,
3507 				     processing_template_decl,
3508 				     decl, TREE_TYPE (parm));
3509 
3510       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))
3511 	= is_parameter_pack;
3512     }
3513   else
3514     {
3515       tree t;
3516       parm = TREE_VALUE (TREE_VALUE (parm));
3517 
3518       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3519 	{
3520 	  t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3521 	  /* This is for distinguishing between real templates and template
3522 	     template parameters */
3523 	  TREE_TYPE (parm) = t;
3524 	  TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3525 	  decl = parm;
3526 	}
3527       else
3528 	{
3529 	  t = cxx_make_type (TEMPLATE_TYPE_PARM);
3530 	  /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3531 	  decl = build_decl (parm_loc,
3532 			     TYPE_DECL, parm, t);
3533 	}
3534 
3535       TYPE_NAME (t) = decl;
3536       TYPE_STUB_DECL (t) = decl;
3537       parm = decl;
3538       TEMPLATE_TYPE_PARM_INDEX (t)
3539 	= build_template_parm_index (idx, processing_template_decl,
3540 				     processing_template_decl,
3541 				     decl, TREE_TYPE (parm));
3542       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3543       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3544     }
3545   DECL_ARTIFICIAL (decl) = 1;
3546   SET_DECL_TEMPLATE_PARM_P (decl);
3547   pushdecl (decl);
3548   parm = build_tree_list (defval, parm);
3549   return chainon (list, parm);
3550 }
3551 
3552 /* The end of a template parameter list has been reached.  Process the
3553    tree list into a parameter vector, converting each parameter into a more
3554    useful form.	 Type parameters are saved as IDENTIFIER_NODEs, and others
3555    as PARM_DECLs.  */
3556 
3557 tree
3558 end_template_parm_list (tree parms)
3559 {
3560   int nparms;
3561   tree parm, next;
3562   tree saved_parmlist = make_tree_vec (list_length (parms));
3563 
3564   current_template_parms
3565     = tree_cons (size_int (processing_template_decl),
3566 		 saved_parmlist, current_template_parms);
3567 
3568   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3569     {
3570       next = TREE_CHAIN (parm);
3571       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3572       TREE_CHAIN (parm) = NULL_TREE;
3573       if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL)
3574 	TEMPLATE_TYPE_PARM_SIBLING_PARMS (TREE_TYPE (TREE_VALUE (parm))) =
3575 	      current_template_parms;
3576     }
3577 
3578   --processing_template_parmlist;
3579 
3580   return saved_parmlist;
3581 }
3582 
3583 /* end_template_decl is called after a template declaration is seen.  */
3584 
3585 void
3586 end_template_decl (void)
3587 {
3588   reset_specialization ();
3589 
3590   if (! processing_template_decl)
3591     return;
3592 
3593   /* This matches the pushlevel in begin_template_parm_list.  */
3594   finish_scope ();
3595 
3596   --processing_template_decl;
3597   current_template_parms = TREE_CHAIN (current_template_parms);
3598 }
3599 
3600 /* Within the declaration of a template, return all levels of template
3601    parameters that apply.  The template parameters are represented as
3602    a TREE_VEC, in the form documented in cp-tree.h for template
3603    arguments.  */
3604 
3605 static tree
3606 current_template_args (void)
3607 {
3608   tree header;
3609   tree args = NULL_TREE;
3610   int length = TMPL_PARMS_DEPTH (current_template_parms);
3611   int l = length;
3612 
3613   /* If there is only one level of template parameters, we do not
3614      create a TREE_VEC of TREE_VECs.  Instead, we return a single
3615      TREE_VEC containing the arguments.  */
3616   if (length > 1)
3617     args = make_tree_vec (length);
3618 
3619   for (header = current_template_parms; header; header = TREE_CHAIN (header))
3620     {
3621       tree a = copy_node (TREE_VALUE (header));
3622       int i;
3623 
3624       TREE_TYPE (a) = NULL_TREE;
3625       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3626 	{
3627 	  tree t = TREE_VEC_ELT (a, i);
3628 
3629 	  /* T will be a list if we are called from within a
3630 	     begin/end_template_parm_list pair, but a vector directly
3631 	     if within a begin/end_member_template_processing pair.  */
3632 	  if (TREE_CODE (t) == TREE_LIST)
3633 	    {
3634 	      t = TREE_VALUE (t);
3635 
3636 	      if (!error_operand_p (t))
3637 		{
3638 		  if (TREE_CODE (t) == TYPE_DECL
3639 		      || TREE_CODE (t) == TEMPLATE_DECL)
3640                     {
3641                       t = TREE_TYPE (t);
3642 
3643                       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3644                         {
3645                           /* Turn this argument into a TYPE_ARGUMENT_PACK
3646                              with a single element, which expands T.  */
3647                           tree vec = make_tree_vec (1);
3648 #ifdef ENABLE_CHECKING
3649 			  SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3650 				(vec, TREE_VEC_LENGTH (vec));
3651 #endif
3652                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3653 
3654                           t = cxx_make_type (TYPE_ARGUMENT_PACK);
3655                           SET_ARGUMENT_PACK_ARGS (t, vec);
3656                         }
3657                     }
3658                   else
3659                     {
3660                       t = DECL_INITIAL (t);
3661 
3662                       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3663                         {
3664                           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3665                              with a single element, which expands T.  */
3666                           tree vec = make_tree_vec (1);
3667                           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3668 #ifdef ENABLE_CHECKING
3669 			  SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3670 				(vec, TREE_VEC_LENGTH (vec));
3671 #endif
3672                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3673 
3674                           t  = make_node (NONTYPE_ARGUMENT_PACK);
3675                           SET_ARGUMENT_PACK_ARGS (t, vec);
3676                           TREE_TYPE (t) = type;
3677                         }
3678                     }
3679 		  TREE_VEC_ELT (a, i) = t;
3680                 }
3681 	    }
3682 	}
3683 
3684 #ifdef ENABLE_CHECKING
3685       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
3686 #endif
3687 
3688       if (length > 1)
3689 	TREE_VEC_ELT (args, --l) = a;
3690       else
3691 	args = a;
3692     }
3693 
3694   return args;
3695 }
3696 
3697 /* Update the declared TYPE by doing any lookups which were thought to be
3698    dependent, but are not now that we know the SCOPE of the declarator.  */
3699 
3700 tree
3701 maybe_update_decl_type (tree orig_type, tree scope)
3702 {
3703   tree type = orig_type;
3704 
3705   if (type == NULL_TREE)
3706     return type;
3707 
3708   if (TREE_CODE (orig_type) == TYPE_DECL)
3709     type = TREE_TYPE (type);
3710 
3711   if (scope && TYPE_P (scope) && dependent_type_p (scope)
3712       && dependent_type_p (type)
3713       /* Don't bother building up the args in this case.  */
3714       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
3715     {
3716       /* tsubst in the args corresponding to the template parameters,
3717 	 including auto if present.  Most things will be unchanged, but
3718 	 make_typename_type and tsubst_qualified_id will resolve
3719 	 TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
3720       tree args = current_template_args ();
3721       tree auto_node = type_uses_auto (type);
3722       tree pushed;
3723       if (auto_node)
3724 	{
3725 	  tree auto_vec = make_tree_vec (1);
3726 	  TREE_VEC_ELT (auto_vec, 0) = auto_node;
3727 	  args = add_to_template_args (args, auto_vec);
3728 	}
3729       pushed = push_scope (scope);
3730       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
3731       if (pushed)
3732 	pop_scope (scope);
3733     }
3734 
3735   if (type == error_mark_node)
3736     return orig_type;
3737 
3738   if (TREE_CODE (orig_type) == TYPE_DECL)
3739     {
3740       if (same_type_p (type, TREE_TYPE (orig_type)))
3741 	type = orig_type;
3742       else
3743 	type = TYPE_NAME (type);
3744     }
3745   return type;
3746 }
3747 
3748 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
3749    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
3750    a member template.  Used by push_template_decl below.  */
3751 
3752 static tree
3753 build_template_decl (tree decl, tree parms, bool member_template_p)
3754 {
3755   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
3756   DECL_TEMPLATE_PARMS (tmpl) = parms;
3757   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
3758   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
3759 
3760   return tmpl;
3761 }
3762 
3763 struct template_parm_data
3764 {
3765   /* The level of the template parameters we are currently
3766      processing.  */
3767   int level;
3768 
3769   /* The index of the specialization argument we are currently
3770      processing.  */
3771   int current_arg;
3772 
3773   /* An array whose size is the number of template parameters.  The
3774      elements are nonzero if the parameter has been used in any one
3775      of the arguments processed so far.  */
3776   int* parms;
3777 
3778   /* An array whose size is the number of template arguments.  The
3779      elements are nonzero if the argument makes use of template
3780      parameters of this level.  */
3781   int* arg_uses_template_parms;
3782 };
3783 
3784 /* Subroutine of push_template_decl used to see if each template
3785    parameter in a partial specialization is used in the explicit
3786    argument list.  If T is of the LEVEL given in DATA (which is
3787    treated as a template_parm_data*), then DATA->PARMS is marked
3788    appropriately.  */
3789 
3790 static int
3791 mark_template_parm (tree t, void* data)
3792 {
3793   int level;
3794   int idx;
3795   struct template_parm_data* tpd = (struct template_parm_data*) data;
3796 
3797   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3798     {
3799       level = TEMPLATE_PARM_LEVEL (t);
3800       idx = TEMPLATE_PARM_IDX (t);
3801     }
3802   else
3803     {
3804       level = TEMPLATE_TYPE_LEVEL (t);
3805       idx = TEMPLATE_TYPE_IDX (t);
3806     }
3807 
3808   if (level == tpd->level)
3809     {
3810       tpd->parms[idx] = 1;
3811       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
3812     }
3813 
3814   /* Return zero so that for_each_template_parm will continue the
3815      traversal of the tree; we want to mark *every* template parm.  */
3816   return 0;
3817 }
3818 
3819 /* Process the partial specialization DECL.  */
3820 
3821 static tree
3822 process_partial_specialization (tree decl)
3823 {
3824   tree type = TREE_TYPE (decl);
3825   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
3826   tree specargs = CLASSTYPE_TI_ARGS (type);
3827   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
3828   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
3829   tree inner_parms;
3830   int nargs = TREE_VEC_LENGTH (inner_args);
3831   int ntparms;
3832   int  i;
3833   int did_error_intro = 0;
3834   struct template_parm_data tpd;
3835   struct template_parm_data tpd2;
3836 
3837   gcc_assert (current_template_parms);
3838 
3839   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3840   ntparms = TREE_VEC_LENGTH (inner_parms);
3841 
3842   /* We check that each of the template parameters given in the
3843      partial specialization is used in the argument list to the
3844      specialization.  For example:
3845 
3846        template <class T> struct S;
3847        template <class T> struct S<T*>;
3848 
3849      The second declaration is OK because `T*' uses the template
3850      parameter T, whereas
3851 
3852        template <class T> struct S<int>;
3853 
3854      is no good.  Even trickier is:
3855 
3856        template <class T>
3857        struct S1
3858        {
3859 	  template <class U>
3860 	  struct S2;
3861 	  template <class U>
3862 	  struct S2<T>;
3863        };
3864 
3865      The S2<T> declaration is actually invalid; it is a
3866      full-specialization.  Of course,
3867 
3868 	  template <class U>
3869 	  struct S2<T (*)(U)>;
3870 
3871      or some such would have been OK.  */
3872   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
3873   tpd.parms = (int *) alloca (sizeof (int) * ntparms);
3874   memset (tpd.parms, 0, sizeof (int) * ntparms);
3875 
3876   tpd.arg_uses_template_parms = (int *) alloca (sizeof (int) * nargs);
3877   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
3878   for (i = 0; i < nargs; ++i)
3879     {
3880       tpd.current_arg = i;
3881       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
3882 			      &mark_template_parm,
3883 			      &tpd,
3884 			      NULL,
3885 			      /*include_nondeduced_p=*/false);
3886     }
3887   for (i = 0; i < ntparms; ++i)
3888     if (tpd.parms[i] == 0)
3889       {
3890 	/* One of the template parms was not used in the
3891 	   specialization.  */
3892 	if (!did_error_intro)
3893 	  {
3894 	    error ("template parameters not used in partial specialization:");
3895 	    did_error_intro = 1;
3896 	  }
3897 
3898 	error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
3899       }
3900 
3901   /* [temp.class.spec]
3902 
3903      The argument list of the specialization shall not be identical to
3904      the implicit argument list of the primary template.  */
3905   if (comp_template_args
3906       (inner_args,
3907        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
3908 						   (maintmpl)))))
3909     error ("partial specialization %qT does not specialize any template arguments", type);
3910 
3911   /* [temp.class.spec]
3912 
3913      A partially specialized non-type argument expression shall not
3914      involve template parameters of the partial specialization except
3915      when the argument expression is a simple identifier.
3916 
3917      The type of a template parameter corresponding to a specialized
3918      non-type argument shall not be dependent on a parameter of the
3919      specialization.
3920 
3921      Also, we verify that pack expansions only occur at the
3922      end of the argument list.  */
3923   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
3924   tpd2.parms = 0;
3925   for (i = 0; i < nargs; ++i)
3926     {
3927       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
3928       tree arg = TREE_VEC_ELT (inner_args, i);
3929       tree packed_args = NULL_TREE;
3930       int j, len = 1;
3931 
3932       if (ARGUMENT_PACK_P (arg))
3933         {
3934           /* Extract the arguments from the argument pack. We'll be
3935              iterating over these in the following loop.  */
3936           packed_args = ARGUMENT_PACK_ARGS (arg);
3937           len = TREE_VEC_LENGTH (packed_args);
3938         }
3939 
3940       for (j = 0; j < len; j++)
3941         {
3942           if (packed_args)
3943             /* Get the Jth argument in the parameter pack.  */
3944             arg = TREE_VEC_ELT (packed_args, j);
3945 
3946           if (PACK_EXPANSION_P (arg))
3947             {
3948               /* Pack expansions must come at the end of the
3949                  argument list.  */
3950               if ((packed_args && j < len - 1)
3951                   || (!packed_args && i < nargs - 1))
3952                 {
3953                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3954                     error ("parameter pack argument %qE must be at the "
3955 			   "end of the template argument list", arg);
3956                   else
3957                     error ("parameter pack argument %qT must be at the "
3958 			   "end of the template argument list", arg);
3959                 }
3960             }
3961 
3962           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3963             /* We only care about the pattern.  */
3964             arg = PACK_EXPANSION_PATTERN (arg);
3965 
3966           if (/* These first two lines are the `non-type' bit.  */
3967               !TYPE_P (arg)
3968               && TREE_CODE (arg) != TEMPLATE_DECL
3969               /* This next line is the `argument expression is not just a
3970                  simple identifier' condition and also the `specialized
3971                  non-type argument' bit.  */
3972               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
3973             {
3974               if ((!packed_args && tpd.arg_uses_template_parms[i])
3975                   || (packed_args && uses_template_parms (arg)))
3976                 error ("template argument %qE involves template parameter(s)",
3977                        arg);
3978               else
3979                 {
3980                   /* Look at the corresponding template parameter,
3981                      marking which template parameters its type depends
3982                      upon.  */
3983                   tree type = TREE_TYPE (parm);
3984 
3985                   if (!tpd2.parms)
3986                     {
3987                       /* We haven't yet initialized TPD2.  Do so now.  */
3988                       tpd2.arg_uses_template_parms
3989                         = (int *) alloca (sizeof (int) * nargs);
3990                       /* The number of parameters here is the number in the
3991                          main template, which, as checked in the assertion
3992                          above, is NARGS.  */
3993                       tpd2.parms = (int *) alloca (sizeof (int) * nargs);
3994                       tpd2.level =
3995                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
3996                     }
3997 
3998                   /* Mark the template parameters.  But this time, we're
3999                      looking for the template parameters of the main
4000                      template, not in the specialization.  */
4001                   tpd2.current_arg = i;
4002                   tpd2.arg_uses_template_parms[i] = 0;
4003                   memset (tpd2.parms, 0, sizeof (int) * nargs);
4004                   for_each_template_parm (type,
4005                                           &mark_template_parm,
4006                                           &tpd2,
4007                                           NULL,
4008 					  /*include_nondeduced_p=*/false);
4009 
4010                   if (tpd2.arg_uses_template_parms [i])
4011                     {
4012                       /* The type depended on some template parameters.
4013                          If they are fully specialized in the
4014                          specialization, that's OK.  */
4015                       int j;
4016                       int count = 0;
4017                       for (j = 0; j < nargs; ++j)
4018                         if (tpd2.parms[j] != 0
4019                             && tpd.arg_uses_template_parms [j])
4020                           ++count;
4021                       if (count != 0)
4022                         error_n (input_location, count,
4023                                  "type %qT of template argument %qE depends "
4024                                  "on a template parameter",
4025                                  "type %qT of template argument %qE depends "
4026                                  "on template parameters",
4027                                  type,
4028                                  arg);
4029                     }
4030                 }
4031             }
4032         }
4033     }
4034 
4035   /* We should only get here once.  */
4036   gcc_assert (!COMPLETE_TYPE_P (type));
4037 
4038   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
4039     = tree_cons (specargs, inner_parms,
4040                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
4041   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
4042   return decl;
4043 }
4044 
4045 /* Check that a template declaration's use of default arguments and
4046    parameter packs is not invalid.  Here, PARMS are the template
4047    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
4048    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
4049    specialization.
4050 
4051 
4052    IS_FRIEND_DECL is nonzero if DECL is a friend function template
4053    declaration (but not a definition); 1 indicates a declaration, 2
4054    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
4055    emitted for extraneous default arguments.
4056 
4057    Returns TRUE if there were no errors found, FALSE otherwise. */
4058 
4059 bool
4060 check_default_tmpl_args (tree decl, tree parms, int is_primary,
4061                          int is_partial, int is_friend_decl)
4062 {
4063   const char *msg;
4064   int last_level_to_check;
4065   tree parm_level;
4066   bool no_errors = true;
4067 
4068   /* [temp.param]
4069 
4070      A default template-argument shall not be specified in a
4071      function template declaration or a function template definition, nor
4072      in the template-parameter-list of the definition of a member of a
4073      class template.  */
4074 
4075   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
4076     /* You can't have a function template declaration in a local
4077        scope, nor you can you define a member of a class template in a
4078        local scope.  */
4079     return true;
4080 
4081   if (current_class_type
4082       && !TYPE_BEING_DEFINED (current_class_type)
4083       && DECL_LANG_SPECIFIC (decl)
4084       && DECL_DECLARES_FUNCTION_P (decl)
4085       /* If this is either a friend defined in the scope of the class
4086 	 or a member function.  */
4087       && (DECL_FUNCTION_MEMBER_P (decl)
4088 	  ? same_type_p (DECL_CONTEXT (decl), current_class_type)
4089 	  : DECL_FRIEND_CONTEXT (decl)
4090 	  ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
4091 	  : false)
4092       /* And, if it was a member function, it really was defined in
4093 	 the scope of the class.  */
4094       && (!DECL_FUNCTION_MEMBER_P (decl)
4095 	  || DECL_INITIALIZED_IN_CLASS_P (decl)))
4096     /* We already checked these parameters when the template was
4097        declared, so there's no need to do it again now.  This function
4098        was defined in class scope, but we're processing it's body now
4099        that the class is complete.  */
4100     return true;
4101 
4102   /* Core issue 226 (C++0x only): the following only applies to class
4103      templates.  */
4104   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
4105     {
4106       /* [temp.param]
4107 
4108          If a template-parameter has a default template-argument, all
4109          subsequent template-parameters shall have a default
4110          template-argument supplied.  */
4111       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
4112         {
4113           tree inner_parms = TREE_VALUE (parm_level);
4114           int ntparms = TREE_VEC_LENGTH (inner_parms);
4115           int seen_def_arg_p = 0;
4116           int i;
4117 
4118           for (i = 0; i < ntparms; ++i)
4119             {
4120               tree parm = TREE_VEC_ELT (inner_parms, i);
4121 
4122               if (parm == error_mark_node)
4123                 continue;
4124 
4125               if (TREE_PURPOSE (parm))
4126                 seen_def_arg_p = 1;
4127               else if (seen_def_arg_p
4128 		       && !template_parameter_pack_p (TREE_VALUE (parm)))
4129                 {
4130                   error ("no default argument for %qD", TREE_VALUE (parm));
4131                   /* For better subsequent error-recovery, we indicate that
4132                      there should have been a default argument.  */
4133                   TREE_PURPOSE (parm) = error_mark_node;
4134                   no_errors = false;
4135                 }
4136 	      else if (is_primary
4137 		       && !is_partial
4138 		       && !is_friend_decl
4139 		       /* Don't complain about an enclosing partial
4140 			  specialization.  */
4141 		       && parm_level == parms
4142 		       && TREE_CODE (decl) == TYPE_DECL
4143 		       && i < ntparms - 1
4144 		       && template_parameter_pack_p (TREE_VALUE (parm)))
4145 		{
4146 		  /* A primary class template can only have one
4147 		     parameter pack, at the end of the template
4148 		     parameter list.  */
4149 
4150 		  if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
4151 		    error ("parameter pack %qE must be at the end of the"
4152 			   " template parameter list", TREE_VALUE (parm));
4153 		  else
4154 		    error ("parameter pack %qT must be at the end of the"
4155 			   " template parameter list",
4156 			   TREE_TYPE (TREE_VALUE (parm)));
4157 
4158 		  TREE_VALUE (TREE_VEC_ELT (inner_parms, i))
4159 		    = error_mark_node;
4160 		  no_errors = false;
4161 		}
4162             }
4163         }
4164     }
4165 
4166   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
4167       || is_partial
4168       || !is_primary
4169       || is_friend_decl)
4170     /* For an ordinary class template, default template arguments are
4171        allowed at the innermost level, e.g.:
4172 	 template <class T = int>
4173 	 struct S {};
4174        but, in a partial specialization, they're not allowed even
4175        there, as we have in [temp.class.spec]:
4176 
4177 	 The template parameter list of a specialization shall not
4178 	 contain default template argument values.
4179 
4180        So, for a partial specialization, or for a function template
4181        (in C++98/C++03), we look at all of them.  */
4182     ;
4183   else
4184     /* But, for a primary class template that is not a partial
4185        specialization we look at all template parameters except the
4186        innermost ones.  */
4187     parms = TREE_CHAIN (parms);
4188 
4189   /* Figure out what error message to issue.  */
4190   if (is_friend_decl == 2)
4191     msg = G_("default template arguments may not be used in function template "
4192 	     "friend re-declaration");
4193   else if (is_friend_decl)
4194     msg = G_("default template arguments may not be used in function template "
4195 	     "friend declarations");
4196   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
4197     msg = G_("default template arguments may not be used in function templates "
4198 	     "without -std=c++0x or -std=gnu++0x");
4199   else if (is_partial)
4200     msg = G_("default template arguments may not be used in "
4201 	     "partial specializations");
4202   else
4203     msg = G_("default argument for template parameter for class enclosing %qD");
4204 
4205   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
4206     /* If we're inside a class definition, there's no need to
4207        examine the parameters to the class itself.  On the one
4208        hand, they will be checked when the class is defined, and,
4209        on the other, default arguments are valid in things like:
4210 	 template <class T = double>
4211 	 struct S { template <class U> void f(U); };
4212        Here the default argument for `S' has no bearing on the
4213        declaration of `f'.  */
4214     last_level_to_check = template_class_depth (current_class_type) + 1;
4215   else
4216     /* Check everything.  */
4217     last_level_to_check = 0;
4218 
4219   for (parm_level = parms;
4220        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
4221        parm_level = TREE_CHAIN (parm_level))
4222     {
4223       tree inner_parms = TREE_VALUE (parm_level);
4224       int i;
4225       int ntparms;
4226 
4227       ntparms = TREE_VEC_LENGTH (inner_parms);
4228       for (i = 0; i < ntparms; ++i)
4229         {
4230           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
4231             continue;
4232 
4233 	  if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
4234 	    {
4235 	      if (msg)
4236 	        {
4237                   no_errors = false;
4238                   if (is_friend_decl == 2)
4239                     return no_errors;
4240 
4241 		  error (msg, decl);
4242 		  msg = 0;
4243 	        }
4244 
4245 	      /* Clear out the default argument so that we are not
4246 	         confused later.  */
4247 	      TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
4248 	    }
4249         }
4250 
4251       /* At this point, if we're still interested in issuing messages,
4252 	 they must apply to classes surrounding the object declared.  */
4253       if (msg)
4254 	msg = G_("default argument for template parameter for class "
4255 		 "enclosing %qD");
4256     }
4257 
4258   return no_errors;
4259 }
4260 
4261 /* Worker for push_template_decl_real, called via
4262    for_each_template_parm.  DATA is really an int, indicating the
4263    level of the parameters we are interested in.  If T is a template
4264    parameter of that level, return nonzero.  */
4265 
4266 static int
4267 template_parm_this_level_p (tree t, void* data)
4268 {
4269   int this_level = *(int *)data;
4270   int level;
4271 
4272   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4273     level = TEMPLATE_PARM_LEVEL (t);
4274   else
4275     level = TEMPLATE_TYPE_LEVEL (t);
4276   return level == this_level;
4277 }
4278 
4279 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
4280    parameters given by current_template_args, or reuses a
4281    previously existing one, if appropriate.  Returns the DECL, or an
4282    equivalent one, if it is replaced via a call to duplicate_decls.
4283 
4284    If IS_FRIEND is true, DECL is a friend declaration.  */
4285 
4286 tree
4287 push_template_decl_real (tree decl, bool is_friend)
4288 {
4289   tree tmpl;
4290   tree args;
4291   tree info;
4292   tree ctx;
4293   int primary;
4294   int is_partial;
4295   int new_template_p = 0;
4296   /* True if the template is a member template, in the sense of
4297      [temp.mem].  */
4298   bool member_template_p = false;
4299 
4300   if (decl == error_mark_node || !current_template_parms)
4301     return error_mark_node;
4302 
4303   /* See if this is a partial specialization.  */
4304   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
4305 		&& TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
4306 		&& CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
4307 
4308   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
4309     is_friend = true;
4310 
4311   if (is_friend)
4312     /* For a friend, we want the context of the friend function, not
4313        the type of which it is a friend.  */
4314     ctx = DECL_CONTEXT (decl);
4315   else if (CP_DECL_CONTEXT (decl)
4316 	   && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
4317     /* In the case of a virtual function, we want the class in which
4318        it is defined.  */
4319     ctx = CP_DECL_CONTEXT (decl);
4320   else
4321     /* Otherwise, if we're currently defining some class, the DECL
4322        is assumed to be a member of the class.  */
4323     ctx = current_scope ();
4324 
4325   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
4326     ctx = NULL_TREE;
4327 
4328   if (!DECL_CONTEXT (decl))
4329     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4330 
4331   /* See if this is a primary template.  */
4332   if (is_friend && ctx)
4333     /* A friend template that specifies a class context, i.e.
4334          template <typename T> friend void A<T>::f();
4335        is not primary.  */
4336     primary = 0;
4337   else
4338     primary = template_parm_scope_p ();
4339 
4340   if (primary)
4341     {
4342       if (DECL_CLASS_SCOPE_P (decl))
4343 	member_template_p = true;
4344       if (TREE_CODE (decl) == TYPE_DECL
4345 	  && ANON_AGGRNAME_P (DECL_NAME (decl)))
4346 	{
4347 	  error ("template class without a name");
4348 	  return error_mark_node;
4349 	}
4350       else if (TREE_CODE (decl) == FUNCTION_DECL)
4351 	{
4352 	  if (DECL_DESTRUCTOR_P (decl))
4353 	    {
4354 	      /* [temp.mem]
4355 
4356 		 A destructor shall not be a member template.  */
4357 	      error ("destructor %qD declared as member template", decl);
4358 	      return error_mark_node;
4359 	    }
4360 	  if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
4361 	      && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
4362 		  || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
4363 		  || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
4364 		  || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
4365 		      == void_list_node)))
4366 	    {
4367 	      /* [basic.stc.dynamic.allocation]
4368 
4369 		 An allocation function can be a function
4370 		 template. ... Template allocation functions shall
4371 		 have two or more parameters.  */
4372 	      error ("invalid template declaration of %qD", decl);
4373 	      return error_mark_node;
4374 	    }
4375 	}
4376       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4377 	       && CLASS_TYPE_P (TREE_TYPE (decl)))
4378 	/* OK */;
4379       else
4380 	{
4381 	  error ("template declaration of %q#D", decl);
4382 	  return error_mark_node;
4383 	}
4384     }
4385 
4386   /* Check to see that the rules regarding the use of default
4387      arguments are not being violated.  */
4388   check_default_tmpl_args (decl, current_template_parms,
4389 			   primary, is_partial, /*is_friend_decl=*/0);
4390 
4391   /* Ensure that there are no parameter packs in the type of this
4392      declaration that have not been expanded.  */
4393   if (TREE_CODE (decl) == FUNCTION_DECL)
4394     {
4395       /* Check each of the arguments individually to see if there are
4396          any bare parameter packs.  */
4397       tree type = TREE_TYPE (decl);
4398       tree arg = DECL_ARGUMENTS (decl);
4399       tree argtype = TYPE_ARG_TYPES (type);
4400 
4401       while (arg && argtype)
4402         {
4403           if (!FUNCTION_PARAMETER_PACK_P (arg)
4404               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
4405             {
4406             /* This is a PARM_DECL that contains unexpanded parameter
4407                packs. We have already complained about this in the
4408                check_for_bare_parameter_packs call, so just replace
4409                these types with ERROR_MARK_NODE.  */
4410               TREE_TYPE (arg) = error_mark_node;
4411               TREE_VALUE (argtype) = error_mark_node;
4412             }
4413 
4414           arg = TREE_CHAIN (arg);
4415           argtype = TREE_CHAIN (argtype);
4416         }
4417 
4418       /* Check for bare parameter packs in the return type and the
4419          exception specifiers.  */
4420       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
4421 	/* Errors were already issued, set return type to int
4422 	   as the frontend doesn't expect error_mark_node as
4423 	   the return type.  */
4424 	TREE_TYPE (type) = integer_type_node;
4425       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
4426 	TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
4427     }
4428   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
4429     {
4430       TREE_TYPE (decl) = error_mark_node;
4431       return error_mark_node;
4432     }
4433 
4434   if (is_partial)
4435     return process_partial_specialization (decl);
4436 
4437   args = current_template_args ();
4438 
4439   if (!ctx
4440       || TREE_CODE (ctx) == FUNCTION_DECL
4441       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
4442       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
4443     {
4444       if (DECL_LANG_SPECIFIC (decl)
4445 	  && DECL_TEMPLATE_INFO (decl)
4446 	  && DECL_TI_TEMPLATE (decl))
4447 	tmpl = DECL_TI_TEMPLATE (decl);
4448       /* If DECL is a TYPE_DECL for a class-template, then there won't
4449 	 be DECL_LANG_SPECIFIC.  The information equivalent to
4450 	 DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
4451       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4452 	       && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
4453 	       && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
4454 	{
4455 	  /* Since a template declaration already existed for this
4456 	     class-type, we must be redeclaring it here.  Make sure
4457 	     that the redeclaration is valid.  */
4458 	  redeclare_class_template (TREE_TYPE (decl),
4459 				    current_template_parms);
4460 	  /* We don't need to create a new TEMPLATE_DECL; just use the
4461 	     one we already had.  */
4462 	  tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
4463 	}
4464       else
4465 	{
4466 	  tmpl = build_template_decl (decl, current_template_parms,
4467 				      member_template_p);
4468 	  new_template_p = 1;
4469 
4470 	  if (DECL_LANG_SPECIFIC (decl)
4471 	      && DECL_TEMPLATE_SPECIALIZATION (decl))
4472 	    {
4473 	      /* A specialization of a member template of a template
4474 		 class.  */
4475 	      SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4476 	      DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
4477 	      DECL_TEMPLATE_INFO (decl) = NULL_TREE;
4478 	    }
4479 	}
4480     }
4481   else
4482     {
4483       tree a, t, current, parms;
4484       int i;
4485       tree tinfo = get_template_info (decl);
4486 
4487       if (!tinfo)
4488 	{
4489 	  error ("template definition of non-template %q#D", decl);
4490 	  return error_mark_node;
4491 	}
4492 
4493       tmpl = TI_TEMPLATE (tinfo);
4494 
4495       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
4496 	  && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
4497 	  && DECL_TEMPLATE_SPECIALIZATION (decl)
4498 	  && DECL_MEMBER_TEMPLATE_P (tmpl))
4499 	{
4500 	  tree new_tmpl;
4501 
4502 	  /* The declaration is a specialization of a member
4503 	     template, declared outside the class.  Therefore, the
4504 	     innermost template arguments will be NULL, so we
4505 	     replace them with the arguments determined by the
4506 	     earlier call to check_explicit_specialization.  */
4507 	  args = DECL_TI_ARGS (decl);
4508 
4509 	  new_tmpl
4510 	    = build_template_decl (decl, current_template_parms,
4511 				   member_template_p);
4512 	  DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4513 	  TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4514 	  DECL_TI_TEMPLATE (decl) = new_tmpl;
4515 	  SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4516 	  DECL_TEMPLATE_INFO (new_tmpl)
4517 	    = build_template_info (tmpl, args);
4518 
4519 	  register_specialization (new_tmpl,
4520 				   most_general_template (tmpl),
4521 				   args,
4522 				   is_friend, 0);
4523 	  return decl;
4524 	}
4525 
4526       /* Make sure the template headers we got make sense.  */
4527 
4528       parms = DECL_TEMPLATE_PARMS (tmpl);
4529       i = TMPL_PARMS_DEPTH (parms);
4530       if (TMPL_ARGS_DEPTH (args) != i)
4531 	{
4532 	  error ("expected %d levels of template parms for %q#D, got %d",
4533 		 i, decl, TMPL_ARGS_DEPTH (args));
4534 	}
4535       else
4536 	for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4537 	  {
4538 	    a = TMPL_ARGS_LEVEL (args, i);
4539 	    t = INNERMOST_TEMPLATE_PARMS (parms);
4540 
4541 	    if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4542 	      {
4543 		if (current == decl)
4544 		  error ("got %d template parameters for %q#D",
4545 			 TREE_VEC_LENGTH (a), decl);
4546 		else
4547 		  error ("got %d template parameters for %q#T",
4548 			 TREE_VEC_LENGTH (a), current);
4549 		error ("  but %d required", TREE_VEC_LENGTH (t));
4550 		return error_mark_node;
4551 	      }
4552 
4553 	    if (current == decl)
4554 	      current = ctx;
4555 	    else if (current == NULL_TREE)
4556 	      /* Can happen in erroneous input.  */
4557 	      break;
4558 	    else
4559 	      current = (TYPE_P (current)
4560 			 ? TYPE_CONTEXT (current)
4561 			 : DECL_CONTEXT (current));
4562 	  }
4563 
4564       /* Check that the parms are used in the appropriate qualifying scopes
4565 	 in the declarator.  */
4566       if (!comp_template_args
4567 	  (TI_ARGS (tinfo),
4568 	   TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4569 	{
4570 	  error ("\
4571 template arguments to %qD do not match original template %qD",
4572 		 decl, DECL_TEMPLATE_RESULT (tmpl));
4573 	  if (!uses_template_parms (TI_ARGS (tinfo)))
4574 	    inform (input_location, "use template<> for an explicit specialization");
4575 	  /* Avoid crash in import_export_decl.  */
4576 	  DECL_INTERFACE_KNOWN (decl) = 1;
4577 	  return error_mark_node;
4578 	}
4579     }
4580 
4581   DECL_TEMPLATE_RESULT (tmpl) = decl;
4582   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4583 
4584   /* Push template declarations for global functions and types.  Note
4585      that we do not try to push a global template friend declared in a
4586      template class; such a thing may well depend on the template
4587      parameters of the class.  */
4588   if (new_template_p && !ctx
4589       && !(is_friend && template_class_depth (current_class_type) > 0))
4590     {
4591       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4592       if (tmpl == error_mark_node)
4593 	return error_mark_node;
4594 
4595       /* Hide template friend classes that haven't been declared yet.  */
4596       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4597 	{
4598 	  DECL_ANTICIPATED (tmpl) = 1;
4599 	  DECL_FRIEND_P (tmpl) = 1;
4600 	}
4601     }
4602 
4603   if (primary)
4604     {
4605       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4606       int i;
4607 
4608       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4609       if (DECL_CONV_FN_P (tmpl))
4610 	{
4611 	  int depth = TMPL_PARMS_DEPTH (parms);
4612 
4613 	  /* It is a conversion operator. See if the type converted to
4614 	     depends on innermost template operands.  */
4615 
4616 	  if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4617 					 depth))
4618 	    DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4619 	}
4620 
4621       /* Give template template parms a DECL_CONTEXT of the template
4622 	 for which they are a parameter.  */
4623       parms = INNERMOST_TEMPLATE_PARMS (parms);
4624       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
4625 	{
4626 	  tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4627 	  if (TREE_CODE (parm) == TEMPLATE_DECL)
4628 	    DECL_CONTEXT (parm) = tmpl;
4629 	}
4630     }
4631 
4632   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
4633      back to its most general template.  If TMPL is a specialization,
4634      ARGS may only have the innermost set of arguments.  Add the missing
4635      argument levels if necessary.  */
4636   if (DECL_TEMPLATE_INFO (tmpl))
4637     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
4638 
4639   info = build_template_info (tmpl, args);
4640 
4641   if (DECL_IMPLICIT_TYPEDEF_P (decl))
4642     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
4643   else if (DECL_LANG_SPECIFIC (decl))
4644     DECL_TEMPLATE_INFO (decl) = info;
4645 
4646   return DECL_TEMPLATE_RESULT (tmpl);
4647 }
4648 
4649 tree
4650 push_template_decl (tree decl)
4651 {
4652   return push_template_decl_real (decl, false);
4653 }
4654 
4655 /* Called when a class template TYPE is redeclared with the indicated
4656    template PARMS, e.g.:
4657 
4658      template <class T> struct S;
4659      template <class T> struct S {};  */
4660 
4661 bool
4662 redeclare_class_template (tree type, tree parms)
4663 {
4664   tree tmpl;
4665   tree tmpl_parms;
4666   int i;
4667 
4668   if (!TYPE_TEMPLATE_INFO (type))
4669     {
4670       error ("%qT is not a template type", type);
4671       return false;
4672     }
4673 
4674   tmpl = TYPE_TI_TEMPLATE (type);
4675   if (!PRIMARY_TEMPLATE_P (tmpl))
4676     /* The type is nested in some template class.  Nothing to worry
4677        about here; there are no new template parameters for the nested
4678        type.  */
4679     return true;
4680 
4681   if (!parms)
4682     {
4683       error ("template specifiers not specified in declaration of %qD",
4684 	     tmpl);
4685       return false;
4686     }
4687 
4688   parms = INNERMOST_TEMPLATE_PARMS (parms);
4689   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
4690 
4691   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
4692     {
4693       error_n (input_location, TREE_VEC_LENGTH (parms),
4694                "redeclared with %d template parameter",
4695                "redeclared with %d template parameters",
4696                TREE_VEC_LENGTH (parms));
4697       inform_n (input_location, TREE_VEC_LENGTH (tmpl_parms),
4698                 "previous declaration %q+D used %d template parameter",
4699                 "previous declaration %q+D used %d template parameters",
4700                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
4701       return false;
4702     }
4703 
4704   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
4705     {
4706       tree tmpl_parm;
4707       tree parm;
4708       tree tmpl_default;
4709       tree parm_default;
4710 
4711       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
4712           || TREE_VEC_ELT (parms, i) == error_mark_node)
4713         continue;
4714 
4715       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
4716       if (tmpl_parm == error_mark_node)
4717 	return false;
4718 
4719       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4720       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
4721       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
4722 
4723       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
4724 	 TEMPLATE_DECL.  */
4725       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
4726 	  || (TREE_CODE (tmpl_parm) != TYPE_DECL
4727 	      && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
4728 	  || (TREE_CODE (tmpl_parm) != PARM_DECL
4729 	      && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
4730 		  != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
4731 	  || (TREE_CODE (tmpl_parm) == PARM_DECL
4732 	      && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
4733 		  != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
4734 	{
4735 	  error ("template parameter %q+#D", tmpl_parm);
4736 	  error ("redeclared here as %q#D", parm);
4737 	  return false;
4738 	}
4739 
4740       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
4741 	{
4742 	  /* We have in [temp.param]:
4743 
4744 	     A template-parameter may not be given default arguments
4745 	     by two different declarations in the same scope.  */
4746 	  error_at (input_location, "redefinition of default argument for %q#D", parm);
4747 	  inform (DECL_SOURCE_LOCATION (tmpl_parm),
4748 		  "original definition appeared here");
4749 	  return false;
4750 	}
4751 
4752       if (parm_default != NULL_TREE)
4753 	/* Update the previous template parameters (which are the ones
4754 	   that will really count) with the new default value.  */
4755 	TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
4756       else if (tmpl_default != NULL_TREE)
4757 	/* Update the new parameters, too; they'll be used as the
4758 	   parameters for any members.  */
4759 	TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
4760     }
4761 
4762     return true;
4763 }
4764 
4765 /* Simplify EXPR if it is a non-dependent expression.  Returns the
4766    (possibly simplified) expression.  */
4767 
4768 tree
4769 fold_non_dependent_expr (tree expr)
4770 {
4771   if (expr == NULL_TREE)
4772     return NULL_TREE;
4773 
4774   /* If we're in a template, but EXPR isn't value dependent, simplify
4775      it.  We're supposed to treat:
4776 
4777        template <typename T> void f(T[1 + 1]);
4778        template <typename T> void f(T[2]);
4779 
4780      as two declarations of the same function, for example.  */
4781   if (processing_template_decl
4782       && !type_dependent_expression_p (expr)
4783       && !value_dependent_expression_p (expr))
4784     {
4785       HOST_WIDE_INT saved_processing_template_decl;
4786 
4787       saved_processing_template_decl = processing_template_decl;
4788       processing_template_decl = 0;
4789       expr = tsubst_copy_and_build (expr,
4790 				    /*args=*/NULL_TREE,
4791 				    tf_error,
4792 				    /*in_decl=*/NULL_TREE,
4793 				    /*function_p=*/false,
4794 				    /*integral_constant_expression_p=*/true);
4795       processing_template_decl = saved_processing_template_decl;
4796     }
4797   return expr;
4798 }
4799 
4800 /* EXPR is an expression which is used in a constant-expression context.
4801    For instance, it could be a VAR_DECL with a constant initializer.
4802    Extract the innermost constant expression.
4803 
4804    This is basically a more powerful version of
4805    integral_constant_value, which can be used also in templates where
4806    initializers can maintain a syntactic rather than semantic form
4807    (even if they are non-dependent, for access-checking purposes).  */
4808 
4809 static tree
4810 fold_decl_constant_value (tree expr)
4811 {
4812   tree const_expr = expr;
4813   do
4814     {
4815       expr = fold_non_dependent_expr (const_expr);
4816       const_expr = integral_constant_value (expr);
4817     }
4818   while (expr != const_expr);
4819 
4820   return expr;
4821 }
4822 
4823 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
4824    must be a function or a pointer-to-function type, as specified
4825    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
4826    and check that the resulting function has external linkage.  */
4827 
4828 static tree
4829 convert_nontype_argument_function (tree type, tree expr)
4830 {
4831   tree fns = expr;
4832   tree fn, fn_no_ptr;
4833 
4834   fn = instantiate_type (type, fns, tf_none);
4835   if (fn == error_mark_node)
4836     return error_mark_node;
4837 
4838   fn_no_ptr = fn;
4839   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
4840     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
4841   if (TREE_CODE (fn_no_ptr) == BASELINK)
4842     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
4843 
4844   /* [temp.arg.nontype]/1
4845 
4846      A template-argument for a non-type, non-template template-parameter
4847      shall be one of:
4848      [...]
4849      -- the address of an object or function with external linkage.  */
4850   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
4851     {
4852       error ("%qE is not a valid template argument for type %qT "
4853 	     "because function %qD has not external linkage",
4854 	     expr, type, fn_no_ptr);
4855       return NULL_TREE;
4856     }
4857 
4858   return fn;
4859 }
4860 
4861 /* Subroutine of convert_nontype_argument.
4862    Check if EXPR of type TYPE is a valid pointer-to-member constant.
4863    Emit an error otherwise.  */
4864 
4865 static bool
4866 check_valid_ptrmem_cst_expr (tree type, tree expr)
4867 {
4868   STRIP_NOPS (expr);
4869   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
4870     return true;
4871   error ("%qE is not a valid template argument for type %qT",
4872 	 expr, type);
4873   error ("it must be a pointer-to-member of the form `&X::Y'");
4874   return false;
4875 }
4876 
4877 /* Returns TRUE iff the address of OP is value-dependent.
4878 
4879    14.6.2.4 [temp.dep.temp]:
4880    A non-integral non-type template-argument is dependent if its type is
4881    dependent or it has either of the following forms
4882      qualified-id
4883      & qualified-id
4884    and contains a nested-name-specifier which specifies a class-name that
4885    names a dependent type.
4886 
4887    We generalize this to just say that the address of a member of a
4888    dependent class is value-dependent; the above doesn't cover the
4889    address of a static data member named with an unqualified-id.  */
4890 
4891 static bool
4892 has_value_dependent_address (tree op)
4893 {
4894   /* We could use get_inner_reference here, but there's no need;
4895      this is only relevant for template non-type arguments, which
4896      can only be expressed as &id-expression.  */
4897   if (DECL_P (op))
4898     {
4899       tree ctx = CP_DECL_CONTEXT (op);
4900       if (TYPE_P (ctx) && dependent_type_p (ctx))
4901 	return true;
4902     }
4903 
4904   return false;
4905 }
4906 
4907 /* Attempt to convert the non-type template parameter EXPR to the
4908    indicated TYPE.  If the conversion is successful, return the
4909    converted value.  If the conversion is unsuccessful, return
4910    NULL_TREE if we issued an error message, or error_mark_node if we
4911    did not.  We issue error messages for out-and-out bad template
4912    parameters, but not simply because the conversion failed, since we
4913    might be just trying to do argument deduction.  Both TYPE and EXPR
4914    must be non-dependent.
4915 
4916    The conversion follows the special rules described in
4917    [temp.arg.nontype], and it is much more strict than an implicit
4918    conversion.
4919 
4920    This function is called twice for each template argument (see
4921    lookup_template_class for a more accurate description of this
4922    problem). This means that we need to handle expressions which
4923    are not valid in a C++ source, but can be created from the
4924    first call (for instance, casts to perform conversions). These
4925    hacks can go away after we fix the double coercion problem.  */
4926 
4927 static tree
4928 convert_nontype_argument (tree type, tree expr)
4929 {
4930   tree expr_type;
4931 
4932   /* Detect immediately string literals as invalid non-type argument.
4933      This special-case is not needed for correctness (we would easily
4934      catch this later), but only to provide better diagnostic for this
4935      common user mistake. As suggested by DR 100, we do not mention
4936      linkage issues in the diagnostic as this is not the point.  */
4937   if (TREE_CODE (expr) == STRING_CST)
4938     {
4939       error ("%qE is not a valid template argument for type %qT "
4940 	     "because string literals can never be used in this context",
4941 	     expr, type);
4942       return NULL_TREE;
4943     }
4944 
4945   /* Add the ADDR_EXPR now for the benefit of
4946      value_dependent_expression_p.  */
4947   if (TYPE_PTROBV_P (type)
4948       && TREE_CODE (TREE_TYPE (expr)) == ARRAY_TYPE)
4949     expr = decay_conversion (expr);
4950 
4951   /* If we are in a template, EXPR may be non-dependent, but still
4952      have a syntactic, rather than semantic, form.  For example, EXPR
4953      might be a SCOPE_REF, rather than the VAR_DECL to which the
4954      SCOPE_REF refers.  Preserving the qualifying scope is necessary
4955      so that access checking can be performed when the template is
4956      instantiated -- but here we need the resolved form so that we can
4957      convert the argument.  */
4958   if (TYPE_REF_OBJ_P (type)
4959       && has_value_dependent_address (expr))
4960     /* If we want the address and it's value-dependent, don't fold.  */;
4961   else
4962     expr = fold_non_dependent_expr (expr);
4963   if (error_operand_p (expr))
4964     return error_mark_node;
4965   expr_type = TREE_TYPE (expr);
4966 
4967   /* HACK: Due to double coercion, we can get a
4968      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
4969      which is the tree that we built on the first call (see
4970      below when coercing to reference to object or to reference to
4971      function). We just strip everything and get to the arg.
4972      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
4973      for examples.  */
4974   if (TREE_CODE (expr) == NOP_EXPR)
4975     {
4976       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
4977 	{
4978 	  /* ??? Maybe we could use convert_from_reference here, but we
4979 	     would need to relax its constraints because the NOP_EXPR
4980 	     could actually change the type to something more cv-qualified,
4981 	     and this is not folded by convert_from_reference.  */
4982 	  tree addr = TREE_OPERAND (expr, 0);
4983 	  gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
4984 	  gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
4985 	  gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
4986 	  gcc_assert (same_type_ignoring_top_level_qualifiers_p
4987 		      (TREE_TYPE (expr_type),
4988 		       TREE_TYPE (TREE_TYPE (addr))));
4989 
4990 	  expr = TREE_OPERAND (addr, 0);
4991 	  expr_type = TREE_TYPE (expr);
4992 	}
4993 
4994       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
4995 	 parameter is a pointer to object, through decay and
4996 	 qualification conversion. Let's strip everything.  */
4997       else if (TYPE_PTROBV_P (type))
4998 	{
4999 	  STRIP_NOPS (expr);
5000 	  gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
5001 	  gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
5002 	  /* Skip the ADDR_EXPR only if it is part of the decay for
5003 	     an array. Otherwise, it is part of the original argument
5004 	     in the source code.  */
5005 	  if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
5006 	    expr = TREE_OPERAND (expr, 0);
5007 	  expr_type = TREE_TYPE (expr);
5008 	}
5009     }
5010 
5011   /* [temp.arg.nontype]/5, bullet 1
5012 
5013      For a non-type template-parameter of integral or enumeration type,
5014      integral promotions (_conv.prom_) and integral conversions
5015      (_conv.integral_) are applied.  */
5016   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
5017     {
5018       if (!INTEGRAL_OR_ENUMERATION_TYPE_P (expr_type))
5019 	return error_mark_node;
5020 
5021       expr = fold_decl_constant_value (expr);
5022       /* Notice that there are constant expressions like '4 % 0' which
5023 	 do not fold into integer constants.  */
5024       if (TREE_CODE (expr) != INTEGER_CST)
5025 	{
5026 	  error ("%qE is not a valid template argument for type %qT "
5027 		 "because it is a non-constant expression", expr, type);
5028 	  return NULL_TREE;
5029 	}
5030 
5031       /* At this point, an implicit conversion does what we want,
5032 	 because we already know that the expression is of integral
5033 	 type.  */
5034       expr = ocp_convert (type, expr, CONV_IMPLICIT, LOOKUP_PROTECT);
5035       if (expr == error_mark_node)
5036 	return error_mark_node;
5037 
5038       /* Conversion was allowed: fold it to a bare integer constant.  */
5039       expr = fold (expr);
5040     }
5041   /* [temp.arg.nontype]/5, bullet 2
5042 
5043      For a non-type template-parameter of type pointer to object,
5044      qualification conversions (_conv.qual_) and the array-to-pointer
5045      conversion (_conv.array_) are applied.  */
5046   else if (TYPE_PTROBV_P (type))
5047     {
5048       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
5049 
5050 	 A template-argument for a non-type, non-template template-parameter
5051 	 shall be one of: [...]
5052 
5053 	 -- the name of a non-type template-parameter;
5054 	 -- the address of an object or function with external linkage, [...]
5055 	    expressed as "& id-expression" where the & is optional if the name
5056 	    refers to a function or array, or if the corresponding
5057 	    template-parameter is a reference.
5058 
5059 	Here, we do not care about functions, as they are invalid anyway
5060 	for a parameter of type pointer-to-object.  */
5061 
5062       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
5063 	/* Non-type template parameters are OK.  */
5064 	;
5065       else if (TREE_CODE (expr) != ADDR_EXPR
5066 	       && TREE_CODE (expr_type) != ARRAY_TYPE)
5067 	{
5068 	  if (TREE_CODE (expr) == VAR_DECL)
5069 	    {
5070 	      error ("%qD is not a valid template argument "
5071 		     "because %qD is a variable, not the address of "
5072 		     "a variable",
5073 		     expr, expr);
5074 	      return NULL_TREE;
5075 	    }
5076 	  /* Other values, like integer constants, might be valid
5077 	     non-type arguments of some other type.  */
5078 	  return error_mark_node;
5079 	}
5080       else
5081 	{
5082 	  tree decl;
5083 
5084 	  decl = ((TREE_CODE (expr) == ADDR_EXPR)
5085 		  ? TREE_OPERAND (expr, 0) : expr);
5086 	  if (TREE_CODE (decl) != VAR_DECL)
5087 	    {
5088 	      error ("%qE is not a valid template argument of type %qT "
5089 		     "because %qE is not a variable",
5090 		     expr, type, decl);
5091 	      return NULL_TREE;
5092 	    }
5093 	  else if (!DECL_EXTERNAL_LINKAGE_P (decl))
5094 	    {
5095 	      error ("%qE is not a valid template argument of type %qT "
5096 		     "because %qD does not have external linkage",
5097 		     expr, type, decl);
5098 	      return NULL_TREE;
5099 	    }
5100 	}
5101 
5102       expr = decay_conversion (expr);
5103       if (expr == error_mark_node)
5104 	return error_mark_node;
5105 
5106       expr = perform_qualification_conversions (type, expr);
5107       if (expr == error_mark_node)
5108 	return error_mark_node;
5109     }
5110   /* [temp.arg.nontype]/5, bullet 3
5111 
5112      For a non-type template-parameter of type reference to object, no
5113      conversions apply. The type referred to by the reference may be more
5114      cv-qualified than the (otherwise identical) type of the
5115      template-argument. The template-parameter is bound directly to the
5116      template-argument, which must be an lvalue.  */
5117   else if (TYPE_REF_OBJ_P (type))
5118     {
5119       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
5120 						      expr_type))
5121 	return error_mark_node;
5122 
5123       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
5124 	{
5125 	  error ("%qE is not a valid template argument for type %qT "
5126 		 "because of conflicts in cv-qualification", expr, type);
5127 	  return NULL_TREE;
5128 	}
5129 
5130       if (!real_lvalue_p (expr))
5131 	{
5132 	  error ("%qE is not a valid template argument for type %qT "
5133 		 "because it is not an lvalue", expr, type);
5134 	  return NULL_TREE;
5135 	}
5136 
5137       /* [temp.arg.nontype]/1
5138 
5139 	 A template-argument for a non-type, non-template template-parameter
5140 	 shall be one of: [...]
5141 
5142 	 -- the address of an object or function with external linkage.  */
5143       if (TREE_CODE (expr) == INDIRECT_REF
5144 	  && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
5145 	{
5146 	  expr = TREE_OPERAND (expr, 0);
5147 	  if (DECL_P (expr))
5148 	    {
5149 	      error ("%q#D is not a valid template argument for type %qT "
5150 		     "because a reference variable does not have a constant "
5151 		     "address", expr, type);
5152 	      return NULL_TREE;
5153 	    }
5154 	}
5155 
5156       if (!DECL_P (expr))
5157 	{
5158 	  error ("%qE is not a valid template argument for type %qT "
5159 		 "because it is not an object with external linkage",
5160 		 expr, type);
5161 	  return NULL_TREE;
5162 	}
5163 
5164       if (!DECL_EXTERNAL_LINKAGE_P (expr))
5165 	{
5166 	  error ("%qE is not a valid template argument for type %qT "
5167 		 "because object %qD has not external linkage",
5168 		 expr, type, expr);
5169 	  return NULL_TREE;
5170 	}
5171 
5172       expr = build_nop (type, build_address (expr));
5173     }
5174   /* [temp.arg.nontype]/5, bullet 4
5175 
5176      For a non-type template-parameter of type pointer to function, only
5177      the function-to-pointer conversion (_conv.func_) is applied. If the
5178      template-argument represents a set of overloaded functions (or a
5179      pointer to such), the matching function is selected from the set
5180      (_over.over_).  */
5181   else if (TYPE_PTRFN_P (type))
5182     {
5183       /* If the argument is a template-id, we might not have enough
5184 	 context information to decay the pointer.  */
5185       if (!type_unknown_p (expr_type))
5186 	{
5187 	  expr = decay_conversion (expr);
5188 	  if (expr == error_mark_node)
5189 	    return error_mark_node;
5190 	}
5191 
5192       expr = convert_nontype_argument_function (type, expr);
5193       if (!expr || expr == error_mark_node)
5194 	return expr;
5195 
5196       if (TREE_CODE (expr) != ADDR_EXPR)
5197 	{
5198 	  error ("%qE is not a valid template argument for type %qT", expr, type);
5199 	  error ("it must be the address of a function with external linkage");
5200 	  return NULL_TREE;
5201 	}
5202     }
5203   /* [temp.arg.nontype]/5, bullet 5
5204 
5205      For a non-type template-parameter of type reference to function, no
5206      conversions apply. If the template-argument represents a set of
5207      overloaded functions, the matching function is selected from the set
5208      (_over.over_).  */
5209   else if (TYPE_REFFN_P (type))
5210     {
5211       if (TREE_CODE (expr) == ADDR_EXPR)
5212 	{
5213 	  error ("%qE is not a valid template argument for type %qT "
5214 		 "because it is a pointer", expr, type);
5215 	  inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
5216 	  return NULL_TREE;
5217 	}
5218 
5219       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
5220       if (!expr || expr == error_mark_node)
5221 	return expr;
5222 
5223       expr = build_nop (type, build_address (expr));
5224     }
5225   /* [temp.arg.nontype]/5, bullet 6
5226 
5227      For a non-type template-parameter of type pointer to member function,
5228      no conversions apply. If the template-argument represents a set of
5229      overloaded member functions, the matching member function is selected
5230      from the set (_over.over_).  */
5231   else if (TYPE_PTRMEMFUNC_P (type))
5232     {
5233       expr = instantiate_type (type, expr, tf_none);
5234       if (expr == error_mark_node)
5235 	return error_mark_node;
5236 
5237       /* [temp.arg.nontype] bullet 1 says the pointer to member
5238          expression must be a pointer-to-member constant.  */
5239       if (!check_valid_ptrmem_cst_expr (type, expr))
5240 	return error_mark_node;
5241 
5242       /* There is no way to disable standard conversions in
5243 	 resolve_address_of_overloaded_function (called by
5244 	 instantiate_type). It is possible that the call succeeded by
5245 	 converting &B::I to &D::I (where B is a base of D), so we need
5246 	 to reject this conversion here.
5247 
5248 	 Actually, even if there was a way to disable standard conversions,
5249 	 it would still be better to reject them here so that we can
5250 	 provide a superior diagnostic.  */
5251       if (!same_type_p (TREE_TYPE (expr), type))
5252 	{
5253 	  error ("%qE is not a valid template argument for type %qT "
5254 		 "because it is of type %qT", expr, type,
5255 		 TREE_TYPE (expr));
5256 	  /* If we are just one standard conversion off, explain.  */
5257 	  if (can_convert (type, TREE_TYPE (expr)))
5258 	    inform (input_location,
5259 		    "standard conversions are not allowed in this context");
5260 	  return NULL_TREE;
5261 	}
5262     }
5263   /* [temp.arg.nontype]/5, bullet 7
5264 
5265      For a non-type template-parameter of type pointer to data member,
5266      qualification conversions (_conv.qual_) are applied.  */
5267   else if (TYPE_PTRMEM_P (type))
5268     {
5269       /* [temp.arg.nontype] bullet 1 says the pointer to member
5270          expression must be a pointer-to-member constant.  */
5271       if (!check_valid_ptrmem_cst_expr (type, expr))
5272 	return error_mark_node;
5273 
5274       expr = perform_qualification_conversions (type, expr);
5275       if (expr == error_mark_node)
5276 	return expr;
5277     }
5278   /* A template non-type parameter must be one of the above.  */
5279   else
5280     gcc_unreachable ();
5281 
5282   /* Sanity check: did we actually convert the argument to the
5283      right type?  */
5284   gcc_assert (same_type_p (type, TREE_TYPE (expr)));
5285   return expr;
5286 }
5287 
5288 /* Subroutine of coerce_template_template_parms, which returns 1 if
5289    PARM_PARM and ARG_PARM match using the rule for the template
5290    parameters of template template parameters. Both PARM and ARG are
5291    template parameters; the rest of the arguments are the same as for
5292    coerce_template_template_parms.
5293  */
5294 static int
5295 coerce_template_template_parm (tree parm,
5296                               tree arg,
5297                               tsubst_flags_t complain,
5298                               tree in_decl,
5299                               tree outer_args)
5300 {
5301   if (arg == NULL_TREE || arg == error_mark_node
5302       || parm == NULL_TREE || parm == error_mark_node)
5303     return 0;
5304 
5305   if (TREE_CODE (arg) != TREE_CODE (parm))
5306     return 0;
5307 
5308   switch (TREE_CODE (parm))
5309     {
5310     case TEMPLATE_DECL:
5311       /* We encounter instantiations of templates like
5312 	 template <template <template <class> class> class TT>
5313 	 class C;  */
5314       {
5315 	tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5316 	tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5317 
5318 	if (!coerce_template_template_parms
5319 	    (parmparm, argparm, complain, in_decl, outer_args))
5320 	  return 0;
5321       }
5322       /* Fall through.  */
5323 
5324     case TYPE_DECL:
5325       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
5326 	  && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5327 	/* Argument is a parameter pack but parameter is not.  */
5328 	return 0;
5329       break;
5330 
5331     case PARM_DECL:
5332       /* The tsubst call is used to handle cases such as
5333 
5334            template <int> class C {};
5335 	   template <class T, template <T> class TT> class D {};
5336 	   D<int, C> d;
5337 
5338 	 i.e. the parameter list of TT depends on earlier parameters.  */
5339       if (!uses_template_parms (TREE_TYPE (arg))
5340 	  && !same_type_p
5341 	        (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
5342 		 TREE_TYPE (arg)))
5343 	return 0;
5344 
5345       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
5346 	  && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5347 	/* Argument is a parameter pack but parameter is not.  */
5348 	return 0;
5349 
5350       break;
5351 
5352     default:
5353       gcc_unreachable ();
5354     }
5355 
5356   return 1;
5357 }
5358 
5359 
5360 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
5361    template template parameters.  Both PARM_PARMS and ARG_PARMS are
5362    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
5363    or PARM_DECL.
5364 
5365    Consider the example:
5366      template <class T> class A;
5367      template<template <class U> class TT> class B;
5368 
5369    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
5370    the parameters to A, and OUTER_ARGS contains A.  */
5371 
5372 static int
5373 coerce_template_template_parms (tree parm_parms,
5374 				tree arg_parms,
5375 				tsubst_flags_t complain,
5376 				tree in_decl,
5377 				tree outer_args)
5378 {
5379   int nparms, nargs, i;
5380   tree parm, arg;
5381   int variadic_p = 0;
5382 
5383   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
5384   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
5385 
5386   nparms = TREE_VEC_LENGTH (parm_parms);
5387   nargs = TREE_VEC_LENGTH (arg_parms);
5388 
5389   /* Determine whether we have a parameter pack at the end of the
5390      template template parameter's template parameter list.  */
5391   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
5392     {
5393       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
5394 
5395       if (parm == error_mark_node)
5396 	return 0;
5397 
5398       switch (TREE_CODE (parm))
5399         {
5400         case TEMPLATE_DECL:
5401         case TYPE_DECL:
5402           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5403             variadic_p = 1;
5404           break;
5405 
5406         case PARM_DECL:
5407           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5408             variadic_p = 1;
5409           break;
5410 
5411         default:
5412           gcc_unreachable ();
5413         }
5414     }
5415 
5416   if (nargs != nparms
5417       && !(variadic_p && nargs >= nparms - 1))
5418     return 0;
5419 
5420   /* Check all of the template parameters except the parameter pack at
5421      the end (if any).  */
5422   for (i = 0; i < nparms - variadic_p; ++i)
5423     {
5424       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
5425           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5426         continue;
5427 
5428       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5429       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5430 
5431       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5432                                           outer_args))
5433 	return 0;
5434 
5435     }
5436 
5437   if (variadic_p)
5438     {
5439       /* Check each of the template parameters in the template
5440 	 argument against the template parameter pack at the end of
5441 	 the template template parameter.  */
5442       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
5443 	return 0;
5444 
5445       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5446 
5447       for (; i < nargs; ++i)
5448         {
5449           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5450             continue;
5451 
5452           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5453 
5454           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5455                                               outer_args))
5456             return 0;
5457         }
5458     }
5459 
5460   return 1;
5461 }
5462 
5463 /* Verifies that the deduced template arguments (in TARGS) for the
5464    template template parameters (in TPARMS) represent valid bindings,
5465    by comparing the template parameter list of each template argument
5466    to the template parameter list of its corresponding template
5467    template parameter, in accordance with DR150. This
5468    routine can only be called after all template arguments have been
5469    deduced. It will return TRUE if all of the template template
5470    parameter bindings are okay, FALSE otherwise.  */
5471 bool
5472 template_template_parm_bindings_ok_p (tree tparms, tree targs)
5473 {
5474   int i, ntparms = TREE_VEC_LENGTH (tparms);
5475   bool ret = true;
5476 
5477   /* We're dealing with template parms in this process.  */
5478   ++processing_template_decl;
5479 
5480   targs = INNERMOST_TEMPLATE_ARGS (targs);
5481 
5482   for (i = 0; i < ntparms; ++i)
5483     {
5484       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
5485       tree targ = TREE_VEC_ELT (targs, i);
5486 
5487       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
5488 	{
5489 	  tree packed_args = NULL_TREE;
5490 	  int idx, len = 1;
5491 
5492 	  if (ARGUMENT_PACK_P (targ))
5493 	    {
5494 	      /* Look inside the argument pack.  */
5495 	      packed_args = ARGUMENT_PACK_ARGS (targ);
5496 	      len = TREE_VEC_LENGTH (packed_args);
5497 	    }
5498 
5499 	  for (idx = 0; idx < len; ++idx)
5500 	    {
5501 	      tree targ_parms = NULL_TREE;
5502 
5503 	      if (packed_args)
5504 		/* Extract the next argument from the argument
5505 		   pack.  */
5506 		targ = TREE_VEC_ELT (packed_args, idx);
5507 
5508 	      if (PACK_EXPANSION_P (targ))
5509 		/* Look at the pattern of the pack expansion.  */
5510 		targ = PACK_EXPANSION_PATTERN (targ);
5511 
5512 	      /* Extract the template parameters from the template
5513 		 argument.  */
5514 	      if (TREE_CODE (targ) == TEMPLATE_DECL)
5515 		targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
5516 	      else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
5517 		targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
5518 
5519 	      /* Verify that we can coerce the template template
5520 		 parameters from the template argument to the template
5521 		 parameter.  This requires an exact match.  */
5522 	      if (targ_parms
5523 		  && !coerce_template_template_parms
5524 		       (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
5525 			targ_parms,
5526 			tf_none,
5527 			tparm,
5528 			targs))
5529 		{
5530 		  ret = false;
5531 		  goto out;
5532 		}
5533 	    }
5534 	}
5535     }
5536 
5537  out:
5538 
5539   --processing_template_decl;
5540   return ret;
5541 }
5542 
5543 /* Convert the indicated template ARG as necessary to match the
5544    indicated template PARM.  Returns the converted ARG, or
5545    error_mark_node if the conversion was unsuccessful.  Error and
5546    warning messages are issued under control of COMPLAIN.  This
5547    conversion is for the Ith parameter in the parameter list.  ARGS is
5548    the full set of template arguments deduced so far.  */
5549 
5550 static tree
5551 convert_template_argument (tree parm,
5552 			   tree arg,
5553 			   tree args,
5554 			   tsubst_flags_t complain,
5555 			   int i,
5556 			   tree in_decl)
5557 {
5558   tree orig_arg;
5559   tree val;
5560   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
5561 
5562   if (TREE_CODE (arg) == TREE_LIST
5563       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
5564     {
5565       /* The template argument was the name of some
5566 	 member function.  That's usually
5567 	 invalid, but static members are OK.  In any
5568 	 case, grab the underlying fields/functions
5569 	 and issue an error later if required.  */
5570       orig_arg = TREE_VALUE (arg);
5571       TREE_TYPE (arg) = unknown_type_node;
5572     }
5573 
5574   orig_arg = arg;
5575 
5576   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
5577   requires_type = (TREE_CODE (parm) == TYPE_DECL
5578 		   || requires_tmpl_type);
5579 
5580   /* When determining whether an argument pack expansion is a template,
5581      look at the pattern.  */
5582   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
5583     arg = PACK_EXPANSION_PATTERN (arg);
5584 
5585   /* Deal with an injected-class-name used as a template template arg.  */
5586   if (requires_tmpl_type && CLASS_TYPE_P (arg))
5587     {
5588       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
5589       if (TREE_CODE (t) == TEMPLATE_DECL)
5590 	{
5591 	  if (complain & tf_warning_or_error)
5592 	    pedwarn (input_location, OPT_pedantic, "injected-class-name %qD"
5593 		     " used as template template argument", TYPE_NAME (arg));
5594 	  else if (flag_pedantic_errors)
5595 	    t = arg;
5596 
5597 	  arg = t;
5598 	}
5599     }
5600 
5601   is_tmpl_type =
5602     ((TREE_CODE (arg) == TEMPLATE_DECL
5603       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
5604      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5605      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
5606 
5607   if (is_tmpl_type
5608       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5609 	  || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
5610     arg = TYPE_STUB_DECL (arg);
5611 
5612   is_type = TYPE_P (arg) || is_tmpl_type;
5613 
5614   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
5615       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
5616     {
5617       permerror (input_location, "to refer to a type member of a template parameter, "
5618 	         "use %<typename %E%>", orig_arg);
5619 
5620       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
5621 				     TREE_OPERAND (arg, 1),
5622 				     typename_type,
5623 				     complain & tf_error);
5624       arg = orig_arg;
5625       is_type = 1;
5626     }
5627   if (is_type != requires_type)
5628     {
5629       if (in_decl)
5630 	{
5631 	  if (complain & tf_error)
5632 	    {
5633 	      error ("type/value mismatch at argument %d in template "
5634 		     "parameter list for %qD",
5635 		     i + 1, in_decl);
5636 	      if (is_type)
5637 		error ("  expected a constant of type %qT, got %qT",
5638 		       TREE_TYPE (parm),
5639 		       (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
5640 	      else if (requires_tmpl_type)
5641 		error ("  expected a class template, got %qE", orig_arg);
5642 	      else
5643 		error ("  expected a type, got %qE", orig_arg);
5644 	    }
5645 	}
5646       return error_mark_node;
5647     }
5648   if (is_tmpl_type ^ requires_tmpl_type)
5649     {
5650       if (in_decl && (complain & tf_error))
5651 	{
5652 	  error ("type/value mismatch at argument %d in template "
5653 		 "parameter list for %qD",
5654 		 i + 1, in_decl);
5655 	  if (is_tmpl_type)
5656 	    error ("  expected a type, got %qT", DECL_NAME (arg));
5657 	  else
5658 	    error ("  expected a class template, got %qT", orig_arg);
5659 	}
5660       return error_mark_node;
5661     }
5662 
5663   if (is_type)
5664     {
5665       if (requires_tmpl_type)
5666 	{
5667 	  if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
5668 	    /* The number of argument required is not known yet.
5669 	       Just accept it for now.  */
5670 	    val = TREE_TYPE (arg);
5671 	  else
5672 	    {
5673 	      tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5674 	      tree argparm;
5675 
5676               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5677 
5678 	      if (coerce_template_template_parms (parmparm, argparm,
5679 						  complain, in_decl,
5680 						  args))
5681 		{
5682 		  val = arg;
5683 
5684 		  /* TEMPLATE_TEMPLATE_PARM node is preferred over
5685 		     TEMPLATE_DECL.  */
5686 		  if (val != error_mark_node)
5687                     {
5688                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
5689                         val = TREE_TYPE (val);
5690 		      if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
5691 			val = make_pack_expansion (val);
5692                     }
5693 		}
5694 	      else
5695 		{
5696 		  if (in_decl && (complain & tf_error))
5697 		    {
5698 		      error ("type/value mismatch at argument %d in "
5699 			     "template parameter list for %qD",
5700 			     i + 1, in_decl);
5701 		      error ("  expected a template of type %qD, got %qT",
5702 			     parm, orig_arg);
5703 		    }
5704 
5705 		  val = error_mark_node;
5706 		}
5707 	    }
5708 	}
5709       else
5710 	val = orig_arg;
5711       /* We only form one instance of each template specialization.
5712 	 Therefore, if we use a non-canonical variant (i.e., a
5713 	 typedef), any future messages referring to the type will use
5714 	 the typedef, which is confusing if those future uses do not
5715 	 themselves also use the typedef.  */
5716       if (TYPE_P (val))
5717 	val = strip_typedefs (val);
5718     }
5719   else
5720     {
5721       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
5722 
5723       if (invalid_nontype_parm_type_p (t, complain))
5724 	return error_mark_node;
5725 
5726       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
5727 	{
5728 	  if (same_type_p (t, TREE_TYPE (orig_arg)))
5729 	    val = orig_arg;
5730 	  else
5731 	    {
5732 	      /* Not sure if this is reachable, but it doesn't hurt
5733 		 to be robust.  */
5734 	      error ("type mismatch in nontype parameter pack");
5735 	      val = error_mark_node;
5736 	    }
5737 	}
5738       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
5739 	/* We used to call digest_init here.  However, digest_init
5740 	   will report errors, which we don't want when complain
5741 	   is zero.  More importantly, digest_init will try too
5742 	   hard to convert things: for example, `0' should not be
5743 	   converted to pointer type at this point according to
5744 	   the standard.  Accepting this is not merely an
5745 	   extension, since deciding whether or not these
5746 	   conversions can occur is part of determining which
5747 	   function template to call, or whether a given explicit
5748 	   argument specification is valid.  */
5749 	val = convert_nontype_argument (t, orig_arg);
5750       else
5751 	val = orig_arg;
5752 
5753       if (val == NULL_TREE)
5754 	val = error_mark_node;
5755       else if (val == error_mark_node && (complain & tf_error))
5756 	error ("could not convert template argument %qE to %qT",  orig_arg, t);
5757 
5758       if (TREE_CODE (val) == SCOPE_REF)
5759 	{
5760 	  /* Strip typedefs from the SCOPE_REF.  */
5761 	  tree type = strip_typedefs (TREE_TYPE (val));
5762 	  tree scope = strip_typedefs (TREE_OPERAND (val, 0));
5763 	  val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
5764 				      QUALIFIED_NAME_IS_TEMPLATE (val));
5765 	}
5766     }
5767 
5768   return val;
5769 }
5770 
5771 /* Coerces the remaining template arguments in INNER_ARGS (from
5772    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
5773    Returns the coerced argument pack. PARM_IDX is the position of this
5774    parameter in the template parameter list. ARGS is the original
5775    template argument list.  */
5776 static tree
5777 coerce_template_parameter_pack (tree parms,
5778                                 int parm_idx,
5779                                 tree args,
5780                                 tree inner_args,
5781                                 int arg_idx,
5782                                 tree new_args,
5783                                 int* lost,
5784                                 tree in_decl,
5785                                 tsubst_flags_t complain)
5786 {
5787   tree parm = TREE_VEC_ELT (parms, parm_idx);
5788   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5789   tree packed_args;
5790   tree argument_pack;
5791   tree packed_types = NULL_TREE;
5792 
5793   if (arg_idx > nargs)
5794     arg_idx = nargs;
5795 
5796   packed_args = make_tree_vec (nargs - arg_idx);
5797 
5798   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
5799       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
5800     {
5801       /* When the template parameter is a non-type template
5802          parameter pack whose type uses parameter packs, we need
5803          to look at each of the template arguments
5804          separately. Build a vector of the types for these
5805          non-type template parameters in PACKED_TYPES.  */
5806       tree expansion
5807         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
5808       packed_types = tsubst_pack_expansion (expansion, args,
5809                                             complain, in_decl);
5810 
5811       if (packed_types == error_mark_node)
5812         return error_mark_node;
5813 
5814       /* Check that we have the right number of arguments.  */
5815       if (arg_idx < nargs
5816           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
5817           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
5818         {
5819           int needed_parms
5820             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
5821           error ("wrong number of template arguments (%d, should be %d)",
5822                  nargs, needed_parms);
5823           return error_mark_node;
5824         }
5825 
5826       /* If we aren't able to check the actual arguments now
5827          (because they haven't been expanded yet), we can at least
5828          verify that all of the types used for the non-type
5829          template parameter pack are, in fact, valid for non-type
5830          template parameters.  */
5831       if (arg_idx < nargs
5832           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
5833         {
5834           int j, len = TREE_VEC_LENGTH (packed_types);
5835           for (j = 0; j < len; ++j)
5836             {
5837               tree t = TREE_VEC_ELT (packed_types, j);
5838               if (invalid_nontype_parm_type_p (t, complain))
5839                 return error_mark_node;
5840             }
5841         }
5842     }
5843 
5844   /* Convert the remaining arguments, which will be a part of the
5845      parameter pack "parm".  */
5846   for (; arg_idx < nargs; ++arg_idx)
5847     {
5848       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
5849       tree actual_parm = TREE_VALUE (parm);
5850 
5851       if (packed_types && !PACK_EXPANSION_P (arg))
5852         {
5853           /* When we have a vector of types (corresponding to the
5854              non-type template parameter pack that uses parameter
5855              packs in its type, as mention above), and the
5856              argument is not an expansion (which expands to a
5857              currently unknown number of arguments), clone the
5858              parm and give it the next type in PACKED_TYPES.  */
5859           actual_parm = copy_node (actual_parm);
5860           TREE_TYPE (actual_parm) =
5861             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
5862         }
5863 
5864       if (arg != error_mark_node)
5865 	arg = convert_template_argument (actual_parm,
5866 					 arg, new_args, complain, parm_idx,
5867 					 in_decl);
5868       if (arg == error_mark_node)
5869         (*lost)++;
5870       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg;
5871     }
5872 
5873   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
5874       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
5875     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
5876   else
5877     {
5878       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
5879       TREE_TYPE (argument_pack)
5880         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
5881       TREE_CONSTANT (argument_pack) = 1;
5882     }
5883 
5884   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
5885 #ifdef ENABLE_CHECKING
5886   SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
5887 				       TREE_VEC_LENGTH (packed_args));
5888 #endif
5889   return argument_pack;
5890 }
5891 
5892 /* Convert all template arguments to their appropriate types, and
5893    return a vector containing the innermost resulting template
5894    arguments.  If any error occurs, return error_mark_node. Error and
5895    warning messages are issued under control of COMPLAIN.
5896 
5897    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
5898    for arguments not specified in ARGS.  Otherwise, if
5899    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
5900    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
5901    USE_DEFAULT_ARGS is false, then all arguments must be specified in
5902    ARGS.  */
5903 
5904 static tree
5905 coerce_template_parms (tree parms,
5906 		       tree args,
5907 		       tree in_decl,
5908 		       tsubst_flags_t complain,
5909 		       bool require_all_args,
5910 		       bool use_default_args)
5911 {
5912   int nparms, nargs, parm_idx, arg_idx, lost = 0;
5913   tree inner_args;
5914   tree new_args;
5915   tree new_inner_args;
5916   int saved_unevaluated_operand;
5917   int saved_inhibit_evaluation_warnings;
5918 
5919   /* When used as a boolean value, indicates whether this is a
5920      variadic template parameter list. Since it's an int, we can also
5921      subtract it from nparms to get the number of non-variadic
5922      parameters.  */
5923   int variadic_p = 0;
5924 
5925   nparms = TREE_VEC_LENGTH (parms);
5926 
5927   /* Determine if there are any parameter packs.  */
5928   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
5929     {
5930       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
5931       if (template_parameter_pack_p (tparm))
5932 	++variadic_p;
5933     }
5934 
5935   inner_args = INNERMOST_TEMPLATE_ARGS (args);
5936   /* If there are 0 or 1 parameter packs, we need to expand any argument
5937      packs so that we can deduce a parameter pack from some non-packed args
5938      followed by an argument pack, as in variadic85.C.  If there are more
5939      than that, we need to leave argument packs intact so the arguments are
5940      assigned to the right parameter packs.  This should only happen when
5941      dealing with a nested class inside a partial specialization of a class
5942      template, as in variadic92.C.  */
5943   if (variadic_p <= 1)
5944     inner_args = expand_template_argument_pack (inner_args);
5945 
5946   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5947   if ((nargs > nparms && !variadic_p)
5948       || (nargs < nparms - variadic_p
5949 	  && require_all_args
5950 	  && (!use_default_args
5951 	      || (TREE_VEC_ELT (parms, nargs) != error_mark_node
5952                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
5953     {
5954       if (complain & tf_error)
5955 	{
5956           const char *or_more = "";
5957           if (variadic_p)
5958             {
5959               or_more = " or more";
5960               --nparms;
5961             }
5962 
5963 	  error ("wrong number of template arguments (%d, should be %d%s)",
5964                  nargs, nparms, or_more);
5965 
5966 	  if (in_decl)
5967 	    error ("provided for %q+D", in_decl);
5968 	}
5969 
5970       return error_mark_node;
5971     }
5972 
5973   /* We need to evaluate the template arguments, even though this
5974      template-id may be nested within a "sizeof".  */
5975   saved_unevaluated_operand = cp_unevaluated_operand;
5976   cp_unevaluated_operand = 0;
5977   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
5978   c_inhibit_evaluation_warnings = 0;
5979   new_inner_args = make_tree_vec (nparms);
5980   new_args = add_outermost_template_args (args, new_inner_args);
5981   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
5982     {
5983       tree arg;
5984       tree parm;
5985 
5986       /* Get the Ith template parameter.  */
5987       parm = TREE_VEC_ELT (parms, parm_idx);
5988 
5989       if (parm == error_mark_node)
5990       {
5991         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
5992         continue;
5993       }
5994 
5995       /* Calculate the next argument.  */
5996       if (arg_idx < nargs)
5997 	arg = TREE_VEC_ELT (inner_args, arg_idx);
5998       else
5999 	arg = NULL_TREE;
6000 
6001       if (template_parameter_pack_p (TREE_VALUE (parm))
6002 	  && !(arg && ARGUMENT_PACK_P (arg)))
6003         {
6004 	  /* All remaining arguments will be placed in the
6005 	     template parameter pack PARM.  */
6006 	  arg = coerce_template_parameter_pack (parms, parm_idx, args,
6007 						inner_args, arg_idx,
6008 						new_args, &lost,
6009 						in_decl, complain);
6010 
6011           /* Store this argument.  */
6012           if (arg == error_mark_node)
6013             lost++;
6014           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
6015 
6016 	  /* We are done with all of the arguments.  */
6017 	  arg_idx = nargs;
6018 
6019           continue;
6020         }
6021       else if (arg)
6022 	{
6023           if (PACK_EXPANSION_P (arg))
6024             {
6025 	      if (complain & tf_error)
6026 		{
6027 		  /* FIXME this restriction was removed by N2555; see
6028 		     bug 35722.  */
6029 		  /* If ARG is a pack expansion, but PARM is not a
6030 		     template parameter pack (if it were, we would have
6031 		     handled it above), we're trying to expand into a
6032 		     fixed-length argument list.  */
6033 		  if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
6034 		    sorry ("cannot expand %<%E%> into a fixed-length "
6035 			   "argument list", arg);
6036 		  else
6037 		    sorry ("cannot expand %<%T%> into a fixed-length "
6038 			   "argument list", arg);
6039 		}
6040 	      ++lost;
6041             }
6042         }
6043       else if (require_all_args)
6044 	{
6045 	  /* There must be a default arg in this case.  */
6046 	  arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
6047 				     complain, in_decl);
6048 	  /* The position of the first default template argument,
6049 	     is also the number of non-defaulted arguments in NEW_INNER_ARGS.
6050 	     Record that.  */
6051 	  if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6052 	    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args, arg_idx);
6053 	}
6054       else
6055 	break;
6056 
6057       if (arg == error_mark_node)
6058 	{
6059 	  if (complain & tf_error)
6060 	    error ("template argument %d is invalid", arg_idx + 1);
6061 	}
6062       else if (!arg)
6063         /* This only occurs if there was an error in the template
6064            parameter list itself (which we would already have
6065            reported) that we are trying to recover from, e.g., a class
6066            template with a parameter list such as
6067            template<typename..., typename>.  */
6068 	++lost;
6069       else
6070 	arg = convert_template_argument (TREE_VALUE (parm),
6071 					 arg, new_args, complain,
6072                                          parm_idx, in_decl);
6073 
6074       if (arg == error_mark_node)
6075 	lost++;
6076       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
6077     }
6078   cp_unevaluated_operand = saved_unevaluated_operand;
6079   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
6080 
6081   if (lost)
6082     return error_mark_node;
6083 
6084 #ifdef ENABLE_CHECKING
6085   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6086     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
6087 					 TREE_VEC_LENGTH (new_inner_args));
6088 #endif
6089 
6090   return new_inner_args;
6091 }
6092 
6093 /* Returns 1 if template args OT and NT are equivalent.  */
6094 
6095 static int
6096 template_args_equal (tree ot, tree nt)
6097 {
6098   if (nt == ot)
6099     return 1;
6100 
6101   if (TREE_CODE (nt) == TREE_VEC)
6102     /* For member templates */
6103     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
6104   else if (PACK_EXPANSION_P (ot))
6105     return PACK_EXPANSION_P (nt)
6106       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
6107                               PACK_EXPANSION_PATTERN (nt));
6108   else if (ARGUMENT_PACK_P (ot))
6109     {
6110       int i, len;
6111       tree opack, npack;
6112 
6113       if (!ARGUMENT_PACK_P (nt))
6114 	return 0;
6115 
6116       opack = ARGUMENT_PACK_ARGS (ot);
6117       npack = ARGUMENT_PACK_ARGS (nt);
6118       len = TREE_VEC_LENGTH (opack);
6119       if (TREE_VEC_LENGTH (npack) != len)
6120 	return 0;
6121       for (i = 0; i < len; ++i)
6122 	if (!template_args_equal (TREE_VEC_ELT (opack, i),
6123 				  TREE_VEC_ELT (npack, i)))
6124 	  return 0;
6125       return 1;
6126     }
6127   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
6128     {
6129       /* We get here probably because we are in the middle of substituting
6130          into the pattern of a pack expansion. In that case the
6131 	 ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
6132 	 interested in. So we want to use the initial pack argument for
6133 	 the comparison.  */
6134       ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
6135       if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
6136 	nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
6137       return template_args_equal (ot, nt);
6138     }
6139   else if (TYPE_P (nt))
6140     return TYPE_P (ot) && same_type_p (ot, nt);
6141   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
6142     return 0;
6143   else
6144     return cp_tree_equal (ot, nt);
6145 }
6146 
6147 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
6148    of template arguments.  Returns 0 otherwise.  */
6149 
6150 int
6151 comp_template_args (tree oldargs, tree newargs)
6152 {
6153   int i;
6154 
6155   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
6156     return 0;
6157 
6158   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
6159     {
6160       tree nt = TREE_VEC_ELT (newargs, i);
6161       tree ot = TREE_VEC_ELT (oldargs, i);
6162 
6163       if (! template_args_equal (ot, nt))
6164 	return 0;
6165     }
6166   return 1;
6167 }
6168 
6169 static void
6170 add_pending_template (tree d)
6171 {
6172   tree ti = (TYPE_P (d)
6173 	     ? CLASSTYPE_TEMPLATE_INFO (d)
6174 	     : DECL_TEMPLATE_INFO (d));
6175   struct pending_template *pt;
6176   int level;
6177 
6178   if (TI_PENDING_TEMPLATE_FLAG (ti))
6179     return;
6180 
6181   /* We are called both from instantiate_decl, where we've already had a
6182      tinst_level pushed, and instantiate_template, where we haven't.
6183      Compensate.  */
6184   level = !current_tinst_level || current_tinst_level->decl != d;
6185 
6186   if (level)
6187     push_tinst_level (d);
6188 
6189   pt = GGC_NEW (struct pending_template);
6190   pt->next = NULL;
6191   pt->tinst = current_tinst_level;
6192   if (last_pending_template)
6193     last_pending_template->next = pt;
6194   else
6195     pending_templates = pt;
6196 
6197   last_pending_template = pt;
6198 
6199   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
6200 
6201   if (level)
6202     pop_tinst_level ();
6203 }
6204 
6205 
6206 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
6207    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
6208    documentation for TEMPLATE_ID_EXPR.  */
6209 
6210 tree
6211 lookup_template_function (tree fns, tree arglist)
6212 {
6213   tree type;
6214 
6215   if (fns == error_mark_node || arglist == error_mark_node)
6216     return error_mark_node;
6217 
6218   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
6219   gcc_assert (fns && (is_overloaded_fn (fns)
6220 		      || TREE_CODE (fns) == IDENTIFIER_NODE));
6221 
6222   if (BASELINK_P (fns))
6223     {
6224       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
6225 					 unknown_type_node,
6226 					 BASELINK_FUNCTIONS (fns),
6227 					 arglist);
6228       return fns;
6229     }
6230 
6231   type = TREE_TYPE (fns);
6232   if (TREE_CODE (fns) == OVERLOAD || !type)
6233     type = unknown_type_node;
6234 
6235   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
6236 }
6237 
6238 /* Within the scope of a template class S<T>, the name S gets bound
6239    (in build_self_reference) to a TYPE_DECL for the class, not a
6240    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
6241    or one of its enclosing classes, and that type is a template,
6242    return the associated TEMPLATE_DECL.  Otherwise, the original
6243    DECL is returned.
6244 
6245    Also handle the case when DECL is a TREE_LIST of ambiguous
6246    injected-class-names from different bases.  */
6247 
6248 tree
6249 maybe_get_template_decl_from_type_decl (tree decl)
6250 {
6251   if (decl == NULL_TREE)
6252     return decl;
6253 
6254   /* DR 176: A lookup that finds an injected-class-name (10.2
6255      [class.member.lookup]) can result in an ambiguity in certain cases
6256      (for example, if it is found in more than one base class). If all of
6257      the injected-class-names that are found refer to specializations of
6258      the same class template, and if the name is followed by a
6259      template-argument-list, the reference refers to the class template
6260      itself and not a specialization thereof, and is not ambiguous.  */
6261   if (TREE_CODE (decl) == TREE_LIST)
6262     {
6263       tree t, tmpl = NULL_TREE;
6264       for (t = decl; t; t = TREE_CHAIN (t))
6265 	{
6266 	  tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
6267 	  if (!tmpl)
6268 	    tmpl = elt;
6269 	  else if (tmpl != elt)
6270 	    break;
6271 	}
6272       if (tmpl && t == NULL_TREE)
6273 	return tmpl;
6274       else
6275 	return decl;
6276     }
6277 
6278   return (decl != NULL_TREE
6279 	  && DECL_SELF_REFERENCE_P (decl)
6280 	  && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
6281     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
6282 }
6283 
6284 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
6285    parameters, find the desired type.
6286 
6287    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
6288 
6289    IN_DECL, if non-NULL, is the template declaration we are trying to
6290    instantiate.
6291 
6292    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
6293    the class we are looking up.
6294 
6295    Issue error and warning messages under control of COMPLAIN.
6296 
6297    If the template class is really a local class in a template
6298    function, then the FUNCTION_CONTEXT is the function in which it is
6299    being instantiated.
6300 
6301    ??? Note that this function is currently called *twice* for each
6302    template-id: the first time from the parser, while creating the
6303    incomplete type (finish_template_type), and the second type during the
6304    real instantiation (instantiate_template_class). This is surely something
6305    that we want to avoid. It also causes some problems with argument
6306    coercion (see convert_nontype_argument for more information on this).  */
6307 
6308 tree
6309 lookup_template_class (tree d1,
6310 		       tree arglist,
6311 		       tree in_decl,
6312 		       tree context,
6313 		       int entering_scope,
6314 		       tsubst_flags_t complain)
6315 {
6316   tree templ = NULL_TREE, parmlist;
6317   tree t;
6318   spec_entry **slot;
6319   spec_entry *entry;
6320   spec_entry elt;
6321   hashval_t hash;
6322 
6323   timevar_push (TV_NAME_LOOKUP);
6324 
6325   if (TREE_CODE (d1) == IDENTIFIER_NODE)
6326     {
6327       tree value = innermost_non_namespace_value (d1);
6328       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
6329 	templ = value;
6330       else
6331 	{
6332 	  if (context)
6333 	    push_decl_namespace (context);
6334 	  templ = lookup_name (d1);
6335 	  templ = maybe_get_template_decl_from_type_decl (templ);
6336 	  if (context)
6337 	    pop_decl_namespace ();
6338 	}
6339       if (templ)
6340 	context = DECL_CONTEXT (templ);
6341     }
6342   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
6343     {
6344       tree type = TREE_TYPE (d1);
6345 
6346       /* If we are declaring a constructor, say A<T>::A<T>, we will get
6347 	 an implicit typename for the second A.  Deal with it.  */
6348       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
6349 	type = TREE_TYPE (type);
6350 
6351       if (CLASSTYPE_TEMPLATE_INFO (type))
6352 	{
6353 	  templ = CLASSTYPE_TI_TEMPLATE (type);
6354 	  d1 = DECL_NAME (templ);
6355 	}
6356     }
6357   else if (TREE_CODE (d1) == ENUMERAL_TYPE
6358 	   || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
6359     {
6360       templ = TYPE_TI_TEMPLATE (d1);
6361       d1 = DECL_NAME (templ);
6362     }
6363   else if (TREE_CODE (d1) == TEMPLATE_DECL
6364            && DECL_TEMPLATE_RESULT (d1)
6365 	   && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
6366     {
6367       templ = d1;
6368       d1 = DECL_NAME (templ);
6369       context = DECL_CONTEXT (templ);
6370     }
6371 
6372   /* Issue an error message if we didn't find a template.  */
6373   if (! templ)
6374     {
6375       if (complain & tf_error)
6376 	error ("%qT is not a template", d1);
6377       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6378     }
6379 
6380   if (TREE_CODE (templ) != TEMPLATE_DECL
6381 	 /* Make sure it's a user visible template, if it was named by
6382 	    the user.  */
6383       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
6384 	  && !PRIMARY_TEMPLATE_P (templ)))
6385     {
6386       if (complain & tf_error)
6387 	{
6388 	  error ("non-template type %qT used as a template", d1);
6389 	  if (in_decl)
6390 	    error ("for template declaration %q+D", in_decl);
6391 	}
6392       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6393     }
6394 
6395   complain &= ~tf_user;
6396 
6397   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
6398     {
6399       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
6400 	 template arguments */
6401 
6402       tree parm;
6403       tree arglist2;
6404       tree outer;
6405 
6406       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
6407 
6408       /* Consider an example where a template template parameter declared as
6409 
6410 	   template <class T, class U = std::allocator<T> > class TT
6411 
6412 	 The template parameter level of T and U are one level larger than
6413 	 of TT.  To proper process the default argument of U, say when an
6414 	 instantiation `TT<int>' is seen, we need to build the full
6415 	 arguments containing {int} as the innermost level.  Outer levels,
6416 	 available when not appearing as default template argument, can be
6417 	 obtained from the arguments of the enclosing template.
6418 
6419 	 Suppose that TT is later substituted with std::vector.  The above
6420 	 instantiation is `TT<int, std::allocator<T> >' with TT at
6421 	 level 1, and T at level 2, while the template arguments at level 1
6422 	 becomes {std::vector} and the inner level 2 is {int}.  */
6423 
6424       outer = DECL_CONTEXT (templ);
6425       if (outer)
6426 	outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
6427       else if (current_template_parms)
6428 	/* This is an argument of the current template, so we haven't set
6429 	   DECL_CONTEXT yet.  */
6430 	outer = current_template_args ();
6431 
6432       if (outer)
6433 	arglist = add_to_template_args (outer, arglist);
6434 
6435       arglist2 = coerce_template_parms (parmlist, arglist, templ,
6436 					complain,
6437 					/*require_all_args=*/true,
6438 					/*use_default_args=*/true);
6439       if (arglist2 == error_mark_node
6440 	  || (!uses_template_parms (arglist2)
6441 	      && check_instantiated_args (templ, arglist2, complain)))
6442 	POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6443 
6444       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
6445       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
6446     }
6447   else
6448     {
6449       tree template_type = TREE_TYPE (templ);
6450       tree gen_tmpl;
6451       tree type_decl;
6452       tree found = NULL_TREE;
6453       int arg_depth;
6454       int parm_depth;
6455       int is_dependent_type;
6456       int use_partial_inst_tmpl = false;
6457 
6458       gen_tmpl = most_general_template (templ);
6459       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
6460       parm_depth = TMPL_PARMS_DEPTH (parmlist);
6461       arg_depth = TMPL_ARGS_DEPTH (arglist);
6462 
6463       if (arg_depth == 1 && parm_depth > 1)
6464 	{
6465 	  /* We've been given an incomplete set of template arguments.
6466 	     For example, given:
6467 
6468 	       template <class T> struct S1 {
6469 		 template <class U> struct S2 {};
6470 		 template <class U> struct S2<U*> {};
6471 		};
6472 
6473 	     we will be called with an ARGLIST of `U*', but the
6474 	     TEMPLATE will be `template <class T> template
6475 	     <class U> struct S1<T>::S2'.  We must fill in the missing
6476 	     arguments.  */
6477 	  arglist
6478 	    = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
6479 					   arglist);
6480 	  arg_depth = TMPL_ARGS_DEPTH (arglist);
6481 	}
6482 
6483       /* Now we should have enough arguments.  */
6484       gcc_assert (parm_depth == arg_depth);
6485 
6486       /* From here on, we're only interested in the most general
6487 	 template.  */
6488 
6489       /* Calculate the BOUND_ARGS.  These will be the args that are
6490 	 actually tsubst'd into the definition to create the
6491 	 instantiation.  */
6492       if (parm_depth > 1)
6493 	{
6494 	  /* We have multiple levels of arguments to coerce, at once.  */
6495 	  int i;
6496 	  int saved_depth = TMPL_ARGS_DEPTH (arglist);
6497 
6498 	  tree bound_args = make_tree_vec (parm_depth);
6499 
6500 	  for (i = saved_depth,
6501 		 t = DECL_TEMPLATE_PARMS (gen_tmpl);
6502 	       i > 0 && t != NULL_TREE;
6503 	       --i, t = TREE_CHAIN (t))
6504 	    {
6505 	      tree a = coerce_template_parms (TREE_VALUE (t),
6506 					      arglist, gen_tmpl,
6507 					      complain,
6508 					      /*require_all_args=*/true,
6509 					      /*use_default_args=*/true);
6510 
6511 	      /* Don't process further if one of the levels fails.  */
6512 	      if (a == error_mark_node)
6513 		{
6514 		  /* Restore the ARGLIST to its full size.  */
6515 		  TREE_VEC_LENGTH (arglist) = saved_depth;
6516 		  POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6517 		}
6518 
6519 	      SET_TMPL_ARGS_LEVEL (bound_args, i, a);
6520 
6521 	      /* We temporarily reduce the length of the ARGLIST so
6522 		 that coerce_template_parms will see only the arguments
6523 		 corresponding to the template parameters it is
6524 		 examining.  */
6525 	      TREE_VEC_LENGTH (arglist)--;
6526 	    }
6527 
6528 	  /* Restore the ARGLIST to its full size.  */
6529 	  TREE_VEC_LENGTH (arglist) = saved_depth;
6530 
6531 	  arglist = bound_args;
6532 	}
6533       else
6534 	arglist
6535 	  = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
6536 				   INNERMOST_TEMPLATE_ARGS (arglist),
6537 				   gen_tmpl,
6538 				   complain,
6539 				   /*require_all_args=*/true,
6540 				   /*use_default_args=*/true);
6541 
6542       if (arglist == error_mark_node)
6543 	/* We were unable to bind the arguments.  */
6544 	POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6545 
6546       /* In the scope of a template class, explicit references to the
6547 	 template class refer to the type of the template, not any
6548 	 instantiation of it.  For example, in:
6549 
6550 	   template <class T> class C { void f(C<T>); }
6551 
6552 	 the `C<T>' is just the same as `C'.  Outside of the
6553 	 class, however, such a reference is an instantiation.  */
6554       if ((entering_scope
6555 	   || !PRIMARY_TEMPLATE_P (gen_tmpl)
6556 	   || currently_open_class (template_type))
6557 	  /* comp_template_args is expensive, check it last.  */
6558 	  && comp_template_args (TYPE_TI_ARGS (template_type),
6559 				 arglist))
6560 	POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, template_type);
6561 
6562       /* If we already have this specialization, return it.  */
6563       elt.tmpl = gen_tmpl;
6564       elt.args = arglist;
6565       hash = hash_specialization (&elt);
6566       entry = (spec_entry *) htab_find_with_hash (type_specializations,
6567 						  &elt, hash);
6568 
6569       if (entry)
6570 	POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, entry->spec);
6571 
6572       is_dependent_type = uses_template_parms (arglist);
6573 
6574       /* If the deduced arguments are invalid, then the binding
6575 	 failed.  */
6576       if (!is_dependent_type
6577 	  && check_instantiated_args (gen_tmpl,
6578 				      INNERMOST_TEMPLATE_ARGS (arglist),
6579 				      complain))
6580 	POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6581 
6582       if (!is_dependent_type
6583 	  && !PRIMARY_TEMPLATE_P (gen_tmpl)
6584 	  && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
6585 	  && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
6586 	{
6587 	  found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
6588 				      DECL_NAME (gen_tmpl),
6589 				      /*tag_scope=*/ts_global);
6590 	  POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
6591 	}
6592 
6593       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
6594 			complain, in_decl);
6595       if (!context)
6596 	context = global_namespace;
6597 
6598       /* Create the type.  */
6599       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
6600 	{
6601 	  if (!is_dependent_type)
6602 	    {
6603 	      set_current_access_from_decl (TYPE_NAME (template_type));
6604 	      t = start_enum (TYPE_IDENTIFIER (template_type),
6605                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
6606                                       arglist, complain, in_decl),
6607                               SCOPED_ENUM_P (template_type));
6608 	    }
6609 	  else
6610             {
6611               /* We don't want to call start_enum for this type, since
6612                  the values for the enumeration constants may involve
6613                  template parameters.  And, no one should be interested
6614                  in the enumeration constants for such a type.  */
6615               t = cxx_make_type (ENUMERAL_TYPE);
6616               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
6617             }
6618 	}
6619       else
6620 	{
6621 	  t = make_class_type (TREE_CODE (template_type));
6622 	  CLASSTYPE_DECLARED_CLASS (t)
6623 	    = CLASSTYPE_DECLARED_CLASS (template_type);
6624 	  SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
6625 	  TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
6626 
6627 	  /* A local class.  Make sure the decl gets registered properly.  */
6628 	  if (context == current_function_decl)
6629 	    pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
6630 
6631 	  if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
6632 	    /* This instantiation is another name for the primary
6633 	       template type. Set the TYPE_CANONICAL field
6634 	       appropriately. */
6635 	    TYPE_CANONICAL (t) = template_type;
6636 	  else if (any_template_arguments_need_structural_equality_p (arglist))
6637 	    /* Some of the template arguments require structural
6638 	       equality testing, so this template class requires
6639 	       structural equality testing. */
6640 	    SET_TYPE_STRUCTURAL_EQUALITY (t);
6641 	}
6642 
6643       /* If we called start_enum or pushtag above, this information
6644 	 will already be set up.  */
6645       if (!TYPE_NAME (t))
6646 	{
6647 	  TYPE_CONTEXT (t) = FROB_CONTEXT (context);
6648 
6649 	  type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
6650 	  DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
6651 	  DECL_SOURCE_LOCATION (type_decl)
6652 	    = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
6653 	}
6654       else
6655 	type_decl = TYPE_NAME (t);
6656 
6657       TREE_PRIVATE (type_decl)
6658 	= TREE_PRIVATE (TYPE_STUB_DECL (template_type));
6659       TREE_PROTECTED (type_decl)
6660 	= TREE_PROTECTED (TYPE_STUB_DECL (template_type));
6661       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
6662 	{
6663 	  DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
6664 	  DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
6665 	}
6666 
6667       /* Let's consider the explicit specialization of a member
6668          of a class template specialization that is implicitely instantiated,
6669 	 e.g.:
6670 	     template<class T>
6671 	     struct S
6672 	     {
6673 	       template<class U> struct M {}; //#0
6674 	     };
6675 
6676 	     template<>
6677 	     template<>
6678 	     struct S<int>::M<char> //#1
6679 	     {
6680 	       int i;
6681 	     };
6682 	[temp.expl.spec]/4 says this is valid.
6683 
6684 	In this case, when we write:
6685 	S<int>::M<char> m;
6686 
6687 	M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
6688 	the one of #0.
6689 
6690 	When we encounter #1, we want to store the partial instantiation
6691 	of M (template<class T> S<int>::M<T>) in it's CLASSTYPE_TI_TEMPLATE.
6692 
6693 	For all cases other than this "explicit specialization of member of a
6694 	class template", we just want to store the most general template into
6695 	the CLASSTYPE_TI_TEMPLATE of M.
6696 
6697 	This case of "explicit specialization of member of a class template"
6698 	only happens when:
6699 	1/ the enclosing class is an instantiation of, and therefore not
6700 	the same as, the context of the most general template, and
6701 	2/ we aren't looking at the partial instantiation itself, i.e.
6702 	the innermost arguments are not the same as the innermost parms of
6703 	the most general template.
6704 
6705 	So it's only when 1/ and 2/ happens that we want to use the partial
6706 	instantiation of the member template in lieu of its most general
6707 	template.  */
6708 
6709       if (PRIMARY_TEMPLATE_P (gen_tmpl)
6710 	  && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
6711 	  /* the enclosing class must be an instantiation...  */
6712 	  && CLASS_TYPE_P (context)
6713 	  && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
6714 	{
6715 	  tree partial_inst_args;
6716 	  TREE_VEC_LENGTH (arglist)--;
6717 	  ++processing_template_decl;
6718 	  partial_inst_args =
6719 	    tsubst (INNERMOST_TEMPLATE_ARGS
6720 			(CLASSTYPE_TI_ARGS (TREE_TYPE (gen_tmpl))),
6721 		    arglist, complain, NULL_TREE);
6722 	  --processing_template_decl;
6723 	  TREE_VEC_LENGTH (arglist)++;
6724 	  use_partial_inst_tmpl =
6725 	    /*...and we must not be looking at the partial instantiation
6726 	     itself. */
6727 	    !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
6728 				 partial_inst_args);
6729 	}
6730 
6731       if (!use_partial_inst_tmpl)
6732 	/* This case is easy; there are no member templates involved.  */
6733 	found = gen_tmpl;
6734       else
6735 	{
6736 	  /* This is a full instantiation of a member template.  Find
6737 	     the partial instantiation of which this is an instance.  */
6738 
6739 	  /* Temporarily reduce by one the number of levels in the ARGLIST
6740 	     so as to avoid comparing the last set of arguments.  */
6741 	  TREE_VEC_LENGTH (arglist)--;
6742 	  found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
6743 	  TREE_VEC_LENGTH (arglist)++;
6744 	  found = CLASSTYPE_TI_TEMPLATE (found);
6745 	}
6746 
6747       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
6748 
6749       elt.spec = t;
6750       slot = (spec_entry **) htab_find_slot_with_hash (type_specializations,
6751 						       &elt, hash, INSERT);
6752       *slot = GGC_NEW (spec_entry);
6753       **slot = elt;
6754 
6755       /* Note this use of the partial instantiation so we can check it
6756 	 later in maybe_process_partial_specialization.  */
6757       DECL_TEMPLATE_INSTANTIATIONS (templ)
6758 	= tree_cons (arglist, t,
6759 		     DECL_TEMPLATE_INSTANTIATIONS (templ));
6760 
6761       if (TREE_CODE (t) == ENUMERAL_TYPE && !is_dependent_type)
6762 	/* Now that the type has been registered on the instantiations
6763 	   list, we set up the enumerators.  Because the enumeration
6764 	   constants may involve the enumeration type itself, we make
6765 	   sure to register the type first, and then create the
6766 	   constants.  That way, doing tsubst_expr for the enumeration
6767 	   constants won't result in recursive calls here; we'll find
6768 	   the instantiation and exit above.  */
6769 	tsubst_enum (template_type, t, arglist);
6770 
6771       if (is_dependent_type)
6772 	/* If the type makes use of template parameters, the
6773 	   code that generates debugging information will crash.  */
6774 	DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
6775 
6776       /* Possibly limit visibility based on template args.  */
6777       TREE_PUBLIC (type_decl) = 1;
6778       determine_visibility (type_decl);
6779 
6780       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
6781     }
6782   timevar_pop (TV_NAME_LOOKUP);
6783 }
6784 
6785 struct pair_fn_data
6786 {
6787   tree_fn_t fn;
6788   void *data;
6789   /* True when we should also visit template parameters that occur in
6790      non-deduced contexts.  */
6791   bool include_nondeduced_p;
6792   struct pointer_set_t *visited;
6793 };
6794 
6795 /* Called from for_each_template_parm via walk_tree.  */
6796 
6797 static tree
6798 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
6799 {
6800   tree t = *tp;
6801   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
6802   tree_fn_t fn = pfd->fn;
6803   void *data = pfd->data;
6804 
6805   if (TYPE_P (t)
6806       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
6807       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
6808 				 pfd->include_nondeduced_p))
6809     return error_mark_node;
6810 
6811   switch (TREE_CODE (t))
6812     {
6813     case RECORD_TYPE:
6814       if (TYPE_PTRMEMFUNC_P (t))
6815 	break;
6816       /* Fall through.  */
6817 
6818     case UNION_TYPE:
6819     case ENUMERAL_TYPE:
6820       if (!TYPE_TEMPLATE_INFO (t))
6821 	*walk_subtrees = 0;
6822       else if (for_each_template_parm (TI_ARGS (TYPE_TEMPLATE_INFO (t)),
6823 				       fn, data, pfd->visited,
6824 				       pfd->include_nondeduced_p))
6825 	return error_mark_node;
6826       break;
6827 
6828     case INTEGER_TYPE:
6829       if (for_each_template_parm (TYPE_MIN_VALUE (t),
6830 				  fn, data, pfd->visited,
6831 				  pfd->include_nondeduced_p)
6832 	  || for_each_template_parm (TYPE_MAX_VALUE (t),
6833 				     fn, data, pfd->visited,
6834 				     pfd->include_nondeduced_p))
6835 	return error_mark_node;
6836       break;
6837 
6838     case METHOD_TYPE:
6839       /* Since we're not going to walk subtrees, we have to do this
6840 	 explicitly here.  */
6841       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
6842 				  pfd->visited, pfd->include_nondeduced_p))
6843 	return error_mark_node;
6844       /* Fall through.  */
6845 
6846     case FUNCTION_TYPE:
6847       /* Check the return type.  */
6848       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6849 				  pfd->include_nondeduced_p))
6850 	return error_mark_node;
6851 
6852       /* Check the parameter types.  Since default arguments are not
6853 	 instantiated until they are needed, the TYPE_ARG_TYPES may
6854 	 contain expressions that involve template parameters.  But,
6855 	 no-one should be looking at them yet.  And, once they're
6856 	 instantiated, they don't contain template parameters, so
6857 	 there's no point in looking at them then, either.  */
6858       {
6859 	tree parm;
6860 
6861 	for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
6862 	  if (for_each_template_parm (TREE_VALUE (parm), fn, data,
6863 				      pfd->visited, pfd->include_nondeduced_p))
6864 	    return error_mark_node;
6865 
6866 	/* Since we've already handled the TYPE_ARG_TYPES, we don't
6867 	   want walk_tree walking into them itself.  */
6868 	*walk_subtrees = 0;
6869       }
6870       break;
6871 
6872     case TYPEOF_TYPE:
6873       if (pfd->include_nondeduced_p
6874 	  && for_each_template_parm (TYPE_FIELDS (t), fn, data,
6875 				     pfd->visited,
6876 				     pfd->include_nondeduced_p))
6877 	return error_mark_node;
6878       break;
6879 
6880     case FUNCTION_DECL:
6881     case VAR_DECL:
6882       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
6883 	  && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
6884 				     pfd->visited, pfd->include_nondeduced_p))
6885 	return error_mark_node;
6886       /* Fall through.  */
6887 
6888     case PARM_DECL:
6889     case CONST_DECL:
6890       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
6891 	  && for_each_template_parm (DECL_INITIAL (t), fn, data,
6892 				     pfd->visited, pfd->include_nondeduced_p))
6893 	return error_mark_node;
6894       if (DECL_CONTEXT (t)
6895 	  && pfd->include_nondeduced_p
6896 	  && for_each_template_parm (DECL_CONTEXT (t), fn, data,
6897 				     pfd->visited, pfd->include_nondeduced_p))
6898 	return error_mark_node;
6899       break;
6900 
6901     case BOUND_TEMPLATE_TEMPLATE_PARM:
6902       /* Record template parameters such as `T' inside `TT<T>'.  */
6903       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
6904 				  pfd->include_nondeduced_p))
6905 	return error_mark_node;
6906       /* Fall through.  */
6907 
6908     case TEMPLATE_TEMPLATE_PARM:
6909     case TEMPLATE_TYPE_PARM:
6910     case TEMPLATE_PARM_INDEX:
6911       if (fn && (*fn)(t, data))
6912 	return error_mark_node;
6913       else if (!fn)
6914 	return error_mark_node;
6915       break;
6916 
6917     case TEMPLATE_DECL:
6918       /* A template template parameter is encountered.  */
6919       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
6920 	  && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6921 				     pfd->include_nondeduced_p))
6922 	return error_mark_node;
6923 
6924       /* Already substituted template template parameter */
6925       *walk_subtrees = 0;
6926       break;
6927 
6928     case TYPENAME_TYPE:
6929       if (!fn
6930 	  || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
6931 				     data, pfd->visited,
6932 				     pfd->include_nondeduced_p))
6933 	return error_mark_node;
6934       break;
6935 
6936     case CONSTRUCTOR:
6937       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
6938 	  && pfd->include_nondeduced_p
6939 	  && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
6940 				     (TREE_TYPE (t)), fn, data,
6941 				     pfd->visited, pfd->include_nondeduced_p))
6942 	return error_mark_node;
6943       break;
6944 
6945     case INDIRECT_REF:
6946     case COMPONENT_REF:
6947       /* If there's no type, then this thing must be some expression
6948 	 involving template parameters.  */
6949       if (!fn && !TREE_TYPE (t))
6950 	return error_mark_node;
6951       break;
6952 
6953     case MODOP_EXPR:
6954     case CAST_EXPR:
6955     case REINTERPRET_CAST_EXPR:
6956     case CONST_CAST_EXPR:
6957     case STATIC_CAST_EXPR:
6958     case DYNAMIC_CAST_EXPR:
6959     case ARROW_EXPR:
6960     case DOTSTAR_EXPR:
6961     case TYPEID_EXPR:
6962     case PSEUDO_DTOR_EXPR:
6963       if (!fn)
6964 	return error_mark_node;
6965       break;
6966 
6967     default:
6968       break;
6969     }
6970 
6971   /* We didn't find any template parameters we liked.  */
6972   return NULL_TREE;
6973 }
6974 
6975 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
6976    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
6977    call FN with the parameter and the DATA.
6978    If FN returns nonzero, the iteration is terminated, and
6979    for_each_template_parm returns 1.  Otherwise, the iteration
6980    continues.  If FN never returns a nonzero value, the value
6981    returned by for_each_template_parm is 0.  If FN is NULL, it is
6982    considered to be the function which always returns 1.
6983 
6984    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
6985    parameters that occur in non-deduced contexts.  When false, only
6986    visits those template parameters that can be deduced.  */
6987 
6988 static int
6989 for_each_template_parm (tree t, tree_fn_t fn, void* data,
6990 			struct pointer_set_t *visited,
6991 			bool include_nondeduced_p)
6992 {
6993   struct pair_fn_data pfd;
6994   int result;
6995 
6996   /* Set up.  */
6997   pfd.fn = fn;
6998   pfd.data = data;
6999   pfd.include_nondeduced_p = include_nondeduced_p;
7000 
7001   /* Walk the tree.  (Conceptually, we would like to walk without
7002      duplicates, but for_each_template_parm_r recursively calls
7003      for_each_template_parm, so we would need to reorganize a fair
7004      bit to use walk_tree_without_duplicates, so we keep our own
7005      visited list.)  */
7006   if (visited)
7007     pfd.visited = visited;
7008   else
7009     pfd.visited = pointer_set_create ();
7010   result = cp_walk_tree (&t,
7011 		         for_each_template_parm_r,
7012 		         &pfd,
7013 		         pfd.visited) != NULL_TREE;
7014 
7015   /* Clean up.  */
7016   if (!visited)
7017     {
7018       pointer_set_destroy (pfd.visited);
7019       pfd.visited = 0;
7020     }
7021 
7022   return result;
7023 }
7024 
7025 /* Returns true if T depends on any template parameter.  */
7026 
7027 int
7028 uses_template_parms (tree t)
7029 {
7030   bool dependent_p;
7031   int saved_processing_template_decl;
7032 
7033   saved_processing_template_decl = processing_template_decl;
7034   if (!saved_processing_template_decl)
7035     processing_template_decl = 1;
7036   if (TYPE_P (t))
7037     dependent_p = dependent_type_p (t);
7038   else if (TREE_CODE (t) == TREE_VEC)
7039     dependent_p = any_dependent_template_arguments_p (t);
7040   else if (TREE_CODE (t) == TREE_LIST)
7041     dependent_p = (uses_template_parms (TREE_VALUE (t))
7042 		   || uses_template_parms (TREE_CHAIN (t)));
7043   else if (TREE_CODE (t) == TYPE_DECL)
7044     dependent_p = dependent_type_p (TREE_TYPE (t));
7045   else if (DECL_P (t)
7046 	   || EXPR_P (t)
7047 	   || TREE_CODE (t) == TEMPLATE_PARM_INDEX
7048 	   || TREE_CODE (t) == OVERLOAD
7049 	   || TREE_CODE (t) == BASELINK
7050 	   || TREE_CODE (t) == IDENTIFIER_NODE
7051 	   || TREE_CODE (t) == TRAIT_EXPR
7052 	   || TREE_CODE (t) == CONSTRUCTOR
7053 	   || CONSTANT_CLASS_P (t))
7054     dependent_p = (type_dependent_expression_p (t)
7055 		   || value_dependent_expression_p (t));
7056   else
7057     {
7058       gcc_assert (t == error_mark_node);
7059       dependent_p = false;
7060     }
7061 
7062   processing_template_decl = saved_processing_template_decl;
7063 
7064   return dependent_p;
7065 }
7066 
7067 /* Returns true if T depends on any template parameter with level LEVEL.  */
7068 
7069 int
7070 uses_template_parms_level (tree t, int level)
7071 {
7072   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
7073 				 /*include_nondeduced_p=*/true);
7074 }
7075 
7076 static int tinst_depth;
7077 extern int max_tinst_depth;
7078 #ifdef GATHER_STATISTICS
7079 int depth_reached;
7080 #endif
7081 static int tinst_level_tick;
7082 static int last_template_error_tick;
7083 
7084 /* We're starting to instantiate D; record the template instantiation context
7085    for diagnostics and to restore it later.  */
7086 
7087 int
7088 push_tinst_level (tree d)
7089 {
7090   struct tinst_level *new_level;
7091 
7092   if (tinst_depth >= max_tinst_depth)
7093     {
7094       /* If the instantiation in question still has unbound template parms,
7095 	 we don't really care if we can't instantiate it, so just return.
7096 	 This happens with base instantiation for implicit `typename'.  */
7097       if (uses_template_parms (d))
7098 	return 0;
7099 
7100       last_template_error_tick = tinst_level_tick;
7101       error ("template instantiation depth exceeds maximum of %d (use "
7102 	     "-ftemplate-depth= to increase the maximum) instantiating %qD",
7103 	     max_tinst_depth, d);
7104 
7105       print_instantiation_context ();
7106 
7107       return 0;
7108     }
7109 
7110   new_level = GGC_NEW (struct tinst_level);
7111   new_level->decl = d;
7112   new_level->locus = input_location;
7113   new_level->in_system_header_p = in_system_header;
7114   new_level->next = current_tinst_level;
7115   current_tinst_level = new_level;
7116 
7117   ++tinst_depth;
7118 #ifdef GATHER_STATISTICS
7119   if (tinst_depth > depth_reached)
7120     depth_reached = tinst_depth;
7121 #endif
7122 
7123   ++tinst_level_tick;
7124   return 1;
7125 }
7126 
7127 /* We're done instantiating this template; return to the instantiation
7128    context.  */
7129 
7130 void
7131 pop_tinst_level (void)
7132 {
7133   /* Restore the filename and line number stashed away when we started
7134      this instantiation.  */
7135   input_location = current_tinst_level->locus;
7136   current_tinst_level = current_tinst_level->next;
7137   --tinst_depth;
7138   ++tinst_level_tick;
7139 }
7140 
7141 /* We're instantiating a deferred template; restore the template
7142    instantiation context in which the instantiation was requested, which
7143    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
7144 
7145 static tree
7146 reopen_tinst_level (struct tinst_level *level)
7147 {
7148   struct tinst_level *t;
7149 
7150   tinst_depth = 0;
7151   for (t = level; t; t = t->next)
7152     ++tinst_depth;
7153 
7154   current_tinst_level = level;
7155   pop_tinst_level ();
7156   return level->decl;
7157 }
7158 
7159 /* Returns the TINST_LEVEL which gives the original instantiation
7160    context.  */
7161 
7162 struct tinst_level *
7163 outermost_tinst_level (void)
7164 {
7165   struct tinst_level *level = current_tinst_level;
7166   if (level)
7167     while (level->next)
7168       level = level->next;
7169   return level;
7170 }
7171 
7172 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
7173 
7174 bool
7175 parameter_of_template_p (tree parm, tree templ)
7176 {
7177   tree parms;
7178   int i;
7179 
7180   if (!parm || !templ)
7181     return false;
7182 
7183   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
7184   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7185 
7186   parms = DECL_TEMPLATE_PARMS (templ);
7187   parms = INNERMOST_TEMPLATE_PARMS (parms);
7188 
7189   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
7190     if (parm == TREE_VALUE (TREE_VEC_ELT (parms, i)))
7191       return true;
7192 
7193   return false;
7194 }
7195 
7196 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
7197    vector of template arguments, as for tsubst.
7198 
7199    Returns an appropriate tsubst'd friend declaration.  */
7200 
7201 static tree
7202 tsubst_friend_function (tree decl, tree args)
7203 {
7204   tree new_friend;
7205 
7206   if (TREE_CODE (decl) == FUNCTION_DECL
7207       && DECL_TEMPLATE_INSTANTIATION (decl)
7208       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
7209     /* This was a friend declared with an explicit template
7210        argument list, e.g.:
7211 
7212        friend void f<>(T);
7213 
7214        to indicate that f was a template instantiation, not a new
7215        function declaration.  Now, we have to figure out what
7216        instantiation of what template.  */
7217     {
7218       tree template_id, arglist, fns;
7219       tree new_args;
7220       tree tmpl;
7221       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
7222 
7223       /* Friend functions are looked up in the containing namespace scope.
7224 	 We must enter that scope, to avoid finding member functions of the
7225 	 current class with same name.  */
7226       push_nested_namespace (ns);
7227       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
7228 			 tf_warning_or_error, NULL_TREE,
7229 			 /*integral_constant_expression_p=*/false);
7230       pop_nested_namespace (ns);
7231       arglist = tsubst (DECL_TI_ARGS (decl), args,
7232 			tf_warning_or_error, NULL_TREE);
7233       template_id = lookup_template_function (fns, arglist);
7234 
7235       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7236       tmpl = determine_specialization (template_id, new_friend,
7237 				       &new_args,
7238 				       /*need_member_template=*/0,
7239 				       TREE_VEC_LENGTH (args),
7240 				       tsk_none);
7241       return instantiate_template (tmpl, new_args, tf_error);
7242     }
7243 
7244   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7245 
7246   /* The NEW_FRIEND will look like an instantiation, to the
7247      compiler, but is not an instantiation from the point of view of
7248      the language.  For example, we might have had:
7249 
7250      template <class T> struct S {
7251        template <class U> friend void f(T, U);
7252      };
7253 
7254      Then, in S<int>, template <class U> void f(int, U) is not an
7255      instantiation of anything.  */
7256   if (new_friend == error_mark_node)
7257     return error_mark_node;
7258 
7259   DECL_USE_TEMPLATE (new_friend) = 0;
7260   if (TREE_CODE (decl) == TEMPLATE_DECL)
7261     {
7262       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
7263       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
7264 	= DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
7265     }
7266 
7267   /* The mangled name for the NEW_FRIEND is incorrect.  The function
7268      is not a template instantiation and should not be mangled like
7269      one.  Therefore, we forget the mangling here; we'll recompute it
7270      later if we need it.  */
7271   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
7272     {
7273       SET_DECL_RTL (new_friend, NULL_RTX);
7274       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
7275     }
7276 
7277   if (DECL_NAMESPACE_SCOPE_P (new_friend))
7278     {
7279       tree old_decl;
7280       tree new_friend_template_info;
7281       tree new_friend_result_template_info;
7282       tree ns;
7283       int  new_friend_is_defn;
7284 
7285       /* We must save some information from NEW_FRIEND before calling
7286 	 duplicate decls since that function will free NEW_FRIEND if
7287 	 possible.  */
7288       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
7289       new_friend_is_defn =
7290 	    (DECL_INITIAL (DECL_TEMPLATE_RESULT
7291 			   (template_for_substitution (new_friend)))
7292 	     != NULL_TREE);
7293       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
7294 	{
7295 	  /* This declaration is a `primary' template.  */
7296 	  DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
7297 
7298 	  new_friend_result_template_info
7299 	    = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
7300 	}
7301       else
7302 	new_friend_result_template_info = NULL_TREE;
7303 
7304       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
7305       if (new_friend_is_defn)
7306 	DECL_INITIAL (new_friend) = error_mark_node;
7307 
7308       /* Inside pushdecl_namespace_level, we will push into the
7309 	 current namespace. However, the friend function should go
7310 	 into the namespace of the template.  */
7311       ns = decl_namespace_context (new_friend);
7312       push_nested_namespace (ns);
7313       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
7314       pop_nested_namespace (ns);
7315 
7316       if (old_decl == error_mark_node)
7317 	return error_mark_node;
7318 
7319       if (old_decl != new_friend)
7320 	{
7321 	  /* This new friend declaration matched an existing
7322 	     declaration.  For example, given:
7323 
7324 	       template <class T> void f(T);
7325 	       template <class U> class C {
7326 		 template <class T> friend void f(T) {}
7327 	       };
7328 
7329 	     the friend declaration actually provides the definition
7330 	     of `f', once C has been instantiated for some type.  So,
7331 	     old_decl will be the out-of-class template declaration,
7332 	     while new_friend is the in-class definition.
7333 
7334 	     But, if `f' was called before this point, the
7335 	     instantiation of `f' will have DECL_TI_ARGS corresponding
7336 	     to `T' but not to `U', references to which might appear
7337 	     in the definition of `f'.  Previously, the most general
7338 	     template for an instantiation of `f' was the out-of-class
7339 	     version; now it is the in-class version.  Therefore, we
7340 	     run through all specialization of `f', adding to their
7341 	     DECL_TI_ARGS appropriately.  In particular, they need a
7342 	     new set of outer arguments, corresponding to the
7343 	     arguments for this class instantiation.
7344 
7345 	     The same situation can arise with something like this:
7346 
7347 	       friend void f(int);
7348 	       template <class T> class C {
7349 		 friend void f(T) {}
7350 	       };
7351 
7352 	     when `C<int>' is instantiated.  Now, `f(int)' is defined
7353 	     in the class.  */
7354 
7355 	  if (!new_friend_is_defn)
7356 	    /* On the other hand, if the in-class declaration does
7357 	       *not* provide a definition, then we don't want to alter
7358 	       existing definitions.  We can just leave everything
7359 	       alone.  */
7360 	    ;
7361 	  else
7362 	    {
7363 	      tree new_template = TI_TEMPLATE (new_friend_template_info);
7364 	      tree new_args = TI_ARGS (new_friend_template_info);
7365 
7366 	      /* Overwrite whatever template info was there before, if
7367 		 any, with the new template information pertaining to
7368 		 the declaration.  */
7369 	      DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
7370 
7371 	      if (TREE_CODE (old_decl) != TEMPLATE_DECL)
7372 		/* We should have called reregister_specialization in
7373 		   duplicate_decls.  */
7374 		gcc_assert (retrieve_specialization (new_template,
7375 						     new_args, 0)
7376 			    == old_decl);
7377 	      else
7378 		{
7379 		  tree t;
7380 
7381 		  /* Indicate that the old function template is a partial
7382 		     instantiation.  */
7383 		  DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
7384 		    = new_friend_result_template_info;
7385 
7386 		  gcc_assert (new_template
7387 			      == most_general_template (new_template));
7388 		  gcc_assert (new_template != old_decl);
7389 
7390 		  /* Reassign any specializations already in the hash table
7391 		     to the new more general template, and add the
7392 		     additional template args.  */
7393 		  for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
7394 		       t != NULL_TREE;
7395 		       t = TREE_CHAIN (t))
7396 		    {
7397 		      tree spec = TREE_VALUE (t);
7398 		      spec_entry elt;
7399 
7400 		      elt.tmpl = old_decl;
7401 		      elt.args = DECL_TI_ARGS (spec);
7402 		      elt.spec = NULL_TREE;
7403 
7404 		      htab_remove_elt (decl_specializations, &elt);
7405 
7406 		      DECL_TI_ARGS (spec)
7407 			= add_outermost_template_args (new_args,
7408 						       DECL_TI_ARGS (spec));
7409 
7410 		      register_specialization
7411 			(spec, new_template, DECL_TI_ARGS (spec), true, 0);
7412 
7413 		    }
7414 		  DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
7415 		}
7416 	    }
7417 
7418 	  /* The information from NEW_FRIEND has been merged into OLD_DECL
7419 	     by duplicate_decls.  */
7420 	  new_friend = old_decl;
7421 	}
7422     }
7423   else
7424     {
7425       tree context = DECL_CONTEXT (new_friend);
7426       bool dependent_p;
7427 
7428       /* In the code
7429 	   template <class T> class C {
7430 	     template <class U> friend void C1<U>::f (); // case 1
7431 	     friend void C2<T>::f ();			 // case 2
7432 	   };
7433 	 we only need to make sure CONTEXT is a complete type for
7434 	 case 2.  To distinguish between the two cases, we note that
7435 	 CONTEXT of case 1 remains dependent type after tsubst while
7436 	 this isn't true for case 2.  */
7437       ++processing_template_decl;
7438       dependent_p = dependent_type_p (context);
7439       --processing_template_decl;
7440 
7441       if (!dependent_p
7442 	  && !complete_type_or_else (context, NULL_TREE))
7443 	return error_mark_node;
7444 
7445       if (COMPLETE_TYPE_P (context))
7446 	{
7447 	  /* Check to see that the declaration is really present, and,
7448 	     possibly obtain an improved declaration.  */
7449 	  tree fn = check_classfn (context,
7450 				   new_friend, NULL_TREE);
7451 
7452 	  if (fn)
7453 	    new_friend = fn;
7454 	}
7455     }
7456 
7457   return new_friend;
7458 }
7459 
7460 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
7461    template arguments, as for tsubst.
7462 
7463    Returns an appropriate tsubst'd friend type or error_mark_node on
7464    failure.  */
7465 
7466 static tree
7467 tsubst_friend_class (tree friend_tmpl, tree args)
7468 {
7469   tree friend_type;
7470   tree tmpl;
7471   tree context;
7472 
7473   context = DECL_CONTEXT (friend_tmpl);
7474 
7475   if (context)
7476     {
7477       if (TREE_CODE (context) == NAMESPACE_DECL)
7478 	push_nested_namespace (context);
7479       else
7480 	push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
7481     }
7482 
7483   /* Look for a class template declaration.  We look for hidden names
7484      because two friend declarations of the same template are the
7485      same.  For example, in:
7486 
7487        struct A {
7488          template <typename> friend class F;
7489        };
7490        template <typename> struct B {
7491          template <typename> friend class F;
7492        };
7493 
7494      both F templates are the same.  */
7495   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
7496 			   /*block_p=*/true, 0,
7497 			   LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
7498 
7499   /* But, if we don't find one, it might be because we're in a
7500      situation like this:
7501 
7502        template <class T>
7503        struct S {
7504 	 template <class U>
7505 	 friend struct S;
7506        };
7507 
7508      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
7509      for `S<int>', not the TEMPLATE_DECL.  */
7510   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
7511     {
7512       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
7513       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
7514     }
7515 
7516   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
7517     {
7518       /* The friend template has already been declared.  Just
7519 	 check to see that the declarations match, and install any new
7520 	 default parameters.  We must tsubst the default parameters,
7521 	 of course.  We only need the innermost template parameters
7522 	 because that is all that redeclare_class_template will look
7523 	 at.  */
7524       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
7525 	  > TMPL_ARGS_DEPTH (args))
7526 	{
7527 	  tree parms;
7528           location_t saved_input_location;
7529 	  parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
7530 					 args, tf_warning_or_error);
7531 
7532           saved_input_location = input_location;
7533           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
7534 	  redeclare_class_template (TREE_TYPE (tmpl), parms);
7535           input_location = saved_input_location;
7536 
7537 	}
7538 
7539       friend_type = TREE_TYPE (tmpl);
7540     }
7541   else
7542     {
7543       /* The friend template has not already been declared.  In this
7544 	 case, the instantiation of the template class will cause the
7545 	 injection of this template into the global scope.  */
7546       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
7547       if (tmpl == error_mark_node)
7548 	return error_mark_node;
7549 
7550       /* The new TMPL is not an instantiation of anything, so we
7551 	 forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
7552 	 the new type because that is supposed to be the corresponding
7553 	 template decl, i.e., TMPL.  */
7554       DECL_USE_TEMPLATE (tmpl) = 0;
7555       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
7556       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
7557       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
7558 	= INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
7559 
7560       /* Inject this template into the global scope.  */
7561       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
7562     }
7563 
7564   if (context)
7565     {
7566       if (TREE_CODE (context) == NAMESPACE_DECL)
7567 	pop_nested_namespace (context);
7568       else
7569 	pop_nested_class ();
7570     }
7571 
7572   return friend_type;
7573 }
7574 
7575 /* Returns zero if TYPE cannot be completed later due to circularity.
7576    Otherwise returns one.  */
7577 
7578 static int
7579 can_complete_type_without_circularity (tree type)
7580 {
7581   if (type == NULL_TREE || type == error_mark_node)
7582     return 0;
7583   else if (COMPLETE_TYPE_P (type))
7584     return 1;
7585   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
7586     return can_complete_type_without_circularity (TREE_TYPE (type));
7587   else if (CLASS_TYPE_P (type)
7588 	   && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
7589     return 0;
7590   else
7591     return 1;
7592 }
7593 
7594 /* Apply any attributes which had to be deferred until instantiation
7595    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
7596    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
7597 
7598 static void
7599 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
7600 				tree args, tsubst_flags_t complain, tree in_decl)
7601 {
7602   tree last_dep = NULL_TREE;
7603   tree t;
7604   tree *p;
7605 
7606   for (t = attributes; t; t = TREE_CHAIN (t))
7607     if (ATTR_IS_DEPENDENT (t))
7608       {
7609 	last_dep = t;
7610 	attributes = copy_list (attributes);
7611 	break;
7612       }
7613 
7614   if (DECL_P (*decl_p))
7615     {
7616       if (TREE_TYPE (*decl_p) == error_mark_node)
7617 	return;
7618       p = &DECL_ATTRIBUTES (*decl_p);
7619     }
7620   else
7621     p = &TYPE_ATTRIBUTES (*decl_p);
7622 
7623   if (last_dep)
7624     {
7625       tree late_attrs = NULL_TREE;
7626       tree *q = &late_attrs;
7627 
7628       for (*p = attributes; *p; )
7629 	{
7630 	  t = *p;
7631 	  if (ATTR_IS_DEPENDENT (t))
7632 	    {
7633 	      *p = TREE_CHAIN (t);
7634 	      TREE_CHAIN (t) = NULL_TREE;
7635 	      /* If the first attribute argument is an identifier, don't
7636 		 pass it through tsubst.  Attributes like mode, format,
7637 		 cleanup and several target specific attributes expect it
7638 		 unmodified.  */
7639 	      if (TREE_VALUE (t)
7640 		  && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
7641 		  && TREE_VALUE (TREE_VALUE (t))
7642 		  && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
7643 		      == IDENTIFIER_NODE))
7644 		{
7645 		  tree chain
7646 		    = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
7647 				   in_decl,
7648 				   /*integral_constant_expression_p=*/false);
7649 		  if (chain != TREE_CHAIN (TREE_VALUE (t)))
7650 		    TREE_VALUE (t)
7651 		      = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
7652 				   chain);
7653 		}
7654 	      else
7655 		TREE_VALUE (t)
7656 		  = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
7657 				 /*integral_constant_expression_p=*/false);
7658 	      *q = t;
7659 	      q = &TREE_CHAIN (t);
7660 	    }
7661 	  else
7662 	    p = &TREE_CHAIN (t);
7663 	}
7664 
7665       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
7666     }
7667 }
7668 
7669 /* Perform (or defer) access check for typedefs that were referenced
7670    from within the template TMPL code.
7671    This is a subroutine of instantiate_template and instantiate_class_template.
7672    TMPL is the template to consider and TARGS is the list of arguments of
7673    that template.  */
7674 
7675 static void
7676 perform_typedefs_access_check (tree tmpl, tree targs)
7677 {
7678   location_t saved_location;
7679   int i;
7680   qualified_typedef_usage_t *iter;
7681 
7682   if (!tmpl
7683       || (!CLASS_TYPE_P (tmpl)
7684 	  && TREE_CODE (tmpl) != FUNCTION_DECL))
7685     return;
7686 
7687   saved_location = input_location;
7688   for (i = 0;
7689        VEC_iterate (qualified_typedef_usage_t,
7690 		    get_types_needing_access_check (tmpl),
7691 		    i, iter);
7692 	++i)
7693     {
7694       tree type_decl = iter->typedef_decl;
7695       tree type_scope = iter->context;
7696 
7697       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
7698 	continue;
7699 
7700       if (uses_template_parms (type_decl))
7701 	type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
7702       if (uses_template_parms (type_scope))
7703 	type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
7704 
7705       /* Make access check error messages point to the location
7706          of the use of the typedef.  */
7707       input_location = iter->locus;
7708       perform_or_defer_access_check (TYPE_BINFO (type_scope),
7709 				     type_decl, type_decl);
7710     }
7711     input_location = saved_location;
7712 }
7713 
7714 tree
7715 instantiate_class_template (tree type)
7716 {
7717   tree templ, args, pattern, t, member;
7718   tree typedecl;
7719   tree pbinfo;
7720   tree base_list;
7721   unsigned int saved_maximum_field_alignment;
7722 
7723   if (type == error_mark_node)
7724     return error_mark_node;
7725 
7726   if (TYPE_BEING_DEFINED (type)
7727       || COMPLETE_TYPE_P (type)
7728       || uses_template_parms (type))
7729     return type;
7730 
7731   /* Figure out which template is being instantiated.  */
7732   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
7733   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7734 
7735   /* Determine what specialization of the original template to
7736      instantiate.  */
7737   t = most_specialized_class (type, templ);
7738   if (t == error_mark_node)
7739     {
7740       TYPE_BEING_DEFINED (type) = 1;
7741       return error_mark_node;
7742     }
7743   else if (t)
7744     {
7745       /* This TYPE is actually an instantiation of a partial
7746 	 specialization.  We replace the innermost set of ARGS with
7747 	 the arguments appropriate for substitution.  For example,
7748 	 given:
7749 
7750 	   template <class T> struct S {};
7751 	   template <class T> struct S<T*> {};
7752 
7753 	 and supposing that we are instantiating S<int*>, ARGS will
7754 	 presently be {int*} -- but we need {int}.  */
7755       pattern = TREE_TYPE (t);
7756       args = TREE_PURPOSE (t);
7757     }
7758   else
7759     {
7760       pattern = TREE_TYPE (templ);
7761       args = CLASSTYPE_TI_ARGS (type);
7762     }
7763 
7764   /* If the template we're instantiating is incomplete, then clearly
7765      there's nothing we can do.  */
7766   if (!COMPLETE_TYPE_P (pattern))
7767     return type;
7768 
7769   /* If we've recursively instantiated too many templates, stop.  */
7770   if (! push_tinst_level (type))
7771     return type;
7772 
7773   /* Now we're really doing the instantiation.  Mark the type as in
7774      the process of being defined.  */
7775   TYPE_BEING_DEFINED (type) = 1;
7776 
7777   /* We may be in the middle of deferred access check.  Disable
7778      it now.  */
7779   push_deferring_access_checks (dk_no_deferred);
7780 
7781   push_to_top_level ();
7782   /* Use #pragma pack from the template context.  */
7783   saved_maximum_field_alignment = maximum_field_alignment;
7784   maximum_field_alignment = TYPE_PRECISION (pattern);
7785 
7786   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
7787 
7788   /* Set the input location to the most specialized template definition.
7789      This is needed if tsubsting causes an error.  */
7790   typedecl = TYPE_MAIN_DECL (pattern);
7791   input_location = DECL_SOURCE_LOCATION (typedecl);
7792 
7793   TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
7794   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
7795   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
7796   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
7797   TYPE_HAS_ASSIGN_REF (type) = TYPE_HAS_ASSIGN_REF (pattern);
7798   TYPE_HAS_CONST_ASSIGN_REF (type) = TYPE_HAS_CONST_ASSIGN_REF (pattern);
7799   TYPE_HAS_INIT_REF (type) = TYPE_HAS_INIT_REF (pattern);
7800   TYPE_HAS_CONST_INIT_REF (type) = TYPE_HAS_CONST_INIT_REF (pattern);
7801   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
7802   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
7803   TYPE_PACKED (type) = TYPE_PACKED (pattern);
7804   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
7805   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
7806   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
7807   if (ANON_AGGR_TYPE_P (pattern))
7808     SET_ANON_AGGR_TYPE_P (type);
7809   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
7810     {
7811       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
7812       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
7813     }
7814 
7815   pbinfo = TYPE_BINFO (pattern);
7816 
7817   /* We should never instantiate a nested class before its enclosing
7818      class; we need to look up the nested class by name before we can
7819      instantiate it, and that lookup should instantiate the enclosing
7820      class.  */
7821   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
7822 	      || COMPLETE_TYPE_P (TYPE_CONTEXT (type))
7823 	      || TYPE_BEING_DEFINED (TYPE_CONTEXT (type)));
7824 
7825   base_list = NULL_TREE;
7826   if (BINFO_N_BASE_BINFOS (pbinfo))
7827     {
7828       tree pbase_binfo;
7829       tree context = TYPE_CONTEXT (type);
7830       tree pushed_scope;
7831       int i;
7832 
7833       /* We must enter the scope containing the type, as that is where
7834 	 the accessibility of types named in dependent bases are
7835 	 looked up from.  */
7836       pushed_scope = push_scope (context ? context : global_namespace);
7837 
7838       /* Substitute into each of the bases to determine the actual
7839 	 basetypes.  */
7840       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
7841 	{
7842 	  tree base;
7843 	  tree access = BINFO_BASE_ACCESS (pbinfo, i);
7844           tree expanded_bases = NULL_TREE;
7845           int idx, len = 1;
7846 
7847           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
7848             {
7849               expanded_bases =
7850 		tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
7851 				       args, tf_error, NULL_TREE);
7852               if (expanded_bases == error_mark_node)
7853                 continue;
7854 
7855               len = TREE_VEC_LENGTH (expanded_bases);
7856             }
7857 
7858           for (idx = 0; idx < len; idx++)
7859             {
7860               if (expanded_bases)
7861                 /* Extract the already-expanded base class.  */
7862                 base = TREE_VEC_ELT (expanded_bases, idx);
7863               else
7864                 /* Substitute to figure out the base class.  */
7865                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error,
7866                                NULL_TREE);
7867 
7868               if (base == error_mark_node)
7869                 continue;
7870 
7871               base_list = tree_cons (access, base, base_list);
7872               if (BINFO_VIRTUAL_P (pbase_binfo))
7873                 TREE_TYPE (base_list) = integer_type_node;
7874             }
7875 	}
7876 
7877       /* The list is now in reverse order; correct that.  */
7878       base_list = nreverse (base_list);
7879 
7880       if (pushed_scope)
7881 	pop_scope (pushed_scope);
7882     }
7883   /* Now call xref_basetypes to set up all the base-class
7884      information.  */
7885   xref_basetypes (type, base_list);
7886 
7887   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
7888 				  (int) ATTR_FLAG_TYPE_IN_PLACE,
7889 				  args, tf_error, NULL_TREE);
7890 
7891   /* Now that our base classes are set up, enter the scope of the
7892      class, so that name lookups into base classes, etc. will work
7893      correctly.  This is precisely analogous to what we do in
7894      begin_class_definition when defining an ordinary non-template
7895      class, except we also need to push the enclosing classes.  */
7896   push_nested_class (type);
7897 
7898   /* Now members are processed in the order of declaration.  */
7899   for (member = CLASSTYPE_DECL_LIST (pattern);
7900        member; member = TREE_CHAIN (member))
7901     {
7902       tree t = TREE_VALUE (member);
7903 
7904       if (TREE_PURPOSE (member))
7905 	{
7906 	  if (TYPE_P (t))
7907 	    {
7908 	      /* Build new CLASSTYPE_NESTED_UTDS.  */
7909 
7910 	      tree newtag;
7911 	      bool class_template_p;
7912 
7913 	      class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
7914 				  && TYPE_LANG_SPECIFIC (t)
7915 				  && CLASSTYPE_IS_TEMPLATE (t));
7916 	      /* If the member is a class template, then -- even after
7917 		 substitution -- there may be dependent types in the
7918 		 template argument list for the class.  We increment
7919 		 PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
7920 		 that function will assume that no types are dependent
7921 		 when outside of a template.  */
7922 	      if (class_template_p)
7923 		++processing_template_decl;
7924 	      newtag = tsubst (t, args, tf_error, NULL_TREE);
7925 	      if (class_template_p)
7926 		--processing_template_decl;
7927 	      if (newtag == error_mark_node)
7928 		continue;
7929 
7930 	      if (TREE_CODE (newtag) != ENUMERAL_TYPE)
7931 		{
7932 		  tree name = TYPE_IDENTIFIER (t);
7933 
7934 		  if (class_template_p)
7935 		    /* Unfortunately, lookup_template_class sets
7936 		       CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
7937 		       instantiation (i.e., for the type of a member
7938 		       template class nested within a template class.)
7939 		       This behavior is required for
7940 		       maybe_process_partial_specialization to work
7941 		       correctly, but is not accurate in this case;
7942 		       the TAG is not an instantiation of anything.
7943 		       (The corresponding TEMPLATE_DECL is an
7944 		       instantiation, but the TYPE is not.) */
7945 		    CLASSTYPE_USE_TEMPLATE (newtag) = 0;
7946 
7947 		  /* Now, we call pushtag to put this NEWTAG into the scope of
7948 		     TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
7949 		     pushtag calling push_template_decl.  We don't have to do
7950 		     this for enums because it will already have been done in
7951 		     tsubst_enum.  */
7952 		  if (name)
7953 		    SET_IDENTIFIER_TYPE_VALUE (name, newtag);
7954 		  pushtag (name, newtag, /*tag_scope=*/ts_current);
7955 		}
7956 	    }
7957 	  else if (TREE_CODE (t) == FUNCTION_DECL
7958 		   || DECL_FUNCTION_TEMPLATE_P (t))
7959 	    {
7960 	      /* Build new TYPE_METHODS.  */
7961 	      tree r;
7962 
7963 	      if (TREE_CODE (t) == TEMPLATE_DECL)
7964 		++processing_template_decl;
7965 	      r = tsubst (t, args, tf_error, NULL_TREE);
7966 	      if (TREE_CODE (t) == TEMPLATE_DECL)
7967 		--processing_template_decl;
7968 	      set_current_access_from_decl (r);
7969 	      finish_member_declaration (r);
7970 	    }
7971 	  else
7972 	    {
7973 	      /* Build new TYPE_FIELDS.  */
7974               if (TREE_CODE (t) == STATIC_ASSERT)
7975                 {
7976                   tree condition =
7977                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args,
7978                                  tf_warning_or_error, NULL_TREE,
7979                                  /*integral_constant_expression_p=*/true);
7980                   finish_static_assert (condition,
7981                                         STATIC_ASSERT_MESSAGE (t),
7982                                         STATIC_ASSERT_SOURCE_LOCATION (t),
7983                                         /*member_p=*/true);
7984                 }
7985 	      else if (TREE_CODE (t) != CONST_DECL)
7986 		{
7987 		  tree r;
7988 
7989 		  /* The file and line for this declaration, to
7990 		     assist in error message reporting.  Since we
7991 		     called push_tinst_level above, we don't need to
7992 		     restore these.  */
7993 		  input_location = DECL_SOURCE_LOCATION (t);
7994 
7995 		  if (TREE_CODE (t) == TEMPLATE_DECL)
7996 		    ++processing_template_decl;
7997 		  r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
7998 		  if (TREE_CODE (t) == TEMPLATE_DECL)
7999 		    --processing_template_decl;
8000 		  if (TREE_CODE (r) == VAR_DECL)
8001 		    {
8002 		      /* In [temp.inst]:
8003 
8004 			   [t]he initialization (and any associated
8005 			   side-effects) of a static data member does
8006 			   not occur unless the static data member is
8007 			   itself used in a way that requires the
8008 			   definition of the static data member to
8009 			   exist.
8010 
8011 			 Therefore, we do not substitute into the
8012 			 initialized for the static data member here.  */
8013 		      finish_static_data_member_decl
8014 			(r,
8015 			 /*init=*/NULL_TREE,
8016 			 /*init_const_expr_p=*/false,
8017 			 /*asmspec_tree=*/NULL_TREE,
8018 			 /*flags=*/0);
8019 		      if (DECL_INITIALIZED_IN_CLASS_P (r))
8020 			check_static_variable_definition (r, TREE_TYPE (r));
8021 		    }
8022 		  else if (TREE_CODE (r) == FIELD_DECL)
8023 		    {
8024 		      /* Determine whether R has a valid type and can be
8025 			 completed later.  If R is invalid, then it is
8026 			 replaced by error_mark_node so that it will not be
8027 			 added to TYPE_FIELDS.  */
8028 		      tree rtype = TREE_TYPE (r);
8029 		      if (can_complete_type_without_circularity (rtype))
8030 			complete_type (rtype);
8031 
8032 		      if (!COMPLETE_TYPE_P (rtype))
8033 			{
8034 			  cxx_incomplete_type_error (r, rtype);
8035 			  r = error_mark_node;
8036 			}
8037 		    }
8038 
8039 		  /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
8040 		     such a thing will already have been added to the field
8041 		     list by tsubst_enum in finish_member_declaration in the
8042 		     CLASSTYPE_NESTED_UTDS case above.  */
8043 		  if (!(TREE_CODE (r) == TYPE_DECL
8044 			&& TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
8045 			&& DECL_ARTIFICIAL (r)))
8046 		    {
8047 		      set_current_access_from_decl (r);
8048 		      finish_member_declaration (r);
8049 		    }
8050 		}
8051 	    }
8052 	}
8053       else
8054 	{
8055 	  if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
8056 	    {
8057 	      /* Build new CLASSTYPE_FRIEND_CLASSES.  */
8058 
8059 	      tree friend_type = t;
8060 	      bool adjust_processing_template_decl = false;
8061 
8062 	      if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8063 		{
8064 		  /* template <class T> friend class C;  */
8065 		  friend_type = tsubst_friend_class (friend_type, args);
8066 		  adjust_processing_template_decl = true;
8067 		}
8068 	      else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
8069 		{
8070 		  /* template <class T> friend class C::D;  */
8071 		  friend_type = tsubst (friend_type, args,
8072 					tf_warning_or_error, NULL_TREE);
8073 		  if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8074 		    friend_type = TREE_TYPE (friend_type);
8075 		  adjust_processing_template_decl = true;
8076 		}
8077 	      else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
8078 		{
8079 		  /* This could be either
8080 
8081 		       friend class T::C;
8082 
8083 		     when dependent_type_p is false or
8084 
8085 		       template <class U> friend class T::C;
8086 
8087 		     otherwise.  */
8088 		  friend_type = tsubst (friend_type, args,
8089 					tf_warning_or_error, NULL_TREE);
8090 		  /* Bump processing_template_decl for correct
8091 		     dependent_type_p calculation.  */
8092 		  ++processing_template_decl;
8093 		  if (dependent_type_p (friend_type))
8094 		    adjust_processing_template_decl = true;
8095 		  --processing_template_decl;
8096 		}
8097 	      else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
8098 		       && hidden_name_p (TYPE_NAME (friend_type)))
8099 		{
8100 		  /* friend class C;
8101 
8102 		     where C hasn't been declared yet.  Let's lookup name
8103 		     from namespace scope directly, bypassing any name that
8104 		     come from dependent base class.  */
8105 		  tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
8106 
8107 		  /* The call to xref_tag_from_type does injection for friend
8108 		     classes.  */
8109 		  push_nested_namespace (ns);
8110 		  friend_type =
8111 		    xref_tag_from_type (friend_type, NULL_TREE,
8112 					/*tag_scope=*/ts_current);
8113 		  pop_nested_namespace (ns);
8114 		}
8115 	      else if (uses_template_parms (friend_type))
8116 		/* friend class C<T>;  */
8117 		friend_type = tsubst (friend_type, args,
8118 				      tf_warning_or_error, NULL_TREE);
8119 	      /* Otherwise it's
8120 
8121 		   friend class C;
8122 
8123 		 where C is already declared or
8124 
8125 		   friend class C<int>;
8126 
8127 		 We don't have to do anything in these cases.  */
8128 
8129 	      if (adjust_processing_template_decl)
8130 		/* Trick make_friend_class into realizing that the friend
8131 		   we're adding is a template, not an ordinary class.  It's
8132 		   important that we use make_friend_class since it will
8133 		   perform some error-checking and output cross-reference
8134 		   information.  */
8135 		++processing_template_decl;
8136 
8137 	      if (friend_type != error_mark_node)
8138 		make_friend_class (type, friend_type, /*complain=*/false);
8139 
8140 	      if (adjust_processing_template_decl)
8141 		--processing_template_decl;
8142 	    }
8143 	  else
8144 	    {
8145 	      /* Build new DECL_FRIENDLIST.  */
8146 	      tree r;
8147 
8148 	      /* The file and line for this declaration, to
8149 		 assist in error message reporting.  Since we
8150 		 called push_tinst_level above, we don't need to
8151 		 restore these.  */
8152 	      input_location = DECL_SOURCE_LOCATION (t);
8153 
8154 	      if (TREE_CODE (t) == TEMPLATE_DECL)
8155 		{
8156 		  ++processing_template_decl;
8157 		  push_deferring_access_checks (dk_no_check);
8158 		}
8159 
8160 	      r = tsubst_friend_function (t, args);
8161 	      add_friend (type, r, /*complain=*/false);
8162 	      if (TREE_CODE (t) == TEMPLATE_DECL)
8163 		{
8164 		  pop_deferring_access_checks ();
8165 		  --processing_template_decl;
8166 		}
8167 	    }
8168 	}
8169     }
8170 
8171   /* Set the file and line number information to whatever is given for
8172      the class itself.  This puts error messages involving generated
8173      implicit functions at a predictable point, and the same point
8174      that would be used for non-template classes.  */
8175   input_location = DECL_SOURCE_LOCATION (typedecl);
8176 
8177   unreverse_member_declarations (type);
8178   finish_struct_1 (type);
8179   TYPE_BEING_DEFINED (type) = 0;
8180 
8181   /* Now that the class is complete, instantiate default arguments for
8182      any member functions.  We don't do this earlier because the
8183      default arguments may reference members of the class.  */
8184   if (!PRIMARY_TEMPLATE_P (templ))
8185     for (t = TYPE_METHODS (type); t; t = TREE_CHAIN (t))
8186       if (TREE_CODE (t) == FUNCTION_DECL
8187 	  /* Implicitly generated member functions will not have template
8188 	     information; they are not instantiations, but instead are
8189 	     created "fresh" for each instantiation.  */
8190 	  && DECL_TEMPLATE_INFO (t))
8191 	tsubst_default_arguments (t);
8192 
8193   /* Some typedefs referenced from within the template code need to be access
8194      checked at template instantiation time, i.e now. These types were
8195      added to the template at parsing time. Let's get those and perform
8196      the access checks then.  */
8197   perform_typedefs_access_check (pattern, args);
8198   perform_deferred_access_checks ();
8199   pop_nested_class ();
8200   maximum_field_alignment = saved_maximum_field_alignment;
8201   pop_from_top_level ();
8202   pop_deferring_access_checks ();
8203   pop_tinst_level ();
8204 
8205   /* The vtable for a template class can be emitted in any translation
8206      unit in which the class is instantiated.  When there is no key
8207      method, however, finish_struct_1 will already have added TYPE to
8208      the keyed_classes list.  */
8209   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
8210     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
8211 
8212   return type;
8213 }
8214 
8215 static tree
8216 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8217 {
8218   tree r;
8219 
8220   if (!t)
8221     r = t;
8222   else if (TYPE_P (t))
8223     r = tsubst (t, args, complain, in_decl);
8224   else
8225     {
8226       r = tsubst_expr (t, args, complain, in_decl,
8227 		       /*integral_constant_expression_p=*/true);
8228       r = fold_non_dependent_expr (r);
8229     }
8230   return r;
8231 }
8232 
8233 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
8234    NONTYPE_ARGUMENT_PACK.  */
8235 
8236 static tree
8237 make_fnparm_pack (tree spec_parm)
8238 {
8239   /* Collect all of the extra "packed" parameters into an
8240      argument pack.  */
8241   tree parmvec;
8242   tree parmtypevec;
8243   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
8244   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
8245   int i, len = list_length (spec_parm);
8246 
8247   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
8248   parmvec = make_tree_vec (len);
8249   parmtypevec = make_tree_vec (len);
8250   for (i = 0; i < len; i++, spec_parm = TREE_CHAIN (spec_parm))
8251     {
8252       TREE_VEC_ELT (parmvec, i) = spec_parm;
8253       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
8254     }
8255 
8256   /* Build the argument packs.  */
8257   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
8258   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
8259   TREE_TYPE (argpack) = argtypepack;
8260 
8261   return argpack;
8262 }
8263 
8264 /* Substitute ARGS into T, which is an pack expansion
8265    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
8266    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
8267    (if only a partial substitution could be performed) or
8268    ERROR_MARK_NODE if there was an error.  */
8269 tree
8270 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
8271 		       tree in_decl)
8272 {
8273   tree pattern;
8274   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
8275   int i, len = -1;
8276   tree result;
8277   int incomplete = 0;
8278   htab_t saved_local_specializations = NULL;
8279 
8280   gcc_assert (PACK_EXPANSION_P (t));
8281   pattern = PACK_EXPANSION_PATTERN (t);
8282 
8283   /* Determine the argument packs that will instantiate the parameter
8284      packs used in the expansion expression. While we're at it,
8285      compute the number of arguments to be expanded and make sure it
8286      is consistent.  */
8287   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack;
8288        pack = TREE_CHAIN (pack))
8289     {
8290       tree parm_pack = TREE_VALUE (pack);
8291       tree arg_pack = NULL_TREE;
8292       tree orig_arg = NULL_TREE;
8293 
8294       if (TREE_CODE (parm_pack) == PARM_DECL)
8295 	{
8296 	  if (!cp_unevaluated_operand)
8297 	    arg_pack = retrieve_local_specialization (parm_pack);
8298 	  else
8299 	    {
8300 	      /* We can't rely on local_specializations for a parameter
8301 		 name used later in a function declaration (such as in a
8302 		 late-specified return type).  Even if it exists, it might
8303 		 have the wrong value for a recursive call.  Just make a
8304 		 dummy decl, since it's only used for its type.  */
8305 	      arg_pack = tsubst_decl (parm_pack, args, complain);
8306 	      arg_pack = make_fnparm_pack (arg_pack);
8307 	    }
8308 	}
8309       else
8310         {
8311           int level, idx, levels;
8312           template_parm_level_and_index (parm_pack, &level, &idx);
8313 
8314           levels = TMPL_ARGS_DEPTH (args);
8315           if (level <= levels)
8316             arg_pack = TMPL_ARG (args, level, idx);
8317         }
8318 
8319       orig_arg = arg_pack;
8320       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
8321 	arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
8322 
8323       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
8324 	/* This can only happen if we forget to expand an argument
8325 	   pack somewhere else. Just return an error, silently.  */
8326 	{
8327 	  result = make_tree_vec (1);
8328 	  TREE_VEC_ELT (result, 0) = error_mark_node;
8329 	  return result;
8330 	}
8331 
8332       if (arg_pack
8333           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
8334           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
8335         {
8336           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
8337           tree pattern = PACK_EXPANSION_PATTERN (expansion);
8338           if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
8339               || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
8340             /* The argument pack that the parameter maps to is just an
8341                expansion of the parameter itself, such as one would
8342                find in the implicit typedef of a class inside the
8343                class itself.  Consider this parameter "unsubstituted",
8344                so that we will maintain the outer pack expansion.  */
8345             arg_pack = NULL_TREE;
8346         }
8347 
8348       if (arg_pack)
8349         {
8350           int my_len =
8351             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
8352 
8353           /* It's all-or-nothing with incomplete argument packs.  */
8354           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8355             return error_mark_node;
8356 
8357           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8358             incomplete = 1;
8359 
8360           if (len < 0)
8361 	    len = my_len;
8362           else if (len != my_len)
8363             {
8364 	      if (incomplete)
8365 		/* We got explicit args for some packs but not others;
8366 		   do nothing now and try again after deduction.  */
8367 		return t;
8368               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
8369                 error ("mismatched argument pack lengths while expanding "
8370                        "%<%T%>",
8371                        pattern);
8372               else
8373                 error ("mismatched argument pack lengths while expanding "
8374                        "%<%E%>",
8375                        pattern);
8376               return error_mark_node;
8377             }
8378 
8379           /* Keep track of the parameter packs and their corresponding
8380              argument packs.  */
8381           packs = tree_cons (parm_pack, arg_pack, packs);
8382           TREE_TYPE (packs) = orig_arg;
8383         }
8384       else
8385         /* We can't substitute for this parameter pack.  */
8386         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
8387                                          TREE_VALUE (pack),
8388                                          unsubstituted_packs);
8389     }
8390 
8391   /* We cannot expand this expansion expression, because we don't have
8392      all of the argument packs we need. Substitute into the pattern
8393      and return a PACK_EXPANSION_*. The caller will need to deal with
8394      that.  */
8395   if (unsubstituted_packs)
8396     {
8397       tree new_pat;
8398       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8399 	new_pat = tsubst_expr (pattern, args, complain, in_decl,
8400 			       /*integral_constant_expression_p=*/false);
8401       else
8402 	new_pat = tsubst (pattern, args, complain, in_decl);
8403       return make_pack_expansion (new_pat);
8404     }
8405 
8406   /* We could not find any argument packs that work.  */
8407   if (len < 0)
8408     return error_mark_node;
8409 
8410   if (cp_unevaluated_operand)
8411     {
8412       /* We're in a late-specified return type, so create our own local
8413 	 specializations table; the current table is either NULL or (in the
8414 	 case of recursive unification) might have bindings that we don't
8415 	 want to use or alter.  */
8416       saved_local_specializations = local_specializations;
8417       local_specializations = htab_create (37,
8418 					   hash_local_specialization,
8419 					   eq_local_specializations,
8420 					   NULL);
8421     }
8422 
8423   /* For each argument in each argument pack, substitute into the
8424      pattern.  */
8425   result = make_tree_vec (len + incomplete);
8426   for (i = 0; i < len + incomplete; ++i)
8427     {
8428       /* For parameter pack, change the substitution of the parameter
8429          pack to the ith argument in its argument pack, then expand
8430          the pattern.  */
8431       for (pack = packs; pack; pack = TREE_CHAIN (pack))
8432         {
8433           tree parm = TREE_PURPOSE (pack);
8434 
8435           if (TREE_CODE (parm) == PARM_DECL)
8436             {
8437 	      /* Select the Ith argument from the pack.  */
8438 	      tree arg = make_node (ARGUMENT_PACK_SELECT);
8439 	      ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
8440 	      ARGUMENT_PACK_SELECT_INDEX (arg) = i;
8441               mark_used (parm);
8442               register_local_specialization (arg, parm);
8443             }
8444           else
8445             {
8446               tree value = parm;
8447               int idx, level;
8448               template_parm_level_and_index (parm, &level, &idx);
8449 
8450 	      if (i < len)
8451 		{
8452 		  /* Select the Ith argument from the pack. */
8453 		  value = make_node (ARGUMENT_PACK_SELECT);
8454 		  ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
8455 		  ARGUMENT_PACK_SELECT_INDEX (value) = i;
8456 		}
8457 
8458               /* Update the corresponding argument.  */
8459               TMPL_ARG (args, level, idx) = value;
8460             }
8461         }
8462 
8463       /* Substitute into the PATTERN with the altered arguments.  */
8464       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8465         TREE_VEC_ELT (result, i) =
8466           tsubst_expr (pattern, args, complain, in_decl,
8467                        /*integral_constant_expression_p=*/false);
8468       else
8469         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
8470 
8471       if (i == len)
8472         /* When we have incomplete argument packs, the last "expanded"
8473            result is itself a pack expansion, which allows us
8474            to deduce more arguments.  */
8475         TREE_VEC_ELT (result, i) =
8476           make_pack_expansion (TREE_VEC_ELT (result, i));
8477 
8478       if (TREE_VEC_ELT (result, i) == error_mark_node)
8479 	{
8480 	  result = error_mark_node;
8481 	  break;
8482 	}
8483     }
8484 
8485   /* Update ARGS to restore the substitution from parameter packs to
8486      their argument packs.  */
8487   for (pack = packs; pack; pack = TREE_CHAIN (pack))
8488     {
8489       tree parm = TREE_PURPOSE (pack);
8490 
8491       if (TREE_CODE (parm) == PARM_DECL)
8492         register_local_specialization (TREE_TYPE (pack), parm);
8493       else
8494         {
8495           int idx, level;
8496           template_parm_level_and_index (parm, &level, &idx);
8497 
8498           /* Update the corresponding argument.  */
8499           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
8500             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
8501               TREE_TYPE (pack);
8502           else
8503             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
8504         }
8505     }
8506 
8507   if (saved_local_specializations)
8508     {
8509       htab_delete (local_specializations);
8510       local_specializations = saved_local_specializations;
8511     }
8512 
8513   return result;
8514 }
8515 
8516 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
8517    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
8518    parameter packs; all parms generated from a function parameter pack will
8519    have the same DECL_PARM_INDEX.  */
8520 
8521 tree
8522 get_pattern_parm (tree parm, tree tmpl)
8523 {
8524   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
8525   tree patparm;
8526 
8527   if (DECL_ARTIFICIAL (parm))
8528     {
8529       for (patparm = DECL_ARGUMENTS (pattern);
8530 	   patparm; patparm = TREE_CHAIN (patparm))
8531 	if (DECL_ARTIFICIAL (patparm)
8532 	    && DECL_NAME (parm) == DECL_NAME (patparm))
8533 	  break;
8534     }
8535   else
8536     {
8537       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
8538       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
8539       gcc_assert (DECL_PARM_INDEX (patparm)
8540 		  == DECL_PARM_INDEX (parm));
8541     }
8542 
8543   return patparm;
8544 }
8545 
8546 /* Substitute ARGS into the vector or list of template arguments T.  */
8547 
8548 static tree
8549 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8550 {
8551   tree orig_t = t;
8552   int len = TREE_VEC_LENGTH (t);
8553   int need_new = 0, i, expanded_len_adjust = 0, out;
8554   tree *elts = (tree *) alloca (len * sizeof (tree));
8555 
8556   for (i = 0; i < len; i++)
8557     {
8558       tree orig_arg = TREE_VEC_ELT (t, i);
8559       tree new_arg;
8560 
8561       if (TREE_CODE (orig_arg) == TREE_VEC)
8562 	new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
8563       else if (PACK_EXPANSION_P (orig_arg))
8564         {
8565           /* Substitute into an expansion expression.  */
8566           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
8567 
8568           if (TREE_CODE (new_arg) == TREE_VEC)
8569             /* Add to the expanded length adjustment the number of
8570                expanded arguments. We subtract one from this
8571                measurement, because the argument pack expression
8572                itself is already counted as 1 in
8573                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
8574                the argument pack is empty.  */
8575             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
8576         }
8577       else if (ARGUMENT_PACK_P (orig_arg))
8578         {
8579           /* Substitute into each of the arguments.  */
8580           new_arg = TYPE_P (orig_arg)
8581             ? cxx_make_type (TREE_CODE (orig_arg))
8582             : make_node (TREE_CODE (orig_arg));
8583 
8584           SET_ARGUMENT_PACK_ARGS (
8585             new_arg,
8586             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
8587                                   args, complain, in_decl));
8588 
8589           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
8590             new_arg = error_mark_node;
8591 
8592           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
8593             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
8594                                           complain, in_decl);
8595             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
8596 
8597             if (TREE_TYPE (new_arg) == error_mark_node)
8598               new_arg = error_mark_node;
8599           }
8600         }
8601       else
8602 	new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
8603 
8604       if (new_arg == error_mark_node)
8605 	return error_mark_node;
8606 
8607       elts[i] = new_arg;
8608       if (new_arg != orig_arg)
8609 	need_new = 1;
8610     }
8611 
8612   if (!need_new)
8613     return t;
8614 
8615   /* Make space for the expanded arguments coming from template
8616      argument packs.  */
8617   t = make_tree_vec (len + expanded_len_adjust);
8618   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
8619      arguments for a member template.
8620      In that case each TREE_VEC in ORIG_T represents a level of template
8621      arguments, and ORIG_T won't carry any non defaulted argument count.
8622      It will rather be the nested TREE_VECs that will carry one.
8623      In other words, ORIG_T carries a non defaulted argument count only
8624      if it doesn't contain any nested TREE_VEC.  */
8625   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
8626     {
8627       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
8628       count += expanded_len_adjust;
8629       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
8630     }
8631   for (i = 0, out = 0; i < len; i++)
8632     {
8633       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
8634            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
8635           && TREE_CODE (elts[i]) == TREE_VEC)
8636         {
8637           int idx;
8638 
8639           /* Now expand the template argument pack "in place".  */
8640           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
8641             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
8642         }
8643       else
8644         {
8645           TREE_VEC_ELT (t, out) = elts[i];
8646           out++;
8647         }
8648     }
8649 
8650   return t;
8651 }
8652 
8653 /* Return the result of substituting ARGS into the template parameters
8654    given by PARMS.  If there are m levels of ARGS and m + n levels of
8655    PARMS, then the result will contain n levels of PARMS.  For
8656    example, if PARMS is `template <class T> template <class U>
8657    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
8658    result will be `template <int*, double, class V>'.  */
8659 
8660 static tree
8661 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
8662 {
8663   tree r = NULL_TREE;
8664   tree* new_parms;
8665 
8666   /* When substituting into a template, we must set
8667      PROCESSING_TEMPLATE_DECL as the template parameters may be
8668      dependent if they are based on one-another, and the dependency
8669      predicates are short-circuit outside of templates.  */
8670   ++processing_template_decl;
8671 
8672   for (new_parms = &r;
8673        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
8674        new_parms = &(TREE_CHAIN (*new_parms)),
8675 	 parms = TREE_CHAIN (parms))
8676     {
8677       tree new_vec =
8678 	make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
8679       int i;
8680 
8681       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
8682 	{
8683           tree tuple;
8684           tree default_value;
8685           tree parm_decl;
8686 
8687           if (parms == error_mark_node)
8688             continue;
8689 
8690           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
8691 
8692           if (tuple == error_mark_node)
8693             continue;
8694 
8695           default_value = TREE_PURPOSE (tuple);
8696           parm_decl = TREE_VALUE (tuple);
8697 
8698 	  parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
8699 	  if (TREE_CODE (parm_decl) == PARM_DECL
8700 	      && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
8701 	    parm_decl = error_mark_node;
8702 	  default_value = tsubst_template_arg (default_value, args,
8703 					       complain, NULL_TREE);
8704 
8705 	  tuple = build_tree_list (default_value, parm_decl);
8706 	  TREE_VEC_ELT (new_vec, i) = tuple;
8707 	}
8708 
8709       *new_parms =
8710 	tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
8711 			     - TMPL_ARGS_DEPTH (args)),
8712 		   new_vec, NULL_TREE);
8713     }
8714 
8715   --processing_template_decl;
8716 
8717   return r;
8718 }
8719 
8720 /* Substitute the ARGS into the indicated aggregate (or enumeration)
8721    type T.  If T is not an aggregate or enumeration type, it is
8722    handled as if by tsubst.  IN_DECL is as for tsubst.  If
8723    ENTERING_SCOPE is nonzero, T is the context for a template which
8724    we are presently tsubst'ing.  Return the substituted value.  */
8725 
8726 static tree
8727 tsubst_aggr_type (tree t,
8728 		  tree args,
8729 		  tsubst_flags_t complain,
8730 		  tree in_decl,
8731 		  int entering_scope)
8732 {
8733   if (t == NULL_TREE)
8734     return NULL_TREE;
8735 
8736   switch (TREE_CODE (t))
8737     {
8738     case RECORD_TYPE:
8739       if (TYPE_PTRMEMFUNC_P (t))
8740 	return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
8741 
8742       /* Else fall through.  */
8743     case ENUMERAL_TYPE:
8744     case UNION_TYPE:
8745       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
8746 	{
8747 	  tree argvec;
8748 	  tree context;
8749 	  tree r;
8750 	  int saved_unevaluated_operand;
8751 	  int saved_inhibit_evaluation_warnings;
8752 
8753 	  /* In "sizeof(X<I>)" we need to evaluate "I".  */
8754 	  saved_unevaluated_operand = cp_unevaluated_operand;
8755 	  cp_unevaluated_operand = 0;
8756 	  saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
8757 	  c_inhibit_evaluation_warnings = 0;
8758 
8759 	  /* First, determine the context for the type we are looking
8760 	     up.  */
8761 	  context = TYPE_CONTEXT (t);
8762 	  if (context)
8763 	    {
8764 	      context = tsubst_aggr_type (context, args, complain,
8765 					  in_decl, /*entering_scope=*/1);
8766 	      /* If context is a nested class inside a class template,
8767 	         it may still need to be instantiated (c++/33959).  */
8768 	      if (TYPE_P (context))
8769 		context = complete_type (context);
8770 	    }
8771 
8772 	  /* Then, figure out what arguments are appropriate for the
8773 	     type we are trying to find.  For example, given:
8774 
8775 	       template <class T> struct S;
8776 	       template <class T, class U> void f(T, U) { S<U> su; }
8777 
8778 	     and supposing that we are instantiating f<int, double>,
8779 	     then our ARGS will be {int, double}, but, when looking up
8780 	     S we only want {double}.  */
8781 	  argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
8782 					 complain, in_decl);
8783 	  if (argvec == error_mark_node)
8784 	    r = error_mark_node;
8785 	  else
8786 	    {
8787 	      r = lookup_template_class (t, argvec, in_decl, context,
8788 					 entering_scope, complain);
8789 	      r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
8790 	    }
8791 
8792 	  cp_unevaluated_operand = saved_unevaluated_operand;
8793 	  c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
8794 
8795 	  return r;
8796 	}
8797       else
8798 	/* This is not a template type, so there's nothing to do.  */
8799 	return t;
8800 
8801     default:
8802       return tsubst (t, args, complain, in_decl);
8803     }
8804 }
8805 
8806 /* Substitute into the default argument ARG (a default argument for
8807    FN), which has the indicated TYPE.  */
8808 
8809 tree
8810 tsubst_default_argument (tree fn, tree type, tree arg)
8811 {
8812   tree saved_class_ptr = NULL_TREE;
8813   tree saved_class_ref = NULL_TREE;
8814 
8815   /* This default argument came from a template.  Instantiate the
8816      default argument here, not in tsubst.  In the case of
8817      something like:
8818 
8819        template <class T>
8820        struct S {
8821 	 static T t();
8822 	 void f(T = t());
8823        };
8824 
8825      we must be careful to do name lookup in the scope of S<T>,
8826      rather than in the current class.  */
8827   push_access_scope (fn);
8828   /* The "this" pointer is not valid in a default argument.  */
8829   if (cfun)
8830     {
8831       saved_class_ptr = current_class_ptr;
8832       cp_function_chain->x_current_class_ptr = NULL_TREE;
8833       saved_class_ref = current_class_ref;
8834       cp_function_chain->x_current_class_ref = NULL_TREE;
8835     }
8836 
8837   push_deferring_access_checks(dk_no_deferred);
8838   /* The default argument expression may cause implicitly defined
8839      member functions to be synthesized, which will result in garbage
8840      collection.  We must treat this situation as if we were within
8841      the body of function so as to avoid collecting live data on the
8842      stack.  */
8843   ++function_depth;
8844   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
8845 		     tf_warning_or_error, NULL_TREE,
8846 		     /*integral_constant_expression_p=*/false);
8847   --function_depth;
8848   pop_deferring_access_checks();
8849 
8850   /* Restore the "this" pointer.  */
8851   if (cfun)
8852     {
8853       cp_function_chain->x_current_class_ptr = saved_class_ptr;
8854       cp_function_chain->x_current_class_ref = saved_class_ref;
8855     }
8856 
8857   /* Make sure the default argument is reasonable.  */
8858   arg = check_default_argument (type, arg);
8859 
8860   pop_access_scope (fn);
8861 
8862   return arg;
8863 }
8864 
8865 /* Substitute into all the default arguments for FN.  */
8866 
8867 static void
8868 tsubst_default_arguments (tree fn)
8869 {
8870   tree arg;
8871   tree tmpl_args;
8872 
8873   tmpl_args = DECL_TI_ARGS (fn);
8874 
8875   /* If this function is not yet instantiated, we certainly don't need
8876      its default arguments.  */
8877   if (uses_template_parms (tmpl_args))
8878     return;
8879 
8880   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
8881        arg;
8882        arg = TREE_CHAIN (arg))
8883     if (TREE_PURPOSE (arg))
8884       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
8885 						    TREE_VALUE (arg),
8886 						    TREE_PURPOSE (arg));
8887 }
8888 
8889 /* Substitute the ARGS into the T, which is a _DECL.  Return the
8890    result of the substitution.  Issue error and warning messages under
8891    control of COMPLAIN.  */
8892 
8893 static tree
8894 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
8895 {
8896 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
8897   location_t saved_loc;
8898   tree r = NULL_TREE;
8899   tree in_decl = t;
8900   hashval_t hash = 0;
8901 
8902   /* Set the filename and linenumber to improve error-reporting.  */
8903   saved_loc = input_location;
8904   input_location = DECL_SOURCE_LOCATION (t);
8905 
8906   switch (TREE_CODE (t))
8907     {
8908     case TEMPLATE_DECL:
8909       {
8910 	/* We can get here when processing a member function template,
8911 	   member class template, or template template parameter.  */
8912 	tree decl = DECL_TEMPLATE_RESULT (t);
8913 	tree spec;
8914 	tree tmpl_args;
8915 	tree full_args;
8916 
8917 	if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
8918 	  {
8919 	    /* Template template parameter is treated here.  */
8920 	    tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8921 	    if (new_type == error_mark_node)
8922 	      RETURN (error_mark_node);
8923 
8924 	    r = copy_decl (t);
8925 	    TREE_CHAIN (r) = NULL_TREE;
8926 	    TREE_TYPE (r) = new_type;
8927 	    DECL_TEMPLATE_RESULT (r)
8928 	      = build_decl (DECL_SOURCE_LOCATION (decl),
8929 			    TYPE_DECL, DECL_NAME (decl), new_type);
8930 	    DECL_TEMPLATE_PARMS (r)
8931 	      = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8932 				       complain);
8933 	    TYPE_NAME (new_type) = r;
8934 	    break;
8935 	  }
8936 
8937 	/* We might already have an instance of this template.
8938 	   The ARGS are for the surrounding class type, so the
8939 	   full args contain the tsubst'd args for the context,
8940 	   plus the innermost args from the template decl.  */
8941 	tmpl_args = DECL_CLASS_TEMPLATE_P (t)
8942 	  ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
8943 	  : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
8944 	/* Because this is a template, the arguments will still be
8945 	   dependent, even after substitution.  If
8946 	   PROCESSING_TEMPLATE_DECL is not set, the dependency
8947 	   predicates will short-circuit.  */
8948 	++processing_template_decl;
8949 	full_args = tsubst_template_args (tmpl_args, args,
8950 					  complain, in_decl);
8951 	--processing_template_decl;
8952 	if (full_args == error_mark_node)
8953 	  RETURN (error_mark_node);
8954 
8955 	/* If this is a default template template argument,
8956 	   tsubst might not have changed anything.  */
8957 	if (full_args == tmpl_args)
8958 	  RETURN (t);
8959 
8960 	hash = hash_tmpl_and_args (t, full_args);
8961 	spec = retrieve_specialization (t, full_args, hash);
8962 	if (spec != NULL_TREE)
8963 	  {
8964 	    r = spec;
8965 	    break;
8966 	  }
8967 
8968 	/* Make a new template decl.  It will be similar to the
8969 	   original, but will record the current template arguments.
8970 	   We also create a new function declaration, which is just
8971 	   like the old one, but points to this new template, rather
8972 	   than the old one.  */
8973 	r = copy_decl (t);
8974 	gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
8975 	TREE_CHAIN (r) = NULL_TREE;
8976 
8977 	DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
8978 
8979 	if (TREE_CODE (decl) == TYPE_DECL)
8980 	  {
8981 	    tree new_type;
8982 	    ++processing_template_decl;
8983 	    new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8984 	    --processing_template_decl;
8985 	    if (new_type == error_mark_node)
8986 	      RETURN (error_mark_node);
8987 
8988 	    TREE_TYPE (r) = new_type;
8989 	    CLASSTYPE_TI_TEMPLATE (new_type) = r;
8990 	    DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
8991 	    DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
8992 	    DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
8993 	  }
8994 	else
8995 	  {
8996 	    tree new_decl;
8997 	    ++processing_template_decl;
8998 	    new_decl = tsubst (decl, args, complain, in_decl);
8999 	    --processing_template_decl;
9000 	    if (new_decl == error_mark_node)
9001 	      RETURN (error_mark_node);
9002 
9003 	    DECL_TEMPLATE_RESULT (r) = new_decl;
9004 	    DECL_TI_TEMPLATE (new_decl) = r;
9005 	    TREE_TYPE (r) = TREE_TYPE (new_decl);
9006 	    DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
9007 	    DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
9008 	  }
9009 
9010 	SET_DECL_IMPLICIT_INSTANTIATION (r);
9011 	DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
9012 	DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
9013 
9014 	/* The template parameters for this new template are all the
9015 	   template parameters for the old template, except the
9016 	   outermost level of parameters.  */
9017 	DECL_TEMPLATE_PARMS (r)
9018 	  = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
9019 				   complain);
9020 
9021 	if (PRIMARY_TEMPLATE_P (t))
9022 	  DECL_PRIMARY_TEMPLATE (r) = r;
9023 
9024 	if (TREE_CODE (decl) != TYPE_DECL)
9025 	  /* Record this non-type partial instantiation.  */
9026 	  register_specialization (r, t,
9027 				   DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
9028 				   false, hash);
9029       }
9030       break;
9031 
9032     case FUNCTION_DECL:
9033       {
9034 	tree ctx;
9035 	tree argvec = NULL_TREE;
9036 	tree *friends;
9037 	tree gen_tmpl;
9038 	tree type;
9039 	int member;
9040 	int args_depth;
9041 	int parms_depth;
9042 
9043 	/* Nobody should be tsubst'ing into non-template functions.  */
9044 	gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
9045 
9046 	if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
9047 	  {
9048 	    tree spec;
9049 	    bool dependent_p;
9050 
9051 	    /* If T is not dependent, just return it.  We have to
9052 	       increment PROCESSING_TEMPLATE_DECL because
9053 	       value_dependent_expression_p assumes that nothing is
9054 	       dependent when PROCESSING_TEMPLATE_DECL is zero.  */
9055 	    ++processing_template_decl;
9056 	    dependent_p = value_dependent_expression_p (t);
9057 	    --processing_template_decl;
9058 	    if (!dependent_p)
9059 	      RETURN (t);
9060 
9061 	    /* Calculate the most general template of which R is a
9062 	       specialization, and the complete set of arguments used to
9063 	       specialize R.  */
9064 	    gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
9065 	    argvec = tsubst_template_args (DECL_TI_ARGS
9066 					   (DECL_TEMPLATE_RESULT (gen_tmpl)),
9067 					   args, complain, in_decl);
9068 
9069 	    /* Check to see if we already have this specialization.  */
9070 	    hash = hash_tmpl_and_args (gen_tmpl, argvec);
9071 	    spec = retrieve_specialization (gen_tmpl, argvec, hash);
9072 
9073 	    if (spec)
9074 	      {
9075 		r = spec;
9076 		break;
9077 	      }
9078 
9079 	    /* We can see more levels of arguments than parameters if
9080 	       there was a specialization of a member template, like
9081 	       this:
9082 
9083 		 template <class T> struct S { template <class U> void f(); }
9084 		 template <> template <class U> void S<int>::f(U);
9085 
9086 	       Here, we'll be substituting into the specialization,
9087 	       because that's where we can find the code we actually
9088 	       want to generate, but we'll have enough arguments for
9089 	       the most general template.
9090 
9091 	       We also deal with the peculiar case:
9092 
9093 		 template <class T> struct S {
9094 		   template <class U> friend void f();
9095 		 };
9096 		 template <class U> void f() {}
9097 		 template S<int>;
9098 		 template void f<double>();
9099 
9100 	       Here, the ARGS for the instantiation of will be {int,
9101 	       double}.  But, we only need as many ARGS as there are
9102 	       levels of template parameters in CODE_PATTERN.  We are
9103 	       careful not to get fooled into reducing the ARGS in
9104 	       situations like:
9105 
9106 		 template <class T> struct S { template <class U> void f(U); }
9107 		 template <class T> template <> void S<T>::f(int) {}
9108 
9109 	       which we can spot because the pattern will be a
9110 	       specialization in this case.  */
9111 	    args_depth = TMPL_ARGS_DEPTH (args);
9112 	    parms_depth =
9113 	      TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
9114 	    if (args_depth > parms_depth
9115 		&& !DECL_TEMPLATE_SPECIALIZATION (t))
9116 	      args = get_innermost_template_args (args, parms_depth);
9117 	  }
9118 	else
9119 	  {
9120 	    /* This special case arises when we have something like this:
9121 
9122 		 template <class T> struct S {
9123 		   friend void f<int>(int, double);
9124 		 };
9125 
9126 	       Here, the DECL_TI_TEMPLATE for the friend declaration
9127 	       will be an IDENTIFIER_NODE.  We are being called from
9128 	       tsubst_friend_function, and we want only to create a
9129 	       new decl (R) with appropriate types so that we can call
9130 	       determine_specialization.  */
9131 	    gen_tmpl = NULL_TREE;
9132 	  }
9133 
9134 	if (DECL_CLASS_SCOPE_P (t))
9135 	  {
9136 	    if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
9137 	      member = 2;
9138 	    else
9139 	      member = 1;
9140 	    ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
9141 				    complain, t, /*entering_scope=*/1);
9142 	  }
9143 	else
9144 	  {
9145 	    member = 0;
9146 	    ctx = DECL_CONTEXT (t);
9147 	  }
9148 	type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9149 	if (type == error_mark_node)
9150 	  RETURN (error_mark_node);
9151 
9152 	/* We do NOT check for matching decls pushed separately at this
9153 	   point, as they may not represent instantiations of this
9154 	   template, and in any case are considered separate under the
9155 	   discrete model.  */
9156 	r = copy_decl (t);
9157 	DECL_USE_TEMPLATE (r) = 0;
9158 	TREE_TYPE (r) = type;
9159 	/* Clear out the mangled name and RTL for the instantiation.  */
9160 	SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9161 	SET_DECL_RTL (r, NULL_RTX);
9162 	/* Leave DECL_INITIAL set on deleted instantiations.  */
9163 	if (!DECL_DELETED_FN (r))
9164 	  DECL_INITIAL (r) = NULL_TREE;
9165 	DECL_CONTEXT (r) = ctx;
9166 
9167 	if (member && DECL_CONV_FN_P (r))
9168 	  /* Type-conversion operator.  Reconstruct the name, in
9169 	     case it's the name of one of the template's parameters.  */
9170 	  DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
9171 
9172 	DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
9173 				     complain, t);
9174 	DECL_RESULT (r) = NULL_TREE;
9175 
9176 	TREE_STATIC (r) = 0;
9177 	TREE_PUBLIC (r) = TREE_PUBLIC (t);
9178 	DECL_EXTERNAL (r) = 1;
9179 	/* If this is an instantiation of a function with internal
9180 	   linkage, we already know what object file linkage will be
9181 	   assigned to the instantiation.  */
9182 	DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
9183 	DECL_DEFER_OUTPUT (r) = 0;
9184 	TREE_CHAIN (r) = NULL_TREE;
9185 	DECL_PENDING_INLINE_INFO (r) = 0;
9186 	DECL_PENDING_INLINE_P (r) = 0;
9187 	DECL_SAVED_TREE (r) = NULL_TREE;
9188 	DECL_STRUCT_FUNCTION (r) = NULL;
9189 	TREE_USED (r) = 0;
9190 	/* We'll re-clone as appropriate in instantiate_template.  */
9191 	DECL_CLONED_FUNCTION (r) = NULL_TREE;
9192 
9193 	/* If we aren't complaining now, return on error before we register
9194 	   the specialization so that we'll complain eventually.  */
9195 	if ((complain & tf_error) == 0
9196 	    && IDENTIFIER_OPNAME_P (DECL_NAME (r))
9197 	    && !grok_op_properties (r, /*complain=*/false))
9198 	  RETURN (error_mark_node);
9199 
9200 	/* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
9201 	   this in the special friend case mentioned above where
9202 	   GEN_TMPL is NULL.  */
9203 	if (gen_tmpl)
9204 	  {
9205 	    DECL_TEMPLATE_INFO (r)
9206 	      = build_template_info (gen_tmpl, argvec);
9207 	    SET_DECL_IMPLICIT_INSTANTIATION (r);
9208 	    register_specialization (r, gen_tmpl, argvec, false, hash);
9209 
9210 	    /* We're not supposed to instantiate default arguments
9211 	       until they are called, for a template.  But, for a
9212 	       declaration like:
9213 
9214 		 template <class T> void f ()
9215 		 { extern void g(int i = T()); }
9216 
9217 	       we should do the substitution when the template is
9218 	       instantiated.  We handle the member function case in
9219 	       instantiate_class_template since the default arguments
9220 	       might refer to other members of the class.  */
9221 	    if (!member
9222 		&& !PRIMARY_TEMPLATE_P (gen_tmpl)
9223 		&& !uses_template_parms (argvec))
9224 	      tsubst_default_arguments (r);
9225 	  }
9226 	else
9227 	  DECL_TEMPLATE_INFO (r) = NULL_TREE;
9228 
9229 	/* Copy the list of befriending classes.  */
9230 	for (friends = &DECL_BEFRIENDING_CLASSES (r);
9231 	     *friends;
9232 	     friends = &TREE_CHAIN (*friends))
9233 	  {
9234 	    *friends = copy_node (*friends);
9235 	    TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
9236 					    args, complain,
9237 					    in_decl);
9238 	  }
9239 
9240 	if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
9241 	  {
9242 	    maybe_retrofit_in_chrg (r);
9243 	    if (DECL_CONSTRUCTOR_P (r))
9244 	      grok_ctor_properties (ctx, r);
9245 	    /* If this is an instantiation of a member template, clone it.
9246 	       If it isn't, that'll be handled by
9247 	       clone_constructors_and_destructors.  */
9248 	    if (PRIMARY_TEMPLATE_P (gen_tmpl))
9249 	      clone_function_decl (r, /*update_method_vec_p=*/0);
9250 	  }
9251 	else if ((complain & tf_error) != 0
9252 		 && IDENTIFIER_OPNAME_P (DECL_NAME (r))
9253 		 && !grok_op_properties (r, /*complain=*/true))
9254 	  RETURN (error_mark_node);
9255 
9256 	if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
9257 	  SET_DECL_FRIEND_CONTEXT (r,
9258 				   tsubst (DECL_FRIEND_CONTEXT (t),
9259 					    args, complain, in_decl));
9260 
9261 	/* Possibly limit visibility based on template args.  */
9262 	DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
9263 	if (DECL_VISIBILITY_SPECIFIED (t))
9264 	  {
9265 	    DECL_VISIBILITY_SPECIFIED (r) = 0;
9266 	    DECL_ATTRIBUTES (r)
9267 	      = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
9268 	  }
9269 	determine_visibility (r);
9270 	if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
9271 	    && !processing_template_decl)
9272 	  defaulted_late_check (r);
9273 
9274 	apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9275 					args, complain, in_decl);
9276       }
9277       break;
9278 
9279     case PARM_DECL:
9280       {
9281 	tree type = NULL_TREE;
9282         int i, len = 1;
9283         tree expanded_types = NULL_TREE;
9284         tree prev_r = NULL_TREE;
9285         tree first_r = NULL_TREE;
9286 
9287         if (FUNCTION_PARAMETER_PACK_P (t))
9288           {
9289             /* If there is a local specialization that isn't a
9290                parameter pack, it means that we're doing a "simple"
9291                substitution from inside tsubst_pack_expansion. Just
9292                return the local specialization (which will be a single
9293                parm).  */
9294             tree spec = retrieve_local_specialization (t);
9295             if (spec
9296                 && TREE_CODE (spec) == PARM_DECL
9297                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
9298               RETURN (spec);
9299 
9300             /* Expand the TYPE_PACK_EXPANSION that provides the types for
9301                the parameters in this function parameter pack.  */
9302             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
9303 						    complain, in_decl);
9304             if (TREE_CODE (expanded_types) == TREE_VEC)
9305               {
9306                 len = TREE_VEC_LENGTH (expanded_types);
9307 
9308                 /* Zero-length parameter packs are boring. Just substitute
9309                    into the chain.  */
9310                 if (len == 0)
9311                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
9312 				  TREE_CHAIN (t)));
9313               }
9314             else
9315               {
9316                 /* All we did was update the type. Make a note of that.  */
9317                 type = expanded_types;
9318                 expanded_types = NULL_TREE;
9319               }
9320           }
9321 
9322         /* Loop through all of the parameter's we'll build. When T is
9323            a function parameter pack, LEN is the number of expanded
9324            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
9325         r = NULL_TREE;
9326         for (i = 0; i < len; ++i)
9327           {
9328             prev_r = r;
9329             r = copy_node (t);
9330             if (DECL_TEMPLATE_PARM_P (t))
9331               SET_DECL_TEMPLATE_PARM_P (r);
9332 
9333 	    /* An argument of a function parameter pack is not a parameter
9334 	       pack.  */
9335 	    FUNCTION_PARAMETER_PACK_P (r) = false;
9336 
9337             if (expanded_types)
9338               /* We're on the Ith parameter of the function parameter
9339                  pack.  */
9340               {
9341                 /* Get the Ith type.  */
9342                 type = TREE_VEC_ELT (expanded_types, i);
9343 
9344                 if (DECL_NAME (r))
9345                   /* Rename the parameter to include the index.  */
9346                   DECL_NAME (r) =
9347                     make_ith_pack_parameter_name (DECL_NAME (r), i);
9348               }
9349             else if (!type)
9350               /* We're dealing with a normal parameter.  */
9351               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9352 
9353             type = type_decays_to (type);
9354             TREE_TYPE (r) = type;
9355             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9356 
9357             if (DECL_INITIAL (r))
9358               {
9359                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
9360                   DECL_INITIAL (r) = TREE_TYPE (r);
9361                 else
9362                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
9363                                              complain, in_decl);
9364               }
9365 
9366             DECL_CONTEXT (r) = NULL_TREE;
9367 
9368             if (!DECL_TEMPLATE_PARM_P (r))
9369               DECL_ARG_TYPE (r) = type_passed_as (type);
9370 
9371 	    apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9372 					    args, complain, in_decl);
9373 
9374             /* Keep track of the first new parameter we
9375                generate. That's what will be returned to the
9376                caller.  */
9377             if (!first_r)
9378               first_r = r;
9379 
9380             /* Build a proper chain of parameters when substituting
9381                into a function parameter pack.  */
9382             if (prev_r)
9383               TREE_CHAIN (prev_r) = r;
9384           }
9385 
9386 	if (TREE_CHAIN (t))
9387 	  TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args,
9388 				   complain, TREE_CHAIN (t));
9389 
9390         /* FIRST_R contains the start of the chain we've built.  */
9391         r = first_r;
9392       }
9393       break;
9394 
9395     case FIELD_DECL:
9396       {
9397 	tree type;
9398 
9399 	r = copy_decl (t);
9400 	type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9401 	if (type == error_mark_node)
9402 	  RETURN (error_mark_node);
9403 	TREE_TYPE (r) = type;
9404 	cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9405 
9406 	/* DECL_INITIAL gives the number of bits in a bit-field.  */
9407 	DECL_INITIAL (r)
9408 	  = tsubst_expr (DECL_INITIAL (t), args,
9409 			 complain, in_decl,
9410 			 /*integral_constant_expression_p=*/true);
9411 	/* We don't have to set DECL_CONTEXT here; it is set by
9412 	   finish_member_declaration.  */
9413 	TREE_CHAIN (r) = NULL_TREE;
9414 	if (VOID_TYPE_P (type))
9415 	  error ("instantiation of %q+D as type %qT", r, type);
9416 
9417 	apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9418 					args, complain, in_decl);
9419       }
9420       break;
9421 
9422     case USING_DECL:
9423       /* We reach here only for member using decls.  */
9424       if (DECL_DEPENDENT_P (t))
9425 	{
9426 	  r = do_class_using_decl
9427 	    (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
9428 	     tsubst_copy (DECL_NAME (t), args, complain, in_decl));
9429 	  if (!r)
9430 	    r = error_mark_node;
9431 	  else
9432 	    {
9433 	      TREE_PROTECTED (r) = TREE_PROTECTED (t);
9434 	      TREE_PRIVATE (r) = TREE_PRIVATE (t);
9435 	    }
9436 	}
9437       else
9438 	{
9439 	  r = copy_node (t);
9440 	  TREE_CHAIN (r) = NULL_TREE;
9441 	}
9442       break;
9443 
9444     case TYPE_DECL:
9445     case VAR_DECL:
9446       {
9447 	tree argvec = NULL_TREE;
9448 	tree gen_tmpl = NULL_TREE;
9449 	tree spec;
9450 	tree tmpl = NULL_TREE;
9451 	tree ctx;
9452 	tree type = NULL_TREE;
9453 	bool local_p;
9454 
9455 	if (TREE_CODE (t) == TYPE_DECL
9456 	    && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
9457 	  {
9458 	    /* If this is the canonical decl, we don't have to
9459 	       mess with instantiations, and often we can't (for
9460 	       typename, template type parms and such).  Note that
9461 	       TYPE_NAME is not correct for the above test if
9462 	       we've copied the type for a typedef.  */
9463 	    type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9464 	    if (type == error_mark_node)
9465 	      RETURN (error_mark_node);
9466 	    r = TYPE_NAME (type);
9467 	    break;
9468 	  }
9469 
9470 	/* Check to see if we already have the specialization we
9471 	   need.  */
9472 	spec = NULL_TREE;
9473 	if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
9474 	  {
9475 	    /* T is a static data member or namespace-scope entity.
9476 	       We have to substitute into namespace-scope variables
9477 	       (even though such entities are never templates) because
9478 	       of cases like:
9479 
9480 	         template <class T> void f() { extern T t; }
9481 
9482 	       where the entity referenced is not known until
9483 	       instantiation time.  */
9484 	    local_p = false;
9485 	    ctx = DECL_CONTEXT (t);
9486 	    if (DECL_CLASS_SCOPE_P (t))
9487 	      {
9488 		ctx = tsubst_aggr_type (ctx, args,
9489 					complain,
9490 					in_decl, /*entering_scope=*/1);
9491 		/* If CTX is unchanged, then T is in fact the
9492 		   specialization we want.  That situation occurs when
9493 		   referencing a static data member within in its own
9494 		   class.  We can use pointer equality, rather than
9495 		   same_type_p, because DECL_CONTEXT is always
9496 		   canonical.  */
9497 		if (ctx == DECL_CONTEXT (t))
9498 		  spec = t;
9499 	      }
9500 
9501 	    if (!spec)
9502 	      {
9503 		tmpl = DECL_TI_TEMPLATE (t);
9504 		gen_tmpl = most_general_template (tmpl);
9505 		argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
9506 		hash = hash_tmpl_and_args (gen_tmpl, argvec);
9507 		spec = retrieve_specialization (gen_tmpl, argvec, hash);
9508 	      }
9509 	  }
9510 	else
9511 	  {
9512 	    /* A local variable.  */
9513 	    local_p = true;
9514 	    /* Subsequent calls to pushdecl will fill this in.  */
9515 	    ctx = NULL_TREE;
9516 	    spec = retrieve_local_specialization (t);
9517 	  }
9518 	/* If we already have the specialization we need, there is
9519 	   nothing more to do.  */
9520 	if (spec)
9521 	  {
9522 	    r = spec;
9523 	    break;
9524 	  }
9525 
9526 	/* Create a new node for the specialization we need.  */
9527 	r = copy_decl (t);
9528 	if (type == NULL_TREE)
9529 	  {
9530 	    if (is_typedef_decl (t))
9531 	      type = DECL_ORIGINAL_TYPE (t);
9532 	    else
9533 	      type = TREE_TYPE (t);
9534 	    type = tsubst (type, args, complain, in_decl);
9535 	  }
9536 	if (TREE_CODE (r) == VAR_DECL)
9537 	  {
9538 	    /* Even if the original location is out of scope, the
9539 	       newly substituted one is not.  */
9540 	    DECL_DEAD_FOR_LOCAL (r) = 0;
9541 	    DECL_INITIALIZED_P (r) = 0;
9542 	    DECL_TEMPLATE_INSTANTIATED (r) = 0;
9543 	    if (type == error_mark_node)
9544 	      RETURN (error_mark_node);
9545 	    if (TREE_CODE (type) == FUNCTION_TYPE)
9546 	      {
9547 		/* It may seem that this case cannot occur, since:
9548 
9549 		     typedef void f();
9550 		     void g() { f x; }
9551 
9552 		   declares a function, not a variable.  However:
9553 
9554 		     typedef void f();
9555 		     template <typename T> void g() { T t; }
9556 		     template void g<f>();
9557 
9558 		   is an attempt to declare a variable with function
9559 		   type.  */
9560 		error ("variable %qD has function type",
9561 		       /* R is not yet sufficiently initialized, so we
9562 			  just use its name.  */
9563 		       DECL_NAME (r));
9564 		RETURN (error_mark_node);
9565 	      }
9566 	    type = complete_type (type);
9567 	    DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
9568 	      = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t);
9569 	    type = check_var_type (DECL_NAME (r), type);
9570 
9571 	    if (DECL_HAS_VALUE_EXPR_P (t))
9572 	      {
9573 		tree ve = DECL_VALUE_EXPR (t);
9574 		ve = tsubst_expr (ve, args, complain, in_decl,
9575 				  /*constant_expression_p=*/false);
9576 		SET_DECL_VALUE_EXPR (r, ve);
9577 	      }
9578 	  }
9579 	else if (DECL_SELF_REFERENCE_P (t))
9580 	  SET_DECL_SELF_REFERENCE_P (r);
9581 	TREE_TYPE (r) = type;
9582 	cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9583 	DECL_CONTEXT (r) = ctx;
9584 	/* Clear out the mangled name and RTL for the instantiation.  */
9585 	SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9586 	if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9587 	  SET_DECL_RTL (r, NULL_RTX);
9588 	/* The initializer must not be expanded until it is required;
9589 	   see [temp.inst].  */
9590 	DECL_INITIAL (r) = NULL_TREE;
9591 	if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9592 	  SET_DECL_RTL (r, NULL_RTX);
9593 	DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
9594 	if (TREE_CODE (r) == VAR_DECL)
9595 	  {
9596 	    /* Possibly limit visibility based on template args.  */
9597 	    DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
9598 	    if (DECL_VISIBILITY_SPECIFIED (t))
9599 	      {
9600 		DECL_VISIBILITY_SPECIFIED (r) = 0;
9601 		DECL_ATTRIBUTES (r)
9602 		  = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
9603 	      }
9604 	    determine_visibility (r);
9605 	  }
9606 
9607 	if (!local_p)
9608 	  {
9609 	    /* A static data member declaration is always marked
9610 	       external when it is declared in-class, even if an
9611 	       initializer is present.  We mimic the non-template
9612 	       processing here.  */
9613 	    DECL_EXTERNAL (r) = 1;
9614 
9615 	    register_specialization (r, gen_tmpl, argvec, false, hash);
9616 	    DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
9617 	    SET_DECL_IMPLICIT_INSTANTIATION (r);
9618 	  }
9619 	else if (cp_unevaluated_operand)
9620 	  {
9621 	    /* We're substituting this var in a decltype outside of its
9622 	       scope, such as for a lambda return type.  Don't add it to
9623 	       local_specializations, do perform auto deduction.  */
9624 	    tree auto_node = type_uses_auto (type);
9625 	    tree init
9626 	      = tsubst_expr (DECL_INITIAL (t), args, complain, in_decl,
9627 			     /*constant_expression_p=*/false);
9628 
9629 	    if (auto_node && init && describable_type (init))
9630 	      {
9631 		type = do_auto_deduction (type, init, auto_node);
9632 		TREE_TYPE (r) = type;
9633 	      }
9634 	  }
9635 	else
9636 	  register_local_specialization (r, t);
9637 
9638 	TREE_CHAIN (r) = NULL_TREE;
9639 
9640 	apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
9641 					/*flags=*/0,
9642 					args, complain, in_decl);
9643 
9644 	/* Preserve a typedef that names a type.  */
9645 	if (is_typedef_decl (r))
9646 	  {
9647 	    DECL_ORIGINAL_TYPE (r) = NULL_TREE;
9648 	    set_underlying_type (r);
9649 	  }
9650 
9651 	layout_decl (r, 0);
9652       }
9653       break;
9654 
9655     default:
9656       gcc_unreachable ();
9657     }
9658 #undef RETURN
9659 
9660  out:
9661   /* Restore the file and line information.  */
9662   input_location = saved_loc;
9663 
9664   return r;
9665 }
9666 
9667 /* Substitute into the ARG_TYPES of a function type.  */
9668 
9669 static tree
9670 tsubst_arg_types (tree arg_types,
9671 		  tree args,
9672 		  tsubst_flags_t complain,
9673 		  tree in_decl)
9674 {
9675   tree remaining_arg_types;
9676   tree type = NULL_TREE;
9677   int i = 1;
9678   tree expanded_args = NULL_TREE;
9679   tree default_arg;
9680 
9681   if (!arg_types || arg_types == void_list_node)
9682     return arg_types;
9683 
9684   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
9685 					  args, complain, in_decl);
9686   if (remaining_arg_types == error_mark_node)
9687     return error_mark_node;
9688 
9689   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
9690     {
9691       /* For a pack expansion, perform substitution on the
9692          entire expression. Later on, we'll handle the arguments
9693          one-by-one.  */
9694       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
9695                                             args, complain, in_decl);
9696 
9697       if (TREE_CODE (expanded_args) == TREE_VEC)
9698         /* So that we'll spin through the parameters, one by one.  */
9699         i = TREE_VEC_LENGTH (expanded_args);
9700       else
9701         {
9702           /* We only partially substituted into the parameter
9703              pack. Our type is TYPE_PACK_EXPANSION.  */
9704           type = expanded_args;
9705           expanded_args = NULL_TREE;
9706         }
9707     }
9708 
9709   while (i > 0) {
9710     --i;
9711 
9712     if (expanded_args)
9713       type = TREE_VEC_ELT (expanded_args, i);
9714     else if (!type)
9715       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
9716 
9717     if (type == error_mark_node)
9718       return error_mark_node;
9719     if (VOID_TYPE_P (type))
9720       {
9721         if (complain & tf_error)
9722           {
9723             error ("invalid parameter type %qT", type);
9724             if (in_decl)
9725               error ("in declaration %q+D", in_decl);
9726           }
9727         return error_mark_node;
9728     }
9729 
9730     /* Do array-to-pointer, function-to-pointer conversion, and ignore
9731        top-level qualifiers as required.  */
9732     type = TYPE_MAIN_VARIANT (type_decays_to (type));
9733 
9734     /* We do not substitute into default arguments here.  The standard
9735        mandates that they be instantiated only when needed, which is
9736        done in build_over_call.  */
9737     default_arg = TREE_PURPOSE (arg_types);
9738 
9739     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
9740       {
9741         /* We've instantiated a template before its default arguments
9742            have been parsed.  This can happen for a nested template
9743            class, and is not an error unless we require the default
9744            argument in a call of this function.  */
9745         remaining_arg_types =
9746           tree_cons (default_arg, type, remaining_arg_types);
9747         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg),
9748                        remaining_arg_types);
9749       }
9750     else
9751       remaining_arg_types =
9752         hash_tree_cons (default_arg, type, remaining_arg_types);
9753   }
9754 
9755   return remaining_arg_types;
9756 }
9757 
9758 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
9759    *not* handle the exception-specification for FNTYPE, because the
9760    initial substitution of explicitly provided template parameters
9761    during argument deduction forbids substitution into the
9762    exception-specification:
9763 
9764      [temp.deduct]
9765 
9766      All references in the function type of the function template to  the
9767      corresponding template parameters are replaced by the specified tem-
9768      plate argument values.  If a substitution in a template parameter or
9769      in  the function type of the function template results in an invalid
9770      type, type deduction fails.  [Note: The equivalent  substitution  in
9771      exception specifications is done only when the function is instanti-
9772      ated, at which point a program is  ill-formed  if  the  substitution
9773      results in an invalid type.]  */
9774 
9775 static tree
9776 tsubst_function_type (tree t,
9777 		      tree args,
9778 		      tsubst_flags_t complain,
9779 		      tree in_decl)
9780 {
9781   tree return_type;
9782   tree arg_types;
9783   tree fntype;
9784 
9785   /* The TYPE_CONTEXT is not used for function/method types.  */
9786   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
9787 
9788   /* Substitute the return type.  */
9789   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9790   if (return_type == error_mark_node)
9791     return error_mark_node;
9792   /* The standard does not presently indicate that creation of a
9793      function type with an invalid return type is a deduction failure.
9794      However, that is clearly analogous to creating an array of "void"
9795      or a reference to a reference.  This is core issue #486.  */
9796   if (TREE_CODE (return_type) == ARRAY_TYPE
9797       || TREE_CODE (return_type) == FUNCTION_TYPE)
9798     {
9799       if (complain & tf_error)
9800 	{
9801 	  if (TREE_CODE (return_type) == ARRAY_TYPE)
9802 	    error ("function returning an array");
9803 	  else
9804 	    error ("function returning a function");
9805 	}
9806       return error_mark_node;
9807     }
9808 
9809   /* Substitute the argument types.  */
9810   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
9811 				complain, in_decl);
9812   if (arg_types == error_mark_node)
9813     return error_mark_node;
9814 
9815   /* Construct a new type node and return it.  */
9816   if (TREE_CODE (t) == FUNCTION_TYPE)
9817     fntype = build_function_type (return_type, arg_types);
9818   else
9819     {
9820       tree r = TREE_TYPE (TREE_VALUE (arg_types));
9821       if (! MAYBE_CLASS_TYPE_P (r))
9822 	{
9823 	  /* [temp.deduct]
9824 
9825 	     Type deduction may fail for any of the following
9826 	     reasons:
9827 
9828 	     -- Attempting to create "pointer to member of T" when T
9829 	     is not a class type.  */
9830 	  if (complain & tf_error)
9831 	    error ("creating pointer to member function of non-class type %qT",
9832 		      r);
9833 	  return error_mark_node;
9834 	}
9835 
9836       fntype = build_method_type_directly (r, return_type,
9837 					   TREE_CHAIN (arg_types));
9838     }
9839   fntype = cp_build_qualified_type_real (fntype, TYPE_QUALS (t), complain);
9840   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
9841 
9842   return fntype;
9843 }
9844 
9845 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
9846    ARGS into that specification, and return the substituted
9847    specification.  If there is no specification, return NULL_TREE.  */
9848 
9849 static tree
9850 tsubst_exception_specification (tree fntype,
9851 				tree args,
9852 				tsubst_flags_t complain,
9853 				tree in_decl)
9854 {
9855   tree specs;
9856   tree new_specs;
9857 
9858   specs = TYPE_RAISES_EXCEPTIONS (fntype);
9859   new_specs = NULL_TREE;
9860   if (specs)
9861     {
9862       if (! TREE_VALUE (specs))
9863 	new_specs = specs;
9864       else
9865 	while (specs)
9866 	  {
9867 	    tree spec;
9868             int i, len = 1;
9869             tree expanded_specs = NULL_TREE;
9870 
9871             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
9872               {
9873                 /* Expand the pack expansion type.  */
9874                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
9875                                                        args, complain,
9876                                                        in_decl);
9877 
9878 		if (expanded_specs == error_mark_node)
9879 		  return error_mark_node;
9880 		else if (TREE_CODE (expanded_specs) == TREE_VEC)
9881 		  len = TREE_VEC_LENGTH (expanded_specs);
9882 		else
9883 		  {
9884 		    /* We're substituting into a member template, so
9885 		       we got a TYPE_PACK_EXPANSION back.  Add that
9886 		       expansion and move on.  */
9887 		    gcc_assert (TREE_CODE (expanded_specs)
9888 				== TYPE_PACK_EXPANSION);
9889 		    new_specs = add_exception_specifier (new_specs,
9890 							 expanded_specs,
9891 							 complain);
9892 		    specs = TREE_CHAIN (specs);
9893 		    continue;
9894 		  }
9895               }
9896 
9897             for (i = 0; i < len; ++i)
9898               {
9899                 if (expanded_specs)
9900                   spec = TREE_VEC_ELT (expanded_specs, i);
9901                 else
9902                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
9903                 if (spec == error_mark_node)
9904                   return spec;
9905                 new_specs = add_exception_specifier (new_specs, spec,
9906                                                      complain);
9907               }
9908 
9909             specs = TREE_CHAIN (specs);
9910 	  }
9911     }
9912   return new_specs;
9913 }
9914 
9915 /* Take the tree structure T and replace template parameters used
9916    therein with the argument vector ARGS.  IN_DECL is an associated
9917    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
9918    Issue error and warning messages under control of COMPLAIN.  Note
9919    that we must be relatively non-tolerant of extensions here, in
9920    order to preserve conformance; if we allow substitutions that
9921    should not be allowed, we may allow argument deductions that should
9922    not succeed, and therefore report ambiguous overload situations
9923    where there are none.  In theory, we could allow the substitution,
9924    but indicate that it should have failed, and allow our caller to
9925    make sure that the right thing happens, but we don't try to do this
9926    yet.
9927 
9928    This function is used for dealing with types, decls and the like;
9929    for expressions, use tsubst_expr or tsubst_copy.  */
9930 
9931 tree
9932 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9933 {
9934   tree type, r;
9935 
9936   if (t == NULL_TREE || t == error_mark_node
9937       || t == integer_type_node
9938       || t == void_type_node
9939       || t == char_type_node
9940       || t == unknown_type_node
9941       || TREE_CODE (t) == NAMESPACE_DECL)
9942     return t;
9943 
9944   if (DECL_P (t))
9945     return tsubst_decl (t, args, complain);
9946 
9947   if (args == NULL_TREE)
9948     return t;
9949 
9950   if (TREE_CODE (t) == IDENTIFIER_NODE)
9951     type = IDENTIFIER_TYPE_VALUE (t);
9952   else
9953     type = TREE_TYPE (t);
9954 
9955   gcc_assert (type != unknown_type_node);
9956 
9957   /* Reuse typedefs.  We need to do this to handle dependent attributes,
9958      such as attribute aligned.  */
9959   if (TYPE_P (t)
9960       && TYPE_NAME (t)
9961       && TYPE_NAME (t) != TYPE_MAIN_DECL (t))
9962     {
9963       tree decl = TYPE_NAME (t);
9964 
9965       if (DECL_CLASS_SCOPE_P (decl)
9966 	  && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
9967 	  && uses_template_parms (DECL_CONTEXT (decl)))
9968 	{
9969 	  tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
9970 	  tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
9971 	  r = retrieve_specialization (tmpl, gen_args, 0);
9972 	}
9973       else if (DECL_FUNCTION_SCOPE_P (decl)
9974 	       && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
9975 	       && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
9976 	r = retrieve_local_specialization (decl);
9977       else
9978 	/* The typedef is from a non-template context.  */
9979 	return t;
9980 
9981       if (r)
9982 	{
9983 	  r = TREE_TYPE (r);
9984 	  r = cp_build_qualified_type_real
9985 	    (r, cp_type_quals (t) | cp_type_quals (r),
9986 	     complain | tf_ignore_bad_quals);
9987 	  return r;
9988 	}
9989       /* Else we must be instantiating the typedef, so fall through.  */
9990     }
9991 
9992   if (type
9993       && TREE_CODE (t) != TYPENAME_TYPE
9994       && TREE_CODE (t) != TEMPLATE_TYPE_PARM
9995       && TREE_CODE (t) != IDENTIFIER_NODE
9996       && TREE_CODE (t) != FUNCTION_TYPE
9997       && TREE_CODE (t) != METHOD_TYPE)
9998     type = tsubst (type, args, complain, in_decl);
9999   if (type == error_mark_node)
10000     return error_mark_node;
10001 
10002   switch (TREE_CODE (t))
10003     {
10004     case RECORD_TYPE:
10005     case UNION_TYPE:
10006     case ENUMERAL_TYPE:
10007       return tsubst_aggr_type (t, args, complain, in_decl,
10008 			       /*entering_scope=*/0);
10009 
10010     case ERROR_MARK:
10011     case IDENTIFIER_NODE:
10012     case VOID_TYPE:
10013     case REAL_TYPE:
10014     case COMPLEX_TYPE:
10015     case VECTOR_TYPE:
10016     case BOOLEAN_TYPE:
10017     case INTEGER_CST:
10018     case REAL_CST:
10019     case STRING_CST:
10020       return t;
10021 
10022     case INTEGER_TYPE:
10023       if (t == integer_type_node)
10024 	return t;
10025 
10026       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
10027 	  && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
10028 	return t;
10029 
10030       {
10031 	tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
10032 
10033 	max = tsubst_expr (omax, args, complain, in_decl,
10034 			   /*integral_constant_expression_p=*/false);
10035 
10036 	/* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
10037 	   needed.  */
10038 	if (TREE_CODE (max) == NOP_EXPR
10039 	    && TREE_SIDE_EFFECTS (omax)
10040 	    && !TREE_TYPE (max))
10041 	  TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
10042 
10043 	max = fold_decl_constant_value (max);
10044 
10045 	/* If we're in a partial instantiation, preserve the magic NOP_EXPR
10046 	   with TREE_SIDE_EFFECTS that indicates this is not an integral
10047 	   constant expression.  */
10048 	if (processing_template_decl
10049 	    && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
10050 	  {
10051 	    gcc_assert (TREE_CODE (max) == NOP_EXPR);
10052 	    TREE_SIDE_EFFECTS (max) = 1;
10053 	  }
10054 
10055 	if (TREE_CODE (max) != INTEGER_CST
10056 	    && !at_function_scope_p ()
10057 	    && !TREE_SIDE_EFFECTS (max)
10058 	    && !value_dependent_expression_p (max))
10059 	  {
10060 	    if (complain & tf_error)
10061 	      error ("array bound is not an integer constant");
10062 	    return error_mark_node;
10063 	  }
10064 
10065 	/* [temp.deduct]
10066 
10067 	   Type deduction may fail for any of the following
10068 	   reasons:
10069 
10070 	     Attempting to create an array with a size that is
10071 	     zero or negative.  */
10072 	if (integer_zerop (max) && !(complain & tf_error))
10073 	  /* We must fail if performing argument deduction (as
10074 	     indicated by the state of complain), so that
10075 	     another substitution can be found.  */
10076 	  return error_mark_node;
10077 	else if (TREE_CODE (max) == INTEGER_CST
10078 		 && INT_CST_LT (max, integer_zero_node))
10079 	  {
10080 	    if (complain & tf_error)
10081 	      error ("creating array with negative size (%qE)", max);
10082 
10083 	    return error_mark_node;
10084 	  }
10085 
10086 	return compute_array_index_type (NULL_TREE, max);
10087       }
10088 
10089     case TEMPLATE_TYPE_PARM:
10090     case TEMPLATE_TEMPLATE_PARM:
10091     case BOUND_TEMPLATE_TEMPLATE_PARM:
10092     case TEMPLATE_PARM_INDEX:
10093       {
10094 	int idx;
10095 	int level;
10096 	int levels;
10097 	tree arg = NULL_TREE;
10098 
10099 	r = NULL_TREE;
10100 
10101 	gcc_assert (TREE_VEC_LENGTH (args) > 0);
10102 	template_parm_level_and_index (t, &level, &idx);
10103 
10104 	levels = TMPL_ARGS_DEPTH (args);
10105 	if (level <= levels)
10106 	  {
10107 	    arg = TMPL_ARG (args, level, idx);
10108 
10109 	    if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
10110 	      /* See through ARGUMENT_PACK_SELECT arguments. */
10111 	      arg = ARGUMENT_PACK_SELECT_ARG (arg);
10112 	  }
10113 
10114 	if (arg == error_mark_node)
10115 	  return error_mark_node;
10116 	else if (arg != NULL_TREE)
10117 	  {
10118 	    if (ARGUMENT_PACK_P (arg))
10119 	      /* If ARG is an argument pack, we don't actually want to
10120 		 perform a substitution here, because substitutions
10121 		 for argument packs are only done
10122 		 element-by-element. We can get to this point when
10123 		 substituting the type of a non-type template
10124 		 parameter pack, when that type actually contains
10125 		 template parameter packs from an outer template, e.g.,
10126 
10127 	         template<typename... Types> struct A {
10128 		   template<Types... Values> struct B { };
10129                  };  */
10130 	      return t;
10131 
10132 	    if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
10133 	      {
10134 		int quals;
10135 		gcc_assert (TYPE_P (arg));
10136 
10137 		/* cv-quals from the template are discarded when
10138 		   substituting in a function or reference type.  */
10139 		if (TREE_CODE (arg) == FUNCTION_TYPE
10140 		    || TREE_CODE (arg) == METHOD_TYPE
10141 		    || TREE_CODE (arg) == REFERENCE_TYPE)
10142 		  quals = cp_type_quals (arg);
10143 		else
10144 		  quals = cp_type_quals (arg) | cp_type_quals (t);
10145 
10146 		return cp_build_qualified_type_real
10147 		  (arg, quals, complain | tf_ignore_bad_quals);
10148 	      }
10149 	    else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
10150 	      {
10151 		/* We are processing a type constructed from a
10152 		   template template parameter.  */
10153 		tree argvec = tsubst (TYPE_TI_ARGS (t),
10154 				      args, complain, in_decl);
10155 		if (argvec == error_mark_node)
10156 		  return error_mark_node;
10157 
10158 		/* We can get a TEMPLATE_TEMPLATE_PARM here when we
10159 		   are resolving nested-types in the signature of a
10160 		   member function templates.  Otherwise ARG is a
10161 		   TEMPLATE_DECL and is the real template to be
10162 		   instantiated.  */
10163 		if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
10164 		  arg = TYPE_NAME (arg);
10165 
10166 		r = lookup_template_class (arg,
10167 					   argvec, in_decl,
10168 					   DECL_CONTEXT (arg),
10169 					    /*entering_scope=*/0,
10170 					   complain);
10171 		return cp_build_qualified_type_real
10172 		  (r, TYPE_QUALS (t), complain);
10173 	      }
10174 	    else
10175 	      /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
10176 	      return arg;
10177 	  }
10178 
10179 	if (level == 1)
10180 	  /* This can happen during the attempted tsubst'ing in
10181 	     unify.  This means that we don't yet have any information
10182 	     about the template parameter in question.  */
10183 	  return t;
10184 
10185 	/* If we get here, we must have been looking at a parm for a
10186 	   more deeply nested template.  Make a new version of this
10187 	   template parameter, but with a lower level.  */
10188 	switch (TREE_CODE (t))
10189 	  {
10190 	  case TEMPLATE_TYPE_PARM:
10191 	  case TEMPLATE_TEMPLATE_PARM:
10192 	  case BOUND_TEMPLATE_TEMPLATE_PARM:
10193 	    if (cp_type_quals (t))
10194 	      {
10195 		r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
10196 		r = cp_build_qualified_type_real
10197 		  (r, cp_type_quals (t),
10198 		   complain | (TREE_CODE (t) == TEMPLATE_TYPE_PARM
10199 			       ? tf_ignore_bad_quals : 0));
10200 	      }
10201 	    else
10202 	      {
10203 		r = copy_type (t);
10204 		TEMPLATE_TYPE_PARM_INDEX (r)
10205 		  = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
10206 						r, levels, args, complain);
10207 		TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
10208 		TYPE_MAIN_VARIANT (r) = r;
10209 		TYPE_POINTER_TO (r) = NULL_TREE;
10210 		TYPE_REFERENCE_TO (r) = NULL_TREE;
10211 
10212 		if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
10213 		  /* We have reduced the level of the template
10214 		     template parameter, but not the levels of its
10215 		     template parameters, so canonical_type_parameter
10216 		     will not be able to find the canonical template
10217 		     template parameter for this level. Thus, we
10218 		     require structural equality checking to compare
10219 		     TEMPLATE_TEMPLATE_PARMs. */
10220 		  SET_TYPE_STRUCTURAL_EQUALITY (r);
10221 		else if (TYPE_STRUCTURAL_EQUALITY_P (t))
10222 		  SET_TYPE_STRUCTURAL_EQUALITY (r);
10223 		else
10224 		  TYPE_CANONICAL (r) = canonical_type_parameter (r);
10225 
10226 		if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
10227 		  {
10228 		    tree argvec = tsubst (TYPE_TI_ARGS (t), args,
10229 					  complain, in_decl);
10230 		    if (argvec == error_mark_node)
10231 		      return error_mark_node;
10232 
10233 		    TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
10234 		      = build_template_info (TYPE_TI_TEMPLATE (t), argvec);
10235 		  }
10236 	      }
10237 	    break;
10238 
10239 	  case TEMPLATE_PARM_INDEX:
10240 	    r = reduce_template_parm_level (t, type, levels, args, complain);
10241 	    break;
10242 
10243 	  default:
10244 	    gcc_unreachable ();
10245 	  }
10246 
10247 	return r;
10248       }
10249 
10250     case TREE_LIST:
10251       {
10252 	tree purpose, value, chain;
10253 
10254 	if (t == void_list_node)
10255 	  return t;
10256 
10257 	purpose = TREE_PURPOSE (t);
10258 	if (purpose)
10259 	  {
10260 	    purpose = tsubst (purpose, args, complain, in_decl);
10261 	    if (purpose == error_mark_node)
10262 	      return error_mark_node;
10263 	  }
10264 	value = TREE_VALUE (t);
10265 	if (value)
10266 	  {
10267 	    value = tsubst (value, args, complain, in_decl);
10268 	    if (value == error_mark_node)
10269 	      return error_mark_node;
10270 	  }
10271 	chain = TREE_CHAIN (t);
10272 	if (chain && chain != void_type_node)
10273 	  {
10274 	    chain = tsubst (chain, args, complain, in_decl);
10275 	    if (chain == error_mark_node)
10276 	      return error_mark_node;
10277 	  }
10278 	if (purpose == TREE_PURPOSE (t)
10279 	    && value == TREE_VALUE (t)
10280 	    && chain == TREE_CHAIN (t))
10281 	  return t;
10282 	return hash_tree_cons (purpose, value, chain);
10283       }
10284 
10285     case TREE_BINFO:
10286       /* We should never be tsubsting a binfo.  */
10287       gcc_unreachable ();
10288 
10289     case TREE_VEC:
10290       /* A vector of template arguments.  */
10291       gcc_assert (!type);
10292       return tsubst_template_args (t, args, complain, in_decl);
10293 
10294     case POINTER_TYPE:
10295     case REFERENCE_TYPE:
10296       {
10297 	enum tree_code code;
10298 
10299 	if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
10300 	  return t;
10301 
10302 	code = TREE_CODE (t);
10303 
10304 
10305 	/* [temp.deduct]
10306 
10307 	   Type deduction may fail for any of the following
10308 	   reasons:
10309 
10310 	   -- Attempting to create a pointer to reference type.
10311 	   -- Attempting to create a reference to a reference type or
10312 	      a reference to void.
10313 
10314 	  Core issue 106 says that creating a reference to a reference
10315 	  during instantiation is no longer a cause for failure. We
10316 	  only enforce this check in strict C++98 mode.  */
10317 	if ((TREE_CODE (type) == REFERENCE_TYPE
10318 	     && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
10319 	    || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
10320 	  {
10321 	    static location_t last_loc;
10322 
10323 	    /* We keep track of the last time we issued this error
10324 	       message to avoid spewing a ton of messages during a
10325 	       single bad template instantiation.  */
10326 	    if (complain & tf_error
10327 		&& last_loc != input_location)
10328 	      {
10329 		if (TREE_CODE (type) == VOID_TYPE)
10330 		  error ("forming reference to void");
10331                else if (code == POINTER_TYPE)
10332                  error ("forming pointer to reference type %qT", type);
10333                else
10334 		  error ("forming reference to reference type %qT", type);
10335 		last_loc = input_location;
10336 	      }
10337 
10338 	    return error_mark_node;
10339 	  }
10340 	else if (code == POINTER_TYPE)
10341 	  {
10342 	    r = build_pointer_type (type);
10343 	    if (TREE_CODE (type) == METHOD_TYPE)
10344 	      r = build_ptrmemfunc_type (r);
10345 	  }
10346 	else if (TREE_CODE (type) == REFERENCE_TYPE)
10347 	  /* In C++0x, during template argument substitution, when there is an
10348 	     attempt to create a reference to a reference type, reference
10349 	     collapsing is applied as described in [14.3.1/4 temp.arg.type]:
10350 
10351 	     "If a template-argument for a template-parameter T names a type
10352 	     that is a reference to a type A, an attempt to create the type
10353 	     'lvalue reference to cv T' creates the type 'lvalue reference to
10354 	     A,' while an attempt to create the type type rvalue reference to
10355 	     cv T' creates the type T"
10356 	  */
10357 	  r = cp_build_reference_type
10358 	      (TREE_TYPE (type),
10359 	       TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
10360 	else
10361 	  r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
10362 	r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
10363 
10364 	if (r != error_mark_node)
10365 	  /* Will this ever be needed for TYPE_..._TO values?  */
10366 	  layout_type (r);
10367 
10368 	return r;
10369       }
10370     case OFFSET_TYPE:
10371       {
10372 	r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
10373 	if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
10374 	  {
10375 	    /* [temp.deduct]
10376 
10377 	       Type deduction may fail for any of the following
10378 	       reasons:
10379 
10380 	       -- Attempting to create "pointer to member of T" when T
10381 		  is not a class type.  */
10382 	    if (complain & tf_error)
10383 	      error ("creating pointer to member of non-class type %qT", r);
10384 	    return error_mark_node;
10385 	  }
10386 	if (TREE_CODE (type) == REFERENCE_TYPE)
10387 	  {
10388 	    if (complain & tf_error)
10389 	      error ("creating pointer to member reference type %qT", type);
10390 	    return error_mark_node;
10391 	  }
10392 	if (TREE_CODE (type) == VOID_TYPE)
10393 	  {
10394 	    if (complain & tf_error)
10395 	      error ("creating pointer to member of type void");
10396 	    return error_mark_node;
10397 	  }
10398 	gcc_assert (TREE_CODE (type) != METHOD_TYPE);
10399 	if (TREE_CODE (type) == FUNCTION_TYPE)
10400 	  {
10401 	    /* The type of the implicit object parameter gets its
10402 	       cv-qualifiers from the FUNCTION_TYPE. */
10403 	    tree memptr;
10404 	    tree method_type = build_memfn_type (type, r, cp_type_quals (type));
10405 	    memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
10406 	    return cp_build_qualified_type_real (memptr, cp_type_quals (t),
10407 						 complain);
10408 	  }
10409 	else
10410 	  return cp_build_qualified_type_real (build_ptrmem_type (r, type),
10411 					       TYPE_QUALS (t),
10412 					       complain);
10413       }
10414     case FUNCTION_TYPE:
10415     case METHOD_TYPE:
10416       {
10417 	tree fntype;
10418 	tree specs;
10419 	fntype = tsubst_function_type (t, args, complain, in_decl);
10420 	if (fntype == error_mark_node)
10421 	  return error_mark_node;
10422 
10423 	/* Substitute the exception specification.  */
10424 	specs = tsubst_exception_specification (t, args, complain,
10425 						in_decl);
10426 	if (specs == error_mark_node)
10427 	  return error_mark_node;
10428 	if (specs)
10429 	  fntype = build_exception_variant (fntype, specs);
10430 	return fntype;
10431       }
10432     case ARRAY_TYPE:
10433       {
10434 	tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
10435 	if (domain == error_mark_node)
10436 	  return error_mark_node;
10437 
10438 	/* As an optimization, we avoid regenerating the array type if
10439 	   it will obviously be the same as T.  */
10440 	if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
10441 	  return t;
10442 
10443 	/* These checks should match the ones in grokdeclarator.
10444 
10445 	   [temp.deduct]
10446 
10447 	   The deduction may fail for any of the following reasons:
10448 
10449 	   -- Attempting to create an array with an element type that
10450 	      is void, a function type, or a reference type, or [DR337]
10451 	      an abstract class type.  */
10452 	if (TREE_CODE (type) == VOID_TYPE
10453 	    || TREE_CODE (type) == FUNCTION_TYPE
10454 	    || TREE_CODE (type) == REFERENCE_TYPE)
10455 	  {
10456 	    if (complain & tf_error)
10457 	      error ("creating array of %qT", type);
10458 	    return error_mark_node;
10459 	  }
10460 	if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
10461 	  {
10462 	    if (complain & tf_error)
10463 	      error ("creating array of %qT, which is an abstract class type",
10464 		     type);
10465 	    return error_mark_node;
10466 	  }
10467 
10468 	r = build_cplus_array_type (type, domain);
10469 
10470 	if (TYPE_USER_ALIGN (t))
10471 	  {
10472 	    TYPE_ALIGN (r) = TYPE_ALIGN (t);
10473 	    TYPE_USER_ALIGN (r) = 1;
10474 	  }
10475 
10476 	return r;
10477       }
10478 
10479     case PLUS_EXPR:
10480     case MINUS_EXPR:
10481       {
10482 	tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10483 	tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
10484 
10485 	if (e1 == error_mark_node || e2 == error_mark_node)
10486 	  return error_mark_node;
10487 
10488 	return fold_build2_loc (input_location,
10489 			    TREE_CODE (t), TREE_TYPE (t), e1, e2);
10490       }
10491 
10492     case NEGATE_EXPR:
10493     case NOP_EXPR:
10494       {
10495 	tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10496 	if (e == error_mark_node)
10497 	  return error_mark_node;
10498 
10499 	return fold_build1_loc (input_location, TREE_CODE (t), TREE_TYPE (t), e);
10500       }
10501 
10502     case TYPENAME_TYPE:
10503       {
10504 	tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10505 				     in_decl, /*entering_scope=*/1);
10506 	tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
10507 			      complain, in_decl);
10508 	int quals;
10509 
10510 	if (ctx == error_mark_node || f == error_mark_node)
10511 	  return error_mark_node;
10512 
10513 	if (!MAYBE_CLASS_TYPE_P (ctx))
10514 	  {
10515 	    if (complain & tf_error)
10516 	      error ("%qT is not a class, struct, or union type", ctx);
10517 	    return error_mark_node;
10518 	  }
10519 	else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
10520 	  {
10521 	    /* Normally, make_typename_type does not require that the CTX
10522 	       have complete type in order to allow things like:
10523 
10524 		 template <class T> struct S { typename S<T>::X Y; };
10525 
10526 	       But, such constructs have already been resolved by this
10527 	       point, so here CTX really should have complete type, unless
10528 	       it's a partial instantiation.  */
10529 	    if (!(complain & tf_no_class_instantiations))
10530 	      ctx = complete_type (ctx);
10531 	    if (!COMPLETE_TYPE_P (ctx))
10532 	      {
10533 		if (complain & tf_error)
10534 		  cxx_incomplete_type_error (NULL_TREE, ctx);
10535 		return error_mark_node;
10536 	      }
10537 	  }
10538 
10539 	f = make_typename_type (ctx, f, typename_type,
10540 				(complain & tf_error) | tf_keep_type_decl);
10541 	if (f == error_mark_node)
10542 	  return f;
10543 	if (TREE_CODE (f) == TYPE_DECL)
10544 	  {
10545 	    complain |= tf_ignore_bad_quals;
10546 	    f = TREE_TYPE (f);
10547 	  }
10548 
10549 	if (TREE_CODE (f) != TYPENAME_TYPE)
10550 	  {
10551 	    if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
10552 	      {
10553 		if (complain & tf_error)
10554 		  error ("%qT resolves to %qT, which is not an enumeration type",
10555 			 t, f);
10556 		else
10557 		  return error_mark_node;
10558 	      }
10559 	    else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
10560 	      {
10561 		if (complain & tf_error)
10562 		  error ("%qT resolves to %qT, which is is not a class type",
10563 			 t, f);
10564 		else
10565 		  return error_mark_node;
10566 	      }
10567 	  }
10568 
10569 	/* cv-quals from the template are discarded when
10570 	   substituting in a function or reference type.  */
10571 	if (TREE_CODE (f) == FUNCTION_TYPE
10572 	    || TREE_CODE (f) == METHOD_TYPE
10573 	    || TREE_CODE (f) == REFERENCE_TYPE)
10574 	  quals = cp_type_quals (f);
10575 	else
10576 	  quals = cp_type_quals (f) | cp_type_quals (t);
10577 	return cp_build_qualified_type_real (f, quals, complain);
10578       }
10579 
10580     case UNBOUND_CLASS_TEMPLATE:
10581       {
10582 	tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10583 				     in_decl, /*entering_scope=*/1);
10584 	tree name = TYPE_IDENTIFIER (t);
10585 	tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
10586 
10587 	if (ctx == error_mark_node || name == error_mark_node)
10588 	  return error_mark_node;
10589 
10590 	if (parm_list)
10591 	  parm_list = tsubst_template_parms (parm_list, args, complain);
10592 	return make_unbound_class_template (ctx, name, parm_list, complain);
10593       }
10594 
10595     case INDIRECT_REF:
10596     case ADDR_EXPR:
10597     case CALL_EXPR:
10598       gcc_unreachable ();
10599 
10600     case ARRAY_REF:
10601       {
10602 	tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10603 	tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl,
10604 			       /*integral_constant_expression_p=*/false);
10605 	if (e1 == error_mark_node || e2 == error_mark_node)
10606 	  return error_mark_node;
10607 
10608 	return build_nt (ARRAY_REF, e1, e2, NULL_TREE, NULL_TREE);
10609       }
10610 
10611     case SCOPE_REF:
10612       {
10613 	tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10614 	tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
10615 	if (e1 == error_mark_node || e2 == error_mark_node)
10616 	  return error_mark_node;
10617 
10618 	return build_qualified_name (/*type=*/NULL_TREE,
10619 				     e1, e2, QUALIFIED_NAME_IS_TEMPLATE (t));
10620       }
10621 
10622     case TYPEOF_TYPE:
10623       {
10624 	tree type;
10625 
10626 	++cp_unevaluated_operand;
10627 	++c_inhibit_evaluation_warnings;
10628 
10629 	type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
10630 			    complain, in_decl,
10631 			    /*integral_constant_expression_p=*/false);
10632 
10633 	--cp_unevaluated_operand;
10634 	--c_inhibit_evaluation_warnings;
10635 
10636 	type = finish_typeof (type);
10637 	return cp_build_qualified_type_real (type,
10638 					     cp_type_quals (t)
10639 					     | cp_type_quals (type),
10640 					     complain);
10641       }
10642 
10643     case DECLTYPE_TYPE:
10644       {
10645 	tree type;
10646 
10647 	++cp_unevaluated_operand;
10648 	++c_inhibit_evaluation_warnings;
10649 
10650 	type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
10651 			    complain, in_decl,
10652 			    /*integral_constant_expression_p=*/false);
10653 
10654 	--cp_unevaluated_operand;
10655 	--c_inhibit_evaluation_warnings;
10656 
10657 	if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
10658 	  type = lambda_capture_field_type (type);
10659 	else if (DECLTYPE_FOR_LAMBDA_RETURN (t))
10660 	  type = lambda_return_type (type);
10661 	else
10662 	  type = finish_decltype_type
10663 	    (type, DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
10664 	return cp_build_qualified_type_real (type,
10665 					     cp_type_quals (t)
10666 					     | cp_type_quals (type),
10667 					     complain);
10668       }
10669 
10670     case TYPE_ARGUMENT_PACK:
10671     case NONTYPE_ARGUMENT_PACK:
10672       {
10673         tree r = TYPE_P (t)
10674           ? cxx_make_type (TREE_CODE (t))
10675           : make_node (TREE_CODE (t));
10676         tree packed_out =
10677           tsubst_template_args (ARGUMENT_PACK_ARGS (t),
10678                                 args,
10679                                 complain,
10680                                 in_decl);
10681         SET_ARGUMENT_PACK_ARGS (r, packed_out);
10682 
10683         /* For template nontype argument packs, also substitute into
10684            the type.  */
10685         if (TREE_CODE (t) == NONTYPE_ARGUMENT_PACK)
10686           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
10687 
10688         return r;
10689       }
10690       break;
10691 
10692     default:
10693       sorry ("use of %qs in template",
10694 	     tree_code_name [(int) TREE_CODE (t)]);
10695       return error_mark_node;
10696     }
10697 }
10698 
10699 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
10700    type of the expression on the left-hand side of the "." or "->"
10701    operator.  */
10702 
10703 static tree
10704 tsubst_baselink (tree baselink, tree object_type,
10705 		 tree args, tsubst_flags_t complain, tree in_decl)
10706 {
10707     tree name;
10708     tree qualifying_scope;
10709     tree fns;
10710     tree optype;
10711     tree template_args = 0;
10712     bool template_id_p = false;
10713 
10714     /* A baselink indicates a function from a base class.  Both the
10715        BASELINK_ACCESS_BINFO and the base class referenced may
10716        indicate bases of the template class, rather than the
10717        instantiated class.  In addition, lookups that were not
10718        ambiguous before may be ambiguous now.  Therefore, we perform
10719        the lookup again.  */
10720     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
10721     qualifying_scope = tsubst (qualifying_scope, args,
10722 			       complain, in_decl);
10723     fns = BASELINK_FUNCTIONS (baselink);
10724     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
10725     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
10726       {
10727 	template_id_p = true;
10728 	template_args = TREE_OPERAND (fns, 1);
10729 	fns = TREE_OPERAND (fns, 0);
10730 	if (template_args)
10731 	  template_args = tsubst_template_args (template_args, args,
10732 						complain, in_decl);
10733       }
10734     name = DECL_NAME (get_first_fn (fns));
10735     if (IDENTIFIER_TYPENAME_P (name))
10736       name = mangle_conv_op_name_for_type (optype);
10737     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
10738     if (!baselink)
10739       return error_mark_node;
10740 
10741     /* If lookup found a single function, mark it as used at this
10742        point.  (If it lookup found multiple functions the one selected
10743        later by overload resolution will be marked as used at that
10744        point.)  */
10745     if (BASELINK_P (baselink))
10746       fns = BASELINK_FUNCTIONS (baselink);
10747     if (!template_id_p && !really_overloaded_fn (fns))
10748       mark_used (OVL_CURRENT (fns));
10749 
10750     /* Add back the template arguments, if present.  */
10751     if (BASELINK_P (baselink) && template_id_p)
10752       BASELINK_FUNCTIONS (baselink)
10753 	= build_nt (TEMPLATE_ID_EXPR,
10754 		    BASELINK_FUNCTIONS (baselink),
10755 		    template_args);
10756     /* Update the conversion operator type.  */
10757     BASELINK_OPTYPE (baselink) = optype;
10758 
10759     if (!object_type)
10760       object_type = current_class_type;
10761     return adjust_result_of_qualified_name_lookup (baselink,
10762 						   qualifying_scope,
10763 						   object_type);
10764 }
10765 
10766 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
10767    true if the qualified-id will be a postfix-expression in-and-of
10768    itself; false if more of the postfix-expression follows the
10769    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
10770    of "&".  */
10771 
10772 static tree
10773 tsubst_qualified_id (tree qualified_id, tree args,
10774 		     tsubst_flags_t complain, tree in_decl,
10775 		     bool done, bool address_p)
10776 {
10777   tree expr;
10778   tree scope;
10779   tree name;
10780   bool is_template;
10781   tree template_args;
10782 
10783   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
10784 
10785   /* Figure out what name to look up.  */
10786   name = TREE_OPERAND (qualified_id, 1);
10787   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
10788     {
10789       is_template = true;
10790       template_args = TREE_OPERAND (name, 1);
10791       if (template_args)
10792 	template_args = tsubst_template_args (template_args, args,
10793 					      complain, in_decl);
10794       name = TREE_OPERAND (name, 0);
10795     }
10796   else
10797     {
10798       is_template = false;
10799       template_args = NULL_TREE;
10800     }
10801 
10802   /* Substitute into the qualifying scope.  When there are no ARGS, we
10803      are just trying to simplify a non-dependent expression.  In that
10804      case the qualifying scope may be dependent, and, in any case,
10805      substituting will not help.  */
10806   scope = TREE_OPERAND (qualified_id, 0);
10807   if (args)
10808     {
10809       scope = tsubst (scope, args, complain, in_decl);
10810       expr = tsubst_copy (name, args, complain, in_decl);
10811     }
10812   else
10813     expr = name;
10814 
10815   if (dependent_scope_p (scope))
10816     return build_qualified_name (NULL_TREE, scope, expr,
10817 				 QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
10818 
10819   if (!BASELINK_P (name) && !DECL_P (expr))
10820     {
10821       if (TREE_CODE (expr) == BIT_NOT_EXPR)
10822 	{
10823 	  /* A BIT_NOT_EXPR is used to represent a destructor.  */
10824 	  if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
10825 	    {
10826 	      error ("qualifying type %qT does not match destructor name ~%qT",
10827 		     scope, TREE_OPERAND (expr, 0));
10828 	      expr = error_mark_node;
10829 	    }
10830 	  else
10831 	    expr = lookup_qualified_name (scope, complete_dtor_identifier,
10832 					  /*is_type_p=*/0, false);
10833 	}
10834       else
10835 	expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
10836       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
10837 		     ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
10838 	{
10839 	  if (complain & tf_error)
10840 	    {
10841 	      error ("dependent-name %qE is parsed as a non-type, but "
10842 		     "instantiation yields a type", qualified_id);
10843 	      inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
10844 	    }
10845 	  return error_mark_node;
10846 	}
10847     }
10848 
10849   if (DECL_P (expr))
10850     {
10851       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
10852 					   scope);
10853       /* Remember that there was a reference to this entity.  */
10854       mark_used (expr);
10855     }
10856 
10857   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
10858     {
10859       if (complain & tf_error)
10860 	qualified_name_lookup_error (scope,
10861 				     TREE_OPERAND (qualified_id, 1),
10862 				     expr, input_location);
10863       return error_mark_node;
10864     }
10865 
10866   if (is_template)
10867     expr = lookup_template_function (expr, template_args);
10868 
10869   if (expr == error_mark_node && complain & tf_error)
10870     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
10871 				 expr, input_location);
10872   else if (TYPE_P (scope))
10873     {
10874       expr = (adjust_result_of_qualified_name_lookup
10875 	      (expr, scope, current_class_type));
10876       expr = (finish_qualified_id_expr
10877 	      (scope, expr, done, address_p,
10878 	       QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
10879 	       /*template_arg_p=*/false));
10880     }
10881 
10882   /* Expressions do not generally have reference type.  */
10883   if (TREE_CODE (expr) != SCOPE_REF
10884       /* However, if we're about to form a pointer-to-member, we just
10885 	 want the referenced member referenced.  */
10886       && TREE_CODE (expr) != OFFSET_REF)
10887     expr = convert_from_reference (expr);
10888 
10889   return expr;
10890 }
10891 
10892 /* Like tsubst, but deals with expressions.  This function just replaces
10893    template parms; to finish processing the resultant expression, use
10894    tsubst_expr.  */
10895 
10896 static tree
10897 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10898 {
10899   enum tree_code code;
10900   tree r;
10901 
10902   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
10903     return t;
10904 
10905   code = TREE_CODE (t);
10906 
10907   switch (code)
10908     {
10909     case PARM_DECL:
10910       r = retrieve_local_specialization (t);
10911 
10912       if (r == NULL)
10913 	{
10914 	  tree c;
10915 	  /* This can happen for a parameter name used later in a function
10916 	     declaration (such as in a late-specified return type).  Just
10917 	     make a dummy decl, since it's only used for its type.  */
10918 	  gcc_assert (cp_unevaluated_operand != 0);
10919 	  /* We copy T because want to tsubst the PARM_DECL only,
10920 	     not the following PARM_DECLs that are chained to T.  */
10921 	  c = copy_node (t);
10922 	  r = tsubst_decl (c, args, complain);
10923 	  /* Give it the template pattern as its context; its true context
10924 	     hasn't been instantiated yet and this is good enough for
10925 	     mangling.  */
10926 	  DECL_CONTEXT (r) = DECL_CONTEXT (t);
10927 	}
10928 
10929       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
10930 	r = ARGUMENT_PACK_SELECT_ARG (r);
10931       mark_used (r);
10932       return r;
10933 
10934     case CONST_DECL:
10935       {
10936 	tree enum_type;
10937 	tree v;
10938 
10939 	if (DECL_TEMPLATE_PARM_P (t))
10940 	  return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
10941 	/* There is no need to substitute into namespace-scope
10942 	   enumerators.  */
10943 	if (DECL_NAMESPACE_SCOPE_P (t))
10944 	  return t;
10945 	/* If ARGS is NULL, then T is known to be non-dependent.  */
10946 	if (args == NULL_TREE)
10947 	  return integral_constant_value (t);
10948 
10949 	/* Unfortunately, we cannot just call lookup_name here.
10950 	   Consider:
10951 
10952 	     template <int I> int f() {
10953 	     enum E { a = I };
10954 	     struct S { void g() { E e = a; } };
10955 	     };
10956 
10957 	   When we instantiate f<7>::S::g(), say, lookup_name is not
10958 	   clever enough to find f<7>::a.  */
10959 	enum_type
10960 	  = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
10961 			      /*entering_scope=*/0);
10962 
10963 	for (v = TYPE_VALUES (enum_type);
10964 	     v != NULL_TREE;
10965 	     v = TREE_CHAIN (v))
10966 	  if (TREE_PURPOSE (v) == DECL_NAME (t))
10967 	    return TREE_VALUE (v);
10968 
10969 	  /* We didn't find the name.  That should never happen; if
10970 	     name-lookup found it during preliminary parsing, we
10971 	     should find it again here during instantiation.  */
10972 	gcc_unreachable ();
10973       }
10974       return t;
10975 
10976     case FIELD_DECL:
10977       if (DECL_CONTEXT (t))
10978 	{
10979 	  tree ctx;
10980 
10981 	  ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
10982 				  /*entering_scope=*/1);
10983 	  if (ctx != DECL_CONTEXT (t))
10984 	    {
10985 	      tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
10986 	      if (!r)
10987 		{
10988 		  if (complain & tf_error)
10989 		    error ("using invalid field %qD", t);
10990 		  return error_mark_node;
10991 		}
10992 	      return r;
10993 	    }
10994 	}
10995 
10996       return t;
10997 
10998     case VAR_DECL:
10999     case FUNCTION_DECL:
11000       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
11001 	  || local_variable_p (t))
11002 	t = tsubst (t, args, complain, in_decl);
11003       mark_used (t);
11004       return t;
11005 
11006     case BASELINK:
11007       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
11008 
11009     case TEMPLATE_DECL:
11010       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
11011 	return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
11012 		       args, complain, in_decl);
11013       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
11014 	return tsubst (t, args, complain, in_decl);
11015       else if (DECL_CLASS_SCOPE_P (t)
11016 	       && uses_template_parms (DECL_CONTEXT (t)))
11017 	{
11018 	  /* Template template argument like the following example need
11019 	     special treatment:
11020 
11021 	       template <template <class> class TT> struct C {};
11022 	       template <class T> struct D {
11023 		 template <class U> struct E {};
11024 		 C<E> c;				// #1
11025 	       };
11026 	       D<int> d;				// #2
11027 
11028 	     We are processing the template argument `E' in #1 for
11029 	     the template instantiation #2.  Originally, `E' is a
11030 	     TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
11031 	     have to substitute this with one having context `D<int>'.  */
11032 
11033 	  tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
11034 	  return lookup_field (context, DECL_NAME(t), 0, false);
11035 	}
11036       else
11037 	/* Ordinary template template argument.  */
11038 	return t;
11039 
11040     case CAST_EXPR:
11041     case REINTERPRET_CAST_EXPR:
11042     case CONST_CAST_EXPR:
11043     case STATIC_CAST_EXPR:
11044     case DYNAMIC_CAST_EXPR:
11045     case NOP_EXPR:
11046       return build1
11047 	(code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11048 	 tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11049 
11050     case SIZEOF_EXPR:
11051       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11052         {
11053           /* We only want to compute the number of arguments.  */
11054           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
11055                                                 complain, in_decl);
11056 	  int len = 0;
11057 
11058 	  if (TREE_CODE (expanded) == TREE_VEC)
11059 	    len = TREE_VEC_LENGTH (expanded);
11060 
11061 	  if (expanded == error_mark_node)
11062 	    return error_mark_node;
11063 	  else if (PACK_EXPANSION_P (expanded)
11064 		   || (TREE_CODE (expanded) == TREE_VEC
11065 		       && len > 0
11066 		       && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
11067 	    {
11068 	      if (TREE_CODE (expanded) == TREE_VEC)
11069 		expanded = TREE_VEC_ELT (expanded, len - 1);
11070 
11071 	      if (TYPE_P (expanded))
11072 		return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR,
11073 						   complain & tf_error);
11074 	      else
11075 		return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
11076                                                    complain & tf_error);
11077 	    }
11078 	  else
11079 	    return build_int_cst (size_type_node, len);
11080         }
11081       /* Fall through */
11082 
11083     case INDIRECT_REF:
11084     case NEGATE_EXPR:
11085     case TRUTH_NOT_EXPR:
11086     case BIT_NOT_EXPR:
11087     case ADDR_EXPR:
11088     case UNARY_PLUS_EXPR:      /* Unary + */
11089     case ALIGNOF_EXPR:
11090     case ARROW_EXPR:
11091     case THROW_EXPR:
11092     case TYPEID_EXPR:
11093     case REALPART_EXPR:
11094     case IMAGPART_EXPR:
11095       return build1
11096 	(code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11097 	 tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11098 
11099     case COMPONENT_REF:
11100       {
11101 	tree object;
11102 	tree name;
11103 
11104 	object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
11105 	name = TREE_OPERAND (t, 1);
11106 	if (TREE_CODE (name) == BIT_NOT_EXPR)
11107 	  {
11108 	    name = tsubst_copy (TREE_OPERAND (name, 0), args,
11109 				complain, in_decl);
11110 	    name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11111 	  }
11112 	else if (TREE_CODE (name) == SCOPE_REF
11113 		 && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
11114 	  {
11115 	    tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
11116 				     complain, in_decl);
11117 	    name = TREE_OPERAND (name, 1);
11118 	    name = tsubst_copy (TREE_OPERAND (name, 0), args,
11119 				complain, in_decl);
11120 	    name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11121 	    name = build_qualified_name (/*type=*/NULL_TREE,
11122 					 base, name,
11123 					 /*template_p=*/false);
11124 	  }
11125 	else if (TREE_CODE (name) == BASELINK)
11126 	  name = tsubst_baselink (name,
11127 				  non_reference (TREE_TYPE (object)),
11128 				  args, complain,
11129 				  in_decl);
11130 	else
11131 	  name = tsubst_copy (name, args, complain, in_decl);
11132 	return build_nt (COMPONENT_REF, object, name, NULL_TREE);
11133       }
11134 
11135     case PLUS_EXPR:
11136     case MINUS_EXPR:
11137     case MULT_EXPR:
11138     case TRUNC_DIV_EXPR:
11139     case CEIL_DIV_EXPR:
11140     case FLOOR_DIV_EXPR:
11141     case ROUND_DIV_EXPR:
11142     case EXACT_DIV_EXPR:
11143     case BIT_AND_EXPR:
11144     case BIT_IOR_EXPR:
11145     case BIT_XOR_EXPR:
11146     case TRUNC_MOD_EXPR:
11147     case FLOOR_MOD_EXPR:
11148     case TRUTH_ANDIF_EXPR:
11149     case TRUTH_ORIF_EXPR:
11150     case TRUTH_AND_EXPR:
11151     case TRUTH_OR_EXPR:
11152     case RSHIFT_EXPR:
11153     case LSHIFT_EXPR:
11154     case RROTATE_EXPR:
11155     case LROTATE_EXPR:
11156     case EQ_EXPR:
11157     case NE_EXPR:
11158     case MAX_EXPR:
11159     case MIN_EXPR:
11160     case LE_EXPR:
11161     case GE_EXPR:
11162     case LT_EXPR:
11163     case GT_EXPR:
11164     case COMPOUND_EXPR:
11165     case DOTSTAR_EXPR:
11166     case MEMBER_REF:
11167     case PREDECREMENT_EXPR:
11168     case PREINCREMENT_EXPR:
11169     case POSTDECREMENT_EXPR:
11170     case POSTINCREMENT_EXPR:
11171       return build_nt
11172 	(code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11173 	 tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11174 
11175     case SCOPE_REF:
11176       return build_qualified_name (/*type=*/NULL_TREE,
11177 				   tsubst_copy (TREE_OPERAND (t, 0),
11178 						args, complain, in_decl),
11179 				   tsubst_copy (TREE_OPERAND (t, 1),
11180 						args, complain, in_decl),
11181 				   QUALIFIED_NAME_IS_TEMPLATE (t));
11182 
11183     case ARRAY_REF:
11184       return build_nt
11185 	(ARRAY_REF,
11186 	 tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11187 	 tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11188 	 NULL_TREE, NULL_TREE);
11189 
11190     case CALL_EXPR:
11191       {
11192 	int n = VL_EXP_OPERAND_LENGTH (t);
11193 	tree result = build_vl_exp (CALL_EXPR, n);
11194 	int i;
11195 	for (i = 0; i < n; i++)
11196 	  TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
11197 					     complain, in_decl);
11198 	return result;
11199       }
11200 
11201     case COND_EXPR:
11202     case MODOP_EXPR:
11203     case PSEUDO_DTOR_EXPR:
11204       {
11205 	r = build_nt
11206 	  (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11207 	   tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11208 	   tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
11209 	TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
11210 	return r;
11211       }
11212 
11213     case NEW_EXPR:
11214       {
11215 	r = build_nt
11216 	(code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11217 	 tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11218 	 tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
11219 	NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
11220 	return r;
11221       }
11222 
11223     case DELETE_EXPR:
11224       {
11225 	r = build_nt
11226 	(code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11227 	 tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11228 	DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
11229 	DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
11230 	return r;
11231       }
11232 
11233     case TEMPLATE_ID_EXPR:
11234       {
11235 	/* Substituted template arguments */
11236 	tree fn = TREE_OPERAND (t, 0);
11237 	tree targs = TREE_OPERAND (t, 1);
11238 
11239 	fn = tsubst_copy (fn, args, complain, in_decl);
11240 	if (targs)
11241 	  targs = tsubst_template_args (targs, args, complain, in_decl);
11242 
11243 	return lookup_template_function (fn, targs);
11244       }
11245 
11246     case TREE_LIST:
11247       {
11248 	tree purpose, value, chain;
11249 
11250 	if (t == void_list_node)
11251 	  return t;
11252 
11253 	purpose = TREE_PURPOSE (t);
11254 	if (purpose)
11255 	  purpose = tsubst_copy (purpose, args, complain, in_decl);
11256 	value = TREE_VALUE (t);
11257 	if (value)
11258 	  value = tsubst_copy (value, args, complain, in_decl);
11259 	chain = TREE_CHAIN (t);
11260 	if (chain && chain != void_type_node)
11261 	  chain = tsubst_copy (chain, args, complain, in_decl);
11262 	if (purpose == TREE_PURPOSE (t)
11263 	    && value == TREE_VALUE (t)
11264 	    && chain == TREE_CHAIN (t))
11265 	  return t;
11266 	return tree_cons (purpose, value, chain);
11267       }
11268 
11269     case RECORD_TYPE:
11270     case UNION_TYPE:
11271     case ENUMERAL_TYPE:
11272     case INTEGER_TYPE:
11273     case TEMPLATE_TYPE_PARM:
11274     case TEMPLATE_TEMPLATE_PARM:
11275     case BOUND_TEMPLATE_TEMPLATE_PARM:
11276     case TEMPLATE_PARM_INDEX:
11277     case POINTER_TYPE:
11278     case REFERENCE_TYPE:
11279     case OFFSET_TYPE:
11280     case FUNCTION_TYPE:
11281     case METHOD_TYPE:
11282     case ARRAY_TYPE:
11283     case TYPENAME_TYPE:
11284     case UNBOUND_CLASS_TEMPLATE:
11285     case TYPEOF_TYPE:
11286     case DECLTYPE_TYPE:
11287     case TYPE_DECL:
11288       return tsubst (t, args, complain, in_decl);
11289 
11290     case IDENTIFIER_NODE:
11291       if (IDENTIFIER_TYPENAME_P (t))
11292 	{
11293 	  tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11294 	  return mangle_conv_op_name_for_type (new_type);
11295 	}
11296       else
11297 	return t;
11298 
11299     case CONSTRUCTOR:
11300       /* This is handled by tsubst_copy_and_build.  */
11301       gcc_unreachable ();
11302 
11303     case VA_ARG_EXPR:
11304       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
11305 					  in_decl),
11306 			     tsubst (TREE_TYPE (t), args, complain, in_decl));
11307 
11308     case CLEANUP_POINT_EXPR:
11309       /* We shouldn't have built any of these during initial template
11310 	 generation.  Instead, they should be built during instantiation
11311 	 in response to the saved STMT_IS_FULL_EXPR_P setting.  */
11312       gcc_unreachable ();
11313 
11314     case OFFSET_REF:
11315       mark_used (TREE_OPERAND (t, 1));
11316       return t;
11317 
11318     case EXPR_PACK_EXPANSION:
11319       error ("invalid use of pack expansion expression");
11320       return error_mark_node;
11321 
11322     case NONTYPE_ARGUMENT_PACK:
11323       error ("use %<...%> to expand argument pack");
11324       return error_mark_node;
11325 
11326     default:
11327       return t;
11328     }
11329 }
11330 
11331 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
11332 
11333 static tree
11334 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
11335 		    tree in_decl)
11336 {
11337   tree new_clauses = NULL, nc, oc;
11338 
11339   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
11340     {
11341       nc = copy_node (oc);
11342       OMP_CLAUSE_CHAIN (nc) = new_clauses;
11343       new_clauses = nc;
11344 
11345       switch (OMP_CLAUSE_CODE (nc))
11346 	{
11347 	case OMP_CLAUSE_LASTPRIVATE:
11348 	  if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
11349 	    {
11350 	      OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
11351 	      tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
11352 			   in_decl, /*integral_constant_expression_p=*/false);
11353 	      OMP_CLAUSE_LASTPRIVATE_STMT (nc)
11354 		= pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
11355 	    }
11356 	  /* FALLTHRU */
11357 	case OMP_CLAUSE_PRIVATE:
11358 	case OMP_CLAUSE_SHARED:
11359 	case OMP_CLAUSE_FIRSTPRIVATE:
11360 	case OMP_CLAUSE_REDUCTION:
11361 	case OMP_CLAUSE_COPYIN:
11362 	case OMP_CLAUSE_COPYPRIVATE:
11363 	case OMP_CLAUSE_IF:
11364 	case OMP_CLAUSE_NUM_THREADS:
11365 	case OMP_CLAUSE_SCHEDULE:
11366 	case OMP_CLAUSE_COLLAPSE:
11367 	  OMP_CLAUSE_OPERAND (nc, 0)
11368 	    = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain,
11369 			   in_decl, /*integral_constant_expression_p=*/false);
11370 	  break;
11371 	case OMP_CLAUSE_NOWAIT:
11372 	case OMP_CLAUSE_ORDERED:
11373 	case OMP_CLAUSE_DEFAULT:
11374 	case OMP_CLAUSE_UNTIED:
11375 	  break;
11376 	default:
11377 	  gcc_unreachable ();
11378 	}
11379     }
11380 
11381   return finish_omp_clauses (nreverse (new_clauses));
11382 }
11383 
11384 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
11385 
11386 static tree
11387 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
11388 			  tree in_decl)
11389 {
11390 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
11391 
11392   tree purpose, value, chain;
11393 
11394   if (t == NULL)
11395     return t;
11396 
11397   if (TREE_CODE (t) != TREE_LIST)
11398     return tsubst_copy_and_build (t, args, complain, in_decl,
11399 				  /*function_p=*/false,
11400 				  /*integral_constant_expression_p=*/false);
11401 
11402   if (t == void_list_node)
11403     return t;
11404 
11405   purpose = TREE_PURPOSE (t);
11406   if (purpose)
11407     purpose = RECUR (purpose);
11408   value = TREE_VALUE (t);
11409   if (value && TREE_CODE (value) != LABEL_DECL)
11410     value = RECUR (value);
11411   chain = TREE_CHAIN (t);
11412   if (chain && chain != void_type_node)
11413     chain = RECUR (chain);
11414   return tree_cons (purpose, value, chain);
11415 #undef RECUR
11416 }
11417 
11418 /* Substitute one OMP_FOR iterator.  */
11419 
11420 static void
11421 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
11422 			 tree condv, tree incrv, tree *clauses,
11423 			 tree args, tsubst_flags_t complain, tree in_decl,
11424 			 bool integral_constant_expression_p)
11425 {
11426 #define RECUR(NODE)				\
11427   tsubst_expr ((NODE), args, complain, in_decl,	\
11428 	       integral_constant_expression_p)
11429   tree decl, init, cond, incr, auto_node;
11430 
11431   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
11432   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
11433   decl = RECUR (TREE_OPERAND (init, 0));
11434   init = TREE_OPERAND (init, 1);
11435   auto_node = type_uses_auto (TREE_TYPE (decl));
11436   if (auto_node && init)
11437     {
11438       tree init_expr = init;
11439       if (TREE_CODE (init_expr) == DECL_EXPR)
11440 	init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
11441       init_expr = RECUR (init_expr);
11442       TREE_TYPE (decl)
11443 	= do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
11444     }
11445   gcc_assert (!type_dependent_expression_p (decl));
11446 
11447   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
11448     {
11449       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
11450       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11451       if (TREE_CODE (incr) == MODIFY_EXPR)
11452 	incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
11453 				    RECUR (TREE_OPERAND (incr, 1)),
11454 				    complain);
11455       else
11456 	incr = RECUR (incr);
11457       TREE_VEC_ELT (declv, i) = decl;
11458       TREE_VEC_ELT (initv, i) = init;
11459       TREE_VEC_ELT (condv, i) = cond;
11460       TREE_VEC_ELT (incrv, i) = incr;
11461       return;
11462     }
11463 
11464   if (init && TREE_CODE (init) != DECL_EXPR)
11465     {
11466       tree c;
11467       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
11468 	{
11469 	  if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
11470 	       || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
11471 	      && OMP_CLAUSE_DECL (c) == decl)
11472 	    break;
11473 	  else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
11474 		   && OMP_CLAUSE_DECL (c) == decl)
11475 	    error ("iteration variable %qD should not be firstprivate", decl);
11476 	  else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
11477 		   && OMP_CLAUSE_DECL (c) == decl)
11478 	    error ("iteration variable %qD should not be reduction", decl);
11479 	}
11480       if (c == NULL)
11481 	{
11482 	  c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
11483 	  OMP_CLAUSE_DECL (c) = decl;
11484 	  c = finish_omp_clauses (c);
11485 	  if (c)
11486 	    {
11487 	      OMP_CLAUSE_CHAIN (c) = *clauses;
11488 	      *clauses = c;
11489 	    }
11490 	}
11491     }
11492   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
11493   if (COMPARISON_CLASS_P (cond))
11494     cond = build2 (TREE_CODE (cond), boolean_type_node,
11495 		   RECUR (TREE_OPERAND (cond, 0)),
11496 		   RECUR (TREE_OPERAND (cond, 1)));
11497   else
11498     cond = RECUR (cond);
11499   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11500   switch (TREE_CODE (incr))
11501     {
11502     case PREINCREMENT_EXPR:
11503     case PREDECREMENT_EXPR:
11504     case POSTINCREMENT_EXPR:
11505     case POSTDECREMENT_EXPR:
11506       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
11507 		     RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
11508       break;
11509     case MODIFY_EXPR:
11510       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11511 	  || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11512 	{
11513 	  tree rhs = TREE_OPERAND (incr, 1);
11514 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11515 			 RECUR (TREE_OPERAND (incr, 0)),
11516 			 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11517 				 RECUR (TREE_OPERAND (rhs, 0)),
11518 				 RECUR (TREE_OPERAND (rhs, 1))));
11519 	}
11520       else
11521 	incr = RECUR (incr);
11522       break;
11523     case MODOP_EXPR:
11524       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11525 	  || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11526 	{
11527 	  tree lhs = RECUR (TREE_OPERAND (incr, 0));
11528 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
11529 			 build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
11530 				 TREE_TYPE (decl), lhs,
11531 				 RECUR (TREE_OPERAND (incr, 2))));
11532 	}
11533       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
11534 	       && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
11535 		   || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
11536 	{
11537 	  tree rhs = TREE_OPERAND (incr, 2);
11538 	  incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11539 			 RECUR (TREE_OPERAND (incr, 0)),
11540 			 build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11541 				 RECUR (TREE_OPERAND (rhs, 0)),
11542 				 RECUR (TREE_OPERAND (rhs, 1))));
11543 	}
11544       else
11545 	incr = RECUR (incr);
11546       break;
11547     default:
11548       incr = RECUR (incr);
11549       break;
11550     }
11551 
11552   TREE_VEC_ELT (declv, i) = decl;
11553   TREE_VEC_ELT (initv, i) = init;
11554   TREE_VEC_ELT (condv, i) = cond;
11555   TREE_VEC_ELT (incrv, i) = incr;
11556 #undef RECUR
11557 }
11558 
11559 /* Like tsubst_copy for expressions, etc. but also does semantic
11560    processing.  */
11561 
11562 static tree
11563 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
11564 	     bool integral_constant_expression_p)
11565 {
11566 #define RECUR(NODE)				\
11567   tsubst_expr ((NODE), args, complain, in_decl,	\
11568 	       integral_constant_expression_p)
11569 
11570   tree stmt, tmp;
11571 
11572   if (t == NULL_TREE || t == error_mark_node)
11573     return t;
11574 
11575   if (EXPR_HAS_LOCATION (t))
11576     input_location = EXPR_LOCATION (t);
11577   if (STATEMENT_CODE_P (TREE_CODE (t)))
11578     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
11579 
11580   switch (TREE_CODE (t))
11581     {
11582     case STATEMENT_LIST:
11583       {
11584 	tree_stmt_iterator i;
11585 	for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
11586 	  RECUR (tsi_stmt (i));
11587 	break;
11588       }
11589 
11590     case CTOR_INITIALIZER:
11591       finish_mem_initializers (tsubst_initializer_list
11592 			       (TREE_OPERAND (t, 0), args));
11593       break;
11594 
11595     case RETURN_EXPR:
11596       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
11597       break;
11598 
11599     case EXPR_STMT:
11600       tmp = RECUR (EXPR_STMT_EXPR (t));
11601       if (EXPR_STMT_STMT_EXPR_RESULT (t))
11602 	finish_stmt_expr_expr (tmp, cur_stmt_expr);
11603       else
11604 	finish_expr_stmt (tmp);
11605       break;
11606 
11607     case USING_STMT:
11608       do_using_directive (RECUR (USING_STMT_NAMESPACE (t)));
11609       break;
11610 
11611     case DECL_EXPR:
11612       {
11613 	tree decl;
11614 	tree init;
11615 
11616 	decl = DECL_EXPR_DECL (t);
11617 	if (TREE_CODE (decl) == LABEL_DECL)
11618 	  finish_label_decl (DECL_NAME (decl));
11619 	else if (TREE_CODE (decl) == USING_DECL)
11620 	  {
11621 	    tree scope = USING_DECL_SCOPE (decl);
11622 	    tree name = DECL_NAME (decl);
11623 	    tree decl;
11624 
11625 	    scope = RECUR (scope);
11626 	    decl = lookup_qualified_name (scope, name,
11627 					  /*is_type_p=*/false,
11628 					  /*complain=*/false);
11629 	    if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
11630 	      qualified_name_lookup_error (scope, name, decl, input_location);
11631 	    else
11632 	      do_local_using_decl (decl, scope, name);
11633 	  }
11634 	else
11635 	  {
11636 	    init = DECL_INITIAL (decl);
11637 	    decl = tsubst (decl, args, complain, in_decl);
11638 	    if (decl != error_mark_node)
11639 	      {
11640 		/* By marking the declaration as instantiated, we avoid
11641 		   trying to instantiate it.  Since instantiate_decl can't
11642 		   handle local variables, and since we've already done
11643 		   all that needs to be done, that's the right thing to
11644 		   do.  */
11645 		if (TREE_CODE (decl) == VAR_DECL)
11646 		  DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11647 		if (TREE_CODE (decl) == VAR_DECL
11648 		    && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
11649 		  /* Anonymous aggregates are a special case.  */
11650 		  finish_anon_union (decl);
11651 		else
11652 		  {
11653 		    maybe_push_decl (decl);
11654 		    if (TREE_CODE (decl) == VAR_DECL
11655 			&& DECL_PRETTY_FUNCTION_P (decl))
11656 		      {
11657 			/* For __PRETTY_FUNCTION__ we have to adjust the
11658 			   initializer.  */
11659 			const char *const name
11660 			  = cxx_printable_name (current_function_decl, 2);
11661 			init = cp_fname_init (name, &TREE_TYPE (decl));
11662 		      }
11663 		    else
11664 		      {
11665 			tree t = RECUR (init);
11666 
11667 			if (init && !t)
11668 			  /* If we had an initializer but it
11669 			     instantiated to nothing,
11670 			     value-initialize the object.  This will
11671 			     only occur when the initializer was a
11672 			     pack expansion where the parameter packs
11673 			     used in that expansion were of length
11674 			     zero.  */
11675 			  init = build_value_init (TREE_TYPE (decl));
11676 			else
11677 			  init = t;
11678 		      }
11679 
11680 		    cp_finish_decl (decl, init, false, NULL_TREE, 0);
11681 		  }
11682 	      }
11683 	  }
11684 
11685 	/* A DECL_EXPR can also be used as an expression, in the condition
11686 	   clause of an if/for/while construct.  */
11687 	return decl;
11688       }
11689 
11690     case FOR_STMT:
11691       stmt = begin_for_stmt ();
11692 			  RECUR (FOR_INIT_STMT (t));
11693       finish_for_init_stmt (stmt);
11694       tmp = RECUR (FOR_COND (t));
11695       finish_for_cond (tmp, stmt);
11696       tmp = RECUR (FOR_EXPR (t));
11697       finish_for_expr (tmp, stmt);
11698       RECUR (FOR_BODY (t));
11699       finish_for_stmt (stmt);
11700       break;
11701 
11702     case WHILE_STMT:
11703       stmt = begin_while_stmt ();
11704       tmp = RECUR (WHILE_COND (t));
11705       finish_while_stmt_cond (tmp, stmt);
11706       RECUR (WHILE_BODY (t));
11707       finish_while_stmt (stmt);
11708       break;
11709 
11710     case DO_STMT:
11711       stmt = begin_do_stmt ();
11712       RECUR (DO_BODY (t));
11713       finish_do_body (stmt);
11714       tmp = RECUR (DO_COND (t));
11715       finish_do_stmt (tmp, stmt);
11716       break;
11717 
11718     case IF_STMT:
11719       stmt = begin_if_stmt ();
11720       tmp = RECUR (IF_COND (t));
11721       finish_if_stmt_cond (tmp, stmt);
11722       RECUR (THEN_CLAUSE (t));
11723       finish_then_clause (stmt);
11724 
11725       if (ELSE_CLAUSE (t))
11726 	{
11727 	  begin_else_clause (stmt);
11728 	  RECUR (ELSE_CLAUSE (t));
11729 	  finish_else_clause (stmt);
11730 	}
11731 
11732       finish_if_stmt (stmt);
11733       break;
11734 
11735     case BIND_EXPR:
11736       if (BIND_EXPR_BODY_BLOCK (t))
11737 	stmt = begin_function_body ();
11738       else
11739 	stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
11740 				    ? BCS_TRY_BLOCK : 0);
11741 
11742       RECUR (BIND_EXPR_BODY (t));
11743 
11744       if (BIND_EXPR_BODY_BLOCK (t))
11745 	finish_function_body (stmt);
11746       else
11747 	finish_compound_stmt (stmt);
11748       break;
11749 
11750     case BREAK_STMT:
11751       finish_break_stmt ();
11752       break;
11753 
11754     case CONTINUE_STMT:
11755       finish_continue_stmt ();
11756       break;
11757 
11758     case SWITCH_STMT:
11759       stmt = begin_switch_stmt ();
11760       tmp = RECUR (SWITCH_STMT_COND (t));
11761       finish_switch_cond (tmp, stmt);
11762       RECUR (SWITCH_STMT_BODY (t));
11763       finish_switch_stmt (stmt);
11764       break;
11765 
11766     case CASE_LABEL_EXPR:
11767       finish_case_label (EXPR_LOCATION (t),
11768 			 RECUR (CASE_LOW (t)),
11769 			 RECUR (CASE_HIGH (t)));
11770       break;
11771 
11772     case LABEL_EXPR:
11773       {
11774 	tree decl = LABEL_EXPR_LABEL (t);
11775 	tree label;
11776 
11777 	label = finish_label_stmt (DECL_NAME (decl));
11778 	if (DECL_ATTRIBUTES (decl) != NULL_TREE)
11779 	  cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
11780       }
11781       break;
11782 
11783     case GOTO_EXPR:
11784       tmp = GOTO_DESTINATION (t);
11785       if (TREE_CODE (tmp) != LABEL_DECL)
11786 	/* Computed goto's must be tsubst'd into.  On the other hand,
11787 	   non-computed gotos must not be; the identifier in question
11788 	   will have no binding.  */
11789 	tmp = RECUR (tmp);
11790       else
11791 	tmp = DECL_NAME (tmp);
11792       finish_goto_stmt (tmp);
11793       break;
11794 
11795     case ASM_EXPR:
11796       tmp = finish_asm_stmt
11797 	(ASM_VOLATILE_P (t),
11798 	 RECUR (ASM_STRING (t)),
11799 	 tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
11800 	 tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
11801 	 tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl),
11802 	 tsubst_copy_asm_operands (ASM_LABELS (t), args, complain, in_decl));
11803       {
11804 	tree asm_expr = tmp;
11805 	if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
11806 	  asm_expr = TREE_OPERAND (asm_expr, 0);
11807 	ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
11808       }
11809       break;
11810 
11811     case TRY_BLOCK:
11812       if (CLEANUP_P (t))
11813 	{
11814 	  stmt = begin_try_block ();
11815 	  RECUR (TRY_STMTS (t));
11816 	  finish_cleanup_try_block (stmt);
11817 	  finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
11818 	}
11819       else
11820 	{
11821 	  tree compound_stmt = NULL_TREE;
11822 
11823 	  if (FN_TRY_BLOCK_P (t))
11824 	    stmt = begin_function_try_block (&compound_stmt);
11825 	  else
11826 	    stmt = begin_try_block ();
11827 
11828 	  RECUR (TRY_STMTS (t));
11829 
11830 	  if (FN_TRY_BLOCK_P (t))
11831 	    finish_function_try_block (stmt);
11832 	  else
11833 	    finish_try_block (stmt);
11834 
11835 	  RECUR (TRY_HANDLERS (t));
11836 	  if (FN_TRY_BLOCK_P (t))
11837 	    finish_function_handler_sequence (stmt, compound_stmt);
11838 	  else
11839 	    finish_handler_sequence (stmt);
11840 	}
11841       break;
11842 
11843     case HANDLER:
11844       {
11845 	tree decl = HANDLER_PARMS (t);
11846 
11847 	if (decl)
11848 	  {
11849 	    decl = tsubst (decl, args, complain, in_decl);
11850 	    /* Prevent instantiate_decl from trying to instantiate
11851 	       this variable.  We've already done all that needs to be
11852 	       done.  */
11853 	    if (decl != error_mark_node)
11854 	      DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11855 	  }
11856 	stmt = begin_handler ();
11857 	finish_handler_parms (decl, stmt);
11858 	RECUR (HANDLER_BODY (t));
11859 	finish_handler (stmt);
11860       }
11861       break;
11862 
11863     case TAG_DEFN:
11864       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
11865       break;
11866 
11867     case STATIC_ASSERT:
11868       {
11869         tree condition =
11870           tsubst_expr (STATIC_ASSERT_CONDITION (t),
11871                        args,
11872                        complain, in_decl,
11873                        /*integral_constant_expression_p=*/true);
11874         finish_static_assert (condition,
11875                               STATIC_ASSERT_MESSAGE (t),
11876                               STATIC_ASSERT_SOURCE_LOCATION (t),
11877                               /*member_p=*/false);
11878       }
11879       break;
11880 
11881     case OMP_PARALLEL:
11882       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
11883 				args, complain, in_decl);
11884       stmt = begin_omp_parallel ();
11885       RECUR (OMP_PARALLEL_BODY (t));
11886       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
11887 	= OMP_PARALLEL_COMBINED (t);
11888       break;
11889 
11890     case OMP_TASK:
11891       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
11892 				args, complain, in_decl);
11893       stmt = begin_omp_task ();
11894       RECUR (OMP_TASK_BODY (t));
11895       finish_omp_task (tmp, stmt);
11896       break;
11897 
11898     case OMP_FOR:
11899       {
11900 	tree clauses, body, pre_body;
11901 	tree declv, initv, condv, incrv;
11902 	int i;
11903 
11904 	clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
11905 				      args, complain, in_decl);
11906 	declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11907 	initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11908 	condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11909 	incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11910 
11911 	for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
11912 	  tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
11913 				   &clauses, args, complain, in_decl,
11914 				   integral_constant_expression_p);
11915 
11916 	stmt = begin_omp_structured_block ();
11917 
11918 	for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
11919 	  if (TREE_VEC_ELT (initv, i) == NULL
11920 	      || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
11921 	    TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
11922 	  else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
11923 	    {
11924 	      tree init = RECUR (TREE_VEC_ELT (initv, i));
11925 	      gcc_assert (init == TREE_VEC_ELT (declv, i));
11926 	      TREE_VEC_ELT (initv, i) = NULL_TREE;
11927 	    }
11928 	  else
11929 	    {
11930 	      tree decl_expr = TREE_VEC_ELT (initv, i);
11931 	      tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
11932 	      gcc_assert (init != NULL);
11933 	      TREE_VEC_ELT (initv, i) = RECUR (init);
11934 	      DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
11935 	      RECUR (decl_expr);
11936 	      DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
11937 	    }
11938 
11939 	pre_body = push_stmt_list ();
11940 	RECUR (OMP_FOR_PRE_BODY (t));
11941 	pre_body = pop_stmt_list (pre_body);
11942 
11943 	body = push_stmt_list ();
11944 	RECUR (OMP_FOR_BODY (t));
11945 	body = pop_stmt_list (body);
11946 
11947 	t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
11948 			    body, pre_body, clauses);
11949 
11950 	add_stmt (finish_omp_structured_block (stmt));
11951       }
11952       break;
11953 
11954     case OMP_SECTIONS:
11955     case OMP_SINGLE:
11956       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
11957       stmt = push_stmt_list ();
11958       RECUR (OMP_BODY (t));
11959       stmt = pop_stmt_list (stmt);
11960 
11961       t = copy_node (t);
11962       OMP_BODY (t) = stmt;
11963       OMP_CLAUSES (t) = tmp;
11964       add_stmt (t);
11965       break;
11966 
11967     case OMP_SECTION:
11968     case OMP_CRITICAL:
11969     case OMP_MASTER:
11970     case OMP_ORDERED:
11971       stmt = push_stmt_list ();
11972       RECUR (OMP_BODY (t));
11973       stmt = pop_stmt_list (stmt);
11974 
11975       t = copy_node (t);
11976       OMP_BODY (t) = stmt;
11977       add_stmt (t);
11978       break;
11979 
11980     case OMP_ATOMIC:
11981       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
11982       {
11983 	tree op1 = TREE_OPERAND (t, 1);
11984 	tree lhs = RECUR (TREE_OPERAND (op1, 0));
11985 	tree rhs = RECUR (TREE_OPERAND (op1, 1));
11986 	finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
11987       }
11988       break;
11989 
11990     case EXPR_PACK_EXPANSION:
11991       error ("invalid use of pack expansion expression");
11992       return error_mark_node;
11993 
11994     case NONTYPE_ARGUMENT_PACK:
11995       error ("use %<...%> to expand argument pack");
11996       return error_mark_node;
11997 
11998     default:
11999       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
12000 
12001       return tsubst_copy_and_build (t, args, complain, in_decl,
12002 				    /*function_p=*/false,
12003 				    integral_constant_expression_p);
12004     }
12005 
12006   return NULL_TREE;
12007 #undef RECUR
12008 }
12009 
12010 /* T is a postfix-expression that is not being used in a function
12011    call.  Return the substituted version of T.  */
12012 
12013 static tree
12014 tsubst_non_call_postfix_expression (tree t, tree args,
12015 				    tsubst_flags_t complain,
12016 				    tree in_decl)
12017 {
12018   if (TREE_CODE (t) == SCOPE_REF)
12019     t = tsubst_qualified_id (t, args, complain, in_decl,
12020 			     /*done=*/false, /*address_p=*/false);
12021   else
12022     t = tsubst_copy_and_build (t, args, complain, in_decl,
12023 			       /*function_p=*/false,
12024 			       /*integral_constant_expression_p=*/false);
12025 
12026   return t;
12027 }
12028 
12029 /* Like tsubst but deals with expressions and performs semantic
12030    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
12031 
12032 tree
12033 tsubst_copy_and_build (tree t,
12034 		       tree args,
12035 		       tsubst_flags_t complain,
12036 		       tree in_decl,
12037 		       bool function_p,
12038 		       bool integral_constant_expression_p)
12039 {
12040 #define RECUR(NODE)						\
12041   tsubst_copy_and_build (NODE, args, complain, in_decl, 	\
12042 			 /*function_p=*/false,			\
12043 			 integral_constant_expression_p)
12044 
12045   tree op1;
12046 
12047   if (t == NULL_TREE || t == error_mark_node)
12048     return t;
12049 
12050   switch (TREE_CODE (t))
12051     {
12052     case USING_DECL:
12053       t = DECL_NAME (t);
12054       /* Fall through.  */
12055     case IDENTIFIER_NODE:
12056       {
12057 	tree decl;
12058 	cp_id_kind idk;
12059 	bool non_integral_constant_expression_p;
12060 	const char *error_msg;
12061 
12062 	if (IDENTIFIER_TYPENAME_P (t))
12063 	  {
12064 	    tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12065 	    t = mangle_conv_op_name_for_type (new_type);
12066 	  }
12067 
12068 	/* Look up the name.  */
12069 	decl = lookup_name (t);
12070 
12071 	/* By convention, expressions use ERROR_MARK_NODE to indicate
12072 	   failure, not NULL_TREE.  */
12073 	if (decl == NULL_TREE)
12074 	  decl = error_mark_node;
12075 
12076 	decl = finish_id_expression (t, decl, NULL_TREE,
12077 				     &idk,
12078 				     integral_constant_expression_p,
12079 				     /*allow_non_integral_constant_expression_p=*/false,
12080 				     &non_integral_constant_expression_p,
12081 				     /*template_p=*/false,
12082 				     /*done=*/true,
12083 				     /*address_p=*/false,
12084 				     /*template_arg_p=*/false,
12085 				     &error_msg,
12086 				     input_location);
12087 	if (error_msg)
12088 	  error (error_msg);
12089 	if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
12090 	  decl = unqualified_name_lookup_error (decl);
12091 	return decl;
12092       }
12093 
12094     case TEMPLATE_ID_EXPR:
12095       {
12096 	tree object;
12097 	tree templ = RECUR (TREE_OPERAND (t, 0));
12098 	tree targs = TREE_OPERAND (t, 1);
12099 
12100 	if (targs)
12101 	  targs = tsubst_template_args (targs, args, complain, in_decl);
12102 
12103 	if (TREE_CODE (templ) == COMPONENT_REF)
12104 	  {
12105 	    object = TREE_OPERAND (templ, 0);
12106 	    templ = TREE_OPERAND (templ, 1);
12107 	  }
12108 	else
12109 	  object = NULL_TREE;
12110 	templ = lookup_template_function (templ, targs);
12111 
12112 	if (object)
12113 	  return build3 (COMPONENT_REF, TREE_TYPE (templ),
12114 			 object, templ, NULL_TREE);
12115 	else
12116 	  return baselink_for_fns (templ);
12117       }
12118 
12119     case INDIRECT_REF:
12120       {
12121 	tree r = RECUR (TREE_OPERAND (t, 0));
12122 
12123 	if (REFERENCE_REF_P (t))
12124 	  {
12125 	    /* A type conversion to reference type will be enclosed in
12126 	       such an indirect ref, but the substitution of the cast
12127 	       will have also added such an indirect ref.  */
12128 	    if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
12129 	      r = convert_from_reference (r);
12130 	  }
12131 	else
12132 	  r = build_x_indirect_ref (r, RO_UNARY_STAR, complain);
12133 	return r;
12134       }
12135 
12136     case NOP_EXPR:
12137       return build_nop
12138 	(tsubst (TREE_TYPE (t), args, complain, in_decl),
12139 	 RECUR (TREE_OPERAND (t, 0)));
12140 
12141     case CAST_EXPR:
12142     case REINTERPRET_CAST_EXPR:
12143     case CONST_CAST_EXPR:
12144     case DYNAMIC_CAST_EXPR:
12145     case STATIC_CAST_EXPR:
12146       {
12147 	tree type;
12148 	tree op;
12149 
12150 	type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12151 	if (integral_constant_expression_p
12152 	    && !cast_valid_in_integral_constant_expression_p (type))
12153 	  {
12154             if (complain & tf_error)
12155               error ("a cast to a type other than an integral or "
12156                      "enumeration type cannot appear in a constant-expression");
12157 	    return error_mark_node;
12158 	  }
12159 
12160 	op = RECUR (TREE_OPERAND (t, 0));
12161 
12162 	switch (TREE_CODE (t))
12163 	  {
12164 	  case CAST_EXPR:
12165 	    return build_functional_cast (type, op, complain);
12166 	  case REINTERPRET_CAST_EXPR:
12167 	    return build_reinterpret_cast (type, op, complain);
12168 	  case CONST_CAST_EXPR:
12169 	    return build_const_cast (type, op, complain);
12170 	  case DYNAMIC_CAST_EXPR:
12171 	    return build_dynamic_cast (type, op, complain);
12172 	  case STATIC_CAST_EXPR:
12173 	    return build_static_cast (type, op, complain);
12174 	  default:
12175 	    gcc_unreachable ();
12176 	  }
12177       }
12178 
12179     case POSTDECREMENT_EXPR:
12180     case POSTINCREMENT_EXPR:
12181       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12182 						args, complain, in_decl);
12183       return build_x_unary_op (TREE_CODE (t), op1, complain);
12184 
12185     case PREDECREMENT_EXPR:
12186     case PREINCREMENT_EXPR:
12187     case NEGATE_EXPR:
12188     case BIT_NOT_EXPR:
12189     case ABS_EXPR:
12190     case TRUTH_NOT_EXPR:
12191     case UNARY_PLUS_EXPR:  /* Unary + */
12192     case REALPART_EXPR:
12193     case IMAGPART_EXPR:
12194       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
12195                                complain);
12196 
12197     case ADDR_EXPR:
12198       op1 = TREE_OPERAND (t, 0);
12199       if (TREE_CODE (op1) == SCOPE_REF)
12200 	op1 = tsubst_qualified_id (op1, args, complain, in_decl,
12201 				   /*done=*/true, /*address_p=*/true);
12202       else
12203 	op1 = tsubst_non_call_postfix_expression (op1, args, complain,
12204 						  in_decl);
12205       if (TREE_CODE (op1) == LABEL_DECL)
12206 	return finish_label_address_expr (DECL_NAME (op1),
12207 					  EXPR_LOCATION (op1));
12208       return build_x_unary_op (ADDR_EXPR, op1, complain);
12209 
12210     case PLUS_EXPR:
12211     case MINUS_EXPR:
12212     case MULT_EXPR:
12213     case TRUNC_DIV_EXPR:
12214     case CEIL_DIV_EXPR:
12215     case FLOOR_DIV_EXPR:
12216     case ROUND_DIV_EXPR:
12217     case EXACT_DIV_EXPR:
12218     case BIT_AND_EXPR:
12219     case BIT_IOR_EXPR:
12220     case BIT_XOR_EXPR:
12221     case TRUNC_MOD_EXPR:
12222     case FLOOR_MOD_EXPR:
12223     case TRUTH_ANDIF_EXPR:
12224     case TRUTH_ORIF_EXPR:
12225     case TRUTH_AND_EXPR:
12226     case TRUTH_OR_EXPR:
12227     case RSHIFT_EXPR:
12228     case LSHIFT_EXPR:
12229     case RROTATE_EXPR:
12230     case LROTATE_EXPR:
12231     case EQ_EXPR:
12232     case NE_EXPR:
12233     case MAX_EXPR:
12234     case MIN_EXPR:
12235     case LE_EXPR:
12236     case GE_EXPR:
12237     case LT_EXPR:
12238     case GT_EXPR:
12239     case MEMBER_REF:
12240     case DOTSTAR_EXPR:
12241       return build_x_binary_op
12242 	(TREE_CODE (t),
12243 	 RECUR (TREE_OPERAND (t, 0)),
12244 	 (TREE_NO_WARNING (TREE_OPERAND (t, 0))
12245 	  ? ERROR_MARK
12246 	  : TREE_CODE (TREE_OPERAND (t, 0))),
12247 	 RECUR (TREE_OPERAND (t, 1)),
12248 	 (TREE_NO_WARNING (TREE_OPERAND (t, 1))
12249 	  ? ERROR_MARK
12250 	  : TREE_CODE (TREE_OPERAND (t, 1))),
12251 	 /*overloaded_p=*/NULL,
12252 	 complain);
12253 
12254     case SCOPE_REF:
12255       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
12256 				  /*address_p=*/false);
12257     case ARRAY_REF:
12258       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12259 						args, complain, in_decl);
12260       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
12261 
12262     case SIZEOF_EXPR:
12263       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
12264 	return tsubst_copy (t, args, complain, in_decl);
12265       /* Fall through */
12266 
12267     case ALIGNOF_EXPR:
12268       op1 = TREE_OPERAND (t, 0);
12269       if (!args)
12270 	{
12271 	  /* When there are no ARGS, we are trying to evaluate a
12272 	     non-dependent expression from the parser.  Trying to do
12273 	     the substitutions may not work.  */
12274 	  if (!TYPE_P (op1))
12275 	    op1 = TREE_TYPE (op1);
12276 	}
12277       else
12278 	{
12279 	  ++cp_unevaluated_operand;
12280 	  ++c_inhibit_evaluation_warnings;
12281 	  op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
12282 				       /*function_p=*/false,
12283 				       /*integral_constant_expression_p=*/false);
12284 	  --cp_unevaluated_operand;
12285 	  --c_inhibit_evaluation_warnings;
12286 	}
12287       if (TYPE_P (op1))
12288 	return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t),
12289                                            complain & tf_error);
12290       else
12291 	return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t),
12292                                            complain & tf_error);
12293 
12294     case MODOP_EXPR:
12295       {
12296 	tree r = build_x_modify_expr
12297 	  (RECUR (TREE_OPERAND (t, 0)),
12298 	   TREE_CODE (TREE_OPERAND (t, 1)),
12299 	   RECUR (TREE_OPERAND (t, 2)),
12300 	   complain);
12301 	/* TREE_NO_WARNING must be set if either the expression was
12302 	   parenthesized or it uses an operator such as >>= rather
12303 	   than plain assignment.  In the former case, it was already
12304 	   set and must be copied.  In the latter case,
12305 	   build_x_modify_expr sets it and it must not be reset
12306 	   here.  */
12307 	if (TREE_NO_WARNING (t))
12308 	  TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
12309 	return r;
12310       }
12311 
12312     case ARROW_EXPR:
12313       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12314 						args, complain, in_decl);
12315       /* Remember that there was a reference to this entity.  */
12316       if (DECL_P (op1))
12317 	mark_used (op1);
12318       return build_x_arrow (op1);
12319 
12320     case NEW_EXPR:
12321       {
12322 	tree placement = RECUR (TREE_OPERAND (t, 0));
12323 	tree init = RECUR (TREE_OPERAND (t, 3));
12324 	VEC(tree,gc) *placement_vec;
12325 	VEC(tree,gc) *init_vec;
12326 	tree ret;
12327 
12328 	if (placement == NULL_TREE)
12329 	  placement_vec = NULL;
12330 	else
12331 	  {
12332 	    placement_vec = make_tree_vector ();
12333 	    for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
12334 	      VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
12335 	  }
12336 
12337 	/* If there was an initializer in the original tree, but it
12338 	   instantiated to an empty list, then we should pass a
12339 	   non-NULL empty vector to tell build_new that it was an
12340 	   empty initializer() rather than no initializer.  This can
12341 	   only happen when the initializer is a pack expansion whose
12342 	   parameter packs are of length zero.  */
12343 	if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
12344 	  init_vec = NULL;
12345 	else
12346 	  {
12347 	    init_vec = make_tree_vector ();
12348 	    if (init == void_zero_node)
12349 	      gcc_assert (init_vec != NULL);
12350 	    else
12351 	      {
12352 		for (; init != NULL_TREE; init = TREE_CHAIN (init))
12353 		  VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
12354 	      }
12355 	  }
12356 
12357 	ret = build_new (&placement_vec,
12358 			 RECUR (TREE_OPERAND (t, 1)),
12359 			 RECUR (TREE_OPERAND (t, 2)),
12360 			 &init_vec,
12361 			 NEW_EXPR_USE_GLOBAL (t),
12362 			 complain);
12363 
12364 	if (placement_vec != NULL)
12365 	  release_tree_vector (placement_vec);
12366 	if (init_vec != NULL)
12367 	  release_tree_vector (init_vec);
12368 
12369 	return ret;
12370       }
12371 
12372     case DELETE_EXPR:
12373      return delete_sanity
12374        (RECUR (TREE_OPERAND (t, 0)),
12375 	RECUR (TREE_OPERAND (t, 1)),
12376 	DELETE_EXPR_USE_VEC (t),
12377 	DELETE_EXPR_USE_GLOBAL (t));
12378 
12379     case COMPOUND_EXPR:
12380       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
12381 				    RECUR (TREE_OPERAND (t, 1)),
12382                                     complain);
12383 
12384     case CALL_EXPR:
12385       {
12386 	tree function;
12387 	VEC(tree,gc) *call_args;
12388 	unsigned int nargs, i;
12389 	bool qualified_p;
12390 	bool koenig_p;
12391 	tree ret;
12392 
12393 	function = CALL_EXPR_FN (t);
12394 	/* When we parsed the expression,  we determined whether or
12395 	   not Koenig lookup should be performed.  */
12396 	koenig_p = KOENIG_LOOKUP_P (t);
12397 	if (TREE_CODE (function) == SCOPE_REF)
12398 	  {
12399 	    qualified_p = true;
12400 	    function = tsubst_qualified_id (function, args, complain, in_decl,
12401 					    /*done=*/false,
12402 					    /*address_p=*/false);
12403 	  }
12404 	else
12405 	  {
12406 	    if (TREE_CODE (function) == COMPONENT_REF)
12407 	      {
12408 		tree op = TREE_OPERAND (function, 1);
12409 
12410 		qualified_p = (TREE_CODE (op) == SCOPE_REF
12411 			       || (BASELINK_P (op)
12412 				   && BASELINK_QUALIFIED_P (op)));
12413 	      }
12414 	    else
12415 	      qualified_p = false;
12416 
12417 	    function = tsubst_copy_and_build (function, args, complain,
12418 					      in_decl,
12419 					      !qualified_p,
12420 					      integral_constant_expression_p);
12421 
12422 	    if (BASELINK_P (function))
12423 	      qualified_p = true;
12424 	  }
12425 
12426 	nargs = call_expr_nargs (t);
12427 	call_args = make_tree_vector ();
12428 	for (i = 0; i < nargs; ++i)
12429 	  {
12430 	    tree arg = CALL_EXPR_ARG (t, i);
12431 
12432 	    if (!PACK_EXPANSION_P (arg))
12433 	      VEC_safe_push (tree, gc, call_args,
12434 			     RECUR (CALL_EXPR_ARG (t, i)));
12435 	    else
12436 	      {
12437 		/* Expand the pack expansion and push each entry onto
12438 		   CALL_ARGS.  */
12439 		arg = tsubst_pack_expansion (arg, args, complain, in_decl);
12440 		if (TREE_CODE (arg) == TREE_VEC)
12441 		  {
12442 		    unsigned int len, j;
12443 
12444 		    len = TREE_VEC_LENGTH (arg);
12445 		    for (j = 0; j < len; ++j)
12446 		      {
12447 			tree value = TREE_VEC_ELT (arg, j);
12448 			if (value != NULL_TREE)
12449 			  value = convert_from_reference (value);
12450 			VEC_safe_push (tree, gc, call_args, value);
12451 		      }
12452 		  }
12453 		else
12454 		  {
12455 		    /* A partial substitution.  Add one entry.  */
12456 		    VEC_safe_push (tree, gc, call_args, arg);
12457 		  }
12458 	      }
12459 	  }
12460 
12461 	/* We do not perform argument-dependent lookup if normal
12462 	   lookup finds a non-function, in accordance with the
12463 	   expected resolution of DR 218.  */
12464 	if (koenig_p
12465 	    && ((is_overloaded_fn (function)
12466 		 /* If lookup found a member function, the Koenig lookup is
12467 		    not appropriate, even if an unqualified-name was used
12468 		    to denote the function.  */
12469 		 && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
12470 		|| TREE_CODE (function) == IDENTIFIER_NODE)
12471 	    /* Only do this when substitution turns a dependent call
12472 	       into a non-dependent call.  */
12473 	    && type_dependent_expression_p_push (t)
12474 	    && !any_type_dependent_arguments_p (call_args))
12475 	  function = perform_koenig_lookup (function, call_args);
12476 
12477 	if (TREE_CODE (function) == IDENTIFIER_NODE)
12478 	  {
12479 	    unqualified_name_lookup_error (function);
12480 	    release_tree_vector (call_args);
12481 	    return error_mark_node;
12482 	  }
12483 
12484 	/* Remember that there was a reference to this entity.  */
12485 	if (DECL_P (function))
12486 	  mark_used (function);
12487 
12488 	if (TREE_CODE (function) == OFFSET_REF)
12489 	  ret = build_offset_ref_call_from_tree (function, &call_args);
12490 	else if (TREE_CODE (function) == COMPONENT_REF)
12491 	  {
12492 	    if (!BASELINK_P (TREE_OPERAND (function, 1)))
12493 	      ret = finish_call_expr (function, &call_args,
12494 				       /*disallow_virtual=*/false,
12495 				       /*koenig_p=*/false,
12496 				       complain);
12497 	    else
12498 	      ret = (build_new_method_call
12499 		      (TREE_OPERAND (function, 0),
12500 		       TREE_OPERAND (function, 1),
12501 		       &call_args, NULL_TREE,
12502 		       qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
12503 		       /*fn_p=*/NULL,
12504 		       complain));
12505 	  }
12506 	else
12507 	  ret = finish_call_expr (function, &call_args,
12508 				  /*disallow_virtual=*/qualified_p,
12509 				  koenig_p,
12510 				  complain);
12511 
12512 	release_tree_vector (call_args);
12513 
12514 	return ret;
12515       }
12516 
12517     case COND_EXPR:
12518       return build_x_conditional_expr
12519 	(RECUR (TREE_OPERAND (t, 0)),
12520 	 RECUR (TREE_OPERAND (t, 1)),
12521 	 RECUR (TREE_OPERAND (t, 2)),
12522          complain);
12523 
12524     case PSEUDO_DTOR_EXPR:
12525       return finish_pseudo_destructor_expr
12526 	(RECUR (TREE_OPERAND (t, 0)),
12527 	 RECUR (TREE_OPERAND (t, 1)),
12528 	 RECUR (TREE_OPERAND (t, 2)));
12529 
12530     case TREE_LIST:
12531       {
12532 	tree purpose, value, chain;
12533 
12534 	if (t == void_list_node)
12535 	  return t;
12536 
12537         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
12538             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
12539           {
12540             /* We have pack expansions, so expand those and
12541                create a new list out of it.  */
12542             tree purposevec = NULL_TREE;
12543             tree valuevec = NULL_TREE;
12544             tree chain;
12545             int i, len = -1;
12546 
12547             /* Expand the argument expressions.  */
12548             if (TREE_PURPOSE (t))
12549               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
12550                                                  complain, in_decl);
12551             if (TREE_VALUE (t))
12552               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
12553                                                complain, in_decl);
12554 
12555             /* Build the rest of the list.  */
12556             chain = TREE_CHAIN (t);
12557             if (chain && chain != void_type_node)
12558               chain = RECUR (chain);
12559 
12560             /* Determine the number of arguments.  */
12561             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
12562               {
12563                 len = TREE_VEC_LENGTH (purposevec);
12564                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
12565               }
12566             else if (TREE_CODE (valuevec) == TREE_VEC)
12567               len = TREE_VEC_LENGTH (valuevec);
12568             else
12569               {
12570                 /* Since we only performed a partial substitution into
12571                    the argument pack, we only return a single list
12572                    node.  */
12573                 if (purposevec == TREE_PURPOSE (t)
12574                     && valuevec == TREE_VALUE (t)
12575                     && chain == TREE_CHAIN (t))
12576                   return t;
12577 
12578                 return tree_cons (purposevec, valuevec, chain);
12579               }
12580 
12581             /* Convert the argument vectors into a TREE_LIST */
12582             i = len;
12583             while (i > 0)
12584               {
12585                 /* Grab the Ith values.  */
12586                 i--;
12587                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i)
12588 		                     : NULL_TREE;
12589                 value
12590 		  = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i))
12591                              : NULL_TREE;
12592 
12593                 /* Build the list (backwards).  */
12594                 chain = tree_cons (purpose, value, chain);
12595               }
12596 
12597             return chain;
12598           }
12599 
12600 	purpose = TREE_PURPOSE (t);
12601 	if (purpose)
12602 	  purpose = RECUR (purpose);
12603 	value = TREE_VALUE (t);
12604 	if (value)
12605 	  value = RECUR (value);
12606 	chain = TREE_CHAIN (t);
12607 	if (chain && chain != void_type_node)
12608 	  chain = RECUR (chain);
12609 	if (purpose == TREE_PURPOSE (t)
12610 	    && value == TREE_VALUE (t)
12611 	    && chain == TREE_CHAIN (t))
12612 	  return t;
12613 	return tree_cons (purpose, value, chain);
12614       }
12615 
12616     case COMPONENT_REF:
12617       {
12618 	tree object;
12619 	tree object_type;
12620 	tree member;
12621 
12622 	object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12623 						     args, complain, in_decl);
12624 	/* Remember that there was a reference to this entity.  */
12625 	if (DECL_P (object))
12626 	  mark_used (object);
12627 	object_type = TREE_TYPE (object);
12628 
12629 	member = TREE_OPERAND (t, 1);
12630 	if (BASELINK_P (member))
12631 	  member = tsubst_baselink (member,
12632 				    non_reference (TREE_TYPE (object)),
12633 				    args, complain, in_decl);
12634 	else
12635 	  member = tsubst_copy (member, args, complain, in_decl);
12636 	if (member == error_mark_node)
12637 	  return error_mark_node;
12638 
12639 	if (object_type && !CLASS_TYPE_P (object_type))
12640 	  {
12641 	    if (SCALAR_TYPE_P (object_type))
12642 	      {
12643 		tree s = NULL_TREE;
12644 		tree dtor = member;
12645 
12646 		if (TREE_CODE (dtor) == SCOPE_REF)
12647 		  {
12648 		    s = TREE_OPERAND (dtor, 0);
12649 		    dtor = TREE_OPERAND (dtor, 1);
12650 		  }
12651 		if (TREE_CODE (dtor) == BIT_NOT_EXPR)
12652 		  {
12653 		    dtor = TREE_OPERAND (dtor, 0);
12654 		    if (TYPE_P (dtor))
12655 		      return finish_pseudo_destructor_expr (object, s, dtor);
12656 		  }
12657 	      }
12658 	  }
12659 	else if (TREE_CODE (member) == SCOPE_REF
12660 		 && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
12661 	  {
12662 	    tree tmpl;
12663 	    tree args;
12664 
12665 	    /* Lookup the template functions now that we know what the
12666 	       scope is.  */
12667 	    tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
12668 	    args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
12669 	    member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
12670 					    /*is_type_p=*/false,
12671 					    /*complain=*/false);
12672 	    if (BASELINK_P (member))
12673 	      {
12674 		BASELINK_FUNCTIONS (member)
12675 		  = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
12676 			      args);
12677 		member = (adjust_result_of_qualified_name_lookup
12678 			  (member, BINFO_TYPE (BASELINK_BINFO (member)),
12679 			   object_type));
12680 	      }
12681 	    else
12682 	      {
12683 		qualified_name_lookup_error (object_type, tmpl, member,
12684 					     input_location);
12685 		return error_mark_node;
12686 	      }
12687 	  }
12688 	else if (TREE_CODE (member) == SCOPE_REF
12689 		 && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
12690 		 && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
12691 	  {
12692 	    if (complain & tf_error)
12693 	      {
12694 		if (TYPE_P (TREE_OPERAND (member, 0)))
12695 		  error ("%qT is not a class or namespace",
12696 			 TREE_OPERAND (member, 0));
12697 		else
12698 		  error ("%qD is not a class or namespace",
12699 			 TREE_OPERAND (member, 0));
12700 	      }
12701 	    return error_mark_node;
12702 	  }
12703 	else if (TREE_CODE (member) == FIELD_DECL)
12704 	  return finish_non_static_data_member (member, object, NULL_TREE);
12705 
12706 	return finish_class_member_access_expr (object, member,
12707 						/*template_p=*/false,
12708 						complain);
12709       }
12710 
12711     case THROW_EXPR:
12712       return build_throw
12713 	(RECUR (TREE_OPERAND (t, 0)));
12714 
12715     case CONSTRUCTOR:
12716       {
12717 	VEC(constructor_elt,gc) *n;
12718 	constructor_elt *ce;
12719 	unsigned HOST_WIDE_INT idx;
12720 	tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12721 	bool process_index_p;
12722         int newlen;
12723         bool need_copy_p = false;
12724 	tree r;
12725 
12726 	if (type == error_mark_node)
12727 	  return error_mark_node;
12728 
12729 	/* digest_init will do the wrong thing if we let it.  */
12730 	if (type && TYPE_PTRMEMFUNC_P (type))
12731 	  return t;
12732 
12733 	/* We do not want to process the index of aggregate
12734 	   initializers as they are identifier nodes which will be
12735 	   looked up by digest_init.  */
12736 	process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
12737 
12738 	n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
12739         newlen = VEC_length (constructor_elt, n);
12740 	for (idx = 0; VEC_iterate (constructor_elt, n, idx, ce); idx++)
12741 	  {
12742 	    if (ce->index && process_index_p)
12743 	      ce->index = RECUR (ce->index);
12744 
12745             if (PACK_EXPANSION_P (ce->value))
12746               {
12747                 /* Substitute into the pack expansion.  */
12748                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
12749                                                   in_decl);
12750 
12751 		if (ce->value == error_mark_node)
12752 		  ;
12753 		else if (TREE_VEC_LENGTH (ce->value) == 1)
12754                   /* Just move the argument into place.  */
12755                   ce->value = TREE_VEC_ELT (ce->value, 0);
12756                 else
12757                   {
12758                     /* Update the length of the final CONSTRUCTOR
12759                        arguments vector, and note that we will need to
12760                        copy.*/
12761                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
12762                     need_copy_p = true;
12763                   }
12764               }
12765             else
12766               ce->value = RECUR (ce->value);
12767 	  }
12768 
12769         if (need_copy_p)
12770           {
12771             VEC(constructor_elt,gc) *old_n = n;
12772 
12773             n = VEC_alloc (constructor_elt, gc, newlen);
12774             for (idx = 0; VEC_iterate (constructor_elt, old_n, idx, ce);
12775                  idx++)
12776               {
12777                 if (TREE_CODE (ce->value) == TREE_VEC)
12778                   {
12779                     int i, len = TREE_VEC_LENGTH (ce->value);
12780                     for (i = 0; i < len; ++i)
12781                       CONSTRUCTOR_APPEND_ELT (n, 0,
12782                                               TREE_VEC_ELT (ce->value, i));
12783                   }
12784                 else
12785                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
12786               }
12787           }
12788 
12789 	r = build_constructor (init_list_type_node, n);
12790 	CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
12791 
12792 	if (TREE_HAS_CONSTRUCTOR (t))
12793 	  return finish_compound_literal (type, r);
12794 
12795 	return r;
12796       }
12797 
12798     case TYPEID_EXPR:
12799       {
12800 	tree operand_0 = RECUR (TREE_OPERAND (t, 0));
12801 	if (TYPE_P (operand_0))
12802 	  return get_typeid (operand_0);
12803 	return build_typeid (operand_0);
12804       }
12805 
12806     case VAR_DECL:
12807       if (!args)
12808 	return t;
12809       /* Fall through */
12810 
12811     case PARM_DECL:
12812       {
12813 	tree r = tsubst_copy (t, args, complain, in_decl);
12814 
12815 	if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
12816 	  /* If the original type was a reference, we'll be wrapped in
12817 	     the appropriate INDIRECT_REF.  */
12818 	  r = convert_from_reference (r);
12819 	return r;
12820       }
12821 
12822     case VA_ARG_EXPR:
12823       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
12824 			     tsubst_copy (TREE_TYPE (t), args, complain,
12825 					  in_decl));
12826 
12827     case OFFSETOF_EXPR:
12828       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
12829 
12830     case TRAIT_EXPR:
12831       {
12832 	tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
12833 				  complain, in_decl);
12834 
12835 	tree type2 = TRAIT_EXPR_TYPE2 (t);
12836 	if (type2)
12837 	  type2 = tsubst_copy (type2, args, complain, in_decl);
12838 
12839 	return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
12840       }
12841 
12842     case STMT_EXPR:
12843       {
12844 	tree old_stmt_expr = cur_stmt_expr;
12845 	tree stmt_expr = begin_stmt_expr ();
12846 
12847 	cur_stmt_expr = stmt_expr;
12848 	tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
12849 		     integral_constant_expression_p);
12850 	stmt_expr = finish_stmt_expr (stmt_expr, false);
12851 	cur_stmt_expr = old_stmt_expr;
12852 
12853 	/* If the resulting list of expression statement is empty,
12854 	   fold it further into void_zero_node.  */
12855 	if (empty_expr_stmt_p (stmt_expr))
12856 	  stmt_expr = void_zero_node;
12857 
12858 	return stmt_expr;
12859       }
12860 
12861     case CONST_DECL:
12862       t = tsubst_copy (t, args, complain, in_decl);
12863       /* As in finish_id_expression, we resolve enumeration constants
12864 	 to their underlying values.  */
12865       if (TREE_CODE (t) == CONST_DECL)
12866 	{
12867 	  used_types_insert (TREE_TYPE (t));
12868 	  return DECL_INITIAL (t);
12869 	}
12870       return t;
12871 
12872     case LAMBDA_EXPR:
12873       {
12874 	tree r = build_lambda_expr ();
12875 
12876 	tree type = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
12877 	TREE_TYPE (r) = type;
12878 	CLASSTYPE_LAMBDA_EXPR (type) = r;
12879 
12880 	LAMBDA_EXPR_LOCATION (r)
12881 	  = LAMBDA_EXPR_LOCATION (t);
12882 	LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
12883 	  = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
12884 	LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
12885 	LAMBDA_EXPR_DISCRIMINATOR (r)
12886 	  = (LAMBDA_EXPR_DISCRIMINATOR (t));
12887 	LAMBDA_EXPR_CAPTURE_LIST (r)
12888 	  = RECUR (LAMBDA_EXPR_CAPTURE_LIST (t));
12889 	LAMBDA_EXPR_THIS_CAPTURE (r)
12890 	  = RECUR (LAMBDA_EXPR_THIS_CAPTURE (t));
12891 	LAMBDA_EXPR_EXTRA_SCOPE (r)
12892 	  = RECUR (LAMBDA_EXPR_EXTRA_SCOPE (t));
12893 
12894 	/* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
12895 	determine_visibility (TYPE_NAME (type));
12896 	/* Now that we know visibility, instantiate the type so we have a
12897 	   declaration of the op() for later calls to lambda_function.  */
12898 	complete_type (type);
12899 
12900 	type = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
12901 	if (type)
12902 	  apply_lambda_return_type (r, type);
12903 
12904 	return build_lambda_object (r);
12905       }
12906 
12907     default:
12908       /* Handle Objective-C++ constructs, if appropriate.  */
12909       {
12910 	tree subst
12911 	  = objcp_tsubst_copy_and_build (t, args, complain,
12912 					 in_decl, /*function_p=*/false);
12913 	if (subst)
12914 	  return subst;
12915       }
12916       return tsubst_copy (t, args, complain, in_decl);
12917     }
12918 
12919 #undef RECUR
12920 }
12921 
12922 /* Verify that the instantiated ARGS are valid. For type arguments,
12923    make sure that the type's linkage is ok. For non-type arguments,
12924    make sure they are constants if they are integral or enumerations.
12925    Emit an error under control of COMPLAIN, and return TRUE on error.  */
12926 
12927 static bool
12928 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
12929 {
12930   if (ARGUMENT_PACK_P (t))
12931     {
12932       tree vec = ARGUMENT_PACK_ARGS (t);
12933       int len = TREE_VEC_LENGTH (vec);
12934       bool result = false;
12935       int i;
12936 
12937       for (i = 0; i < len; ++i)
12938 	if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
12939 	  result = true;
12940       return result;
12941     }
12942   else if (TYPE_P (t))
12943     {
12944       /* [basic.link]: A name with no linkage (notably, the name
12945 	 of a class or enumeration declared in a local scope)
12946 	 shall not be used to declare an entity with linkage.
12947 	 This implies that names with no linkage cannot be used as
12948 	 template arguments
12949 
12950 	 DR 757 relaxes this restriction for C++0x.  */
12951       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
12952 		 : no_linkage_check (t, /*relaxed_p=*/false));
12953 
12954       if (nt)
12955 	{
12956 	  /* DR 488 makes use of a type with no linkage cause
12957 	     type deduction to fail.  */
12958 	  if (complain & tf_error)
12959 	    {
12960 	      if (TYPE_ANONYMOUS_P (nt))
12961 		error ("%qT is/uses anonymous type", t);
12962 	      else
12963 		error ("template argument for %qD uses local type %qT",
12964 		       tmpl, t);
12965 	    }
12966 	  return true;
12967 	}
12968       /* In order to avoid all sorts of complications, we do not
12969 	 allow variably-modified types as template arguments.  */
12970       else if (variably_modified_type_p (t, NULL_TREE))
12971 	{
12972 	  if (complain & tf_error)
12973 	    error ("%qT is a variably modified type", t);
12974 	  return true;
12975 	}
12976     }
12977   /* A non-type argument of integral or enumerated type must be a
12978      constant.  */
12979   else if (TREE_TYPE (t)
12980 	   && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
12981 	   && !TREE_CONSTANT (t))
12982     {
12983       if (complain & tf_error)
12984 	error ("integral expression %qE is not constant", t);
12985       return true;
12986     }
12987   return false;
12988 }
12989 
12990 static bool
12991 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
12992 {
12993   int ix, len = DECL_NTPARMS (tmpl);
12994   bool result = false;
12995 
12996   for (ix = 0; ix != len; ix++)
12997     {
12998       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
12999 	result = true;
13000     }
13001   if (result && (complain & tf_error))
13002     error ("  trying to instantiate %qD", tmpl);
13003   return result;
13004 }
13005 
13006 /* Instantiate the indicated variable or function template TMPL with
13007    the template arguments in TARG_PTR.  */
13008 
13009 tree
13010 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
13011 {
13012   tree targ_ptr = orig_args;
13013   tree fndecl;
13014   tree gen_tmpl;
13015   tree spec;
13016   HOST_WIDE_INT saved_processing_template_decl;
13017 
13018   if (tmpl == error_mark_node)
13019     return error_mark_node;
13020 
13021   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
13022 
13023   /* If this function is a clone, handle it specially.  */
13024   if (DECL_CLONED_FUNCTION_P (tmpl))
13025     {
13026       tree spec;
13027       tree clone;
13028 
13029       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
13030 	 DECL_CLONED_FUNCTION.  */
13031       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
13032 				   targ_ptr, complain);
13033       if (spec == error_mark_node)
13034 	return error_mark_node;
13035 
13036       /* Look for the clone.  */
13037       FOR_EACH_CLONE (clone, spec)
13038 	if (DECL_NAME (clone) == DECL_NAME (tmpl))
13039 	  return clone;
13040       /* We should always have found the clone by now.  */
13041       gcc_unreachable ();
13042       return NULL_TREE;
13043     }
13044 
13045   /* Check to see if we already have this specialization.  */
13046   gen_tmpl = most_general_template (tmpl);
13047   if (tmpl != gen_tmpl)
13048     /* The TMPL is a partial instantiation.  To get a full set of
13049        arguments we must add the arguments used to perform the
13050        partial instantiation.  */
13051     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
13052 					    targ_ptr);
13053 
13054   /* It would be nice to avoid hashing here and then again in tsubst_decl,
13055      but it doesn't seem to be on the hot path.  */
13056   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
13057 
13058   gcc_assert (tmpl == gen_tmpl
13059 	      || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
13060 		  == spec)
13061 	      || fndecl == NULL_TREE);
13062 
13063   if (spec != NULL_TREE)
13064     return spec;
13065 
13066   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
13067 			       complain))
13068     return error_mark_node;
13069 
13070   /* We are building a FUNCTION_DECL, during which the access of its
13071      parameters and return types have to be checked.  However this
13072      FUNCTION_DECL which is the desired context for access checking
13073      is not built yet.  We solve this chicken-and-egg problem by
13074      deferring all checks until we have the FUNCTION_DECL.  */
13075   push_deferring_access_checks (dk_deferred);
13076 
13077   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
13078      (because, for example, we have encountered a non-dependent
13079      function call in the body of a template function and must now
13080      determine which of several overloaded functions will be called),
13081      within the instantiation itself we are not processing a
13082      template.  */
13083   saved_processing_template_decl = processing_template_decl;
13084   processing_template_decl = 0;
13085   /* Substitute template parameters to obtain the specialization.  */
13086   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
13087 		   targ_ptr, complain, gen_tmpl);
13088   processing_template_decl = saved_processing_template_decl;
13089   if (fndecl == error_mark_node)
13090     return error_mark_node;
13091 
13092   /* Now we know the specialization, compute access previously
13093      deferred.  */
13094   push_access_scope (fndecl);
13095 
13096   /* Some typedefs referenced from within the template code need to be access
13097      checked at template instantiation time, i.e now. These types were
13098      added to the template at parsing time. Let's get those and perfom
13099      the acces checks then.  */
13100   perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
13101   perform_deferred_access_checks ();
13102   pop_access_scope (fndecl);
13103   pop_deferring_access_checks ();
13104 
13105   /* The DECL_TI_TEMPLATE should always be the immediate parent
13106      template, not the most general template.  */
13107   DECL_TI_TEMPLATE (fndecl) = tmpl;
13108 
13109   /* If we've just instantiated the main entry point for a function,
13110      instantiate all the alternate entry points as well.  We do this
13111      by cloning the instantiation of the main entry point, not by
13112      instantiating the template clones.  */
13113   if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
13114     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
13115 
13116   return fndecl;
13117 }
13118 
13119 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
13120    NARGS elements of the arguments that are being used when calling
13121    it.  TARGS is a vector into which the deduced template arguments
13122    are placed.
13123 
13124    Return zero for success, 2 for an incomplete match that doesn't resolve
13125    all the types, and 1 for complete failure.  An error message will be
13126    printed only for an incomplete match.
13127 
13128    If FN is a conversion operator, or we are trying to produce a specific
13129    specialization, RETURN_TYPE is the return type desired.
13130 
13131    The EXPLICIT_TARGS are explicit template arguments provided via a
13132    template-id.
13133 
13134    The parameter STRICT is one of:
13135 
13136    DEDUCE_CALL:
13137      We are deducing arguments for a function call, as in
13138      [temp.deduct.call].
13139 
13140    DEDUCE_CONV:
13141      We are deducing arguments for a conversion function, as in
13142      [temp.deduct.conv].
13143 
13144    DEDUCE_EXACT:
13145      We are deducing arguments when doing an explicit instantiation
13146      as in [temp.explicit], when determining an explicit specialization
13147      as in [temp.expl.spec], or when taking the address of a function
13148      template, as in [temp.deduct.funcaddr].  */
13149 
13150 int
13151 fn_type_unification (tree fn,
13152 		     tree explicit_targs,
13153 		     tree targs,
13154 		     const tree *args,
13155 		     unsigned int nargs,
13156 		     tree return_type,
13157 		     unification_kind_t strict,
13158 		     int flags)
13159 {
13160   tree parms;
13161   tree fntype;
13162   int result;
13163   bool incomplete_argument_packs_p = false;
13164 
13165   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
13166 
13167   fntype = TREE_TYPE (fn);
13168   if (explicit_targs)
13169     {
13170       /* [temp.deduct]
13171 
13172 	 The specified template arguments must match the template
13173 	 parameters in kind (i.e., type, nontype, template), and there
13174 	 must not be more arguments than there are parameters;
13175 	 otherwise type deduction fails.
13176 
13177 	 Nontype arguments must match the types of the corresponding
13178 	 nontype template parameters, or must be convertible to the
13179 	 types of the corresponding nontype parameters as specified in
13180 	 _temp.arg.nontype_, otherwise type deduction fails.
13181 
13182 	 All references in the function type of the function template
13183 	 to the corresponding template parameters are replaced by the
13184 	 specified template argument values.  If a substitution in a
13185 	 template parameter or in the function type of the function
13186 	 template results in an invalid type, type deduction fails.  */
13187       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
13188       int i, len = TREE_VEC_LENGTH (tparms);
13189       tree converted_args;
13190       bool incomplete = false;
13191 
13192       if (explicit_targs == error_mark_node)
13193 	return 1;
13194 
13195       converted_args
13196 	= (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
13197 				  /*require_all_args=*/false,
13198 				  /*use_default_args=*/false));
13199       if (converted_args == error_mark_node)
13200 	return 1;
13201 
13202       /* Substitute the explicit args into the function type.  This is
13203 	 necessary so that, for instance, explicitly declared function
13204 	 arguments can match null pointed constants.  If we were given
13205 	 an incomplete set of explicit args, we must not do semantic
13206 	 processing during substitution as we could create partial
13207 	 instantiations.  */
13208       for (i = 0; i < len; i++)
13209         {
13210           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13211           bool parameter_pack = false;
13212 
13213           /* Dig out the actual parm.  */
13214           if (TREE_CODE (parm) == TYPE_DECL
13215               || TREE_CODE (parm) == TEMPLATE_DECL)
13216             {
13217               parm = TREE_TYPE (parm);
13218               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
13219             }
13220           else if (TREE_CODE (parm) == PARM_DECL)
13221             {
13222               parm = DECL_INITIAL (parm);
13223               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
13224             }
13225 
13226           if (parameter_pack)
13227             {
13228               int level, idx;
13229               tree targ;
13230               template_parm_level_and_index (parm, &level, &idx);
13231 
13232               /* Mark the argument pack as "incomplete". We could
13233                  still deduce more arguments during unification.  */
13234               targ = TMPL_ARG (converted_args, level, idx);
13235               if (targ)
13236                 {
13237                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
13238                   ARGUMENT_PACK_EXPLICIT_ARGS (targ)
13239                     = ARGUMENT_PACK_ARGS (targ);
13240                 }
13241 
13242               /* We have some incomplete argument packs.  */
13243               incomplete_argument_packs_p = true;
13244             }
13245         }
13246 
13247       if (incomplete_argument_packs_p)
13248         /* Any substitution is guaranteed to be incomplete if there
13249            are incomplete argument packs, because we can still deduce
13250            more arguments.  */
13251         incomplete = 1;
13252       else
13253         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
13254 
13255       processing_template_decl += incomplete;
13256       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
13257       processing_template_decl -= incomplete;
13258 
13259       if (fntype == error_mark_node)
13260 	return 1;
13261 
13262       /* Place the explicitly specified arguments in TARGS.  */
13263       for (i = NUM_TMPL_ARGS (converted_args); i--;)
13264 	TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
13265     }
13266 
13267   /* Never do unification on the 'this' parameter.  */
13268   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
13269 
13270   if (return_type)
13271     {
13272       tree *new_args;
13273 
13274       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
13275       new_args = XALLOCAVEC (tree, nargs + 1);
13276       new_args[0] = return_type;
13277       memcpy (new_args + 1, args, nargs * sizeof (tree));
13278       args = new_args;
13279       ++nargs;
13280     }
13281 
13282   /* We allow incomplete unification without an error message here
13283      because the standard doesn't seem to explicitly prohibit it.  Our
13284      callers must be ready to deal with unification failures in any
13285      event.  */
13286   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
13287 				  targs, parms, args, nargs, /*subr=*/0,
13288 				  strict, flags);
13289 
13290   if (result == 0 && incomplete_argument_packs_p)
13291     {
13292       int i, len = NUM_TMPL_ARGS (targs);
13293 
13294       /* Clear the "incomplete" flags on all argument packs.  */
13295       for (i = 0; i < len; i++)
13296         {
13297           tree arg = TREE_VEC_ELT (targs, i);
13298           if (ARGUMENT_PACK_P (arg))
13299             {
13300               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
13301               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
13302             }
13303         }
13304     }
13305 
13306   /* Now that we have bindings for all of the template arguments,
13307      ensure that the arguments deduced for the template template
13308      parameters have compatible template parameter lists.  We cannot
13309      check this property before we have deduced all template
13310      arguments, because the template parameter types of a template
13311      template parameter might depend on prior template parameters
13312      deduced after the template template parameter.  The following
13313      ill-formed example illustrates this issue:
13314 
13315        template<typename T, template<T> class C> void f(C<5>, T);
13316 
13317        template<int N> struct X {};
13318 
13319        void g() {
13320          f(X<5>(), 5l); // error: template argument deduction fails
13321        }
13322 
13323      The template parameter list of 'C' depends on the template type
13324      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
13325      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
13326      time that we deduce 'C'.  */
13327   if (result == 0
13328       && !template_template_parm_bindings_ok_p
13329            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
13330     return 1;
13331 
13332   if (result == 0)
13333     /* All is well so far.  Now, check:
13334 
13335        [temp.deduct]
13336 
13337        When all template arguments have been deduced, all uses of
13338        template parameters in nondeduced contexts are replaced with
13339        the corresponding deduced argument values.  If the
13340        substitution results in an invalid type, as described above,
13341        type deduction fails.  */
13342     {
13343       tree substed = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
13344       if (substed == error_mark_node)
13345 	return 1;
13346 
13347       /* If we're looking for an exact match, check that what we got
13348 	 is indeed an exact match.  It might not be if some template
13349 	 parameters are used in non-deduced contexts.  */
13350       if (strict == DEDUCE_EXACT)
13351 	{
13352 	  unsigned int i;
13353 
13354 	  tree sarg
13355 	    = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
13356 	  if (return_type)
13357 	    sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
13358 	  for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
13359 	    if (!same_type_p (args[i], TREE_VALUE (sarg)))
13360 	      return 1;
13361 	}
13362     }
13363 
13364   return result;
13365 }
13366 
13367 /* Adjust types before performing type deduction, as described in
13368    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
13369    sections are symmetric.  PARM is the type of a function parameter
13370    or the return type of the conversion function.  ARG is the type of
13371    the argument passed to the call, or the type of the value
13372    initialized with the result of the conversion function.
13373    ARG_EXPR is the original argument expression, which may be null.  */
13374 
13375 static int
13376 maybe_adjust_types_for_deduction (unification_kind_t strict,
13377 				  tree* parm,
13378 				  tree* arg,
13379 				  tree arg_expr)
13380 {
13381   int result = 0;
13382 
13383   switch (strict)
13384     {
13385     case DEDUCE_CALL:
13386       break;
13387 
13388     case DEDUCE_CONV:
13389       {
13390 	/* Swap PARM and ARG throughout the remainder of this
13391 	   function; the handling is precisely symmetric since PARM
13392 	   will initialize ARG rather than vice versa.  */
13393 	tree* temp = parm;
13394 	parm = arg;
13395 	arg = temp;
13396 	break;
13397       }
13398 
13399     case DEDUCE_EXACT:
13400       /* Core issue #873: Do the DR606 thing (see below) for these cases,
13401 	 too, but here handle it by stripping the reference from PARM
13402 	 rather than by adding it to ARG.  */
13403       if (TREE_CODE (*parm) == REFERENCE_TYPE
13404 	  && TYPE_REF_IS_RVALUE (*parm)
13405 	  && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13406 	  && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13407 	  && TREE_CODE (*arg) == REFERENCE_TYPE
13408 	  && !TYPE_REF_IS_RVALUE (*arg))
13409 	*parm = TREE_TYPE (*parm);
13410       /* Nothing else to do in this case.  */
13411       return 0;
13412 
13413     default:
13414       gcc_unreachable ();
13415     }
13416 
13417   if (TREE_CODE (*parm) != REFERENCE_TYPE)
13418     {
13419       /* [temp.deduct.call]
13420 
13421 	 If P is not a reference type:
13422 
13423 	 --If A is an array type, the pointer type produced by the
13424 	 array-to-pointer standard conversion (_conv.array_) is
13425 	 used in place of A for type deduction; otherwise,
13426 
13427 	 --If A is a function type, the pointer type produced by
13428 	 the function-to-pointer standard conversion
13429 	 (_conv.func_) is used in place of A for type deduction;
13430 	 otherwise,
13431 
13432 	 --If A is a cv-qualified type, the top level
13433 	 cv-qualifiers of A's type are ignored for type
13434 	 deduction.  */
13435       if (TREE_CODE (*arg) == ARRAY_TYPE)
13436 	*arg = build_pointer_type (TREE_TYPE (*arg));
13437       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
13438 	*arg = build_pointer_type (*arg);
13439       else
13440 	*arg = TYPE_MAIN_VARIANT (*arg);
13441     }
13442 
13443   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
13444      of the form T&&, where T is a template parameter, and the argument
13445      is an lvalue, T is deduced as A& */
13446   if (TREE_CODE (*parm) == REFERENCE_TYPE
13447       && TYPE_REF_IS_RVALUE (*parm)
13448       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13449       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13450       && arg_expr && real_lvalue_p (arg_expr))
13451     *arg = build_reference_type (*arg);
13452 
13453   /* [temp.deduct.call]
13454 
13455      If P is a cv-qualified type, the top level cv-qualifiers
13456      of P's type are ignored for type deduction.  If P is a
13457      reference type, the type referred to by P is used for
13458      type deduction.  */
13459   *parm = TYPE_MAIN_VARIANT (*parm);
13460   if (TREE_CODE (*parm) == REFERENCE_TYPE)
13461     {
13462       *parm = TREE_TYPE (*parm);
13463       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
13464     }
13465 
13466   /* DR 322. For conversion deduction, remove a reference type on parm
13467      too (which has been swapped into ARG).  */
13468   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
13469     *arg = TREE_TYPE (*arg);
13470 
13471   return result;
13472 }
13473 
13474 /* Most parms like fn_type_unification.
13475 
13476    If SUBR is 1, we're being called recursively (to unify the
13477    arguments of a function or method parameter of a function
13478    template). */
13479 
13480 static int
13481 type_unification_real (tree tparms,
13482 		       tree targs,
13483 		       tree xparms,
13484 		       const tree *xargs,
13485 		       unsigned int xnargs,
13486 		       int subr,
13487 		       unification_kind_t strict,
13488 		       int flags)
13489 {
13490   tree parm, arg, arg_expr;
13491   int i;
13492   int ntparms = TREE_VEC_LENGTH (tparms);
13493   int sub_strict;
13494   int saw_undeduced = 0;
13495   tree parms;
13496   const tree *args;
13497   unsigned int nargs;
13498   unsigned int ia;
13499 
13500   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
13501   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
13502   gcc_assert (ntparms > 0);
13503 
13504   /* Reset the number of non-defaulted template arguments contained
13505      in in TARGS.  */
13506   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
13507 
13508   switch (strict)
13509     {
13510     case DEDUCE_CALL:
13511       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
13512 		    | UNIFY_ALLOW_DERIVED);
13513       break;
13514 
13515     case DEDUCE_CONV:
13516       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
13517       break;
13518 
13519     case DEDUCE_EXACT:
13520       sub_strict = UNIFY_ALLOW_NONE;
13521       break;
13522 
13523     default:
13524       gcc_unreachable ();
13525     }
13526 
13527  again:
13528   parms = xparms;
13529   args = xargs;
13530   nargs = xnargs;
13531 
13532   ia = 0;
13533   while (parms && parms != void_list_node
13534 	 && ia < nargs)
13535     {
13536       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13537         break;
13538 
13539       parm = TREE_VALUE (parms);
13540       parms = TREE_CHAIN (parms);
13541       arg = args[ia];
13542       ++ia;
13543       arg_expr = NULL;
13544 
13545       if (arg == error_mark_node)
13546 	return 1;
13547       if (arg == unknown_type_node)
13548 	/* We can't deduce anything from this, but we might get all the
13549 	   template args from other function args.  */
13550 	continue;
13551 
13552       /* Conversions will be performed on a function argument that
13553 	 corresponds with a function parameter that contains only
13554 	 non-deducible template parameters and explicitly specified
13555 	 template parameters.  */
13556       if (!uses_template_parms (parm))
13557 	{
13558 	  tree type;
13559 
13560 	  if (!TYPE_P (arg))
13561 	    type = TREE_TYPE (arg);
13562 	  else
13563 	    type = arg;
13564 
13565 	  if (same_type_p (parm, type))
13566 	    continue;
13567 	  if (strict != DEDUCE_EXACT
13568 	      && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
13569 				  flags))
13570 	    continue;
13571 
13572 	  return 1;
13573 	}
13574 
13575       if (!TYPE_P (arg))
13576 	{
13577 	  gcc_assert (TREE_TYPE (arg) != NULL_TREE);
13578 	  if (type_unknown_p (arg))
13579 	    {
13580 	      /* [temp.deduct.type]
13581 
13582 	         A template-argument can be deduced from a pointer to
13583 		 function or pointer to member function argument if
13584 		 the set of overloaded functions does not contain
13585 		 function templates and at most one of a set of
13586 		 overloaded functions provides a unique match.  */
13587 	      if (resolve_overloaded_unification
13588 		  (tparms, targs, parm, arg, strict, sub_strict))
13589 		continue;
13590 
13591 	      return 1;
13592 	    }
13593 	  arg_expr = arg;
13594 	  arg = unlowered_expr_type (arg);
13595 	  if (arg == error_mark_node)
13596 	    return 1;
13597 	}
13598 
13599       {
13600 	int arg_strict = sub_strict;
13601 
13602 	if (!subr)
13603 	  arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
13604 							  arg_expr);
13605 
13606 	if (arg == init_list_type_node && arg_expr)
13607 	  arg = arg_expr;
13608 	if (unify (tparms, targs, parm, arg, arg_strict))
13609 	  return 1;
13610       }
13611     }
13612 
13613 
13614   if (parms
13615       && parms != void_list_node
13616       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13617     {
13618       /* Unify the remaining arguments with the pack expansion type.  */
13619       tree argvec;
13620       tree parmvec = make_tree_vec (1);
13621 
13622       /* Allocate a TREE_VEC and copy in all of the arguments */
13623       argvec = make_tree_vec (nargs - ia);
13624       for (i = 0; ia < nargs; ++ia, ++i)
13625 	TREE_VEC_ELT (argvec, i) = args[ia];
13626 
13627       /* Copy the parameter into parmvec.  */
13628       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
13629       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
13630                                 /*call_args_p=*/true, /*subr=*/subr))
13631         return 1;
13632 
13633       /* Advance to the end of the list of parameters.  */
13634       parms = TREE_CHAIN (parms);
13635     }
13636 
13637   /* Fail if we've reached the end of the parm list, and more args
13638      are present, and the parm list isn't variadic.  */
13639   if (ia < nargs && parms == void_list_node)
13640     return 1;
13641   /* Fail if parms are left and they don't have default values.  */
13642   if (parms && parms != void_list_node
13643       && TREE_PURPOSE (parms) == NULL_TREE)
13644     return 1;
13645 
13646   if (!subr)
13647     for (i = 0; i < ntparms; i++)
13648       if (!TREE_VEC_ELT (targs, i))
13649 	{
13650 	  tree tparm;
13651 
13652           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
13653             continue;
13654 
13655           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13656 
13657 	  /* If this is an undeduced nontype parameter that depends on
13658 	     a type parameter, try another pass; its type may have been
13659 	     deduced from a later argument than the one from which
13660 	     this parameter can be deduced.  */
13661 	  if (TREE_CODE (tparm) == PARM_DECL
13662 	      && uses_template_parms (TREE_TYPE (tparm))
13663 	      && !saw_undeduced++)
13664 	    goto again;
13665 
13666           /* Core issue #226 (C++0x) [temp.deduct]:
13667 
13668                If a template argument has not been deduced, its
13669                default template argument, if any, is used.
13670 
13671              When we are in C++98 mode, TREE_PURPOSE will either
13672 	     be NULL_TREE or ERROR_MARK_NODE, so we do not need
13673 	     to explicitly check cxx_dialect here.  */
13674           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
13675             {
13676 	      tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13677 	      tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
13678               arg = tsubst_template_arg (arg, targs, tf_none, NULL_TREE);
13679 	      arg = convert_template_argument (parm, arg, targs, tf_none,
13680 					       i, NULL_TREE);
13681               if (arg == error_mark_node)
13682                 return 1;
13683               else
13684                 {
13685                   TREE_VEC_ELT (targs, i) = arg;
13686 		  /* The position of the first default template argument,
13687 		     is also the number of non-defaulted arguments in TARGS.
13688 		     Record that.  */
13689 		  if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
13690 		    SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
13691                   continue;
13692                 }
13693             }
13694 
13695           /* If the type parameter is a parameter pack, then it will
13696              be deduced to an empty parameter pack.  */
13697           if (template_parameter_pack_p (tparm))
13698             {
13699               tree arg;
13700 
13701               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
13702                 {
13703                   arg = make_node (NONTYPE_ARGUMENT_PACK);
13704                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
13705                   TREE_CONSTANT (arg) = 1;
13706                 }
13707               else
13708                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
13709 
13710               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
13711 
13712               TREE_VEC_ELT (targs, i) = arg;
13713               continue;
13714             }
13715 
13716 	  return 2;
13717 	}
13718 #ifdef ENABLE_CHECKING
13719   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
13720     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
13721 #endif
13722 
13723   return 0;
13724 }
13725 
13726 /* Subroutine of type_unification_real.  Args are like the variables
13727    at the call site.  ARG is an overloaded function (or template-id);
13728    we try deducing template args from each of the overloads, and if
13729    only one succeeds, we go with that.  Modifies TARGS and returns
13730    true on success.  */
13731 
13732 static bool
13733 resolve_overloaded_unification (tree tparms,
13734 				tree targs,
13735 				tree parm,
13736 				tree arg,
13737 				unification_kind_t strict,
13738 				int sub_strict)
13739 {
13740   tree tempargs = copy_node (targs);
13741   int good = 0;
13742   tree goodfn = NULL_TREE;
13743   bool addr_p;
13744 
13745   if (TREE_CODE (arg) == ADDR_EXPR)
13746     {
13747       arg = TREE_OPERAND (arg, 0);
13748       addr_p = true;
13749     }
13750   else
13751     addr_p = false;
13752 
13753   if (TREE_CODE (arg) == COMPONENT_REF)
13754     /* Handle `&x' where `x' is some static or non-static member
13755        function name.  */
13756     arg = TREE_OPERAND (arg, 1);
13757 
13758   if (TREE_CODE (arg) == OFFSET_REF)
13759     arg = TREE_OPERAND (arg, 1);
13760 
13761   /* Strip baselink information.  */
13762   if (BASELINK_P (arg))
13763     arg = BASELINK_FUNCTIONS (arg);
13764 
13765   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
13766     {
13767       /* If we got some explicit template args, we need to plug them into
13768 	 the affected templates before we try to unify, in case the
13769 	 explicit args will completely resolve the templates in question.  */
13770 
13771       tree expl_subargs = TREE_OPERAND (arg, 1);
13772       arg = TREE_OPERAND (arg, 0);
13773 
13774       for (; arg; arg = OVL_NEXT (arg))
13775 	{
13776 	  tree fn = OVL_CURRENT (arg);
13777 	  tree subargs, elem;
13778 
13779 	  if (TREE_CODE (fn) != TEMPLATE_DECL)
13780 	    continue;
13781 
13782 	  ++processing_template_decl;
13783 	  subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13784 				  expl_subargs, /*check_ret=*/false);
13785 	  if (subargs)
13786 	    {
13787 	      elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
13788 	      if (try_one_overload (tparms, targs, tempargs, parm,
13789 				    elem, strict, sub_strict, addr_p)
13790 		  && (!goodfn || !decls_match (goodfn, elem)))
13791 		{
13792 		  goodfn = elem;
13793 		  ++good;
13794 		}
13795 	    }
13796 	  --processing_template_decl;
13797 	}
13798     }
13799   else if (TREE_CODE (arg) != OVERLOAD
13800 	   && TREE_CODE (arg) != FUNCTION_DECL)
13801     /* If ARG is, for example, "(0, &f)" then its type will be unknown
13802        -- but the deduction does not succeed because the expression is
13803        not just the function on its own.  */
13804     return false;
13805   else
13806     for (; arg; arg = OVL_NEXT (arg))
13807       if (try_one_overload (tparms, targs, tempargs, parm,
13808 			    TREE_TYPE (OVL_CURRENT (arg)),
13809 			    strict, sub_strict, addr_p)
13810 	  && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
13811 	{
13812 	  goodfn = OVL_CURRENT (arg);
13813 	  ++good;
13814 	}
13815 
13816   /* [temp.deduct.type] A template-argument can be deduced from a pointer
13817      to function or pointer to member function argument if the set of
13818      overloaded functions does not contain function templates and at most
13819      one of a set of overloaded functions provides a unique match.
13820 
13821      So if we found multiple possibilities, we return success but don't
13822      deduce anything.  */
13823 
13824   if (good == 1)
13825     {
13826       int i = TREE_VEC_LENGTH (targs);
13827       for (; i--; )
13828 	if (TREE_VEC_ELT (tempargs, i))
13829 	  TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
13830     }
13831   if (good)
13832     return true;
13833 
13834   return false;
13835 }
13836 
13837 /* Core DR 115: In contexts where deduction is done and fails, or in
13838    contexts where deduction is not done, if a template argument list is
13839    specified and it, along with any default template arguments, identifies
13840    a single function template specialization, then the template-id is an
13841    lvalue for the function template specialization.  */
13842 
13843 tree
13844 resolve_nondeduced_context (tree orig_expr)
13845 {
13846   tree expr, offset, baselink;
13847   bool addr;
13848 
13849   if (!type_unknown_p (orig_expr))
13850     return orig_expr;
13851 
13852   expr = orig_expr;
13853   addr = false;
13854   offset = NULL_TREE;
13855   baselink = NULL_TREE;
13856 
13857   if (TREE_CODE (expr) == ADDR_EXPR)
13858     {
13859       expr = TREE_OPERAND (expr, 0);
13860       addr = true;
13861     }
13862   if (TREE_CODE (expr) == OFFSET_REF)
13863     {
13864       offset = expr;
13865       expr = TREE_OPERAND (expr, 1);
13866     }
13867   if (TREE_CODE (expr) == BASELINK)
13868     {
13869       baselink = expr;
13870       expr = BASELINK_FUNCTIONS (expr);
13871     }
13872 
13873   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
13874     {
13875       int good = 0;
13876       tree goodfn = NULL_TREE;
13877 
13878       /* If we got some explicit template args, we need to plug them into
13879 	 the affected templates before we try to unify, in case the
13880 	 explicit args will completely resolve the templates in question.  */
13881 
13882       tree expl_subargs = TREE_OPERAND (expr, 1);
13883       tree arg = TREE_OPERAND (expr, 0);
13884       tree badfn = NULL_TREE;
13885       tree badargs = NULL_TREE;
13886 
13887       for (; arg; arg = OVL_NEXT (arg))
13888 	{
13889 	  tree fn = OVL_CURRENT (arg);
13890 	  tree subargs, elem;
13891 
13892 	  if (TREE_CODE (fn) != TEMPLATE_DECL)
13893 	    continue;
13894 
13895 	  ++processing_template_decl;
13896 	  subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13897 				  expl_subargs, /*check_ret=*/false);
13898 	  if (subargs && !any_dependent_template_arguments_p (subargs))
13899 	    {
13900 	      elem = instantiate_template (fn, subargs, tf_none);
13901 	      if (elem == error_mark_node)
13902 		{
13903 		  badfn = fn;
13904 		  badargs = subargs;
13905 		}
13906 	      else if (elem && (!goodfn || !decls_match (goodfn, elem)))
13907 		{
13908 		  goodfn = elem;
13909 		  ++good;
13910 		}
13911 	    }
13912 	  --processing_template_decl;
13913 	}
13914       if (good == 1)
13915 	{
13916 	  expr = goodfn;
13917 	  if (baselink)
13918 	    expr = build_baselink (BASELINK_BINFO (baselink),
13919 				   BASELINK_ACCESS_BINFO (baselink),
13920 				   expr, BASELINK_OPTYPE (baselink));
13921 	  if (offset)
13922 	    expr = build2 (OFFSET_REF, TREE_TYPE (expr),
13923 			   TREE_OPERAND (offset, 0), expr);
13924 	  if (addr)
13925 	    expr = build_address (expr);
13926 	  return expr;
13927 	}
13928       else if (good == 0 && badargs)
13929 	/* There were no good options and at least one bad one, so let the
13930 	   user know what the problem is.  */
13931 	instantiate_template (badfn, badargs, tf_warning_or_error);
13932     }
13933   return orig_expr;
13934 }
13935 
13936 /* Subroutine of resolve_overloaded_unification; does deduction for a single
13937    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
13938    different overloads deduce different arguments for a given parm.
13939    ADDR_P is true if the expression for which deduction is being
13940    performed was of the form "& fn" rather than simply "fn".
13941 
13942    Returns 1 on success.  */
13943 
13944 static int
13945 try_one_overload (tree tparms,
13946 		  tree orig_targs,
13947 		  tree targs,
13948 		  tree parm,
13949 		  tree arg,
13950 		  unification_kind_t strict,
13951 		  int sub_strict,
13952 		  bool addr_p)
13953 {
13954   int nargs;
13955   tree tempargs;
13956   int i;
13957 
13958   /* [temp.deduct.type] A template-argument can be deduced from a pointer
13959      to function or pointer to member function argument if the set of
13960      overloaded functions does not contain function templates and at most
13961      one of a set of overloaded functions provides a unique match.
13962 
13963      So if this is a template, just return success.  */
13964 
13965   if (uses_template_parms (arg))
13966     return 1;
13967 
13968   if (TREE_CODE (arg) == METHOD_TYPE)
13969     arg = build_ptrmemfunc_type (build_pointer_type (arg));
13970   else if (addr_p)
13971     arg = build_pointer_type (arg);
13972 
13973   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
13974 
13975   /* We don't copy orig_targs for this because if we have already deduced
13976      some template args from previous args, unify would complain when we
13977      try to deduce a template parameter for the same argument, even though
13978      there isn't really a conflict.  */
13979   nargs = TREE_VEC_LENGTH (targs);
13980   tempargs = make_tree_vec (nargs);
13981 
13982   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
13983     return 0;
13984 
13985   /* First make sure we didn't deduce anything that conflicts with
13986      explicitly specified args.  */
13987   for (i = nargs; i--; )
13988     {
13989       tree elt = TREE_VEC_ELT (tempargs, i);
13990       tree oldelt = TREE_VEC_ELT (orig_targs, i);
13991 
13992       if (!elt)
13993 	/*NOP*/;
13994       else if (uses_template_parms (elt))
13995 	/* Since we're unifying against ourselves, we will fill in
13996 	   template args used in the function parm list with our own
13997 	   template parms.  Discard them.  */
13998 	TREE_VEC_ELT (tempargs, i) = NULL_TREE;
13999       else if (oldelt && !template_args_equal (oldelt, elt))
14000 	return 0;
14001     }
14002 
14003   for (i = nargs; i--; )
14004     {
14005       tree elt = TREE_VEC_ELT (tempargs, i);
14006 
14007       if (elt)
14008 	TREE_VEC_ELT (targs, i) = elt;
14009     }
14010 
14011   return 1;
14012 }
14013 
14014 /* PARM is a template class (perhaps with unbound template
14015    parameters).  ARG is a fully instantiated type.  If ARG can be
14016    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
14017    TARGS are as for unify.  */
14018 
14019 static tree
14020 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
14021 {
14022   tree copy_of_targs;
14023 
14024   if (!CLASSTYPE_TEMPLATE_INFO (arg)
14025       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
14026 	  != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
14027     return NULL_TREE;
14028 
14029   /* We need to make a new template argument vector for the call to
14030      unify.  If we used TARGS, we'd clutter it up with the result of
14031      the attempted unification, even if this class didn't work out.
14032      We also don't want to commit ourselves to all the unifications
14033      we've already done, since unification is supposed to be done on
14034      an argument-by-argument basis.  In other words, consider the
14035      following pathological case:
14036 
14037        template <int I, int J, int K>
14038        struct S {};
14039 
14040        template <int I, int J>
14041        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
14042 
14043        template <int I, int J, int K>
14044        void f(S<I, J, K>, S<I, I, I>);
14045 
14046        void g() {
14047 	 S<0, 0, 0> s0;
14048 	 S<0, 1, 2> s2;
14049 
14050 	 f(s0, s2);
14051        }
14052 
14053      Now, by the time we consider the unification involving `s2', we
14054      already know that we must have `f<0, 0, 0>'.  But, even though
14055      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
14056      because there are two ways to unify base classes of S<0, 1, 2>
14057      with S<I, I, I>.  If we kept the already deduced knowledge, we
14058      would reject the possibility I=1.  */
14059   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
14060 
14061   /* If unification failed, we're done.  */
14062   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
14063 	     CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
14064     return NULL_TREE;
14065 
14066   return arg;
14067 }
14068 
14069 /* Given a template type PARM and a class type ARG, find the unique
14070    base type in ARG that is an instance of PARM.  We do not examine
14071    ARG itself; only its base-classes.  If there is not exactly one
14072    appropriate base class, return NULL_TREE.  PARM may be the type of
14073    a partial specialization, as well as a plain template type.  Used
14074    by unify.  */
14075 
14076 static tree
14077 get_template_base (tree tparms, tree targs, tree parm, tree arg)
14078 {
14079   tree rval = NULL_TREE;
14080   tree binfo;
14081 
14082   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
14083 
14084   binfo = TYPE_BINFO (complete_type (arg));
14085   if (!binfo)
14086     /* The type could not be completed.  */
14087     return NULL_TREE;
14088 
14089   /* Walk in inheritance graph order.  The search order is not
14090      important, and this avoids multiple walks of virtual bases.  */
14091   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
14092     {
14093       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
14094 
14095       if (r)
14096 	{
14097 	  /* If there is more than one satisfactory baseclass, then:
14098 
14099 	       [temp.deduct.call]
14100 
14101 	      If they yield more than one possible deduced A, the type
14102 	      deduction fails.
14103 
14104 	     applies.  */
14105 	  if (rval && !same_type_p (r, rval))
14106 	    return NULL_TREE;
14107 
14108 	  rval = r;
14109 	}
14110     }
14111 
14112   return rval;
14113 }
14114 
14115 /* Returns the level of DECL, which declares a template parameter.  */
14116 
14117 static int
14118 template_decl_level (tree decl)
14119 {
14120   switch (TREE_CODE (decl))
14121     {
14122     case TYPE_DECL:
14123     case TEMPLATE_DECL:
14124       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
14125 
14126     case PARM_DECL:
14127       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
14128 
14129     default:
14130       gcc_unreachable ();
14131     }
14132   return 0;
14133 }
14134 
14135 /* Decide whether ARG can be unified with PARM, considering only the
14136    cv-qualifiers of each type, given STRICT as documented for unify.
14137    Returns nonzero iff the unification is OK on that basis.  */
14138 
14139 static int
14140 check_cv_quals_for_unify (int strict, tree arg, tree parm)
14141 {
14142   int arg_quals = cp_type_quals (arg);
14143   int parm_quals = cp_type_quals (parm);
14144 
14145   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14146       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
14147     {
14148       /*  Although a CVR qualifier is ignored when being applied to a
14149 	  substituted template parameter ([8.3.2]/1 for example), that
14150 	  does not apply during deduction [14.8.2.4]/1, (even though
14151 	  that is not explicitly mentioned, [14.8.2.4]/9 indicates
14152 	  this).  Except when we're allowing additional CV qualifiers
14153 	  at the outer level [14.8.2.1]/3,1st bullet.  */
14154       if ((TREE_CODE (arg) == REFERENCE_TYPE
14155 	   || TREE_CODE (arg) == FUNCTION_TYPE
14156 	   || TREE_CODE (arg) == METHOD_TYPE)
14157 	  && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
14158 	return 0;
14159 
14160       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
14161 	  && (parm_quals & TYPE_QUAL_RESTRICT))
14162 	return 0;
14163     }
14164 
14165   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
14166       && (arg_quals & parm_quals) != parm_quals)
14167     return 0;
14168 
14169   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
14170       && (parm_quals & arg_quals) != arg_quals)
14171     return 0;
14172 
14173   return 1;
14174 }
14175 
14176 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
14177 void
14178 template_parm_level_and_index (tree parm, int* level, int* index)
14179 {
14180   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14181       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14182       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14183     {
14184       *index = TEMPLATE_TYPE_IDX (parm);
14185       *level = TEMPLATE_TYPE_LEVEL (parm);
14186     }
14187   else
14188     {
14189       *index = TEMPLATE_PARM_IDX (parm);
14190       *level = TEMPLATE_PARM_LEVEL (parm);
14191     }
14192 }
14193 
14194 /* Unifies the remaining arguments in PACKED_ARGS with the pack
14195    expansion at the end of PACKED_PARMS. Returns 0 if the type
14196    deduction succeeds, 1 otherwise. STRICT is the same as in
14197    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
14198    call argument list. We'll need to adjust the arguments to make them
14199    types. SUBR tells us if this is from a recursive call to
14200    type_unification_real.  */
14201 int
14202 unify_pack_expansion (tree tparms, tree targs, tree packed_parms,
14203                       tree packed_args, int strict, bool call_args_p,
14204                       bool subr)
14205 {
14206   tree parm
14207     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
14208   tree pattern = PACK_EXPANSION_PATTERN (parm);
14209   tree pack, packs = NULL_TREE;
14210   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
14211   int len = TREE_VEC_LENGTH (packed_args);
14212 
14213   /* Determine the parameter packs we will be deducing from the
14214      pattern, and record their current deductions.  */
14215   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm);
14216        pack; pack = TREE_CHAIN (pack))
14217     {
14218       tree parm_pack = TREE_VALUE (pack);
14219       int idx, level;
14220 
14221       /* Determine the index and level of this parameter pack.  */
14222       template_parm_level_and_index (parm_pack, &level, &idx);
14223 
14224       /* Keep track of the parameter packs and their corresponding
14225          argument packs.  */
14226       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
14227       TREE_TYPE (packs) = make_tree_vec (len - start);
14228     }
14229 
14230   /* Loop through all of the arguments that have not yet been
14231      unified and unify each with the pattern.  */
14232   for (i = start; i < len; i++)
14233     {
14234       tree parm = pattern;
14235 
14236       /* For each parameter pack, clear out the deduced value so that
14237          we can deduce it again.  */
14238       for (pack = packs; pack; pack = TREE_CHAIN (pack))
14239         {
14240           int idx, level;
14241           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14242 
14243           TMPL_ARG (targs, level, idx) = NULL_TREE;
14244         }
14245 
14246       /* Unify the pattern with the current argument.  */
14247       {
14248         tree arg = TREE_VEC_ELT (packed_args, i);
14249 	tree arg_expr = NULL_TREE;
14250         int arg_strict = strict;
14251         bool skip_arg_p = false;
14252 
14253         if (call_args_p)
14254           {
14255             int sub_strict;
14256 
14257             /* This mirrors what we do in type_unification_real.  */
14258             switch (strict)
14259               {
14260               case DEDUCE_CALL:
14261                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL
14262                               | UNIFY_ALLOW_MORE_CV_QUAL
14263                               | UNIFY_ALLOW_DERIVED);
14264                 break;
14265 
14266               case DEDUCE_CONV:
14267                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
14268                 break;
14269 
14270               case DEDUCE_EXACT:
14271                 sub_strict = UNIFY_ALLOW_NONE;
14272                 break;
14273 
14274               default:
14275                 gcc_unreachable ();
14276               }
14277 
14278             if (!TYPE_P (arg))
14279               {
14280                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
14281                 if (type_unknown_p (arg))
14282                   {
14283                     /* [temp.deduct.type] A template-argument can be
14284                        deduced from a pointer to function or pointer
14285                        to member function argument if the set of
14286                        overloaded functions does not contain function
14287                        templates and at most one of a set of
14288                        overloaded functions provides a unique
14289                        match.  */
14290 
14291                     if (resolve_overloaded_unification
14292                         (tparms, targs, parm, arg,
14293 			 (unification_kind_t) strict,
14294 			 sub_strict)
14295                         != 0)
14296                       return 1;
14297                     skip_arg_p = true;
14298                   }
14299 
14300                 if (!skip_arg_p)
14301                   {
14302 		    arg_expr = arg;
14303                     arg = unlowered_expr_type (arg);
14304                     if (arg == error_mark_node)
14305                       return 1;
14306                   }
14307               }
14308 
14309             arg_strict = sub_strict;
14310 
14311             if (!subr)
14312               arg_strict |=
14313                 maybe_adjust_types_for_deduction ((unification_kind_t) strict,
14314 						  &parm, &arg, arg_expr);
14315           }
14316 
14317         if (!skip_arg_p)
14318           {
14319 	    /* For deduction from an init-list we need the actual list.  */
14320 	    if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
14321 	      arg = arg_expr;
14322             if (unify (tparms, targs, parm, arg, arg_strict))
14323               return 1;
14324           }
14325       }
14326 
14327       /* For each parameter pack, collect the deduced value.  */
14328       for (pack = packs; pack; pack = TREE_CHAIN (pack))
14329         {
14330           int idx, level;
14331           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14332 
14333           TREE_VEC_ELT (TREE_TYPE (pack), i - start) =
14334             TMPL_ARG (targs, level, idx);
14335         }
14336     }
14337 
14338   /* Verify that the results of unification with the parameter packs
14339      produce results consistent with what we've seen before, and make
14340      the deduced argument packs available.  */
14341   for (pack = packs; pack; pack = TREE_CHAIN (pack))
14342     {
14343       tree old_pack = TREE_VALUE (pack);
14344       tree new_args = TREE_TYPE (pack);
14345       int i, len = TREE_VEC_LENGTH (new_args);
14346       int idx, level;
14347       bool nondeduced_p = false;
14348 
14349       /* By default keep the original deduced argument pack.
14350 	 If necessary, more specific code is going to update the
14351 	 resulting deduced argument later down in this function.  */
14352       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14353       TMPL_ARG (targs, level, idx) = old_pack;
14354 
14355       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
14356 	 actually deduce anything.  */
14357       for (i = 0; i < len && !nondeduced_p; ++i)
14358 	if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
14359 	  nondeduced_p = true;
14360       if (nondeduced_p)
14361 	continue;
14362 
14363       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
14364         {
14365           /* Prepend the explicit arguments onto NEW_ARGS.  */
14366           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14367           tree old_args = new_args;
14368           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
14369           int len = explicit_len + TREE_VEC_LENGTH (old_args);
14370 
14371           /* Copy the explicit arguments.  */
14372           new_args = make_tree_vec (len);
14373           for (i = 0; i < explicit_len; i++)
14374             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
14375 
14376           /* Copy the deduced arguments.  */
14377           for (; i < len; i++)
14378             TREE_VEC_ELT (new_args, i) =
14379               TREE_VEC_ELT (old_args, i - explicit_len);
14380         }
14381 
14382       if (!old_pack)
14383         {
14384           tree result;
14385           /* Build the deduced *_ARGUMENT_PACK.  */
14386           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
14387             {
14388               result = make_node (NONTYPE_ARGUMENT_PACK);
14389               TREE_TYPE (result) =
14390                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
14391               TREE_CONSTANT (result) = 1;
14392             }
14393           else
14394             result = cxx_make_type (TYPE_ARGUMENT_PACK);
14395 
14396           SET_ARGUMENT_PACK_ARGS (result, new_args);
14397 
14398           /* Note the deduced argument packs for this parameter
14399              pack.  */
14400           TMPL_ARG (targs, level, idx) = result;
14401         }
14402       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
14403                && (ARGUMENT_PACK_ARGS (old_pack)
14404                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
14405         {
14406           /* We only had the explicitly-provided arguments before, but
14407              now we have a complete set of arguments.  */
14408           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14409 
14410           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
14411           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
14412           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
14413         }
14414       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
14415                                     new_args))
14416         /* Inconsistent unification of this parameter pack.  */
14417         return 1;
14418     }
14419 
14420   return 0;
14421 }
14422 
14423 /* Deduce the value of template parameters.  TPARMS is the (innermost)
14424    set of template parameters to a template.  TARGS is the bindings
14425    for those template parameters, as determined thus far; TARGS may
14426    include template arguments for outer levels of template parameters
14427    as well.  PARM is a parameter to a template function, or a
14428    subcomponent of that parameter; ARG is the corresponding argument.
14429    This function attempts to match PARM with ARG in a manner
14430    consistent with the existing assignments in TARGS.  If more values
14431    are deduced, then TARGS is updated.
14432 
14433    Returns 0 if the type deduction succeeds, 1 otherwise.  The
14434    parameter STRICT is a bitwise or of the following flags:
14435 
14436      UNIFY_ALLOW_NONE:
14437        Require an exact match between PARM and ARG.
14438      UNIFY_ALLOW_MORE_CV_QUAL:
14439        Allow the deduced ARG to be more cv-qualified (by qualification
14440        conversion) than ARG.
14441      UNIFY_ALLOW_LESS_CV_QUAL:
14442        Allow the deduced ARG to be less cv-qualified than ARG.
14443      UNIFY_ALLOW_DERIVED:
14444        Allow the deduced ARG to be a template base class of ARG,
14445        or a pointer to a template base class of the type pointed to by
14446        ARG.
14447      UNIFY_ALLOW_INTEGER:
14448        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
14449        case for more information.
14450      UNIFY_ALLOW_OUTER_LEVEL:
14451        This is the outermost level of a deduction. Used to determine validity
14452        of qualification conversions. A valid qualification conversion must
14453        have const qualified pointers leading up to the inner type which
14454        requires additional CV quals, except at the outer level, where const
14455        is not required [conv.qual]. It would be normal to set this flag in
14456        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
14457      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
14458        This is the outermost level of a deduction, and PARM can be more CV
14459        qualified at this point.
14460      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
14461        This is the outermost level of a deduction, and PARM can be less CV
14462        qualified at this point.  */
14463 
14464 static int
14465 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
14466 {
14467   int idx;
14468   tree targ;
14469   tree tparm;
14470   int strict_in = strict;
14471 
14472   /* I don't think this will do the right thing with respect to types.
14473      But the only case I've seen it in so far has been array bounds, where
14474      signedness is the only information lost, and I think that will be
14475      okay.  */
14476   while (TREE_CODE (parm) == NOP_EXPR)
14477     parm = TREE_OPERAND (parm, 0);
14478 
14479   if (arg == error_mark_node)
14480     return 1;
14481   if (arg == unknown_type_node
14482       || arg == init_list_type_node)
14483     /* We can't deduce anything from this, but we might get all the
14484        template args from other function args.  */
14485     return 0;
14486 
14487   /* If PARM uses template parameters, then we can't bail out here,
14488      even if ARG == PARM, since we won't record unifications for the
14489      template parameters.  We might need them if we're trying to
14490      figure out which of two things is more specialized.  */
14491   if (arg == parm && !uses_template_parms (parm))
14492     return 0;
14493 
14494   /* Handle init lists early, so the rest of the function can assume
14495      we're dealing with a type. */
14496   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
14497     {
14498       tree elt, elttype;
14499       unsigned i;
14500       tree orig_parm = parm;
14501 
14502       /* Replace T with std::initializer_list<T> for deduction.  */
14503       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14504 	  && flag_deduce_init_list)
14505 	parm = listify (parm);
14506 
14507       if (!is_std_init_list (parm))
14508 	/* We can only deduce from an initializer list argument if the
14509 	   parameter is std::initializer_list; otherwise this is a
14510 	   non-deduced context. */
14511 	return 0;
14512 
14513       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
14514 
14515       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
14516 	{
14517 	  int elt_strict = strict;
14518 	  if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
14519 	    {
14520 	      tree type = TREE_TYPE (elt);
14521 	      /* It should only be possible to get here for a call.  */
14522 	      gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
14523 	      elt_strict |= maybe_adjust_types_for_deduction
14524 		(DEDUCE_CALL, &elttype, &type, elt);
14525 	      elt = type;
14526 	    }
14527 
14528 	  if (unify (tparms, targs, elttype, elt, elt_strict))
14529 	    return 1;
14530 	}
14531 
14532       /* If the std::initializer_list<T> deduction worked, replace the
14533 	 deduced A with std::initializer_list<A>.  */
14534       if (orig_parm != parm)
14535 	{
14536 	  idx = TEMPLATE_TYPE_IDX (orig_parm);
14537 	  targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14538 	  targ = listify (targ);
14539 	  TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
14540 	}
14541       return 0;
14542     }
14543 
14544   /* Immediately reject some pairs that won't unify because of
14545      cv-qualification mismatches.  */
14546   if (TREE_CODE (arg) == TREE_CODE (parm)
14547       && TYPE_P (arg)
14548       /* It is the elements of the array which hold the cv quals of an array
14549 	 type, and the elements might be template type parms. We'll check
14550 	 when we recurse.  */
14551       && TREE_CODE (arg) != ARRAY_TYPE
14552       /* We check the cv-qualifiers when unifying with template type
14553 	 parameters below.  We want to allow ARG `const T' to unify with
14554 	 PARM `T' for example, when computing which of two templates
14555 	 is more specialized, for example.  */
14556       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
14557       && !check_cv_quals_for_unify (strict_in, arg, parm))
14558     return 1;
14559 
14560   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
14561       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
14562     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
14563   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
14564   strict &= ~UNIFY_ALLOW_DERIVED;
14565   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
14566   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
14567 
14568   switch (TREE_CODE (parm))
14569     {
14570     case TYPENAME_TYPE:
14571     case SCOPE_REF:
14572     case UNBOUND_CLASS_TEMPLATE:
14573       /* In a type which contains a nested-name-specifier, template
14574 	 argument values cannot be deduced for template parameters used
14575 	 within the nested-name-specifier.  */
14576       return 0;
14577 
14578     case TEMPLATE_TYPE_PARM:
14579     case TEMPLATE_TEMPLATE_PARM:
14580     case BOUND_TEMPLATE_TEMPLATE_PARM:
14581       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14582       if (tparm == error_mark_node)
14583 	return 1;
14584 
14585       if (TEMPLATE_TYPE_LEVEL (parm)
14586 	  != template_decl_level (tparm))
14587 	/* The PARM is not one we're trying to unify.  Just check
14588 	   to see if it matches ARG.  */
14589 	return (TREE_CODE (arg) == TREE_CODE (parm)
14590 		&& same_type_p (parm, arg)) ? 0 : 1;
14591       idx = TEMPLATE_TYPE_IDX (parm);
14592       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14593       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
14594 
14595       /* Check for mixed types and values.  */
14596       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14597 	   && TREE_CODE (tparm) != TYPE_DECL)
14598 	  || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14599 	      && TREE_CODE (tparm) != TEMPLATE_DECL))
14600 	return 1;
14601 
14602       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14603 	{
14604 	  /* ARG must be constructed from a template class or a template
14605 	     template parameter.  */
14606 	  if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
14607 	      && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
14608 	    return 1;
14609 
14610 	  {
14611 	    tree parmvec = TYPE_TI_ARGS (parm);
14612 	    tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
14613 	    tree parm_parms
14614               = DECL_INNERMOST_TEMPLATE_PARMS
14615 	          (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
14616 	    int i, len;
14617             int parm_variadic_p = 0;
14618 
14619 	    /* The resolution to DR150 makes clear that default
14620 	       arguments for an N-argument may not be used to bind T
14621 	       to a template template parameter with fewer than N
14622 	       parameters.  It is not safe to permit the binding of
14623 	       default arguments as an extension, as that may change
14624 	       the meaning of a conforming program.  Consider:
14625 
14626 		  struct Dense { static const unsigned int dim = 1; };
14627 
14628 		  template <template <typename> class View,
14629 			    typename Block>
14630 		  void operator+(float, View<Block> const&);
14631 
14632 		  template <typename Block,
14633 			    unsigned int Dim = Block::dim>
14634 		  struct Lvalue_proxy { operator float() const; };
14635 
14636 		  void
14637 		  test_1d (void) {
14638 		    Lvalue_proxy<Dense> p;
14639 		    float b;
14640 		    b + p;
14641 		  }
14642 
14643 	      Here, if Lvalue_proxy is permitted to bind to View, then
14644 	      the global operator+ will be used; if they are not, the
14645 	      Lvalue_proxy will be converted to float.  */
14646 	    if (coerce_template_parms (parm_parms,
14647                                        argvec,
14648 				       TYPE_TI_TEMPLATE (parm),
14649 				       tf_none,
14650 				       /*require_all_args=*/true,
14651 				       /*use_default_args=*/false)
14652 		== error_mark_node)
14653 	      return 1;
14654 
14655 	    /* Deduce arguments T, i from TT<T> or TT<i>.
14656 	       We check each element of PARMVEC and ARGVEC individually
14657 	       rather than the whole TREE_VEC since they can have
14658 	       different number of elements.  */
14659 
14660             parmvec = expand_template_argument_pack (parmvec);
14661             argvec = expand_template_argument_pack (argvec);
14662 
14663             len = TREE_VEC_LENGTH (parmvec);
14664 
14665             /* Check if the parameters end in a pack, making them
14666                variadic.  */
14667             if (len > 0
14668                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
14669               parm_variadic_p = 1;
14670 
14671             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
14672               return 1;
14673 
14674              for (i = 0; i < len - parm_variadic_p; ++i)
14675 	      {
14676 		if (unify (tparms, targs,
14677 			   TREE_VEC_ELT (parmvec, i),
14678 			   TREE_VEC_ELT (argvec, i),
14679 			   UNIFY_ALLOW_NONE))
14680 		  return 1;
14681 	      }
14682 
14683 	    if (parm_variadic_p
14684 		&& unify_pack_expansion (tparms, targs,
14685 					 parmvec, argvec,
14686 					 UNIFY_ALLOW_NONE,
14687 					 /*call_args_p=*/false,
14688 					 /*subr=*/false))
14689 	      return 1;
14690 	  }
14691 	  arg = TYPE_TI_TEMPLATE (arg);
14692 
14693 	  /* Fall through to deduce template name.  */
14694 	}
14695 
14696       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14697 	  || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14698 	{
14699 	  /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
14700 
14701 	  /* Simple cases: Value already set, does match or doesn't.  */
14702 	  if (targ != NULL_TREE && template_args_equal (targ, arg))
14703 	    return 0;
14704 	  else if (targ)
14705 	    return 1;
14706 	}
14707       else
14708 	{
14709 	  /* If PARM is `const T' and ARG is only `int', we don't have
14710 	     a match unless we are allowing additional qualification.
14711 	     If ARG is `const int' and PARM is just `T' that's OK;
14712 	     that binds `const int' to `T'.  */
14713 	  if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
14714 					 arg, parm))
14715 	    return 1;
14716 
14717 	  /* Consider the case where ARG is `const volatile int' and
14718 	     PARM is `const T'.  Then, T should be `volatile int'.  */
14719 	  arg = cp_build_qualified_type_real
14720 	    (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
14721 	  if (arg == error_mark_node)
14722 	    return 1;
14723 
14724 	  /* Simple cases: Value already set, does match or doesn't.  */
14725 	  if (targ != NULL_TREE && same_type_p (targ, arg))
14726 	    return 0;
14727 	  else if (targ)
14728 	    return 1;
14729 
14730 	  /* Make sure that ARG is not a variable-sized array.  (Note
14731 	     that were talking about variable-sized arrays (like
14732 	     `int[n]'), rather than arrays of unknown size (like
14733 	     `int[]').)  We'll get very confused by such a type since
14734 	     the bound of the array will not be computable in an
14735 	     instantiation.  Besides, such types are not allowed in
14736 	     ISO C++, so we can do as we please here.  */
14737 	  if (variably_modified_type_p (arg, NULL_TREE))
14738 	    return 1;
14739 
14740 	  /* Strip typedefs as in convert_template_argument.  */
14741 	  arg = strip_typedefs (arg);
14742 	}
14743 
14744       /* If ARG is a parameter pack or an expansion, we cannot unify
14745 	 against it unless PARM is also a parameter pack.  */
14746       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
14747 	  && !template_parameter_pack_p (parm))
14748 	return 1;
14749 
14750       /* If the argument deduction results is a METHOD_TYPE,
14751          then there is a problem.
14752          METHOD_TYPE doesn't map to any real C++ type the result of
14753 	 the deduction can not be of that type.  */
14754       if (TREE_CODE (arg) == METHOD_TYPE)
14755 	return 1;
14756 
14757       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
14758       return 0;
14759 
14760     case TEMPLATE_PARM_INDEX:
14761       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14762       if (tparm == error_mark_node)
14763 	return 1;
14764 
14765       if (TEMPLATE_PARM_LEVEL (parm)
14766 	  != template_decl_level (tparm))
14767 	/* The PARM is not one we're trying to unify.  Just check
14768 	   to see if it matches ARG.  */
14769 	return !(TREE_CODE (arg) == TREE_CODE (parm)
14770 		 && cp_tree_equal (parm, arg));
14771 
14772       idx = TEMPLATE_PARM_IDX (parm);
14773       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14774 
14775       if (targ)
14776 	return !cp_tree_equal (targ, arg);
14777 
14778       /* [temp.deduct.type] If, in the declaration of a function template
14779 	 with a non-type template-parameter, the non-type
14780 	 template-parameter is used in an expression in the function
14781 	 parameter-list and, if the corresponding template-argument is
14782 	 deduced, the template-argument type shall match the type of the
14783 	 template-parameter exactly, except that a template-argument
14784 	 deduced from an array bound may be of any integral type.
14785 	 The non-type parameter might use already deduced type parameters.  */
14786       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
14787       if (!TREE_TYPE (arg))
14788 	/* Template-parameter dependent expression.  Just accept it for now.
14789 	   It will later be processed in convert_template_argument.  */
14790 	;
14791       else if (same_type_p (TREE_TYPE (arg), tparm))
14792 	/* OK */;
14793       else if ((strict & UNIFY_ALLOW_INTEGER)
14794 	       && (TREE_CODE (tparm) == INTEGER_TYPE
14795 		   || TREE_CODE (tparm) == BOOLEAN_TYPE))
14796 	/* Convert the ARG to the type of PARM; the deduced non-type
14797 	   template argument must exactly match the types of the
14798 	   corresponding parameter.  */
14799 	arg = fold (build_nop (tparm, arg));
14800       else if (uses_template_parms (tparm))
14801 	/* We haven't deduced the type of this parameter yet.  Try again
14802 	   later.  */
14803 	return 0;
14804       else
14805 	return 1;
14806 
14807       /* If ARG is a parameter pack or an expansion, we cannot unify
14808 	 against it unless PARM is also a parameter pack.  */
14809       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
14810 	  && !TEMPLATE_PARM_PARAMETER_PACK (parm))
14811 	return 1;
14812 
14813       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
14814       return 0;
14815 
14816     case PTRMEM_CST:
14817      {
14818 	/* A pointer-to-member constant can be unified only with
14819 	 another constant.  */
14820       if (TREE_CODE (arg) != PTRMEM_CST)
14821 	return 1;
14822 
14823       /* Just unify the class member. It would be useless (and possibly
14824 	 wrong, depending on the strict flags) to unify also
14825 	 PTRMEM_CST_CLASS, because we want to be sure that both parm and
14826 	 arg refer to the same variable, even if through different
14827 	 classes. For instance:
14828 
14829 	 struct A { int x; };
14830 	 struct B : A { };
14831 
14832 	 Unification of &A::x and &B::x must succeed.  */
14833       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
14834 		    PTRMEM_CST_MEMBER (arg), strict);
14835      }
14836 
14837     case POINTER_TYPE:
14838       {
14839 	if (TREE_CODE (arg) != POINTER_TYPE)
14840 	  return 1;
14841 
14842 	/* [temp.deduct.call]
14843 
14844 	   A can be another pointer or pointer to member type that can
14845 	   be converted to the deduced A via a qualification
14846 	   conversion (_conv.qual_).
14847 
14848 	   We pass down STRICT here rather than UNIFY_ALLOW_NONE.
14849 	   This will allow for additional cv-qualification of the
14850 	   pointed-to types if appropriate.  */
14851 
14852 	if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
14853 	  /* The derived-to-base conversion only persists through one
14854 	     level of pointers.  */
14855 	  strict |= (strict_in & UNIFY_ALLOW_DERIVED);
14856 
14857 	return unify (tparms, targs, TREE_TYPE (parm),
14858 		      TREE_TYPE (arg), strict);
14859       }
14860 
14861     case REFERENCE_TYPE:
14862       if (TREE_CODE (arg) != REFERENCE_TYPE)
14863 	return 1;
14864       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14865 		    strict & UNIFY_ALLOW_MORE_CV_QUAL);
14866 
14867     case ARRAY_TYPE:
14868       if (TREE_CODE (arg) != ARRAY_TYPE)
14869 	return 1;
14870       if ((TYPE_DOMAIN (parm) == NULL_TREE)
14871 	  != (TYPE_DOMAIN (arg) == NULL_TREE))
14872 	return 1;
14873       if (TYPE_DOMAIN (parm) != NULL_TREE)
14874 	{
14875 	  tree parm_max;
14876 	  tree arg_max;
14877 	  bool parm_cst;
14878 	  bool arg_cst;
14879 
14880 	  /* Our representation of array types uses "N - 1" as the
14881 	     TYPE_MAX_VALUE for an array with "N" elements, if "N" is
14882 	     not an integer constant.  We cannot unify arbitrarily
14883 	     complex expressions, so we eliminate the MINUS_EXPRs
14884 	     here.  */
14885 	  parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
14886 	  parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
14887 	  if (!parm_cst)
14888 	    {
14889 	      gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
14890 	      parm_max = TREE_OPERAND (parm_max, 0);
14891 	    }
14892 	  arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
14893 	  arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
14894 	  if (!arg_cst)
14895 	    {
14896 	      /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
14897 		 trying to unify the type of a variable with the type
14898 		 of a template parameter.  For example:
14899 
14900                    template <unsigned int N>
14901 		   void f (char (&) [N]);
14902 		   int g();
14903 		   void h(int i) {
14904                      char a[g(i)];
14905 		     f(a);
14906                    }
14907 
14908                 Here, the type of the ARG will be "int [g(i)]", and
14909                 may be a SAVE_EXPR, etc.  */
14910 	      if (TREE_CODE (arg_max) != MINUS_EXPR)
14911 		return 1;
14912 	      arg_max = TREE_OPERAND (arg_max, 0);
14913 	    }
14914 
14915 	  /* If only one of the bounds used a MINUS_EXPR, compensate
14916 	     by adding one to the other bound.  */
14917 	  if (parm_cst && !arg_cst)
14918 	    parm_max = fold_build2_loc (input_location, PLUS_EXPR,
14919 				    integer_type_node,
14920 				    parm_max,
14921 				    integer_one_node);
14922 	  else if (arg_cst && !parm_cst)
14923 	    arg_max = fold_build2_loc (input_location, PLUS_EXPR,
14924 				   integer_type_node,
14925 				   arg_max,
14926 				   integer_one_node);
14927 
14928 	  if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
14929 	    return 1;
14930 	}
14931       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14932 		    strict & UNIFY_ALLOW_MORE_CV_QUAL);
14933 
14934     case REAL_TYPE:
14935     case COMPLEX_TYPE:
14936     case VECTOR_TYPE:
14937     case INTEGER_TYPE:
14938     case BOOLEAN_TYPE:
14939     case ENUMERAL_TYPE:
14940     case VOID_TYPE:
14941       if (TREE_CODE (arg) != TREE_CODE (parm))
14942 	return 1;
14943 
14944       /* We have already checked cv-qualification at the top of the
14945 	 function.  */
14946       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
14947 	return 1;
14948 
14949       /* As far as unification is concerned, this wins.	 Later checks
14950 	 will invalidate it if necessary.  */
14951       return 0;
14952 
14953       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
14954       /* Type INTEGER_CST can come from ordinary constant template args.  */
14955     case INTEGER_CST:
14956       while (TREE_CODE (arg) == NOP_EXPR)
14957 	arg = TREE_OPERAND (arg, 0);
14958 
14959       if (TREE_CODE (arg) != INTEGER_CST)
14960 	return 1;
14961       return !tree_int_cst_equal (parm, arg);
14962 
14963     case TREE_VEC:
14964       {
14965 	int i;
14966 	if (TREE_CODE (arg) != TREE_VEC)
14967 	  return 1;
14968 	if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
14969 	  return 1;
14970 	for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
14971 	  if (unify (tparms, targs,
14972 		     TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
14973 		     UNIFY_ALLOW_NONE))
14974 	    return 1;
14975 	return 0;
14976       }
14977 
14978     case RECORD_TYPE:
14979     case UNION_TYPE:
14980       if (TREE_CODE (arg) != TREE_CODE (parm))
14981 	return 1;
14982 
14983       if (TYPE_PTRMEMFUNC_P (parm))
14984 	{
14985 	  if (!TYPE_PTRMEMFUNC_P (arg))
14986 	    return 1;
14987 
14988 	  return unify (tparms, targs,
14989 			TYPE_PTRMEMFUNC_FN_TYPE (parm),
14990 			TYPE_PTRMEMFUNC_FN_TYPE (arg),
14991 			strict);
14992 	}
14993 
14994       if (CLASSTYPE_TEMPLATE_INFO (parm))
14995 	{
14996 	  tree t = NULL_TREE;
14997 
14998 	  if (strict_in & UNIFY_ALLOW_DERIVED)
14999 	    {
15000 	      /* First, we try to unify the PARM and ARG directly.  */
15001 	      t = try_class_unification (tparms, targs,
15002 					 parm, arg);
15003 
15004 	      if (!t)
15005 		{
15006 		  /* Fallback to the special case allowed in
15007 		     [temp.deduct.call]:
15008 
15009 		       If P is a class, and P has the form
15010 		       template-id, then A can be a derived class of
15011 		       the deduced A.  Likewise, if P is a pointer to
15012 		       a class of the form template-id, A can be a
15013 		       pointer to a derived class pointed to by the
15014 		       deduced A.  */
15015 		  t = get_template_base (tparms, targs, parm, arg);
15016 
15017 		  if (!t)
15018 		    return 1;
15019 		}
15020 	    }
15021 	  else if (CLASSTYPE_TEMPLATE_INFO (arg)
15022 		   && (CLASSTYPE_TI_TEMPLATE (parm)
15023 		       == CLASSTYPE_TI_TEMPLATE (arg)))
15024 	    /* Perhaps PARM is something like S<U> and ARG is S<int>.
15025 	       Then, we should unify `int' and `U'.  */
15026 	    t = arg;
15027 	  else
15028 	    /* There's no chance of unification succeeding.  */
15029 	    return 1;
15030 
15031 	  return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
15032 			CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
15033 	}
15034       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
15035 	return 1;
15036       return 0;
15037 
15038     case METHOD_TYPE:
15039     case FUNCTION_TYPE:
15040       {
15041 	unsigned int nargs;
15042 	tree *args;
15043 	tree a;
15044 	unsigned int i;
15045 
15046 	if (TREE_CODE (arg) != TREE_CODE (parm))
15047 	  return 1;
15048 
15049 	/* CV qualifications for methods can never be deduced, they must
15050 	   match exactly.  We need to check them explicitly here,
15051 	   because type_unification_real treats them as any other
15052 	   cv-qualified parameter.  */
15053 	if (TREE_CODE (parm) == METHOD_TYPE
15054 	    && (!check_cv_quals_for_unify
15055 		(UNIFY_ALLOW_NONE,
15056 		 TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
15057 		 TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
15058 	  return 1;
15059 
15060 	if (unify (tparms, targs, TREE_TYPE (parm),
15061 		   TREE_TYPE (arg), UNIFY_ALLOW_NONE))
15062 	  return 1;
15063 
15064 	nargs = list_length (TYPE_ARG_TYPES (arg));
15065 	args = XALLOCAVEC (tree, nargs);
15066 	for (a = TYPE_ARG_TYPES (arg), i = 0;
15067 	     a != NULL_TREE && a != void_list_node;
15068 	     a = TREE_CHAIN (a), ++i)
15069 	  args[i] = TREE_VALUE (a);
15070 	nargs = i;
15071 
15072 	return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
15073 				      args, nargs, 1, DEDUCE_EXACT,
15074 				      LOOKUP_NORMAL);
15075       }
15076 
15077     case OFFSET_TYPE:
15078       /* Unify a pointer to member with a pointer to member function, which
15079 	 deduces the type of the member as a function type. */
15080       if (TYPE_PTRMEMFUNC_P (arg))
15081 	{
15082 	  tree method_type;
15083 	  tree fntype;
15084 	  cp_cv_quals cv_quals;
15085 
15086 	  /* Check top-level cv qualifiers */
15087 	  if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
15088 	    return 1;
15089 
15090 	  if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
15091 		     TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
15092 	    return 1;
15093 
15094 	  /* Determine the type of the function we are unifying against. */
15095 	  method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
15096 	  fntype =
15097 	    build_function_type (TREE_TYPE (method_type),
15098 				 TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
15099 
15100 	  /* Extract the cv-qualifiers of the member function from the
15101 	     implicit object parameter and place them on the function
15102 	     type to be restored later. */
15103 	  cv_quals =
15104 	    cp_type_quals(TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (method_type))));
15105 	  fntype = build_qualified_type (fntype, cv_quals);
15106 	  return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
15107 	}
15108 
15109       if (TREE_CODE (arg) != OFFSET_TYPE)
15110 	return 1;
15111       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
15112 		 TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
15113 	return 1;
15114       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
15115 		    strict);
15116 
15117     case CONST_DECL:
15118       if (DECL_TEMPLATE_PARM_P (parm))
15119 	return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
15120       if (arg != integral_constant_value (parm))
15121 	return 1;
15122       return 0;
15123 
15124     case FIELD_DECL:
15125     case TEMPLATE_DECL:
15126       /* Matched cases are handled by the ARG == PARM test above.  */
15127       return 1;
15128 
15129     case VAR_DECL:
15130       /* A non-type template parameter that is a variable should be a
15131 	 an integral constant, in which case, it whould have been
15132 	 folded into its (constant) value. So we should not be getting
15133 	 a variable here.  */
15134       gcc_unreachable ();
15135 
15136     case TYPE_ARGUMENT_PACK:
15137     case NONTYPE_ARGUMENT_PACK:
15138       {
15139         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
15140         tree packed_args = ARGUMENT_PACK_ARGS (arg);
15141         int i, len = TREE_VEC_LENGTH (packed_parms);
15142         int argslen = TREE_VEC_LENGTH (packed_args);
15143         int parm_variadic_p = 0;
15144 
15145 	for (i = 0; i < len; ++i)
15146 	  {
15147 	    if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
15148 	      {
15149 		if (i == len - 1)
15150 		  /* We can unify against something with a trailing
15151 		     parameter pack.  */
15152 		  parm_variadic_p = 1;
15153 		else
15154 		  /* Since there is something following the pack
15155 		     expansion, we cannot unify this template argument
15156 		     list.  */
15157 		  return 0;
15158 	      }
15159 	  }
15160 
15161 
15162         /* If we don't have enough arguments to satisfy the parameters
15163            (not counting the pack expression at the end), or we have
15164            too many arguments for a parameter list that doesn't end in
15165            a pack expression, we can't unify.  */
15166         if (argslen < (len - parm_variadic_p)
15167             || (argslen > len && !parm_variadic_p))
15168           return 1;
15169 
15170         /* Unify all of the parameters that precede the (optional)
15171            pack expression.  */
15172         for (i = 0; i < len - parm_variadic_p; ++i)
15173           {
15174             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
15175                        TREE_VEC_ELT (packed_args, i), strict))
15176               return 1;
15177           }
15178 
15179         if (parm_variadic_p)
15180           return unify_pack_expansion (tparms, targs,
15181                                        packed_parms, packed_args,
15182                                        strict, /*call_args_p=*/false,
15183                                        /*subr=*/false);
15184         return 0;
15185       }
15186 
15187       break;
15188 
15189     case TYPEOF_TYPE:
15190     case DECLTYPE_TYPE:
15191       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
15192          nodes.  */
15193       return 0;
15194 
15195     case ERROR_MARK:
15196       /* Unification fails if we hit an error node.  */
15197       return 1;
15198 
15199     default:
15200       /* An unresolved overload is a nondeduced context.  */
15201       if (type_unknown_p (parm))
15202 	return 0;
15203       gcc_assert (EXPR_P (parm));
15204 
15205       /* We must be looking at an expression.  This can happen with
15206 	 something like:
15207 
15208 	   template <int I>
15209 	   void foo(S<I>, S<I + 2>);
15210 
15211 	 This is a "nondeduced context":
15212 
15213 	   [deduct.type]
15214 
15215 	   The nondeduced contexts are:
15216 
15217 	   --A type that is a template-id in which one or more of
15218 	     the template-arguments is an expression that references
15219 	     a template-parameter.
15220 
15221 	 In these cases, we assume deduction succeeded, but don't
15222 	 actually infer any unifications.  */
15223 
15224       if (!uses_template_parms (parm)
15225 	  && !template_args_equal (parm, arg))
15226 	return 1;
15227       else
15228 	return 0;
15229     }
15230 }
15231 
15232 /* Note that DECL can be defined in this translation unit, if
15233    required.  */
15234 
15235 static void
15236 mark_definable (tree decl)
15237 {
15238   tree clone;
15239   DECL_NOT_REALLY_EXTERN (decl) = 1;
15240   FOR_EACH_CLONE (clone, decl)
15241     DECL_NOT_REALLY_EXTERN (clone) = 1;
15242 }
15243 
15244 /* Called if RESULT is explicitly instantiated, or is a member of an
15245    explicitly instantiated class.  */
15246 
15247 void
15248 mark_decl_instantiated (tree result, int extern_p)
15249 {
15250   SET_DECL_EXPLICIT_INSTANTIATION (result);
15251 
15252   /* If this entity has already been written out, it's too late to
15253      make any modifications.  */
15254   if (TREE_ASM_WRITTEN (result))
15255     return;
15256 
15257   if (TREE_CODE (result) != FUNCTION_DECL)
15258     /* The TREE_PUBLIC flag for function declarations will have been
15259        set correctly by tsubst.  */
15260     TREE_PUBLIC (result) = 1;
15261 
15262   /* This might have been set by an earlier implicit instantiation.  */
15263   DECL_COMDAT (result) = 0;
15264 
15265   if (extern_p)
15266     DECL_NOT_REALLY_EXTERN (result) = 0;
15267   else
15268     {
15269       mark_definable (result);
15270       /* Always make artificials weak.  */
15271       if (DECL_ARTIFICIAL (result) && flag_weak)
15272 	comdat_linkage (result);
15273       /* For WIN32 we also want to put explicit instantiations in
15274 	 linkonce sections.  */
15275       else if (TREE_PUBLIC (result))
15276 	maybe_make_one_only (result);
15277     }
15278 
15279   /* If EXTERN_P, then this function will not be emitted -- unless
15280      followed by an explicit instantiation, at which point its linkage
15281      will be adjusted.  If !EXTERN_P, then this function will be
15282      emitted here.  In neither circumstance do we want
15283      import_export_decl to adjust the linkage.  */
15284   DECL_INTERFACE_KNOWN (result) = 1;
15285 }
15286 
15287 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
15288    important template arguments.  If any are missing, we check whether
15289    they're important by using error_mark_node for substituting into any
15290    args that were used for partial ordering (the ones between ARGS and END)
15291    and seeing if it bubbles up.  */
15292 
15293 static bool
15294 check_undeduced_parms (tree targs, tree args, tree end)
15295 {
15296   bool found = false;
15297   int i;
15298   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
15299     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
15300       {
15301 	found = true;
15302 	TREE_VEC_ELT (targs, i) = error_mark_node;
15303       }
15304   if (found)
15305     {
15306       for (; args != end; args = TREE_CHAIN (args))
15307 	{
15308 	  tree substed = tsubst (TREE_VALUE (args), targs, tf_none, NULL_TREE);
15309 	  if (substed == error_mark_node)
15310 	    return true;
15311 	}
15312     }
15313   return false;
15314 }
15315 
15316 /* Given two function templates PAT1 and PAT2, return:
15317 
15318    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
15319    -1 if PAT2 is more specialized than PAT1.
15320    0 if neither is more specialized.
15321 
15322    LEN indicates the number of parameters we should consider
15323    (defaulted parameters should not be considered).
15324 
15325    The 1998 std underspecified function template partial ordering, and
15326    DR214 addresses the issue.  We take pairs of arguments, one from
15327    each of the templates, and deduce them against each other.  One of
15328    the templates will be more specialized if all the *other*
15329    template's arguments deduce against its arguments and at least one
15330    of its arguments *does* *not* deduce against the other template's
15331    corresponding argument.  Deduction is done as for class templates.
15332    The arguments used in deduction have reference and top level cv
15333    qualifiers removed.  Iff both arguments were originally reference
15334    types *and* deduction succeeds in both directions, the template
15335    with the more cv-qualified argument wins for that pairing (if
15336    neither is more cv-qualified, they both are equal).  Unlike regular
15337    deduction, after all the arguments have been deduced in this way,
15338    we do *not* verify the deduced template argument values can be
15339    substituted into non-deduced contexts.
15340 
15341    The logic can be a bit confusing here, because we look at deduce1 and
15342    targs1 to see if pat2 is at least as specialized, and vice versa; if we
15343    can find template arguments for pat1 to make arg1 look like arg2, that
15344    means that arg2 is at least as specialized as arg1.  */
15345 
15346 int
15347 more_specialized_fn (tree pat1, tree pat2, int len)
15348 {
15349   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
15350   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
15351   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
15352   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
15353   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
15354   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
15355   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
15356   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
15357   tree origs1, origs2;
15358   bool lose1 = false;
15359   bool lose2 = false;
15360 
15361   /* Remove the this parameter from non-static member functions.  If
15362      one is a non-static member function and the other is not a static
15363      member function, remove the first parameter from that function
15364      also.  This situation occurs for operator functions where we
15365      locate both a member function (with this pointer) and non-member
15366      operator (with explicit first operand).  */
15367   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
15368     {
15369       len--; /* LEN is the number of significant arguments for DECL1 */
15370       args1 = TREE_CHAIN (args1);
15371       if (!DECL_STATIC_FUNCTION_P (decl2))
15372 	args2 = TREE_CHAIN (args2);
15373     }
15374   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
15375     {
15376       args2 = TREE_CHAIN (args2);
15377       if (!DECL_STATIC_FUNCTION_P (decl1))
15378 	{
15379 	  len--;
15380 	  args1 = TREE_CHAIN (args1);
15381 	}
15382     }
15383 
15384   /* If only one is a conversion operator, they are unordered.  */
15385   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
15386     return 0;
15387 
15388   /* Consider the return type for a conversion function */
15389   if (DECL_CONV_FN_P (decl1))
15390     {
15391       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
15392       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
15393       len++;
15394     }
15395 
15396   processing_template_decl++;
15397 
15398   origs1 = args1;
15399   origs2 = args2;
15400 
15401   while (len--
15402 	 /* Stop when an ellipsis is seen.  */
15403 	 && args1 != NULL_TREE && args2 != NULL_TREE)
15404     {
15405       tree arg1 = TREE_VALUE (args1);
15406       tree arg2 = TREE_VALUE (args2);
15407       int deduce1, deduce2;
15408       int quals1 = -1;
15409       int quals2 = -1;
15410 
15411       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15412           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15413         {
15414           /* When both arguments are pack expansions, we need only
15415              unify the patterns themselves.  */
15416           arg1 = PACK_EXPANSION_PATTERN (arg1);
15417           arg2 = PACK_EXPANSION_PATTERN (arg2);
15418 
15419           /* This is the last comparison we need to do.  */
15420           len = 0;
15421         }
15422 
15423       if (TREE_CODE (arg1) == REFERENCE_TYPE)
15424 	{
15425 	  arg1 = TREE_TYPE (arg1);
15426 	  quals1 = cp_type_quals (arg1);
15427 	}
15428 
15429       if (TREE_CODE (arg2) == REFERENCE_TYPE)
15430 	{
15431 	  arg2 = TREE_TYPE (arg2);
15432 	  quals2 = cp_type_quals (arg2);
15433 	}
15434 
15435       if ((quals1 < 0) != (quals2 < 0))
15436 	{
15437 	  /* Only of the args is a reference, see if we should apply
15438 	     array/function pointer decay to it.  This is not part of
15439 	     DR214, but is, IMHO, consistent with the deduction rules
15440 	     for the function call itself, and with our earlier
15441 	     implementation of the underspecified partial ordering
15442 	     rules.  (nathan).  */
15443 	  if (quals1 >= 0)
15444 	    {
15445 	      switch (TREE_CODE (arg1))
15446 		{
15447 		case ARRAY_TYPE:
15448 		  arg1 = TREE_TYPE (arg1);
15449 		  /* FALLTHROUGH. */
15450 		case FUNCTION_TYPE:
15451 		  arg1 = build_pointer_type (arg1);
15452 		  break;
15453 
15454 		default:
15455 		  break;
15456 		}
15457 	    }
15458 	  else
15459 	    {
15460 	      switch (TREE_CODE (arg2))
15461 		{
15462 		case ARRAY_TYPE:
15463 		  arg2 = TREE_TYPE (arg2);
15464 		  /* FALLTHROUGH. */
15465 		case FUNCTION_TYPE:
15466 		  arg2 = build_pointer_type (arg2);
15467 		  break;
15468 
15469 		default:
15470 		  break;
15471 		}
15472 	    }
15473 	}
15474 
15475       arg1 = TYPE_MAIN_VARIANT (arg1);
15476       arg2 = TYPE_MAIN_VARIANT (arg2);
15477 
15478       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
15479         {
15480           int i, len2 = list_length (args2);
15481           tree parmvec = make_tree_vec (1);
15482           tree argvec = make_tree_vec (len2);
15483           tree ta = args2;
15484 
15485           /* Setup the parameter vector, which contains only ARG1.  */
15486           TREE_VEC_ELT (parmvec, 0) = arg1;
15487 
15488           /* Setup the argument vector, which contains the remaining
15489              arguments.  */
15490           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
15491             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15492 
15493           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec,
15494 					   argvec, UNIFY_ALLOW_NONE,
15495                                            /*call_args_p=*/false,
15496 					   /*subr=*/0);
15497 
15498           /* We cannot deduce in the other direction, because ARG1 is
15499              a pack expansion but ARG2 is not.  */
15500           deduce2 = 0;
15501         }
15502       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15503         {
15504           int i, len1 = list_length (args1);
15505           tree parmvec = make_tree_vec (1);
15506           tree argvec = make_tree_vec (len1);
15507           tree ta = args1;
15508 
15509           /* Setup the parameter vector, which contains only ARG1.  */
15510           TREE_VEC_ELT (parmvec, 0) = arg2;
15511 
15512           /* Setup the argument vector, which contains the remaining
15513              arguments.  */
15514           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
15515             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15516 
15517           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec,
15518 					   argvec, UNIFY_ALLOW_NONE,
15519                                            /*call_args_p=*/false,
15520 					   /*subr=*/0);
15521 
15522           /* We cannot deduce in the other direction, because ARG2 is
15523              a pack expansion but ARG1 is not.*/
15524           deduce1 = 0;
15525         }
15526 
15527       else
15528         {
15529           /* The normal case, where neither argument is a pack
15530              expansion.  */
15531           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
15532           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
15533         }
15534 
15535       /* If we couldn't deduce arguments for tparms1 to make arg1 match
15536 	 arg2, then arg2 is not as specialized as arg1.  */
15537       if (!deduce1)
15538 	lose2 = true;
15539       if (!deduce2)
15540 	lose1 = true;
15541 
15542       /* "If, for a given type, deduction succeeds in both directions
15543 	 (i.e., the types are identical after the transformations above)
15544 	 and if the type from the argument template is more cv-qualified
15545 	 than the type from the parameter template (as described above)
15546 	 that type is considered to be more specialized than the other. If
15547 	 neither type is more cv-qualified than the other then neither type
15548 	 is more specialized than the other."  */
15549 
15550       if (deduce1 && deduce2
15551 	  && quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
15552 	{
15553 	  if ((quals1 & quals2) == quals2)
15554 	    lose2 = true;
15555 	  if ((quals1 & quals2) == quals1)
15556 	    lose1 = true;
15557 	}
15558 
15559       if (lose1 && lose2)
15560 	/* We've failed to deduce something in either direction.
15561 	   These must be unordered.  */
15562 	break;
15563 
15564       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15565           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15566         /* We have already processed all of the arguments in our
15567            handing of the pack expansion type.  */
15568         len = 0;
15569 
15570       args1 = TREE_CHAIN (args1);
15571       args2 = TREE_CHAIN (args2);
15572     }
15573 
15574   /* "In most cases, all template parameters must have values in order for
15575      deduction to succeed, but for partial ordering purposes a template
15576      parameter may remain without a value provided it is not used in the
15577      types being used for partial ordering."
15578 
15579      Thus, if we are missing any of the targs1 we need to substitute into
15580      origs1, then pat2 is not as specialized as pat1.  This can happen when
15581      there is a nondeduced context.  */
15582   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
15583     lose2 = true;
15584   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
15585     lose1 = true;
15586 
15587   processing_template_decl--;
15588 
15589   /* All things being equal, if the next argument is a pack expansion
15590      for one function but not for the other, prefer the
15591      non-variadic function.  FIXME this is bogus; see c++/41958.  */
15592   if (lose1 == lose2
15593       && args1 && TREE_VALUE (args1)
15594       && args2 && TREE_VALUE (args2))
15595     {
15596       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
15597       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
15598     }
15599 
15600   if (lose1 == lose2)
15601     return 0;
15602   else if (!lose1)
15603     return 1;
15604   else
15605     return -1;
15606 }
15607 
15608 /* Determine which of two partial specializations is more specialized.
15609 
15610    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
15611    to the first partial specialization.  The TREE_VALUE is the
15612    innermost set of template parameters for the partial
15613    specialization.  PAT2 is similar, but for the second template.
15614 
15615    Return 1 if the first partial specialization is more specialized;
15616    -1 if the second is more specialized; 0 if neither is more
15617    specialized.
15618 
15619    See [temp.class.order] for information about determining which of
15620    two templates is more specialized.  */
15621 
15622 static int
15623 more_specialized_class (tree pat1, tree pat2)
15624 {
15625   tree targs;
15626   tree tmpl1, tmpl2;
15627   int winner = 0;
15628   bool any_deductions = false;
15629 
15630   tmpl1 = TREE_TYPE (pat1);
15631   tmpl2 = TREE_TYPE (pat2);
15632 
15633   /* Just like what happens for functions, if we are ordering between
15634      different class template specializations, we may encounter dependent
15635      types in the arguments, and we need our dependency check functions
15636      to behave correctly.  */
15637   ++processing_template_decl;
15638   targs = get_class_bindings (TREE_VALUE (pat1),
15639 			      CLASSTYPE_TI_ARGS (tmpl1),
15640 			      CLASSTYPE_TI_ARGS (tmpl2));
15641   if (targs)
15642     {
15643       --winner;
15644       any_deductions = true;
15645     }
15646 
15647   targs = get_class_bindings (TREE_VALUE (pat2),
15648 			      CLASSTYPE_TI_ARGS (tmpl2),
15649 			      CLASSTYPE_TI_ARGS (tmpl1));
15650   if (targs)
15651     {
15652       ++winner;
15653       any_deductions = true;
15654     }
15655   --processing_template_decl;
15656 
15657   /* In the case of a tie where at least one of the class templates
15658      has a parameter pack at the end, the template with the most
15659      non-packed parameters wins.  */
15660   if (winner == 0
15661       && any_deductions
15662       && (template_args_variadic_p (TREE_PURPOSE (pat1))
15663           || template_args_variadic_p (TREE_PURPOSE (pat2))))
15664     {
15665       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
15666       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
15667       int len1 = TREE_VEC_LENGTH (args1);
15668       int len2 = TREE_VEC_LENGTH (args2);
15669 
15670       /* We don't count the pack expansion at the end.  */
15671       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
15672         --len1;
15673       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
15674         --len2;
15675 
15676       if (len1 > len2)
15677         return 1;
15678       else if (len1 < len2)
15679         return -1;
15680     }
15681 
15682   return winner;
15683 }
15684 
15685 /* Return the template arguments that will produce the function signature
15686    DECL from the function template FN, with the explicit template
15687    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
15688    also match.  Return NULL_TREE if no satisfactory arguments could be
15689    found.  */
15690 
15691 static tree
15692 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
15693 {
15694   int ntparms = DECL_NTPARMS (fn);
15695   tree targs = make_tree_vec (ntparms);
15696   tree decl_type;
15697   tree decl_arg_types;
15698   tree *args;
15699   unsigned int nargs, ix;
15700   tree arg;
15701 
15702   /* Substitute the explicit template arguments into the type of DECL.
15703      The call to fn_type_unification will handle substitution into the
15704      FN.  */
15705   decl_type = TREE_TYPE (decl);
15706   if (explicit_args && uses_template_parms (decl_type))
15707     {
15708       tree tmpl;
15709       tree converted_args;
15710 
15711       if (DECL_TEMPLATE_INFO (decl))
15712 	tmpl = DECL_TI_TEMPLATE (decl);
15713       else
15714 	/* We can get here for some invalid specializations.  */
15715 	return NULL_TREE;
15716 
15717       converted_args
15718 	= coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
15719 				 explicit_args, NULL_TREE,
15720 				 tf_none,
15721 				 /*require_all_args=*/false,
15722 				 /*use_default_args=*/false);
15723       if (converted_args == error_mark_node)
15724 	return NULL_TREE;
15725 
15726       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
15727       if (decl_type == error_mark_node)
15728 	return NULL_TREE;
15729     }
15730 
15731   /* Never do unification on the 'this' parameter.  */
15732   decl_arg_types = skip_artificial_parms_for (decl,
15733 					      TYPE_ARG_TYPES (decl_type));
15734 
15735   nargs = list_length (decl_arg_types);
15736   args = XALLOCAVEC (tree, nargs);
15737   for (arg = decl_arg_types, ix = 0;
15738        arg != NULL_TREE && arg != void_list_node;
15739        arg = TREE_CHAIN (arg), ++ix)
15740     args[ix] = TREE_VALUE (arg);
15741 
15742   if (fn_type_unification (fn, explicit_args, targs,
15743 			   args, ix,
15744 			   (check_rettype || DECL_CONV_FN_P (fn)
15745 			    ? TREE_TYPE (decl_type) : NULL_TREE),
15746 			   DEDUCE_EXACT, LOOKUP_NORMAL))
15747     return NULL_TREE;
15748 
15749   return targs;
15750 }
15751 
15752 /* Return the innermost template arguments that, when applied to a
15753    template specialization whose innermost template parameters are
15754    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
15755    ARGS.
15756 
15757    For example, suppose we have:
15758 
15759      template <class T, class U> struct S {};
15760      template <class T> struct S<T*, int> {};
15761 
15762    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
15763    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
15764    int}.  The resulting vector will be {double}, indicating that `T'
15765    is bound to `double'.  */
15766 
15767 static tree
15768 get_class_bindings (tree tparms, tree spec_args, tree args)
15769 {
15770   int i, ntparms = TREE_VEC_LENGTH (tparms);
15771   tree deduced_args;
15772   tree innermost_deduced_args;
15773 
15774   innermost_deduced_args = make_tree_vec (ntparms);
15775   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
15776     {
15777       deduced_args = copy_node (args);
15778       SET_TMPL_ARGS_LEVEL (deduced_args,
15779 			   TMPL_ARGS_DEPTH (deduced_args),
15780 			   innermost_deduced_args);
15781     }
15782   else
15783     deduced_args = innermost_deduced_args;
15784 
15785   if (unify (tparms, deduced_args,
15786 	     INNERMOST_TEMPLATE_ARGS (spec_args),
15787 	     INNERMOST_TEMPLATE_ARGS (args),
15788 	     UNIFY_ALLOW_NONE))
15789     return NULL_TREE;
15790 
15791   for (i =  0; i < ntparms; ++i)
15792     if (! TREE_VEC_ELT (innermost_deduced_args, i))
15793       return NULL_TREE;
15794 
15795   /* Verify that nondeduced template arguments agree with the type
15796      obtained from argument deduction.
15797 
15798      For example:
15799 
15800        struct A { typedef int X; };
15801        template <class T, class U> struct C {};
15802        template <class T> struct C<T, typename T::X> {};
15803 
15804      Then with the instantiation `C<A, int>', we can deduce that
15805      `T' is `A' but unify () does not check whether `typename T::X'
15806      is `int'.  */
15807   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
15808   if (spec_args == error_mark_node
15809       /* We only need to check the innermost arguments; the other
15810 	 arguments will always agree.  */
15811       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
15812 			      INNERMOST_TEMPLATE_ARGS (args)))
15813     return NULL_TREE;
15814 
15815   /* Now that we have bindings for all of the template arguments,
15816      ensure that the arguments deduced for the template template
15817      parameters have compatible template parameter lists.  See the use
15818      of template_template_parm_bindings_ok_p in fn_type_unification
15819      for more information.  */
15820   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
15821     return NULL_TREE;
15822 
15823   return deduced_args;
15824 }
15825 
15826 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
15827    Return the TREE_LIST node with the most specialized template, if
15828    any.  If there is no most specialized template, the error_mark_node
15829    is returned.
15830 
15831    Note that this function does not look at, or modify, the
15832    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
15833    returned is one of the elements of INSTANTIATIONS, callers may
15834    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
15835    and retrieve it from the value returned.  */
15836 
15837 tree
15838 most_specialized_instantiation (tree templates)
15839 {
15840   tree fn, champ;
15841 
15842   ++processing_template_decl;
15843 
15844   champ = templates;
15845   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
15846     {
15847       int fate = 0;
15848 
15849       if (get_bindings (TREE_VALUE (champ),
15850 			DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
15851 			NULL_TREE, /*check_ret=*/false))
15852 	fate--;
15853 
15854       if (get_bindings (TREE_VALUE (fn),
15855 			DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
15856 			NULL_TREE, /*check_ret=*/false))
15857 	fate++;
15858 
15859       if (fate == -1)
15860 	champ = fn;
15861       else if (!fate)
15862 	{
15863 	  /* Equally specialized, move to next function.  If there
15864 	     is no next function, nothing's most specialized.  */
15865 	  fn = TREE_CHAIN (fn);
15866 	  champ = fn;
15867 	  if (!fn)
15868 	    break;
15869 	}
15870     }
15871 
15872   if (champ)
15873     /* Now verify that champ is better than everything earlier in the
15874        instantiation list.  */
15875     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
15876       if (get_bindings (TREE_VALUE (champ),
15877 			DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
15878 			NULL_TREE, /*check_ret=*/false)
15879 	  || !get_bindings (TREE_VALUE (fn),
15880 			    DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
15881 			    NULL_TREE, /*check_ret=*/false))
15882 	{
15883 	  champ = NULL_TREE;
15884 	  break;
15885 	}
15886 
15887   processing_template_decl--;
15888 
15889   if (!champ)
15890     return error_mark_node;
15891 
15892   return champ;
15893 }
15894 
15895 /* If DECL is a specialization of some template, return the most
15896    general such template.  Otherwise, returns NULL_TREE.
15897 
15898    For example, given:
15899 
15900      template <class T> struct S { template <class U> void f(U); };
15901 
15902    if TMPL is `template <class U> void S<int>::f(U)' this will return
15903    the full template.  This function will not trace past partial
15904    specializations, however.  For example, given in addition:
15905 
15906      template <class T> struct S<T*> { template <class U> void f(U); };
15907 
15908    if TMPL is `template <class U> void S<int*>::f(U)' this will return
15909    `template <class T> template <class U> S<T*>::f(U)'.  */
15910 
15911 tree
15912 most_general_template (tree decl)
15913 {
15914   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
15915      an immediate specialization.  */
15916   if (TREE_CODE (decl) == FUNCTION_DECL)
15917     {
15918       if (DECL_TEMPLATE_INFO (decl)) {
15919 	decl = DECL_TI_TEMPLATE (decl);
15920 
15921 	/* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
15922 	   template friend.  */
15923 	if (TREE_CODE (decl) != TEMPLATE_DECL)
15924 	  return NULL_TREE;
15925       } else
15926 	return NULL_TREE;
15927     }
15928 
15929   /* Look for more and more general templates.  */
15930   while (DECL_TEMPLATE_INFO (decl))
15931     {
15932       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
15933 	 (See cp-tree.h for details.)  */
15934       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
15935 	break;
15936 
15937       if (CLASS_TYPE_P (TREE_TYPE (decl))
15938 	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
15939 	break;
15940 
15941       /* Stop if we run into an explicitly specialized class template.  */
15942       if (!DECL_NAMESPACE_SCOPE_P (decl)
15943 	  && DECL_CONTEXT (decl)
15944 	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
15945 	break;
15946 
15947       decl = DECL_TI_TEMPLATE (decl);
15948     }
15949 
15950   return decl;
15951 }
15952 
15953 /* Return the most specialized of the class template partial
15954    specializations of TMPL which can produce TYPE, a specialization of
15955    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
15956    a _TYPE node corresponding to the partial specialization, while the
15957    TREE_PURPOSE is the set of template arguments that must be
15958    substituted into the TREE_TYPE in order to generate TYPE.
15959 
15960    If the choice of partial specialization is ambiguous, a diagnostic
15961    is issued, and the error_mark_node is returned.  If there are no
15962    partial specializations of TMPL matching TYPE, then NULL_TREE is
15963    returned.  */
15964 
15965 static tree
15966 most_specialized_class (tree type, tree tmpl)
15967 {
15968   tree list = NULL_TREE;
15969   tree t;
15970   tree champ;
15971   int fate;
15972   bool ambiguous_p;
15973   tree args;
15974   tree outer_args = NULL_TREE;
15975 
15976   tmpl = most_general_template (tmpl);
15977   args = CLASSTYPE_TI_ARGS (type);
15978 
15979   /* For determining which partial specialization to use, only the
15980      innermost args are interesting.  */
15981   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
15982     {
15983       outer_args = strip_innermost_template_args (args, 1);
15984       args = INNERMOST_TEMPLATE_ARGS (args);
15985     }
15986 
15987   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
15988     {
15989       tree partial_spec_args;
15990       tree spec_args;
15991       tree parms = TREE_VALUE (t);
15992 
15993       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
15994 
15995       ++processing_template_decl;
15996 
15997       if (outer_args)
15998 	{
15999 	  int i;
16000 
16001 	  /* Discard the outer levels of args, and then substitute in the
16002 	     template args from the enclosing class.  */
16003 	  partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
16004 	  partial_spec_args = tsubst_template_args
16005 	    (partial_spec_args, outer_args, tf_none, NULL_TREE);
16006 
16007 	  /* PARMS already refers to just the innermost parms, but the
16008 	     template parms in partial_spec_args had their levels lowered
16009 	     by tsubst, so we need to do the same for the parm list.  We
16010 	     can't just tsubst the TREE_VEC itself, as tsubst wants to
16011 	     treat a TREE_VEC as an argument vector.  */
16012 	  parms = copy_node (parms);
16013 	  for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
16014 	    TREE_VEC_ELT (parms, i) =
16015 	      tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
16016 
16017 	}
16018 
16019       partial_spec_args =
16020 	  coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
16021 				 add_to_template_args (outer_args,
16022 						       partial_spec_args),
16023 				 tmpl, tf_none,
16024 				 /*require_all_args=*/true,
16025 				 /*use_default_args=*/true);
16026 
16027       --processing_template_decl;
16028 
16029       if (partial_spec_args == error_mark_node)
16030 	return error_mark_node;
16031 
16032       spec_args = get_class_bindings (parms,
16033 				      partial_spec_args,
16034 				      args);
16035       if (spec_args)
16036 	{
16037 	  if (outer_args)
16038 	    spec_args = add_to_template_args (outer_args, spec_args);
16039 	  list = tree_cons (spec_args, TREE_VALUE (t), list);
16040 	  TREE_TYPE (list) = TREE_TYPE (t);
16041 	}
16042     }
16043 
16044   if (! list)
16045     return NULL_TREE;
16046 
16047   ambiguous_p = false;
16048   t = list;
16049   champ = t;
16050   t = TREE_CHAIN (t);
16051   for (; t; t = TREE_CHAIN (t))
16052     {
16053       fate = more_specialized_class (champ, t);
16054       if (fate == 1)
16055 	;
16056       else
16057 	{
16058 	  if (fate == 0)
16059 	    {
16060 	      t = TREE_CHAIN (t);
16061 	      if (! t)
16062 		{
16063 		  ambiguous_p = true;
16064 		  break;
16065 		}
16066 	    }
16067 	  champ = t;
16068 	}
16069     }
16070 
16071   if (!ambiguous_p)
16072     for (t = list; t && t != champ; t = TREE_CHAIN (t))
16073       {
16074 	fate = more_specialized_class (champ, t);
16075 	if (fate != 1)
16076 	  {
16077 	    ambiguous_p = true;
16078 	    break;
16079 	  }
16080       }
16081 
16082   if (ambiguous_p)
16083     {
16084       const char *str;
16085       char *spaces = NULL;
16086       error ("ambiguous class template instantiation for %q#T", type);
16087       str = TREE_CHAIN (list) ? _("candidates are:") : _("candidate is:");
16088       for (t = list; t; t = TREE_CHAIN (t))
16089         {
16090           error ("%s %+#T", spaces ? spaces : str, TREE_TYPE (t));
16091           spaces = spaces ? spaces : get_spaces (str);
16092         }
16093       free (spaces);
16094       return error_mark_node;
16095     }
16096 
16097   return champ;
16098 }
16099 
16100 /* Explicitly instantiate DECL.  */
16101 
16102 void
16103 do_decl_instantiation (tree decl, tree storage)
16104 {
16105   tree result = NULL_TREE;
16106   int extern_p = 0;
16107 
16108   if (!decl || decl == error_mark_node)
16109     /* An error occurred, for which grokdeclarator has already issued
16110        an appropriate message.  */
16111     return;
16112   else if (! DECL_LANG_SPECIFIC (decl))
16113     {
16114       error ("explicit instantiation of non-template %q#D", decl);
16115       return;
16116     }
16117   else if (TREE_CODE (decl) == VAR_DECL)
16118     {
16119       /* There is an asymmetry here in the way VAR_DECLs and
16120 	 FUNCTION_DECLs are handled by grokdeclarator.  In the case of
16121 	 the latter, the DECL we get back will be marked as a
16122 	 template instantiation, and the appropriate
16123 	 DECL_TEMPLATE_INFO will be set up.  This does not happen for
16124 	 VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
16125 	 should handle VAR_DECLs as it currently handles
16126 	 FUNCTION_DECLs.  */
16127       if (!DECL_CLASS_SCOPE_P (decl))
16128 	{
16129 	  error ("%qD is not a static data member of a class template", decl);
16130 	  return;
16131 	}
16132       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
16133       if (!result || TREE_CODE (result) != VAR_DECL)
16134 	{
16135 	  error ("no matching template for %qD found", decl);
16136 	  return;
16137 	}
16138       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
16139 	{
16140 	  error ("type %qT for explicit instantiation %qD does not match "
16141 		 "declared type %qT", TREE_TYPE (result), decl,
16142 		 TREE_TYPE (decl));
16143 	  return;
16144 	}
16145     }
16146   else if (TREE_CODE (decl) != FUNCTION_DECL)
16147     {
16148       error ("explicit instantiation of %q#D", decl);
16149       return;
16150     }
16151   else
16152     result = decl;
16153 
16154   /* Check for various error cases.  Note that if the explicit
16155      instantiation is valid the RESULT will currently be marked as an
16156      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
16157      until we get here.  */
16158 
16159   if (DECL_TEMPLATE_SPECIALIZATION (result))
16160     {
16161       /* DR 259 [temp.spec].
16162 
16163 	 Both an explicit instantiation and a declaration of an explicit
16164 	 specialization shall not appear in a program unless the explicit
16165 	 instantiation follows a declaration of the explicit specialization.
16166 
16167 	 For a given set of template parameters, if an explicit
16168 	 instantiation of a template appears after a declaration of an
16169 	 explicit specialization for that template, the explicit
16170 	 instantiation has no effect.  */
16171       return;
16172     }
16173   else if (DECL_EXPLICIT_INSTANTIATION (result))
16174     {
16175       /* [temp.spec]
16176 
16177 	 No program shall explicitly instantiate any template more
16178 	 than once.
16179 
16180 	 We check DECL_NOT_REALLY_EXTERN so as not to complain when
16181 	 the first instantiation was `extern' and the second is not,
16182 	 and EXTERN_P for the opposite case.  */
16183       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
16184 	permerror (input_location, "duplicate explicit instantiation of %q#D", result);
16185       /* If an "extern" explicit instantiation follows an ordinary
16186 	 explicit instantiation, the template is instantiated.  */
16187       if (extern_p)
16188 	return;
16189     }
16190   else if (!DECL_IMPLICIT_INSTANTIATION (result))
16191     {
16192       error ("no matching template for %qD found", result);
16193       return;
16194     }
16195   else if (!DECL_TEMPLATE_INFO (result))
16196     {
16197       permerror (input_location, "explicit instantiation of non-template %q#D", result);
16198       return;
16199     }
16200 
16201   if (storage == NULL_TREE)
16202     ;
16203   else if (storage == ridpointers[(int) RID_EXTERN])
16204     {
16205       if (!in_system_header && (cxx_dialect == cxx98))
16206 	pedwarn (input_location, OPT_pedantic,
16207 		 "ISO C++ 1998 forbids the use of %<extern%> on explicit "
16208 		 "instantiations");
16209       extern_p = 1;
16210     }
16211   else
16212     error ("storage class %qD applied to template instantiation", storage);
16213 
16214   check_explicit_instantiation_namespace (result);
16215   mark_decl_instantiated (result, extern_p);
16216   if (! extern_p)
16217     instantiate_decl (result, /*defer_ok=*/1,
16218 		      /*expl_inst_class_mem_p=*/false);
16219 }
16220 
16221 static void
16222 mark_class_instantiated (tree t, int extern_p)
16223 {
16224   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
16225   SET_CLASSTYPE_INTERFACE_KNOWN (t);
16226   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
16227   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
16228   if (! extern_p)
16229     {
16230       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
16231       rest_of_type_compilation (t, 1);
16232     }
16233 }
16234 
16235 /* Called from do_type_instantiation through binding_table_foreach to
16236    do recursive instantiation for the type bound in ENTRY.  */
16237 static void
16238 bt_instantiate_type_proc (binding_entry entry, void *data)
16239 {
16240   tree storage = *(tree *) data;
16241 
16242   if (MAYBE_CLASS_TYPE_P (entry->type)
16243       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
16244     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
16245 }
16246 
16247 /* Called from do_type_instantiation to instantiate a member
16248    (a member function or a static member variable) of an
16249    explicitly instantiated class template.  */
16250 static void
16251 instantiate_class_member (tree decl, int extern_p)
16252 {
16253   mark_decl_instantiated (decl, extern_p);
16254   if (! extern_p)
16255     instantiate_decl (decl, /*defer_ok=*/1,
16256 		      /*expl_inst_class_mem_p=*/true);
16257 }
16258 
16259 /* Perform an explicit instantiation of template class T.  STORAGE, if
16260    non-null, is the RID for extern, inline or static.  COMPLAIN is
16261    nonzero if this is called from the parser, zero if called recursively,
16262    since the standard is unclear (as detailed below).  */
16263 
16264 void
16265 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
16266 {
16267   int extern_p = 0;
16268   int nomem_p = 0;
16269   int static_p = 0;
16270   int previous_instantiation_extern_p = 0;
16271 
16272   if (TREE_CODE (t) == TYPE_DECL)
16273     t = TREE_TYPE (t);
16274 
16275   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
16276     {
16277       error ("explicit instantiation of non-template type %qT", t);
16278       return;
16279     }
16280 
16281   complete_type (t);
16282 
16283   if (!COMPLETE_TYPE_P (t))
16284     {
16285       if (complain & tf_error)
16286 	error ("explicit instantiation of %q#T before definition of template",
16287 	       t);
16288       return;
16289     }
16290 
16291   if (storage != NULL_TREE)
16292     {
16293       if (!in_system_header)
16294 	{
16295 	  if (storage == ridpointers[(int) RID_EXTERN])
16296 	    {
16297 	      if (cxx_dialect == cxx98)
16298 		pedwarn (input_location, OPT_pedantic,
16299 			 "ISO C++ 1998 forbids the use of %<extern%> on "
16300 			 "explicit instantiations");
16301 	    }
16302 	  else
16303 	    pedwarn (input_location, OPT_pedantic,
16304 		     "ISO C++ forbids the use of %qE"
16305 		     " on explicit instantiations", storage);
16306 	}
16307 
16308       if (storage == ridpointers[(int) RID_INLINE])
16309 	nomem_p = 1;
16310       else if (storage == ridpointers[(int) RID_EXTERN])
16311 	extern_p = 1;
16312       else if (storage == ridpointers[(int) RID_STATIC])
16313 	static_p = 1;
16314       else
16315 	{
16316 	  error ("storage class %qD applied to template instantiation",
16317 		 storage);
16318 	  extern_p = 0;
16319 	}
16320     }
16321 
16322   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
16323     {
16324       /* DR 259 [temp.spec].
16325 
16326 	 Both an explicit instantiation and a declaration of an explicit
16327 	 specialization shall not appear in a program unless the explicit
16328 	 instantiation follows a declaration of the explicit specialization.
16329 
16330 	 For a given set of template parameters, if an explicit
16331 	 instantiation of a template appears after a declaration of an
16332 	 explicit specialization for that template, the explicit
16333 	 instantiation has no effect.  */
16334       return;
16335     }
16336   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
16337     {
16338       /* [temp.spec]
16339 
16340 	 No program shall explicitly instantiate any template more
16341 	 than once.
16342 
16343 	 If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
16344 	 instantiation was `extern'.  If EXTERN_P then the second is.
16345 	 These cases are OK.  */
16346       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
16347 
16348       if (!previous_instantiation_extern_p && !extern_p
16349 	  && (complain & tf_error))
16350 	permerror (input_location, "duplicate explicit instantiation of %q#T", t);
16351 
16352       /* If we've already instantiated the template, just return now.  */
16353       if (!CLASSTYPE_INTERFACE_ONLY (t))
16354 	return;
16355     }
16356 
16357   check_explicit_instantiation_namespace (TYPE_NAME (t));
16358   mark_class_instantiated (t, extern_p);
16359 
16360   if (nomem_p)
16361     return;
16362 
16363   {
16364     tree tmp;
16365 
16366     /* In contrast to implicit instantiation, where only the
16367        declarations, and not the definitions, of members are
16368        instantiated, we have here:
16369 
16370 	 [temp.explicit]
16371 
16372 	 The explicit instantiation of a class template specialization
16373 	 implies the instantiation of all of its members not
16374 	 previously explicitly specialized in the translation unit
16375 	 containing the explicit instantiation.
16376 
16377        Of course, we can't instantiate member template classes, since
16378        we don't have any arguments for them.  Note that the standard
16379        is unclear on whether the instantiation of the members are
16380        *explicit* instantiations or not.  However, the most natural
16381        interpretation is that it should be an explicit instantiation.  */
16382 
16383     if (! static_p)
16384       for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
16385 	if (TREE_CODE (tmp) == FUNCTION_DECL
16386 	    && DECL_TEMPLATE_INSTANTIATION (tmp))
16387 	  instantiate_class_member (tmp, extern_p);
16388 
16389     for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
16390       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
16391 	instantiate_class_member (tmp, extern_p);
16392 
16393     if (CLASSTYPE_NESTED_UTDS (t))
16394       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
16395 			     bt_instantiate_type_proc, &storage);
16396   }
16397 }
16398 
16399 /* Given a function DECL, which is a specialization of TMPL, modify
16400    DECL to be a re-instantiation of TMPL with the same template
16401    arguments.  TMPL should be the template into which tsubst'ing
16402    should occur for DECL, not the most general template.
16403 
16404    One reason for doing this is a scenario like this:
16405 
16406      template <class T>
16407      void f(const T&, int i);
16408 
16409      void g() { f(3, 7); }
16410 
16411      template <class T>
16412      void f(const T& t, const int i) { }
16413 
16414    Note that when the template is first instantiated, with
16415    instantiate_template, the resulting DECL will have no name for the
16416    first parameter, and the wrong type for the second.  So, when we go
16417    to instantiate the DECL, we regenerate it.  */
16418 
16419 static void
16420 regenerate_decl_from_template (tree decl, tree tmpl)
16421 {
16422   /* The arguments used to instantiate DECL, from the most general
16423      template.  */
16424   tree args;
16425   tree code_pattern;
16426 
16427   args = DECL_TI_ARGS (decl);
16428   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
16429 
16430   /* Make sure that we can see identifiers, and compute access
16431      correctly.  */
16432   push_access_scope (decl);
16433 
16434   if (TREE_CODE (decl) == FUNCTION_DECL)
16435     {
16436       tree decl_parm;
16437       tree pattern_parm;
16438       tree specs;
16439       int args_depth;
16440       int parms_depth;
16441 
16442       args_depth = TMPL_ARGS_DEPTH (args);
16443       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
16444       if (args_depth > parms_depth)
16445 	args = get_innermost_template_args (args, parms_depth);
16446 
16447       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
16448 					      args, tf_error, NULL_TREE);
16449       if (specs)
16450 	TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
16451 						    specs);
16452 
16453       /* Merge parameter declarations.  */
16454       decl_parm = skip_artificial_parms_for (decl,
16455 					     DECL_ARGUMENTS (decl));
16456       pattern_parm
16457 	= skip_artificial_parms_for (code_pattern,
16458 				     DECL_ARGUMENTS (code_pattern));
16459       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
16460 	{
16461 	  tree parm_type;
16462 	  tree attributes;
16463 
16464 	  if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16465 	    DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
16466 	  parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
16467 			      NULL_TREE);
16468 	  parm_type = type_decays_to (parm_type);
16469 	  if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16470 	    TREE_TYPE (decl_parm) = parm_type;
16471 	  attributes = DECL_ATTRIBUTES (pattern_parm);
16472 	  if (DECL_ATTRIBUTES (decl_parm) != attributes)
16473 	    {
16474 	      DECL_ATTRIBUTES (decl_parm) = attributes;
16475 	      cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16476 	    }
16477 	  decl_parm = TREE_CHAIN (decl_parm);
16478 	  pattern_parm = TREE_CHAIN (pattern_parm);
16479 	}
16480       /* Merge any parameters that match with the function parameter
16481          pack.  */
16482       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
16483         {
16484           int i, len;
16485           tree expanded_types;
16486           /* Expand the TYPE_PACK_EXPANSION that provides the types for
16487              the parameters in this function parameter pack.  */
16488           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm),
16489                                                  args, tf_error, NULL_TREE);
16490           len = TREE_VEC_LENGTH (expanded_types);
16491           for (i = 0; i < len; i++)
16492             {
16493               tree parm_type;
16494               tree attributes;
16495 
16496               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16497                 /* Rename the parameter to include the index.  */
16498                 DECL_NAME (decl_parm) =
16499                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
16500               parm_type = TREE_VEC_ELT (expanded_types, i);
16501               parm_type = type_decays_to (parm_type);
16502               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16503                 TREE_TYPE (decl_parm) = parm_type;
16504               attributes = DECL_ATTRIBUTES (pattern_parm);
16505               if (DECL_ATTRIBUTES (decl_parm) != attributes)
16506                 {
16507                   DECL_ATTRIBUTES (decl_parm) = attributes;
16508                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16509                 }
16510               decl_parm = TREE_CHAIN (decl_parm);
16511             }
16512         }
16513       /* Merge additional specifiers from the CODE_PATTERN.  */
16514       if (DECL_DECLARED_INLINE_P (code_pattern)
16515 	  && !DECL_DECLARED_INLINE_P (decl))
16516 	DECL_DECLARED_INLINE_P (decl) = 1;
16517     }
16518   else if (TREE_CODE (decl) == VAR_DECL)
16519     DECL_INITIAL (decl) =
16520       tsubst_expr (DECL_INITIAL (code_pattern), args,
16521 		   tf_error, DECL_TI_TEMPLATE (decl),
16522 		   /*integral_constant_expression_p=*/false);
16523   else
16524     gcc_unreachable ();
16525 
16526   pop_access_scope (decl);
16527 }
16528 
16529 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
16530    substituted to get DECL.  */
16531 
16532 tree
16533 template_for_substitution (tree decl)
16534 {
16535   tree tmpl = DECL_TI_TEMPLATE (decl);
16536 
16537   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
16538      for the instantiation.  This is not always the most general
16539      template.  Consider, for example:
16540 
16541 	template <class T>
16542 	struct S { template <class U> void f();
16543 		   template <> void f<int>(); };
16544 
16545      and an instantiation of S<double>::f<int>.  We want TD to be the
16546      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
16547   while (/* An instantiation cannot have a definition, so we need a
16548 	    more general template.  */
16549 	 DECL_TEMPLATE_INSTANTIATION (tmpl)
16550 	   /* We must also deal with friend templates.  Given:
16551 
16552 		template <class T> struct S {
16553 		  template <class U> friend void f() {};
16554 		};
16555 
16556 	      S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
16557 	      so far as the language is concerned, but that's still
16558 	      where we get the pattern for the instantiation from.  On
16559 	      other hand, if the definition comes outside the class, say:
16560 
16561 		template <class T> struct S {
16562 		  template <class U> friend void f();
16563 		};
16564 		template <class U> friend void f() {}
16565 
16566 	      we don't need to look any further.  That's what the check for
16567 	      DECL_INITIAL is for.  */
16568 	  || (TREE_CODE (decl) == FUNCTION_DECL
16569 	      && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
16570 	      && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
16571     {
16572       /* The present template, TD, should not be a definition.  If it
16573 	 were a definition, we should be using it!  Note that we
16574 	 cannot restructure the loop to just keep going until we find
16575 	 a template with a definition, since that might go too far if
16576 	 a specialization was declared, but not defined.  */
16577       gcc_assert (TREE_CODE (decl) != VAR_DECL
16578 		  || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
16579 
16580       /* Fetch the more general template.  */
16581       tmpl = DECL_TI_TEMPLATE (tmpl);
16582     }
16583 
16584   return tmpl;
16585 }
16586 
16587 /* Returns true if we need to instantiate this template instance even if we
16588    know we aren't going to emit it..  */
16589 
16590 bool
16591 always_instantiate_p (tree decl)
16592 {
16593   /* We always instantiate inline functions so that we can inline them.  An
16594      explicit instantiation declaration prohibits implicit instantiation of
16595      non-inline functions.  With high levels of optimization, we would
16596      normally inline non-inline functions -- but we're not allowed to do
16597      that for "extern template" functions.  Therefore, we check
16598      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
16599   return ((TREE_CODE (decl) == FUNCTION_DECL
16600 	   && DECL_DECLARED_INLINE_P (decl))
16601 	  /* And we need to instantiate static data members so that
16602 	     their initializers are available in integral constant
16603 	     expressions.  */
16604 	  || (TREE_CODE (decl) == VAR_DECL
16605 	      && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl)));
16606 }
16607 
16608 /* Produce the definition of D, a _DECL generated from a template.  If
16609    DEFER_OK is nonzero, then we don't have to actually do the
16610    instantiation now; we just have to do it sometime.  Normally it is
16611    an error if this is an explicit instantiation but D is undefined.
16612    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
16613    explicitly instantiated class template.  */
16614 
16615 tree
16616 instantiate_decl (tree d, int defer_ok,
16617 		  bool expl_inst_class_mem_p)
16618 {
16619   tree tmpl = DECL_TI_TEMPLATE (d);
16620   tree gen_args;
16621   tree args;
16622   tree td;
16623   tree code_pattern;
16624   tree spec;
16625   tree gen_tmpl;
16626   bool pattern_defined;
16627   int need_push;
16628   location_t saved_loc = input_location;
16629   bool external_p;
16630 
16631   /* This function should only be used to instantiate templates for
16632      functions and static member variables.  */
16633   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
16634 	      || TREE_CODE (d) == VAR_DECL);
16635 
16636   /* Variables are never deferred; if instantiation is required, they
16637      are instantiated right away.  That allows for better code in the
16638      case that an expression refers to the value of the variable --
16639      if the variable has a constant value the referring expression can
16640      take advantage of that fact.  */
16641   if (TREE_CODE (d) == VAR_DECL)
16642     defer_ok = 0;
16643 
16644   /* Don't instantiate cloned functions.  Instead, instantiate the
16645      functions they cloned.  */
16646   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
16647     d = DECL_CLONED_FUNCTION (d);
16648 
16649   if (DECL_TEMPLATE_INSTANTIATED (d)
16650       || DECL_TEMPLATE_SPECIALIZATION (d))
16651     /* D has already been instantiated or explicitly specialized, so
16652        there's nothing for us to do here.
16653 
16654        It might seem reasonable to check whether or not D is an explicit
16655        instantiation, and, if so, stop here.  But when an explicit
16656        instantiation is deferred until the end of the compilation,
16657        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
16658        the instantiation.  */
16659     return d;
16660 
16661   /* Check to see whether we know that this template will be
16662      instantiated in some other file, as with "extern template"
16663      extension.  */
16664   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
16665 
16666   /* In general, we do not instantiate such templates.  */
16667   if (external_p && !always_instantiate_p (d))
16668     return d;
16669 
16670   gen_tmpl = most_general_template (tmpl);
16671   gen_args = DECL_TI_ARGS (d);
16672 
16673   if (tmpl != gen_tmpl)
16674     /* We should already have the extra args.  */
16675     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
16676 		== TMPL_ARGS_DEPTH (gen_args));
16677   /* And what's in the hash table should match D.  */
16678   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
16679 	      || spec == NULL_TREE);
16680 
16681   /* This needs to happen before any tsubsting.  */
16682   if (! push_tinst_level (d))
16683     return d;
16684 
16685   timevar_push (TV_PARSE);
16686 
16687   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
16688      for the instantiation.  */
16689   td = template_for_substitution (d);
16690   code_pattern = DECL_TEMPLATE_RESULT (td);
16691 
16692   /* We should never be trying to instantiate a member of a class
16693      template or partial specialization.  */
16694   gcc_assert (d != code_pattern);
16695 
16696   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
16697       || DECL_TEMPLATE_SPECIALIZATION (td))
16698     /* In the case of a friend template whose definition is provided
16699        outside the class, we may have too many arguments.  Drop the
16700        ones we don't need.  The same is true for specializations.  */
16701     args = get_innermost_template_args
16702       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
16703   else
16704     args = gen_args;
16705 
16706   if (TREE_CODE (d) == FUNCTION_DECL)
16707     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
16708   else
16709     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
16710 
16711   /* We may be in the middle of deferred access check.  Disable it now.  */
16712   push_deferring_access_checks (dk_no_deferred);
16713 
16714   /* Unless an explicit instantiation directive has already determined
16715      the linkage of D, remember that a definition is available for
16716      this entity.  */
16717   if (pattern_defined
16718       && !DECL_INTERFACE_KNOWN (d)
16719       && !DECL_NOT_REALLY_EXTERN (d))
16720     mark_definable (d);
16721 
16722   input_location = DECL_SOURCE_LOCATION (d);
16723 
16724   /* If D is a member of an explicitly instantiated class template,
16725      and no definition is available, treat it like an implicit
16726      instantiation.  */
16727   if (!pattern_defined && expl_inst_class_mem_p
16728       && DECL_EXPLICIT_INSTANTIATION (d))
16729     {
16730       /* Leave linkage flags alone on instantiations with anonymous
16731 	 visibility.  */
16732       if (TREE_PUBLIC (d))
16733 	{
16734 	  DECL_NOT_REALLY_EXTERN (d) = 0;
16735 	  DECL_INTERFACE_KNOWN (d) = 0;
16736 	}
16737       SET_DECL_IMPLICIT_INSTANTIATION (d);
16738     }
16739 
16740   /* Recheck the substitutions to obtain any warning messages
16741      about ignoring cv qualifiers.  Don't do this for artificial decls,
16742      as it breaks the context-sensitive substitution for lambda op(). */
16743   if (!defer_ok && !DECL_ARTIFICIAL (d))
16744     {
16745       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
16746       tree type = TREE_TYPE (gen);
16747 
16748       /* Make sure that we can see identifiers, and compute access
16749 	 correctly.  D is already the target FUNCTION_DECL with the
16750 	 right context.  */
16751       push_access_scope (d);
16752 
16753       if (TREE_CODE (gen) == FUNCTION_DECL)
16754 	{
16755 	  tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
16756           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
16757                                           d);
16758 	  /* Don't simply tsubst the function type, as that will give
16759 	     duplicate warnings about poor parameter qualifications.
16760 	     The function arguments are the same as the decl_arguments
16761 	     without the top level cv qualifiers.  */
16762 	  type = TREE_TYPE (type);
16763 	}
16764       tsubst (type, gen_args, tf_warning_or_error, d);
16765 
16766       pop_access_scope (d);
16767     }
16768 
16769   /* Defer all other templates, unless we have been explicitly
16770      forbidden from doing so.  */
16771   if (/* If there is no definition, we cannot instantiate the
16772 	 template.  */
16773       ! pattern_defined
16774       /* If it's OK to postpone instantiation, do so.  */
16775       || defer_ok
16776       /* If this is a static data member that will be defined
16777 	 elsewhere, we don't want to instantiate the entire data
16778 	 member, but we do want to instantiate the initializer so that
16779 	 we can substitute that elsewhere.  */
16780       || (external_p && TREE_CODE (d) == VAR_DECL))
16781     {
16782       /* The definition of the static data member is now required so
16783 	 we must substitute the initializer.  */
16784       if (TREE_CODE (d) == VAR_DECL
16785 	  && !DECL_INITIAL (d)
16786 	  && DECL_INITIAL (code_pattern))
16787 	{
16788 	  tree ns;
16789 	  tree init;
16790 
16791 	  ns = decl_namespace_context (d);
16792 	  push_nested_namespace (ns);
16793 	  push_nested_class (DECL_CONTEXT (d));
16794 	  init = tsubst_expr (DECL_INITIAL (code_pattern),
16795 			      args,
16796 			      tf_warning_or_error, NULL_TREE,
16797 			      /*integral_constant_expression_p=*/false);
16798 	  cp_finish_decl (d, init, /*init_const_expr_p=*/false,
16799 			  /*asmspec_tree=*/NULL_TREE,
16800 			  LOOKUP_ONLYCONVERTING);
16801 	  pop_nested_class ();
16802 	  pop_nested_namespace (ns);
16803 	}
16804 
16805       /* We restore the source position here because it's used by
16806 	 add_pending_template.  */
16807       input_location = saved_loc;
16808 
16809       if (at_eof && !pattern_defined
16810 	  && DECL_EXPLICIT_INSTANTIATION (d)
16811 	  && DECL_NOT_REALLY_EXTERN (d))
16812 	/* [temp.explicit]
16813 
16814 	   The definition of a non-exported function template, a
16815 	   non-exported member function template, or a non-exported
16816 	   member function or static data member of a class template
16817 	   shall be present in every translation unit in which it is
16818 	   explicitly instantiated.  */
16819 	permerror (input_location,  "explicit instantiation of %qD "
16820 		   "but no definition available", d);
16821 
16822       /* ??? Historically, we have instantiated inline functions, even
16823 	 when marked as "extern template".  */
16824       if (!(external_p && TREE_CODE (d) == VAR_DECL))
16825 	add_pending_template (d);
16826       goto out;
16827     }
16828   /* Tell the repository that D is available in this translation unit
16829      -- and see if it is supposed to be instantiated here.  */
16830   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
16831     {
16832       /* In a PCH file, despite the fact that the repository hasn't
16833 	 requested instantiation in the PCH it is still possible that
16834 	 an instantiation will be required in a file that includes the
16835 	 PCH.  */
16836       if (pch_file)
16837 	add_pending_template (d);
16838       /* Instantiate inline functions so that the inliner can do its
16839 	 job, even though we'll not be emitting a copy of this
16840 	 function.  */
16841       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
16842 	goto out;
16843     }
16844 
16845   need_push = !cfun || !global_bindings_p ();
16846   if (need_push)
16847     push_to_top_level ();
16848 
16849   /* Mark D as instantiated so that recursive calls to
16850      instantiate_decl do not try to instantiate it again.  */
16851   DECL_TEMPLATE_INSTANTIATED (d) = 1;
16852 
16853   /* Regenerate the declaration in case the template has been modified
16854      by a subsequent redeclaration.  */
16855   regenerate_decl_from_template (d, td);
16856 
16857   /* We already set the file and line above.  Reset them now in case
16858      they changed as a result of calling regenerate_decl_from_template.  */
16859   input_location = DECL_SOURCE_LOCATION (d);
16860 
16861   if (TREE_CODE (d) == VAR_DECL)
16862     {
16863       tree init;
16864 
16865       /* Clear out DECL_RTL; whatever was there before may not be right
16866 	 since we've reset the type of the declaration.  */
16867       SET_DECL_RTL (d, NULL_RTX);
16868       DECL_IN_AGGR_P (d) = 0;
16869 
16870       /* The initializer is placed in DECL_INITIAL by
16871 	 regenerate_decl_from_template.  Pull it out so that
16872 	 cp_finish_decl can process it.  */
16873       init = DECL_INITIAL (d);
16874       DECL_INITIAL (d) = NULL_TREE;
16875       DECL_INITIALIZED_P (d) = 0;
16876 
16877       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
16878 	 initializer.  That function will defer actual emission until
16879 	 we have a chance to determine linkage.  */
16880       DECL_EXTERNAL (d) = 0;
16881 
16882       /* Enter the scope of D so that access-checking works correctly.  */
16883       push_nested_class (DECL_CONTEXT (d));
16884       cp_finish_decl (d, init, false, NULL_TREE, 0);
16885       pop_nested_class ();
16886     }
16887   else if (TREE_CODE (d) == FUNCTION_DECL)
16888     {
16889       htab_t saved_local_specializations;
16890       tree subst_decl;
16891       tree tmpl_parm;
16892       tree spec_parm;
16893 
16894       /* Save away the current list, in case we are instantiating one
16895 	 template from within the body of another.  */
16896       saved_local_specializations = local_specializations;
16897 
16898       /* Set up the list of local specializations.  */
16899       local_specializations = htab_create (37,
16900 					   hash_local_specialization,
16901 					   eq_local_specializations,
16902 					   NULL);
16903 
16904       /* Set up context.  */
16905       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
16906 
16907       /* Create substitution entries for the parameters.  */
16908       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
16909       tmpl_parm = DECL_ARGUMENTS (subst_decl);
16910       spec_parm = DECL_ARGUMENTS (d);
16911       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
16912 	{
16913 	  register_local_specialization (spec_parm, tmpl_parm);
16914 	  spec_parm = skip_artificial_parms_for (d, spec_parm);
16915 	  tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
16916 	}
16917       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
16918 	{
16919 	  register_local_specialization (spec_parm, tmpl_parm);
16920 	  tmpl_parm = TREE_CHAIN (tmpl_parm);
16921 	  spec_parm = TREE_CHAIN (spec_parm);
16922 	}
16923       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
16924         {
16925           /* Register the (value) argument pack as a specialization of
16926              TMPL_PARM, then move on.  */
16927 	  tree argpack = make_fnparm_pack (spec_parm);
16928           register_local_specialization (argpack, tmpl_parm);
16929           tmpl_parm = TREE_CHAIN (tmpl_parm);
16930 	  spec_parm = NULL_TREE;
16931         }
16932       gcc_assert (!spec_parm);
16933 
16934       /* Substitute into the body of the function.  */
16935       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
16936 		   tf_warning_or_error, tmpl,
16937 		   /*integral_constant_expression_p=*/false);
16938 
16939       /* Set the current input_location to the end of the function
16940          so that finish_function knows where we are.  */
16941       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
16942 
16943       /* We don't need the local specializations any more.  */
16944       htab_delete (local_specializations);
16945       local_specializations = saved_local_specializations;
16946 
16947       /* Finish the function.  */
16948       d = finish_function (0);
16949       expand_or_defer_fn (d);
16950     }
16951 
16952   /* We're not deferring instantiation any more.  */
16953   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
16954 
16955   if (need_push)
16956     pop_from_top_level ();
16957 
16958 out:
16959   input_location = saved_loc;
16960   pop_deferring_access_checks ();
16961   pop_tinst_level ();
16962 
16963   timevar_pop (TV_PARSE);
16964 
16965   return d;
16966 }
16967 
16968 /* Run through the list of templates that we wish we could
16969    instantiate, and instantiate any we can.  RETRIES is the
16970    number of times we retry pending template instantiation.  */
16971 
16972 void
16973 instantiate_pending_templates (int retries)
16974 {
16975   int reconsider;
16976   location_t saved_loc = input_location;
16977 
16978   /* Instantiating templates may trigger vtable generation.  This in turn
16979      may require further template instantiations.  We place a limit here
16980      to avoid infinite loop.  */
16981   if (pending_templates && retries >= max_tinst_depth)
16982     {
16983       tree decl = pending_templates->tinst->decl;
16984 
16985       error ("template instantiation depth exceeds maximum of %d"
16986 	     " instantiating %q+D, possibly from virtual table generation"
16987 	     " (use -ftemplate-depth= to increase the maximum)",
16988 	     max_tinst_depth, decl);
16989       if (TREE_CODE (decl) == FUNCTION_DECL)
16990 	/* Pretend that we defined it.  */
16991 	DECL_INITIAL (decl) = error_mark_node;
16992       return;
16993     }
16994 
16995   do
16996     {
16997       struct pending_template **t = &pending_templates;
16998       struct pending_template *last = NULL;
16999       reconsider = 0;
17000       while (*t)
17001 	{
17002 	  tree instantiation = reopen_tinst_level ((*t)->tinst);
17003 	  bool complete = false;
17004 
17005 	  if (TYPE_P (instantiation))
17006 	    {
17007 	      tree fn;
17008 
17009 	      if (!COMPLETE_TYPE_P (instantiation))
17010 		{
17011 		  instantiate_class_template (instantiation);
17012 		  if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
17013 		    for (fn = TYPE_METHODS (instantiation);
17014 			 fn;
17015 			 fn = TREE_CHAIN (fn))
17016 		      if (! DECL_ARTIFICIAL (fn))
17017 			instantiate_decl (fn,
17018 					  /*defer_ok=*/0,
17019 					  /*expl_inst_class_mem_p=*/false);
17020 		  if (COMPLETE_TYPE_P (instantiation))
17021 		    reconsider = 1;
17022 		}
17023 
17024 	      complete = COMPLETE_TYPE_P (instantiation);
17025 	    }
17026 	  else
17027 	    {
17028 	      if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
17029 		  && !DECL_TEMPLATE_INSTANTIATED (instantiation))
17030 		{
17031 		  instantiation
17032 		    = instantiate_decl (instantiation,
17033 					/*defer_ok=*/0,
17034 					/*expl_inst_class_mem_p=*/false);
17035 		  if (DECL_TEMPLATE_INSTANTIATED (instantiation))
17036 		    reconsider = 1;
17037 		}
17038 
17039 	      complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
17040 			  || DECL_TEMPLATE_INSTANTIATED (instantiation));
17041 	    }
17042 
17043 	  if (complete)
17044 	    /* If INSTANTIATION has been instantiated, then we don't
17045 	       need to consider it again in the future.  */
17046 	    *t = (*t)->next;
17047 	  else
17048 	    {
17049 	      last = *t;
17050 	      t = &(*t)->next;
17051 	    }
17052 	  tinst_depth = 0;
17053 	  current_tinst_level = NULL;
17054 	}
17055       last_pending_template = last;
17056     }
17057   while (reconsider);
17058 
17059   input_location = saved_loc;
17060 }
17061 
17062 /* Substitute ARGVEC into T, which is a list of initializers for
17063    either base class or a non-static data member.  The TREE_PURPOSEs
17064    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
17065    instantiate_decl.  */
17066 
17067 static tree
17068 tsubst_initializer_list (tree t, tree argvec)
17069 {
17070   tree inits = NULL_TREE;
17071 
17072   for (; t; t = TREE_CHAIN (t))
17073     {
17074       tree decl;
17075       tree init;
17076       tree expanded_bases = NULL_TREE;
17077       tree expanded_arguments = NULL_TREE;
17078       int i, len = 1;
17079 
17080       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
17081         {
17082           tree expr;
17083           tree arg;
17084 
17085           /* Expand the base class expansion type into separate base
17086              classes.  */
17087           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
17088                                                  tf_warning_or_error,
17089                                                  NULL_TREE);
17090           if (expanded_bases == error_mark_node)
17091             continue;
17092 
17093           /* We'll be building separate TREE_LISTs of arguments for
17094              each base.  */
17095           len = TREE_VEC_LENGTH (expanded_bases);
17096           expanded_arguments = make_tree_vec (len);
17097           for (i = 0; i < len; i++)
17098             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
17099 
17100           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
17101              expand each argument in the TREE_VALUE of t.  */
17102           expr = make_node (EXPR_PACK_EXPANSION);
17103           PACK_EXPANSION_PARAMETER_PACKS (expr) =
17104             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
17105 
17106 	  if (TREE_VALUE (t) == void_type_node)
17107 	    /* VOID_TYPE_NODE is used to indicate
17108 	       value-initialization.  */
17109 	    {
17110 	      for (i = 0; i < len; i++)
17111 		TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
17112 	    }
17113 	  else
17114 	    {
17115 	      /* Substitute parameter packs into each argument in the
17116 		 TREE_LIST.  */
17117 	      in_base_initializer = 1;
17118 	      for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
17119 		{
17120 		  tree expanded_exprs;
17121 
17122 		  /* Expand the argument.  */
17123 		  SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
17124 		  expanded_exprs
17125 		    = tsubst_pack_expansion (expr, argvec,
17126 					     tf_warning_or_error,
17127 					     NULL_TREE);
17128 		  if (expanded_exprs == error_mark_node)
17129 		    continue;
17130 
17131 		  /* Prepend each of the expanded expressions to the
17132 		     corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
17133 		  for (i = 0; i < len; i++)
17134 		    {
17135 		      TREE_VEC_ELT (expanded_arguments, i) =
17136 			tree_cons (NULL_TREE,
17137 				   TREE_VEC_ELT (expanded_exprs, i),
17138 				   TREE_VEC_ELT (expanded_arguments, i));
17139 		    }
17140 		}
17141 	      in_base_initializer = 0;
17142 
17143 	      /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
17144 		 since we built them backwards.  */
17145 	      for (i = 0; i < len; i++)
17146 		{
17147 		  TREE_VEC_ELT (expanded_arguments, i) =
17148 		    nreverse (TREE_VEC_ELT (expanded_arguments, i));
17149 		}
17150 	    }
17151         }
17152 
17153       for (i = 0; i < len; ++i)
17154         {
17155           if (expanded_bases)
17156             {
17157               decl = TREE_VEC_ELT (expanded_bases, i);
17158               decl = expand_member_init (decl);
17159               init = TREE_VEC_ELT (expanded_arguments, i);
17160             }
17161           else
17162             {
17163               decl = tsubst_copy (TREE_PURPOSE (t), argvec,
17164                                   tf_warning_or_error, NULL_TREE);
17165 
17166               decl = expand_member_init (decl);
17167               if (decl && !DECL_P (decl))
17168                 in_base_initializer = 1;
17169 
17170               init = tsubst_expr (TREE_VALUE (t), argvec,
17171 				  tf_warning_or_error, NULL_TREE,
17172                                   /*integral_constant_expression_p=*/false);
17173               in_base_initializer = 0;
17174             }
17175 
17176           if (decl)
17177             {
17178               init = build_tree_list (decl, init);
17179               TREE_CHAIN (init) = inits;
17180               inits = init;
17181             }
17182         }
17183     }
17184   return inits;
17185 }
17186 
17187 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
17188 
17189 static void
17190 set_current_access_from_decl (tree decl)
17191 {
17192   if (TREE_PRIVATE (decl))
17193     current_access_specifier = access_private_node;
17194   else if (TREE_PROTECTED (decl))
17195     current_access_specifier = access_protected_node;
17196   else
17197     current_access_specifier = access_public_node;
17198 }
17199 
17200 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
17201    is the instantiation (which should have been created with
17202    start_enum) and ARGS are the template arguments to use.  */
17203 
17204 static void
17205 tsubst_enum (tree tag, tree newtag, tree args)
17206 {
17207   tree e;
17208 
17209   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
17210     {
17211       tree value;
17212       tree decl;
17213 
17214       decl = TREE_VALUE (e);
17215       /* Note that in a template enum, the TREE_VALUE is the
17216 	 CONST_DECL, not the corresponding INTEGER_CST.  */
17217       value = tsubst_expr (DECL_INITIAL (decl),
17218 			   args, tf_warning_or_error, NULL_TREE,
17219 			   /*integral_constant_expression_p=*/true);
17220 
17221       /* Give this enumeration constant the correct access.  */
17222       set_current_access_from_decl (decl);
17223 
17224       /* Actually build the enumerator itself.  */
17225       build_enumerator (DECL_NAME (decl), value, newtag);
17226     }
17227 
17228   finish_enum (newtag);
17229   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
17230     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
17231 }
17232 
17233 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
17234    its type -- but without substituting the innermost set of template
17235    arguments.  So, innermost set of template parameters will appear in
17236    the type.  */
17237 
17238 tree
17239 get_mostly_instantiated_function_type (tree decl)
17240 {
17241   tree fn_type;
17242   tree tmpl;
17243   tree targs;
17244   tree tparms;
17245   int parm_depth;
17246 
17247   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
17248   targs = DECL_TI_ARGS (decl);
17249   tparms = DECL_TEMPLATE_PARMS (tmpl);
17250   parm_depth = TMPL_PARMS_DEPTH (tparms);
17251 
17252   /* There should be as many levels of arguments as there are levels
17253      of parameters.  */
17254   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
17255 
17256   fn_type = TREE_TYPE (tmpl);
17257 
17258   if (parm_depth == 1)
17259     /* No substitution is necessary.  */
17260     ;
17261   else
17262     {
17263       int i, save_access_control;
17264       tree partial_args;
17265 
17266       /* Replace the innermost level of the TARGS with NULL_TREEs to
17267 	 let tsubst know not to substitute for those parameters.  */
17268       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
17269       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
17270 	SET_TMPL_ARGS_LEVEL (partial_args, i,
17271 			     TMPL_ARGS_LEVEL (targs, i));
17272       SET_TMPL_ARGS_LEVEL (partial_args,
17273 			   TMPL_ARGS_DEPTH (targs),
17274 			   make_tree_vec (DECL_NTPARMS (tmpl)));
17275 
17276       /* Disable access control as this function is used only during
17277 	 name-mangling.  */
17278       save_access_control = flag_access_control;
17279       flag_access_control = 0;
17280 
17281       ++processing_template_decl;
17282       /* Now, do the (partial) substitution to figure out the
17283 	 appropriate function type.  */
17284       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
17285       --processing_template_decl;
17286 
17287       /* Substitute into the template parameters to obtain the real
17288 	 innermost set of parameters.  This step is important if the
17289 	 innermost set of template parameters contains value
17290 	 parameters whose types depend on outer template parameters.  */
17291       TREE_VEC_LENGTH (partial_args)--;
17292       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
17293 
17294       flag_access_control = save_access_control;
17295     }
17296 
17297   return fn_type;
17298 }
17299 
17300 /* Return truthvalue if we're processing a template different from
17301    the last one involved in diagnostics.  */
17302 int
17303 problematic_instantiation_changed (void)
17304 {
17305   return last_template_error_tick != tinst_level_tick;
17306 }
17307 
17308 /* Remember current template involved in diagnostics.  */
17309 void
17310 record_last_problematic_instantiation (void)
17311 {
17312   last_template_error_tick = tinst_level_tick;
17313 }
17314 
17315 struct tinst_level *
17316 current_instantiation (void)
17317 {
17318   return current_tinst_level;
17319 }
17320 
17321 /* [temp.param] Check that template non-type parm TYPE is of an allowable
17322    type. Return zero for ok, nonzero for disallowed. Issue error and
17323    warning messages under control of COMPLAIN.  */
17324 
17325 static int
17326 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
17327 {
17328   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
17329     return 0;
17330   else if (POINTER_TYPE_P (type))
17331     return 0;
17332   else if (TYPE_PTR_TO_MEMBER_P (type))
17333     return 0;
17334   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
17335     return 0;
17336   else if (TREE_CODE (type) == TYPENAME_TYPE)
17337     return 0;
17338 
17339   if (complain & tf_error)
17340     error ("%q#T is not a valid type for a template constant parameter", type);
17341   return 1;
17342 }
17343 
17344 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
17345    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
17346 
17347 static bool
17348 dependent_type_p_r (tree type)
17349 {
17350   tree scope;
17351 
17352   /* [temp.dep.type]
17353 
17354      A type is dependent if it is:
17355 
17356      -- a template parameter. Template template parameters are types
17357 	for us (since TYPE_P holds true for them) so we handle
17358 	them here.  */
17359   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
17360       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
17361     return true;
17362   /* -- a qualified-id with a nested-name-specifier which contains a
17363 	class-name that names a dependent type or whose unqualified-id
17364 	names a dependent type.  */
17365   if (TREE_CODE (type) == TYPENAME_TYPE)
17366     return true;
17367   /* -- a cv-qualified type where the cv-unqualified type is
17368 	dependent.  */
17369   type = TYPE_MAIN_VARIANT (type);
17370   /* -- a compound type constructed from any dependent type.  */
17371   if (TYPE_PTR_TO_MEMBER_P (type))
17372     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
17373 	    || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
17374 					   (type)));
17375   else if (TREE_CODE (type) == POINTER_TYPE
17376 	   || TREE_CODE (type) == REFERENCE_TYPE)
17377     return dependent_type_p (TREE_TYPE (type));
17378   else if (TREE_CODE (type) == FUNCTION_TYPE
17379 	   || TREE_CODE (type) == METHOD_TYPE)
17380     {
17381       tree arg_type;
17382 
17383       if (dependent_type_p (TREE_TYPE (type)))
17384 	return true;
17385       for (arg_type = TYPE_ARG_TYPES (type);
17386 	   arg_type;
17387 	   arg_type = TREE_CHAIN (arg_type))
17388 	if (dependent_type_p (TREE_VALUE (arg_type)))
17389 	  return true;
17390       return false;
17391     }
17392   /* -- an array type constructed from any dependent type or whose
17393 	size is specified by a constant expression that is
17394 	value-dependent.  */
17395   if (TREE_CODE (type) == ARRAY_TYPE)
17396     {
17397       if (TYPE_DOMAIN (type)
17398 	  && dependent_type_p (TYPE_DOMAIN (type)))
17399 	return true;
17400       return dependent_type_p (TREE_TYPE (type));
17401     }
17402   else if (TREE_CODE (type) == INTEGER_TYPE
17403 	   && !TREE_CONSTANT (TYPE_MAX_VALUE (type)))
17404     {
17405       /* If this is the TYPE_DOMAIN of an array type, consider it
17406 	 dependent.  We already checked for value-dependence in
17407 	 compute_array_index_type.  */
17408       return type_dependent_expression_p (TYPE_MAX_VALUE (type));
17409     }
17410 
17411   /* -- a template-id in which either the template name is a template
17412      parameter ...  */
17413   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
17414     return true;
17415   /* ... or any of the template arguments is a dependent type or
17416 	an expression that is type-dependent or value-dependent.  */
17417   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
17418 	   && (any_dependent_template_arguments_p
17419 	       (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
17420     return true;
17421 
17422   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
17423      argument of the `typeof' expression is not type-dependent, then
17424      it should already been have resolved.  */
17425   if (TREE_CODE (type) == TYPEOF_TYPE
17426       || TREE_CODE (type) == DECLTYPE_TYPE)
17427     return true;
17428 
17429   /* A template argument pack is dependent if any of its packed
17430      arguments are.  */
17431   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
17432     {
17433       tree args = ARGUMENT_PACK_ARGS (type);
17434       int i, len = TREE_VEC_LENGTH (args);
17435       for (i = 0; i < len; ++i)
17436         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
17437           return true;
17438     }
17439 
17440   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
17441      be template parameters.  */
17442   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
17443     return true;
17444 
17445   /* The standard does not specifically mention types that are local
17446      to template functions or local classes, but they should be
17447      considered dependent too.  For example:
17448 
17449        template <int I> void f() {
17450 	 enum E { a = I };
17451 	 S<sizeof (E)> s;
17452        }
17453 
17454      The size of `E' cannot be known until the value of `I' has been
17455      determined.  Therefore, `E' must be considered dependent.  */
17456   scope = TYPE_CONTEXT (type);
17457   if (scope && TYPE_P (scope))
17458     return dependent_type_p (scope);
17459   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
17460     return type_dependent_expression_p (scope);
17461 
17462   /* Other types are non-dependent.  */
17463   return false;
17464 }
17465 
17466 /* Returns TRUE if TYPE is dependent, in the sense of
17467    [temp.dep.type].  */
17468 
17469 bool
17470 dependent_type_p (tree type)
17471 {
17472   /* If there are no template parameters in scope, then there can't be
17473      any dependent types.  */
17474   if (!processing_template_decl)
17475     {
17476       /* If we are not processing a template, then nobody should be
17477 	 providing us with a dependent type.  */
17478       gcc_assert (type);
17479       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
17480       return false;
17481     }
17482 
17483   /* If the type is NULL, we have not computed a type for the entity
17484      in question; in that case, the type is dependent.  */
17485   if (!type)
17486     return true;
17487 
17488   /* Erroneous types can be considered non-dependent.  */
17489   if (type == error_mark_node)
17490     return false;
17491 
17492   /* If we have not already computed the appropriate value for TYPE,
17493      do so now.  */
17494   if (!TYPE_DEPENDENT_P_VALID (type))
17495     {
17496       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
17497       TYPE_DEPENDENT_P_VALID (type) = 1;
17498     }
17499 
17500   return TYPE_DEPENDENT_P (type);
17501 }
17502 
17503 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
17504    lookup.  In other words, a dependent type that is not the current
17505    instantiation.  */
17506 
17507 bool
17508 dependent_scope_p (tree scope)
17509 {
17510   return (scope && TYPE_P (scope) && dependent_type_p (scope)
17511 	  && !currently_open_class (scope));
17512 }
17513 
17514 /* Returns TRUE if EXPRESSION is dependent, according to CRITERION.  */
17515 
17516 static bool
17517 dependent_scope_ref_p (tree expression, bool criterion (tree))
17518 {
17519   tree scope;
17520   tree name;
17521 
17522   gcc_assert (TREE_CODE (expression) == SCOPE_REF);
17523 
17524   if (!TYPE_P (TREE_OPERAND (expression, 0)))
17525     return true;
17526 
17527   scope = TREE_OPERAND (expression, 0);
17528   name = TREE_OPERAND (expression, 1);
17529 
17530   /* [temp.dep.expr]
17531 
17532      An id-expression is type-dependent if it contains a
17533      nested-name-specifier that contains a class-name that names a
17534      dependent type.  */
17535   /* The suggested resolution to Core Issue 224 implies that if the
17536      qualifying type is the current class, then we must peek
17537      inside it.  */
17538   if (DECL_P (name)
17539       && currently_open_class (scope)
17540       && !criterion (name))
17541     return false;
17542   if (dependent_type_p (scope))
17543     return true;
17544 
17545   return false;
17546 }
17547 
17548 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
17549    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
17550    expression.  */
17551 
17552 bool
17553 value_dependent_expression_p (tree expression)
17554 {
17555   if (!processing_template_decl)
17556     return false;
17557 
17558   /* A name declared with a dependent type.  */
17559   if (DECL_P (expression) && type_dependent_expression_p (expression))
17560     return true;
17561 
17562   switch (TREE_CODE (expression))
17563     {
17564     case IDENTIFIER_NODE:
17565       /* A name that has not been looked up -- must be dependent.  */
17566       return true;
17567 
17568     case TEMPLATE_PARM_INDEX:
17569       /* A non-type template parm.  */
17570       return true;
17571 
17572     case CONST_DECL:
17573       /* A non-type template parm.  */
17574       if (DECL_TEMPLATE_PARM_P (expression))
17575 	return true;
17576       return value_dependent_expression_p (DECL_INITIAL (expression));
17577 
17578     case VAR_DECL:
17579        /* A constant with integral or enumeration type and is initialized
17580 	  with an expression that is value-dependent.  */
17581       if (DECL_INITIAL (expression)
17582 	  && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
17583 	  && value_dependent_expression_p (DECL_INITIAL (expression)))
17584 	return true;
17585       return false;
17586 
17587     case DYNAMIC_CAST_EXPR:
17588     case STATIC_CAST_EXPR:
17589     case CONST_CAST_EXPR:
17590     case REINTERPRET_CAST_EXPR:
17591     case CAST_EXPR:
17592       /* These expressions are value-dependent if the type to which
17593 	 the cast occurs is dependent or the expression being casted
17594 	 is value-dependent.  */
17595       {
17596 	tree type = TREE_TYPE (expression);
17597 
17598 	if (dependent_type_p (type))
17599 	  return true;
17600 
17601 	/* A functional cast has a list of operands.  */
17602 	expression = TREE_OPERAND (expression, 0);
17603 	if (!expression)
17604 	  {
17605 	    /* If there are no operands, it must be an expression such
17606 	       as "int()". This should not happen for aggregate types
17607 	       because it would form non-constant expressions.  */
17608 	    gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
17609 
17610 	    return false;
17611 	  }
17612 
17613 	if (TREE_CODE (expression) == TREE_LIST)
17614 	  return any_value_dependent_elements_p (expression);
17615 
17616 	return value_dependent_expression_p (expression);
17617       }
17618 
17619     case SIZEOF_EXPR:
17620     case ALIGNOF_EXPR:
17621       /* A `sizeof' expression is value-dependent if the operand is
17622 	 type-dependent or is a pack expansion.  */
17623       expression = TREE_OPERAND (expression, 0);
17624       if (PACK_EXPANSION_P (expression))
17625         return true;
17626       else if (TYPE_P (expression))
17627 	return dependent_type_p (expression);
17628       return type_dependent_expression_p (expression);
17629 
17630     case SCOPE_REF:
17631       return dependent_scope_ref_p (expression, value_dependent_expression_p);
17632 
17633     case COMPONENT_REF:
17634       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
17635 	      || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
17636 
17637     case CALL_EXPR:
17638       /* A CALL_EXPR may appear in a constant expression if it is a
17639 	 call to a builtin function, e.g., __builtin_constant_p.  All
17640 	 such calls are value-dependent.  */
17641       return true;
17642 
17643     case NONTYPE_ARGUMENT_PACK:
17644       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
17645          is value-dependent.  */
17646       {
17647         tree values = ARGUMENT_PACK_ARGS (expression);
17648         int i, len = TREE_VEC_LENGTH (values);
17649 
17650         for (i = 0; i < len; ++i)
17651           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
17652             return true;
17653 
17654         return false;
17655       }
17656 
17657     case TRAIT_EXPR:
17658       {
17659 	tree type2 = TRAIT_EXPR_TYPE2 (expression);
17660 	return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
17661 		|| (type2 ? dependent_type_p (type2) : false));
17662       }
17663 
17664     case MODOP_EXPR:
17665       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
17666 	      || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
17667 
17668     case ADDR_EXPR:
17669       {
17670 	tree op = TREE_OPERAND (expression, 0);
17671 	return (value_dependent_expression_p (op)
17672 		|| has_value_dependent_address (op));
17673       }
17674 
17675     default:
17676       /* A constant expression is value-dependent if any subexpression is
17677 	 value-dependent.  */
17678       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
17679 	{
17680 	case tcc_reference:
17681 	case tcc_unary:
17682 	  return (value_dependent_expression_p
17683 		  (TREE_OPERAND (expression, 0)));
17684 
17685 	case tcc_comparison:
17686 	case tcc_binary:
17687 	  return ((value_dependent_expression_p
17688 		   (TREE_OPERAND (expression, 0)))
17689 		  || (value_dependent_expression_p
17690 		      (TREE_OPERAND (expression, 1))));
17691 
17692 	case tcc_expression:
17693 	case tcc_vl_exp:
17694 	  {
17695 	    int i;
17696 	    for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
17697 	      /* In some cases, some of the operands may be missing.
17698 		 (For example, in the case of PREDECREMENT_EXPR, the
17699 		 amount to increment by may be missing.)  That doesn't
17700 		 make the expression dependent.  */
17701 	      if (TREE_OPERAND (expression, i)
17702 		  && (value_dependent_expression_p
17703 		      (TREE_OPERAND (expression, i))))
17704 		return true;
17705 	    return false;
17706 	  }
17707 
17708 	default:
17709 	  break;
17710 	}
17711     }
17712 
17713   /* The expression is not value-dependent.  */
17714   return false;
17715 }
17716 
17717 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
17718    [temp.dep.expr].  */
17719 
17720 bool
17721 type_dependent_expression_p (tree expression)
17722 {
17723   if (!processing_template_decl)
17724     return false;
17725 
17726   if (expression == error_mark_node)
17727     return false;
17728 
17729   /* An unresolved name is always dependent.  */
17730   if (TREE_CODE (expression) == IDENTIFIER_NODE
17731       || TREE_CODE (expression) == USING_DECL)
17732     return true;
17733 
17734   /* Some expression forms are never type-dependent.  */
17735   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
17736       || TREE_CODE (expression) == SIZEOF_EXPR
17737       || TREE_CODE (expression) == ALIGNOF_EXPR
17738       || TREE_CODE (expression) == TRAIT_EXPR
17739       || TREE_CODE (expression) == TYPEID_EXPR
17740       || TREE_CODE (expression) == DELETE_EXPR
17741       || TREE_CODE (expression) == VEC_DELETE_EXPR
17742       || TREE_CODE (expression) == THROW_EXPR)
17743     return false;
17744 
17745   /* The types of these expressions depends only on the type to which
17746      the cast occurs.  */
17747   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
17748       || TREE_CODE (expression) == STATIC_CAST_EXPR
17749       || TREE_CODE (expression) == CONST_CAST_EXPR
17750       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
17751       || TREE_CODE (expression) == CAST_EXPR)
17752     return dependent_type_p (TREE_TYPE (expression));
17753 
17754   /* The types of these expressions depends only on the type created
17755      by the expression.  */
17756   if (TREE_CODE (expression) == NEW_EXPR
17757       || TREE_CODE (expression) == VEC_NEW_EXPR)
17758     {
17759       /* For NEW_EXPR tree nodes created inside a template, either
17760 	 the object type itself or a TREE_LIST may appear as the
17761 	 operand 1.  */
17762       tree type = TREE_OPERAND (expression, 1);
17763       if (TREE_CODE (type) == TREE_LIST)
17764 	/* This is an array type.  We need to check array dimensions
17765 	   as well.  */
17766 	return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
17767 	       || value_dependent_expression_p
17768 		    (TREE_OPERAND (TREE_VALUE (type), 1));
17769       else
17770 	return dependent_type_p (type);
17771     }
17772 
17773   if (TREE_CODE (expression) == SCOPE_REF
17774       && dependent_scope_ref_p (expression,
17775 				type_dependent_expression_p))
17776     return true;
17777 
17778   if (TREE_CODE (expression) == FUNCTION_DECL
17779       && DECL_LANG_SPECIFIC (expression)
17780       && DECL_TEMPLATE_INFO (expression)
17781       && (any_dependent_template_arguments_p
17782 	  (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
17783     return true;
17784 
17785   if (TREE_CODE (expression) == TEMPLATE_DECL
17786       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
17787     return false;
17788 
17789   if (TREE_CODE (expression) == STMT_EXPR)
17790     expression = stmt_expr_value_expr (expression);
17791 
17792   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
17793     {
17794       tree elt;
17795       unsigned i;
17796 
17797       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
17798 	{
17799 	  if (type_dependent_expression_p (elt))
17800 	    return true;
17801 	}
17802       return false;
17803     }
17804 
17805   if (TREE_TYPE (expression) == unknown_type_node)
17806     {
17807       if (TREE_CODE (expression) == ADDR_EXPR)
17808 	return type_dependent_expression_p (TREE_OPERAND (expression, 0));
17809       if (TREE_CODE (expression) == COMPONENT_REF
17810 	  || TREE_CODE (expression) == OFFSET_REF)
17811 	{
17812 	  if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
17813 	    return true;
17814 	  expression = TREE_OPERAND (expression, 1);
17815 	  if (TREE_CODE (expression) == IDENTIFIER_NODE)
17816 	    return false;
17817 	}
17818       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
17819       if (TREE_CODE (expression) == SCOPE_REF)
17820 	return false;
17821 
17822       if (TREE_CODE (expression) == BASELINK)
17823 	expression = BASELINK_FUNCTIONS (expression);
17824 
17825       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
17826 	{
17827 	  if (any_dependent_template_arguments_p
17828 	      (TREE_OPERAND (expression, 1)))
17829 	    return true;
17830 	  expression = TREE_OPERAND (expression, 0);
17831 	}
17832       gcc_assert (TREE_CODE (expression) == OVERLOAD
17833 		  || TREE_CODE (expression) == FUNCTION_DECL);
17834 
17835       while (expression)
17836 	{
17837 	  if (type_dependent_expression_p (OVL_CURRENT (expression)))
17838 	    return true;
17839 	  expression = OVL_NEXT (expression);
17840 	}
17841       return false;
17842     }
17843 
17844   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
17845 
17846   return (dependent_type_p (TREE_TYPE (expression)));
17847 }
17848 
17849 /* Like type_dependent_expression_p, but it also works while not processing
17850    a template definition, i.e. during substitution or mangling.  */
17851 
17852 bool
17853 type_dependent_expression_p_push (tree expr)
17854 {
17855   bool b;
17856   ++processing_template_decl;
17857   b = type_dependent_expression_p (expr);
17858   --processing_template_decl;
17859   return b;
17860 }
17861 
17862 /* Returns TRUE if ARGS contains a type-dependent expression.  */
17863 
17864 bool
17865 any_type_dependent_arguments_p (const VEC(tree,gc) *args)
17866 {
17867   unsigned int i;
17868   tree arg;
17869 
17870   for (i = 0; VEC_iterate (tree, args, i, arg); ++i)
17871     {
17872       if (type_dependent_expression_p (arg))
17873 	return true;
17874     }
17875   return false;
17876 }
17877 
17878 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
17879    expressions) contains any value-dependent expressions.  */
17880 
17881 bool
17882 any_value_dependent_elements_p (const_tree list)
17883 {
17884   for (; list; list = TREE_CHAIN (list))
17885     if (value_dependent_expression_p (TREE_VALUE (list)))
17886       return true;
17887 
17888   return false;
17889 }
17890 
17891 /* Returns TRUE if the ARG (a template argument) is dependent.  */
17892 
17893 bool
17894 dependent_template_arg_p (tree arg)
17895 {
17896   if (!processing_template_decl)
17897     return false;
17898 
17899   if (TREE_CODE (arg) == TEMPLATE_DECL
17900       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
17901     return dependent_template_p (arg);
17902   else if (ARGUMENT_PACK_P (arg))
17903     {
17904       tree args = ARGUMENT_PACK_ARGS (arg);
17905       int i, len = TREE_VEC_LENGTH (args);
17906       for (i = 0; i < len; ++i)
17907         {
17908           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
17909             return true;
17910         }
17911 
17912       return false;
17913     }
17914   else if (TYPE_P (arg))
17915     return dependent_type_p (arg);
17916   else
17917     return (type_dependent_expression_p (arg)
17918 	    || value_dependent_expression_p (arg));
17919 }
17920 
17921 /* Returns true if ARGS (a collection of template arguments) contains
17922    any types that require structural equality testing.  */
17923 
17924 bool
17925 any_template_arguments_need_structural_equality_p (tree args)
17926 {
17927   int i;
17928   int j;
17929 
17930   if (!args)
17931     return false;
17932   if (args == error_mark_node)
17933     return true;
17934 
17935   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
17936     {
17937       tree level = TMPL_ARGS_LEVEL (args, i + 1);
17938       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
17939 	{
17940 	  tree arg = TREE_VEC_ELT (level, j);
17941 	  tree packed_args = NULL_TREE;
17942 	  int k, len = 1;
17943 
17944 	  if (ARGUMENT_PACK_P (arg))
17945 	    {
17946 	      /* Look inside the argument pack.  */
17947 	      packed_args = ARGUMENT_PACK_ARGS (arg);
17948 	      len = TREE_VEC_LENGTH (packed_args);
17949 	    }
17950 
17951 	  for (k = 0; k < len; ++k)
17952 	    {
17953 	      if (packed_args)
17954 		arg = TREE_VEC_ELT (packed_args, k);
17955 
17956 	      if (error_operand_p (arg))
17957 		return true;
17958 	      else if (TREE_CODE (arg) == TEMPLATE_DECL
17959 		       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
17960 		continue;
17961 	      else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
17962 		return true;
17963 	      else if (!TYPE_P (arg) && TREE_TYPE (arg)
17964 		       && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
17965 		return true;
17966 	    }
17967 	}
17968     }
17969 
17970   return false;
17971 }
17972 
17973 /* Returns true if ARGS (a collection of template arguments) contains
17974    any dependent arguments.  */
17975 
17976 bool
17977 any_dependent_template_arguments_p (const_tree args)
17978 {
17979   int i;
17980   int j;
17981 
17982   if (!args)
17983     return false;
17984   if (args == error_mark_node)
17985     return true;
17986 
17987   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
17988     {
17989       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
17990       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
17991 	if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
17992 	  return true;
17993     }
17994 
17995   return false;
17996 }
17997 
17998 /* Returns TRUE if the template TMPL is dependent.  */
17999 
18000 bool
18001 dependent_template_p (tree tmpl)
18002 {
18003   if (TREE_CODE (tmpl) == OVERLOAD)
18004     {
18005       while (tmpl)
18006 	{
18007 	  if (dependent_template_p (OVL_FUNCTION (tmpl)))
18008 	    return true;
18009 	  tmpl = OVL_CHAIN (tmpl);
18010 	}
18011       return false;
18012     }
18013 
18014   /* Template template parameters are dependent.  */
18015   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
18016       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
18017     return true;
18018   /* So are names that have not been looked up.  */
18019   if (TREE_CODE (tmpl) == SCOPE_REF
18020       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
18021     return true;
18022   /* So are member templates of dependent classes.  */
18023   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
18024     return dependent_type_p (DECL_CONTEXT (tmpl));
18025   return false;
18026 }
18027 
18028 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
18029 
18030 bool
18031 dependent_template_id_p (tree tmpl, tree args)
18032 {
18033   return (dependent_template_p (tmpl)
18034 	  || any_dependent_template_arguments_p (args));
18035 }
18036 
18037 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
18038    is dependent.  */
18039 
18040 bool
18041 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
18042 {
18043   int i;
18044 
18045   if (!processing_template_decl)
18046     return false;
18047 
18048   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
18049     {
18050       tree decl = TREE_VEC_ELT (declv, i);
18051       tree init = TREE_VEC_ELT (initv, i);
18052       tree cond = TREE_VEC_ELT (condv, i);
18053       tree incr = TREE_VEC_ELT (incrv, i);
18054 
18055       if (type_dependent_expression_p (decl))
18056 	return true;
18057 
18058       if (init && type_dependent_expression_p (init))
18059 	return true;
18060 
18061       if (type_dependent_expression_p (cond))
18062 	return true;
18063 
18064       if (COMPARISON_CLASS_P (cond)
18065 	  && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
18066 	      || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
18067 	return true;
18068 
18069       if (TREE_CODE (incr) == MODOP_EXPR)
18070 	{
18071 	  if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
18072 	      || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
18073 	    return true;
18074 	}
18075       else if (type_dependent_expression_p (incr))
18076 	return true;
18077       else if (TREE_CODE (incr) == MODIFY_EXPR)
18078 	{
18079 	  if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
18080 	    return true;
18081 	  else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
18082 	    {
18083 	      tree t = TREE_OPERAND (incr, 1);
18084 	      if (type_dependent_expression_p (TREE_OPERAND (t, 0))
18085 		  || type_dependent_expression_p (TREE_OPERAND (t, 1)))
18086 		return true;
18087 	    }
18088 	}
18089     }
18090 
18091   return false;
18092 }
18093 
18094 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
18095    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
18096    no such TYPE can be found.  Note that this function peers inside
18097    uninstantiated templates and therefore should be used only in
18098    extremely limited situations.  ONLY_CURRENT_P restricts this
18099    peering to the currently open classes hierarchy (which is required
18100    when comparing types).  */
18101 
18102 tree
18103 resolve_typename_type (tree type, bool only_current_p)
18104 {
18105   tree scope;
18106   tree name;
18107   tree decl;
18108   int quals;
18109   tree pushed_scope;
18110   tree result;
18111 
18112   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
18113 
18114   scope = TYPE_CONTEXT (type);
18115   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
18116      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
18117      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
18118      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
18119      identifier  of the TYPENAME_TYPE anymore.
18120      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
18121      TYPENAME_TYPE instead, we avoid messing up with a possible
18122      typedef variant case.  */
18123   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
18124 
18125   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
18126      it first before we can figure out what NAME refers to.  */
18127   if (TREE_CODE (scope) == TYPENAME_TYPE)
18128     scope = resolve_typename_type (scope, only_current_p);
18129   /* If we don't know what SCOPE refers to, then we cannot resolve the
18130      TYPENAME_TYPE.  */
18131   if (TREE_CODE (scope) == TYPENAME_TYPE)
18132     return type;
18133   /* If the SCOPE is a template type parameter, we have no way of
18134      resolving the name.  */
18135   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
18136     return type;
18137   /* If the SCOPE is not the current instantiation, there's no reason
18138      to look inside it.  */
18139   if (only_current_p && !currently_open_class (scope))
18140     return type;
18141   /* If this is a typedef, we don't want to look inside (c++/11987).  */
18142   if (typedef_variant_p (type))
18143     return type;
18144   /* If SCOPE isn't the template itself, it will not have a valid
18145      TYPE_FIELDS list.  */
18146   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
18147     /* scope is either the template itself or a compatible instantiation
18148        like X<T>, so look up the name in the original template.  */
18149     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
18150   else
18151     /* scope is a partial instantiation, so we can't do the lookup or we
18152        will lose the template arguments.  */
18153     return type;
18154   /* Enter the SCOPE so that name lookup will be resolved as if we
18155      were in the class definition.  In particular, SCOPE will no
18156      longer be considered a dependent type.  */
18157   pushed_scope = push_scope (scope);
18158   /* Look up the declaration.  */
18159   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
18160 
18161   result = NULL_TREE;
18162 
18163   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
18164      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
18165   if (!decl)
18166     /*nop*/;
18167   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
18168 	   && TREE_CODE (decl) == TYPE_DECL)
18169     {
18170       result = TREE_TYPE (decl);
18171       if (result == error_mark_node)
18172 	result = NULL_TREE;
18173     }
18174   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
18175 	   && DECL_CLASS_TEMPLATE_P (decl))
18176     {
18177       tree tmpl;
18178       tree args;
18179       /* Obtain the template and the arguments.  */
18180       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
18181       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
18182       /* Instantiate the template.  */
18183       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
18184 				      /*entering_scope=*/0,
18185 				      tf_error | tf_user);
18186       if (result == error_mark_node)
18187 	result = NULL_TREE;
18188     }
18189 
18190   /* Leave the SCOPE.  */
18191   if (pushed_scope)
18192     pop_scope (pushed_scope);
18193 
18194   /* If we failed to resolve it, return the original typename.  */
18195   if (!result)
18196     return type;
18197 
18198   /* If lookup found a typename type, resolve that too.  */
18199   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
18200     {
18201       /* Ill-formed programs can cause infinite recursion here, so we
18202 	 must catch that.  */
18203       TYPENAME_IS_RESOLVING_P (type) = 1;
18204       result = resolve_typename_type (result, only_current_p);
18205       TYPENAME_IS_RESOLVING_P (type) = 0;
18206     }
18207 
18208   /* Qualify the resulting type.  */
18209   quals = cp_type_quals (type);
18210   if (quals)
18211     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
18212 
18213   return result;
18214 }
18215 
18216 /* EXPR is an expression which is not type-dependent.  Return a proxy
18217    for EXPR that can be used to compute the types of larger
18218    expressions containing EXPR.  */
18219 
18220 tree
18221 build_non_dependent_expr (tree expr)
18222 {
18223   tree inner_expr;
18224 
18225   /* Preserve null pointer constants so that the type of things like
18226      "p == 0" where "p" is a pointer can be determined.  */
18227   if (null_ptr_cst_p (expr))
18228     return expr;
18229   /* Preserve OVERLOADs; the functions must be available to resolve
18230      types.  */
18231   inner_expr = expr;
18232   if (TREE_CODE (inner_expr) == STMT_EXPR)
18233     inner_expr = stmt_expr_value_expr (inner_expr);
18234   if (TREE_CODE (inner_expr) == ADDR_EXPR)
18235     inner_expr = TREE_OPERAND (inner_expr, 0);
18236   if (TREE_CODE (inner_expr) == COMPONENT_REF)
18237     inner_expr = TREE_OPERAND (inner_expr, 1);
18238   if (is_overloaded_fn (inner_expr)
18239       || TREE_CODE (inner_expr) == OFFSET_REF)
18240     return expr;
18241   /* There is no need to return a proxy for a variable.  */
18242   if (TREE_CODE (expr) == VAR_DECL)
18243     return expr;
18244   /* Preserve string constants; conversions from string constants to
18245      "char *" are allowed, even though normally a "const char *"
18246      cannot be used to initialize a "char *".  */
18247   if (TREE_CODE (expr) == STRING_CST)
18248     return expr;
18249   /* Preserve arithmetic constants, as an optimization -- there is no
18250      reason to create a new node.  */
18251   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
18252     return expr;
18253   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
18254      There is at least one place where we want to know that a
18255      particular expression is a throw-expression: when checking a ?:
18256      expression, there are special rules if the second or third
18257      argument is a throw-expression.  */
18258   if (TREE_CODE (expr) == THROW_EXPR)
18259     return expr;
18260 
18261   if (TREE_CODE (expr) == COND_EXPR)
18262     return build3 (COND_EXPR,
18263 		   TREE_TYPE (expr),
18264 		   TREE_OPERAND (expr, 0),
18265 		   (TREE_OPERAND (expr, 1)
18266 		    ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
18267 		    : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
18268 		   build_non_dependent_expr (TREE_OPERAND (expr, 2)));
18269   if (TREE_CODE (expr) == COMPOUND_EXPR
18270       && !COMPOUND_EXPR_OVERLOADED (expr))
18271     return build2 (COMPOUND_EXPR,
18272 		   TREE_TYPE (expr),
18273 		   TREE_OPERAND (expr, 0),
18274 		   build_non_dependent_expr (TREE_OPERAND (expr, 1)));
18275 
18276   /* If the type is unknown, it can't really be non-dependent */
18277   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
18278 
18279   /* Otherwise, build a NON_DEPENDENT_EXPR.
18280 
18281      REFERENCE_TYPEs are not stripped for expressions in templates
18282      because doing so would play havoc with mangling.  Consider, for
18283      example:
18284 
18285        template <typename T> void f<T& g>() { g(); }
18286 
18287      In the body of "f", the expression for "g" will have
18288      REFERENCE_TYPE, even though the standard says that it should
18289      not.  The reason is that we must preserve the syntactic form of
18290      the expression so that mangling (say) "f<g>" inside the body of
18291      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
18292      stripped here.  */
18293   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
18294 }
18295 
18296 /* ARGS is a vector of expressions as arguments to a function call.
18297    Replace the arguments with equivalent non-dependent expressions.
18298    This modifies ARGS in place.  */
18299 
18300 void
18301 make_args_non_dependent (VEC(tree,gc) *args)
18302 {
18303   unsigned int ix;
18304   tree arg;
18305 
18306   for (ix = 0; VEC_iterate (tree, args, ix, arg); ++ix)
18307     {
18308       tree newarg = build_non_dependent_expr (arg);
18309       if (newarg != arg)
18310 	VEC_replace (tree, args, ix, newarg);
18311     }
18312 }
18313 
18314 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
18315    with a level one deeper than the actual template parms.  */
18316 
18317 tree
18318 make_auto (void)
18319 {
18320   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
18321   TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
18322 			       TYPE_DECL, get_identifier ("auto"), au);
18323   TYPE_STUB_DECL (au) = TYPE_NAME (au);
18324   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
18325     (0, processing_template_decl + 1, processing_template_decl + 1,
18326      TYPE_NAME (au), NULL_TREE);
18327   TYPE_CANONICAL (au) = canonical_type_parameter (au);
18328   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
18329   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
18330 
18331   return au;
18332 }
18333 
18334 /* Given type ARG, return std::initializer_list<ARG>.  */
18335 
18336 static tree
18337 listify (tree arg)
18338 {
18339   tree std_init_list = namespace_binding
18340     (get_identifier ("initializer_list"), std_node);
18341   tree argvec;
18342   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
18343     {
18344       error ("deducing from brace-enclosed initializer list requires "
18345 	     "#include <initializer_list>");
18346       return error_mark_node;
18347     }
18348   argvec = make_tree_vec (1);
18349   TREE_VEC_ELT (argvec, 0) = arg;
18350   return lookup_template_class (std_init_list, argvec, NULL_TREE,
18351 				NULL_TREE, 0, tf_warning_or_error);
18352 }
18353 
18354 /* Replace auto in TYPE with std::initializer_list<auto>.  */
18355 
18356 static tree
18357 listify_autos (tree type, tree auto_node)
18358 {
18359   tree init_auto = listify (auto_node);
18360   tree argvec = make_tree_vec (1);
18361   TREE_VEC_ELT (argvec, 0) = init_auto;
18362   if (processing_template_decl)
18363     argvec = add_to_template_args (current_template_args (), argvec);
18364   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
18365 }
18366 
18367 /* walk_tree helper for do_auto_deduction.  */
18368 
18369 static tree
18370 contains_auto_r (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
18371 		 void *type)
18372 {
18373   /* Is this a variable with the type we're looking for?  */
18374   if (DECL_P (*tp)
18375       && TREE_TYPE (*tp) == type)
18376     return *tp;
18377   else
18378     return NULL_TREE;
18379 }
18380 
18381 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
18382    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
18383 
18384 tree
18385 do_auto_deduction (tree type, tree init, tree auto_node)
18386 {
18387   tree parms, tparms, targs;
18388   tree args[1];
18389   tree decl;
18390   int val;
18391 
18392   /* The name of the object being declared shall not appear in the
18393      initializer expression.  */
18394   decl = cp_walk_tree_without_duplicates (&init, contains_auto_r, type);
18395   if (decl)
18396     {
18397       error ("variable %q#D with %<auto%> type used in its own "
18398 	     "initializer", decl);
18399       return error_mark_node;
18400     }
18401 
18402   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
18403      with either a new invented type template parameter U or, if the
18404      initializer is a braced-init-list (8.5.4), with
18405      std::initializer_list<U>.  */
18406   if (BRACE_ENCLOSED_INITIALIZER_P (init))
18407     type = listify_autos (type, auto_node);
18408 
18409   parms = build_tree_list (NULL_TREE, type);
18410   args[0] = init;
18411   tparms = make_tree_vec (1);
18412   targs = make_tree_vec (1);
18413   TREE_VEC_ELT (tparms, 0)
18414     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
18415   val = type_unification_real (tparms, targs, parms, args, 1, 0,
18416 			       DEDUCE_CALL, LOOKUP_NORMAL);
18417   if (val > 0)
18418     {
18419       error ("unable to deduce %qT from %qE", type, init);
18420       return error_mark_node;
18421     }
18422 
18423   /* If the list of declarators contains more than one declarator, the type
18424      of each declared variable is determined as described above. If the
18425      type deduced for the template parameter U is not the same in each
18426      deduction, the program is ill-formed.  */
18427   if (TREE_TYPE (auto_node)
18428       && !same_type_p (TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0)))
18429     {
18430       error ("inconsistent deduction for %qT: %qT and then %qT",
18431 	     auto_node, TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0));
18432       return error_mark_node;
18433     }
18434   TREE_TYPE (auto_node) = TREE_VEC_ELT (targs, 0);
18435 
18436   if (processing_template_decl)
18437     targs = add_to_template_args (current_template_args (), targs);
18438   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
18439 }
18440 
18441 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
18442    result.  */
18443 
18444 tree
18445 splice_late_return_type (tree type, tree late_return_type)
18446 {
18447   tree argvec;
18448 
18449   if (late_return_type == NULL_TREE)
18450     return type;
18451   argvec = make_tree_vec (1);
18452   TREE_VEC_ELT (argvec, 0) = late_return_type;
18453   if (processing_template_decl)
18454     argvec = add_to_template_args (current_template_args (), argvec);
18455   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
18456 }
18457 
18458 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
18459 
18460 bool
18461 is_auto (const_tree type)
18462 {
18463   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
18464       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
18465     return true;
18466   else
18467     return false;
18468 }
18469 
18470 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
18471    appear as a type-specifier for the declaration in question, we don't
18472    have to look through the whole type.  */
18473 
18474 tree
18475 type_uses_auto (tree type)
18476 {
18477   enum tree_code code;
18478   if (is_auto (type))
18479     return type;
18480 
18481   code = TREE_CODE (type);
18482 
18483   if (code == POINTER_TYPE || code == REFERENCE_TYPE
18484       || code == OFFSET_TYPE || code == FUNCTION_TYPE
18485       || code == METHOD_TYPE || code == ARRAY_TYPE)
18486     return type_uses_auto (TREE_TYPE (type));
18487 
18488   if (TYPE_PTRMEMFUNC_P (type))
18489     return type_uses_auto (TREE_TYPE (TREE_TYPE
18490 				   (TYPE_PTRMEMFUNC_FN_TYPE (type))));
18491 
18492   return NULL_TREE;
18493 }
18494 
18495 /* For a given template T, return the vector of typedefs referenced
18496    in T for which access check is needed at T instantiation time.
18497    T is either  a FUNCTION_DECL or a RECORD_TYPE.
18498    Those typedefs were added to T by the function
18499    append_type_to_template_for_access_check.  */
18500 
18501 VEC(qualified_typedef_usage_t,gc)*
18502 get_types_needing_access_check (tree t)
18503 {
18504   tree ti;
18505   VEC(qualified_typedef_usage_t,gc) *result = NULL;
18506 
18507   if (!t || t == error_mark_node)
18508     return NULL;
18509 
18510   if (!(ti = get_template_info (t)))
18511     return NULL;
18512 
18513   if (CLASS_TYPE_P (t)
18514       || TREE_CODE (t) == FUNCTION_DECL)
18515     {
18516       if (!TI_TEMPLATE (ti))
18517 	return NULL;
18518 
18519       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
18520     }
18521 
18522   return result;
18523 }
18524 
18525 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
18526    tied to T. That list of typedefs will be access checked at
18527    T instantiation time.
18528    T is either a FUNCTION_DECL or a RECORD_TYPE.
18529    TYPE_DECL is a TYPE_DECL node representing a typedef.
18530    SCOPE is the scope through which TYPE_DECL is accessed.
18531    LOCATION is the location of the usage point of TYPE_DECL.
18532 
18533    This function is a subroutine of
18534    append_type_to_template_for_access_check.  */
18535 
18536 static void
18537 append_type_to_template_for_access_check_1 (tree t,
18538 					    tree type_decl,
18539 					    tree scope,
18540 					    location_t location)
18541 {
18542   qualified_typedef_usage_t typedef_usage;
18543   tree ti;
18544 
18545   if (!t || t == error_mark_node)
18546     return;
18547 
18548   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
18549 	       || CLASS_TYPE_P (t))
18550 	      && type_decl
18551 	      && TREE_CODE (type_decl) == TYPE_DECL
18552 	      && scope);
18553 
18554   if (!(ti = get_template_info (t)))
18555     return;
18556 
18557   gcc_assert (TI_TEMPLATE (ti));
18558 
18559   typedef_usage.typedef_decl = type_decl;
18560   typedef_usage.context = scope;
18561   typedef_usage.locus = location;
18562 
18563   VEC_safe_push (qualified_typedef_usage_t, gc,
18564 		 TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti),
18565 		 &typedef_usage);
18566 }
18567 
18568 /* Append TYPE_DECL to the template TEMPL.
18569    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
18570    At TEMPL instanciation time, TYPE_DECL will be checked to see
18571    if it can be accessed through SCOPE.
18572    LOCATION is the location of the usage point of TYPE_DECL.
18573 
18574    e.g. consider the following code snippet:
18575 
18576      class C
18577      {
18578        typedef int myint;
18579      };
18580 
18581      template<class U> struct S
18582      {
18583        C::myint mi; // <-- usage point of the typedef C::myint
18584      };
18585 
18586      S<char> s;
18587 
18588    At S<char> instantiation time, we need to check the access of C::myint
18589    In other words, we need to check the access of the myint typedef through
18590    the C scope. For that purpose, this function will add the myint typedef
18591    and the scope C through which its being accessed to a list of typedefs
18592    tied to the template S. That list will be walked at template instantiation
18593    time and access check performed on each typedefs it contains.
18594    Note that this particular code snippet should yield an error because
18595    myint is private to C.  */
18596 
18597 void
18598 append_type_to_template_for_access_check (tree templ,
18599                                           tree type_decl,
18600 					  tree scope,
18601 					  location_t location)
18602 {
18603   qualified_typedef_usage_t *iter;
18604   int i;
18605 
18606   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
18607 
18608   /* Make sure we don't append the type to the template twice.  */
18609   for (i = 0;
18610        VEC_iterate (qualified_typedef_usage_t,
18611 		    get_types_needing_access_check (templ),
18612 		    i, iter);
18613        ++i)
18614     if (iter->typedef_decl == type_decl && scope == iter->context)
18615       return;
18616 
18617   append_type_to_template_for_access_check_1 (templ, type_decl,
18618 					      scope, location);
18619 }
18620 
18621 /* Set up the hash tables for template instantiations.  */
18622 
18623 void
18624 init_template_processing (void)
18625 {
18626   decl_specializations = htab_create_ggc (37,
18627 					  hash_specialization,
18628 					  eq_specializations,
18629 					  ggc_free);
18630   type_specializations = htab_create_ggc (37,
18631 					  hash_specialization,
18632 					  eq_specializations,
18633 					  ggc_free);
18634 }
18635 
18636 #include "gt-cp-pt.h"
18637