pt.c revision 107590
1/* Handle parameterized types (templates) for GNU C++.
2   Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
3   2001, 2002  Free Software Foundation, Inc.
4   Written by Ken Raeburn (raeburn@cygnus.com) while at Watchmaker Computing.
5   Rewritten by Jason Merrill (jason@cygnus.com).
6
7This file is part of GNU CC.
8
9GNU CC is free software; you can redistribute it and/or modify
10it under the terms of the GNU General Public License as published by
11the Free Software Foundation; either version 2, or (at your option)
12any later version.
13
14GNU CC is distributed in the hope that it will be useful,
15but WITHOUT ANY WARRANTY; without even the implied warranty of
16MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17GNU General Public License for more details.
18
19You should have received a copy of the GNU General Public License
20along with GNU CC; see the file COPYING.  If not, write to
21the Free Software Foundation, 59 Temple Place - Suite 330,
22Boston, MA 02111-1307, USA.  */
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 "obstack.h"
32#include "tree.h"
33#include "flags.h"
34#include "cp-tree.h"
35#include "tree-inline.h"
36#include "decl.h"
37#include "parse.h"
38#include "lex.h"
39#include "output.h"
40#include "except.h"
41#include "toplev.h"
42#include "rtl.h"
43#include "ggc.h"
44#include "timevar.h"
45
46/* The type of functions taking a tree, and some additional data, and
47   returning an int.  */
48typedef int (*tree_fn_t) PARAMS ((tree, void*));
49
50extern struct obstack permanent_obstack;
51
52/* The PENDING_TEMPLATES is a TREE_LIST of templates whose
53   instantiations have been deferred, either because their definitions
54   were not yet available, or because we were putting off doing the
55   work.  The TREE_PURPOSE of each entry is a SRCLOC indicating where
56   the instantiate request occurred; the TREE_VALUE is a either a DECL
57   (for a function or static data member), or a TYPE (for a class)
58   indicating what we are hoping to instantiate.  */
59static tree pending_templates;
60static tree last_pending_template;
61
62int processing_template_parmlist;
63static int template_header_count;
64
65static tree saved_trees;
66static varray_type inline_parm_levels;
67static size_t inline_parm_levels_used;
68
69static tree current_tinst_level;
70
71/* A map from local variable declarations in the body of the template
72   presently being instantiated to the corresponding instantiated
73   local variables.  */
74static htab_t local_specializations;
75
76#define obstack_chunk_alloc xmalloc
77#define obstack_chunk_free free
78
79#define UNIFY_ALLOW_NONE 0
80#define UNIFY_ALLOW_MORE_CV_QUAL 1
81#define UNIFY_ALLOW_LESS_CV_QUAL 2
82#define UNIFY_ALLOW_DERIVED 4
83#define UNIFY_ALLOW_INTEGER 8
84#define UNIFY_ALLOW_OUTER_LEVEL 16
85#define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
86#define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
87#define UNIFY_ALLOW_MAX_CORRECTION 128
88
89#define GTB_VIA_VIRTUAL 1 /* The base class we are examining is
90			     virtual, or a base class of a virtual
91			     base.  */
92#define GTB_IGNORE_TYPE 2 /* We don't need to try to unify the current
93			     type with the desired type.  */
94
95static int resolve_overloaded_unification PARAMS ((tree, tree, tree, tree,
96						   unification_kind_t, int));
97static int try_one_overload PARAMS ((tree, tree, tree, tree, tree,
98				     unification_kind_t, int));
99static int unify PARAMS ((tree, tree, tree, tree, int));
100static void add_pending_template PARAMS ((tree));
101static void reopen_tinst_level PARAMS ((tree));
102static tree classtype_mangled_name PARAMS ((tree));
103static char *mangle_class_name_for_template PARAMS ((const char *,
104						     tree, tree));
105static tree tsubst_initializer_list PARAMS ((tree, tree));
106static int list_eq PARAMS ((tree, tree));
107static tree get_class_bindings PARAMS ((tree, tree, tree));
108static tree coerce_template_parms PARAMS ((tree, tree, tree,
109					   tsubst_flags_t, int));
110static void tsubst_enum	PARAMS ((tree, tree, tree));
111static tree add_to_template_args PARAMS ((tree, tree));
112static tree add_outermost_template_args PARAMS ((tree, tree));
113static int maybe_adjust_types_for_deduction PARAMS ((unification_kind_t, tree*,
114						     tree*));
115static int  type_unification_real PARAMS ((tree, tree, tree, tree,
116					   int, unification_kind_t, int, int));
117static void note_template_header PARAMS ((int));
118static tree maybe_fold_nontype_arg PARAMS ((tree));
119static tree convert_nontype_argument PARAMS ((tree, tree));
120static tree convert_template_argument PARAMS ((tree, tree, tree,
121					       tsubst_flags_t, int, tree));
122static tree get_bindings_overload PARAMS ((tree, tree, tree));
123static int for_each_template_parm PARAMS ((tree, tree_fn_t, void*));
124static tree build_template_parm_index PARAMS ((int, int, int, tree, tree));
125static int inline_needs_template_parms PARAMS ((tree));
126static void push_inline_template_parms_recursive PARAMS ((tree, int));
127static tree retrieve_specialization PARAMS ((tree, tree));
128static tree retrieve_local_specialization PARAMS ((tree));
129static tree register_specialization PARAMS ((tree, tree, tree));
130static void register_local_specialization PARAMS ((tree, tree));
131static int unregister_specialization PARAMS ((tree, tree));
132static tree reduce_template_parm_level PARAMS ((tree, tree, int));
133static tree build_template_decl PARAMS ((tree, tree));
134static int mark_template_parm PARAMS ((tree, void *));
135static tree tsubst_friend_function PARAMS ((tree, tree));
136static tree tsubst_friend_class PARAMS ((tree, tree));
137static int can_complete_type_without_circularity PARAMS ((tree));
138static tree get_bindings_real PARAMS ((tree, tree, tree, int, int, int));
139static int template_decl_level PARAMS ((tree));
140static tree maybe_get_template_decl_from_type_decl PARAMS ((tree));
141static int check_cv_quals_for_unify PARAMS ((int, tree, tree));
142static tree tsubst_template_arg_vector PARAMS ((tree, tree, tsubst_flags_t));
143static tree tsubst_template_parms PARAMS ((tree, tree, tsubst_flags_t));
144static void regenerate_decl_from_template PARAMS ((tree, tree));
145static tree most_specialized PARAMS ((tree, tree, tree));
146static tree most_specialized_class PARAMS ((tree, tree));
147static int template_class_depth_real PARAMS ((tree, int));
148static tree tsubst_aggr_type PARAMS ((tree, tree, tsubst_flags_t, tree, int));
149static tree tsubst_decl PARAMS ((tree, tree, tree, tsubst_flags_t));
150static tree tsubst_arg_types PARAMS ((tree, tree, tsubst_flags_t, tree));
151static tree tsubst_function_type PARAMS ((tree, tree, tsubst_flags_t, tree));
152static void check_specialization_scope PARAMS ((void));
153static tree process_partial_specialization PARAMS ((tree));
154static void set_current_access_from_decl PARAMS ((tree));
155static void check_default_tmpl_args PARAMS ((tree, tree, int, int));
156static tree tsubst_call_declarator_parms PARAMS ((tree, tree,
157						  tsubst_flags_t, tree));
158static tree get_template_base_recursive PARAMS ((tree, tree,
159						 tree, tree, tree, int));
160static tree get_template_base PARAMS ((tree, tree, tree, tree));
161static int verify_class_unification PARAMS ((tree, tree, tree));
162static tree try_class_unification PARAMS ((tree, tree, tree, tree));
163static int coerce_template_template_parms PARAMS ((tree, tree, tsubst_flags_t,
164						   tree, tree));
165static tree determine_specialization PARAMS ((tree, tree, tree *, int));
166static int template_args_equal PARAMS ((tree, tree));
167static void tsubst_default_arguments PARAMS ((tree));
168static tree for_each_template_parm_r PARAMS ((tree *, int *, void *));
169static tree copy_default_args_to_explicit_spec_1 PARAMS ((tree, tree));
170static void copy_default_args_to_explicit_spec PARAMS ((tree));
171static int invalid_nontype_parm_type_p PARAMS ((tree, tsubst_flags_t));
172
173/* Called once to initialize pt.c.  */
174
175void
176init_pt ()
177{
178  ggc_add_tree_root (&pending_templates, 1);
179  ggc_add_tree_root (&saved_trees, 1);
180  ggc_add_tree_root (&current_tinst_level, 1);
181}
182
183/* Do any processing required when DECL (a member template declaration
184   using TEMPLATE_PARAMETERS as its innermost parameter list) is
185   finished.  Returns the TEMPLATE_DECL corresponding to DECL, unless
186   it is a specialization, in which case the DECL itself is returned.  */
187
188tree
189finish_member_template_decl (decl)
190  tree decl;
191{
192  if (decl == NULL_TREE || decl == void_type_node)
193    return NULL_TREE;
194  else if (decl == error_mark_node)
195    /* By returning NULL_TREE, the parser will just ignore this
196       declaration.  We have already issued the error.  */
197    return NULL_TREE;
198  else if (TREE_CODE (decl) == TREE_LIST)
199    {
200      /* Assume that the class is the only declspec.  */
201      decl = TREE_VALUE (decl);
202      if (IS_AGGR_TYPE (decl) && CLASSTYPE_TEMPLATE_INFO (decl)
203	  && ! CLASSTYPE_TEMPLATE_SPECIALIZATION (decl))
204	{
205	  tree tmpl = CLASSTYPE_TI_TEMPLATE (decl);
206	  check_member_template (tmpl);
207	  return tmpl;
208	}
209      return NULL_TREE;
210    }
211  else if (TREE_CODE (decl) == FIELD_DECL)
212    error ("data member `%D' cannot be a member template", decl);
213  else if (DECL_TEMPLATE_INFO (decl))
214    {
215      if (!DECL_TEMPLATE_SPECIALIZATION (decl))
216	{
217	  check_member_template (DECL_TI_TEMPLATE (decl));
218	  return DECL_TI_TEMPLATE (decl);
219	}
220      else
221	return decl;
222    }
223  else
224    error ("invalid member template declaration `%D'", decl);
225
226  return error_mark_node;
227}
228
229/* Returns the template nesting level of the indicated class TYPE.
230
231   For example, in:
232     template <class T>
233     struct A
234     {
235       template <class U>
236       struct B {};
237     };
238
239   A<T>::B<U> has depth two, while A<T> has depth one.
240   Both A<T>::B<int> and A<int>::B<U> have depth one, if
241   COUNT_SPECIALIZATIONS is 0 or if they are instantiations, not
242   specializations.
243
244   This function is guaranteed to return 0 if passed NULL_TREE so
245   that, for example, `template_class_depth (current_class_type)' is
246   always safe.  */
247
248static int
249template_class_depth_real (type, count_specializations)
250     tree type;
251     int count_specializations;
252{
253  int depth;
254
255  for (depth = 0;
256       type && TREE_CODE (type) != NAMESPACE_DECL;
257       type = (TREE_CODE (type) == FUNCTION_DECL)
258	 ? CP_DECL_CONTEXT (type) : TYPE_CONTEXT (type))
259    {
260      if (TREE_CODE (type) != FUNCTION_DECL)
261	{
262	  if (CLASSTYPE_TEMPLATE_INFO (type)
263	      && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (type))
264	      && ((count_specializations
265		   && CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
266		  || uses_template_parms (CLASSTYPE_TI_ARGS (type))))
267	    ++depth;
268	}
269      else
270	{
271	  if (DECL_TEMPLATE_INFO (type)
272	      && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (type))
273	      && ((count_specializations
274		   && DECL_TEMPLATE_SPECIALIZATION (type))
275		  || uses_template_parms (DECL_TI_ARGS (type))))
276	    ++depth;
277	}
278    }
279
280  return depth;
281}
282
283/* Returns the template nesting level of the indicated class TYPE.
284   Like template_class_depth_real, but instantiations do not count in
285   the depth.  */
286
287int
288template_class_depth (type)
289     tree type;
290{
291  return template_class_depth_real (type, /*count_specializations=*/0);
292}
293
294/* Returns 1 if processing DECL as part of do_pending_inlines
295   needs us to push template parms.  */
296
297static int
298inline_needs_template_parms (decl)
299     tree decl;
300{
301  if (! DECL_TEMPLATE_INFO (decl))
302    return 0;
303
304  return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
305	  > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
306}
307
308/* Subroutine of maybe_begin_member_template_processing.
309   Push the template parms in PARMS, starting from LEVELS steps into the
310   chain, and ending at the beginning, since template parms are listed
311   innermost first.  */
312
313static void
314push_inline_template_parms_recursive (parmlist, levels)
315     tree parmlist;
316     int levels;
317{
318  tree parms = TREE_VALUE (parmlist);
319  int i;
320
321  if (levels > 1)
322    push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
323
324  ++processing_template_decl;
325  current_template_parms
326    = tree_cons (size_int (processing_template_decl),
327		 parms, current_template_parms);
328  TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
329
330  pushlevel (0);
331  for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
332    {
333      tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
334      my_friendly_assert (DECL_P (parm), 0);
335
336      switch (TREE_CODE (parm))
337	{
338	case TYPE_DECL:
339	case TEMPLATE_DECL:
340	  pushdecl (parm);
341	  break;
342
343	case PARM_DECL:
344	  {
345	    /* Make a CONST_DECL as is done in process_template_parm.
346	       It is ugly that we recreate this here; the original
347	       version built in process_template_parm is no longer
348	       available.  */
349	    tree decl = build_decl (CONST_DECL, DECL_NAME (parm),
350				    TREE_TYPE (parm));
351	    DECL_ARTIFICIAL (decl) = 1;
352	    DECL_INITIAL (decl) = DECL_INITIAL (parm);
353	    SET_DECL_TEMPLATE_PARM_P (decl);
354	    pushdecl (decl);
355	  }
356	  break;
357
358	default:
359	  abort ();
360	}
361    }
362}
363
364/* Restore the template parameter context for a member template or
365   a friend template defined in a class definition.  */
366
367void
368maybe_begin_member_template_processing (decl)
369     tree decl;
370{
371  tree parms;
372  int levels = 0;
373
374  if (inline_needs_template_parms (decl))
375    {
376      parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
377      levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
378
379      if (DECL_TEMPLATE_SPECIALIZATION (decl))
380	{
381	  --levels;
382	  parms = TREE_CHAIN (parms);
383	}
384
385      push_inline_template_parms_recursive (parms, levels);
386    }
387
388  /* Remember how many levels of template parameters we pushed so that
389     we can pop them later.  */
390  if (!inline_parm_levels)
391    VARRAY_INT_INIT (inline_parm_levels, 4, "inline_parm_levels");
392  if (inline_parm_levels_used == inline_parm_levels->num_elements)
393    VARRAY_GROW (inline_parm_levels, 2 * inline_parm_levels_used);
394  VARRAY_INT (inline_parm_levels, inline_parm_levels_used) = levels;
395  ++inline_parm_levels_used;
396}
397
398/* Undo the effects of begin_member_template_processing. */
399
400void
401maybe_end_member_template_processing ()
402{
403  int i;
404
405  if (!inline_parm_levels_used)
406    return;
407
408  --inline_parm_levels_used;
409  for (i = 0;
410       i < VARRAY_INT (inline_parm_levels, inline_parm_levels_used);
411       ++i)
412    {
413      --processing_template_decl;
414      current_template_parms = TREE_CHAIN (current_template_parms);
415      poplevel (0, 0, 0);
416    }
417}
418
419/* Returns non-zero iff T is a member template function.  We must be
420   careful as in
421
422     template <class T> class C { void f(); }
423
424   Here, f is a template function, and a member, but not a member
425   template.  This function does not concern itself with the origin of
426   T, only its present state.  So if we have
427
428     template <class T> class C { template <class U> void f(U); }
429
430   then neither C<int>::f<char> nor C<T>::f<double> is considered
431   to be a member template.  But, `template <class U> void
432   C<int>::f(U)' is considered a member template.  */
433
434int
435is_member_template (t)
436     tree t;
437{
438  if (!DECL_FUNCTION_TEMPLATE_P (t))
439    /* Anything that isn't a function or a template function is
440       certainly not a member template.  */
441    return 0;
442
443  /* A local class can't have member templates.  */
444  if (decl_function_context (t))
445    return 0;
446
447  return (DECL_FUNCTION_MEMBER_P (DECL_TEMPLATE_RESULT (t))
448	  /* If there are more levels of template parameters than
449	     there are template classes surrounding the declaration,
450	     then we have a member template.  */
451	  && (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (t)) >
452	      template_class_depth (DECL_CONTEXT (t))));
453}
454
455#if 0 /* UNUSED */
456/* Returns non-zero iff T is a member template class.  See
457   is_member_template for a description of what precisely constitutes
458   a member template.  */
459
460int
461is_member_template_class (t)
462     tree t;
463{
464  if (!DECL_CLASS_TEMPLATE_P (t))
465    /* Anything that isn't a class template, is certainly not a member
466       template.  */
467    return 0;
468
469  if (!DECL_CLASS_SCOPE_P (t))
470    /* Anything whose context isn't a class type is surely not a
471       member template.  */
472    return 0;
473
474  /* If there are more levels of template parameters than there are
475     template classes surrounding the declaration, then we have a
476     member template.  */
477  return  (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (t)) >
478	   template_class_depth (DECL_CONTEXT (t)));
479}
480#endif
481
482/* Return a new template argument vector which contains all of ARGS,
483   but has as its innermost set of arguments the EXTRA_ARGS.  */
484
485static tree
486add_to_template_args (args, extra_args)
487     tree args;
488     tree extra_args;
489{
490  tree new_args;
491  int extra_depth;
492  int i;
493  int j;
494
495  extra_depth = TMPL_ARGS_DEPTH (extra_args);
496  new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
497
498  for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
499    SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
500
501  for (j = 1; j <= extra_depth; ++j, ++i)
502    SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
503
504  return new_args;
505}
506
507/* Like add_to_template_args, but only the outermost ARGS are added to
508   the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
509   (EXTRA_ARGS) levels are added.  This function is used to combine
510   the template arguments from a partial instantiation with the
511   template arguments used to attain the full instantiation from the
512   partial instantiation.  */
513
514static tree
515add_outermost_template_args (args, extra_args)
516     tree args;
517     tree extra_args;
518{
519  tree new_args;
520
521  /* If there are more levels of EXTRA_ARGS than there are ARGS,
522     something very fishy is going on.  */
523  my_friendly_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args),
524		      0);
525
526  /* If *all* the new arguments will be the EXTRA_ARGS, just return
527     them.  */
528  if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
529    return extra_args;
530
531  /* For the moment, we make ARGS look like it contains fewer levels.  */
532  TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
533
534  new_args = add_to_template_args (args, extra_args);
535
536  /* Now, we restore ARGS to its full dimensions.  */
537  TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
538
539  return new_args;
540}
541
542/* Return the N levels of innermost template arguments from the ARGS.  */
543
544tree
545get_innermost_template_args (args, n)
546     tree args;
547     int n;
548{
549  tree new_args;
550  int extra_levels;
551  int i;
552
553  my_friendly_assert (n >= 0, 20000603);
554
555  /* If N is 1, just return the innermost set of template arguments.  */
556  if (n == 1)
557    return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
558
559  /* If we're not removing anything, just return the arguments we were
560     given.  */
561  extra_levels = TMPL_ARGS_DEPTH (args) - n;
562  my_friendly_assert (extra_levels >= 0, 20000603);
563  if (extra_levels == 0)
564    return args;
565
566  /* Make a new set of arguments, not containing the outer arguments.  */
567  new_args = make_tree_vec (n);
568  for (i = 1; i <= n; ++i)
569    SET_TMPL_ARGS_LEVEL (new_args, i,
570			 TMPL_ARGS_LEVEL (args, i + extra_levels));
571
572  return new_args;
573}
574
575/* We've got a template header coming up; push to a new level for storing
576   the parms.  */
577
578void
579begin_template_parm_list ()
580{
581  /* We use a non-tag-transparent scope here, which causes pushtag to
582     put tags in this scope, rather than in the enclosing class or
583     namespace scope.  This is the right thing, since we want
584     TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
585     global template class, push_template_decl handles putting the
586     TEMPLATE_DECL into top-level scope.  For a nested template class,
587     e.g.:
588
589       template <class T> struct S1 {
590         template <class T> struct S2 {};
591       };
592
593     pushtag contains special code to call pushdecl_with_scope on the
594     TEMPLATE_DECL for S2.  */
595  begin_scope (sk_template_parms);
596  ++processing_template_decl;
597  ++processing_template_parmlist;
598  note_template_header (0);
599}
600
601/* This routine is called when a specialization is declared.  If it is
602   illegal to declare a specialization here, an error is reported.  */
603
604static void
605check_specialization_scope ()
606{
607  tree scope = current_scope ();
608
609  /* [temp.expl.spec]
610
611     An explicit specialization shall be declared in the namespace of
612     which the template is a member, or, for member templates, in the
613     namespace of which the enclosing class or enclosing class
614     template is a member.  An explicit specialization of a member
615     function, member class or static data member of a class template
616     shall be declared in the namespace of which the class template
617     is a member.  */
618  if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
619    error ("explicit specialization in non-namespace scope `%D'",
620	      scope);
621
622  /* [temp.expl.spec]
623
624     In an explicit specialization declaration for a member of a class
625     template or a member template that appears in namespace scope,
626     the member template and some of its enclosing class templates may
627     remain unspecialized, except that the declaration shall not
628     explicitly specialize a class member template if its enclosing
629     class templates are not explicitly specialized as well.  */
630  if (current_template_parms)
631    error ("enclosing class templates are not explicitly specialized");
632}
633
634/* We've just seen template <>. */
635
636void
637begin_specialization ()
638{
639  begin_scope (sk_template_spec);
640  note_template_header (1);
641  check_specialization_scope ();
642}
643
644/* Called at then end of processing a declaration preceded by
645   template<>.  */
646
647void
648end_specialization ()
649{
650  finish_scope ();
651  reset_specialization ();
652}
653
654/* Any template <>'s that we have seen thus far are not referring to a
655   function specialization. */
656
657void
658reset_specialization ()
659{
660  processing_specialization = 0;
661  template_header_count = 0;
662}
663
664/* We've just seen a template header.  If SPECIALIZATION is non-zero,
665   it was of the form template <>.  */
666
667static void
668note_template_header (specialization)
669     int specialization;
670{
671  processing_specialization = specialization;
672  template_header_count++;
673}
674
675/* We're beginning an explicit instantiation.  */
676
677void
678begin_explicit_instantiation ()
679{
680  ++processing_explicit_instantiation;
681}
682
683
684void
685end_explicit_instantiation ()
686{
687  my_friendly_assert(processing_explicit_instantiation > 0, 0);
688  --processing_explicit_instantiation;
689}
690
691/* The TYPE is being declared.  If it is a template type, that means it
692   is a partial specialization.  Do appropriate error-checking.  */
693
694void
695maybe_process_partial_specialization (type)
696     tree type;
697{
698  if (IS_AGGR_TYPE (type) && CLASSTYPE_USE_TEMPLATE (type))
699    {
700      if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
701	  && !COMPLETE_TYPE_P (type))
702	{
703	  if (current_namespace
704	      != decl_namespace_context (CLASSTYPE_TI_TEMPLATE (type)))
705	    {
706	      pedwarn ("specializing `%#T' in different namespace", type);
707	      cp_pedwarn_at ("  from definition of `%#D'",
708			     CLASSTYPE_TI_TEMPLATE (type));
709	    }
710	  SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
711	  if (processing_template_decl)
712	    push_template_decl (TYPE_MAIN_DECL (type));
713	}
714      else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
715	error ("specialization of `%T' after instantiation", type);
716    }
717  else if (processing_specialization)
718    error ("explicit specialization of non-template `%T'", type);
719}
720
721/* Retrieve the specialization (in the sense of [temp.spec] - a
722   specialization is either an instantiation or an explicit
723   specialization) of TMPL for the given template ARGS.  If there is
724   no such specialization, return NULL_TREE.  The ARGS are a vector of
725   arguments, or a vector of vectors of arguments, in the case of
726   templates with more than one level of parameters.  */
727
728static tree
729retrieve_specialization (tmpl, args)
730     tree tmpl;
731     tree args;
732{
733  tree s;
734
735  my_friendly_assert (TREE_CODE (tmpl) == TEMPLATE_DECL, 0);
736
737  /* There should be as many levels of arguments as there are
738     levels of parameters.  */
739  my_friendly_assert (TMPL_ARGS_DEPTH (args)
740		      == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)),
741		      0);
742
743  for (s = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
744       s != NULL_TREE;
745       s = TREE_CHAIN (s))
746    if (comp_template_args (TREE_PURPOSE (s), args))
747      return TREE_VALUE (s);
748
749  return NULL_TREE;
750}
751
752/* Like retrieve_specialization, but for local declarations.  */
753
754static tree
755retrieve_local_specialization (tmpl)
756     tree tmpl;
757{
758  return (tree) htab_find (local_specializations, tmpl);
759}
760
761/* Returns non-zero iff DECL is a specialization of TMPL.  */
762
763int
764is_specialization_of (decl, tmpl)
765     tree decl;
766     tree tmpl;
767{
768  tree t;
769
770  if (TREE_CODE (decl) == FUNCTION_DECL)
771    {
772      for (t = decl;
773	   t != NULL_TREE;
774	   t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
775	if (t == tmpl)
776	  return 1;
777    }
778  else
779    {
780      my_friendly_assert (TREE_CODE (decl) == TYPE_DECL, 0);
781
782      for (t = TREE_TYPE (decl);
783	   t != NULL_TREE;
784	   t = CLASSTYPE_USE_TEMPLATE (t)
785	     ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
786	if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
787	  return 1;
788    }
789
790  return 0;
791}
792
793/* Register the specialization SPEC as a specialization of TMPL with
794   the indicated ARGS.  Returns SPEC, or an equivalent prior
795   declaration, if available.  */
796
797static tree
798register_specialization (spec, tmpl, args)
799     tree spec;
800     tree tmpl;
801     tree args;
802{
803  tree s;
804
805  my_friendly_assert (TREE_CODE (tmpl) == TEMPLATE_DECL, 0);
806
807  if (TREE_CODE (spec) == FUNCTION_DECL
808      && uses_template_parms (DECL_TI_ARGS (spec)))
809    /* This is the FUNCTION_DECL for a partial instantiation.  Don't
810       register it; we want the corresponding TEMPLATE_DECL instead.
811       We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
812       the more obvious `uses_template_parms (spec)' to avoid problems
813       with default function arguments.  In particular, given
814       something like this:
815
816          template <class T> void f(T t1, T t = T())
817
818       the default argument expression is not substituted for in an
819       instantiation unless and until it is actually needed.  */
820    return spec;
821
822  /* There should be as many levels of arguments as there are
823     levels of parameters.  */
824  my_friendly_assert (TMPL_ARGS_DEPTH (args)
825		      == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)),
826		      0);
827
828  for (s = DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
829       s != NULL_TREE;
830       s = TREE_CHAIN (s))
831    {
832      tree fn = TREE_VALUE (s);
833
834      /* We can sometimes try to re-register a specialization that we've
835	 already got.  In particular, regenerate_decl_from_template
836	 calls duplicate_decls which will update the specialization
837	 list.  But, we'll still get called again here anyhow.  It's
838	 more convenient to simply allow this than to try to prevent it.  */
839      if (fn == spec)
840	return spec;
841      else if (comp_template_args (TREE_PURPOSE (s), args))
842	{
843	  if (DECL_TEMPLATE_SPECIALIZATION (spec))
844	    {
845	      if (DECL_TEMPLATE_INSTANTIATION (fn))
846		{
847		  if (TREE_USED (fn)
848		      || DECL_EXPLICIT_INSTANTIATION (fn))
849		    {
850		      error ("specialization of %D after instantiation",
851				fn);
852		      return spec;
853		    }
854		  else
855		    {
856		      /* This situation should occur only if the first
857			 specialization is an implicit instantiation,
858			 the second is an explicit specialization, and
859			 the implicit instantiation has not yet been
860			 used.  That situation can occur if we have
861			 implicitly instantiated a member function and
862			 then specialized it later.
863
864			 We can also wind up here if a friend
865			 declaration that looked like an instantiation
866			 turns out to be a specialization:
867
868			   template <class T> void foo(T);
869			   class S { friend void foo<>(int) };
870			   template <> void foo(int);
871
872			 We transform the existing DECL in place so that
873			 any pointers to it become pointers to the
874			 updated declaration.
875
876			 If there was a definition for the template, but
877			 not for the specialization, we want this to
878			 look as if there is no definition, and vice
879			 versa.  */
880		      DECL_INITIAL (fn) = NULL_TREE;
881		      duplicate_decls (spec, fn);
882
883		      return fn;
884		    }
885		}
886	      else if (DECL_TEMPLATE_SPECIALIZATION (fn))
887		{
888		  duplicate_decls (spec, fn);
889		  return fn;
890		}
891	    }
892	}
893      }
894
895  DECL_TEMPLATE_SPECIALIZATIONS (tmpl)
896     = tree_cons (args, spec, DECL_TEMPLATE_SPECIALIZATIONS (tmpl));
897
898  return spec;
899}
900
901/* Unregister the specialization SPEC as a specialization of TMPL.
902   Returns nonzero if the SPEC was listed as a specialization of
903   TMPL.  */
904
905static int
906unregister_specialization (spec, tmpl)
907     tree spec;
908     tree tmpl;
909{
910  tree* s;
911
912  for (s = &DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
913       *s != NULL_TREE;
914       s = &TREE_CHAIN (*s))
915    if (TREE_VALUE (*s) == spec)
916      {
917	*s = TREE_CHAIN (*s);
918	return 1;
919      }
920
921  return 0;
922}
923
924/* Like register_specialization, but for local declarations.  We are
925   registering SPEC, an instantiation of TMPL.  */
926
927static void
928register_local_specialization (spec, tmpl)
929     tree spec;
930     tree tmpl;
931{
932  void **slot;
933
934  slot = htab_find_slot (local_specializations, tmpl, INSERT);
935  *slot = spec;
936}
937
938/* Print the list of candidate FNS in an error message.  */
939
940void
941print_candidates (fns)
942     tree fns;
943{
944  tree fn;
945
946  const char *str = "candidates are:";
947
948  for (fn = fns; fn != NULL_TREE; fn = TREE_CHAIN (fn))
949    {
950      tree f;
951
952      for (f = TREE_VALUE (fn); f; f = OVL_NEXT (f))
953	cp_error_at ("%s %+#D", str, OVL_CURRENT (f));
954      str = "               ";
955    }
956}
957
958/* Returns the template (one of the functions given by TEMPLATE_ID)
959   which can be specialized to match the indicated DECL with the
960   explicit template args given in TEMPLATE_ID.  The DECL may be
961   NULL_TREE if none is available.  In that case, the functions in
962   TEMPLATE_ID are non-members.
963
964   If NEED_MEMBER_TEMPLATE is non-zero the function is known to be a
965   specialization of a member template.
966
967   The template args (those explicitly specified and those deduced)
968   are output in a newly created vector *TARGS_OUT.
969
970   If it is impossible to determine the result, an error message is
971   issued.  The error_mark_node is returned to indicate failure.  */
972
973static tree
974determine_specialization (template_id, decl, targs_out,
975			  need_member_template)
976     tree template_id;
977     tree decl;
978     tree* targs_out;
979     int need_member_template;
980{
981  tree fns;
982  tree targs;
983  tree explicit_targs;
984  tree candidates = NULL_TREE;
985  tree templates = NULL_TREE;
986
987  *targs_out = NULL_TREE;
988
989  if (template_id == error_mark_node)
990    return error_mark_node;
991
992  fns = TREE_OPERAND (template_id, 0);
993  explicit_targs = TREE_OPERAND (template_id, 1);
994
995  if (fns == error_mark_node)
996    return error_mark_node;
997
998  /* Check for baselinks. */
999  if (BASELINK_P (fns))
1000    fns = TREE_VALUE (fns);
1001
1002  if (!is_overloaded_fn (fns))
1003    {
1004      error ("`%D' is not a function template", fns);
1005      return error_mark_node;
1006    }
1007
1008  for (; fns; fns = OVL_NEXT (fns))
1009    {
1010      tree tmpl;
1011
1012      tree fn = OVL_CURRENT (fns);
1013
1014      if (TREE_CODE (fn) == TEMPLATE_DECL)
1015	/* DECL might be a specialization of FN.  */
1016	tmpl = fn;
1017      else if (need_member_template)
1018	/* FN is an ordinary member function, and we need a
1019	   specialization of a member template.  */
1020	continue;
1021      else if (TREE_CODE (fn) != FUNCTION_DECL)
1022	/* We can get IDENTIFIER_NODEs here in certain erroneous
1023	   cases.  */
1024	continue;
1025      else if (!DECL_FUNCTION_MEMBER_P (fn))
1026	/* This is just an ordinary non-member function.  Nothing can
1027	   be a specialization of that.  */
1028	continue;
1029      else if (DECL_ARTIFICIAL (fn))
1030	/* Cannot specialize functions that are created implicitly.  */
1031	continue;
1032      else
1033	{
1034	  tree decl_arg_types;
1035
1036	  /* This is an ordinary member function.  However, since
1037	     we're here, we can assume it's enclosing class is a
1038	     template class.  For example,
1039
1040	       template <typename T> struct S { void f(); };
1041	       template <> void S<int>::f() {}
1042
1043	     Here, S<int>::f is a non-template, but S<int> is a
1044	     template class.  If FN has the same type as DECL, we
1045	     might be in business.  */
1046
1047	  if (!DECL_TEMPLATE_INFO (fn))
1048	    /* Its enclosing class is an explicit specialization
1049	       of a template class.  This is not a candidate.  */
1050	    continue;
1051
1052	  if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1053			    TREE_TYPE (TREE_TYPE (fn))))
1054	    /* The return types differ.  */
1055	    continue;
1056
1057	  /* Adjust the type of DECL in case FN is a static member.  */
1058	  decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1059	  if (DECL_STATIC_FUNCTION_P (fn)
1060	      && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1061	    decl_arg_types = TREE_CHAIN (decl_arg_types);
1062
1063	  if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1064			 decl_arg_types))
1065	    /* They match!  */
1066	    candidates = tree_cons (NULL_TREE, fn, candidates);
1067
1068	  continue;
1069	}
1070
1071      /* See whether this function might be a specialization of this
1072	 template.  */
1073      targs = get_bindings (tmpl, decl, explicit_targs);
1074
1075      if (!targs)
1076	/* We cannot deduce template arguments that when used to
1077	   specialize TMPL will produce DECL.  */
1078	continue;
1079
1080      /* Save this template, and the arguments deduced.  */
1081      templates = tree_cons (targs, tmpl, templates);
1082    }
1083
1084  if (templates && TREE_CHAIN (templates))
1085    {
1086      /* We have:
1087
1088	   [temp.expl.spec]
1089
1090	   It is possible for a specialization with a given function
1091	   signature to be instantiated from more than one function
1092	   template.  In such cases, explicit specification of the
1093	   template arguments must be used to uniquely identify the
1094	   function template specialization being specialized.
1095
1096	 Note that here, there's no suggestion that we're supposed to
1097	 determine which of the candidate templates is most
1098	 specialized.  However, we, also have:
1099
1100	   [temp.func.order]
1101
1102	   Partial ordering of overloaded function template
1103	   declarations is used in the following contexts to select
1104	   the function template to which a function template
1105	   specialization refers:
1106
1107           -- when an explicit specialization refers to a function
1108	      template.
1109
1110	 So, we do use the partial ordering rules, at least for now.
1111	 This extension can only serve to make illegal programs legal,
1112	 so it's safe.  And, there is strong anecdotal evidence that
1113	 the committee intended the partial ordering rules to apply;
1114	 the EDG front-end has that behavior, and John Spicer claims
1115	 that the committee simply forgot to delete the wording in
1116	 [temp.expl.spec].  */
1117     tree tmpl = most_specialized (templates, decl, explicit_targs);
1118     if (tmpl && tmpl != error_mark_node)
1119       {
1120	 targs = get_bindings (tmpl, decl, explicit_targs);
1121	 templates = tree_cons (targs, tmpl, NULL_TREE);
1122       }
1123    }
1124
1125  if (templates == NULL_TREE && candidates == NULL_TREE)
1126    {
1127      cp_error_at ("template-id `%D' for `%+D' does not match any template declaration",
1128		   template_id, decl);
1129      return error_mark_node;
1130    }
1131  else if ((templates && TREE_CHAIN (templates))
1132	   || (candidates && TREE_CHAIN (candidates))
1133	   || (templates && candidates))
1134    {
1135      cp_error_at ("ambiguous template specialization `%D' for `%+D'",
1136		   template_id, decl);
1137      chainon (candidates, templates);
1138      print_candidates (candidates);
1139      return error_mark_node;
1140    }
1141
1142  /* We have one, and exactly one, match. */
1143  if (candidates)
1144    {
1145      /* It was a specialization of an ordinary member function in a
1146	 template class.  */
1147      *targs_out = copy_node (DECL_TI_ARGS (TREE_VALUE (candidates)));
1148      return DECL_TI_TEMPLATE (TREE_VALUE (candidates));
1149    }
1150
1151  /* It was a specialization of a template.  */
1152  targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
1153  if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
1154    {
1155      *targs_out = copy_node (targs);
1156      SET_TMPL_ARGS_LEVEL (*targs_out,
1157			   TMPL_ARGS_DEPTH (*targs_out),
1158			   TREE_PURPOSE (templates));
1159    }
1160  else
1161    *targs_out = TREE_PURPOSE (templates);
1162  return TREE_VALUE (templates);
1163}
1164
1165/* Returns a chain of parameter types, exactly like the SPEC_TYPES,
1166   but with the default argument values filled in from those in the
1167   TMPL_TYPES.  */
1168
1169static tree
1170copy_default_args_to_explicit_spec_1 (spec_types,
1171				      tmpl_types)
1172     tree spec_types;
1173     tree tmpl_types;
1174{
1175  tree new_spec_types;
1176
1177  if (!spec_types)
1178    return NULL_TREE;
1179
1180  if (spec_types == void_list_node)
1181    return void_list_node;
1182
1183  /* Substitute into the rest of the list.  */
1184  new_spec_types =
1185    copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
1186					  TREE_CHAIN (tmpl_types));
1187
1188  /* Add the default argument for this parameter.  */
1189  return hash_tree_cons (TREE_PURPOSE (tmpl_types),
1190			 TREE_VALUE (spec_types),
1191			 new_spec_types);
1192}
1193
1194/* DECL is an explicit specialization.  Replicate default arguments
1195   from the template it specializes.  (That way, code like:
1196
1197     template <class T> void f(T = 3);
1198     template <> void f(double);
1199     void g () { f (); }
1200
1201   works, as required.)  An alternative approach would be to look up
1202   the correct default arguments at the call-site, but this approach
1203   is consistent with how implicit instantiations are handled.  */
1204
1205static void
1206copy_default_args_to_explicit_spec (decl)
1207     tree decl;
1208{
1209  tree tmpl;
1210  tree spec_types;
1211  tree tmpl_types;
1212  tree new_spec_types;
1213  tree old_type;
1214  tree new_type;
1215  tree t;
1216  tree object_type = NULL_TREE;
1217  tree in_charge = NULL_TREE;
1218  tree vtt = NULL_TREE;
1219
1220  /* See if there's anything we need to do.  */
1221  tmpl = DECL_TI_TEMPLATE (decl);
1222  tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
1223  for (t = tmpl_types; t; t = TREE_CHAIN (t))
1224    if (TREE_PURPOSE (t))
1225      break;
1226  if (!t)
1227    return;
1228
1229  old_type = TREE_TYPE (decl);
1230  spec_types = TYPE_ARG_TYPES (old_type);
1231
1232  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1233    {
1234      /* Remove the this pointer, but remember the object's type for
1235         CV quals.  */
1236      object_type = TREE_TYPE (TREE_VALUE (spec_types));
1237      spec_types = TREE_CHAIN (spec_types);
1238      tmpl_types = TREE_CHAIN (tmpl_types);
1239
1240      if (DECL_HAS_IN_CHARGE_PARM_P (decl))
1241        {
1242          /* DECL may contain more parameters than TMPL due to the extra
1243             in-charge parameter in constructors and destructors.  */
1244          in_charge = spec_types;
1245	  spec_types = TREE_CHAIN (spec_types);
1246	}
1247      if (DECL_HAS_VTT_PARM_P (decl))
1248	{
1249	  vtt = spec_types;
1250	  spec_types = TREE_CHAIN (spec_types);
1251	}
1252    }
1253
1254  /* Compute the merged default arguments.  */
1255  new_spec_types =
1256    copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
1257
1258  /* Compute the new FUNCTION_TYPE.  */
1259  if (object_type)
1260    {
1261      if (vtt)
1262        new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
1263			  	         TREE_VALUE (vtt),
1264				         new_spec_types);
1265
1266      if (in_charge)
1267        /* Put the in-charge parameter back.  */
1268        new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
1269			  	         TREE_VALUE (in_charge),
1270				         new_spec_types);
1271
1272      new_type = build_cplus_method_type (object_type,
1273					  TREE_TYPE (old_type),
1274					  new_spec_types);
1275    }
1276  else
1277    new_type = build_function_type (TREE_TYPE (old_type),
1278				    new_spec_types);
1279  new_type = build_type_attribute_variant (new_type,
1280					   TYPE_ATTRIBUTES (old_type));
1281  new_type = build_exception_variant (new_type,
1282				      TYPE_RAISES_EXCEPTIONS (old_type));
1283  TREE_TYPE (decl) = new_type;
1284}
1285
1286/* Check to see if the function just declared, as indicated in
1287   DECLARATOR, and in DECL, is a specialization of a function
1288   template.  We may also discover that the declaration is an explicit
1289   instantiation at this point.
1290
1291   Returns DECL, or an equivalent declaration that should be used
1292   instead if all goes well.  Issues an error message if something is
1293   amiss.  Returns error_mark_node if the error is not easily
1294   recoverable.
1295
1296   FLAGS is a bitmask consisting of the following flags:
1297
1298   2: The function has a definition.
1299   4: The function is a friend.
1300
1301   The TEMPLATE_COUNT is the number of references to qualifying
1302   template classes that appeared in the name of the function.  For
1303   example, in
1304
1305     template <class T> struct S { void f(); };
1306     void S<int>::f();
1307
1308   the TEMPLATE_COUNT would be 1.  However, explicitly specialized
1309   classes are not counted in the TEMPLATE_COUNT, so that in
1310
1311     template <class T> struct S {};
1312     template <> struct S<int> { void f(); }
1313     template <> void S<int>::f();
1314
1315   the TEMPLATE_COUNT would be 0.  (Note that this declaration is
1316   illegal; there should be no template <>.)
1317
1318   If the function is a specialization, it is marked as such via
1319   DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
1320   is set up correctly, and it is added to the list of specializations
1321   for that template.  */
1322
1323tree
1324check_explicit_specialization (declarator, decl, template_count, flags)
1325     tree declarator;
1326     tree decl;
1327     int template_count;
1328     int flags;
1329{
1330  int have_def = flags & 2;
1331  int is_friend = flags & 4;
1332  int specialization = 0;
1333  int explicit_instantiation = 0;
1334  int member_specialization = 0;
1335  tree ctype = DECL_CLASS_CONTEXT (decl);
1336  tree dname = DECL_NAME (decl);
1337  tmpl_spec_kind tsk;
1338
1339  tsk = current_tmpl_spec_kind (template_count);
1340
1341  switch (tsk)
1342    {
1343    case tsk_none:
1344      if (processing_specialization)
1345	{
1346	  specialization = 1;
1347	  SET_DECL_TEMPLATE_SPECIALIZATION (decl);
1348	}
1349      else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
1350	{
1351	  if (is_friend)
1352	    /* This could be something like:
1353
1354	       template <class T> void f(T);
1355	       class S { friend void f<>(int); }  */
1356	    specialization = 1;
1357	  else
1358	    {
1359	      /* This case handles bogus declarations like template <>
1360		 template <class T> void f<int>(); */
1361
1362	      error ("template-id `%D' in declaration of primary template",
1363			declarator);
1364	      return decl;
1365	    }
1366	}
1367      break;
1368
1369    case tsk_invalid_member_spec:
1370      /* The error has already been reported in
1371	 check_specialization_scope.  */
1372      return error_mark_node;
1373
1374    case tsk_invalid_expl_inst:
1375      error ("template parameter list used in explicit instantiation");
1376
1377      /* Fall through.  */
1378
1379    case tsk_expl_inst:
1380      if (have_def)
1381	error ("definition provided for explicit instantiation");
1382
1383      explicit_instantiation = 1;
1384      break;
1385
1386    case tsk_excessive_parms:
1387      error ("too many template parameter lists in declaration of `%D'",
1388		decl);
1389      return error_mark_node;
1390
1391      /* Fall through.  */
1392    case tsk_expl_spec:
1393      SET_DECL_TEMPLATE_SPECIALIZATION (decl);
1394      if (ctype)
1395	member_specialization = 1;
1396      else
1397	specialization = 1;
1398      break;
1399
1400    case tsk_insufficient_parms:
1401      if (template_header_count)
1402	{
1403	  error("too few template parameter lists in declaration of `%D'",
1404		   decl);
1405	  return decl;
1406	}
1407      else if (ctype != NULL_TREE
1408	       && !TYPE_BEING_DEFINED (ctype)
1409	       && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype)
1410	       && !is_friend)
1411	{
1412	  /* For backwards compatibility, we accept:
1413
1414	       template <class T> struct S { void f(); };
1415	       void S<int>::f() {} // Missing template <>
1416
1417	     That used to be legal C++.  */
1418	  if (pedantic)
1419	    pedwarn
1420	      ("explicit specialization not preceded by `template <>'");
1421	  specialization = 1;
1422	  SET_DECL_TEMPLATE_SPECIALIZATION (decl);
1423	}
1424      break;
1425
1426    case tsk_template:
1427      if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
1428	{
1429	  /* This case handles bogus declarations like template <>
1430	     template <class T> void f<int>(); */
1431
1432	  if (uses_template_parms (declarator))
1433	    error ("partial specialization `%D' of function template",
1434		      declarator);
1435	  else
1436	    error ("template-id `%D' in declaration of primary template",
1437		      declarator);
1438	  return decl;
1439	}
1440
1441      if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
1442	/* This is a specialization of a member template, without
1443	   specialization the containing class.  Something like:
1444
1445	     template <class T> struct S {
1446	       template <class U> void f (U);
1447             };
1448	     template <> template <class U> void S<int>::f(U) {}
1449
1450	   That's a specialization -- but of the entire template.  */
1451	specialization = 1;
1452      break;
1453
1454    default:
1455      abort ();
1456    }
1457
1458  if (specialization || member_specialization)
1459    {
1460      tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
1461      for (; t; t = TREE_CHAIN (t))
1462	if (TREE_PURPOSE (t))
1463	  {
1464	    pedwarn
1465	      ("default argument specified in explicit specialization");
1466	    break;
1467	  }
1468      if (current_lang_name == lang_name_c)
1469	error ("template specialization with C linkage");
1470    }
1471
1472  if (specialization || member_specialization || explicit_instantiation)
1473    {
1474      tree tmpl = NULL_TREE;
1475      tree targs = NULL_TREE;
1476
1477      /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
1478      if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
1479	{
1480	  tree fns;
1481
1482	  my_friendly_assert (TREE_CODE (declarator) == IDENTIFIER_NODE,
1483			      0);
1484	  if (!ctype)
1485	    fns = IDENTIFIER_NAMESPACE_VALUE (dname);
1486	  else
1487	    fns = dname;
1488
1489	  declarator =
1490	    lookup_template_function (fns, NULL_TREE);
1491	}
1492
1493      if (declarator == error_mark_node)
1494	return error_mark_node;
1495
1496      if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
1497	{
1498	  if (!explicit_instantiation)
1499	    /* A specialization in class scope.  This is illegal,
1500	       but the error will already have been flagged by
1501	       check_specialization_scope.  */
1502	    return error_mark_node;
1503	  else
1504	    {
1505	      /* It's not legal to write an explicit instantiation in
1506		 class scope, e.g.:
1507
1508	           class C { template void f(); }
1509
1510		   This case is caught by the parser.  However, on
1511		   something like:
1512
1513		   template class C { void f(); };
1514
1515		   (which is illegal) we can get here.  The error will be
1516		   issued later.  */
1517	      ;
1518	    }
1519
1520	  return decl;
1521	}
1522      else if (TREE_CODE (TREE_OPERAND (declarator, 0)) == LOOKUP_EXPR)
1523	{
1524	  /* A friend declaration.  We can't do much, because we don't
1525	     know what this resolves to, yet.  */
1526	  my_friendly_assert (is_friend != 0, 0);
1527	  my_friendly_assert (!explicit_instantiation, 0);
1528	  SET_DECL_IMPLICIT_INSTANTIATION (decl);
1529	  return decl;
1530	}
1531      else if (ctype != NULL_TREE
1532	       && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
1533		   IDENTIFIER_NODE))
1534	{
1535	  /* Find the list of functions in ctype that have the same
1536	     name as the declared function.  */
1537	  tree name = TREE_OPERAND (declarator, 0);
1538	  tree fns = NULL_TREE;
1539	  int idx;
1540
1541	  if (name == constructor_name (ctype)
1542	      || name == constructor_name_full (ctype))
1543	    {
1544	      int is_constructor = DECL_CONSTRUCTOR_P (decl);
1545
1546	      if (is_constructor ? !TYPE_HAS_CONSTRUCTOR (ctype)
1547		  : !TYPE_HAS_DESTRUCTOR (ctype))
1548		{
1549		  /* From [temp.expl.spec]:
1550
1551		     If such an explicit specialization for the member
1552		     of a class template names an implicitly-declared
1553		     special member function (clause _special_), the
1554		     program is ill-formed.
1555
1556		     Similar language is found in [temp.explicit].  */
1557		  error ("specialization of implicitly-declared special member function");
1558		  return error_mark_node;
1559		}
1560
1561	      name = is_constructor ? ctor_identifier : dtor_identifier;
1562	    }
1563
1564	  if (!DECL_CONV_FN_P (decl))
1565	    {
1566	      idx = lookup_fnfields_1 (ctype, name);
1567	      if (idx >= 0)
1568		fns = TREE_VEC_ELT (CLASSTYPE_METHOD_VEC (ctype), idx);
1569	    }
1570	  else
1571	    {
1572	      tree methods;
1573
1574	      /* For a type-conversion operator, we cannot do a
1575		 name-based lookup.  We might be looking for `operator
1576		 int' which will be a specialization of `operator T'.
1577		 So, we find *all* the conversion operators, and then
1578		 select from them.  */
1579	      fns = NULL_TREE;
1580
1581	      methods = CLASSTYPE_METHOD_VEC (ctype);
1582	      if (methods)
1583		for (idx = 2; idx < TREE_VEC_LENGTH (methods); ++idx)
1584		  {
1585		    tree ovl = TREE_VEC_ELT (methods, idx);
1586
1587		    if (!ovl || !DECL_CONV_FN_P (OVL_CURRENT (ovl)))
1588		      /* There are no more conversion functions.  */
1589		      break;
1590
1591		    /* Glue all these conversion functions together
1592		       with those we already have.  */
1593		    for (; ovl; ovl = OVL_NEXT (ovl))
1594		      fns = ovl_cons (OVL_CURRENT (ovl), fns);
1595		  }
1596	    }
1597
1598	  if (fns == NULL_TREE)
1599	    {
1600	      error ("no member function `%D' declared in `%T'",
1601			name, ctype);
1602	      return error_mark_node;
1603	    }
1604	  else
1605	    TREE_OPERAND (declarator, 0) = fns;
1606	}
1607
1608      /* Figure out what exactly is being specialized at this point.
1609	 Note that for an explicit instantiation, even one for a
1610	 member function, we cannot tell apriori whether the
1611	 instantiation is for a member template, or just a member
1612	 function of a template class.  Even if a member template is
1613	 being instantiated, the member template arguments may be
1614	 elided if they can be deduced from the rest of the
1615	 declaration.  */
1616      tmpl = determine_specialization (declarator, decl,
1617				       &targs,
1618				       member_specialization);
1619
1620      if (!tmpl || tmpl == error_mark_node)
1621	/* We couldn't figure out what this declaration was
1622	   specializing.  */
1623	return error_mark_node;
1624      else
1625	{
1626	  tree gen_tmpl = most_general_template (tmpl);
1627
1628	  if (explicit_instantiation)
1629	    {
1630	      /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
1631		 is done by do_decl_instantiation later.  */
1632
1633	      int arg_depth = TMPL_ARGS_DEPTH (targs);
1634	      int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
1635
1636	      if (arg_depth > parm_depth)
1637		{
1638		  /* If TMPL is not the most general template (for
1639		     example, if TMPL is a friend template that is
1640		     injected into namespace scope), then there will
1641		     be too many levels of TARGS.  Remove some of them
1642		     here.  */
1643		  int i;
1644		  tree new_targs;
1645
1646		  new_targs = make_tree_vec (parm_depth);
1647		  for (i = arg_depth - parm_depth; i < arg_depth; ++i)
1648		    TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
1649		      = TREE_VEC_ELT (targs, i);
1650		  targs = new_targs;
1651		}
1652
1653	      return instantiate_template (tmpl, targs);
1654	    }
1655
1656	  /* If this is a specialization of a member template of a
1657	     template class.  In we want to return the TEMPLATE_DECL,
1658	     not the specialization of it.  */
1659	  if (tsk == tsk_template)
1660	    {
1661	      SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
1662	      DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl)) = NULL_TREE;
1663	      return tmpl;
1664	    }
1665
1666	  /* If we thought that the DECL was a member function, but it
1667	     turns out to be specializing a static member function,
1668	     make DECL a static member function as well.  */
1669	  if (DECL_STATIC_FUNCTION_P (tmpl)
1670	      && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1671	    {
1672	      revert_static_member_fn (decl);
1673	      last_function_parms = TREE_CHAIN (last_function_parms);
1674	    }
1675
1676	  /* Set up the DECL_TEMPLATE_INFO for DECL.  */
1677	  DECL_TEMPLATE_INFO (decl) = tree_cons (tmpl, targs, NULL_TREE);
1678
1679	  /* Inherit default function arguments from the template
1680	     DECL is specializing.  */
1681	  copy_default_args_to_explicit_spec (decl);
1682
1683	  /* This specialization has the same protection as the
1684	     template it specializes.  */
1685	  TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
1686	  TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
1687
1688	  if (is_friend && !have_def)
1689	    /* This is not really a declaration of a specialization.
1690	       It's just the name of an instantiation.  But, it's not
1691	       a request for an instantiation, either.  */
1692	    SET_DECL_IMPLICIT_INSTANTIATION (decl);
1693	  else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
1694	    /* This is indeed a specialization.  In case of constructors
1695	       and destructors, we need in-charge and not-in-charge
1696	       versions in V3 ABI.  */
1697	    clone_function_decl (decl, /*update_method_vec_p=*/0);
1698
1699	  /* Register this specialization so that we can find it
1700	     again.  */
1701	  decl = register_specialization (decl, gen_tmpl, targs);
1702	}
1703    }
1704
1705  return decl;
1706}
1707
1708/* TYPE is being declared.  Verify that the use of template headers
1709   and such is reasonable.  Issue error messages if not.  */
1710
1711void
1712maybe_check_template_type (type)
1713     tree type;
1714{
1715  if (template_header_count)
1716    {
1717      /* We are in the scope of some `template <...>' header.  */
1718
1719      int context_depth
1720	= template_class_depth_real (TYPE_CONTEXT (type),
1721				     /*count_specializations=*/1);
1722
1723      if (template_header_count <= context_depth)
1724	/* This is OK; the template headers are for the context.  We
1725	   are actually too lenient here; like
1726	   check_explicit_specialization we should consider the number
1727	   of template types included in the actual declaration.  For
1728	   example,
1729
1730	     template <class T> struct S {
1731	       template <class U> template <class V>
1732	       struct I {};
1733	     };
1734
1735	   is illegal, but:
1736
1737	     template <class T> struct S {
1738	       template <class U> struct I;
1739	     };
1740
1741	     template <class T> template <class U.
1742	     struct S<T>::I {};
1743
1744	   is not.  */
1745	;
1746      else if (template_header_count > context_depth + 1)
1747	/* There are two many template parameter lists.  */
1748	error ("too many template parameter lists in declaration of `%T'", type);
1749    }
1750}
1751
1752/* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
1753   parameters.  These are represented in the same format used for
1754   DECL_TEMPLATE_PARMS.  */
1755
1756int comp_template_parms (parms1, parms2)
1757     tree parms1;
1758     tree parms2;
1759{
1760  tree p1;
1761  tree p2;
1762
1763  if (parms1 == parms2)
1764    return 1;
1765
1766  for (p1 = parms1, p2 = parms2;
1767       p1 != NULL_TREE && p2 != NULL_TREE;
1768       p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
1769    {
1770      tree t1 = TREE_VALUE (p1);
1771      tree t2 = TREE_VALUE (p2);
1772      int i;
1773
1774      my_friendly_assert (TREE_CODE (t1) == TREE_VEC, 0);
1775      my_friendly_assert (TREE_CODE (t2) == TREE_VEC, 0);
1776
1777      if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
1778	return 0;
1779
1780      for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
1781	{
1782	  tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
1783	  tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
1784
1785	  if (TREE_CODE (parm1) != TREE_CODE (parm2))
1786	    return 0;
1787
1788	  if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM)
1789	    continue;
1790	  else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
1791	    return 0;
1792	}
1793    }
1794
1795  if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
1796    /* One set of parameters has more parameters lists than the
1797       other.  */
1798    return 0;
1799
1800  return 1;
1801}
1802
1803/* Complain if DECL shadows a template parameter.
1804
1805   [temp.local]: A template-parameter shall not be redeclared within its
1806   scope (including nested scopes).  */
1807
1808void
1809check_template_shadow (decl)
1810     tree decl;
1811{
1812  tree olddecl;
1813
1814  /* If we're not in a template, we can't possibly shadow a template
1815     parameter.  */
1816  if (!current_template_parms)
1817    return;
1818
1819  /* Figure out what we're shadowing.  */
1820  if (TREE_CODE (decl) == OVERLOAD)
1821    decl = OVL_CURRENT (decl);
1822  olddecl = IDENTIFIER_VALUE (DECL_NAME (decl));
1823
1824  /* If there's no previous binding for this name, we're not shadowing
1825     anything, let alone a template parameter.  */
1826  if (!olddecl)
1827    return;
1828
1829  /* If we're not shadowing a template parameter, we're done.  Note
1830     that OLDDECL might be an OVERLOAD (or perhaps even an
1831     ERROR_MARK), so we can't just blithely assume it to be a _DECL
1832     node.  */
1833  if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
1834    return;
1835
1836  /* We check for decl != olddecl to avoid bogus errors for using a
1837     name inside a class.  We check TPFI to avoid duplicate errors for
1838     inline member templates.  */
1839  if (decl == olddecl
1840      || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
1841    return;
1842
1843  cp_error_at ("declaration of `%#D'", decl);
1844  cp_error_at (" shadows template parm `%#D'", olddecl);
1845}
1846
1847/* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
1848   ORIG_LEVEL, DECL, and TYPE.  */
1849
1850static tree
1851build_template_parm_index (index, level, orig_level, decl, type)
1852     int index;
1853     int level;
1854     int orig_level;
1855     tree decl;
1856     tree type;
1857{
1858  tree t = make_node (TEMPLATE_PARM_INDEX);
1859  TEMPLATE_PARM_IDX (t) = index;
1860  TEMPLATE_PARM_LEVEL (t) = level;
1861  TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
1862  TEMPLATE_PARM_DECL (t) = decl;
1863  TREE_TYPE (t) = type;
1864
1865  return t;
1866}
1867
1868/* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
1869   TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
1870   TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
1871   new one is created.  */
1872
1873static tree
1874reduce_template_parm_level (index, type, levels)
1875     tree index;
1876     tree type;
1877     int levels;
1878{
1879  if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
1880      || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
1881	  != TEMPLATE_PARM_LEVEL (index) - levels))
1882    {
1883      tree decl
1884	= build_decl (TREE_CODE (TEMPLATE_PARM_DECL (index)),
1885		      DECL_NAME (TEMPLATE_PARM_DECL (index)),
1886		      type);
1887      tree t
1888	= build_template_parm_index (TEMPLATE_PARM_IDX (index),
1889				     TEMPLATE_PARM_LEVEL (index) - levels,
1890				     TEMPLATE_PARM_ORIG_LEVEL (index),
1891				     decl, type);
1892      TEMPLATE_PARM_DESCENDANTS (index) = t;
1893
1894      DECL_ARTIFICIAL (decl) = 1;
1895      SET_DECL_TEMPLATE_PARM_P (decl);
1896
1897      /* Template template parameters need this.  */
1898      DECL_TEMPLATE_PARMS (decl)
1899	= DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index));
1900    }
1901
1902  return TEMPLATE_PARM_DESCENDANTS (index);
1903}
1904
1905/* Process information from new template parameter NEXT and append it to the
1906   LIST being built.  */
1907
1908tree
1909process_template_parm (list, next)
1910     tree list, next;
1911{
1912  tree parm;
1913  tree decl = 0;
1914  tree defval;
1915  int is_type, idx;
1916
1917  parm = next;
1918  my_friendly_assert (TREE_CODE (parm) == TREE_LIST, 259);
1919  defval = TREE_PURPOSE (parm);
1920  parm = TREE_VALUE (parm);
1921  is_type = TREE_PURPOSE (parm) == class_type_node;
1922
1923  if (list)
1924    {
1925      tree p = TREE_VALUE (tree_last (list));
1926
1927      if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
1928	idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
1929      else
1930	idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
1931      ++idx;
1932    }
1933  else
1934    idx = 0;
1935
1936  if (!is_type)
1937    {
1938      my_friendly_assert (TREE_CODE (TREE_PURPOSE (parm)) == TREE_LIST, 260);
1939      /* is a const-param */
1940      parm = grokdeclarator (TREE_VALUE (parm), TREE_PURPOSE (parm),
1941			     PARM, 0, NULL);
1942      SET_DECL_TEMPLATE_PARM_P (parm);
1943
1944      /* [temp.param]
1945
1946	 The top-level cv-qualifiers on the template-parameter are
1947	 ignored when determining its type.  */
1948      TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
1949
1950      /* A template parameter is not modifiable.  */
1951      TREE_READONLY (parm) = 1;
1952      if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
1953        TREE_TYPE (parm) = void_type_node;
1954      decl = build_decl (CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
1955      DECL_INITIAL (parm) = DECL_INITIAL (decl)
1956	= build_template_parm_index (idx, processing_template_decl,
1957				     processing_template_decl,
1958				     decl, TREE_TYPE (parm));
1959    }
1960  else
1961    {
1962      tree t;
1963      parm = TREE_VALUE (parm);
1964
1965      if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
1966	{
1967	  t = make_aggr_type (TEMPLATE_TEMPLATE_PARM);
1968	  /* This is for distinguishing between real templates and template
1969	     template parameters */
1970	  TREE_TYPE (parm) = t;
1971	  TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
1972	  decl = parm;
1973	}
1974      else
1975	{
1976	  t = make_aggr_type (TEMPLATE_TYPE_PARM);
1977	  /* parm is either IDENTIFIER_NODE or NULL_TREE */
1978	  decl = build_decl (TYPE_DECL, parm, t);
1979	}
1980
1981      TYPE_NAME (t) = decl;
1982      TYPE_STUB_DECL (t) = decl;
1983      parm = decl;
1984      TEMPLATE_TYPE_PARM_INDEX (t)
1985	= build_template_parm_index (idx, processing_template_decl,
1986				     processing_template_decl,
1987				     decl, TREE_TYPE (parm));
1988    }
1989  DECL_ARTIFICIAL (decl) = 1;
1990  SET_DECL_TEMPLATE_PARM_P (decl);
1991  pushdecl (decl);
1992  parm = build_tree_list (defval, parm);
1993  return chainon (list, parm);
1994}
1995
1996/* The end of a template parameter list has been reached.  Process the
1997   tree list into a parameter vector, converting each parameter into a more
1998   useful form.	 Type parameters are saved as IDENTIFIER_NODEs, and others
1999   as PARM_DECLs.  */
2000
2001tree
2002end_template_parm_list (parms)
2003     tree parms;
2004{
2005  int nparms;
2006  tree parm, next;
2007  tree saved_parmlist = make_tree_vec (list_length (parms));
2008
2009  current_template_parms
2010    = tree_cons (size_int (processing_template_decl),
2011		 saved_parmlist, current_template_parms);
2012
2013  for (parm = parms, nparms = 0; parm; parm = next, nparms++)
2014    {
2015      next = TREE_CHAIN (parm);
2016      TREE_VEC_ELT (saved_parmlist, nparms) = parm;
2017      TREE_CHAIN (parm) = NULL_TREE;
2018    }
2019
2020  --processing_template_parmlist;
2021
2022  return saved_parmlist;
2023}
2024
2025/* end_template_decl is called after a template declaration is seen.  */
2026
2027void
2028end_template_decl ()
2029{
2030  reset_specialization ();
2031
2032  if (! processing_template_decl)
2033    return;
2034
2035  /* This matches the pushlevel in begin_template_parm_list.  */
2036  finish_scope ();
2037
2038  --processing_template_decl;
2039  current_template_parms = TREE_CHAIN (current_template_parms);
2040}
2041
2042/* Given a template argument vector containing the template PARMS.
2043   The innermost PARMS are given first.  */
2044
2045tree
2046current_template_args ()
2047{
2048  tree header;
2049  tree args = NULL_TREE;
2050  int length = TMPL_PARMS_DEPTH (current_template_parms);
2051  int l = length;
2052
2053  /* If there is only one level of template parameters, we do not
2054     create a TREE_VEC of TREE_VECs.  Instead, we return a single
2055     TREE_VEC containing the arguments.  */
2056  if (length > 1)
2057    args = make_tree_vec (length);
2058
2059  for (header = current_template_parms; header; header = TREE_CHAIN (header))
2060    {
2061      tree a = copy_node (TREE_VALUE (header));
2062      int i;
2063
2064      TREE_TYPE (a) = NULL_TREE;
2065      for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
2066	{
2067	  tree t = TREE_VEC_ELT (a, i);
2068
2069	  /* T will be a list if we are called from within a
2070	     begin/end_template_parm_list pair, but a vector directly
2071	     if within a begin/end_member_template_processing pair.  */
2072	  if (TREE_CODE (t) == TREE_LIST)
2073	    {
2074	      t = TREE_VALUE (t);
2075
2076	      if (TREE_CODE (t) == TYPE_DECL
2077		  || TREE_CODE (t) == TEMPLATE_DECL)
2078		t = TREE_TYPE (t);
2079	      else
2080		t = DECL_INITIAL (t);
2081	      TREE_VEC_ELT (a, i) = t;
2082	    }
2083	}
2084
2085      if (length > 1)
2086	TREE_VEC_ELT (args, --l) = a;
2087      else
2088	args = a;
2089    }
2090
2091  return args;
2092}
2093
2094/* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
2095   template PARMS.  Used by push_template_decl below.  */
2096
2097static tree
2098build_template_decl (decl, parms)
2099     tree decl;
2100     tree parms;
2101{
2102  tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
2103  DECL_TEMPLATE_PARMS (tmpl) = parms;
2104  DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
2105  if (DECL_LANG_SPECIFIC (decl))
2106    {
2107      if (CAN_HAVE_FULL_LANG_DECL_P (decl))
2108	DECL_VIRTUAL_CONTEXT (tmpl) = DECL_VIRTUAL_CONTEXT (decl);
2109      DECL_STATIC_FUNCTION_P (tmpl) = DECL_STATIC_FUNCTION_P (decl);
2110      DECL_CONSTRUCTOR_P (tmpl) = DECL_CONSTRUCTOR_P (decl);
2111      DECL_NONCONVERTING_P (tmpl) = DECL_NONCONVERTING_P (decl);
2112      DECL_ASSIGNMENT_OPERATOR_P (tmpl) = DECL_ASSIGNMENT_OPERATOR_P (decl);
2113      if (DECL_OVERLOADED_OPERATOR_P (decl))
2114	SET_OVERLOADED_OPERATOR_CODE (tmpl,
2115				      DECL_OVERLOADED_OPERATOR_P (decl));
2116    }
2117
2118  return tmpl;
2119}
2120
2121struct template_parm_data
2122{
2123  /* The level of the template parameters we are currently
2124     processing.  */
2125  int level;
2126
2127  /* The index of the specialization argument we are currently
2128     processing.  */
2129  int current_arg;
2130
2131  /* An array whose size is the number of template parameters.  The
2132     elements are non-zero if the parameter has been used in any one
2133     of the arguments processed so far.  */
2134  int* parms;
2135
2136  /* An array whose size is the number of template arguments.  The
2137     elements are non-zero if the argument makes use of template
2138     parameters of this level.  */
2139  int* arg_uses_template_parms;
2140};
2141
2142/* Subroutine of push_template_decl used to see if each template
2143   parameter in a partial specialization is used in the explicit
2144   argument list.  If T is of the LEVEL given in DATA (which is
2145   treated as a template_parm_data*), then DATA->PARMS is marked
2146   appropriately.  */
2147
2148static int
2149mark_template_parm (t, data)
2150     tree t;
2151     void* data;
2152{
2153  int level;
2154  int idx;
2155  struct template_parm_data* tpd = (struct template_parm_data*) data;
2156
2157  if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
2158    {
2159      level = TEMPLATE_PARM_LEVEL (t);
2160      idx = TEMPLATE_PARM_IDX (t);
2161    }
2162  else
2163    {
2164      level = TEMPLATE_TYPE_LEVEL (t);
2165      idx = TEMPLATE_TYPE_IDX (t);
2166    }
2167
2168  if (level == tpd->level)
2169    {
2170      tpd->parms[idx] = 1;
2171      tpd->arg_uses_template_parms[tpd->current_arg] = 1;
2172    }
2173
2174  /* Return zero so that for_each_template_parm will continue the
2175     traversal of the tree; we want to mark *every* template parm.  */
2176  return 0;
2177}
2178
2179/* Process the partial specialization DECL.  */
2180
2181static tree
2182process_partial_specialization (decl)
2183     tree decl;
2184{
2185  tree type = TREE_TYPE (decl);
2186  tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
2187  tree specargs = CLASSTYPE_TI_ARGS (type);
2188  tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
2189  tree inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
2190  tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
2191  int nargs = TREE_VEC_LENGTH (inner_args);
2192  int ntparms = TREE_VEC_LENGTH (inner_parms);
2193  int  i;
2194  int did_error_intro = 0;
2195  struct template_parm_data tpd;
2196  struct template_parm_data tpd2;
2197
2198  /* We check that each of the template parameters given in the
2199     partial specialization is used in the argument list to the
2200     specialization.  For example:
2201
2202       template <class T> struct S;
2203       template <class T> struct S<T*>;
2204
2205     The second declaration is OK because `T*' uses the template
2206     parameter T, whereas
2207
2208       template <class T> struct S<int>;
2209
2210     is no good.  Even trickier is:
2211
2212       template <class T>
2213       struct S1
2214       {
2215	  template <class U>
2216	  struct S2;
2217	  template <class U>
2218	  struct S2<T>;
2219       };
2220
2221     The S2<T> declaration is actually illegal; it is a
2222     full-specialization.  Of course,
2223
2224	  template <class U>
2225	  struct S2<T (*)(U)>;
2226
2227     or some such would have been OK.  */
2228  tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
2229  tpd.parms = alloca (sizeof (int) * ntparms);
2230  memset ((PTR) tpd.parms, 0, sizeof (int) * ntparms);
2231
2232  tpd.arg_uses_template_parms = alloca (sizeof (int) * nargs);
2233  memset ((PTR) tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
2234  for (i = 0; i < nargs; ++i)
2235    {
2236      tpd.current_arg = i;
2237      for_each_template_parm (TREE_VEC_ELT (inner_args, i),
2238			      &mark_template_parm,
2239			      &tpd);
2240    }
2241  for (i = 0; i < ntparms; ++i)
2242    if (tpd.parms[i] == 0)
2243      {
2244	/* One of the template parms was not used in the
2245	   specialization.  */
2246	if (!did_error_intro)
2247	  {
2248	    error ("template parameters not used in partial specialization:");
2249	    did_error_intro = 1;
2250	  }
2251
2252	error ("        `%D'",
2253		  TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
2254      }
2255
2256  /* [temp.class.spec]
2257
2258     The argument list of the specialization shall not be identical to
2259     the implicit argument list of the primary template.  */
2260  if (comp_template_args
2261      (inner_args,
2262       INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
2263						   (maintmpl)))))
2264    error ("partial specialization `%T' does not specialize any template arguments", type);
2265
2266  /* [temp.class.spec]
2267
2268     A partially specialized non-type argument expression shall not
2269     involve template parameters of the partial specialization except
2270     when the argument expression is a simple identifier.
2271
2272     The type of a template parameter corresponding to a specialized
2273     non-type argument shall not be dependent on a parameter of the
2274     specialization.  */
2275  my_friendly_assert (nargs == DECL_NTPARMS (maintmpl), 0);
2276  tpd2.parms = 0;
2277  for (i = 0; i < nargs; ++i)
2278    {
2279      tree arg = TREE_VEC_ELT (inner_args, i);
2280      if (/* These first two lines are the `non-type' bit.  */
2281	  !TYPE_P (arg)
2282	  && TREE_CODE (arg) != TEMPLATE_DECL
2283	  /* This next line is the `argument expression is not just a
2284	     simple identifier' condition and also the `specialized
2285	     non-type argument' bit.  */
2286	  && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
2287	{
2288	  if (tpd.arg_uses_template_parms[i])
2289	    error ("template argument `%E' involves template parameter(s)", arg);
2290	  else
2291	    {
2292	      /* Look at the corresponding template parameter,
2293		 marking which template parameters its type depends
2294		 upon.  */
2295	      tree type =
2296		TREE_TYPE (TREE_VALUE (TREE_VEC_ELT (main_inner_parms,
2297						     i)));
2298
2299	      if (!tpd2.parms)
2300		{
2301		  /* We haven't yet initialized TPD2.  Do so now.  */
2302		  tpd2.arg_uses_template_parms
2303		    =  (int*) alloca (sizeof (int) * nargs);
2304		  /* The number of parameters here is the number in the
2305		     main template, which, as checked in the assertion
2306		     above, is NARGS.  */
2307		  tpd2.parms = (int*) alloca (sizeof (int) * nargs);
2308		  tpd2.level =
2309		    TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
2310		}
2311
2312	      /* Mark the template parameters.  But this time, we're
2313		 looking for the template parameters of the main
2314		 template, not in the specialization.  */
2315	      tpd2.current_arg = i;
2316	      tpd2.arg_uses_template_parms[i] = 0;
2317	      memset ((PTR) tpd2.parms, 0, sizeof (int) * nargs);
2318	      for_each_template_parm (type,
2319				      &mark_template_parm,
2320				      &tpd2);
2321
2322	      if (tpd2.arg_uses_template_parms [i])
2323		{
2324		  /* The type depended on some template parameters.
2325		     If they are fully specialized in the
2326		     specialization, that's OK.  */
2327		  int j;
2328		  for (j = 0; j < nargs; ++j)
2329		    if (tpd2.parms[j] != 0
2330			&& tpd.arg_uses_template_parms [j])
2331		      {
2332			error ("type `%T' of template argument `%E' depends on template parameter(s)",
2333				  type,
2334				  arg);
2335			break;
2336		      }
2337		}
2338	    }
2339	}
2340    }
2341
2342  if (retrieve_specialization (maintmpl, specargs))
2343    /* We've already got this specialization.  */
2344    return decl;
2345
2346  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
2347    = tree_cons (inner_args, inner_parms,
2348		 DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
2349  TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
2350  return decl;
2351}
2352
2353/* Check that a template declaration's use of default arguments is not
2354   invalid.  Here, PARMS are the template parameters.  IS_PRIMARY is
2355   non-zero if DECL is the thing declared by a primary template.
2356   IS_PARTIAL is non-zero if DECL is a partial specialization.  */
2357
2358static void
2359check_default_tmpl_args (decl, parms, is_primary, is_partial)
2360     tree decl;
2361     tree parms;
2362     int is_primary;
2363     int is_partial;
2364{
2365  const char *msg;
2366  int last_level_to_check;
2367  tree parm_level;
2368
2369  /* [temp.param]
2370
2371     A default template-argument shall not be specified in a
2372     function template declaration or a function template definition, nor
2373     in the template-parameter-list of the definition of a member of a
2374     class template.  */
2375
2376  if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
2377    /* You can't have a function template declaration in a local
2378       scope, nor you can you define a member of a class template in a
2379       local scope.  */
2380    return;
2381
2382  if (current_class_type
2383      && !TYPE_BEING_DEFINED (current_class_type)
2384      && DECL_LANG_SPECIFIC (decl)
2385      /* If this is either a friend defined in the scope of the class
2386	 or a member function.  */
2387      && ((DECL_CONTEXT (decl)
2388	   && same_type_p (DECL_CONTEXT (decl), current_class_type))
2389	  || (DECL_FRIEND_CONTEXT (decl)
2390	      && same_type_p (DECL_FRIEND_CONTEXT (decl),
2391			      current_class_type)))
2392      /* And, if it was a member function, it really was defined in
2393	 the scope of the class.  */
2394      && (!DECL_FUNCTION_MEMBER_P (decl) || DECL_INITIALIZED_IN_CLASS_P (decl)))
2395    /* We already checked these parameters when the template was
2396       declared, so there's no need to do it again now.  This function
2397       was defined in class scope, but we're processing it's body now
2398       that the class is complete.  */
2399    return;
2400
2401  /* [temp.param]
2402
2403     If a template-parameter has a default template-argument, all
2404     subsequent template-parameters shall have a default
2405     template-argument supplied.  */
2406  for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
2407    {
2408      tree inner_parms = TREE_VALUE (parm_level);
2409      int ntparms = TREE_VEC_LENGTH (inner_parms);
2410      int seen_def_arg_p = 0;
2411      int i;
2412
2413      for (i = 0; i < ntparms; ++i)
2414	{
2415	  tree parm = TREE_VEC_ELT (inner_parms, i);
2416	  if (TREE_PURPOSE (parm))
2417	    seen_def_arg_p = 1;
2418	  else if (seen_def_arg_p)
2419	    {
2420	      error ("no default argument for `%D'", TREE_VALUE (parm));
2421	      /* For better subsequent error-recovery, we indicate that
2422		 there should have been a default argument.  */
2423	      TREE_PURPOSE (parm) = error_mark_node;
2424	    }
2425	}
2426    }
2427
2428  if (TREE_CODE (decl) != TYPE_DECL || is_partial || !is_primary)
2429    /* For an ordinary class template, default template arguments are
2430       allowed at the innermost level, e.g.:
2431         template <class T = int>
2432	 struct S {};
2433       but, in a partial specialization, they're not allowed even
2434       there, as we have in [temp.class.spec]:
2435
2436	 The template parameter list of a specialization shall not
2437	 contain default template argument values.
2438
2439       So, for a partial specialization, or for a function template,
2440       we look at all of them.  */
2441    ;
2442  else
2443    /* But, for a primary class template that is not a partial
2444       specialization we look at all template parameters except the
2445       innermost ones.  */
2446    parms = TREE_CHAIN (parms);
2447
2448  /* Figure out what error message to issue.  */
2449  if (TREE_CODE (decl) == FUNCTION_DECL)
2450    msg = "default template arguments may not be used in function templates";
2451  else if (is_partial)
2452    msg = "default template arguments may not be used in partial specializations";
2453  else
2454    msg = "default argument for template parameter for class enclosing `%D'";
2455
2456  if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
2457    /* If we're inside a class definition, there's no need to
2458       examine the parameters to the class itself.  On the one
2459       hand, they will be checked when the class is defined, and,
2460       on the other, default arguments are legal in things like:
2461         template <class T = double>
2462         struct S { template <class U> void f(U); };
2463       Here the default argument for `S' has no bearing on the
2464       declaration of `f'.  */
2465    last_level_to_check = template_class_depth (current_class_type) + 1;
2466  else
2467    /* Check everything.  */
2468    last_level_to_check = 0;
2469
2470  for (parm_level = parms;
2471       parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
2472       parm_level = TREE_CHAIN (parm_level))
2473    {
2474      tree inner_parms = TREE_VALUE (parm_level);
2475      int i;
2476      int ntparms;
2477
2478      ntparms = TREE_VEC_LENGTH (inner_parms);
2479      for (i = 0; i < ntparms; ++i)
2480	if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
2481	  {
2482	    if (msg)
2483	      {
2484		error (msg, decl);
2485		msg = 0;
2486	      }
2487
2488	    /* Clear out the default argument so that we are not
2489	       confused later.  */
2490	    TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
2491	  }
2492
2493      /* At this point, if we're still interested in issuing messages,
2494	 they must apply to classes surrounding the object declared.  */
2495      if (msg)
2496	msg = "default argument for template parameter for class enclosing `%D'";
2497    }
2498}
2499
2500/* Creates a TEMPLATE_DECL for the indicated DECL using the template
2501   parameters given by current_template_args, or reuses a
2502   previously existing one, if appropriate.  Returns the DECL, or an
2503   equivalent one, if it is replaced via a call to duplicate_decls.
2504
2505   If IS_FRIEND is non-zero, DECL is a friend declaration.  */
2506
2507tree
2508push_template_decl_real (decl, is_friend)
2509     tree decl;
2510     int is_friend;
2511{
2512  tree tmpl;
2513  tree args;
2514  tree info;
2515  tree ctx;
2516  int primary;
2517  int is_partial;
2518  int new_template_p = 0;
2519
2520  /* See if this is a partial specialization.  */
2521  is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
2522		&& TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
2523		&& CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
2524
2525  is_friend |= (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl));
2526
2527  if (is_friend)
2528    /* For a friend, we want the context of the friend function, not
2529       the type of which it is a friend.  */
2530    ctx = DECL_CONTEXT (decl);
2531  else if (CP_DECL_CONTEXT (decl)
2532	   && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
2533    /* In the case of a virtual function, we want the class in which
2534       it is defined.  */
2535    ctx = CP_DECL_CONTEXT (decl);
2536  else
2537    /* Otherwise, if we're currently defining some class, the DECL
2538       is assumed to be a member of the class.  */
2539    ctx = current_scope ();
2540
2541  if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
2542    ctx = NULL_TREE;
2543
2544  if (!DECL_CONTEXT (decl))
2545    DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
2546
2547  /* See if this is a primary template.  */
2548  primary = template_parm_scope_p ();
2549
2550  if (primary)
2551    {
2552      if (current_lang_name == lang_name_c)
2553	error ("template with C linkage");
2554      else if (TREE_CODE (decl) == TYPE_DECL
2555	       && ANON_AGGRNAME_P (DECL_NAME (decl)))
2556	error ("template class without a name");
2557      else if ((DECL_IMPLICIT_TYPEDEF_P (decl)
2558		&& CLASS_TYPE_P (TREE_TYPE (decl)))
2559	       || (TREE_CODE (decl) == VAR_DECL && ctx && CLASS_TYPE_P (ctx))
2560	       || TREE_CODE (decl) == FUNCTION_DECL)
2561	/* OK */;
2562      else
2563	error ("template declaration of `%#D'", decl);
2564    }
2565
2566  /* Check to see that the rules regarding the use of default
2567     arguments are not being violated.  */
2568  check_default_tmpl_args (decl, current_template_parms,
2569			   primary, is_partial);
2570
2571  if (is_partial)
2572    return process_partial_specialization (decl);
2573
2574  args = current_template_args ();
2575
2576  if (!ctx
2577      || TREE_CODE (ctx) == FUNCTION_DECL
2578      || (TREE_CODE (ctx) != TEMPLATE_TYPE_PARM
2579	  && TREE_CODE (ctx) != BOUND_TEMPLATE_TEMPLATE_PARM
2580	  && TYPE_BEING_DEFINED (ctx))
2581      || (is_friend && !DECL_TEMPLATE_INFO (decl)))
2582    {
2583      if (DECL_LANG_SPECIFIC (decl)
2584	  && DECL_TEMPLATE_INFO (decl)
2585	  && DECL_TI_TEMPLATE (decl))
2586	tmpl = DECL_TI_TEMPLATE (decl);
2587      /* If DECL is a TYPE_DECL for a class-template, then there won't
2588	 be DECL_LANG_SPECIFIC.  The information equivalent to
2589	 DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
2590      else if (DECL_IMPLICIT_TYPEDEF_P (decl)
2591	       && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
2592	       && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
2593	{
2594	  /* Since a template declaration already existed for this
2595	     class-type, we must be redeclaring it here.  Make sure
2596	     that the redeclaration is legal.  */
2597	  redeclare_class_template (TREE_TYPE (decl),
2598				    current_template_parms);
2599	  /* We don't need to create a new TEMPLATE_DECL; just use the
2600	     one we already had.  */
2601	  tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
2602	}
2603      else
2604	{
2605	  tmpl = build_template_decl (decl, current_template_parms);
2606	  new_template_p = 1;
2607
2608	  if (DECL_LANG_SPECIFIC (decl)
2609	      && DECL_TEMPLATE_SPECIALIZATION (decl))
2610	    {
2611	      /* A specialization of a member template of a template
2612		 class. */
2613	      SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2614	      DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
2615	      DECL_TEMPLATE_INFO (decl) = NULL_TREE;
2616	    }
2617	}
2618    }
2619  else
2620    {
2621      tree a, t, current, parms;
2622      int i;
2623
2624      if (TREE_CODE (decl) == TYPE_DECL)
2625	{
2626	  if ((IS_AGGR_TYPE_CODE (TREE_CODE (TREE_TYPE (decl)))
2627	       || TREE_CODE (TREE_TYPE (decl)) == ENUMERAL_TYPE)
2628	      && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
2629	      && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
2630	    tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
2631	  else
2632	    {
2633	      error ("`%D' does not declare a template type", decl);
2634	      return decl;
2635	    }
2636	}
2637      else if (!DECL_LANG_SPECIFIC (decl) || !DECL_TEMPLATE_INFO (decl))
2638	{
2639	  error ("template definition of non-template `%#D'", decl);
2640	  return decl;
2641	}
2642      else
2643	tmpl = DECL_TI_TEMPLATE (decl);
2644
2645      if (is_member_template (tmpl)
2646	  && DECL_FUNCTION_TEMPLATE_P (tmpl)
2647	  && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
2648	  && DECL_TEMPLATE_SPECIALIZATION (decl))
2649	{
2650	  tree new_tmpl;
2651
2652	  /* The declaration is a specialization of a member
2653	     template, declared outside the class.  Therefore, the
2654	     innermost template arguments will be NULL, so we
2655	     replace them with the arguments determined by the
2656	     earlier call to check_explicit_specialization.  */
2657	  args = DECL_TI_ARGS (decl);
2658
2659	  new_tmpl
2660	    = build_template_decl (decl, current_template_parms);
2661	  DECL_TEMPLATE_RESULT (new_tmpl) = decl;
2662	  TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
2663	  DECL_TI_TEMPLATE (decl) = new_tmpl;
2664	  SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
2665	  DECL_TEMPLATE_INFO (new_tmpl)
2666	    = tree_cons (tmpl, args, NULL_TREE);
2667
2668	  register_specialization (new_tmpl,
2669				   most_general_template (tmpl),
2670				   args);
2671	  return decl;
2672	}
2673
2674      /* Make sure the template headers we got make sense.  */
2675
2676      parms = DECL_TEMPLATE_PARMS (tmpl);
2677      i = TMPL_PARMS_DEPTH (parms);
2678      if (TMPL_ARGS_DEPTH (args) != i)
2679	{
2680	  error ("expected %d levels of template parms for `%#D', got %d",
2681		    i, decl, TMPL_ARGS_DEPTH (args));
2682	}
2683      else
2684	for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
2685	  {
2686	    a = TMPL_ARGS_LEVEL (args, i);
2687	    t = INNERMOST_TEMPLATE_PARMS (parms);
2688
2689	    if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
2690	      {
2691		if (current == decl)
2692		  error ("got %d template parameters for `%#D'",
2693			    TREE_VEC_LENGTH (a), decl);
2694		else
2695		  error ("got %d template parameters for `%#T'",
2696			    TREE_VEC_LENGTH (a), current);
2697		error ("  but %d required", TREE_VEC_LENGTH (t));
2698	      }
2699
2700	    /* Perhaps we should also check that the parms are used in the
2701               appropriate qualifying scopes in the declarator?  */
2702
2703	    if (current == decl)
2704	      current = ctx;
2705	    else
2706	      current = TYPE_CONTEXT (current);
2707	  }
2708    }
2709
2710  DECL_TEMPLATE_RESULT (tmpl) = decl;
2711  TREE_TYPE (tmpl) = TREE_TYPE (decl);
2712
2713  /* Push template declarations for global functions and types.  Note
2714     that we do not try to push a global template friend declared in a
2715     template class; such a thing may well depend on the template
2716     parameters of the class.  */
2717  if (new_template_p && !ctx
2718      && !(is_friend && template_class_depth (current_class_type) > 0))
2719    tmpl = pushdecl_namespace_level (tmpl);
2720
2721  if (primary)
2722    DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
2723
2724  info = tree_cons (tmpl, args, NULL_TREE);
2725
2726  if (DECL_IMPLICIT_TYPEDEF_P (decl))
2727    {
2728      SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
2729      if ((!ctx || TREE_CODE (ctx) != FUNCTION_DECL)
2730	  && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
2731	  /* Don't change the name if we've already set it up.  */
2732	  && !IDENTIFIER_TEMPLATE (DECL_NAME (decl)))
2733	DECL_NAME (decl) = classtype_mangled_name (TREE_TYPE (decl));
2734    }
2735  else if (DECL_LANG_SPECIFIC (decl))
2736    DECL_TEMPLATE_INFO (decl) = info;
2737
2738  return DECL_TEMPLATE_RESULT (tmpl);
2739}
2740
2741tree
2742push_template_decl (decl)
2743     tree decl;
2744{
2745  return push_template_decl_real (decl, 0);
2746}
2747
2748/* Called when a class template TYPE is redeclared with the indicated
2749   template PARMS, e.g.:
2750
2751     template <class T> struct S;
2752     template <class T> struct S {};  */
2753
2754void
2755redeclare_class_template (type, parms)
2756     tree type;
2757     tree parms;
2758{
2759  tree tmpl;
2760  tree tmpl_parms;
2761  int i;
2762
2763  if (!TYPE_TEMPLATE_INFO (type))
2764    {
2765      error ("`%T' is not a template type", type);
2766      return;
2767    }
2768
2769  tmpl = TYPE_TI_TEMPLATE (type);
2770  if (!PRIMARY_TEMPLATE_P (tmpl))
2771    /* The type is nested in some template class.  Nothing to worry
2772       about here; there are no new template parameters for the nested
2773       type.  */
2774    return;
2775
2776  parms = INNERMOST_TEMPLATE_PARMS (parms);
2777  tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
2778
2779  if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
2780    {
2781      cp_error_at ("previous declaration `%D'", tmpl);
2782      error ("used %d template parameter%s instead of %d",
2783		TREE_VEC_LENGTH (tmpl_parms),
2784		TREE_VEC_LENGTH (tmpl_parms) == 1 ? "" : "s",
2785		TREE_VEC_LENGTH (parms));
2786      return;
2787    }
2788
2789  for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
2790    {
2791      tree tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
2792      tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
2793      tree tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
2794      tree parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
2795
2796      if (TREE_CODE (tmpl_parm) != TREE_CODE (parm))
2797	{
2798	  cp_error_at ("template parameter `%#D'", tmpl_parm);
2799	  error ("redeclared here as `%#D'", parm);
2800	  return;
2801	}
2802
2803      if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
2804	{
2805	  /* We have in [temp.param]:
2806
2807	     A template-parameter may not be given default arguments
2808	     by two different declarations in the same scope.  */
2809	  error ("redefinition of default argument for `%#D'", parm);
2810	  cp_error_at ("  original definition appeared here", tmpl_parm);
2811	  return;
2812	}
2813
2814      if (parm_default != NULL_TREE)
2815	/* Update the previous template parameters (which are the ones
2816	   that will really count) with the new default value.  */
2817	TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
2818      else if (tmpl_default != NULL_TREE)
2819	/* Update the new parameters, too; they'll be used as the
2820	   parameters for any members.  */
2821	TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
2822    }
2823}
2824
2825/* Attempt to convert the non-type template parameter EXPR to the
2826   indicated TYPE.  If the conversion is successful, return the
2827   converted value.  If the conversion is unsuccessful, return
2828   NULL_TREE if we issued an error message, or error_mark_node if we
2829   did not.  We issue error messages for out-and-out bad template
2830   parameters, but not simply because the conversion failed, since we
2831   might be just trying to do argument deduction.  By the time this
2832   function is called, neither TYPE nor EXPR may make use of template
2833   parameters.  */
2834
2835static tree
2836convert_nontype_argument (type, expr)
2837     tree type;
2838     tree expr;
2839{
2840  tree expr_type = TREE_TYPE (expr);
2841
2842  /* A template-argument for a non-type, non-template
2843     template-parameter shall be one of:
2844
2845     --an integral constant-expression of integral or enumeration
2846     type; or
2847
2848     --the name of a non-type template-parameter; or
2849
2850     --the name of an object or function with external linkage,
2851     including function templates and function template-ids but
2852     excluding non-static class members, expressed as id-expression;
2853     or
2854
2855     --the address of an object or function with external linkage,
2856     including function templates and function template-ids but
2857     excluding non-static class members, expressed as & id-expression
2858     where the & is optional if the name refers to a function or
2859     array; or
2860
2861     --a pointer to member expressed as described in _expr.unary.op_.  */
2862
2863  /* An integral constant-expression can include const variables or
2864     enumerators.  Simplify things by folding them to their values,
2865     unless we're about to bind the declaration to a reference
2866     parameter.  */
2867  if (INTEGRAL_TYPE_P (expr_type)
2868      && TREE_CODE (type) != REFERENCE_TYPE)
2869    expr = decl_constant_value (expr);
2870
2871  if (is_overloaded_fn (expr))
2872    /* OK for now.  We'll check that it has external linkage later.
2873       Check this first since if expr_type is the unknown_type_node
2874       we would otherwise complain below.  */
2875    ;
2876  else if (TYPE_PTRMEM_P (expr_type)
2877	   || TYPE_PTRMEMFUNC_P (expr_type))
2878    {
2879      if (TREE_CODE (expr) != PTRMEM_CST)
2880	goto bad_argument;
2881    }
2882  else if (TYPE_PTR_P (expr_type)
2883	   || TYPE_PTRMEM_P (expr_type)
2884	   || TREE_CODE (expr_type) == ARRAY_TYPE
2885	   || TREE_CODE (type) == REFERENCE_TYPE
2886	   /* If expr is the address of an overloaded function, we
2887	      will get the unknown_type_node at this point.  */
2888	   || expr_type == unknown_type_node)
2889    {
2890      tree referent;
2891      tree e = expr;
2892      STRIP_NOPS (e);
2893
2894      if (TREE_CODE (expr_type) == ARRAY_TYPE
2895	  || (TREE_CODE (type) == REFERENCE_TYPE
2896	      && TREE_CODE (e) != ADDR_EXPR))
2897	referent = e;
2898      else
2899	{
2900	  if (TREE_CODE (e) != ADDR_EXPR)
2901	    {
2902	    bad_argument:
2903	      error ("`%E' is not a valid template argument", expr);
2904	      if (TYPE_PTR_P (expr_type))
2905		{
2906		  if (TREE_CODE (TREE_TYPE (expr_type)) == FUNCTION_TYPE)
2907		    error ("it must be the address of a function with external linkage");
2908		  else
2909		    error ("it must be the address of an object with external linkage");
2910		}
2911	      else if (TYPE_PTRMEM_P (expr_type)
2912		       || TYPE_PTRMEMFUNC_P (expr_type))
2913		error ("it must be a pointer-to-member of the form `&X::Y'");
2914
2915	      return NULL_TREE;
2916	    }
2917
2918	  referent = TREE_OPERAND (e, 0);
2919	  STRIP_NOPS (referent);
2920	}
2921
2922      if (TREE_CODE (referent) == STRING_CST)
2923	{
2924	  error ("string literal %E is not a valid template argument because it is the address of an object with static linkage",
2925		    referent);
2926	  return NULL_TREE;
2927	}
2928
2929      if (is_overloaded_fn (referent))
2930	/* We'll check that it has external linkage later.  */
2931	;
2932      else if (TREE_CODE (referent) != VAR_DECL)
2933	goto bad_argument;
2934      else if (!DECL_EXTERNAL_LINKAGE_P (referent))
2935	{
2936	  error ("address of non-extern `%E' cannot be used as template argument", referent);
2937	  return error_mark_node;
2938	}
2939    }
2940  else if (INTEGRAL_TYPE_P (expr_type)
2941	   || TYPE_PTRMEM_P (expr_type)
2942	   || TYPE_PTRMEMFUNC_P (expr_type))
2943    {
2944      if (! TREE_CONSTANT (expr))
2945	{
2946	non_constant:
2947	  error ("non-constant `%E' cannot be used as template argument",
2948		    expr);
2949	  return NULL_TREE;
2950	}
2951    }
2952  else
2953    {
2954      error ("object `%E' cannot be used as template argument", expr);
2955      return NULL_TREE;
2956    }
2957
2958  switch (TREE_CODE (type))
2959    {
2960    case INTEGER_TYPE:
2961    case BOOLEAN_TYPE:
2962    case ENUMERAL_TYPE:
2963      /* For a non-type template-parameter of integral or enumeration
2964         type, integral promotions (_conv.prom_) and integral
2965         conversions (_conv.integral_) are applied. */
2966      if (!INTEGRAL_TYPE_P (expr_type))
2967	return error_mark_node;
2968
2969      /* It's safe to call digest_init in this case; we know we're
2970	 just converting one integral constant expression to another.  */
2971      expr = digest_init (type, expr, (tree*) 0);
2972
2973      if (TREE_CODE (expr) != INTEGER_CST)
2974	/* Curiously, some TREE_CONSTANT integral expressions do not
2975	   simplify to integer constants.  For example, `3 % 0',
2976	   remains a TRUNC_MOD_EXPR.  */
2977	goto non_constant;
2978
2979      return expr;
2980
2981    case POINTER_TYPE:
2982      {
2983	tree type_pointed_to = TREE_TYPE (type);
2984
2985	if (TYPE_PTRMEM_P (type))
2986	  {
2987	    tree e;
2988
2989	    /* For a non-type template-parameter of type pointer to data
2990	       member, qualification conversions (_conv.qual_) are
2991	       applied.  */
2992	    e = perform_qualification_conversions (type, expr);
2993	    if (TREE_CODE (e) == NOP_EXPR)
2994	      /* The call to perform_qualification_conversions will
2995		 insert a NOP_EXPR over EXPR to do express conversion,
2996		 if necessary.  But, that will confuse us if we use
2997		 this (converted) template parameter to instantiate
2998		 another template; then the thing will not look like a
2999		 valid template argument.  So, just make a new
3000		 constant, of the appropriate type.  */
3001	      e = make_ptrmem_cst (type, PTRMEM_CST_MEMBER (expr));
3002	    return e;
3003	  }
3004	else if (TREE_CODE (type_pointed_to) == FUNCTION_TYPE)
3005	  {
3006	    /* For a non-type template-parameter of type pointer to
3007	       function, only the function-to-pointer conversion
3008	       (_conv.func_) is applied.  If the template-argument
3009	       represents a set of overloaded functions (or a pointer to
3010	       such), the matching function is selected from the set
3011	       (_over.over_).  */
3012	    tree fns;
3013	    tree fn;
3014
3015	    if (TREE_CODE (expr) == ADDR_EXPR)
3016	      fns = TREE_OPERAND (expr, 0);
3017	    else
3018	      fns = expr;
3019
3020	    fn = instantiate_type (type_pointed_to, fns, tf_none);
3021
3022	    if (fn == error_mark_node)
3023	      return error_mark_node;
3024
3025	    if (!DECL_EXTERNAL_LINKAGE_P (fn))
3026	      {
3027		if (really_overloaded_fn (fns))
3028		  return error_mark_node;
3029		else
3030		  goto bad_argument;
3031	      }
3032
3033	    expr = build_unary_op (ADDR_EXPR, fn, 0);
3034
3035	    my_friendly_assert (same_type_p (type, TREE_TYPE (expr)),
3036				0);
3037	    return expr;
3038	  }
3039	else
3040	  {
3041	    /* For a non-type template-parameter of type pointer to
3042	       object, qualification conversions (_conv.qual_) and the
3043	       array-to-pointer conversion (_conv.array_) are applied.
3044	       [Note: In particular, neither the null pointer conversion
3045	       (_conv.ptr_) nor the derived-to-base conversion
3046	       (_conv.ptr_) are applied.  Although 0 is a valid
3047	       template-argument for a non-type template-parameter of
3048	       integral type, it is not a valid template-argument for a
3049	       non-type template-parameter of pointer type.]
3050
3051	       The call to decay_conversion performs the
3052	       array-to-pointer conversion, if appropriate.  */
3053	    expr = decay_conversion (expr);
3054
3055	    if (expr == error_mark_node)
3056	      return error_mark_node;
3057	    else
3058	      return perform_qualification_conversions (type, expr);
3059	  }
3060      }
3061      break;
3062
3063    case REFERENCE_TYPE:
3064      {
3065	tree type_referred_to = TREE_TYPE (type);
3066
3067	/* If this expression already has reference type, get the
3068	   underling object.  */
3069	if (TREE_CODE (expr_type) == REFERENCE_TYPE)
3070	  {
3071	    my_friendly_assert (TREE_CODE (expr) == ADDR_EXPR, 20000604);
3072	    expr = TREE_OPERAND (expr, 0);
3073	    expr_type = TREE_TYPE (expr);
3074	  }
3075
3076	if (TREE_CODE (type_referred_to) == FUNCTION_TYPE)
3077	  {
3078	    /* For a non-type template-parameter of type reference to
3079	       function, no conversions apply.  If the
3080	       template-argument represents a set of overloaded
3081	       functions, the matching function is selected from the
3082	       set (_over.over_).  */
3083	    tree fn;
3084
3085	    fn = instantiate_type (type_referred_to, expr, tf_none);
3086
3087	    if (fn == error_mark_node)
3088	      return error_mark_node;
3089
3090	    if (!DECL_EXTERNAL_LINKAGE_P (fn))
3091	      {
3092		if (really_overloaded_fn (expr))
3093		  /* Don't issue an error here; we might get a different
3094		     function if the overloading had worked out
3095		     differently.  */
3096		  return error_mark_node;
3097		else
3098		  goto bad_argument;
3099	      }
3100
3101	    my_friendly_assert (same_type_p (type_referred_to,
3102					     TREE_TYPE (fn)),
3103				0);
3104
3105	    expr = fn;
3106	  }
3107	else
3108	  {
3109	    /* For a non-type template-parameter of type reference to
3110	       object, no conversions apply.  The type referred to by the
3111	       reference may be more cv-qualified than the (otherwise
3112	       identical) type of the template-argument.  The
3113	       template-parameter is bound directly to the
3114	       template-argument, which must be an lvalue.  */
3115	    if (!same_type_p (TYPE_MAIN_VARIANT (expr_type),
3116			      TYPE_MAIN_VARIANT (type_referred_to))
3117		|| !at_least_as_qualified_p (type_referred_to,
3118					     expr_type)
3119		|| !real_lvalue_p (expr))
3120	      return error_mark_node;
3121	  }
3122
3123	mark_addressable (expr);
3124	return build1 (ADDR_EXPR, type, expr);
3125      }
3126      break;
3127
3128    case RECORD_TYPE:
3129      {
3130	my_friendly_assert (TYPE_PTRMEMFUNC_P (type), 20010112);
3131
3132	/* For a non-type template-parameter of type pointer to member
3133	   function, no conversions apply.  If the template-argument
3134	   represents a set of overloaded member functions, the
3135	   matching member function is selected from the set
3136	   (_over.over_).  */
3137
3138	if (!TYPE_PTRMEMFUNC_P (expr_type) &&
3139	    expr_type != unknown_type_node)
3140	  return error_mark_node;
3141
3142	if (TREE_CODE (expr) == PTRMEM_CST)
3143	  {
3144	    /* A ptr-to-member constant.  */
3145	    if (!same_type_p (type, expr_type))
3146	      return error_mark_node;
3147	    else
3148	      return expr;
3149	  }
3150
3151	if (TREE_CODE (expr) != ADDR_EXPR)
3152	  return error_mark_node;
3153
3154	expr = instantiate_type (type, expr, tf_none);
3155
3156	if (expr == error_mark_node)
3157	  return error_mark_node;
3158
3159	my_friendly_assert (same_type_p (type, TREE_TYPE (expr)),
3160			    0);
3161	return expr;
3162      }
3163      break;
3164
3165    default:
3166      /* All non-type parameters must have one of these types.  */
3167      abort ();
3168      break;
3169    }
3170
3171  return error_mark_node;
3172}
3173
3174/* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
3175   template template parameters.  Both PARM_PARMS and ARG_PARMS are
3176   vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
3177   or PARM_DECL.
3178
3179   ARG_PARMS may contain more parameters than PARM_PARMS.  If this is
3180   the case, then extra parameters must have default arguments.
3181
3182   Consider the example:
3183     template <class T, class Allocator = allocator> class vector;
3184     template<template <class U> class TT> class C;
3185
3186   C<vector> is a valid instantiation.  PARM_PARMS for the above code
3187   contains a TYPE_DECL (for U),  ARG_PARMS contains two TYPE_DECLs (for
3188   T and Allocator) and OUTER_ARGS contains the argument that is used to
3189   substitute the TT parameter.  */
3190
3191static int
3192coerce_template_template_parms (parm_parms, arg_parms, complain,
3193				in_decl, outer_args)
3194     tree parm_parms, arg_parms;
3195     tsubst_flags_t complain;
3196     tree in_decl, outer_args;
3197{
3198  int nparms, nargs, i;
3199  tree parm, arg;
3200
3201  my_friendly_assert (TREE_CODE (parm_parms) == TREE_VEC, 0);
3202  my_friendly_assert (TREE_CODE (arg_parms) == TREE_VEC, 0);
3203
3204  nparms = TREE_VEC_LENGTH (parm_parms);
3205  nargs = TREE_VEC_LENGTH (arg_parms);
3206
3207  /* The rule here is opposite of coerce_template_parms.  */
3208  if (nargs < nparms
3209      || (nargs > nparms
3210	  && TREE_PURPOSE (TREE_VEC_ELT (arg_parms, nparms)) == NULL_TREE))
3211    return 0;
3212
3213  for (i = 0; i < nparms; ++i)
3214    {
3215      parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
3216      arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
3217
3218      if (arg == NULL_TREE || arg == error_mark_node
3219          || parm == NULL_TREE || parm == error_mark_node)
3220	return 0;
3221
3222      if (TREE_CODE (arg) != TREE_CODE (parm))
3223        return 0;
3224
3225      switch (TREE_CODE (parm))
3226	{
3227	case TYPE_DECL:
3228	  break;
3229
3230	case TEMPLATE_DECL:
3231	  /* We encounter instantiations of templates like
3232	       template <template <template <class> class> class TT>
3233	       class C;  */
3234	  {
3235	    tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
3236	    tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
3237
3238	    if (!coerce_template_template_parms (parmparm, argparm,
3239					         complain, in_decl,
3240						 outer_args))
3241	      return 0;
3242	  }
3243	  break;
3244
3245	case PARM_DECL:
3246	  /* The tsubst call is used to handle cases such as
3247	       template <class T, template <T> class TT> class D;
3248	     i.e. the parameter list of TT depends on earlier parameters.  */
3249	  if (!same_type_p (tsubst (TREE_TYPE (parm), outer_args,
3250				    complain, in_decl),
3251			    TREE_TYPE (arg)))
3252	    return 0;
3253	  break;
3254
3255	default:
3256	  abort ();
3257	}
3258    }
3259  return 1;
3260}
3261
3262/* Convert the indicated template ARG as necessary to match the
3263   indicated template PARM.  Returns the converted ARG, or
3264   error_mark_node if the conversion was unsuccessful.  Error and
3265   warning messages are issued under control of COMPLAIN.  This
3266   conversion is for the Ith parameter in the parameter list.  ARGS is
3267   the full set of template arguments deduced so far.  */
3268
3269static tree
3270convert_template_argument (parm, arg, args, complain, i, in_decl)
3271     tree parm;
3272     tree arg;
3273     tree args;
3274     tsubst_flags_t complain;
3275     int i;
3276     tree in_decl;
3277{
3278  tree val;
3279  tree inner_args;
3280  int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
3281
3282  inner_args = INNERMOST_TEMPLATE_ARGS (args);
3283
3284  if (TREE_CODE (arg) == TREE_LIST
3285      && TREE_TYPE (arg) != NULL_TREE
3286      && TREE_CODE (TREE_TYPE (arg)) == OFFSET_TYPE)
3287    {
3288      /* The template argument was the name of some
3289	 member function.  That's usually
3290	 illegal, but static members are OK.  In any
3291	 case, grab the underlying fields/functions
3292	 and issue an error later if required.  */
3293      arg = TREE_VALUE (arg);
3294      TREE_TYPE (arg) = unknown_type_node;
3295    }
3296
3297  requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
3298  requires_type = (TREE_CODE (parm) == TYPE_DECL
3299		   || requires_tmpl_type);
3300
3301  if (TREE_CODE (arg) != RECORD_TYPE)
3302    is_tmpl_type = ((TREE_CODE (arg) == TEMPLATE_DECL
3303		     && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
3304		    || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
3305		    || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
3306  else if (CLASSTYPE_TEMPLATE_INFO (arg) && !CLASSTYPE_USE_TEMPLATE (arg)
3307	   && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (arg)))
3308    {
3309      if (is_base_of_enclosing_class (arg, current_class_type))
3310	/* This is a template name used within the scope of the
3311	   template. It could be the template, or it could be the
3312	   instantiation. Choose whichever makes sense.  */
3313	is_tmpl_type = requires_tmpl_type;
3314      else
3315	is_tmpl_type = 1;
3316    }
3317  else
3318    /* It is a non-template class, or a specialization of a template
3319       class, or a non-template member of a template class.  */
3320    is_tmpl_type = 0;
3321
3322  if (is_tmpl_type
3323      && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
3324	  || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
3325    arg = TYPE_STUB_DECL (arg);
3326  else if (is_tmpl_type && TREE_CODE (arg) == RECORD_TYPE)
3327    arg = CLASSTYPE_TI_TEMPLATE (arg);
3328
3329  is_type = TYPE_P (arg) || is_tmpl_type;
3330
3331  if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
3332      && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
3333    {
3334      pedwarn ("to refer to a type member of a template parameter, use `typename %E'", arg);
3335
3336      arg = make_typename_type (TREE_OPERAND (arg, 0),
3337				TREE_OPERAND (arg, 1),
3338				complain & tf_error);
3339      is_type = 1;
3340    }
3341  if (is_type != requires_type)
3342    {
3343      if (in_decl)
3344	{
3345	  if (complain & tf_error)
3346	    {
3347	      error ("type/value mismatch at argument %d in template parameter list for `%D'",
3348			i + 1, in_decl);
3349	      if (is_type)
3350		error ("  expected a constant of type `%T', got `%T'",
3351			  TREE_TYPE (parm),
3352			  (is_tmpl_type ? DECL_NAME (arg) : arg));
3353	      else
3354		error ("  expected a type, got `%E'", arg);
3355	    }
3356	}
3357      return error_mark_node;
3358    }
3359  if (is_tmpl_type ^ requires_tmpl_type)
3360    {
3361      if (in_decl && (complain & tf_error))
3362	{
3363	  error ("type/value mismatch at argument %d in template parameter list for `%D'",
3364		    i + 1, in_decl);
3365	  if (is_tmpl_type)
3366	    error ("  expected a type, got `%T'", DECL_NAME (arg));
3367	  else
3368	    error ("  expected a class template, got `%T'", arg);
3369	}
3370      return error_mark_node;
3371    }
3372
3373  if (is_type)
3374    {
3375      if (requires_tmpl_type)
3376	{
3377	  if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
3378	    /* The number of argument required is not known yet.
3379	       Just accept it for now.  */
3380	    val = TREE_TYPE (arg);
3381	  else
3382	    {
3383	      tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
3384	      tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
3385
3386	      if (coerce_template_template_parms (parmparm, argparm,
3387						  complain, in_decl,
3388						  inner_args))
3389		{
3390		  val = arg;
3391
3392		  /* TEMPLATE_TEMPLATE_PARM node is preferred over
3393		     TEMPLATE_DECL.  */
3394		  if (val != error_mark_node
3395		      && DECL_TEMPLATE_TEMPLATE_PARM_P (val))
3396		    val = TREE_TYPE (val);
3397		}
3398	      else
3399		{
3400		  if (in_decl && (complain & tf_error))
3401		    {
3402		      error ("type/value mismatch at argument %d in template parameter list for `%D'",
3403				i + 1, in_decl);
3404		      error ("  expected a template of type `%D', got `%D'", parm, arg);
3405		    }
3406
3407		  val = error_mark_node;
3408		}
3409	    }
3410	}
3411      else
3412	{
3413	  val = groktypename (arg);
3414	  if (! processing_template_decl)
3415	    {
3416	      /* [basic.link]: A name with no linkage (notably, the
3417		 name of a class or enumeration declared in a local
3418		 scope) shall not be used to declare an entity with
3419		 linkage.  This implies that names with no linkage
3420		 cannot be used as template arguments.  */
3421	      tree t = no_linkage_check (val);
3422	      if (t)
3423		{
3424		  if (TYPE_ANONYMOUS_P (t))
3425		    pedwarn
3426		      ("template-argument `%T' uses anonymous type", val);
3427		  else
3428		    error
3429		      ("template-argument `%T' uses local type `%T'",
3430		       val, t);
3431		  return error_mark_node;
3432		}
3433
3434	      /* In order to avoid all sorts of complications, we do
3435		 not allow variably-modified types as template
3436		 arguments.  */
3437	      if (variably_modified_type_p (val))
3438		{
3439		  error ("template-argument `%T' is a variably modified type",
3440			 val);
3441		  return error_mark_node;
3442		}
3443	    }
3444	}
3445    }
3446  else
3447    {
3448      tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
3449
3450      if (invalid_nontype_parm_type_p (t, complain))
3451        return error_mark_node;
3452
3453      if (processing_template_decl)
3454	arg = maybe_fold_nontype_arg (arg);
3455
3456      if (!uses_template_parms (arg) && !uses_template_parms (t))
3457	/* We used to call digest_init here.  However, digest_init
3458	   will report errors, which we don't want when complain
3459	   is zero.  More importantly, digest_init will try too
3460	   hard to convert things: for example, `0' should not be
3461	   converted to pointer type at this point according to
3462	   the standard.  Accepting this is not merely an
3463	   extension, since deciding whether or not these
3464	   conversions can occur is part of determining which
3465	   function template to call, or whether a given explicit
3466	   argument specification is legal.  */
3467	val = convert_nontype_argument (t, arg);
3468      else
3469	val = arg;
3470
3471      if (val == NULL_TREE)
3472	val = error_mark_node;
3473      else if (val == error_mark_node && (complain & tf_error))
3474	error ("could not convert template argument `%E' to `%T'",
3475		  arg, t);
3476    }
3477
3478  return val;
3479}
3480
3481/* Convert all template arguments to their appropriate types, and
3482   return a vector containing the innermost resulting template
3483   arguments.  If any error occurs, return error_mark_node. Error and
3484   warning messages are issued under control of COMPLAIN.  Some error
3485   messages are issued even if COMPLAIN is zero; for instance, if a
3486   template argument is composed from a local class.
3487
3488   If REQUIRE_ALL_ARGUMENTS is non-zero, all arguments must be
3489   provided in ARGLIST, or else trailing parameters must have default
3490   values.  If REQUIRE_ALL_ARGUMENTS is zero, we will attempt argument
3491   deduction for any unspecified trailing arguments.  */
3492
3493static tree
3494coerce_template_parms (parms, args, in_decl,
3495		       complain,
3496		       require_all_arguments)
3497     tree parms, args;
3498     tree in_decl;
3499     tsubst_flags_t complain;
3500     int require_all_arguments;
3501{
3502  int nparms, nargs, i, lost = 0;
3503  tree inner_args;
3504  tree new_args;
3505  tree new_inner_args;
3506
3507  inner_args = INNERMOST_TEMPLATE_ARGS (args);
3508  nargs = NUM_TMPL_ARGS (inner_args);
3509  nparms = TREE_VEC_LENGTH (parms);
3510
3511  if (nargs > nparms
3512      || (nargs < nparms
3513	  && require_all_arguments
3514	  && TREE_PURPOSE (TREE_VEC_ELT (parms, nargs)) == NULL_TREE))
3515    {
3516      if (complain & tf_error)
3517	{
3518	  error ("wrong number of template arguments (%d, should be %d)",
3519		    nargs, nparms);
3520
3521	  if (in_decl)
3522	    cp_error_at ("provided for `%D'", in_decl);
3523	}
3524
3525      return error_mark_node;
3526    }
3527
3528  new_inner_args = make_tree_vec (nparms);
3529  new_args = add_outermost_template_args (args, new_inner_args);
3530  for (i = 0; i < nparms; i++)
3531    {
3532      tree arg;
3533      tree parm;
3534
3535      /* Get the Ith template parameter.  */
3536      parm = TREE_VEC_ELT (parms, i);
3537
3538      /* Calculate the Ith argument.  */
3539      if (inner_args && TREE_CODE (inner_args) == TREE_LIST)
3540	{
3541	  arg = TREE_VALUE (inner_args);
3542	  inner_args = TREE_CHAIN (inner_args);
3543	}
3544      else if (i < nargs)
3545	arg = TREE_VEC_ELT (inner_args, i);
3546      /* If no template argument was supplied, look for a default
3547	 value.  */
3548      else if (TREE_PURPOSE (parm) == NULL_TREE)
3549	{
3550	  /* There was no default value.  */
3551	  my_friendly_assert (!require_all_arguments, 0);
3552	  break;
3553	}
3554      else if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL)
3555	arg = tsubst (TREE_PURPOSE (parm), new_args, complain, in_decl);
3556      else
3557	arg = tsubst_expr (TREE_PURPOSE (parm), new_args, complain,
3558			   in_decl);
3559
3560      /* Now, convert the Ith argument, as necessary.  */
3561      if (arg == NULL_TREE)
3562	/* We're out of arguments.  */
3563	{
3564	  my_friendly_assert (!require_all_arguments, 0);
3565	  break;
3566	}
3567      else if (arg == error_mark_node)
3568	{
3569	  error ("template argument %d is invalid", i + 1);
3570	  arg = error_mark_node;
3571	}
3572      else
3573	arg = convert_template_argument (TREE_VALUE (parm),
3574					 arg, new_args, complain, i,
3575					 in_decl);
3576
3577      if (arg == error_mark_node)
3578	lost++;
3579      TREE_VEC_ELT (new_inner_args, i) = arg;
3580    }
3581
3582  if (lost)
3583    return error_mark_node;
3584
3585  return new_inner_args;
3586}
3587
3588/* Returns 1 if template args OT and NT are equivalent.  */
3589
3590static int
3591template_args_equal (ot, nt)
3592     tree ot, nt;
3593{
3594  if (nt == ot)
3595    return 1;
3596
3597  if (TREE_CODE (nt) == TREE_VEC)
3598    /* For member templates */
3599    return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
3600  else if (TYPE_P (nt))
3601    return TYPE_P (ot) && same_type_p (ot, nt);
3602  else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
3603    return 0;
3604  else
3605    return (cp_tree_equal (ot, nt) > 0);
3606}
3607
3608/* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
3609   of template arguments.  Returns 0 otherwise.  */
3610
3611int
3612comp_template_args (oldargs, newargs)
3613     tree oldargs, newargs;
3614{
3615  int i;
3616
3617  if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
3618    return 0;
3619
3620  for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
3621    {
3622      tree nt = TREE_VEC_ELT (newargs, i);
3623      tree ot = TREE_VEC_ELT (oldargs, i);
3624
3625      if (! template_args_equal (ot, nt))
3626	return 0;
3627    }
3628  return 1;
3629}
3630
3631/* Given class template name and parameter list, produce a user-friendly name
3632   for the instantiation.  */
3633
3634static char *
3635mangle_class_name_for_template (name, parms, arglist)
3636     const char *name;
3637     tree parms, arglist;
3638{
3639  static struct obstack scratch_obstack;
3640  static char *scratch_firstobj;
3641  int i, nparms;
3642
3643  if (!scratch_firstobj)
3644    gcc_obstack_init (&scratch_obstack);
3645  else
3646    obstack_free (&scratch_obstack, scratch_firstobj);
3647  scratch_firstobj = obstack_alloc (&scratch_obstack, 1);
3648
3649#define ccat(C)	obstack_1grow (&scratch_obstack, (C));
3650#define cat(S)	obstack_grow (&scratch_obstack, (S), strlen (S))
3651
3652  cat (name);
3653  ccat ('<');
3654  nparms = TREE_VEC_LENGTH (parms);
3655  arglist = INNERMOST_TEMPLATE_ARGS (arglist);
3656  my_friendly_assert (nparms == TREE_VEC_LENGTH (arglist), 268);
3657  for (i = 0; i < nparms; i++)
3658    {
3659      tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
3660      tree arg = TREE_VEC_ELT (arglist, i);
3661
3662      if (i)
3663	ccat (',');
3664
3665      if (TREE_CODE (parm) == TYPE_DECL)
3666	{
3667	  cat (type_as_string (arg, TFF_CHASE_TYPEDEF));
3668	  continue;
3669	}
3670      else if (TREE_CODE (parm) == TEMPLATE_DECL)
3671	{
3672	  if (TREE_CODE (arg) == TEMPLATE_DECL)
3673	    {
3674	      /* Already substituted with real template.  Just output
3675		 the template name here */
3676              tree context = DECL_CONTEXT (arg);
3677              if (context)
3678                {
3679                  /* The template may be defined in a namespace, or
3680                     may be a member template.  */
3681                  my_friendly_assert (TREE_CODE (context) == NAMESPACE_DECL
3682                                      || CLASS_TYPE_P (context),
3683                                      980422);
3684		  cat(decl_as_string (DECL_CONTEXT (arg), TFF_PLAIN_IDENTIFIER));
3685		  cat("::");
3686		}
3687	      cat (IDENTIFIER_POINTER (DECL_NAME (arg)));
3688	    }
3689	  else
3690	    /* Output the parameter declaration */
3691	    cat (type_as_string (arg, TFF_CHASE_TYPEDEF));
3692	  continue;
3693	}
3694      else
3695	my_friendly_assert (TREE_CODE (parm) == PARM_DECL, 269);
3696
3697      if (TREE_CODE (arg) == TREE_LIST)
3698	{
3699	  /* New list cell was built because old chain link was in
3700	     use.  */
3701	  my_friendly_assert (TREE_PURPOSE (arg) == NULL_TREE, 270);
3702	  arg = TREE_VALUE (arg);
3703	}
3704      /* No need to check arglist against parmlist here; we did that
3705	 in coerce_template_parms, called from lookup_template_class.  */
3706      cat (expr_as_string (arg, TFF_PLAIN_IDENTIFIER));
3707    }
3708  {
3709    char *bufp = obstack_next_free (&scratch_obstack);
3710    int offset = 0;
3711    while (bufp[offset - 1] == ' ')
3712      offset--;
3713    obstack_blank_fast (&scratch_obstack, offset);
3714
3715    /* B<C<char> >, not B<C<char>> */
3716    if (bufp[offset - 1] == '>')
3717      ccat (' ');
3718  }
3719  ccat ('>');
3720  ccat ('\0');
3721  return (char *) obstack_base (&scratch_obstack);
3722}
3723
3724static tree
3725classtype_mangled_name (t)
3726     tree t;
3727{
3728  if (CLASSTYPE_TEMPLATE_INFO (t)
3729      /* Specializations have already had their names set up in
3730	 lookup_template_class.  */
3731      && !CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
3732    {
3733      tree tmpl = most_general_template (CLASSTYPE_TI_TEMPLATE (t));
3734
3735      /* For non-primary templates, the template parameters are
3736	 implicit from their surrounding context.  */
3737      if (PRIMARY_TEMPLATE_P (tmpl))
3738	{
3739	  tree name = DECL_NAME (tmpl);
3740	  char *mangled_name = mangle_class_name_for_template
3741	    (IDENTIFIER_POINTER (name),
3742	     DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
3743	     CLASSTYPE_TI_ARGS (t));
3744	  tree id = get_identifier (mangled_name);
3745	  IDENTIFIER_TEMPLATE (id) = name;
3746	  return id;
3747	}
3748    }
3749
3750  return TYPE_IDENTIFIER (t);
3751}
3752
3753static void
3754add_pending_template (d)
3755     tree d;
3756{
3757  tree ti = (TYPE_P (d)
3758	     ? CLASSTYPE_TEMPLATE_INFO (d)
3759	     : DECL_TEMPLATE_INFO (d));
3760  tree pt;
3761  int level;
3762
3763  if (TI_PENDING_TEMPLATE_FLAG (ti))
3764    return;
3765
3766  /* We are called both from instantiate_decl, where we've already had a
3767     tinst_level pushed, and instantiate_template, where we haven't.
3768     Compensate.  */
3769  level = !(current_tinst_level && TINST_DECL (current_tinst_level) == d);
3770
3771  if (level)
3772    push_tinst_level (d);
3773
3774  pt = tree_cons (current_tinst_level, d, NULL_TREE);
3775  if (last_pending_template)
3776    TREE_CHAIN (last_pending_template) = pt;
3777  else
3778    pending_templates = pt;
3779
3780  last_pending_template = pt;
3781
3782  TI_PENDING_TEMPLATE_FLAG (ti) = 1;
3783
3784  if (level)
3785    pop_tinst_level ();
3786}
3787
3788
3789/* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS (which
3790   may be either a _DECL or an overloaded function or an
3791   IDENTIFIER_NODE), and ARGLIST.  */
3792
3793tree
3794lookup_template_function (fns, arglist)
3795     tree fns, arglist;
3796{
3797  tree type;
3798
3799  if (fns == NULL_TREE)
3800    {
3801      error ("non-template used as template");
3802      return error_mark_node;
3803    }
3804
3805  type = TREE_TYPE (fns);
3806  if (TREE_CODE (fns) == OVERLOAD || !type)
3807    type = unknown_type_node;
3808
3809  if (processing_template_decl)
3810    return build_min (TEMPLATE_ID_EXPR, type, fns, arglist);
3811  else
3812    return build (TEMPLATE_ID_EXPR, type, fns, arglist);
3813}
3814
3815/* Within the scope of a template class S<T>, the name S gets bound
3816   (in build_self_reference) to a TYPE_DECL for the class, not a
3817   TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
3818   or one of its enclosing classes, and that type is a template,
3819   return the associated TEMPLATE_DECL.  Otherwise, the original
3820   DECL is returned.  */
3821
3822static tree
3823maybe_get_template_decl_from_type_decl (decl)
3824     tree decl;
3825{
3826  return (decl != NULL_TREE
3827	  && TREE_CODE (decl) == TYPE_DECL
3828	  && DECL_ARTIFICIAL (decl)
3829	  && CLASS_TYPE_P (TREE_TYPE (decl))
3830	  && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
3831    ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
3832}
3833
3834/* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
3835   parameters, find the desired type.
3836
3837   D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
3838   (Actually ARGLIST may be either a TREE_LIST or a TREE_VEC.  It will
3839   be a TREE_LIST if called directly from the parser, and a TREE_VEC
3840   otherwise.)
3841
3842   IN_DECL, if non-NULL, is the template declaration we are trying to
3843   instantiate.
3844
3845   If ENTERING_SCOPE is non-zero, we are about to enter the scope of
3846   the class we are looking up.
3847
3848   Issue error and warning messages under control of COMPLAIN.
3849
3850   If the template class is really a local class in a template
3851   function, then the FUNCTION_CONTEXT is the function in which it is
3852   being instantiated.  */
3853
3854tree
3855lookup_template_class (d1, arglist, in_decl, context, entering_scope, complain)
3856     tree d1, arglist;
3857     tree in_decl;
3858     tree context;
3859     int entering_scope;
3860     tsubst_flags_t complain;
3861{
3862  tree template = NULL_TREE, parmlist;
3863  tree t;
3864
3865  if (TREE_CODE (d1) == IDENTIFIER_NODE)
3866    {
3867      if (IDENTIFIER_VALUE (d1)
3868	  && DECL_TEMPLATE_TEMPLATE_PARM_P (IDENTIFIER_VALUE (d1)))
3869	template = IDENTIFIER_VALUE (d1);
3870      else
3871	{
3872	  if (context)
3873	    push_decl_namespace (context);
3874	  template = lookup_name (d1, /*prefer_type=*/0);
3875	  template = maybe_get_template_decl_from_type_decl (template);
3876	  if (context)
3877	    pop_decl_namespace ();
3878	}
3879      if (template)
3880	context = DECL_CONTEXT (template);
3881    }
3882  else if (TREE_CODE (d1) == TYPE_DECL && IS_AGGR_TYPE (TREE_TYPE (d1)))
3883    {
3884      tree type = TREE_TYPE (d1);
3885
3886      /* If we are declaring a constructor, say A<T>::A<T>, we will get
3887	 an implicit typename for the second A.  Deal with it.  */
3888      if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
3889	type = TREE_TYPE (type);
3890
3891      if (CLASSTYPE_TEMPLATE_INFO (type))
3892	{
3893	  template = CLASSTYPE_TI_TEMPLATE (type);
3894	  d1 = DECL_NAME (template);
3895	}
3896    }
3897  else if (TREE_CODE (d1) == ENUMERAL_TYPE
3898	   || (TYPE_P (d1) && IS_AGGR_TYPE (d1)))
3899    {
3900      template = TYPE_TI_TEMPLATE (d1);
3901      d1 = DECL_NAME (template);
3902    }
3903  else if (TREE_CODE (d1) == TEMPLATE_DECL
3904	   && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
3905    {
3906      template = d1;
3907      d1 = DECL_NAME (template);
3908      context = DECL_CONTEXT (template);
3909    }
3910
3911  /* With something like `template <class T> class X class X { ... };'
3912     we could end up with D1 having nothing but an IDENTIFIER_VALUE.
3913     We don't want to do that, but we have to deal with the situation,
3914     so let's give them some syntax errors to chew on instead of a
3915     crash. Alternatively D1 might not be a template type at all.  */
3916  if (! template)
3917    {
3918      if (complain & tf_error)
3919        error ("`%T' is not a template", d1);
3920      return error_mark_node;
3921    }
3922
3923  if (TREE_CODE (template) != TEMPLATE_DECL
3924         /* If we're called from the parser, make sure it's a user visible
3925            template.  */
3926      || ((!arglist || TREE_CODE (arglist) == TREE_LIST)
3927          && !DECL_TEMPLATE_PARM_P (template)
3928          && !PRIMARY_TEMPLATE_P (template)))
3929    {
3930      if (complain & tf_error)
3931        {
3932          error ("non-template type `%T' used as a template", d1);
3933          if (in_decl)
3934	    cp_error_at ("for template declaration `%D'", in_decl);
3935	}
3936      return error_mark_node;
3937    }
3938
3939  if (DECL_TEMPLATE_TEMPLATE_PARM_P (template))
3940    {
3941      /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
3942         template arguments */
3943
3944      tree parm;
3945      tree arglist2;
3946
3947      parmlist = DECL_INNERMOST_TEMPLATE_PARMS (template);
3948
3949      /* Consider an example where a template template parameter declared as
3950
3951	   template <class T, class U = std::allocator<T> > class TT
3952
3953	 The template parameter level of T and U are one level larger than
3954	 of TT.  To proper process the default argument of U, say when an
3955	 instantiation `TT<int>' is seen, we need to build the full
3956	 arguments containing {int} as the innermost level.  Outer levels,
3957	 available when not appearing as default template argument, can be
3958	 obtained from `current_template_args ()'.
3959
3960	 Suppose that TT is later substituted with std::vector.  The above
3961	 instantiation is `TT<int, std::allocator<T> >' with TT at
3962	 level 1, and T at level 2, while the template arguments at level 1
3963	 becomes {std::vector} and the inner level 2 is {int}.  */
3964
3965      if (current_template_parms)
3966	arglist = add_to_template_args (current_template_args (), arglist);
3967
3968      arglist2 = coerce_template_parms (parmlist, arglist, template,
3969                                        complain, /*require_all_args=*/1);
3970      if (arglist2 == error_mark_node)
3971	return error_mark_node;
3972
3973      parm = bind_template_template_parm (TREE_TYPE (template), arglist2);
3974      return parm;
3975    }
3976  else
3977    {
3978      tree template_type = TREE_TYPE (template);
3979      tree gen_tmpl;
3980      tree type_decl;
3981      tree found = NULL_TREE;
3982      tree *tp;
3983      int arg_depth;
3984      int parm_depth;
3985      int is_partial_instantiation;
3986
3987      gen_tmpl = most_general_template (template);
3988      parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
3989      parm_depth = TMPL_PARMS_DEPTH (parmlist);
3990      arg_depth = TMPL_ARGS_DEPTH (arglist);
3991
3992      if (arg_depth == 1 && parm_depth > 1)
3993	{
3994	  /* We've been given an incomplete set of template arguments.
3995	     For example, given:
3996
3997	       template <class T> struct S1 {
3998	         template <class U> struct S2 {};
3999		 template <class U> struct S2<U*> {};
4000	        };
4001
4002	     we will be called with an ARGLIST of `U*', but the
4003	     TEMPLATE will be `template <class T> template
4004	     <class U> struct S1<T>::S2'.  We must fill in the missing
4005	     arguments.  */
4006	  arglist
4007	    = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (template)),
4008					   arglist);
4009	  arg_depth = TMPL_ARGS_DEPTH (arglist);
4010	}
4011
4012      /* Now we should have enough arguments.  */
4013      my_friendly_assert (parm_depth == arg_depth, 0);
4014
4015      /* From here on, we're only interested in the most general
4016	 template.  */
4017      template = gen_tmpl;
4018
4019      /* Calculate the BOUND_ARGS.  These will be the args that are
4020	 actually tsubst'd into the definition to create the
4021	 instantiation.  */
4022      if (parm_depth > 1)
4023	{
4024	  /* We have multiple levels of arguments to coerce, at once.  */
4025	  int i;
4026	  int saved_depth = TMPL_ARGS_DEPTH (arglist);
4027
4028	  tree bound_args = make_tree_vec (parm_depth);
4029
4030	  for (i = saved_depth,
4031		 t = DECL_TEMPLATE_PARMS (template);
4032	       i > 0 && t != NULL_TREE;
4033	       --i, t = TREE_CHAIN (t))
4034	    {
4035	      tree a = coerce_template_parms (TREE_VALUE (t),
4036					      arglist, template,
4037	                                      complain, /*require_all_args=*/1);
4038	      SET_TMPL_ARGS_LEVEL (bound_args, i, a);
4039
4040	      /* We temporarily reduce the length of the ARGLIST so
4041		 that coerce_template_parms will see only the arguments
4042		 corresponding to the template parameters it is
4043		 examining.  */
4044	      TREE_VEC_LENGTH (arglist)--;
4045	    }
4046
4047	  /* Restore the ARGLIST to its full size.  */
4048	  TREE_VEC_LENGTH (arglist) = saved_depth;
4049
4050	  arglist = bound_args;
4051	}
4052      else
4053	arglist
4054	  = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
4055				   INNERMOST_TEMPLATE_ARGS (arglist),
4056				   template,
4057	                           complain, /*require_all_args=*/1);
4058
4059      if (arglist == error_mark_node)
4060	/* We were unable to bind the arguments.  */
4061	return error_mark_node;
4062
4063      /* In the scope of a template class, explicit references to the
4064	 template class refer to the type of the template, not any
4065	 instantiation of it.  For example, in:
4066
4067	   template <class T> class C { void f(C<T>); }
4068
4069	 the `C<T>' is just the same as `C'.  Outside of the
4070	 class, however, such a reference is an instantiation.  */
4071      if (comp_template_args (TYPE_TI_ARGS (template_type),
4072			      arglist))
4073	{
4074	  found = template_type;
4075
4076	  if (!entering_scope && PRIMARY_TEMPLATE_P (template))
4077	    {
4078	      tree ctx;
4079
4080	      /* Note that we use DECL_CONTEXT, rather than
4081		 CP_DECL_CONTEXT, so that the termination test is
4082		 always just `ctx'.  We're not interested in namespace
4083		 scopes.  */
4084	      for (ctx = current_class_type;
4085		   ctx;
4086		   ctx = (TYPE_P (ctx)) ? TYPE_CONTEXT (ctx) : DECL_CONTEXT (ctx))
4087		if (same_type_p (ctx, template_type))
4088		  break;
4089
4090	      if (!ctx)
4091		/* We're not in the scope of the class, so the
4092		   TEMPLATE_TYPE is not the type we want after
4093		   all.  */
4094		found = NULL_TREE;
4095	    }
4096	}
4097      if (found)
4098        return found;
4099
4100      for (tp = &DECL_TEMPLATE_INSTANTIATIONS (template);
4101	   *tp;
4102	   tp = &TREE_CHAIN (*tp))
4103	if (comp_template_args (TREE_PURPOSE (*tp), arglist))
4104	  {
4105	    found = *tp;
4106
4107	    /* Use the move-to-front heuristic to speed up future
4108	       searches.  */
4109	    *tp = TREE_CHAIN (*tp);
4110	    TREE_CHAIN (found)
4111	      = DECL_TEMPLATE_INSTANTIATIONS (template);
4112	    DECL_TEMPLATE_INSTANTIATIONS (template) = found;
4113
4114	    return TREE_VALUE (found);
4115	  }
4116
4117      /* This type is a "partial instantiation" if any of the template
4118	 arguments still involve template parameters.  Note that we set
4119	 IS_PARTIAL_INSTANTIATION for partial specializations as
4120	 well.  */
4121      is_partial_instantiation = uses_template_parms (arglist);
4122
4123      if (!is_partial_instantiation
4124	  && !PRIMARY_TEMPLATE_P (template)
4125	  && TREE_CODE (CP_DECL_CONTEXT (template)) == NAMESPACE_DECL)
4126	{
4127	  found = xref_tag_from_type (TREE_TYPE (template),
4128				      DECL_NAME (template),
4129				      /*globalize=*/1);
4130	  return found;
4131	}
4132
4133      context = tsubst (DECL_CONTEXT (template), arglist,
4134			complain, in_decl);
4135      if (!context)
4136	context = global_namespace;
4137
4138      /* Create the type.  */
4139      if (TREE_CODE (template_type) == ENUMERAL_TYPE)
4140	{
4141	  if (!is_partial_instantiation)
4142	    {
4143	      set_current_access_from_decl (TYPE_NAME (template_type));
4144	      t = start_enum (TYPE_IDENTIFIER (template_type));
4145	    }
4146	  else
4147	    /* We don't want to call start_enum for this type, since
4148	       the values for the enumeration constants may involve
4149	       template parameters.  And, no one should be interested
4150	       in the enumeration constants for such a type.  */
4151	    t = make_node (ENUMERAL_TYPE);
4152	}
4153      else
4154	{
4155	  t = make_aggr_type (TREE_CODE (template_type));
4156	  CLASSTYPE_DECLARED_CLASS (t)
4157	    = CLASSTYPE_DECLARED_CLASS (template_type);
4158	  CLASSTYPE_GOT_SEMICOLON (t) = 1;
4159	  SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
4160	  TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
4161
4162	  /* A local class.  Make sure the decl gets registered properly.  */
4163	  if (context == current_function_decl)
4164	    pushtag (DECL_NAME (template), t, 0);
4165	}
4166
4167      /* If we called start_enum or pushtag above, this information
4168	 will already be set up.  */
4169      if (!TYPE_NAME (t))
4170	{
4171	  TYPE_CONTEXT (t) = FROB_CONTEXT (context);
4172
4173	  type_decl = create_implicit_typedef (DECL_NAME (template), t);
4174	  DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
4175	  TYPE_STUB_DECL (t) = type_decl;
4176	  DECL_SOURCE_FILE (type_decl)
4177	    = DECL_SOURCE_FILE (TYPE_STUB_DECL (template_type));
4178	  DECL_SOURCE_LINE (type_decl)
4179	    = DECL_SOURCE_LINE (TYPE_STUB_DECL (template_type));
4180	}
4181      else
4182	type_decl = TYPE_NAME (t);
4183
4184      /* Set up the template information.  We have to figure out which
4185	 template is the immediate parent if this is a full
4186	 instantiation.  */
4187      if (parm_depth == 1 || is_partial_instantiation
4188	  || !PRIMARY_TEMPLATE_P (template))
4189	/* This case is easy; there are no member templates involved.  */
4190	found = template;
4191      else
4192	{
4193	  /* This is a full instantiation of a member template.  Look
4194	     for a partial instantiation of which this is an instance.  */
4195
4196	  for (found = DECL_TEMPLATE_INSTANTIATIONS (template);
4197	       found; found = TREE_CHAIN (found))
4198	    {
4199	      int success;
4200	      tree tmpl = CLASSTYPE_TI_TEMPLATE (TREE_VALUE (found));
4201
4202	      /* We only want partial instantiations, here, not
4203		 specializations or full instantiations.  */
4204	      if (CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_VALUE (found))
4205		  || !uses_template_parms (TREE_VALUE (found)))
4206		continue;
4207
4208	      /* Temporarily reduce by one the number of levels in the
4209		 ARGLIST and in FOUND so as to avoid comparing the
4210		 last set of arguments.  */
4211	      TREE_VEC_LENGTH (arglist)--;
4212	      TREE_VEC_LENGTH (TREE_PURPOSE (found)) --;
4213
4214	      /* See if the arguments match.  If they do, then TMPL is
4215		 the partial instantiation we want.  */
4216	      success = comp_template_args (TREE_PURPOSE (found), arglist);
4217
4218	      /* Restore the argument vectors to their full size.  */
4219	      TREE_VEC_LENGTH (arglist)++;
4220	      TREE_VEC_LENGTH (TREE_PURPOSE (found))++;
4221
4222	      if (success)
4223		{
4224		  found = tmpl;
4225		  break;
4226		}
4227	    }
4228
4229	  if (!found)
4230	    {
4231	      /* There was no partial instantiation. This happens
4232                 where C<T> is a member template of A<T> and it's used
4233                 in something like
4234
4235                  template <typename T> struct B { A<T>::C<int> m; };
4236                  B<float>;
4237
4238                 Create the partial instantiation.
4239               */
4240              TREE_VEC_LENGTH (arglist)--;
4241              found = tsubst (template, arglist, complain, NULL_TREE);
4242              TREE_VEC_LENGTH (arglist)++;
4243            }
4244	}
4245
4246      SET_TYPE_TEMPLATE_INFO (t, tree_cons (found, arglist, NULL_TREE));
4247      DECL_TEMPLATE_INSTANTIATIONS (template)
4248	= tree_cons (arglist, t,
4249		     DECL_TEMPLATE_INSTANTIATIONS (template));
4250
4251      if (TREE_CODE (t) == ENUMERAL_TYPE
4252	  && !is_partial_instantiation)
4253	/* Now that the type has been registered on the instantiations
4254	   list, we set up the enumerators.  Because the enumeration
4255	   constants may involve the enumeration type itself, we make
4256	   sure to register the type first, and then create the
4257	   constants.  That way, doing tsubst_expr for the enumeration
4258	   constants won't result in recursive calls here; we'll find
4259	   the instantiation and exit above.  */
4260	tsubst_enum (template_type, t, arglist);
4261
4262      /* Reset the name of the type, now that CLASSTYPE_TEMPLATE_INFO
4263	 is set up.  */
4264      if (TREE_CODE (t) != ENUMERAL_TYPE)
4265	DECL_NAME (type_decl) = classtype_mangled_name (t);
4266      if (!is_partial_instantiation)
4267	{
4268	  /* For backwards compatibility; code that uses
4269	     -fexternal-templates expects looking up a template to
4270	     instantiate it.  I think DDD still relies on this.
4271	     (jason 8/20/1998) */
4272	  if (TREE_CODE (t) != ENUMERAL_TYPE
4273	      && flag_external_templates
4274	      && CLASSTYPE_INTERFACE_KNOWN (TREE_TYPE (template))
4275	      && ! CLASSTYPE_INTERFACE_ONLY (TREE_TYPE (template)))
4276	    add_pending_template (t);
4277	}
4278      else
4279	/* If the type makes use of template parameters, the
4280	   code that generates debugging information will crash.  */
4281	DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
4282
4283      return t;
4284    }
4285}
4286
4287struct pair_fn_data
4288{
4289  tree_fn_t fn;
4290  void *data;
4291};
4292
4293/* Called from for_each_template_parm via walk_tree.  */
4294
4295static tree
4296for_each_template_parm_r (tp, walk_subtrees, d)
4297     tree *tp;
4298     int *walk_subtrees;
4299     void *d;
4300{
4301  tree t = *tp;
4302  struct pair_fn_data *pfd = (struct pair_fn_data *) d;
4303  tree_fn_t fn = pfd->fn;
4304  void *data = pfd->data;
4305
4306  if (TYPE_P (t)
4307      && for_each_template_parm (TYPE_CONTEXT (t), fn, data))
4308    return error_mark_node;
4309
4310  switch (TREE_CODE (t))
4311    {
4312    case RECORD_TYPE:
4313      if (TYPE_PTRMEMFUNC_P (t))
4314	break;
4315      /* Fall through.  */
4316
4317    case UNION_TYPE:
4318    case ENUMERAL_TYPE:
4319      if (!TYPE_TEMPLATE_INFO (t))
4320	*walk_subtrees = 0;
4321      else if (for_each_template_parm (TREE_VALUE (TYPE_TEMPLATE_INFO (t)),
4322				       fn, data))
4323	return error_mark_node;
4324      break;
4325
4326    case METHOD_TYPE:
4327      /* Since we're not going to walk subtrees, we have to do this
4328	 explicitly here.  */
4329      if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data))
4330	return error_mark_node;
4331      /* Fall through.  */
4332
4333    case FUNCTION_TYPE:
4334      /* Check the return type.  */
4335      if (for_each_template_parm (TREE_TYPE (t), fn, data))
4336	return error_mark_node;
4337
4338      /* Check the parameter types.  Since default arguments are not
4339	 instantiated until they are needed, the TYPE_ARG_TYPES may
4340	 contain expressions that involve template parameters.  But,
4341	 no-one should be looking at them yet.  And, once they're
4342	 instantiated, they don't contain template parameters, so
4343	 there's no point in looking at them then, either.  */
4344      {
4345	tree parm;
4346
4347	for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
4348	  if (for_each_template_parm (TREE_VALUE (parm), fn, data))
4349	    return error_mark_node;
4350
4351	/* Since we've already handled the TYPE_ARG_TYPES, we don't
4352	   want walk_tree walking into them itself.  */
4353	*walk_subtrees = 0;
4354      }
4355      break;
4356
4357    case FUNCTION_DECL:
4358    case VAR_DECL:
4359      if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
4360	  && for_each_template_parm (DECL_TI_ARGS (t), fn, data))
4361	return error_mark_node;
4362      /* Fall through.  */
4363
4364    case CONST_DECL:
4365    case PARM_DECL:
4366      if (DECL_CONTEXT (t)
4367	  && for_each_template_parm (DECL_CONTEXT (t), fn, data))
4368	return error_mark_node;
4369      break;
4370
4371    case BOUND_TEMPLATE_TEMPLATE_PARM:
4372      /* Record template parameters such as `T' inside `TT<T>'.  */
4373      if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data))
4374	return error_mark_node;
4375      /* Fall through.  */
4376
4377    case TEMPLATE_TEMPLATE_PARM:
4378    case TEMPLATE_TYPE_PARM:
4379    case TEMPLATE_PARM_INDEX:
4380      if (fn && (*fn)(t, data))
4381	return error_mark_node;
4382      else if (!fn)
4383	return error_mark_node;
4384      break;
4385
4386    case TEMPLATE_DECL:
4387      /* A template template parameter is encountered */
4388      if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
4389	  && for_each_template_parm (TREE_TYPE (t), fn, data))
4390	return error_mark_node;
4391
4392      /* Already substituted template template parameter */
4393      *walk_subtrees = 0;
4394      break;
4395
4396    case TYPENAME_TYPE:
4397      if (!fn || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn, data))
4398	return error_mark_node;
4399      break;
4400
4401    case CONSTRUCTOR:
4402      if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
4403	  && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
4404				     (TREE_TYPE (t)), fn, data))
4405	return error_mark_node;
4406      break;
4407
4408    case INDIRECT_REF:
4409    case COMPONENT_REF:
4410      /* If there's no type, then this thing must be some expression
4411	 involving template parameters.  */
4412      if (!fn && !TREE_TYPE (t))
4413	return error_mark_node;
4414      break;
4415
4416    case MODOP_EXPR:
4417    case CAST_EXPR:
4418    case REINTERPRET_CAST_EXPR:
4419    case CONST_CAST_EXPR:
4420    case STATIC_CAST_EXPR:
4421    case DYNAMIC_CAST_EXPR:
4422    case ARROW_EXPR:
4423    case DOTSTAR_EXPR:
4424    case TYPEID_EXPR:
4425    case LOOKUP_EXPR:
4426    case PSEUDO_DTOR_EXPR:
4427      if (!fn)
4428	return error_mark_node;
4429      break;
4430
4431    default:
4432      break;
4433    }
4434
4435  /* We didn't find any template parameters we liked.  */
4436  return NULL_TREE;
4437}
4438
4439/* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
4440   BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
4441   call FN with the parameter and the DATA.
4442   If FN returns non-zero, the iteration is terminated, and
4443   for_each_template_parm returns 1.  Otherwise, the iteration
4444   continues.  If FN never returns a non-zero value, the value
4445   returned by for_each_template_parm is 0.  If FN is NULL, it is
4446   considered to be the function which always returns 1.  */
4447
4448static int
4449for_each_template_parm (t, fn, data)
4450     tree t;
4451     tree_fn_t fn;
4452     void* data;
4453{
4454  struct pair_fn_data pfd;
4455
4456  /* Set up.  */
4457  pfd.fn = fn;
4458  pfd.data = data;
4459
4460  /* Walk the tree.  (Conceptually, we would like to walk without
4461     duplicates, but for_each_template_parm_r recursively calls
4462     for_each_template_parm, so we would need to reorganize a fair
4463     bit to use walk_tree_without_duplicates.)  */
4464  return walk_tree (&t,
4465		    for_each_template_parm_r,
4466		    &pfd,
4467		    NULL) != NULL_TREE;
4468}
4469
4470int
4471uses_template_parms (t)
4472     tree t;
4473{
4474  return for_each_template_parm (t, 0, 0);
4475}
4476
4477static int tinst_depth;
4478extern int max_tinst_depth;
4479#ifdef GATHER_STATISTICS
4480int depth_reached;
4481#endif
4482static int tinst_level_tick;
4483static int last_template_error_tick;
4484
4485/* We're starting to instantiate D; record the template instantiation context
4486   for diagnostics and to restore it later.  */
4487
4488int
4489push_tinst_level (d)
4490     tree d;
4491{
4492  tree new;
4493
4494  if (tinst_depth >= max_tinst_depth)
4495    {
4496      /* If the instantiation in question still has unbound template parms,
4497	 we don't really care if we can't instantiate it, so just return.
4498         This happens with base instantiation for implicit `typename'.  */
4499      if (uses_template_parms (d))
4500	return 0;
4501
4502      last_template_error_tick = tinst_level_tick;
4503      error ("template instantiation depth exceeds maximum of %d (use -ftemplate-depth-NN to increase the maximum) instantiating `%D'",
4504	     max_tinst_depth, d);
4505
4506      print_instantiation_context ();
4507
4508      return 0;
4509    }
4510
4511  new = build_expr_wfl (d, input_filename, lineno, 0);
4512  TREE_CHAIN (new) = current_tinst_level;
4513  current_tinst_level = new;
4514
4515  ++tinst_depth;
4516#ifdef GATHER_STATISTICS
4517  if (tinst_depth > depth_reached)
4518    depth_reached = tinst_depth;
4519#endif
4520
4521  ++tinst_level_tick;
4522  return 1;
4523}
4524
4525/* We're done instantiating this template; return to the instantiation
4526   context.  */
4527
4528void
4529pop_tinst_level ()
4530{
4531  tree old = current_tinst_level;
4532
4533  /* Restore the filename and line number stashed away when we started
4534     this instantiation.  */
4535  lineno = TINST_LINE (old);
4536  input_filename = TINST_FILE (old);
4537  extract_interface_info ();
4538
4539  current_tinst_level = TREE_CHAIN (old);
4540  --tinst_depth;
4541  ++tinst_level_tick;
4542}
4543
4544/* We're instantiating a deferred template; restore the template
4545   instantiation context in which the instantiation was requested, which
4546   is one step out from LEVEL.  */
4547
4548static void
4549reopen_tinst_level (level)
4550     tree level;
4551{
4552  tree t;
4553
4554  tinst_depth = 0;
4555  for (t = level; t; t = TREE_CHAIN (t))
4556    ++tinst_depth;
4557
4558  current_tinst_level = level;
4559  pop_tinst_level ();
4560}
4561
4562/* Return the outermost template instantiation context, for use with
4563   -falt-external-templates.  */
4564
4565tree
4566tinst_for_decl ()
4567{
4568  tree p = current_tinst_level;
4569
4570  if (p)
4571    for (; TREE_CHAIN (p) ; p = TREE_CHAIN (p))
4572      ;
4573  return p;
4574}
4575
4576/* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
4577   vector of template arguments, as for tsubst.
4578
4579   Returns an appropriate tsubst'd friend declaration.  */
4580
4581static tree
4582tsubst_friend_function (decl, args)
4583     tree decl;
4584     tree args;
4585{
4586  tree new_friend;
4587  int line = lineno;
4588  const char *file = input_filename;
4589
4590  lineno = DECL_SOURCE_LINE (decl);
4591  input_filename = DECL_SOURCE_FILE (decl);
4592
4593  if (TREE_CODE (decl) == FUNCTION_DECL
4594      && DECL_TEMPLATE_INSTANTIATION (decl)
4595      && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
4596    /* This was a friend declared with an explicit template
4597       argument list, e.g.:
4598
4599       friend void f<>(T);
4600
4601       to indicate that f was a template instantiation, not a new
4602       function declaration.  Now, we have to figure out what
4603       instantiation of what template.  */
4604    {
4605      tree template_id, arglist, fns;
4606      tree new_args;
4607      tree tmpl;
4608      tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
4609
4610      /* Friend functions are looked up in the containing namespace scope.
4611         We must enter that scope, to avoid finding member functions of the
4612         current cless with same name.  */
4613      push_nested_namespace (ns);
4614      fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
4615                         tf_error | tf_warning, NULL_TREE);
4616      pop_nested_namespace (ns);
4617      arglist = tsubst (DECL_TI_ARGS (decl), args,
4618                        tf_error | tf_warning, NULL_TREE);
4619      template_id = lookup_template_function (fns, arglist);
4620
4621      new_friend = tsubst (decl, args, tf_error | tf_warning, NULL_TREE);
4622      tmpl = determine_specialization (template_id, new_friend,
4623				       &new_args,
4624				       /*need_member_template=*/0);
4625      new_friend = instantiate_template (tmpl, new_args);
4626      goto done;
4627    }
4628
4629  new_friend = tsubst (decl, args, tf_error | tf_warning, NULL_TREE);
4630
4631  /* The NEW_FRIEND will look like an instantiation, to the
4632     compiler, but is not an instantiation from the point of view of
4633     the language.  For example, we might have had:
4634
4635     template <class T> struct S {
4636       template <class U> friend void f(T, U);
4637     };
4638
4639     Then, in S<int>, template <class U> void f(int, U) is not an
4640     instantiation of anything.  */
4641  DECL_USE_TEMPLATE (new_friend) = 0;
4642  if (TREE_CODE (decl) == TEMPLATE_DECL)
4643    {
4644      DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
4645      DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
4646	= DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
4647    }
4648
4649  /* The mangled name for the NEW_FRIEND is incorrect.  The function
4650     is not a template instantiation and should not be mangled like
4651     one.  Therefore, we forget the mangling here; we'll recompute it
4652     later if we need it.  */
4653  if (TREE_CODE (new_friend) != TEMPLATE_DECL)
4654    {
4655      SET_DECL_RTL (new_friend, NULL_RTX);
4656      SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
4657    }
4658
4659  if (DECL_NAMESPACE_SCOPE_P (new_friend))
4660    {
4661      tree old_decl;
4662      tree new_friend_template_info;
4663      tree new_friend_result_template_info;
4664      tree ns;
4665      int  new_friend_is_defn;
4666
4667      /* We must save some information from NEW_FRIEND before calling
4668	 duplicate decls since that function will free NEW_FRIEND if
4669	 possible.  */
4670      new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
4671      if (TREE_CODE (new_friend) == TEMPLATE_DECL)
4672	{
4673	  /* This declaration is a `primary' template.  */
4674	  DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
4675
4676	  new_friend_is_defn
4677	    = DECL_INITIAL (DECL_TEMPLATE_RESULT (new_friend)) != NULL_TREE;
4678	  new_friend_result_template_info
4679	    = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
4680	}
4681      else
4682	{
4683	  new_friend_is_defn = DECL_INITIAL (new_friend) != NULL_TREE;
4684	  new_friend_result_template_info = NULL_TREE;
4685	}
4686
4687      /* Inside pushdecl_namespace_level, we will push into the
4688	 current namespace. However, the friend function should go
4689	 into the namespace of the template. */
4690      ns = decl_namespace_context (new_friend);
4691      push_nested_namespace (ns);
4692      old_decl = pushdecl_namespace_level (new_friend);
4693      pop_nested_namespace (ns);
4694
4695      if (old_decl != new_friend)
4696	{
4697	  /* This new friend declaration matched an existing
4698	     declaration.  For example, given:
4699
4700	       template <class T> void f(T);
4701	       template <class U> class C {
4702		 template <class T> friend void f(T) {}
4703	       };
4704
4705	     the friend declaration actually provides the definition
4706	     of `f', once C has been instantiated for some type.  So,
4707	     old_decl will be the out-of-class template declaration,
4708	     while new_friend is the in-class definition.
4709
4710	     But, if `f' was called before this point, the
4711	     instantiation of `f' will have DECL_TI_ARGS corresponding
4712	     to `T' but not to `U', references to which might appear
4713	     in the definition of `f'.  Previously, the most general
4714	     template for an instantiation of `f' was the out-of-class
4715	     version; now it is the in-class version.  Therefore, we
4716	     run through all specialization of `f', adding to their
4717	     DECL_TI_ARGS appropriately.  In particular, they need a
4718	     new set of outer arguments, corresponding to the
4719	     arguments for this class instantiation.
4720
4721	     The same situation can arise with something like this:
4722
4723	       friend void f(int);
4724	       template <class T> class C {
4725	         friend void f(T) {}
4726               };
4727
4728	     when `C<int>' is instantiated.  Now, `f(int)' is defined
4729	     in the class.  */
4730
4731	  if (!new_friend_is_defn)
4732	    /* On the other hand, if the in-class declaration does
4733	       *not* provide a definition, then we don't want to alter
4734	       existing definitions.  We can just leave everything
4735	       alone.  */
4736	    ;
4737	  else
4738	    {
4739	      /* Overwrite whatever template info was there before, if
4740		 any, with the new template information pertaining to
4741		 the declaration.  */
4742	      DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
4743
4744	      if (TREE_CODE (old_decl) != TEMPLATE_DECL)
4745		/* duplicate_decls will take care of this case.  */
4746		;
4747	      else
4748		{
4749		  tree t;
4750		  tree new_friend_args;
4751
4752		  DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
4753		    = new_friend_result_template_info;
4754
4755		  new_friend_args = TI_ARGS (new_friend_template_info);
4756		  for (t = DECL_TEMPLATE_SPECIALIZATIONS (old_decl);
4757		       t != NULL_TREE;
4758		       t = TREE_CHAIN (t))
4759		    {
4760		      tree spec = TREE_VALUE (t);
4761
4762		      DECL_TI_ARGS (spec)
4763			= add_outermost_template_args (new_friend_args,
4764						       DECL_TI_ARGS (spec));
4765		    }
4766
4767		  /* Now, since specializations are always supposed to
4768		     hang off of the most general template, we must move
4769		     them.  */
4770		  t = most_general_template (old_decl);
4771		  if (t != old_decl)
4772		    {
4773		      DECL_TEMPLATE_SPECIALIZATIONS (t)
4774			= chainon (DECL_TEMPLATE_SPECIALIZATIONS (t),
4775				   DECL_TEMPLATE_SPECIALIZATIONS (old_decl));
4776		      DECL_TEMPLATE_SPECIALIZATIONS (old_decl) = NULL_TREE;
4777		    }
4778		}
4779	    }
4780
4781	  /* The information from NEW_FRIEND has been merged into OLD_DECL
4782	     by duplicate_decls.  */
4783	  new_friend = old_decl;
4784	}
4785    }
4786  else if (COMPLETE_TYPE_P (DECL_CONTEXT (new_friend)))
4787    {
4788      /* Check to see that the declaration is really present, and,
4789	 possibly obtain an improved declaration.  */
4790      tree fn = check_classfn (DECL_CONTEXT (new_friend),
4791			       new_friend);
4792
4793      if (fn)
4794	new_friend = fn;
4795    }
4796
4797 done:
4798  lineno = line;
4799  input_filename = file;
4800  return new_friend;
4801}
4802
4803/* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
4804   template arguments, as for tsubst.
4805
4806   Returns an appropriate tsubst'd friend type or error_mark_node on
4807   failure.  */
4808
4809static tree
4810tsubst_friend_class (friend_tmpl, args)
4811     tree friend_tmpl;
4812     tree args;
4813{
4814  tree friend_type;
4815  tree tmpl;
4816  tree context;
4817
4818  context = DECL_CONTEXT (friend_tmpl);
4819
4820  if (context)
4821    {
4822      if (TREE_CODE (context) == NAMESPACE_DECL)
4823	push_nested_namespace (context);
4824      else
4825	push_nested_class (tsubst (context, args, tf_none, NULL_TREE), 2);
4826    }
4827
4828  /* First, we look for a class template.  */
4829  tmpl = lookup_name (DECL_NAME (friend_tmpl), /*prefer_type=*/0);
4830
4831  /* But, if we don't find one, it might be because we're in a
4832     situation like this:
4833
4834       template <class T>
4835       struct S {
4836	 template <class U>
4837	 friend struct S;
4838       };
4839
4840     Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
4841     for `S<int>', not the TEMPLATE_DECL.  */
4842  if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
4843    {
4844      tmpl = lookup_name (DECL_NAME (friend_tmpl), /*prefer_type=*/1);
4845      tmpl = maybe_get_template_decl_from_type_decl (tmpl);
4846    }
4847
4848  if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
4849    {
4850      /* The friend template has already been declared.  Just
4851	 check to see that the declarations match, and install any new
4852	 default parameters.  We must tsubst the default parameters,
4853	 of course.  We only need the innermost template parameters
4854	 because that is all that redeclare_class_template will look
4855	 at.  */
4856      if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
4857	  > TMPL_ARGS_DEPTH (args))
4858	{
4859	  tree parms;
4860	  parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
4861					 args, tf_error | tf_warning);
4862	  redeclare_class_template (TREE_TYPE (tmpl), parms);
4863	}
4864
4865      friend_type = TREE_TYPE (tmpl);
4866    }
4867  else
4868    {
4869      /* The friend template has not already been declared.  In this
4870	 case, the instantiation of the template class will cause the
4871	 injection of this template into the global scope.  */
4872      tmpl = tsubst (friend_tmpl, args, tf_error | tf_warning, NULL_TREE);
4873
4874      /* The new TMPL is not an instantiation of anything, so we
4875 	 forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
4876	 the new type because that is supposed to be the corresponding
4877	 template decl, i.e., TMPL.  */
4878      DECL_USE_TEMPLATE (tmpl) = 0;
4879      DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
4880      CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
4881
4882      /* Inject this template into the global scope.  */
4883      friend_type = TREE_TYPE (pushdecl_top_level (tmpl));
4884    }
4885
4886  if (context)
4887    {
4888      if (TREE_CODE (context) == NAMESPACE_DECL)
4889	pop_nested_namespace (context);
4890      else
4891	pop_nested_class ();
4892    }
4893
4894  return friend_type;
4895}
4896
4897/* Returns zero if TYPE cannot be completed later due to circularity.
4898   Otherwise returns one.  */
4899
4900static int
4901can_complete_type_without_circularity (type)
4902     tree type;
4903{
4904  if (type == NULL_TREE || type == error_mark_node)
4905    return 0;
4906  else if (COMPLETE_TYPE_P (type))
4907    return 1;
4908  else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
4909    return can_complete_type_without_circularity (TREE_TYPE (type));
4910  else if (CLASS_TYPE_P (type) && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
4911    return 0;
4912  else
4913    return 1;
4914}
4915
4916tree
4917instantiate_class_template (type)
4918     tree type;
4919{
4920  tree template, args, pattern, t;
4921  tree typedecl;
4922
4923  if (type == error_mark_node)
4924    return error_mark_node;
4925
4926  if (TYPE_BEING_DEFINED (type) || COMPLETE_TYPE_P (type))
4927    return type;
4928
4929  /* Figure out which template is being instantiated.  */
4930  template = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
4931  my_friendly_assert (TREE_CODE (template) == TEMPLATE_DECL, 279);
4932
4933  /* Figure out which arguments are being used to do the
4934     instantiation.  */
4935  args = CLASSTYPE_TI_ARGS (type);
4936  PARTIAL_INSTANTIATION_P (type) = uses_template_parms (args);
4937
4938  if (pedantic && PARTIAL_INSTANTIATION_P (type))
4939    /* If this is a partial instantiation, then we can't instantiate
4940       the type; there's no telling whether or not one of the
4941       template parameters might eventually be instantiated to some
4942       value that results in a specialization being used.  For
4943       example, consider:
4944
4945         template <class T>
4946         struct S {};
4947
4948         template <class U>
4949         void f(S<U>);
4950
4951         template <>
4952         struct S<int> {};
4953
4954       Now, the `S<U>' in `f<int>' is the specialization, not an
4955       instantiation of the original template.  */
4956    return type;
4957
4958  /* Determine what specialization of the original template to
4959     instantiate.  */
4960  if (PARTIAL_INSTANTIATION_P (type))
4961    /* There's no telling which specialization is appropriate at this
4962       point.  Since all peeking at the innards of this partial
4963       instantiation are extensions (like the "implicit typename"
4964       extension, which allows users to omit the keyword `typename' on
4965       names that are declared as types in template base classes), we
4966       are free to do what we please.
4967
4968       Trying to figure out which partial instantiation to use can
4969       cause a crash.  (Some of the template arguments don't even have
4970       types.)  So, we just use the most general version.  */
4971    t = NULL_TREE;
4972  else
4973    {
4974      t = most_specialized_class (template, args);
4975
4976      if (t == error_mark_node)
4977	{
4978	  const char *str = "candidates are:";
4979	  error ("ambiguous class template instantiation for `%#T'", type);
4980	  for (t = DECL_TEMPLATE_SPECIALIZATIONS (template); t;
4981	       t = TREE_CHAIN (t))
4982	    {
4983	      if (get_class_bindings (TREE_VALUE (t), TREE_PURPOSE (t),
4984				      args))
4985		{
4986		  cp_error_at ("%s %+#T", str, TREE_TYPE (t));
4987		  str = "               ";
4988		}
4989	    }
4990	  TYPE_BEING_DEFINED (type) = 1;
4991	  return error_mark_node;
4992	}
4993    }
4994
4995  if (t)
4996    pattern = TREE_TYPE (t);
4997  else
4998    pattern = TREE_TYPE (template);
4999
5000  /* If the template we're instantiating is incomplete, then clearly
5001     there's nothing we can do.  */
5002  if (!COMPLETE_TYPE_P (pattern))
5003    return type;
5004
5005  /* If this is a partial instantiation, don't tsubst anything.  We will
5006     only use this type for implicit typename, so the actual contents don't
5007     matter.  All that matters is whether a particular name is a type.  */
5008  if (PARTIAL_INSTANTIATION_P (type))
5009    {
5010      /* The fields set here must be kept in sync with those cleared
5011	 in begin_class_definition.  */
5012      TYPE_BINFO_BASETYPES (type) = TYPE_BINFO_BASETYPES (pattern);
5013      TYPE_FIELDS (type) = TYPE_FIELDS (pattern);
5014      TYPE_METHODS (type) = TYPE_METHODS (pattern);
5015      CLASSTYPE_TAGS (type) = CLASSTYPE_TAGS (pattern);
5016      CLASSTYPE_VBASECLASSES (type) = CLASSTYPE_VBASECLASSES (pattern);
5017
5018      /* Pretend that the type is complete, so that we will look
5019	 inside it during name lookup and such.  */
5020      TYPE_SIZE (type) = bitsize_zero_node;
5021      return type;
5022    }
5023
5024  /* If we've recursively instantiated too many templates, stop.  */
5025  if (! push_tinst_level (type))
5026    return type;
5027
5028  /* Now we're really doing the instantiation.  Mark the type as in
5029     the process of being defined.  */
5030  TYPE_BEING_DEFINED (type) = 1;
5031
5032  maybe_push_to_top_level (uses_template_parms (type));
5033
5034  if (t)
5035    {
5036      /* This TYPE is actually a instantiation of of a partial
5037	 specialization.  We replace the innermost set of ARGS with
5038	 the arguments appropriate for substitution.  For example,
5039	 given:
5040
5041	   template <class T> struct S {};
5042	   template <class T> struct S<T*> {};
5043
5044	 and supposing that we are instantiating S<int*>, ARGS will
5045	 present be {int*} but we need {int}.  */
5046      tree inner_args
5047	= get_class_bindings (TREE_VALUE (t), TREE_PURPOSE (t),
5048			      args);
5049
5050      /* If there were multiple levels in ARGS, replacing the
5051	 innermost level would alter CLASSTYPE_TI_ARGS, which we don't
5052	 want, so we make a copy first.  */
5053      if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
5054	{
5055	  args = copy_node (args);
5056	  SET_TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args), inner_args);
5057	}
5058      else
5059	args = inner_args;
5060    }
5061
5062  if (flag_external_templates)
5063    {
5064      if (flag_alt_external_templates)
5065	{
5066	  CLASSTYPE_INTERFACE_ONLY (type) = interface_only;
5067	  SET_CLASSTYPE_INTERFACE_UNKNOWN_X (type, interface_unknown);
5068	}
5069      else
5070	{
5071	  CLASSTYPE_INTERFACE_ONLY (type) = CLASSTYPE_INTERFACE_ONLY (pattern);
5072	  SET_CLASSTYPE_INTERFACE_UNKNOWN_X
5073	    (type, CLASSTYPE_INTERFACE_UNKNOWN (pattern));
5074	}
5075    }
5076  else
5077    {
5078      SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
5079    }
5080
5081  TYPE_HAS_CONSTRUCTOR (type) = TYPE_HAS_CONSTRUCTOR (pattern);
5082  TYPE_HAS_DESTRUCTOR (type) = TYPE_HAS_DESTRUCTOR (pattern);
5083  TYPE_OVERLOADS_CALL_EXPR (type) = TYPE_OVERLOADS_CALL_EXPR (pattern);
5084  TYPE_OVERLOADS_ARRAY_REF (type) = TYPE_OVERLOADS_ARRAY_REF (pattern);
5085  TYPE_OVERLOADS_ARROW (type) = TYPE_OVERLOADS_ARROW (pattern);
5086  TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
5087  TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
5088  TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
5089  TYPE_HAS_ASSIGN_REF (type) = TYPE_HAS_ASSIGN_REF (pattern);
5090  TYPE_HAS_CONST_ASSIGN_REF (type) = TYPE_HAS_CONST_ASSIGN_REF (pattern);
5091  TYPE_HAS_ABSTRACT_ASSIGN_REF (type) = TYPE_HAS_ABSTRACT_ASSIGN_REF (pattern);
5092  TYPE_HAS_INIT_REF (type) = TYPE_HAS_INIT_REF (pattern);
5093  TYPE_HAS_CONST_INIT_REF (type) = TYPE_HAS_CONST_INIT_REF (pattern);
5094  TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
5095  TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
5096  TYPE_BASE_CONVS_MAY_REQUIRE_CODE_P (type)
5097    = TYPE_BASE_CONVS_MAY_REQUIRE_CODE_P (pattern);
5098  TYPE_USES_MULTIPLE_INHERITANCE (type)
5099    = TYPE_USES_MULTIPLE_INHERITANCE (pattern);
5100  TYPE_USES_VIRTUAL_BASECLASSES (type)
5101    = TYPE_USES_VIRTUAL_BASECLASSES (pattern);
5102  TYPE_PACKED (type) = TYPE_PACKED (pattern);
5103  TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
5104  TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
5105  TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
5106  if (ANON_AGGR_TYPE_P (pattern))
5107    SET_ANON_AGGR_TYPE_P (type);
5108
5109  if (TYPE_BINFO_BASETYPES (pattern))
5110    {
5111      tree base_list = NULL_TREE;
5112      tree pbases = TYPE_BINFO_BASETYPES (pattern);
5113      int i;
5114
5115      /* Substitute into each of the bases to determine the actual
5116	 basetypes.  */
5117      for (i = 0; i < TREE_VEC_LENGTH (pbases); ++i)
5118	{
5119	  tree base;
5120	  tree access;
5121	  tree pbase;
5122
5123	  pbase = TREE_VEC_ELT (pbases, i);
5124
5125	  /* Substitute to figure out the base class.  */
5126	  base = tsubst (BINFO_TYPE (pbase), args, tf_error, NULL_TREE);
5127	  if (base == error_mark_node)
5128	    continue;
5129
5130	  /* Calculate the correct access node.  */
5131	  if (TREE_VIA_VIRTUAL (pbase))
5132	    {
5133	      if (TREE_VIA_PUBLIC (pbase))
5134		access = access_public_virtual_node;
5135	      else if (TREE_VIA_PROTECTED (pbase))
5136		access = access_protected_virtual_node;
5137	      else
5138		access = access_private_virtual_node;
5139	    }
5140	  else
5141	    {
5142	      if (TREE_VIA_PUBLIC (pbase))
5143		access = access_public_node;
5144	      else if (TREE_VIA_PROTECTED (pbase))
5145		access = access_protected_node;
5146	      else
5147		access = access_private_node;
5148	    }
5149
5150	  base_list = tree_cons (access, base, base_list);
5151	}
5152
5153      /* The list is now in reverse order; correct that.  */
5154      base_list = nreverse (base_list);
5155
5156      /* Now call xref_basetypes to set up all the base-class
5157	 information.  */
5158      xref_basetypes (TREE_CODE (pattern) == RECORD_TYPE
5159		      ? (CLASSTYPE_DECLARED_CLASS (pattern)
5160			 ? class_type_node : record_type_node)
5161		      : union_type_node,
5162		      DECL_NAME (TYPE_NAME (pattern)),
5163		      type,
5164		      base_list);
5165    }
5166
5167  /* Now that our base classes are set up, enter the scope of the
5168     class, so that name lookups into base classes, etc. will work
5169     correctly.  This is precisely analogous to what we do in
5170     begin_class_definition when defining an ordinary non-template
5171     class.  */
5172  pushclass (type, 1);
5173
5174  for (t = CLASSTYPE_TAGS (pattern); t; t = TREE_CHAIN (t))
5175    {
5176      tree tag = TREE_VALUE (t);
5177      tree name = TYPE_IDENTIFIER (tag);
5178      tree newtag;
5179
5180      newtag = tsubst (tag, args, tf_error, NULL_TREE);
5181      my_friendly_assert (newtag != error_mark_node, 20010206);
5182      if (TREE_CODE (newtag) != ENUMERAL_TYPE)
5183	{
5184	  if (TYPE_LANG_SPECIFIC (tag) && CLASSTYPE_IS_TEMPLATE (tag))
5185	    /* Unfortunately, lookup_template_class sets
5186	       CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
5187	       instantiation (i.e., for the type of a member template
5188	       class nested within a template class.)  This behavior is
5189	       required for maybe_process_partial_specialization to work
5190	       correctly, but is not accurate in this case; the TAG is not
5191	       an instantiation of anything.  (The corresponding
5192	       TEMPLATE_DECL is an instantiation, but the TYPE is not.) */
5193	    CLASSTYPE_USE_TEMPLATE (newtag) = 0;
5194
5195	  /* Now, we call pushtag to put this NEWTAG into the scope of
5196	     TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
5197	     pushtag calling push_template_decl.  We don't have to do
5198	     this for enums because it will already have been done in
5199	     tsubst_enum.  */
5200	  if (name)
5201	    SET_IDENTIFIER_TYPE_VALUE (name, newtag);
5202	  pushtag (name, newtag, /*globalize=*/0);
5203	}
5204    }
5205
5206  /* Don't replace enum constants here.  */
5207  for (t = TYPE_FIELDS (pattern); t; t = TREE_CHAIN (t))
5208    if (TREE_CODE (t) != CONST_DECL)
5209      {
5210	tree r;
5211
5212	/* The the file and line for this declaration, to assist in
5213	   error message reporting.  Since we called push_tinst_level
5214	   above, we don't need to restore these.  */
5215	lineno = DECL_SOURCE_LINE (t);
5216	input_filename = DECL_SOURCE_FILE (t);
5217
5218	r = tsubst (t, args, tf_error | tf_warning, NULL_TREE);
5219	if (TREE_CODE (r) == VAR_DECL)
5220	  {
5221	    tree init;
5222
5223	    if (DECL_INITIALIZED_IN_CLASS_P (r))
5224	      init = tsubst_expr (DECL_INITIAL (t), args,
5225				  tf_error | tf_warning, NULL_TREE);
5226	    else
5227	      init = NULL_TREE;
5228
5229	    finish_static_data_member_decl (r, init,
5230					    /*asmspec_tree=*/NULL_TREE,
5231					    /*flags=*/0);
5232
5233	    if (DECL_INITIALIZED_IN_CLASS_P (r))
5234	      check_static_variable_definition (r, TREE_TYPE (r));
5235	  }
5236	else if (TREE_CODE (r) == FIELD_DECL)
5237	  {
5238	    /* Determine whether R has a valid type and can be
5239	       completed later.  If R is invalid, then it is replaced
5240	       by error_mark_node so that it will not be added to
5241	       TYPE_FIELDS.  */
5242	    tree rtype = TREE_TYPE (r);
5243	    if (!can_complete_type_without_circularity (rtype))
5244	      {
5245		incomplete_type_error (r, rtype);
5246		r = error_mark_node;
5247	      }
5248	  }
5249
5250	/* R will have a TREE_CHAIN if and only if it has already been
5251	   processed by finish_member_declaration.  This can happen
5252	   if, for example, it is a TYPE_DECL for a class-scoped
5253	   ENUMERAL_TYPE; such a thing will already have been added to
5254	   the field list by tsubst_enum above.  */
5255	if (!TREE_CHAIN (r))
5256	  {
5257	    set_current_access_from_decl (r);
5258	    finish_member_declaration (r);
5259	  }
5260      }
5261
5262  /* Set up the list (TYPE_METHODS) and vector (CLASSTYPE_METHOD_VEC)
5263     for this instantiation.  */
5264  for (t = TYPE_METHODS (pattern); t; t = TREE_CHAIN (t))
5265    {
5266      tree r = tsubst (t, args, tf_error, NULL_TREE);
5267      set_current_access_from_decl (r);
5268      grok_special_member_properties (r);
5269      finish_member_declaration (r);
5270    }
5271
5272  /* Construct the DECL_FRIENDLIST for the new class type.  */
5273  typedecl = TYPE_MAIN_DECL (type);
5274  for (t = DECL_FRIENDLIST (TYPE_MAIN_DECL (pattern));
5275       t != NULL_TREE;
5276       t = TREE_CHAIN (t))
5277    {
5278      tree friends;
5279
5280      for (friends = TREE_VALUE (t);
5281	   friends != NULL_TREE;
5282	   friends = TREE_CHAIN (friends))
5283	if (TREE_PURPOSE (friends) == error_mark_node)
5284	  add_friend (type,
5285		      tsubst_friend_function (TREE_VALUE (friends),
5286					      args));
5287	else
5288	  abort ();
5289    }
5290
5291  for (t = CLASSTYPE_FRIEND_CLASSES (pattern);
5292       t != NULL_TREE;
5293       t = TREE_CHAIN (t))
5294    {
5295      tree friend_type = TREE_VALUE (t);
5296      tree new_friend_type;
5297
5298      if (TREE_CODE (friend_type) == TEMPLATE_DECL)
5299	new_friend_type = tsubst_friend_class (friend_type, args);
5300      else if (uses_template_parms (friend_type))
5301	new_friend_type = tsubst (friend_type, args,
5302				  tf_error | tf_warning, NULL_TREE);
5303      else
5304	{
5305	  tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
5306
5307	  /* The call to xref_tag_from_type does injection for friend
5308	     classes.  */
5309	  push_nested_namespace (ns);
5310	  new_friend_type =
5311	    xref_tag_from_type (friend_type, NULL_TREE, 1);
5312	  pop_nested_namespace (ns);
5313	}
5314
5315      if (TREE_CODE (friend_type) == TEMPLATE_DECL)
5316	/* Trick make_friend_class into realizing that the friend
5317	   we're adding is a template, not an ordinary class.  It's
5318	   important that we use make_friend_class since it will
5319	   perform some error-checking and output cross-reference
5320	   information.  */
5321	++processing_template_decl;
5322
5323      if (new_friend_type != error_mark_node)
5324        make_friend_class (type, new_friend_type);
5325
5326      if (TREE_CODE (friend_type) == TEMPLATE_DECL)
5327	--processing_template_decl;
5328    }
5329
5330  /* Now that TYPE_FIELDS and TYPE_METHODS are set up.  We can
5331     instantiate templates used by this class.  */
5332  for (t = TYPE_FIELDS (type); t; t = TREE_CHAIN (t))
5333    if (TREE_CODE (t) == FIELD_DECL)
5334      {
5335	TREE_TYPE (t) = complete_type (TREE_TYPE (t));
5336	require_complete_type (t);
5337      }
5338
5339  /* Set the file and line number information to whatever is given for
5340     the class itself.  This puts error messages involving generated
5341     implicit functions at a predictable point, and the same point
5342     that would be used for non-template classes.  */
5343  lineno = DECL_SOURCE_LINE (typedecl);
5344  input_filename = DECL_SOURCE_FILE (typedecl);
5345
5346  unreverse_member_declarations (type);
5347  finish_struct_1 (type);
5348  CLASSTYPE_GOT_SEMICOLON (type) = 1;
5349
5350  /* Clear this now so repo_template_used is happy.  */
5351  TYPE_BEING_DEFINED (type) = 0;
5352  repo_template_used (type);
5353
5354  /* Now that the class is complete, instantiate default arguments for
5355     any member functions.  We don't do this earlier because the
5356     default arguments may reference members of the class.  */
5357  if (!PRIMARY_TEMPLATE_P (template))
5358    for (t = TYPE_METHODS (type); t; t = TREE_CHAIN (t))
5359      if (TREE_CODE (t) == FUNCTION_DECL
5360	  /* Implicitly generated member functions will not have template
5361	     information; they are not instantiations, but instead are
5362	     created "fresh" for each instantiation.  */
5363	  && DECL_TEMPLATE_INFO (t))
5364	tsubst_default_arguments (t);
5365
5366  popclass ();
5367  pop_from_top_level ();
5368  pop_tinst_level ();
5369
5370  return type;
5371}
5372
5373static int
5374list_eq (t1, t2)
5375     tree t1, t2;
5376{
5377  if (t1 == NULL_TREE)
5378    return t2 == NULL_TREE;
5379  if (t2 == NULL_TREE)
5380    return 0;
5381  /* Don't care if one declares its arg const and the other doesn't -- the
5382     main variant of the arg type is all that matters.  */
5383  if (TYPE_MAIN_VARIANT (TREE_VALUE (t1))
5384      != TYPE_MAIN_VARIANT (TREE_VALUE (t2)))
5385    return 0;
5386  return list_eq (TREE_CHAIN (t1), TREE_CHAIN (t2));
5387}
5388
5389/* If arg is a non-type template parameter that does not depend on template
5390   arguments, fold it like we weren't in the body of a template.  */
5391
5392static tree
5393maybe_fold_nontype_arg (arg)
5394     tree arg;
5395{
5396  if (arg && !TYPE_P (arg) && !uses_template_parms (arg))
5397    {
5398      /* Sometimes, one of the args was an expression involving a
5399	 template constant parameter, like N - 1.  Now that we've
5400	 tsubst'd, we might have something like 2 - 1.  This will
5401	 confuse lookup_template_class, so we do constant folding
5402	 here.  We have to unset processing_template_decl, to
5403	 fool build_expr_from_tree() into building an actual
5404	 tree.  */
5405
5406      /* If the TREE_TYPE of ARG is not NULL_TREE, ARG is already
5407	 as simple as it's going to get, and trying to reprocess
5408	 the trees will break.  */
5409      if (!TREE_TYPE (arg))
5410	{
5411	  int saved_processing_template_decl = processing_template_decl;
5412	  processing_template_decl = 0;
5413	  arg = build_expr_from_tree (arg);
5414	  processing_template_decl = saved_processing_template_decl;
5415	}
5416
5417      arg = fold (arg);
5418    }
5419  return arg;
5420}
5421
5422/* Substitute ARGS into the vector of template arguments T.  */
5423
5424static tree
5425tsubst_template_arg_vector (t, args, complain)
5426     tree t;
5427     tree args;
5428     tsubst_flags_t complain;
5429{
5430  int len = TREE_VEC_LENGTH (t), need_new = 0, i;
5431  tree *elts = (tree *) alloca (len * sizeof (tree));
5432
5433  memset ((char *) elts, 0, len * sizeof (tree));
5434
5435  for (i = 0; i < len; i++)
5436    {
5437      if (TREE_VEC_ELT (t, i) != NULL_TREE
5438	  && TREE_CODE (TREE_VEC_ELT (t, i)) == TREE_VEC)
5439	elts[i] = tsubst_template_arg_vector (TREE_VEC_ELT (t, i),
5440					      args, complain);
5441      else
5442	elts[i] = maybe_fold_nontype_arg
5443	  (tsubst_expr (TREE_VEC_ELT (t, i), args, complain,
5444			NULL_TREE));
5445
5446      if (elts[i] == error_mark_node)
5447	return error_mark_node;
5448
5449      if (elts[i] != TREE_VEC_ELT (t, i))
5450	need_new = 1;
5451    }
5452
5453  if (!need_new)
5454    return t;
5455
5456  t = make_tree_vec (len);
5457  for (i = 0; i < len; i++)
5458    TREE_VEC_ELT (t, i) = elts[i];
5459
5460  return t;
5461}
5462
5463/* Return the result of substituting ARGS into the template parameters
5464   given by PARMS.  If there are m levels of ARGS and m + n levels of
5465   PARMS, then the result will contain n levels of PARMS.  For
5466   example, if PARMS is `template <class T> template <class U>
5467   template <T*, U, class V>' and ARGS is {{int}, {double}} then the
5468   result will be `template <int*, double, class V>'.  */
5469
5470static tree
5471tsubst_template_parms (parms, args, complain)
5472     tree parms;
5473     tree args;
5474     tsubst_flags_t complain;
5475{
5476  tree r = NULL_TREE;
5477  tree* new_parms;
5478
5479  for (new_parms = &r;
5480       TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
5481       new_parms = &(TREE_CHAIN (*new_parms)),
5482	 parms = TREE_CHAIN (parms))
5483    {
5484      tree new_vec =
5485	make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
5486      int i;
5487
5488      for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
5489	{
5490	  tree tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
5491	  tree default_value = TREE_PURPOSE (tuple);
5492	  tree parm_decl = TREE_VALUE (tuple);
5493
5494	  parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
5495	  default_value = tsubst_expr (default_value, args,
5496				       complain, NULL_TREE);
5497	  tuple = build_tree_list (maybe_fold_nontype_arg (default_value),
5498				   parm_decl);
5499	  TREE_VEC_ELT (new_vec, i) = tuple;
5500	}
5501
5502      *new_parms =
5503	tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
5504			     - TMPL_ARGS_DEPTH (args)),
5505		   new_vec, NULL_TREE);
5506    }
5507
5508  return r;
5509}
5510
5511/* Substitute the ARGS into the indicated aggregate (or enumeration)
5512   type T.  If T is not an aggregate or enumeration type, it is
5513   handled as if by tsubst.  IN_DECL is as for tsubst.  If
5514   ENTERING_SCOPE is non-zero, T is the context for a template which
5515   we are presently tsubst'ing.  Return the substituted value.  */
5516
5517static tree
5518tsubst_aggr_type (t, args, complain, in_decl, entering_scope)
5519     tree t;
5520     tree args;
5521     tsubst_flags_t complain;
5522     tree in_decl;
5523     int entering_scope;
5524{
5525  if (t == NULL_TREE)
5526    return NULL_TREE;
5527
5528  switch (TREE_CODE (t))
5529    {
5530    case RECORD_TYPE:
5531      if (TYPE_PTRMEMFUNC_P (t))
5532	return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
5533
5534      /* else fall through */
5535    case ENUMERAL_TYPE:
5536    case UNION_TYPE:
5537      if (TYPE_TEMPLATE_INFO (t))
5538	{
5539	  tree argvec;
5540	  tree context;
5541	  tree r;
5542
5543	  /* First, determine the context for the type we are looking
5544	     up.  */
5545	  if (TYPE_CONTEXT (t) != NULL_TREE)
5546	    context = tsubst_aggr_type (TYPE_CONTEXT (t), args,
5547					complain,
5548					in_decl, /*entering_scope=*/1);
5549	  else
5550	    context = NULL_TREE;
5551
5552	  /* Then, figure out what arguments are appropriate for the
5553	     type we are trying to find.  For example, given:
5554
5555	       template <class T> struct S;
5556	       template <class T, class U> void f(T, U) { S<U> su; }
5557
5558	     and supposing that we are instantiating f<int, double>,
5559	     then our ARGS will be {int, double}, but, when looking up
5560	     S we only want {double}.  */
5561	  argvec = tsubst_template_arg_vector (TYPE_TI_ARGS (t), args,
5562					       complain);
5563	  if (argvec == error_mark_node)
5564	    return error_mark_node;
5565
5566  	  r = lookup_template_class (t, argvec, in_decl, context,
5567				     entering_scope, complain);
5568
5569	  return cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
5570	}
5571      else
5572	/* This is not a template type, so there's nothing to do.  */
5573	return t;
5574
5575    default:
5576      return tsubst (t, args, complain, in_decl);
5577    }
5578}
5579
5580/* Substitute into the default argument ARG (a default argument for
5581   FN), which has the indicated TYPE.  */
5582
5583tree
5584tsubst_default_argument (fn, type, arg)
5585     tree fn;
5586     tree type;
5587     tree arg;
5588{
5589  /* This default argument came from a template.  Instantiate the
5590     default argument here, not in tsubst.  In the case of
5591     something like:
5592
5593       template <class T>
5594       struct S {
5595	 static T t();
5596	 void f(T = t());
5597       };
5598
5599     we must be careful to do name lookup in the scope of S<T>,
5600     rather than in the current class.  */
5601  if (DECL_CLASS_SCOPE_P (fn))
5602    pushclass (DECL_CONTEXT (fn), 2);
5603
5604  arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
5605		     tf_error | tf_warning, NULL_TREE);
5606
5607  if (DECL_CLASS_SCOPE_P (fn))
5608    popclass ();
5609
5610  /* Make sure the default argument is reasonable.  */
5611  arg = check_default_argument (type, arg);
5612
5613  return arg;
5614}
5615
5616/* Substitute into all the default arguments for FN.  */
5617
5618static void
5619tsubst_default_arguments (fn)
5620     tree fn;
5621{
5622  tree arg;
5623  tree tmpl_args;
5624
5625  tmpl_args = DECL_TI_ARGS (fn);
5626
5627  /* If this function is not yet instantiated, we certainly don't need
5628     its default arguments.  */
5629  if (uses_template_parms (tmpl_args))
5630    return;
5631
5632  for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
5633       arg;
5634       arg = TREE_CHAIN (arg))
5635    if (TREE_PURPOSE (arg))
5636      TREE_PURPOSE (arg) = tsubst_default_argument (fn,
5637						    TREE_VALUE (arg),
5638						    TREE_PURPOSE (arg));
5639}
5640
5641/* Substitute the ARGS into the T, which is a _DECL.  TYPE is the
5642   (already computed) substitution of ARGS into TREE_TYPE (T), if
5643   appropriate.  Return the result of the substitution.  Issue error
5644   and warning messages under control of COMPLAIN.  */
5645
5646static tree
5647tsubst_decl (t, args, type, complain)
5648     tree t;
5649     tree args;
5650     tree type;
5651     tsubst_flags_t complain;
5652{
5653  int saved_lineno;
5654  const char *saved_filename;
5655  tree r = NULL_TREE;
5656  tree in_decl = t;
5657
5658  my_friendly_assert (complain & tf_error, 20011214);
5659
5660  /* Set the filename and linenumber to improve error-reporting.  */
5661  saved_lineno = lineno;
5662  saved_filename = input_filename;
5663  lineno = DECL_SOURCE_LINE (t);
5664  input_filename = DECL_SOURCE_FILE (t);
5665
5666  switch (TREE_CODE (t))
5667    {
5668    case TEMPLATE_DECL:
5669      {
5670	/* We can get here when processing a member template function
5671	   of a template class.  */
5672	tree decl = DECL_TEMPLATE_RESULT (t);
5673	tree spec;
5674	int is_template_template_parm = DECL_TEMPLATE_TEMPLATE_PARM_P (t);
5675
5676	if (!is_template_template_parm)
5677	  {
5678	    /* We might already have an instance of this template.
5679	       The ARGS are for the surrounding class type, so the
5680	       full args contain the tsubst'd args for the context,
5681	       plus the innermost args from the template decl.  */
5682	    tree tmpl_args = DECL_CLASS_TEMPLATE_P (t)
5683	      ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
5684	      : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
5685	    tree full_args;
5686
5687	    full_args = tsubst_template_arg_vector (tmpl_args, args,
5688						    complain);
5689
5690	    /* tsubst_template_arg_vector doesn't copy the vector if
5691	       nothing changed.  But, *something* should have
5692	       changed.  */
5693	    my_friendly_assert (full_args != tmpl_args, 0);
5694
5695	    spec = retrieve_specialization (t, full_args);
5696	    if (spec != NULL_TREE)
5697	      {
5698		r = spec;
5699		break;
5700	      }
5701	  }
5702
5703	/* Make a new template decl.  It will be similar to the
5704	   original, but will record the current template arguments.
5705	   We also create a new function declaration, which is just
5706	   like the old one, but points to this new template, rather
5707	   than the old one.  */
5708	r = copy_decl (t);
5709	my_friendly_assert (DECL_LANG_SPECIFIC (r) != 0, 0);
5710	TREE_CHAIN (r) = NULL_TREE;
5711
5712	if (is_template_template_parm)
5713	  {
5714	    tree new_decl = tsubst (decl, args, complain, in_decl);
5715	    DECL_TEMPLATE_RESULT (r) = new_decl;
5716	    TREE_TYPE (r) = TREE_TYPE (new_decl);
5717	    break;
5718	  }
5719
5720	DECL_CONTEXT (r)
5721	  = tsubst_aggr_type (DECL_CONTEXT (t), args,
5722			      complain, in_decl,
5723			      /*entering_scope=*/1);
5724	DECL_VIRTUAL_CONTEXT (r)
5725	  = tsubst_aggr_type (DECL_VIRTUAL_CONTEXT (t), args,
5726			      complain, in_decl,
5727			      /*entering_scope=*/1);
5728	DECL_TEMPLATE_INFO (r) = build_tree_list (t, args);
5729
5730	if (TREE_CODE (decl) == TYPE_DECL)
5731	  {
5732	    tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
5733	    TREE_TYPE (r) = new_type;
5734	    CLASSTYPE_TI_TEMPLATE (new_type) = r;
5735	    DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
5736	    DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
5737	  }
5738	else
5739	  {
5740	    tree new_decl = tsubst (decl, args, complain, in_decl);
5741
5742	    DECL_TEMPLATE_RESULT (r) = new_decl;
5743	    DECL_TI_TEMPLATE (new_decl) = r;
5744	    TREE_TYPE (r) = TREE_TYPE (new_decl);
5745	    DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
5746	  }
5747
5748	SET_DECL_IMPLICIT_INSTANTIATION (r);
5749	DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
5750	DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
5751
5752	/* The template parameters for this new template are all the
5753	   template parameters for the old template, except the
5754	   outermost level of parameters. */
5755	DECL_TEMPLATE_PARMS (r)
5756	  = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
5757				   complain);
5758
5759	if (PRIMARY_TEMPLATE_P (t))
5760	  DECL_PRIMARY_TEMPLATE (r) = r;
5761
5762	/* We don't partially instantiate partial specializations.  */
5763	if (TREE_CODE (decl) == TYPE_DECL)
5764	  break;
5765
5766	/* Record this partial instantiation.  */
5767	register_specialization (r, t,
5768				 DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)));
5769
5770      }
5771      break;
5772
5773    case FUNCTION_DECL:
5774      {
5775	tree ctx;
5776	tree argvec = NULL_TREE;
5777	tree *friends;
5778	tree gen_tmpl;
5779	int member;
5780	int args_depth;
5781	int parms_depth;
5782
5783	/* Nobody should be tsubst'ing into non-template functions.  */
5784	my_friendly_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE, 0);
5785
5786	if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
5787	  {
5788	    tree spec;
5789
5790	    /* Calculate the most general template of which R is a
5791	       specialization, and the complete set of arguments used to
5792	       specialize R.  */
5793	    gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
5794	    argvec
5795	      = tsubst_template_arg_vector (DECL_TI_ARGS
5796					    (DECL_TEMPLATE_RESULT (gen_tmpl)),
5797					    args, complain);
5798
5799	    /* Check to see if we already have this specialization.  */
5800	    spec = retrieve_specialization (gen_tmpl, argvec);
5801
5802	    if (spec)
5803	      {
5804		r = spec;
5805		break;
5806	      }
5807
5808	    /* We can see more levels of arguments than parameters if
5809	       there was a specialization of a member template, like
5810	       this:
5811
5812	         template <class T> struct S { template <class U> void f(); }
5813		 template <> template <class U> void S<int>::f(U);
5814
5815	       Here, we'll be substituting into the specialization,
5816	       because that's where we can find the code we actually
5817	       want to generate, but we'll have enough arguments for
5818	       the most general template.
5819
5820	       We also deal with the peculiar case:
5821
5822		 template <class T> struct S {
5823		   template <class U> friend void f();
5824		 };
5825		 template <class U> void f() {}
5826		 template S<int>;
5827		 template void f<double>();
5828
5829	       Here, the ARGS for the instantiation of will be {int,
5830	       double}.  But, we only need as many ARGS as there are
5831	       levels of template parameters in CODE_PATTERN.  We are
5832	       careful not to get fooled into reducing the ARGS in
5833	       situations like:
5834
5835		 template <class T> struct S { template <class U> void f(U); }
5836		 template <class T> template <> void S<T>::f(int) {}
5837
5838	       which we can spot because the pattern will be a
5839	       specialization in this case.  */
5840	    args_depth = TMPL_ARGS_DEPTH (args);
5841	    parms_depth =
5842	      TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
5843	    if (args_depth > parms_depth
5844		&& !DECL_TEMPLATE_SPECIALIZATION (t))
5845	      args = get_innermost_template_args (args, parms_depth);
5846	  }
5847	else
5848	  {
5849	    /* This special case arises when we have something like this:
5850
5851	         template <class T> struct S {
5852		   friend void f<int>(int, double);
5853		 };
5854
5855	       Here, the DECL_TI_TEMPLATE for the friend declaration
5856	       will be a LOOKUP_EXPR or an IDENTIFIER_NODE.  We are
5857	       being called from tsubst_friend_function, and we want
5858	       only to create a new decl (R) with appropriate types so
5859	       that we can call determine_specialization.  */
5860	    my_friendly_assert ((TREE_CODE (DECL_TI_TEMPLATE (t))
5861				 == LOOKUP_EXPR)
5862				|| (TREE_CODE (DECL_TI_TEMPLATE (t))
5863				    == IDENTIFIER_NODE), 0);
5864	    gen_tmpl = NULL_TREE;
5865	  }
5866
5867	if (DECL_CLASS_SCOPE_P (t))
5868	  {
5869	    if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
5870	      member = 2;
5871	    else
5872	      member = 1;
5873	    ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
5874				    complain, t,
5875				    /*entering_scope=*/1);
5876	  }
5877	else
5878	  {
5879	    member = 0;
5880	    ctx = DECL_CONTEXT (t);
5881	  }
5882	type = tsubst (type, args, complain, in_decl);
5883	if (type == error_mark_node)
5884	  return error_mark_node;
5885
5886	/* We do NOT check for matching decls pushed separately at this
5887           point, as they may not represent instantiations of this
5888           template, and in any case are considered separate under the
5889           discrete model.  */
5890	r = copy_decl (t);
5891	DECL_USE_TEMPLATE (r) = 0;
5892	TREE_TYPE (r) = type;
5893	/* Clear out the mangled name and RTL for the instantiation.  */
5894	SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
5895	SET_DECL_RTL (r, NULL_RTX);
5896
5897	DECL_CONTEXT (r) = ctx;
5898	DECL_VIRTUAL_CONTEXT (r)
5899	  = tsubst_aggr_type (DECL_VIRTUAL_CONTEXT (t), args,
5900			      complain, t,
5901			      /*entering_scope=*/1);
5902
5903	if (member && DECL_CONV_FN_P (r))
5904	  /* Type-conversion operator.  Reconstruct the name, in
5905	     case it's the name of one of the template's parameters.  */
5906	  DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
5907
5908	DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
5909				     complain, t);
5910	DECL_RESULT (r) = NULL_TREE;
5911
5912	TREE_STATIC (r) = 0;
5913	TREE_PUBLIC (r) = TREE_PUBLIC (t);
5914	DECL_EXTERNAL (r) = 1;
5915	DECL_INTERFACE_KNOWN (r) = 0;
5916	DECL_DEFER_OUTPUT (r) = 0;
5917	TREE_CHAIN (r) = NULL_TREE;
5918	DECL_PENDING_INLINE_INFO (r) = 0;
5919	DECL_PENDING_INLINE_P (r) = 0;
5920	DECL_SAVED_TREE (r) = NULL_TREE;
5921	TREE_USED (r) = 0;
5922	if (DECL_CLONED_FUNCTION (r))
5923	  {
5924	    DECL_CLONED_FUNCTION (r) = tsubst (DECL_CLONED_FUNCTION (t),
5925					       args, complain, t);
5926	    TREE_CHAIN (r) = TREE_CHAIN (DECL_CLONED_FUNCTION (r));
5927	    TREE_CHAIN (DECL_CLONED_FUNCTION (r)) = r;
5928	  }
5929
5930	/* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
5931	   this in the special friend case mentioned above where
5932	   GEN_TMPL is NULL.  */
5933	if (gen_tmpl)
5934	  {
5935	    DECL_TEMPLATE_INFO (r)
5936	      = tree_cons (gen_tmpl, argvec, NULL_TREE);
5937	    SET_DECL_IMPLICIT_INSTANTIATION (r);
5938	    register_specialization (r, gen_tmpl, argvec);
5939
5940	    /* We're not supposed to instantiate default arguments
5941	       until they are called, for a template.  But, for a
5942	       declaration like:
5943
5944	         template <class T> void f ()
5945                 { extern void g(int i = T()); }
5946
5947	       we should do the substitution when the template is
5948	       instantiated.  We handle the member function case in
5949	       instantiate_class_template since the default arguments
5950	       might refer to other members of the class.  */
5951	    if (!member
5952		&& !PRIMARY_TEMPLATE_P (gen_tmpl)
5953		&& !uses_template_parms (argvec))
5954	      tsubst_default_arguments (r);
5955	  }
5956
5957	/* Copy the list of befriending classes.  */
5958	for (friends = &DECL_BEFRIENDING_CLASSES (r);
5959	     *friends;
5960	     friends = &TREE_CHAIN (*friends))
5961	  {
5962	    *friends = copy_node (*friends);
5963	    TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
5964					    args, complain,
5965					    in_decl);
5966	  }
5967
5968	if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
5969	  {
5970	    maybe_retrofit_in_chrg (r);
5971	    if (DECL_CONSTRUCTOR_P (r))
5972	      grok_ctor_properties (ctx, r);
5973	    /* If this is an instantiation of a member template, clone it.
5974	       If it isn't, that'll be handled by
5975	       clone_constructors_and_destructors.  */
5976	    if (PRIMARY_TEMPLATE_P (gen_tmpl))
5977	      clone_function_decl (r, /*update_method_vec_p=*/0);
5978	  }
5979	else if (IDENTIFIER_OPNAME_P (DECL_NAME (r)))
5980	  grok_op_properties (r, DECL_FRIEND_P (r));
5981      }
5982      break;
5983
5984    case PARM_DECL:
5985      {
5986	r = copy_node (t);
5987	if (DECL_TEMPLATE_PARM_P (t))
5988	  SET_DECL_TEMPLATE_PARM_P (r);
5989
5990	TREE_TYPE (r) = type;
5991	c_apply_type_quals_to_decl (cp_type_quals (type), r);
5992
5993	if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
5994	  DECL_INITIAL (r) = TREE_TYPE (r);
5995	else
5996	  DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
5997				     complain, in_decl);
5998
5999	DECL_CONTEXT (r) = NULL_TREE;
6000	if (!DECL_TEMPLATE_PARM_P (r) && PROMOTE_PROTOTYPES
6001	    && INTEGRAL_TYPE_P (type)
6002	    && TYPE_PRECISION (type) < TYPE_PRECISION (integer_type_node))
6003	  DECL_ARG_TYPE (r) = integer_type_node;
6004	if (TREE_CHAIN (t))
6005	  TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args,
6006				   complain, TREE_CHAIN (t));
6007      }
6008      break;
6009
6010    case FIELD_DECL:
6011      {
6012	r = copy_decl (t);
6013	TREE_TYPE (r) = type;
6014	c_apply_type_quals_to_decl (cp_type_quals (type), r);
6015
6016	/* We don't have to set DECL_CONTEXT here; it is set by
6017	   finish_member_declaration.  */
6018	DECL_INITIAL (r) = tsubst_expr (DECL_INITIAL (t), args,
6019					complain, in_decl);
6020	TREE_CHAIN (r) = NULL_TREE;
6021	if (VOID_TYPE_P (type))
6022	  cp_error_at ("instantiation of `%D' as type `%T'", r, type);
6023      }
6024      break;
6025
6026    case USING_DECL:
6027      {
6028	r = copy_node (t);
6029	DECL_INITIAL (r)
6030	  = tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
6031	TREE_CHAIN (r) = NULL_TREE;
6032      }
6033      break;
6034
6035    case TYPE_DECL:
6036      if (TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM
6037	  || t == TYPE_MAIN_DECL (TREE_TYPE (t)))
6038	{
6039	  /* If this is the canonical decl, we don't have to mess with
6040             instantiations, and often we can't (for typename, template
6041	     type parms and such).  Note that TYPE_NAME is not correct for
6042	     the above test if we've copied the type for a typedef.  */
6043	  r = TYPE_NAME (type);
6044	  break;
6045	}
6046
6047      /* Fall through.  */
6048
6049    case VAR_DECL:
6050      {
6051	tree argvec = NULL_TREE;
6052	tree gen_tmpl = NULL_TREE;
6053	tree spec;
6054	tree tmpl = NULL_TREE;
6055	tree ctx;
6056	int local_p;
6057
6058	/* Assume this is a non-local variable.  */
6059	local_p = 0;
6060
6061	if (TYPE_P (CP_DECL_CONTEXT (t)))
6062	  ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
6063				  complain,
6064				  in_decl, /*entering_scope=*/1);
6065	else if (DECL_NAMESPACE_SCOPE_P (t))
6066	  ctx = DECL_CONTEXT (t);
6067	else
6068	  {
6069	    /* Subsequent calls to pushdecl will fill this in.  */
6070	    ctx = NULL_TREE;
6071	    local_p = 1;
6072	  }
6073
6074	/* Check to see if we already have this specialization.  */
6075	if (!local_p)
6076	  {
6077	    tmpl = DECL_TI_TEMPLATE (t);
6078	    gen_tmpl = most_general_template (tmpl);
6079	    argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
6080	    spec = retrieve_specialization (gen_tmpl, argvec);
6081	  }
6082	else
6083	  spec = retrieve_local_specialization (t);
6084
6085	if (spec)
6086	  {
6087	    r = spec;
6088	    break;
6089	  }
6090
6091	r = copy_decl (t);
6092	if (TREE_CODE (r) == VAR_DECL)
6093	  type = complete_type (type);
6094	TREE_TYPE (r) = type;
6095	c_apply_type_quals_to_decl (cp_type_quals (type), r);
6096	DECL_CONTEXT (r) = ctx;
6097	/* Clear out the mangled name and RTL for the instantiation.  */
6098	SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
6099	SET_DECL_RTL (r, NULL_RTX);
6100
6101	/* Don't try to expand the initializer until someone tries to use
6102	   this variable; otherwise we run into circular dependencies.  */
6103	DECL_INITIAL (r) = NULL_TREE;
6104	SET_DECL_RTL (r, NULL_RTX);
6105	DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
6106
6107	/* Even if the original location is out of scope, the newly
6108	   substituted one is not.  */
6109	if (TREE_CODE (r) == VAR_DECL)
6110	  DECL_DEAD_FOR_LOCAL (r) = 0;
6111
6112	if (!local_p)
6113	  {
6114	    /* A static data member declaration is always marked
6115	       external when it is declared in-class, even if an
6116	       initializer is present.  We mimic the non-template
6117	       processing here.  */
6118	    DECL_EXTERNAL (r) = 1;
6119
6120	    register_specialization (r, gen_tmpl, argvec);
6121	    DECL_TEMPLATE_INFO (r) = tree_cons (tmpl, argvec, NULL_TREE);
6122	    SET_DECL_IMPLICIT_INSTANTIATION (r);
6123	  }
6124	else
6125	  register_local_specialization (r, t);
6126
6127	TREE_CHAIN (r) = NULL_TREE;
6128	if (TREE_CODE (r) == VAR_DECL && VOID_TYPE_P (type))
6129	  cp_error_at ("instantiation of `%D' as type `%T'", r, type);
6130	/* Compute the size, alignment, etc. of R.  */
6131	layout_decl (r, 0);
6132      }
6133      break;
6134
6135    default:
6136      abort ();
6137    }
6138
6139  /* Restore the file and line information.  */
6140  lineno = saved_lineno;
6141  input_filename = saved_filename;
6142
6143  return r;
6144}
6145
6146/* Substitue into the ARG_TYPES of a function type.  */
6147
6148static tree
6149tsubst_arg_types (arg_types, args, complain, in_decl)
6150     tree arg_types;
6151     tree args;
6152     tsubst_flags_t complain;
6153     tree in_decl;
6154{
6155  tree remaining_arg_types;
6156  tree type;
6157
6158  if (!arg_types || arg_types == void_list_node)
6159    return arg_types;
6160
6161  remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
6162					  args, complain, in_decl);
6163  if (remaining_arg_types == error_mark_node)
6164    return error_mark_node;
6165
6166  type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
6167  if (type == error_mark_node)
6168    return error_mark_node;
6169  if (VOID_TYPE_P (type))
6170    {
6171      if (complain & tf_error)
6172        {
6173          error ("invalid parameter type `%T'", type);
6174          if (in_decl)
6175            cp_error_at ("in declaration `%D'", in_decl);
6176        }
6177      return error_mark_node;
6178    }
6179
6180  /* Do array-to-pointer, function-to-pointer conversion, and ignore
6181     top-level qualifiers as required.  */
6182  type = TYPE_MAIN_VARIANT (type_decays_to (type));
6183
6184  /* Note that we do not substitute into default arguments here.  The
6185     standard mandates that they be instantiated only when needed,
6186     which is done in build_over_call.  */
6187  return hash_tree_cons (TREE_PURPOSE (arg_types), type,
6188			 remaining_arg_types);
6189
6190}
6191
6192/* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
6193   *not* handle the exception-specification for FNTYPE, because the
6194   initial substitution of explicitly provided template parameters
6195   during argument deduction forbids substitution into the
6196   exception-specification:
6197
6198     [temp.deduct]
6199
6200     All references in the function type of the function template to  the
6201     corresponding template parameters are replaced by the specified tem-
6202     plate argument values.  If a substitution in a template parameter or
6203     in  the function type of the function template results in an invalid
6204     type, type deduction fails.  [Note: The equivalent  substitution  in
6205     exception specifications is done only when the function is instanti-
6206     ated, at which point a program is  ill-formed  if  the  substitution
6207     results in an invalid type.]  */
6208
6209static tree
6210tsubst_function_type (t, args, complain, in_decl)
6211     tree t;
6212     tree args;
6213     tsubst_flags_t complain;
6214     tree in_decl;
6215{
6216  tree return_type;
6217  tree arg_types;
6218  tree fntype;
6219
6220  /* The TYPE_CONTEXT is not used for function/method types.  */
6221  my_friendly_assert (TYPE_CONTEXT (t) == NULL_TREE, 0);
6222
6223  /* Substitute the return type.  */
6224  return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
6225  if (return_type == error_mark_node)
6226    return error_mark_node;
6227
6228  /* Substitue the argument types.  */
6229  arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
6230				complain, in_decl);
6231  if (arg_types == error_mark_node)
6232    return error_mark_node;
6233
6234  /* Construct a new type node and return it.  */
6235  if (TREE_CODE (t) == FUNCTION_TYPE)
6236    fntype = build_function_type (return_type, arg_types);
6237  else
6238    {
6239      tree r = TREE_TYPE (TREE_VALUE (arg_types));
6240      if (! IS_AGGR_TYPE (r))
6241	{
6242	  /* [temp.deduct]
6243
6244	     Type deduction may fail for any of the following
6245	     reasons:
6246
6247	     -- Attempting to create "pointer to member of T" when T
6248	     is not a class type.  */
6249	  if (complain & tf_error)
6250	    error ("creating pointer to member function of non-class type `%T'",
6251		      r);
6252	  return error_mark_node;
6253	}
6254
6255      fntype = build_cplus_method_type (r, return_type, TREE_CHAIN
6256					(arg_types));
6257    }
6258  fntype = cp_build_qualified_type_real (fntype, TYPE_QUALS (t), complain);
6259  fntype = build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
6260
6261  return fntype;
6262}
6263
6264/* Substitute into the PARMS of a call-declarator.  */
6265
6266static tree
6267tsubst_call_declarator_parms (parms, args, complain, in_decl)
6268     tree parms;
6269     tree args;
6270     tsubst_flags_t complain;
6271     tree in_decl;
6272{
6273  tree new_parms;
6274  tree type;
6275  tree defarg;
6276
6277  if (!parms || parms == void_list_node)
6278    return parms;
6279
6280  new_parms = tsubst_call_declarator_parms (TREE_CHAIN (parms),
6281					    args, complain, in_decl);
6282
6283  /* Figure out the type of this parameter.  */
6284  type = tsubst (TREE_VALUE (parms), args, complain, in_decl);
6285
6286  /* Figure out the default argument as well.  Note that we use
6287     tsubst_expr since the default argument is really an expression.  */
6288  defarg = tsubst_expr (TREE_PURPOSE (parms), args, complain, in_decl);
6289
6290  /* Chain this parameter on to the front of those we have already
6291     processed.  We don't use hash_tree_cons because that function
6292     doesn't check TREE_PARMLIST.  */
6293  new_parms = tree_cons (defarg, type, new_parms);
6294
6295  /* And note that these are parameters.  */
6296  TREE_PARMLIST (new_parms) = 1;
6297
6298  return new_parms;
6299}
6300
6301/* Take the tree structure T and replace template parameters used
6302   therein with the argument vector ARGS.  IN_DECL is an associated
6303   decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
6304   Issue error and warning messages under control of COMPLAIN.  Note
6305   that we must be relatively non-tolerant of extensions here, in
6306   order to preserve conformance; if we allow substitutions that
6307   should not be allowed, we may allow argument deductions that should
6308   not succeed, and therefore report ambiguous overload situations
6309   where there are none.  In theory, we could allow the substitution,
6310   but indicate that it should have failed, and allow our caller to
6311   make sure that the right thing happens, but we don't try to do this
6312   yet.
6313
6314   This function is used for dealing with types, decls and the like;
6315   for expressions, use tsubst_expr or tsubst_copy.  */
6316
6317tree
6318tsubst (t, args, complain, in_decl)
6319     tree t, args;
6320     tsubst_flags_t complain;
6321     tree in_decl;
6322{
6323  tree type, r;
6324
6325  if (t == NULL_TREE || t == error_mark_node
6326      || t == integer_type_node
6327      || t == void_type_node
6328      || t == char_type_node
6329      || TREE_CODE (t) == NAMESPACE_DECL)
6330    return t;
6331
6332  if (TREE_CODE (t) == IDENTIFIER_NODE)
6333    type = IDENTIFIER_TYPE_VALUE (t);
6334  else
6335    type = TREE_TYPE (t);
6336  if (type == unknown_type_node)
6337    abort ();
6338
6339  if (type && TREE_CODE (t) != FUNCTION_DECL
6340      && TREE_CODE (t) != TYPENAME_TYPE
6341      && TREE_CODE (t) != TEMPLATE_DECL
6342      && TREE_CODE (t) != IDENTIFIER_NODE
6343      && TREE_CODE (t) != FUNCTION_TYPE
6344      && TREE_CODE (t) != METHOD_TYPE)
6345    type = tsubst (type, args, complain, in_decl);
6346  if (type == error_mark_node)
6347    return error_mark_node;
6348
6349  if (DECL_P (t))
6350    return tsubst_decl (t, args, type, complain);
6351
6352  switch (TREE_CODE (t))
6353    {
6354    case RECORD_TYPE:
6355    case UNION_TYPE:
6356    case ENUMERAL_TYPE:
6357      return tsubst_aggr_type (t, args, complain, in_decl,
6358			       /*entering_scope=*/0);
6359
6360    case ERROR_MARK:
6361    case IDENTIFIER_NODE:
6362    case VOID_TYPE:
6363    case REAL_TYPE:
6364    case COMPLEX_TYPE:
6365    case VECTOR_TYPE:
6366    case BOOLEAN_TYPE:
6367    case INTEGER_CST:
6368    case REAL_CST:
6369    case STRING_CST:
6370      return t;
6371
6372    case INTEGER_TYPE:
6373      if (t == integer_type_node)
6374	return t;
6375
6376      if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
6377	  && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
6378	return t;
6379
6380      {
6381	tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
6382
6383	max = tsubst_expr (omax, args, complain, in_decl);
6384	if (max == error_mark_node)
6385	  return error_mark_node;
6386
6387	/* See if we can reduce this expression to something simpler.  */
6388	max = maybe_fold_nontype_arg (max);
6389	if (!processing_template_decl)
6390	  max = decl_constant_value (max);
6391
6392	if (processing_template_decl
6393	    /* When providing explicit arguments to a template
6394	       function, but leaving some arguments for subsequent
6395	       deduction, MAX may be template-dependent even if we're
6396	       not PROCESSING_TEMPLATE_DECL.  We still need to check for
6397	       template parms, though; MAX won't be an INTEGER_CST for
6398	       dynamic arrays, either.  */
6399	    || (TREE_CODE (max) != INTEGER_CST
6400		&& uses_template_parms (max)))
6401	  {
6402	    tree itype = make_node (INTEGER_TYPE);
6403	    TYPE_MIN_VALUE (itype) = size_zero_node;
6404	    TYPE_MAX_VALUE (itype) = build_min (MINUS_EXPR, sizetype, max,
6405						integer_one_node);
6406	    return itype;
6407	  }
6408
6409	if (integer_zerop (omax))
6410	  {
6411	    /* Still allow an explicit array of size zero.  */
6412	    if (pedantic)
6413	      pedwarn ("creating array with size zero");
6414	  }
6415	else if (integer_zerop (max)
6416		 || (TREE_CODE (max) == INTEGER_CST
6417		     && INT_CST_LT (max, integer_zero_node)))
6418	  {
6419	    /* [temp.deduct]
6420
6421	       Type deduction may fail for any of the following
6422	       reasons:
6423
6424		 Attempting to create an array with a size that is
6425		 zero or negative.  */
6426	    if (complain & tf_error)
6427	      error ("creating array with size zero (`%E')", max);
6428
6429	    return error_mark_node;
6430	  }
6431
6432	return compute_array_index_type (NULL_TREE, max);
6433      }
6434
6435    case TEMPLATE_TYPE_PARM:
6436    case TEMPLATE_TEMPLATE_PARM:
6437    case BOUND_TEMPLATE_TEMPLATE_PARM:
6438    case TEMPLATE_PARM_INDEX:
6439      {
6440	int idx;
6441	int level;
6442	int levels;
6443
6444	r = NULL_TREE;
6445
6446	if (TREE_CODE (t) == TEMPLATE_TYPE_PARM
6447	    || TREE_CODE (t) == TEMPLATE_TEMPLATE_PARM
6448	    || TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
6449	  {
6450	    idx = TEMPLATE_TYPE_IDX (t);
6451	    level = TEMPLATE_TYPE_LEVEL (t);
6452	  }
6453	else
6454	  {
6455	    idx = TEMPLATE_PARM_IDX (t);
6456	    level = TEMPLATE_PARM_LEVEL (t);
6457	  }
6458
6459	if (TREE_VEC_LENGTH (args) > 0)
6460	  {
6461	    tree arg = NULL_TREE;
6462
6463	    levels = TMPL_ARGS_DEPTH (args);
6464	    if (level <= levels)
6465	      arg = TMPL_ARG (args, level, idx);
6466
6467	    if (arg == error_mark_node)
6468	      return error_mark_node;
6469	    else if (arg != NULL_TREE)
6470	      {
6471		if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
6472		  {
6473		    my_friendly_assert (TYPE_P (arg), 0);
6474		    return cp_build_qualified_type_real
6475		      (arg, cp_type_quals (arg) | cp_type_quals (t),
6476		       complain | tf_ignore_bad_quals);
6477		  }
6478		else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
6479		  {
6480		    /* We are processing a type constructed from
6481		       a template template parameter */
6482		    tree argvec = tsubst (TYPE_TI_ARGS (t),
6483					  args, complain, in_decl);
6484		    if (argvec == error_mark_node)
6485		      return error_mark_node;
6486
6487		    /* We can get a TEMPLATE_TEMPLATE_PARM here when
6488		       we are resolving nested-types in the signature of
6489		       a member function templates.
6490		       Otherwise ARG is a TEMPLATE_DECL and is the real
6491		       template to be instantiated.  */
6492		    if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
6493		      arg = TYPE_NAME (arg);
6494
6495		    r = lookup_template_class (arg,
6496					       argvec, in_decl,
6497					       DECL_CONTEXT (arg),
6498					       /*entering_scope=*/0,
6499	                                       complain);
6500		    return cp_build_qualified_type_real
6501		      (r, TYPE_QUALS (t), complain);
6502		  }
6503		else
6504		  /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
6505		  return arg;
6506	      }
6507	  }
6508	else
6509	  abort ();
6510
6511	if (level == 1)
6512	  /* This can happen during the attempted tsubst'ing in
6513	     unify.  This means that we don't yet have any information
6514	     about the template parameter in question.  */
6515	  return t;
6516
6517	/* If we get here, we must have been looking at a parm for a
6518	   more deeply nested template.  Make a new version of this
6519	   template parameter, but with a lower level.  */
6520	switch (TREE_CODE (t))
6521	  {
6522	  case TEMPLATE_TYPE_PARM:
6523	  case TEMPLATE_TEMPLATE_PARM:
6524	  case BOUND_TEMPLATE_TEMPLATE_PARM:
6525	    if (cp_type_quals (t))
6526	      {
6527		r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
6528 		r = cp_build_qualified_type_real
6529 		  (r, cp_type_quals (t),
6530		   complain | (TREE_CODE (t) == TEMPLATE_TYPE_PARM
6531			       ? tf_ignore_bad_quals : 0));
6532	      }
6533	    else
6534	      {
6535		r = copy_type (t);
6536		TEMPLATE_TYPE_PARM_INDEX (r)
6537		  = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
6538						r, levels);
6539		TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
6540		TYPE_MAIN_VARIANT (r) = r;
6541		TYPE_POINTER_TO (r) = NULL_TREE;
6542		TYPE_REFERENCE_TO (r) = NULL_TREE;
6543
6544		if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
6545		  {
6546		    tree argvec = tsubst (TYPE_TI_ARGS (t), args,
6547					  complain, in_decl);
6548		    if (argvec == error_mark_node)
6549		      return error_mark_node;
6550
6551		    TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
6552		      = tree_cons (TYPE_TI_TEMPLATE (t), argvec, NULL_TREE);
6553		  }
6554	      }
6555	    break;
6556
6557	  case TEMPLATE_PARM_INDEX:
6558	    r = reduce_template_parm_level (t, type, levels);
6559	    break;
6560
6561	  default:
6562	    abort ();
6563	  }
6564
6565	return r;
6566      }
6567
6568    case TREE_LIST:
6569      {
6570	tree purpose, value, chain, result;
6571
6572	if (t == void_list_node)
6573	  return t;
6574
6575	purpose = TREE_PURPOSE (t);
6576	if (purpose)
6577	  {
6578	    purpose = tsubst (purpose, args, complain, in_decl);
6579	    if (purpose == error_mark_node)
6580	      return error_mark_node;
6581	  }
6582	value = TREE_VALUE (t);
6583	if (value)
6584	  {
6585	    value = tsubst (value, args, complain, in_decl);
6586	    if (value == error_mark_node)
6587	      return error_mark_node;
6588	  }
6589	chain = TREE_CHAIN (t);
6590	if (chain && chain != void_type_node)
6591	  {
6592	    chain = tsubst (chain, args, complain, in_decl);
6593	    if (chain == error_mark_node)
6594	      return error_mark_node;
6595	  }
6596	if (purpose == TREE_PURPOSE (t)
6597	    && value == TREE_VALUE (t)
6598	    && chain == TREE_CHAIN (t))
6599	  return t;
6600	if (TREE_PARMLIST (t))
6601	  {
6602	    result = tree_cons (purpose, value, chain);
6603	    TREE_PARMLIST (result) = 1;
6604	  }
6605	else
6606	  result = hash_tree_cons (purpose, value, chain);
6607	return result;
6608      }
6609    case TREE_VEC:
6610      if (type != NULL_TREE)
6611	{
6612	  /* A binfo node.  We always need to make a copy, of the node
6613	     itself and of its BINFO_BASETYPES.  */
6614
6615	  t = copy_node (t);
6616
6617	  /* Make sure type isn't a typedef copy.  */
6618	  type = BINFO_TYPE (TYPE_BINFO (type));
6619
6620	  TREE_TYPE (t) = complete_type (type);
6621	  if (IS_AGGR_TYPE (type))
6622	    {
6623	      BINFO_VTABLE (t) = TYPE_BINFO_VTABLE (type);
6624	      BINFO_VIRTUALS (t) = TYPE_BINFO_VIRTUALS (type);
6625	      if (TYPE_BINFO_BASETYPES (type) != NULL_TREE)
6626		BINFO_BASETYPES (t) = copy_node (TYPE_BINFO_BASETYPES (type));
6627	    }
6628	  return t;
6629	}
6630
6631      /* Otherwise, a vector of template arguments.  */
6632      return tsubst_template_arg_vector (t, args, complain);
6633
6634    case POINTER_TYPE:
6635    case REFERENCE_TYPE:
6636      {
6637	enum tree_code code;
6638
6639	if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
6640	  return t;
6641
6642	code = TREE_CODE (t);
6643
6644
6645	/* [temp.deduct]
6646
6647	   Type deduction may fail for any of the following
6648	   reasons:
6649
6650	   -- Attempting to create a pointer to reference type.
6651	   -- Attempting to create a reference to a reference type or
6652	      a reference to void.  */
6653	if (TREE_CODE (type) == REFERENCE_TYPE
6654	    || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
6655	  {
6656	    static int   last_line = 0;
6657	    static const char* last_file = 0;
6658
6659	    /* We keep track of the last time we issued this error
6660	       message to avoid spewing a ton of messages during a
6661	       single bad template instantiation.  */
6662	    if (complain & tf_error
6663		&& (last_line != lineno || last_file != input_filename))
6664	      {
6665		if (TREE_CODE (type) == VOID_TYPE)
6666		  error ("forming reference to void");
6667		else
6668		  error ("forming %s to reference type `%T'",
6669			    (code == POINTER_TYPE) ? "pointer" : "reference",
6670			    type);
6671		last_line = lineno;
6672		last_file = input_filename;
6673	      }
6674
6675	    return error_mark_node;
6676	  }
6677	else if (code == POINTER_TYPE)
6678	  {
6679	    r = build_pointer_type (type);
6680	    if (TREE_CODE (type) == METHOD_TYPE)
6681	      r = build_ptrmemfunc_type (r);
6682	  }
6683	else
6684	  r = build_reference_type (type);
6685	r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
6686
6687	if (r != error_mark_node)
6688	  /* Will this ever be needed for TYPE_..._TO values?  */
6689	  layout_type (r);
6690
6691	return r;
6692      }
6693    case OFFSET_TYPE:
6694      {
6695	r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
6696	if (r == error_mark_node || !IS_AGGR_TYPE (r))
6697	  {
6698	    /* [temp.deduct]
6699
6700	       Type deduction may fail for any of the following
6701	       reasons:
6702
6703	       -- Attempting to create "pointer to member of T" when T
6704	          is not a class type.  */
6705	    if (complain & tf_error)
6706	      error ("creating pointer to member of non-class type `%T'", r);
6707	    return error_mark_node;
6708	  }
6709	if (TREE_CODE (type) == REFERENCE_TYPE)
6710	  {
6711	    if (complain)
6712	      error ("creating pointer to member reference type `%T'", type);
6713
6714	    return error_mark_node;
6715	  }
6716	my_friendly_assert (TREE_CODE (type) != METHOD_TYPE, 20011231);
6717	if (TREE_CODE (type) == FUNCTION_TYPE)
6718	  /* This is really a method type. The cv qualifiers of the
6719	     this pointer should _not_ be determined by the cv
6720	     qualifiers of the class type.  They should be held
6721	     somewhere in the FUNCTION_TYPE, but we don't do that at
6722	     the moment.  Consider
6723	        typedef void (Func) () const;
6724
6725		template <typename T1> void Foo (Func T1::*);
6726
6727	      */
6728	  return build_cplus_method_type (TYPE_MAIN_VARIANT (r),
6729					  TREE_TYPE (type),
6730					  TYPE_ARG_TYPES (type));
6731	else
6732	  return build_offset_type (r, type);
6733      }
6734    case FUNCTION_TYPE:
6735    case METHOD_TYPE:
6736      {
6737	tree fntype;
6738	tree raises;
6739
6740	fntype = tsubst_function_type (t, args, complain, in_decl);
6741	if (fntype == error_mark_node)
6742	  return error_mark_node;
6743
6744	/* Substitue the exception specification. */
6745	raises = TYPE_RAISES_EXCEPTIONS (t);
6746	if (raises)
6747	  {
6748	    tree   list = NULL_TREE;
6749
6750	    if (! TREE_VALUE (raises))
6751	      list = raises;
6752	    else
6753	      for (; raises != NULL_TREE; raises = TREE_CHAIN (raises))
6754	        {
6755	          tree spec = TREE_VALUE (raises);
6756
6757	          spec = tsubst (spec, args, complain, in_decl);
6758	          if (spec == error_mark_node)
6759	            return spec;
6760	          list = add_exception_specifier (list, spec, complain);
6761	        }
6762	    fntype = build_exception_variant (fntype, list);
6763	  }
6764	return fntype;
6765      }
6766    case ARRAY_TYPE:
6767      {
6768	tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
6769	if (domain == error_mark_node)
6770	  return error_mark_node;
6771
6772	/* As an optimization, we avoid regenerating the array type if
6773	   it will obviously be the same as T.  */
6774	if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
6775	  return t;
6776
6777	/* These checks should match the ones in grokdeclarator.
6778
6779	   [temp.deduct]
6780
6781	   The deduction may fail for any of the following reasons:
6782
6783	   -- Attempting to create an array with an element type that
6784	      is void, a function type, or a reference type.  */
6785	if (TREE_CODE (type) == VOID_TYPE
6786	    || TREE_CODE (type) == FUNCTION_TYPE
6787	    || TREE_CODE (type) == REFERENCE_TYPE)
6788	  {
6789	    if (complain & tf_error)
6790	      error ("creating array of `%T'", type);
6791	    return error_mark_node;
6792	  }
6793
6794	r = build_cplus_array_type (type, domain);
6795	return r;
6796      }
6797
6798    case PLUS_EXPR:
6799    case MINUS_EXPR:
6800      {
6801	tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
6802	tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
6803
6804	if (e1 == error_mark_node || e2 == error_mark_node)
6805	  return error_mark_node;
6806
6807	return fold (build (TREE_CODE (t), TREE_TYPE (t), e1, e2));
6808      }
6809
6810    case NEGATE_EXPR:
6811    case NOP_EXPR:
6812      {
6813	tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
6814	if (e == error_mark_node)
6815	  return error_mark_node;
6816
6817	return fold (build (TREE_CODE (t), TREE_TYPE (t), e));
6818      }
6819
6820    case TYPENAME_TYPE:
6821      {
6822	tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
6823				     in_decl, /*entering_scope=*/1);
6824	tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
6825			      complain, in_decl);
6826
6827	if (ctx == error_mark_node || f == error_mark_node)
6828	  return error_mark_node;
6829
6830	if (!IS_AGGR_TYPE (ctx))
6831	  {
6832	    if (complain & tf_error)
6833	      error ("`%T' is not a class, struct, or union type",
6834			ctx);
6835	    return error_mark_node;
6836	  }
6837	else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
6838	  {
6839	    /* Normally, make_typename_type does not require that the CTX
6840	       have complete type in order to allow things like:
6841
6842	         template <class T> struct S { typename S<T>::X Y; };
6843
6844	       But, such constructs have already been resolved by this
6845	       point, so here CTX really should have complete type, unless
6846	       it's a partial instantiation.  */
6847	    ctx = complete_type (ctx);
6848	    if (!COMPLETE_TYPE_P (ctx))
6849	      {
6850		if (complain & tf_error)
6851		  incomplete_type_error (NULL_TREE, ctx);
6852		return error_mark_node;
6853	      }
6854	  }
6855
6856	f = make_typename_type (ctx, f,
6857				(complain & tf_error) | tf_keep_type_decl);
6858	if (f == error_mark_node)
6859	  return f;
6860 	if (TREE_CODE (f) == TYPE_DECL)
6861 	  {
6862	    complain |= tf_ignore_bad_quals;
6863 	    f = TREE_TYPE (f);
6864 	  }
6865
6866 	return cp_build_qualified_type_real
6867 	  (f, cp_type_quals (f) | cp_type_quals (t), complain);
6868      }
6869
6870    case UNBOUND_CLASS_TEMPLATE:
6871      {
6872	tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
6873				     in_decl, /*entering_scope=*/1);
6874	tree name = TYPE_IDENTIFIER (t);
6875
6876	if (ctx == error_mark_node || name == error_mark_node)
6877	  return error_mark_node;
6878
6879	return make_unbound_class_template (ctx, name, complain);
6880      }
6881
6882    case INDIRECT_REF:
6883      {
6884	tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
6885	if (e == error_mark_node)
6886	  return error_mark_node;
6887	return make_pointer_declarator (type, e);
6888      }
6889
6890    case ADDR_EXPR:
6891      {
6892	tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
6893	if (e == error_mark_node)
6894	  return error_mark_node;
6895	return make_reference_declarator (type, e);
6896      }
6897
6898    case ARRAY_REF:
6899      {
6900	tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
6901	tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl);
6902	if (e1 == error_mark_node || e2 == error_mark_node)
6903	  return error_mark_node;
6904
6905	return build_nt (ARRAY_REF, e1, e2, tsubst_expr);
6906      }
6907
6908    case CALL_EXPR:
6909      {
6910	tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
6911	tree e2 = (tsubst_call_declarator_parms
6912		   (CALL_DECLARATOR_PARMS (t), args, complain, in_decl));
6913	tree e3 = tsubst (CALL_DECLARATOR_EXCEPTION_SPEC (t), args,
6914			  complain, in_decl);
6915
6916	if (e1 == error_mark_node || e2 == error_mark_node
6917	    || e3 == error_mark_node)
6918	  return error_mark_node;
6919
6920	return make_call_declarator (e1, e2, CALL_DECLARATOR_QUALS (t), e3);
6921      }
6922
6923    case SCOPE_REF:
6924      {
6925	tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
6926	tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
6927	if (e1 == error_mark_node || e2 == error_mark_node)
6928	  return error_mark_node;
6929
6930	return build_nt (TREE_CODE (t), e1, e2);
6931      }
6932
6933    case TYPEOF_TYPE:
6934      {
6935	tree e1 = tsubst_expr (TYPE_FIELDS (t), args, complain, in_decl);
6936	if (e1 == error_mark_node)
6937	  return error_mark_node;
6938
6939	return TREE_TYPE (e1);
6940      }
6941
6942    default:
6943      sorry ("use of `%s' in template",
6944	     tree_code_name [(int) TREE_CODE (t)]);
6945      return error_mark_node;
6946    }
6947}
6948
6949/* Like tsubst, but deals with expressions.  This function just replaces
6950   template parms; to finish processing the resultant expression, use
6951   tsubst_expr.  */
6952
6953tree
6954tsubst_copy (t, args, complain, in_decl)
6955     tree t, args;
6956     tsubst_flags_t complain;
6957     tree in_decl;
6958{
6959  enum tree_code code;
6960  tree r;
6961
6962  if (t == NULL_TREE || t == error_mark_node)
6963    return t;
6964
6965  code = TREE_CODE (t);
6966
6967  switch (code)
6968    {
6969    case PARM_DECL:
6970      return do_identifier (DECL_NAME (t), 0, NULL_TREE);
6971
6972    case CONST_DECL:
6973      {
6974	tree enum_type;
6975	tree v;
6976
6977	if (!DECL_CONTEXT (t))
6978	  /* This is a global enumeration constant.  */
6979	  return t;
6980
6981	/* Unfortunately, we cannot just call lookup_name here.
6982	   Consider:
6983
6984	     template <int I> int f() {
6985	     enum E { a = I };
6986	     struct S { void g() { E e = a; } };
6987	     };
6988
6989	   When we instantiate f<7>::S::g(), say, lookup_name is not
6990	   clever enough to find f<7>::a.  */
6991	enum_type
6992	  = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
6993			      /*entering_scope=*/0);
6994
6995	for (v = TYPE_VALUES (enum_type);
6996	     v != NULL_TREE;
6997	     v = TREE_CHAIN (v))
6998	  if (TREE_PURPOSE (v) == DECL_NAME (t))
6999	    return TREE_VALUE (v);
7000
7001	  /* We didn't find the name.  That should never happen; if
7002	     name-lookup found it during preliminary parsing, we
7003	     should find it again here during instantiation.  */
7004	abort ();
7005      }
7006      return t;
7007
7008    case FIELD_DECL:
7009      if (DECL_CONTEXT (t))
7010	{
7011	  tree ctx;
7012
7013	  ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
7014				  /*entering_scope=*/1);
7015	  if (ctx != DECL_CONTEXT (t))
7016	    return lookup_field (ctx, DECL_NAME (t), 0, 0);
7017	}
7018      return t;
7019
7020    case VAR_DECL:
7021    case FUNCTION_DECL:
7022      if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
7023	t = tsubst (t, args, complain, in_decl);
7024      mark_used (t);
7025      return t;
7026
7027    case TEMPLATE_DECL:
7028      if (is_member_template (t))
7029	return tsubst (t, args, complain, in_decl);
7030      else
7031	return t;
7032
7033    case LOOKUP_EXPR:
7034      {
7035	/* We must tsubst into a LOOKUP_EXPR in case the names to
7036	   which it refers is a conversion operator; in that case the
7037	   name will change.  We avoid making unnecessary copies,
7038	   however.  */
7039
7040	tree id = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
7041
7042	if (id != TREE_OPERAND (t, 0))
7043	  {
7044	    r = build_nt (LOOKUP_EXPR, id);
7045	    LOOKUP_EXPR_GLOBAL (r) = LOOKUP_EXPR_GLOBAL (t);
7046	    t = r;
7047	  }
7048
7049	return t;
7050      }
7051
7052    case CAST_EXPR:
7053    case REINTERPRET_CAST_EXPR:
7054    case CONST_CAST_EXPR:
7055    case STATIC_CAST_EXPR:
7056    case DYNAMIC_CAST_EXPR:
7057    case NOP_EXPR:
7058      return build1
7059	(code, tsubst (TREE_TYPE (t), args, complain, in_decl),
7060	 tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
7061
7062    case INDIRECT_REF:
7063    case NEGATE_EXPR:
7064    case TRUTH_NOT_EXPR:
7065    case BIT_NOT_EXPR:
7066    case ADDR_EXPR:
7067    case CONVERT_EXPR:      /* Unary + */
7068    case SIZEOF_EXPR:
7069    case ALIGNOF_EXPR:
7070    case ARROW_EXPR:
7071    case THROW_EXPR:
7072    case TYPEID_EXPR:
7073    case REALPART_EXPR:
7074    case IMAGPART_EXPR:
7075      return build1
7076	(code, tsubst (TREE_TYPE (t), args, complain, in_decl),
7077	 tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
7078
7079    case PLUS_EXPR:
7080    case MINUS_EXPR:
7081    case MULT_EXPR:
7082    case TRUNC_DIV_EXPR:
7083    case CEIL_DIV_EXPR:
7084    case FLOOR_DIV_EXPR:
7085    case ROUND_DIV_EXPR:
7086    case EXACT_DIV_EXPR:
7087    case BIT_AND_EXPR:
7088    case BIT_ANDTC_EXPR:
7089    case BIT_IOR_EXPR:
7090    case BIT_XOR_EXPR:
7091    case TRUNC_MOD_EXPR:
7092    case FLOOR_MOD_EXPR:
7093    case TRUTH_ANDIF_EXPR:
7094    case TRUTH_ORIF_EXPR:
7095    case TRUTH_AND_EXPR:
7096    case TRUTH_OR_EXPR:
7097    case RSHIFT_EXPR:
7098    case LSHIFT_EXPR:
7099    case RROTATE_EXPR:
7100    case LROTATE_EXPR:
7101    case EQ_EXPR:
7102    case NE_EXPR:
7103    case MAX_EXPR:
7104    case MIN_EXPR:
7105    case LE_EXPR:
7106    case GE_EXPR:
7107    case LT_EXPR:
7108    case GT_EXPR:
7109    case COMPONENT_REF:
7110    case ARRAY_REF:
7111    case COMPOUND_EXPR:
7112    case SCOPE_REF:
7113    case DOTSTAR_EXPR:
7114    case MEMBER_REF:
7115    case PREDECREMENT_EXPR:
7116    case PREINCREMENT_EXPR:
7117    case POSTDECREMENT_EXPR:
7118    case POSTINCREMENT_EXPR:
7119      return build_nt
7120	(code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
7121	 tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
7122
7123    case CALL_EXPR:
7124      {
7125	tree fn = TREE_OPERAND (t, 0);
7126	if (is_overloaded_fn (fn))
7127	  fn = tsubst_copy (get_first_fn (fn), args, complain, in_decl);
7128	else
7129	  /* Sometimes FN is a LOOKUP_EXPR.  */
7130	  fn = tsubst_copy (fn, args, complain, in_decl);
7131	return build_nt
7132	  (code, fn, tsubst_copy (TREE_OPERAND (t, 1), args, complain,
7133				  in_decl),
7134	   NULL_TREE);
7135      }
7136
7137    case METHOD_CALL_EXPR:
7138      {
7139	tree name = TREE_OPERAND (t, 0);
7140	if (TREE_CODE (name) == BIT_NOT_EXPR)
7141	  {
7142	    name = tsubst_copy (TREE_OPERAND (name, 0), args,
7143				complain, in_decl);
7144	    name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
7145	  }
7146	else if (TREE_CODE (name) == SCOPE_REF
7147		 && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
7148	  {
7149	    tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
7150				     complain, in_decl);
7151	    name = TREE_OPERAND (name, 1);
7152	    name = tsubst_copy (TREE_OPERAND (name, 0), args,
7153				complain, in_decl);
7154	    name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
7155	    name = build_nt (SCOPE_REF, base, name);
7156	  }
7157	else
7158	  name = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
7159	return build_nt
7160	  (code, name, tsubst_copy (TREE_OPERAND (t, 1), args,
7161				    complain, in_decl),
7162	   tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl),
7163	   NULL_TREE);
7164      }
7165
7166    case STMT_EXPR:
7167      /* This processing should really occur in tsubst_expr, However,
7168	 tsubst_expr does not recurse into expressions, since it
7169	 assumes that there aren't any statements inside them.
7170	 Instead, it simply calls build_expr_from_tree.  So, we need
7171	 to expand the STMT_EXPR here.  */
7172      if (!processing_template_decl)
7173	{
7174	  tree stmt_expr = begin_stmt_expr ();
7175	  tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl);
7176	  return finish_stmt_expr (stmt_expr);
7177	}
7178
7179      return t;
7180
7181    case COND_EXPR:
7182    case MODOP_EXPR:
7183    case PSEUDO_DTOR_EXPR:
7184      {
7185	r = build_nt
7186	  (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
7187	   tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
7188	   tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
7189	return r;
7190      }
7191
7192    case NEW_EXPR:
7193      {
7194	r = build_nt
7195	(code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
7196	 tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
7197	 tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
7198	NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
7199	return r;
7200      }
7201
7202    case DELETE_EXPR:
7203      {
7204	r = build_nt
7205	(code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
7206	 tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
7207	DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
7208	DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
7209	return r;
7210      }
7211
7212    case TEMPLATE_ID_EXPR:
7213      {
7214        /* Substituted template arguments */
7215	tree targs = tsubst_copy (TREE_OPERAND (t, 1), args, complain,
7216				  in_decl);
7217
7218	if (targs && TREE_CODE (targs) == TREE_LIST)
7219	  {
7220	    tree chain;
7221	    for (chain = targs; chain; chain = TREE_CHAIN (chain))
7222	      TREE_VALUE (chain) = maybe_fold_nontype_arg (TREE_VALUE (chain));
7223	  }
7224	else if (targs)
7225	  {
7226	    int i;
7227	    for (i = 0; i < TREE_VEC_LENGTH (targs); ++i)
7228	      TREE_VEC_ELT (targs, i)
7229		= maybe_fold_nontype_arg (TREE_VEC_ELT (targs, i));
7230	  }
7231
7232	return lookup_template_function
7233	  (tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl), targs);
7234      }
7235
7236    case TREE_LIST:
7237      {
7238	tree purpose, value, chain;
7239
7240	if (t == void_list_node)
7241	  return t;
7242
7243	purpose = TREE_PURPOSE (t);
7244	if (purpose)
7245	  purpose = tsubst_copy (purpose, args, complain, in_decl);
7246	value = TREE_VALUE (t);
7247	if (value)
7248	  value = tsubst_copy (value, args, complain, in_decl);
7249	chain = TREE_CHAIN (t);
7250	if (chain && chain != void_type_node)
7251	  chain = tsubst_copy (chain, args, complain, in_decl);
7252	if (purpose == TREE_PURPOSE (t)
7253	    && value == TREE_VALUE (t)
7254	    && chain == TREE_CHAIN (t))
7255	  return t;
7256	return tree_cons (purpose, value, chain);
7257      }
7258
7259    case RECORD_TYPE:
7260    case UNION_TYPE:
7261    case ENUMERAL_TYPE:
7262    case INTEGER_TYPE:
7263    case TEMPLATE_TYPE_PARM:
7264    case TEMPLATE_TEMPLATE_PARM:
7265    case BOUND_TEMPLATE_TEMPLATE_PARM:
7266    case TEMPLATE_PARM_INDEX:
7267    case POINTER_TYPE:
7268    case REFERENCE_TYPE:
7269    case OFFSET_TYPE:
7270    case FUNCTION_TYPE:
7271    case METHOD_TYPE:
7272    case ARRAY_TYPE:
7273    case TYPENAME_TYPE:
7274    case UNBOUND_CLASS_TEMPLATE:
7275    case TYPEOF_TYPE:
7276    case TYPE_DECL:
7277      return tsubst (t, args, complain, in_decl);
7278
7279    case IDENTIFIER_NODE:
7280      if (IDENTIFIER_TYPENAME_P (t))
7281	{
7282	  tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
7283	  return mangle_conv_op_name_for_type (new_type);
7284	}
7285      else
7286	return t;
7287
7288    case CONSTRUCTOR:
7289      {
7290	r = build
7291	  (CONSTRUCTOR, tsubst (TREE_TYPE (t), args, complain, in_decl),
7292	   NULL_TREE, tsubst_copy (CONSTRUCTOR_ELTS (t), args,
7293				   complain, in_decl));
7294	TREE_HAS_CONSTRUCTOR (r) = TREE_HAS_CONSTRUCTOR (t);
7295	return r;
7296      }
7297
7298    case VA_ARG_EXPR:
7299      return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
7300					  in_decl),
7301			     tsubst (TREE_TYPE (t), args, complain, in_decl));
7302
7303    default:
7304      return t;
7305    }
7306}
7307
7308/* Like tsubst_copy, but also does semantic processing.  */
7309
7310tree
7311tsubst_expr (t, args, complain, in_decl)
7312     tree t, args;
7313     tsubst_flags_t complain;
7314     tree in_decl;
7315{
7316  tree stmt, tmp;
7317
7318  if (t == NULL_TREE || t == error_mark_node)
7319    return t;
7320
7321  if (processing_template_decl)
7322    return tsubst_copy (t, args, complain, in_decl);
7323
7324  if (!statement_code_p (TREE_CODE (t)))
7325    return build_expr_from_tree (tsubst_copy (t, args, complain, in_decl));
7326
7327  switch (TREE_CODE (t))
7328    {
7329    case RETURN_INIT:
7330      prep_stmt (t);
7331      finish_named_return_value
7332	(TREE_OPERAND (t, 0),
7333	 tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl));
7334      break;
7335
7336    case CTOR_INITIALIZER:
7337      {
7338	tree member_init_list;
7339	tree base_init_list;
7340
7341	prep_stmt (t);
7342	member_init_list
7343	  = tsubst_initializer_list (TREE_OPERAND (t, 0), args);
7344	base_init_list
7345	  = tsubst_initializer_list (TREE_OPERAND (t, 1), args);
7346	emit_base_init (member_init_list, base_init_list);
7347	break;
7348      }
7349
7350    case RETURN_STMT:
7351      prep_stmt (t);
7352      finish_return_stmt (tsubst_expr (RETURN_EXPR (t),
7353				       args, complain, in_decl));
7354      break;
7355
7356    case EXPR_STMT:
7357      prep_stmt (t);
7358      finish_expr_stmt (tsubst_expr (EXPR_STMT_EXPR (t),
7359				     args, complain, in_decl));
7360      break;
7361
7362    case USING_STMT:
7363      prep_stmt (t);
7364      do_using_directive (tsubst_expr (USING_STMT_NAMESPACE (t),
7365				       args, complain, in_decl));
7366      break;
7367
7368    case DECL_STMT:
7369      {
7370	tree decl;
7371	tree init;
7372
7373	prep_stmt (t);
7374	decl = DECL_STMT_DECL (t);
7375	if (TREE_CODE (decl) == LABEL_DECL)
7376	  finish_label_decl (DECL_NAME (decl));
7377	else if (TREE_CODE (decl) == USING_DECL)
7378	  {
7379	    tree scope = DECL_INITIAL (decl);
7380	    tree name = DECL_NAME (decl);
7381
7382	    scope = tsubst_expr (scope, args, complain, in_decl);
7383	    do_local_using_decl (build_nt (SCOPE_REF, scope, name));
7384	  }
7385	else
7386	  {
7387	    init = DECL_INITIAL (decl);
7388	    decl = tsubst (decl, args, complain, in_decl);
7389	    if (decl != error_mark_node)
7390	      {
7391	        if (init)
7392	          DECL_INITIAL (decl) = error_mark_node;
7393	        /* By marking the declaration as instantiated, we avoid
7394	           trying to instantiate it.  Since instantiate_decl can't
7395	           handle local variables, and since we've already done
7396	           all that needs to be done, that's the right thing to
7397	           do.  */
7398	        if (TREE_CODE (decl) == VAR_DECL)
7399	          DECL_TEMPLATE_INSTANTIATED (decl) = 1;
7400		if (TREE_CODE (decl) == VAR_DECL
7401		    && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
7402		  /* Anonymous aggregates are a special case.  */
7403		  finish_anon_union (decl);
7404		else
7405		  {
7406		    maybe_push_decl (decl);
7407		    if (DECL_PRETTY_FUNCTION_P (decl))
7408		      {
7409			/* For __PRETTY_FUNCTION__ we have to adjust the
7410			   initializer.  */
7411			const char *const name
7412			  = (*decl_printable_name) (current_function_decl, 2);
7413			init = cp_fname_init (name);
7414			TREE_TYPE (decl) = TREE_TYPE (init);
7415		      }
7416		    else
7417		      init = tsubst_expr (init, args, complain, in_decl);
7418		    cp_finish_decl (decl, init, NULL_TREE, 0);
7419		  }
7420	      }
7421	  }
7422
7423	/* A DECL_STMT can also be used as an expression, in the condition
7424	   clause of a if/for/while construct.  If we aren't followed by
7425	   another statement, return our decl.  */
7426	if (TREE_CHAIN (t) == NULL_TREE)
7427	  return decl;
7428      }
7429      break;
7430
7431    case FOR_STMT:
7432      {
7433	prep_stmt (t);
7434
7435	stmt = begin_for_stmt ();
7436	tsubst_expr (FOR_INIT_STMT (t), args, complain, in_decl);
7437	finish_for_init_stmt (stmt);
7438	finish_for_cond (tsubst_expr (FOR_COND (t),
7439				      args, complain, in_decl),
7440			 stmt);
7441	tmp = tsubst_expr (FOR_EXPR (t), args, complain, in_decl);
7442	finish_for_expr (tmp, stmt);
7443	tsubst_expr (FOR_BODY (t), args, complain, in_decl);
7444	finish_for_stmt (stmt);
7445      }
7446      break;
7447
7448    case WHILE_STMT:
7449      {
7450	prep_stmt (t);
7451	stmt = begin_while_stmt ();
7452	finish_while_stmt_cond (tsubst_expr (WHILE_COND (t),
7453					     args, complain, in_decl),
7454				stmt);
7455	tsubst_expr (WHILE_BODY (t), args, complain, in_decl);
7456	finish_while_stmt (stmt);
7457      }
7458      break;
7459
7460    case DO_STMT:
7461      {
7462	prep_stmt (t);
7463	stmt = begin_do_stmt ();
7464	tsubst_expr (DO_BODY (t), args, complain, in_decl);
7465	finish_do_body (stmt);
7466	finish_do_stmt (tsubst_expr (DO_COND (t),
7467				     args, complain, in_decl),
7468			stmt);
7469      }
7470      break;
7471
7472    case IF_STMT:
7473      {
7474	prep_stmt (t);
7475	stmt = begin_if_stmt ();
7476	finish_if_stmt_cond (tsubst_expr (IF_COND (t),
7477					  args, complain, in_decl),
7478			     stmt);
7479
7480	if (tmp = THEN_CLAUSE (t), tmp)
7481	  {
7482	    tsubst_expr (tmp, args, complain, in_decl);
7483	    finish_then_clause (stmt);
7484	  }
7485
7486	if (tmp = ELSE_CLAUSE (t), tmp)
7487	  {
7488	    begin_else_clause ();
7489	    tsubst_expr (tmp, args, complain, in_decl);
7490	    finish_else_clause (stmt);
7491	  }
7492
7493	finish_if_stmt ();
7494      }
7495      break;
7496
7497    case COMPOUND_STMT:
7498      {
7499	prep_stmt (t);
7500	if (COMPOUND_STMT_BODY_BLOCK (t))
7501	  stmt = begin_function_body ();
7502	else
7503	  stmt = begin_compound_stmt (COMPOUND_STMT_NO_SCOPE (t));
7504
7505	tsubst_expr (COMPOUND_BODY (t), args, complain, in_decl);
7506
7507	if (COMPOUND_STMT_BODY_BLOCK (t))
7508	  finish_function_body (stmt);
7509	else
7510	  finish_compound_stmt (COMPOUND_STMT_NO_SCOPE (t), stmt);
7511      }
7512      break;
7513
7514    case BREAK_STMT:
7515      prep_stmt (t);
7516      finish_break_stmt ();
7517      break;
7518
7519    case CONTINUE_STMT:
7520      prep_stmt (t);
7521      finish_continue_stmt ();
7522      break;
7523
7524    case SWITCH_STMT:
7525      {
7526	tree val;
7527
7528	prep_stmt (t);
7529	stmt = begin_switch_stmt ();
7530	val = tsubst_expr (SWITCH_COND (t), args, complain, in_decl);
7531	finish_switch_cond (val, stmt);
7532	tsubst_expr (SWITCH_BODY (t), args, complain, in_decl);
7533	finish_switch_stmt (stmt);
7534      }
7535      break;
7536
7537    case CASE_LABEL:
7538      prep_stmt (t);
7539      finish_case_label (tsubst_expr (CASE_LOW (t), args, complain, in_decl),
7540			 tsubst_expr (CASE_HIGH (t), args, complain,
7541				      in_decl));
7542      break;
7543
7544    case LABEL_STMT:
7545      lineno = STMT_LINENO (t);
7546      finish_label_stmt (DECL_NAME (LABEL_STMT_LABEL (t)));
7547      break;
7548
7549    case FILE_STMT:
7550      input_filename = FILE_STMT_FILENAME (t);
7551      add_stmt (build_nt (FILE_STMT, FILE_STMT_FILENAME_NODE (t)));
7552      break;
7553
7554    case GOTO_STMT:
7555      prep_stmt (t);
7556      tmp = GOTO_DESTINATION (t);
7557      if (TREE_CODE (tmp) != LABEL_DECL)
7558	/* Computed goto's must be tsubst'd into.  On the other hand,
7559	   non-computed gotos must not be; the identifier in question
7560	   will have no binding.  */
7561	tmp = tsubst_expr (tmp, args, complain, in_decl);
7562      else
7563	tmp = DECL_NAME (tmp);
7564      finish_goto_stmt (tmp);
7565      break;
7566
7567    case ASM_STMT:
7568      prep_stmt (t);
7569      tmp = finish_asm_stmt
7570	(ASM_CV_QUAL (t),
7571	 tsubst_expr (ASM_STRING (t), args, complain, in_decl),
7572	 tsubst_expr (ASM_OUTPUTS (t), args, complain, in_decl),
7573	 tsubst_expr (ASM_INPUTS (t), args, complain, in_decl),
7574	 tsubst_expr (ASM_CLOBBERS (t), args, complain, in_decl));
7575      ASM_INPUT_P (tmp) = ASM_INPUT_P (t);
7576      break;
7577
7578    case TRY_BLOCK:
7579      prep_stmt (t);
7580      if (CLEANUP_P (t))
7581	{
7582	  stmt = begin_try_block ();
7583	  tsubst_expr (TRY_STMTS (t), args, complain, in_decl);
7584	  finish_cleanup_try_block (stmt);
7585	  finish_cleanup (tsubst_expr (TRY_HANDLERS (t), args,
7586				       complain, in_decl),
7587			  stmt);
7588	}
7589      else
7590	{
7591	  if (FN_TRY_BLOCK_P (t))
7592	    stmt = begin_function_try_block ();
7593	  else
7594	    stmt = begin_try_block ();
7595
7596	  tsubst_expr (TRY_STMTS (t), args, complain, in_decl);
7597
7598	  if (FN_TRY_BLOCK_P (t))
7599	    finish_function_try_block (stmt);
7600	  else
7601	    finish_try_block (stmt);
7602
7603	  tsubst_expr (TRY_HANDLERS (t), args, complain, in_decl);
7604	  if (FN_TRY_BLOCK_P (t))
7605	    finish_function_handler_sequence (stmt);
7606	  else
7607	    finish_handler_sequence (stmt);
7608	}
7609      break;
7610
7611    case HANDLER:
7612      {
7613	tree decl;
7614
7615	prep_stmt (t);
7616	stmt = begin_handler ();
7617	if (HANDLER_PARMS (t))
7618	  {
7619	    decl = DECL_STMT_DECL (HANDLER_PARMS (t));
7620	    decl = tsubst (decl, args, complain, in_decl);
7621	    /* Prevent instantiate_decl from trying to instantiate
7622	       this variable.  We've already done all that needs to be
7623	       done.  */
7624	    DECL_TEMPLATE_INSTANTIATED (decl) = 1;
7625	  }
7626	else
7627	  decl = NULL_TREE;
7628	finish_handler_parms (decl, stmt);
7629	tsubst_expr (HANDLER_BODY (t), args, complain, in_decl);
7630	finish_handler (stmt);
7631      }
7632      break;
7633
7634    case TAG_DEFN:
7635      prep_stmt (t);
7636      tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
7637      break;
7638
7639    case CTOR_STMT:
7640      add_stmt (copy_node (t));
7641      break;
7642
7643    default:
7644      abort ();
7645    }
7646
7647  return tsubst_expr (TREE_CHAIN (t), args, complain, in_decl);
7648}
7649
7650/* Instantiate the indicated variable or function template TMPL with
7651   the template arguments in TARG_PTR.  */
7652
7653tree
7654instantiate_template (tmpl, targ_ptr)
7655     tree tmpl, targ_ptr;
7656{
7657  tree fndecl;
7658  tree gen_tmpl;
7659  tree spec;
7660  int i, len;
7661  tree inner_args;
7662
7663  if (tmpl == error_mark_node)
7664    return error_mark_node;
7665
7666  my_friendly_assert (TREE_CODE (tmpl) == TEMPLATE_DECL, 283);
7667
7668  /* If this function is a clone, handle it specially.  */
7669  if (DECL_CLONED_FUNCTION_P (tmpl))
7670    {
7671      tree spec = instantiate_template (DECL_CLONED_FUNCTION (tmpl), targ_ptr);
7672      tree clone;
7673
7674      /* Look for the clone. */
7675      for (clone = TREE_CHAIN (spec);
7676	   clone && DECL_CLONED_FUNCTION_P (clone);
7677	   clone = TREE_CHAIN (clone))
7678	if (DECL_NAME (clone) == DECL_NAME (tmpl))
7679	  return clone;
7680      /* We should always have found the clone by now.  */
7681      abort ();
7682      return NULL_TREE;
7683    }
7684
7685  /* Check to see if we already have this specialization.  */
7686  spec = retrieve_specialization (tmpl, targ_ptr);
7687  if (spec != NULL_TREE)
7688    return spec;
7689
7690  gen_tmpl = most_general_template (tmpl);
7691  if (tmpl != gen_tmpl)
7692    {
7693      /* The TMPL is a partial instantiation.  To get a full set of
7694	 arguments we must add the arguments used to perform the
7695	 partial instantiation.  */
7696      targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
7697					      targ_ptr);
7698
7699      /* Check to see if we already have this specialization.  */
7700      spec = retrieve_specialization (gen_tmpl, targ_ptr);
7701      if (spec != NULL_TREE)
7702	return spec;
7703    }
7704
7705  len = DECL_NTPARMS (gen_tmpl);
7706  inner_args = INNERMOST_TEMPLATE_ARGS (targ_ptr);
7707  i = len;
7708  while (i--)
7709    {
7710      tree t = TREE_VEC_ELT (inner_args, i);
7711      if (TYPE_P (t))
7712	{
7713	  tree nt = target_type (t);
7714	  if (IS_AGGR_TYPE (nt) && decl_function_context (TYPE_MAIN_DECL (nt)))
7715	    {
7716	      error ("type `%T' composed from a local class is not a valid template-argument", t);
7717	      error ("  trying to instantiate `%D'", gen_tmpl);
7718	      return error_mark_node;
7719	    }
7720	}
7721    }
7722
7723  /* substitute template parameters */
7724  fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
7725		   targ_ptr, tf_error, gen_tmpl);
7726  /* The DECL_TI_TEMPLATE should always be the immediate parent
7727     template, not the most general template.  */
7728  DECL_TI_TEMPLATE (fndecl) = tmpl;
7729
7730  if (flag_external_templates)
7731    add_pending_template (fndecl);
7732
7733  /* If we've just instantiated the main entry point for a function,
7734     instantiate all the alternate entry points as well.  We do this
7735     by cloning the instantiation of the main entry point, not by
7736     instantiating the template clones.  */
7737  if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
7738    clone_function_decl (fndecl, /*update_method_vec_p=*/0);
7739
7740  return fndecl;
7741}
7742
7743/* The FN is a TEMPLATE_DECL for a function.  The ARGS are the
7744   arguments that are being used when calling it.  TARGS is a vector
7745   into which the deduced template arguments are placed.
7746
7747   Return zero for success, 2 for an incomplete match that doesn't resolve
7748   all the types, and 1 for complete failure.  An error message will be
7749   printed only for an incomplete match.
7750
7751   If FN is a conversion operator, or we are trying to produce a specific
7752   specialization, RETURN_TYPE is the return type desired.
7753
7754   The EXPLICIT_TARGS are explicit template arguments provided via a
7755   template-id.
7756
7757   The parameter STRICT is one of:
7758
7759   DEDUCE_CALL:
7760     We are deducing arguments for a function call, as in
7761     [temp.deduct.call].
7762
7763   DEDUCE_CONV:
7764     We are deducing arguments for a conversion function, as in
7765     [temp.deduct.conv].
7766
7767   DEDUCE_EXACT:
7768     We are deducing arguments when doing an explicit instantiation
7769     as in [temp.explicit], when determining an explicit specialization
7770     as in [temp.expl.spec], or when taking the address of a function
7771     template, as in [temp.deduct.funcaddr].
7772
7773   DEDUCE_ORDER:
7774     We are deducing arguments when calculating the partial
7775     ordering between specializations of function or class
7776     templates, as in [temp.func.order] and [temp.class.order].
7777
7778   LEN is the number of parms to consider before returning success, or -1
7779   for all.  This is used in partial ordering to avoid comparing parms for
7780   which no actual argument was passed, since they are not considered in
7781   overload resolution (and are explicitly excluded from consideration in
7782   partial ordering in [temp.func.order]/6).  */
7783
7784int
7785fn_type_unification (fn, explicit_targs, targs, args, return_type,
7786		     strict, len)
7787     tree fn, explicit_targs, targs, args, return_type;
7788     unification_kind_t strict;
7789     int len;
7790{
7791  tree parms;
7792  tree fntype;
7793  int result;
7794
7795  my_friendly_assert (TREE_CODE (fn) == TEMPLATE_DECL, 0);
7796
7797  fntype = TREE_TYPE (fn);
7798  if (explicit_targs)
7799    {
7800      /* [temp.deduct]
7801
7802	 The specified template arguments must match the template
7803	 parameters in kind (i.e., type, nontype, template), and there
7804	 must not be more arguments than there are parameters;
7805	 otherwise type deduction fails.
7806
7807	 Nontype arguments must match the types of the corresponding
7808	 nontype template parameters, or must be convertible to the
7809	 types of the corresponding nontype parameters as specified in
7810	 _temp.arg.nontype_, otherwise type deduction fails.
7811
7812	 All references in the function type of the function template
7813	 to the corresponding template parameters are replaced by the
7814	 specified template argument values.  If a substitution in a
7815	 template parameter or in the function type of the function
7816	 template results in an invalid type, type deduction fails.  */
7817      int i;
7818      tree converted_args;
7819
7820      converted_args
7821	= (coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (fn),
7822				  explicit_targs, NULL_TREE, tf_none,
7823				  /*require_all_arguments=*/0));
7824      if (converted_args == error_mark_node)
7825	return 1;
7826
7827      fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
7828      if (fntype == error_mark_node)
7829	return 1;
7830
7831      /* Place the explicitly specified arguments in TARGS.  */
7832      for (i = 0; i < TREE_VEC_LENGTH (targs); i++)
7833	TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
7834    }
7835
7836  parms = TYPE_ARG_TYPES (fntype);
7837  /* Never do unification on the 'this' parameter.  */
7838  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn))
7839    parms = TREE_CHAIN (parms);
7840
7841  if (return_type)
7842    {
7843      /* We've been given a return type to match, prepend it.  */
7844      parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
7845      args = tree_cons (NULL_TREE, return_type, args);
7846      if (len >= 0)
7847	++len;
7848    }
7849
7850  /* We allow incomplete unification without an error message here
7851     because the standard doesn't seem to explicitly prohibit it.  Our
7852     callers must be ready to deal with unification failures in any
7853     event.  */
7854  result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
7855				  targs, parms, args, /*subr=*/0,
7856				  strict, /*allow_incomplete*/1, len);
7857
7858  if (result == 0)
7859    /* All is well so far.  Now, check:
7860
7861       [temp.deduct]
7862
7863       When all template arguments have been deduced, all uses of
7864       template parameters in nondeduced contexts are replaced with
7865       the corresponding deduced argument values.  If the
7866       substitution results in an invalid type, as described above,
7867       type deduction fails.  */
7868    if (tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE)
7869	== error_mark_node)
7870      return 1;
7871
7872  return result;
7873}
7874
7875/* Adjust types before performing type deduction, as described in
7876   [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
7877   sections are symmetric.  PARM is the type of a function parameter
7878   or the return type of the conversion function.  ARG is the type of
7879   the argument passed to the call, or the type of the value
7880   initialized with the result of the conversion function.  */
7881
7882static int
7883maybe_adjust_types_for_deduction (strict, parm, arg)
7884     unification_kind_t strict;
7885     tree* parm;
7886     tree* arg;
7887{
7888  int result = 0;
7889
7890  switch (strict)
7891    {
7892    case DEDUCE_CALL:
7893      break;
7894
7895    case DEDUCE_CONV:
7896      {
7897	/* Swap PARM and ARG throughout the remainder of this
7898	   function; the handling is precisely symmetric since PARM
7899	   will initialize ARG rather than vice versa.  */
7900	tree* temp = parm;
7901	parm = arg;
7902	arg = temp;
7903	break;
7904      }
7905
7906    case DEDUCE_EXACT:
7907      /* There is nothing to do in this case.  */
7908      return 0;
7909
7910    case DEDUCE_ORDER:
7911      /* DR 214. [temp.func.order] is underspecified, and leads to no
7912         ordering between things like `T *' and `T const &' for `U *'.
7913         The former has T=U and the latter T=U*. The former looks more
7914         specialized and John Spicer considers it well-formed (the EDG
7915         compiler accepts it).
7916
7917         John also confirms that deduction should proceed as in a function
7918         call. Which implies the usual ARG and PARM conversions as DEDUCE_CALL.
7919         However, in ordering, ARG can have REFERENCE_TYPE, but no argument
7920         to an actual call can have such a type.
7921
7922         If both ARG and PARM are REFERENCE_TYPE, we change neither.
7923         If only ARG is a REFERENCE_TYPE, we look through that and then
7924         proceed as with DEDUCE_CALL (which could further convert it).  */
7925      if (TREE_CODE (*arg) == REFERENCE_TYPE)
7926        {
7927          if (TREE_CODE (*parm) == REFERENCE_TYPE)
7928            return 0;
7929          *arg = TREE_TYPE (*arg);
7930        }
7931      break;
7932    default:
7933      abort ();
7934    }
7935
7936  if (TREE_CODE (*parm) != REFERENCE_TYPE)
7937    {
7938      /* [temp.deduct.call]
7939
7940	 If P is not a reference type:
7941
7942	 --If A is an array type, the pointer type produced by the
7943	 array-to-pointer standard conversion (_conv.array_) is
7944	 used in place of A for type deduction; otherwise,
7945
7946	 --If A is a function type, the pointer type produced by
7947	 the function-to-pointer standard conversion
7948	 (_conv.func_) is used in place of A for type deduction;
7949	 otherwise,
7950
7951	 --If A is a cv-qualified type, the top level
7952	 cv-qualifiers of A's type are ignored for type
7953	 deduction.  */
7954      if (TREE_CODE (*arg) == ARRAY_TYPE)
7955	*arg = build_pointer_type (TREE_TYPE (*arg));
7956      else if (TREE_CODE (*arg) == FUNCTION_TYPE)
7957	*arg = build_pointer_type (*arg);
7958      else
7959	*arg = TYPE_MAIN_VARIANT (*arg);
7960    }
7961
7962  /* [temp.deduct.call]
7963
7964     If P is a cv-qualified type, the top level cv-qualifiers
7965     of P's type are ignored for type deduction.  If P is a
7966     reference type, the type referred to by P is used for
7967     type deduction.  */
7968  *parm = TYPE_MAIN_VARIANT (*parm);
7969  if (TREE_CODE (*parm) == REFERENCE_TYPE)
7970    {
7971      *parm = TREE_TYPE (*parm);
7972      result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
7973    }
7974  return result;
7975}
7976
7977/* Most parms like fn_type_unification.
7978
7979   If SUBR is 1, we're being called recursively (to unify the
7980   arguments of a function or method parameter of a function
7981   template).  */
7982
7983static int
7984type_unification_real (tparms, targs, xparms, xargs, subr,
7985		       strict, allow_incomplete, xlen)
7986     tree tparms, targs, xparms, xargs;
7987     int subr;
7988     unification_kind_t strict;
7989     int allow_incomplete, xlen;
7990{
7991  tree parm, arg;
7992  int i;
7993  int ntparms = TREE_VEC_LENGTH (tparms);
7994  int sub_strict;
7995  int saw_undeduced = 0;
7996  tree parms, args;
7997  int len;
7998
7999  my_friendly_assert (TREE_CODE (tparms) == TREE_VEC, 289);
8000  my_friendly_assert (xparms == NULL_TREE
8001		      || TREE_CODE (xparms) == TREE_LIST, 290);
8002  /* ARGS could be NULL (via a call from parse.y to
8003     build_x_function_call).  */
8004  if (xargs)
8005    my_friendly_assert (TREE_CODE (xargs) == TREE_LIST, 291);
8006  my_friendly_assert (ntparms > 0, 292);
8007
8008  switch (strict)
8009    {
8010    case DEDUCE_CALL:
8011      sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
8012                    | UNIFY_ALLOW_DERIVED);
8013      break;
8014
8015    case DEDUCE_CONV:
8016      sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
8017      break;
8018
8019    case DEDUCE_EXACT:
8020      sub_strict = UNIFY_ALLOW_NONE;
8021      break;
8022
8023    case DEDUCE_ORDER:
8024      sub_strict = UNIFY_ALLOW_NONE;
8025      break;
8026
8027    default:
8028      abort ();
8029    }
8030
8031  if (xlen == 0)
8032    return 0;
8033
8034 again:
8035  parms = xparms;
8036  args = xargs;
8037  len = xlen;
8038
8039  while (parms
8040	 && parms != void_list_node
8041	 && args
8042	 && args != void_list_node)
8043    {
8044      parm = TREE_VALUE (parms);
8045      parms = TREE_CHAIN (parms);
8046      arg = TREE_VALUE (args);
8047      args = TREE_CHAIN (args);
8048
8049      if (arg == error_mark_node)
8050	return 1;
8051      if (arg == unknown_type_node)
8052	/* We can't deduce anything from this, but we might get all the
8053	   template args from other function args.  */
8054	continue;
8055
8056      /* Conversions will be performed on a function argument that
8057	 corresponds with a function parameter that contains only
8058	 non-deducible template parameters and explicitly specified
8059	 template parameters.  */
8060      if (! uses_template_parms (parm))
8061	{
8062	  tree type;
8063
8064	  if (!TYPE_P (arg))
8065	    type = TREE_TYPE (arg);
8066	  else
8067	    {
8068	      type = arg;
8069	      arg = NULL_TREE;
8070	    }
8071
8072	  if (strict == DEDUCE_EXACT || strict == DEDUCE_ORDER)
8073	    {
8074	      if (same_type_p (parm, type))
8075		continue;
8076	    }
8077	  else
8078	    /* It might work; we shouldn't check now, because we might
8079	       get into infinite recursion.  Overload resolution will
8080	       handle it.  */
8081	    continue;
8082
8083	  return 1;
8084	}
8085
8086      if (!TYPE_P (arg))
8087	{
8088	  my_friendly_assert (TREE_TYPE (arg) != NULL_TREE, 293);
8089	  if (type_unknown_p (arg))
8090	    {
8091	      /* [temp.deduct.type] A template-argument can be deduced from
8092		 a pointer to function or pointer to member function
8093		 argument if the set of overloaded functions does not
8094		 contain function templates and at most one of a set of
8095		 overloaded functions provides a unique match.  */
8096
8097	      if (resolve_overloaded_unification
8098		  (tparms, targs, parm, arg, strict, sub_strict)
8099		  != 0)
8100		return 1;
8101	      continue;
8102	    }
8103	  arg = TREE_TYPE (arg);
8104	}
8105
8106      {
8107        int arg_strict = sub_strict;
8108
8109        if (!subr)
8110	  arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg);
8111
8112        if (unify (tparms, targs, parm, arg, arg_strict))
8113          return 1;
8114      }
8115
8116      /* Are we done with the interesting parms?  */
8117      if (--len == 0)
8118	goto done;
8119    }
8120  /* Fail if we've reached the end of the parm list, and more args
8121     are present, and the parm list isn't variadic.  */
8122  if (args && args != void_list_node && parms == void_list_node)
8123    return 1;
8124  /* Fail if parms are left and they don't have default values.	 */
8125  if (parms
8126      && parms != void_list_node
8127      && TREE_PURPOSE (parms) == NULL_TREE)
8128    return 1;
8129
8130 done:
8131  if (!subr)
8132    for (i = 0; i < ntparms; i++)
8133      if (TREE_VEC_ELT (targs, i) == NULL_TREE)
8134	{
8135	  tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
8136
8137	  /* If this is an undeduced nontype parameter that depends on
8138	     a type parameter, try another pass; its type may have been
8139	     deduced from a later argument than the one from which
8140	     this parameter can be deduced.  */
8141	  if (TREE_CODE (tparm) == PARM_DECL
8142	      && uses_template_parms (TREE_TYPE (tparm))
8143	      && !saw_undeduced++)
8144	    goto again;
8145
8146	  if (!allow_incomplete)
8147	    error ("incomplete type unification");
8148	  return 2;
8149	}
8150  return 0;
8151}
8152
8153/* Subroutine of type_unification_real.  Args are like the variables at the
8154   call site.  ARG is an overloaded function (or template-id); we try
8155   deducing template args from each of the overloads, and if only one
8156   succeeds, we go with that.  Modifies TARGS and returns 0 on success.  */
8157
8158static int
8159resolve_overloaded_unification (tparms, targs, parm, arg, strict,
8160				sub_strict)
8161     tree tparms, targs, parm, arg;
8162     unification_kind_t strict;
8163     int sub_strict;
8164{
8165  tree tempargs = copy_node (targs);
8166  int good = 0;
8167
8168  if (TREE_CODE (arg) == ADDR_EXPR)
8169    arg = TREE_OPERAND (arg, 0);
8170
8171  if (TREE_CODE (arg) == COMPONENT_REF)
8172    /* Handle `&x' where `x' is some static or non-static member
8173       function name.  */
8174    arg = TREE_OPERAND (arg, 1);
8175
8176  if (TREE_CODE (arg) == OFFSET_REF)
8177    arg = TREE_OPERAND (arg, 1);
8178
8179  /* Strip baselink information.  */
8180  while (TREE_CODE (arg) == TREE_LIST)
8181    arg = TREE_VALUE (arg);
8182
8183  if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
8184    {
8185      /* If we got some explicit template args, we need to plug them into
8186	 the affected templates before we try to unify, in case the
8187	 explicit args will completely resolve the templates in question.  */
8188
8189      tree expl_subargs = TREE_OPERAND (arg, 1);
8190      arg = TREE_OPERAND (arg, 0);
8191
8192      for (; arg; arg = OVL_NEXT (arg))
8193	{
8194	  tree fn = OVL_CURRENT (arg);
8195	  tree subargs, elem;
8196
8197	  if (TREE_CODE (fn) != TEMPLATE_DECL)
8198	    continue;
8199
8200	  subargs = get_bindings_overload (fn, DECL_TEMPLATE_RESULT (fn),
8201					   expl_subargs);
8202	  if (subargs)
8203	    {
8204	      elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
8205	      if (TREE_CODE (elem) == METHOD_TYPE)
8206		elem = build_ptrmemfunc_type (build_pointer_type (elem));
8207	      good += try_one_overload (tparms, targs, tempargs, parm, elem,
8208					strict, sub_strict);
8209	    }
8210	}
8211    }
8212  else if (TREE_CODE (arg) == OVERLOAD)
8213    {
8214      for (; arg; arg = OVL_NEXT (arg))
8215	{
8216	  tree type = TREE_TYPE (OVL_CURRENT (arg));
8217	  if (TREE_CODE (type) == METHOD_TYPE)
8218	    type = build_ptrmemfunc_type (build_pointer_type (type));
8219	  good += try_one_overload (tparms, targs, tempargs, parm,
8220				    type,
8221				    strict, sub_strict);
8222	}
8223    }
8224  else
8225    abort ();
8226
8227  /* [temp.deduct.type] A template-argument can be deduced from a pointer
8228     to function or pointer to member function argument if the set of
8229     overloaded functions does not contain function templates and at most
8230     one of a set of overloaded functions provides a unique match.
8231
8232     So if we found multiple possibilities, we return success but don't
8233     deduce anything.  */
8234
8235  if (good == 1)
8236    {
8237      int i = TREE_VEC_LENGTH (targs);
8238      for (; i--; )
8239	if (TREE_VEC_ELT (tempargs, i))
8240	  TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
8241    }
8242  if (good)
8243    return 0;
8244
8245  return 1;
8246}
8247
8248/* Subroutine of resolve_overloaded_unification; does deduction for a single
8249   overload.  Fills TARGS with any deduced arguments, or error_mark_node if
8250   different overloads deduce different arguments for a given parm.
8251   Returns 1 on success.  */
8252
8253static int
8254try_one_overload (tparms, orig_targs, targs, parm, arg, strict,
8255		  sub_strict)
8256     tree tparms, orig_targs, targs, parm, arg;
8257     unification_kind_t strict;
8258     int sub_strict;
8259{
8260  int nargs;
8261  tree tempargs;
8262  int i;
8263
8264  /* [temp.deduct.type] A template-argument can be deduced from a pointer
8265     to function or pointer to member function argument if the set of
8266     overloaded functions does not contain function templates and at most
8267     one of a set of overloaded functions provides a unique match.
8268
8269     So if this is a template, just return success.  */
8270
8271  if (uses_template_parms (arg))
8272    return 1;
8273
8274  sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg);
8275
8276  /* We don't copy orig_targs for this because if we have already deduced
8277     some template args from previous args, unify would complain when we
8278     try to deduce a template parameter for the same argument, even though
8279     there isn't really a conflict.  */
8280  nargs = TREE_VEC_LENGTH (targs);
8281  tempargs = make_tree_vec (nargs);
8282
8283  if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
8284    return 0;
8285
8286  /* First make sure we didn't deduce anything that conflicts with
8287     explicitly specified args.  */
8288  for (i = nargs; i--; )
8289    {
8290      tree elt = TREE_VEC_ELT (tempargs, i);
8291      tree oldelt = TREE_VEC_ELT (orig_targs, i);
8292
8293      if (elt == NULL_TREE)
8294	continue;
8295      else if (uses_template_parms (elt))
8296	{
8297	  /* Since we're unifying against ourselves, we will fill in template
8298	     args used in the function parm list with our own template parms.
8299	     Discard them.  */
8300	  TREE_VEC_ELT (tempargs, i) = NULL_TREE;
8301	  continue;
8302	}
8303      else if (oldelt && ! template_args_equal (oldelt, elt))
8304	return 0;
8305    }
8306
8307  for (i = nargs; i--; )
8308    {
8309      tree elt = TREE_VEC_ELT (tempargs, i);
8310
8311      if (elt)
8312	TREE_VEC_ELT (targs, i) = elt;
8313    }
8314
8315  return 1;
8316}
8317
8318/* Verify that nondeduce template argument agrees with the type
8319   obtained from argument deduction.  Return nonzero if the
8320   verification fails.
8321
8322   For example:
8323
8324     struct A { typedef int X; };
8325     template <class T, class U> struct C {};
8326     template <class T> struct C<T, typename T::X> {};
8327
8328   Then with the instantiation `C<A, int>', we can deduce that
8329   `T' is `A' but unify () does not check whether `typename T::X'
8330   is `int'.  This function ensure that they agree.
8331
8332   TARGS, PARMS are the same as the arguments of unify.
8333   ARGS contains template arguments from all levels.  */
8334
8335static int
8336verify_class_unification (targs, parms, args)
8337     tree targs, parms, args;
8338{
8339  int i;
8340  int nparms = TREE_VEC_LENGTH (parms);
8341  tree new_parms = tsubst (parms, add_outermost_template_args (args, targs),
8342  			   tf_none, NULL_TREE);
8343  if (new_parms == error_mark_node)
8344    return 1;
8345
8346  args = INNERMOST_TEMPLATE_ARGS (args);
8347
8348  for (i = 0; i < nparms; i++)
8349    {
8350      tree parm = TREE_VEC_ELT (new_parms, i);
8351      tree arg = TREE_VEC_ELT (args, i);
8352
8353      /* In case we are deducing from a function argument of a function
8354	 templates, some parameters may not be deduced yet.  So we
8355	 make sure that only fully substituted elements of PARM are
8356	 compared below.  */
8357
8358      if (!uses_template_parms (parm) && !template_args_equal (parm, arg))
8359	return 1;
8360    }
8361  return 0;
8362}
8363
8364/* PARM is a template class (perhaps with unbound template
8365   parameters).  ARG is a fully instantiated type.  If ARG can be
8366   bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
8367   TARGS are as for unify.  */
8368
8369static tree
8370try_class_unification (tparms, targs, parm, arg)
8371     tree tparms;
8372     tree targs;
8373     tree parm;
8374     tree arg;
8375{
8376  tree copy_of_targs;
8377
8378  if (!CLASSTYPE_TEMPLATE_INFO (arg)
8379      || CLASSTYPE_TI_TEMPLATE (arg) != CLASSTYPE_TI_TEMPLATE (parm))
8380    return NULL_TREE;
8381
8382  /* We need to make a new template argument vector for the call to
8383     unify.  If we used TARGS, we'd clutter it up with the result of
8384     the attempted unification, even if this class didn't work out.
8385     We also don't want to commit ourselves to all the unifications
8386     we've already done, since unification is supposed to be done on
8387     an argument-by-argument basis.  In other words, consider the
8388     following pathological case:
8389
8390       template <int I, int J, int K>
8391       struct S {};
8392
8393       template <int I, int J>
8394       struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
8395
8396       template <int I, int J, int K>
8397       void f(S<I, J, K>, S<I, I, I>);
8398
8399       void g() {
8400         S<0, 0, 0> s0;
8401         S<0, 1, 2> s2;
8402
8403         f(s0, s2);
8404       }
8405
8406     Now, by the time we consider the unification involving `s2', we
8407     already know that we must have `f<0, 0, 0>'.  But, even though
8408     `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is not legal
8409     because there are two ways to unify base classes of S<0, 1, 2>
8410     with S<I, I, I>.  If we kept the already deduced knowledge, we
8411     would reject the possibility I=1.  */
8412  copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
8413
8414  /* If unification failed, we're done.  */
8415  if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
8416	     CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
8417    return NULL_TREE;
8418
8419  return arg;
8420}
8421
8422/* Subroutine of get_template_base.  RVAL, if non-NULL, is a base we
8423   have already discovered to be satisfactory.  ARG_BINFO is the binfo
8424   for the base class of ARG that we are currently examining.  */
8425
8426static tree
8427get_template_base_recursive (tparms, targs, parm,
8428			     arg_binfo, rval, flags)
8429     tree tparms;
8430     tree targs;
8431     tree arg_binfo;
8432     tree rval;
8433     tree parm;
8434     int flags;
8435{
8436  tree binfos;
8437  int i, n_baselinks;
8438  tree arg = BINFO_TYPE (arg_binfo);
8439
8440  if (!(flags & GTB_IGNORE_TYPE))
8441    {
8442      tree r = try_class_unification (tparms, targs,
8443				      parm, arg);
8444
8445      /* If there is more than one satisfactory baseclass, then:
8446
8447	   [temp.deduct.call]
8448
8449	   If they yield more than one possible deduced A, the type
8450	   deduction fails.
8451
8452	   applies.  */
8453      if (r && rval && !same_type_p (r, rval))
8454	return error_mark_node;
8455      else if (r)
8456	rval = r;
8457    }
8458
8459  binfos = BINFO_BASETYPES (arg_binfo);
8460  n_baselinks = binfos ? TREE_VEC_LENGTH (binfos) : 0;
8461
8462  /* Process base types.  */
8463  for (i = 0; i < n_baselinks; i++)
8464    {
8465      tree base_binfo = TREE_VEC_ELT (binfos, i);
8466      int this_virtual;
8467
8468      /* Skip this base, if we've already seen it.  */
8469      if (BINFO_MARKED (base_binfo))
8470	continue;
8471
8472      this_virtual =
8473	(flags & GTB_VIA_VIRTUAL) || TREE_VIA_VIRTUAL (base_binfo);
8474
8475      /* When searching for a non-virtual, we cannot mark virtually
8476	 found binfos.  */
8477      if (! this_virtual)
8478	SET_BINFO_MARKED (base_binfo);
8479
8480      rval = get_template_base_recursive (tparms, targs,
8481					  parm,
8482					  base_binfo,
8483					  rval,
8484					  GTB_VIA_VIRTUAL * this_virtual);
8485
8486      /* If we discovered more than one matching base class, we can
8487	 stop now.  */
8488      if (rval == error_mark_node)
8489	return error_mark_node;
8490    }
8491
8492  return rval;
8493}
8494
8495/* Given a template type PARM and a class type ARG, find the unique
8496   base type in ARG that is an instance of PARM.  We do not examine
8497   ARG itself; only its base-classes.  If there is no appropriate base
8498   class, return NULL_TREE.  If there is more than one, return
8499   error_mark_node.  PARM may be the type of a partial specialization,
8500   as well as a plain template type.  Used by unify.  */
8501
8502static tree
8503get_template_base (tparms, targs, parm, arg)
8504     tree tparms;
8505     tree targs;
8506     tree parm;
8507     tree arg;
8508{
8509  tree rval;
8510  tree arg_binfo;
8511
8512  my_friendly_assert (IS_AGGR_TYPE_CODE (TREE_CODE (arg)), 92);
8513
8514  arg_binfo = TYPE_BINFO (complete_type (arg));
8515  rval = get_template_base_recursive (tparms, targs,
8516				      parm, arg_binfo,
8517				      NULL_TREE,
8518				      GTB_IGNORE_TYPE);
8519
8520  /* Since get_template_base_recursive marks the bases classes, we
8521     must unmark them here.  */
8522  dfs_walk (arg_binfo, dfs_unmark, markedp, 0);
8523
8524  return rval;
8525}
8526
8527/* Returns the level of DECL, which declares a template parameter.  */
8528
8529static int
8530template_decl_level (decl)
8531     tree decl;
8532{
8533  switch (TREE_CODE (decl))
8534    {
8535    case TYPE_DECL:
8536    case TEMPLATE_DECL:
8537      return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
8538
8539    case PARM_DECL:
8540      return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
8541
8542    default:
8543      abort ();
8544      return 0;
8545    }
8546}
8547
8548/* Decide whether ARG can be unified with PARM, considering only the
8549   cv-qualifiers of each type, given STRICT as documented for unify.
8550   Returns non-zero iff the unification is OK on that basis.*/
8551
8552static int
8553check_cv_quals_for_unify (strict, arg, parm)
8554     int strict;
8555     tree arg;
8556     tree parm;
8557{
8558  int arg_quals = cp_type_quals (arg);
8559  int parm_quals = cp_type_quals (parm);
8560
8561  if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM)
8562    {
8563      /* If the cvr quals of parm will not unify with ARG, they'll be
8564	 ignored in instantiation, so we have to do the same here.  */
8565      if (TREE_CODE (arg) == REFERENCE_TYPE
8566	  || TREE_CODE (arg) == FUNCTION_TYPE
8567	  || TREE_CODE (arg) == METHOD_TYPE)
8568	parm_quals &= ~(TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE);
8569      if (!POINTER_TYPE_P (arg) &&
8570	  TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
8571	parm_quals &= ~TYPE_QUAL_RESTRICT;
8572    }
8573
8574  if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
8575      && (arg_quals & parm_quals) != parm_quals)
8576    return 0;
8577
8578  if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
8579      && (parm_quals & arg_quals) != arg_quals)
8580    return 0;
8581
8582  return 1;
8583}
8584
8585/* Takes parameters as for type_unification.  Returns 0 if the
8586   type deduction succeeds, 1 otherwise.  The parameter STRICT is a
8587   bitwise or of the following flags:
8588
8589     UNIFY_ALLOW_NONE:
8590       Require an exact match between PARM and ARG.
8591     UNIFY_ALLOW_MORE_CV_QUAL:
8592       Allow the deduced ARG to be more cv-qualified (by qualification
8593       conversion) than ARG.
8594     UNIFY_ALLOW_LESS_CV_QUAL:
8595       Allow the deduced ARG to be less cv-qualified than ARG.
8596     UNIFY_ALLOW_DERIVED:
8597       Allow the deduced ARG to be a template base class of ARG,
8598       or a pointer to a template base class of the type pointed to by
8599       ARG.
8600     UNIFY_ALLOW_INTEGER:
8601       Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
8602       case for more information.
8603     UNIFY_ALLOW_OUTER_LEVEL:
8604       This is the outermost level of a deduction. Used to determine validity
8605       of qualification conversions. A valid qualification conversion must
8606       have const qualified pointers leading up to the inner type which
8607       requires additional CV quals, except at the outer level, where const
8608       is not required [conv.qual]. It would be normal to set this flag in
8609       addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
8610     UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
8611       This is the outermost level of a deduction, and PARM can be more CV
8612       qualified at this point.
8613     UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
8614       This is the outermost level of a deduction, and PARM can be less CV
8615       qualified at this point.
8616     UNIFY_ALLOW_MAX_CORRECTION:
8617       This is an INTEGER_TYPE's maximum value.  Used if the range may
8618       have been derived from a size specification, such as an array size.
8619       If the size was given by a nontype template parameter N, the maximum
8620       value will have the form N-1.  The flag says that we can (and indeed
8621       must) unify N with (ARG + 1), an exception to the normal rules on
8622       folding PARM.  */
8623
8624static int
8625unify (tparms, targs, parm, arg, strict)
8626     tree tparms, targs, parm, arg;
8627     int strict;
8628{
8629  int idx;
8630  tree targ;
8631  tree tparm;
8632  int strict_in = strict;
8633
8634  /* I don't think this will do the right thing with respect to types.
8635     But the only case I've seen it in so far has been array bounds, where
8636     signedness is the only information lost, and I think that will be
8637     okay.  */
8638  while (TREE_CODE (parm) == NOP_EXPR)
8639    parm = TREE_OPERAND (parm, 0);
8640
8641  if (arg == error_mark_node)
8642    return 1;
8643  if (arg == unknown_type_node)
8644    /* We can't deduce anything from this, but we might get all the
8645       template args from other function args.  */
8646    return 0;
8647
8648  /* If PARM uses template parameters, then we can't bail out here,
8649     even if ARG == PARM, since we won't record unifications for the
8650     template parameters.  We might need them if we're trying to
8651     figure out which of two things is more specialized.  */
8652  if (arg == parm && !uses_template_parms (parm))
8653    return 0;
8654
8655  /* Immediately reject some pairs that won't unify because of
8656     cv-qualification mismatches.  */
8657  if (TREE_CODE (arg) == TREE_CODE (parm)
8658      && TYPE_P (arg)
8659      /* It is the elements of the array which hold the cv quals of an array
8660         type, and the elements might be template type parms. We'll check
8661         when we recurse.  */
8662      && TREE_CODE (arg) != ARRAY_TYPE
8663      /* We check the cv-qualifiers when unifying with template type
8664	 parameters below.  We want to allow ARG `const T' to unify with
8665	 PARM `T' for example, when computing which of two templates
8666	 is more specialized, for example.  */
8667      && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
8668      && !check_cv_quals_for_unify (strict_in, arg, parm))
8669    return 1;
8670
8671  if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
8672      && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
8673    strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
8674  strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
8675  strict &= ~UNIFY_ALLOW_DERIVED;
8676  strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
8677  strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
8678  strict &= ~UNIFY_ALLOW_MAX_CORRECTION;
8679
8680  switch (TREE_CODE (parm))
8681    {
8682    case TYPENAME_TYPE:
8683    case SCOPE_REF:
8684    case UNBOUND_CLASS_TEMPLATE:
8685      /* In a type which contains a nested-name-specifier, template
8686	 argument values cannot be deduced for template parameters used
8687	 within the nested-name-specifier.  */
8688      return 0;
8689
8690    case TEMPLATE_TYPE_PARM:
8691    case TEMPLATE_TEMPLATE_PARM:
8692    case BOUND_TEMPLATE_TEMPLATE_PARM:
8693      tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
8694
8695      if (TEMPLATE_TYPE_LEVEL (parm)
8696	  != template_decl_level (tparm))
8697	/* The PARM is not one we're trying to unify.  Just check
8698	   to see if it matches ARG.  */
8699	return (TREE_CODE (arg) == TREE_CODE (parm)
8700		&& same_type_p (parm, arg)) ? 0 : 1;
8701      idx = TEMPLATE_TYPE_IDX (parm);
8702      targ = TREE_VEC_ELT (targs, idx);
8703      tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
8704
8705      /* Check for mixed types and values.  */
8706      if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
8707	   && TREE_CODE (tparm) != TYPE_DECL)
8708	  || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
8709	      && TREE_CODE (tparm) != TEMPLATE_DECL))
8710	return 1;
8711
8712      if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
8713	{
8714	  /* ARG must be constructed from a template class or a template
8715	     template parameter.  */
8716	  if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
8717	      && (TREE_CODE (arg) != RECORD_TYPE || !CLASSTYPE_TEMPLATE_INFO (arg)))
8718	    return 1;
8719
8720	  {
8721	    tree parmtmpl = TYPE_TI_TEMPLATE (parm);
8722	    tree parmvec = TYPE_TI_ARGS (parm);
8723	    tree argvec = TYPE_TI_ARGS (arg);
8724	    tree argtmplvec
8725	      = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_TI_TEMPLATE (arg));
8726	    int i;
8727
8728	    /* The parameter and argument roles have to be switched here
8729	       in order to handle default arguments properly.  For example,
8730	       template<template <class> class TT> void f(TT<int>)
8731	       should be able to accept vector<int> which comes from
8732	       template <class T, class Allocator = allocator>
8733	       class vector.  */
8734
8735	    if (coerce_template_parms (argtmplvec, parmvec, parmtmpl, 0, 1)
8736	        == error_mark_node)
8737	      return 1;
8738
8739	    /* Deduce arguments T, i from TT<T> or TT<i>.
8740	       We check each element of PARMVEC and ARGVEC individually
8741	       rather than the whole TREE_VEC since they can have
8742	       different number of elements.  */
8743
8744	    for (i = 0; i < TREE_VEC_LENGTH (parmvec); ++i)
8745	      {
8746	        tree t = TREE_VEC_ELT (parmvec, i);
8747
8748	        if (unify (tparms, targs, t,
8749			   TREE_VEC_ELT (argvec, i),
8750			   UNIFY_ALLOW_NONE))
8751		  return 1;
8752	      }
8753	  }
8754	  arg = TYPE_TI_TEMPLATE (arg);
8755
8756	  /* Fall through to deduce template name.  */
8757	}
8758
8759      if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
8760	  || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
8761	{
8762	  /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
8763
8764	  /* Simple cases: Value already set, does match or doesn't.  */
8765	  if (targ != NULL_TREE && template_args_equal (targ, arg))
8766	    return 0;
8767	  else if (targ)
8768	    return 1;
8769	}
8770      else
8771	{
8772	  /* If PARM is `const T' and ARG is only `int', we don't have
8773	     a match unless we are allowing additional qualification.
8774	     If ARG is `const int' and PARM is just `T' that's OK;
8775	     that binds `const int' to `T'.  */
8776	  if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
8777					 arg, parm))
8778	    return 1;
8779
8780	  /* Consider the case where ARG is `const volatile int' and
8781	     PARM is `const T'.  Then, T should be `volatile int'.  */
8782	  arg = cp_build_qualified_type_real
8783	    (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
8784	  if (arg == error_mark_node)
8785	    return 1;
8786
8787	  /* Simple cases: Value already set, does match or doesn't.  */
8788	  if (targ != NULL_TREE && same_type_p (targ, arg))
8789	    return 0;
8790	  else if (targ)
8791	    return 1;
8792	}
8793
8794      /* Make sure that ARG is not a variable-sized array.  (Note that
8795	 were talking about variable-sized arrays (like `int[n]'),
8796	 rather than arrays of unknown size (like `int[]').)  We'll
8797	 get very confused by such a type since the bound of the array
8798	 will not be computable in an instantiation.  Besides, such
8799	 types are not allowed in ISO C++, so we can do as we please
8800	 here.  */
8801      if (TREE_CODE (arg) == ARRAY_TYPE
8802	  && !uses_template_parms (arg)
8803	  && TYPE_DOMAIN (arg)
8804	  && (TREE_CODE (TYPE_MAX_VALUE (TYPE_DOMAIN (arg)))
8805	      != INTEGER_CST))
8806	return 1;
8807
8808      TREE_VEC_ELT (targs, idx) = arg;
8809      return 0;
8810
8811    case TEMPLATE_PARM_INDEX:
8812      tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
8813
8814      if (TEMPLATE_PARM_LEVEL (parm)
8815	  != template_decl_level (tparm))
8816	/* The PARM is not one we're trying to unify.  Just check
8817	   to see if it matches ARG.  */
8818	return (TREE_CODE (arg) == TREE_CODE (parm)
8819		&& cp_tree_equal (parm, arg) > 0) ? 0 : 1;
8820
8821      idx = TEMPLATE_PARM_IDX (parm);
8822      targ = TREE_VEC_ELT (targs, idx);
8823
8824      if (targ)
8825	{
8826	  int i = (cp_tree_equal (targ, arg) > 0);
8827	  if (i == 1)
8828	    return 0;
8829	  else if (i == 0)
8830	    return 1;
8831	  else
8832	    abort ();
8833	}
8834
8835      /* [temp.deduct.type] If, in the declaration of a function template
8836	 with a non-type template-parameter, the non-type
8837	 template-parameter is used in an expression in the function
8838	 parameter-list and, if the corresponding template-argument is
8839	 deduced, the template-argument type shall match the type of the
8840	 template-parameter exactly, except that a template-argument
8841	 deduced from an array bound may be of any integral type.
8842	 The non-type parameter might use already deduced type parameters.  */
8843      tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
8844      if (same_type_p (TREE_TYPE (arg), tparm))
8845	  /* OK */;
8846      else if ((strict & UNIFY_ALLOW_INTEGER)
8847	       && (TREE_CODE (tparm) == INTEGER_TYPE
8848		   || TREE_CODE (tparm) == BOOLEAN_TYPE))
8849	/* OK */;
8850      else if (uses_template_parms (tparm))
8851	/* We haven't deduced the type of this parameter yet.  Try again
8852	   later.  */
8853	return 0;
8854      else
8855	return 1;
8856
8857      TREE_VEC_ELT (targs, idx) = arg;
8858      return 0;
8859
8860    case POINTER_TYPE:
8861      {
8862	if (TREE_CODE (arg) != POINTER_TYPE)
8863	  return 1;
8864
8865	/* [temp.deduct.call]
8866
8867	   A can be another pointer or pointer to member type that can
8868	   be converted to the deduced A via a qualification
8869	   conversion (_conv.qual_).
8870
8871	   We pass down STRICT here rather than UNIFY_ALLOW_NONE.
8872	   This will allow for additional cv-qualification of the
8873	   pointed-to types if appropriate.  */
8874
8875	if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
8876	  /* The derived-to-base conversion only persists through one
8877	     level of pointers.  */
8878	  strict |= (strict_in & UNIFY_ALLOW_DERIVED);
8879
8880	if (TREE_CODE (TREE_TYPE (parm)) == OFFSET_TYPE
8881	    && TREE_CODE (TREE_TYPE (arg)) == OFFSET_TYPE)
8882	  {
8883	    /* Avoid getting confused about cv-quals; don't recurse here.
8884	       Pointers to members should really be just OFFSET_TYPE, not
8885	       this two-level nonsense... */
8886
8887	    parm = TREE_TYPE (parm);
8888	    arg = TREE_TYPE (arg);
8889	    goto offset;
8890	  }
8891
8892	return unify (tparms, targs, TREE_TYPE (parm),
8893		      TREE_TYPE (arg), strict);
8894      }
8895
8896    case REFERENCE_TYPE:
8897      if (TREE_CODE (arg) != REFERENCE_TYPE)
8898	return 1;
8899      return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
8900		    strict & UNIFY_ALLOW_MORE_CV_QUAL);
8901
8902    case ARRAY_TYPE:
8903      if (TREE_CODE (arg) != ARRAY_TYPE)
8904	return 1;
8905      if ((TYPE_DOMAIN (parm) == NULL_TREE)
8906	  != (TYPE_DOMAIN (arg) == NULL_TREE))
8907	return 1;
8908      if (TYPE_DOMAIN (parm) != NULL_TREE
8909	  && unify (tparms, targs, TYPE_DOMAIN (parm),
8910		    TYPE_DOMAIN (arg), UNIFY_ALLOW_NONE) != 0)
8911	return 1;
8912      return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
8913		    UNIFY_ALLOW_NONE);
8914
8915    case REAL_TYPE:
8916    case COMPLEX_TYPE:
8917    case VECTOR_TYPE:
8918    case INTEGER_TYPE:
8919    case BOOLEAN_TYPE:
8920    case VOID_TYPE:
8921      if (TREE_CODE (arg) != TREE_CODE (parm))
8922	return 1;
8923
8924      if (TREE_CODE (parm) == INTEGER_TYPE
8925	  && TREE_CODE (TYPE_MAX_VALUE (parm)) != INTEGER_CST)
8926	{
8927	  if (TYPE_MIN_VALUE (parm) && TYPE_MIN_VALUE (arg)
8928	      && unify (tparms, targs, TYPE_MIN_VALUE (parm),
8929			TYPE_MIN_VALUE (arg), UNIFY_ALLOW_INTEGER))
8930	    return 1;
8931	  if (TYPE_MAX_VALUE (parm) && TYPE_MAX_VALUE (arg)
8932	      && unify (tparms, targs, TYPE_MAX_VALUE (parm),
8933			TYPE_MAX_VALUE (arg),
8934			UNIFY_ALLOW_INTEGER | UNIFY_ALLOW_MAX_CORRECTION))
8935	    return 1;
8936	}
8937      /* We have already checked cv-qualification at the top of the
8938	 function.  */
8939      else if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
8940	return 1;
8941
8942      /* As far as unification is concerned, this wins.	 Later checks
8943	 will invalidate it if necessary.  */
8944      return 0;
8945
8946      /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
8947      /* Type INTEGER_CST can come from ordinary constant template args.  */
8948    case INTEGER_CST:
8949      while (TREE_CODE (arg) == NOP_EXPR)
8950	arg = TREE_OPERAND (arg, 0);
8951
8952      if (TREE_CODE (arg) != INTEGER_CST)
8953	return 1;
8954      return !tree_int_cst_equal (parm, arg);
8955
8956    case TREE_VEC:
8957      {
8958	int i;
8959	if (TREE_CODE (arg) != TREE_VEC)
8960	  return 1;
8961	if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
8962	  return 1;
8963	for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
8964	  if (unify (tparms, targs,
8965		     TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
8966		     UNIFY_ALLOW_NONE))
8967	    return 1;
8968	return 0;
8969      }
8970
8971    case RECORD_TYPE:
8972    case UNION_TYPE:
8973      if (TREE_CODE (arg) != TREE_CODE (parm))
8974	return 1;
8975
8976      if (TYPE_PTRMEMFUNC_P (parm))
8977	{
8978	  if (!TYPE_PTRMEMFUNC_P (arg))
8979	    return 1;
8980
8981	  return unify (tparms, targs,
8982			TYPE_PTRMEMFUNC_FN_TYPE (parm),
8983			TYPE_PTRMEMFUNC_FN_TYPE (arg),
8984			strict);
8985	}
8986
8987      if (CLASSTYPE_TEMPLATE_INFO (parm))
8988	{
8989	  tree t = NULL_TREE;
8990
8991	  if (strict_in & UNIFY_ALLOW_DERIVED)
8992	    {
8993	      /* First, we try to unify the PARM and ARG directly.  */
8994	      t = try_class_unification (tparms, targs,
8995					 parm, arg);
8996
8997	      if (!t)
8998		{
8999		  /* Fallback to the special case allowed in
9000		     [temp.deduct.call]:
9001
9002		       If P is a class, and P has the form
9003		       template-id, then A can be a derived class of
9004		       the deduced A.  Likewise, if P is a pointer to
9005		       a class of the form template-id, A can be a
9006		       pointer to a derived class pointed to by the
9007		       deduced A.  */
9008		  t = get_template_base (tparms, targs,
9009					 parm, arg);
9010
9011		  if (! t || t == error_mark_node)
9012		    return 1;
9013		}
9014	    }
9015	  else if (CLASSTYPE_TEMPLATE_INFO (arg)
9016		   && (CLASSTYPE_TI_TEMPLATE (parm)
9017		       == CLASSTYPE_TI_TEMPLATE (arg)))
9018	    /* Perhaps PARM is something like S<U> and ARG is S<int>.
9019	       Then, we should unify `int' and `U'.  */
9020	    t = arg;
9021	  else
9022	    /* There's no chance of unification succeeding.  */
9023	    return 1;
9024
9025	  return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
9026			CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
9027	}
9028      else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
9029	return 1;
9030      return 0;
9031
9032    case METHOD_TYPE:
9033    case FUNCTION_TYPE:
9034      if (TREE_CODE (arg) != TREE_CODE (parm))
9035	return 1;
9036
9037      if (unify (tparms, targs, TREE_TYPE (parm),
9038		 TREE_TYPE (arg), UNIFY_ALLOW_NONE))
9039	return 1;
9040      return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
9041				    TYPE_ARG_TYPES (arg), 1,
9042				    DEDUCE_EXACT, 0, -1);
9043
9044    case OFFSET_TYPE:
9045    offset:
9046      if (TREE_CODE (arg) != OFFSET_TYPE)
9047	return 1;
9048      if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
9049		 TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
9050	return 1;
9051      return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
9052		    strict);
9053
9054    case CONST_DECL:
9055      if (arg != decl_constant_value (parm))
9056	return 1;
9057      return 0;
9058
9059    case TEMPLATE_DECL:
9060      /* Matched cases are handled by the ARG == PARM test above.  */
9061      return 1;
9062
9063    case MINUS_EXPR:
9064      if (tree_int_cst_equal (TREE_OPERAND (parm, 1), integer_one_node)
9065	  && (strict_in & UNIFY_ALLOW_MAX_CORRECTION))
9066	{
9067	  /* We handle this case specially, since it comes up with
9068	     arrays.  In particular, something like:
9069
9070	     template <int N> void f(int (&x)[N]);
9071
9072	     Here, we are trying to unify the range type, which
9073	     looks like [0 ... (N - 1)].  */
9074	  tree t, t1, t2;
9075	  t1 = TREE_OPERAND (parm, 0);
9076	  t2 = TREE_OPERAND (parm, 1);
9077
9078	  t = fold (build (PLUS_EXPR, integer_type_node, arg, t2));
9079
9080	  return unify (tparms, targs, t1, t, strict);
9081	}
9082      /* else fall through */
9083
9084    default:
9085      if (IS_EXPR_CODE_CLASS (TREE_CODE_CLASS (TREE_CODE (parm))))
9086	{
9087
9088	  /* We're looking at an expression.  This can happen with
9089	     something like:
9090
9091	       template <int I>
9092	       void foo(S<I>, S<I + 2>);
9093
9094	     This is a "nondeduced context":
9095
9096	       [deduct.type]
9097
9098	       The nondeduced contexts are:
9099
9100	       --A type that is a template-id in which one or more of
9101	         the template-arguments is an expression that references
9102	         a template-parameter.
9103
9104	     In these cases, we assume deduction succeeded, but don't
9105	     actually infer any unifications.  */
9106
9107	  if (!uses_template_parms (parm)
9108	      && !template_args_equal (parm, arg))
9109	    return 1;
9110	  else
9111	    return 0;
9112	}
9113      else
9114	sorry ("use of `%s' in template type unification",
9115	       tree_code_name [(int) TREE_CODE (parm)]);
9116
9117      return 1;
9118    }
9119}
9120
9121/* Called if RESULT is explicitly instantiated, or is a member of an
9122   explicitly instantiated class, or if using -frepo and the
9123   instantiation of RESULT has been assigned to this file.  */
9124
9125void
9126mark_decl_instantiated (result, extern_p)
9127     tree result;
9128     int extern_p;
9129{
9130  if (TREE_CODE (result) != FUNCTION_DECL)
9131    /* The TREE_PUBLIC flag for function declarations will have been
9132       set correctly by tsubst.  */
9133    TREE_PUBLIC (result) = 1;
9134
9135  /* We used to set this unconditionally; we moved that to
9136     do_decl_instantiation so it wouldn't get set on members of
9137     explicit class template instantiations.  But we still need to set
9138     it here for the 'extern template' case in order to suppress
9139     implicit instantiations.  */
9140  if (extern_p)
9141    SET_DECL_EXPLICIT_INSTANTIATION (result);
9142
9143  if (! extern_p)
9144    {
9145      DECL_INTERFACE_KNOWN (result) = 1;
9146      DECL_NOT_REALLY_EXTERN (result) = 1;
9147
9148      /* Always make artificials weak.  */
9149      if (DECL_ARTIFICIAL (result) && flag_weak)
9150	comdat_linkage (result);
9151      /* For WIN32 we also want to put explicit instantiations in
9152	 linkonce sections.  */
9153      else if (TREE_PUBLIC (result))
9154	maybe_make_one_only (result);
9155    }
9156  else if (TREE_CODE (result) == FUNCTION_DECL)
9157    defer_fn (result);
9158}
9159
9160/* Given two function templates PAT1 and PAT2, return:
9161
9162   DEDUCE should be DEDUCE_EXACT or DEDUCE_ORDER.
9163
9164   1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
9165   -1 if PAT2 is more specialized than PAT1.
9166   0 if neither is more specialized.
9167
9168   LEN is passed through to fn_type_unification.  */
9169
9170int
9171more_specialized (pat1, pat2, deduce, len)
9172     tree pat1, pat2;
9173     int deduce;
9174     int len;
9175{
9176  tree targs;
9177  int winner = 0;
9178
9179  targs = get_bindings_real (pat1, DECL_TEMPLATE_RESULT (pat2),
9180                             NULL_TREE, 0, deduce, len);
9181  if (targs)
9182    --winner;
9183
9184  targs = get_bindings_real (pat2, DECL_TEMPLATE_RESULT (pat1),
9185                             NULL_TREE, 0, deduce, len);
9186  if (targs)
9187    ++winner;
9188
9189  return winner;
9190}
9191
9192/* Given two class template specialization list nodes PAT1 and PAT2, return:
9193
9194   1 if PAT1 is more specialized than PAT2 as described in [temp.class.order].
9195   -1 if PAT2 is more specialized than PAT1.
9196   0 if neither is more specialized.  */
9197
9198int
9199more_specialized_class (pat1, pat2)
9200     tree pat1, pat2;
9201{
9202  tree targs;
9203  int winner = 0;
9204
9205  targs = get_class_bindings (TREE_VALUE (pat1), TREE_PURPOSE (pat1),
9206			      TREE_PURPOSE (pat2));
9207  if (targs)
9208    --winner;
9209
9210  targs = get_class_bindings (TREE_VALUE (pat2), TREE_PURPOSE (pat2),
9211			      TREE_PURPOSE (pat1));
9212  if (targs)
9213    ++winner;
9214
9215  return winner;
9216}
9217
9218/* Return the template arguments that will produce the function signature
9219   DECL from the function template FN, with the explicit template
9220   arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is 1, the return type must
9221   also match.  Return NULL_TREE if no satisfactory arguments could be
9222   found.  DEDUCE and LEN are passed through to fn_type_unification.  */
9223
9224static tree
9225get_bindings_real (fn, decl, explicit_args, check_rettype, deduce, len)
9226     tree fn, decl, explicit_args;
9227     int check_rettype, deduce, len;
9228{
9229  int ntparms = DECL_NTPARMS (fn);
9230  tree targs = make_tree_vec (ntparms);
9231  tree decl_type;
9232  tree decl_arg_types;
9233  int i;
9234
9235  /* Substitute the explicit template arguments into the type of DECL.
9236     The call to fn_type_unification will handle substitution into the
9237     FN.  */
9238  decl_type = TREE_TYPE (decl);
9239  if (explicit_args && uses_template_parms (decl_type))
9240    {
9241      tree tmpl;
9242      tree converted_args;
9243
9244      if (DECL_TEMPLATE_INFO (decl))
9245	tmpl = DECL_TI_TEMPLATE (decl);
9246      else
9247	/* We can get here for some illegal specializations.  */
9248	return NULL_TREE;
9249
9250      converted_args
9251	= (coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
9252				  explicit_args, NULL_TREE,
9253				  tf_none, /*require_all_arguments=*/0));
9254      if (converted_args == error_mark_node)
9255	return NULL_TREE;
9256
9257      decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
9258      if (decl_type == error_mark_node)
9259	return NULL_TREE;
9260    }
9261
9262  decl_arg_types = TYPE_ARG_TYPES (decl_type);
9263  /* Never do unification on the 'this' parameter.  */
9264  if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
9265    decl_arg_types = TREE_CHAIN (decl_arg_types);
9266
9267  i = fn_type_unification (fn, explicit_args, targs,
9268			   decl_arg_types,
9269			   (check_rettype || DECL_CONV_FN_P (fn)
9270	                    ? TREE_TYPE (decl_type) : NULL_TREE),
9271			   deduce, len);
9272
9273  if (i != 0)
9274    return NULL_TREE;
9275
9276  return targs;
9277}
9278
9279/* For most uses, we want to check the return type.  */
9280
9281tree
9282get_bindings (fn, decl, explicit_args)
9283     tree fn, decl, explicit_args;
9284{
9285  return get_bindings_real (fn, decl, explicit_args, 1, DEDUCE_EXACT, -1);
9286}
9287
9288/* But for resolve_overloaded_unification, we only care about the parameter
9289   types.  */
9290
9291static tree
9292get_bindings_overload (fn, decl, explicit_args)
9293     tree fn, decl, explicit_args;
9294{
9295  return get_bindings_real (fn, decl, explicit_args, 0, DEDUCE_EXACT, -1);
9296}
9297
9298/* Return the innermost template arguments that, when applied to a
9299   template specialization whose innermost template parameters are
9300   TPARMS, and whose specialization arguments are PARMS, yield the
9301   ARGS.
9302
9303   For example, suppose we have:
9304
9305     template <class T, class U> struct S {};
9306     template <class T> struct S<T*, int> {};
9307
9308   Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
9309   {T}, the PARMS will be {T*, int} and the ARGS will be {double*,
9310   int}.  The resulting vector will be {double}, indicating that `T'
9311   is bound to `double'.  */
9312
9313static tree
9314get_class_bindings (tparms, parms, args)
9315     tree tparms, parms, args;
9316{
9317  int i, ntparms = TREE_VEC_LENGTH (tparms);
9318  tree vec = make_tree_vec (ntparms);
9319
9320  if (unify (tparms, vec, parms, INNERMOST_TEMPLATE_ARGS (args),
9321  	     UNIFY_ALLOW_NONE))
9322    return NULL_TREE;
9323
9324  for (i =  0; i < ntparms; ++i)
9325    if (! TREE_VEC_ELT (vec, i))
9326      return NULL_TREE;
9327
9328  if (verify_class_unification (vec, parms, args))
9329    return NULL_TREE;
9330
9331  return vec;
9332}
9333
9334/* In INSTANTIATIONS is a list of <INSTANTIATION, TEMPLATE> pairs.
9335   Pick the most specialized template, and return the corresponding
9336   instantiation, or if there is no corresponding instantiation, the
9337   template itself.  If there is no most specialized template,
9338   error_mark_node is returned.  If there are no templates at all,
9339   NULL_TREE is returned.  */
9340
9341tree
9342most_specialized_instantiation (instantiations)
9343     tree instantiations;
9344{
9345  tree fn, champ;
9346  int fate;
9347
9348  if (!instantiations)
9349    return NULL_TREE;
9350
9351  champ = instantiations;
9352  for (fn = TREE_CHAIN (instantiations); fn; fn = TREE_CHAIN (fn))
9353    {
9354      fate = more_specialized (TREE_VALUE (champ), TREE_VALUE (fn),
9355                               DEDUCE_EXACT, -1);
9356      if (fate == 1)
9357	;
9358      else
9359	{
9360	  if (fate == 0)
9361	    {
9362	      fn = TREE_CHAIN (fn);
9363	      if (! fn)
9364		return error_mark_node;
9365	    }
9366	  champ = fn;
9367	}
9368    }
9369
9370  for (fn = instantiations; fn && fn != champ; fn = TREE_CHAIN (fn))
9371    {
9372      fate = more_specialized (TREE_VALUE (champ), TREE_VALUE (fn),
9373                               DEDUCE_EXACT, -1);
9374      if (fate != 1)
9375	return error_mark_node;
9376    }
9377
9378  return TREE_PURPOSE (champ) ? TREE_PURPOSE (champ) : TREE_VALUE (champ);
9379}
9380
9381/* Return the most specialized of the list of templates in FNS that can
9382   produce an instantiation matching DECL, given the explicit template
9383   arguments EXPLICIT_ARGS.  */
9384
9385static tree
9386most_specialized (fns, decl, explicit_args)
9387     tree fns, decl, explicit_args;
9388{
9389  tree candidates = NULL_TREE;
9390  tree fn, args;
9391
9392  for (fn = fns; fn; fn = TREE_CHAIN (fn))
9393    {
9394      tree candidate = TREE_VALUE (fn);
9395
9396      args = get_bindings (candidate, decl, explicit_args);
9397      if (args)
9398	candidates = tree_cons (NULL_TREE, candidate, candidates);
9399    }
9400
9401  return most_specialized_instantiation (candidates);
9402}
9403
9404/* If DECL is a specialization of some template, return the most
9405   general such template.  Otherwise, returns NULL_TREE.
9406
9407   For example, given:
9408
9409     template <class T> struct S { template <class U> void f(U); };
9410
9411   if TMPL is `template <class U> void S<int>::f(U)' this will return
9412   the full template.  This function will not trace past partial
9413   specializations, however.  For example, given in addition:
9414
9415     template <class T> struct S<T*> { template <class U> void f(U); };
9416
9417   if TMPL is `template <class U> void S<int*>::f(U)' this will return
9418   `template <class T> template <class U> S<T*>::f(U)'.  */
9419
9420tree
9421most_general_template (decl)
9422     tree decl;
9423{
9424  /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
9425     an immediate specialization.  */
9426  if (TREE_CODE (decl) == FUNCTION_DECL)
9427    {
9428      if (DECL_TEMPLATE_INFO (decl)) {
9429	decl = DECL_TI_TEMPLATE (decl);
9430
9431	/* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
9432	   template friend.  */
9433	if (TREE_CODE (decl) != TEMPLATE_DECL)
9434	  return NULL_TREE;
9435      } else
9436	return NULL_TREE;
9437    }
9438
9439  /* Look for more and more general templates.  */
9440  while (DECL_TEMPLATE_INFO (decl))
9441    {
9442      /* The DECL_TI_TEMPLATE can be a LOOKUP_EXPR or IDENTIFIER_NODE
9443	 in some cases.  (See cp-tree.h for details.)  */
9444      if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
9445	break;
9446
9447      /* Stop if we run into an explicitly specialized class template.  */
9448      if (!DECL_NAMESPACE_SCOPE_P (decl)
9449	  && DECL_CONTEXT (decl)
9450	  && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
9451	break;
9452
9453      decl = DECL_TI_TEMPLATE (decl);
9454    }
9455
9456  return decl;
9457}
9458
9459/* Return the most specialized of the class template specializations
9460   of TMPL which can produce an instantiation matching ARGS, or
9461   error_mark_node if the choice is ambiguous.  */
9462
9463static tree
9464most_specialized_class (tmpl, args)
9465     tree tmpl;
9466     tree args;
9467{
9468  tree list = NULL_TREE;
9469  tree t;
9470  tree champ;
9471  int fate;
9472
9473  tmpl = most_general_template (tmpl);
9474  for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
9475    {
9476      tree spec_args
9477	= get_class_bindings (TREE_VALUE (t), TREE_PURPOSE (t), args);
9478      if (spec_args)
9479	{
9480	  list = tree_cons (TREE_PURPOSE (t), TREE_VALUE (t), list);
9481	  TREE_TYPE (list) = TREE_TYPE (t);
9482	}
9483    }
9484
9485  if (! list)
9486    return NULL_TREE;
9487
9488  t = list;
9489  champ = t;
9490  t = TREE_CHAIN (t);
9491  for (; t; t = TREE_CHAIN (t))
9492    {
9493      fate = more_specialized_class (champ, t);
9494      if (fate == 1)
9495	;
9496      else
9497	{
9498	  if (fate == 0)
9499	    {
9500	      t = TREE_CHAIN (t);
9501	      if (! t)
9502		return error_mark_node;
9503	    }
9504	  champ = t;
9505	}
9506    }
9507
9508  for (t = list; t && t != champ; t = TREE_CHAIN (t))
9509    {
9510      fate = more_specialized_class (champ, t);
9511      if (fate != 1)
9512	return error_mark_node;
9513    }
9514
9515  return champ;
9516}
9517
9518/* called from the parser.  */
9519
9520void
9521do_decl_instantiation (declspecs, declarator, storage)
9522     tree declspecs, declarator, storage;
9523{
9524  tree decl = grokdeclarator (declarator, declspecs, NORMAL, 0, NULL);
9525  tree result = NULL_TREE;
9526  int extern_p = 0;
9527
9528  if (!decl)
9529    /* An error occurred, for which grokdeclarator has already issued
9530       an appropriate message.  */
9531    return;
9532  else if (! DECL_LANG_SPECIFIC (decl))
9533    {
9534      error ("explicit instantiation of non-template `%#D'", decl);
9535      return;
9536    }
9537  else if (TREE_CODE (decl) == VAR_DECL)
9538    {
9539      /* There is an asymmetry here in the way VAR_DECLs and
9540	 FUNCTION_DECLs are handled by grokdeclarator.  In the case of
9541	 the latter, the DECL we get back will be marked as a
9542	 template instantiation, and the appropriate
9543	 DECL_TEMPLATE_INFO will be set up.  This does not happen for
9544	 VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
9545	 should handle VAR_DECLs as it currently handles
9546	 FUNCTION_DECLs.  */
9547      result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, 0);
9548      if (result && TREE_CODE (result) != VAR_DECL)
9549	{
9550	  error ("no matching template for `%D' found", result);
9551	  return;
9552	}
9553    }
9554  else if (TREE_CODE (decl) != FUNCTION_DECL)
9555    {
9556      error ("explicit instantiation of `%#D'", decl);
9557      return;
9558    }
9559  else
9560    result = decl;
9561
9562  /* Check for various error cases.  Note that if the explicit
9563     instantiation is legal the RESULT will currently be marked as an
9564     *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
9565     until we get here.  */
9566
9567  if (DECL_TEMPLATE_SPECIALIZATION (result))
9568    {
9569      /* DR 259 [temp.spec].
9570
9571	 Both an explicit instantiation and a declaration of an explicit
9572	 specialization shall not appear in a program unless the explicit
9573	 instantiation follows a declaration of the explicit specialization.
9574
9575	 For a given set of template parameters, if an explicit
9576	 instantiation of a template appears after a declaration of an
9577	 explicit specialization for that template, the explicit
9578	 instantiation has no effect.  */
9579      return;
9580    }
9581  else if (DECL_EXPLICIT_INSTANTIATION (result))
9582    {
9583      /* [temp.spec]
9584
9585	 No program shall explicitly instantiate any template more
9586	 than once.
9587
9588	 We check DECL_INTERFACE_KNOWN so as not to complain when the first
9589	 instantiation was `extern' and the second is not, and EXTERN_P for
9590	 the opposite case.  If -frepo, chances are we already got marked
9591	 as an explicit instantiation because of the repo file.  */
9592      if (DECL_INTERFACE_KNOWN (result) && !extern_p && !flag_use_repository)
9593	pedwarn ("duplicate explicit instantiation of `%#D'", result);
9594
9595      /* If we've already instantiated the template, just return now.  */
9596      if (DECL_INTERFACE_KNOWN (result))
9597	return;
9598    }
9599  else if (!DECL_IMPLICIT_INSTANTIATION (result))
9600    {
9601      error ("no matching template for `%D' found", result);
9602      return;
9603    }
9604  else if (!DECL_TEMPLATE_INFO (result))
9605    {
9606      pedwarn ("explicit instantiation of non-template `%#D'", result);
9607      return;
9608    }
9609
9610  if (flag_external_templates)
9611    return;
9612
9613  if (storage == NULL_TREE)
9614    ;
9615  else if (storage == ridpointers[(int) RID_EXTERN])
9616    {
9617      if (pedantic && !in_system_header)
9618	pedwarn ("ISO C++ forbids the use of `extern' on explicit instantiations");
9619      extern_p = 1;
9620    }
9621  else
9622    error ("storage class `%D' applied to template instantiation",
9623	      storage);
9624
9625  SET_DECL_EXPLICIT_INSTANTIATION (result);
9626  mark_decl_instantiated (result, extern_p);
9627  repo_template_instantiated (result, extern_p);
9628  if (! extern_p)
9629    instantiate_decl (result, /*defer_ok=*/1);
9630}
9631
9632void
9633mark_class_instantiated (t, extern_p)
9634     tree t;
9635     int extern_p;
9636{
9637  SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
9638  SET_CLASSTYPE_INTERFACE_KNOWN (t);
9639  CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
9640  TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
9641  if (! extern_p)
9642    {
9643      CLASSTYPE_DEBUG_REQUESTED (t) = 1;
9644      rest_of_type_compilation (t, 1);
9645    }
9646}
9647
9648/* Perform an explicit instantiation of template class T.  STORAGE, if
9649   non-null, is the RID for extern, inline or static.  COMPLAIN is
9650   non-zero if this is called from the parser, zero if called recursively,
9651   since the standard is unclear (as detailed below).  */
9652
9653void
9654do_type_instantiation (t, storage, complain)
9655     tree t, storage;
9656     tsubst_flags_t complain;
9657{
9658  int extern_p = 0;
9659  int nomem_p = 0;
9660  int static_p = 0;
9661
9662  if (TREE_CODE (t) == TYPE_DECL)
9663    t = TREE_TYPE (t);
9664
9665  if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
9666    {
9667      error ("explicit instantiation of non-template type `%T'", t);
9668      return;
9669    }
9670
9671  complete_type (t);
9672
9673  /* With -fexternal-templates, explicit instantiations are treated the same
9674     as implicit ones.  */
9675  if (flag_external_templates)
9676    return;
9677
9678  if (!COMPLETE_TYPE_P (t))
9679    {
9680      if (complain & tf_error)
9681	error ("explicit instantiation of `%#T' before definition of template",
9682		  t);
9683      return;
9684    }
9685
9686  if (storage != NULL_TREE)
9687    {
9688      if (pedantic && !in_system_header)
9689	pedwarn("ISO C++ forbids the use of `%s' on explicit instantiations",
9690		   IDENTIFIER_POINTER (storage));
9691
9692      if (storage == ridpointers[(int) RID_INLINE])
9693	nomem_p = 1;
9694      else if (storage == ridpointers[(int) RID_EXTERN])
9695	extern_p = 1;
9696      else if (storage == ridpointers[(int) RID_STATIC])
9697	static_p = 1;
9698      else
9699	{
9700	  error ("storage class `%D' applied to template instantiation",
9701		    storage);
9702	  extern_p = 0;
9703	}
9704    }
9705
9706  if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
9707    {
9708      /* DR 259 [temp.spec].
9709
9710	 Both an explicit instantiation and a declaration of an explicit
9711	 specialization shall not appear in a program unless the explicit
9712	 instantiation follows a declaration of the explicit specialization.
9713
9714	 For a given set of template parameters, if an explicit
9715	 instantiation of a template appears after a declaration of an
9716	 explicit specialization for that template, the explicit
9717	 instantiation has no effect.  */
9718      return;
9719    }
9720  else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
9721    {
9722      /* [temp.spec]
9723
9724	 No program shall explicitly instantiate any template more
9725	 than once.
9726
9727         If CLASSTYPE_INTERFACE_ONLY, then the first explicit instantiation
9728	 was `extern'.  If EXTERN_P then the second is.  If -frepo, chances
9729	 are we already got marked as an explicit instantiation because of the
9730	 repo file.  All these cases are OK.  */
9731      if (!CLASSTYPE_INTERFACE_ONLY (t) && !extern_p && !flag_use_repository
9732	  && (complain & tf_error))
9733	pedwarn ("duplicate explicit instantiation of `%#T'", t);
9734
9735      /* If we've already instantiated the template, just return now.  */
9736      if (!CLASSTYPE_INTERFACE_ONLY (t))
9737	return;
9738    }
9739
9740  mark_class_instantiated (t, extern_p);
9741  repo_template_instantiated (t, extern_p);
9742
9743  if (nomem_p)
9744    return;
9745
9746  {
9747    tree tmp;
9748
9749    /* In contrast to implicit instantiation, where only the
9750       declarations, and not the definitions, of members are
9751       instantiated, we have here:
9752
9753         [temp.explicit]
9754
9755	 The explicit instantiation of a class template specialization
9756	 implies the instantiation of all of its members not
9757	 previously explicitly specialized in the translation unit
9758	 containing the explicit instantiation.
9759
9760       Of course, we can't instantiate member template classes, since
9761       we don't have any arguments for them.  Note that the standard
9762       is unclear on whether the instantiation of the members are
9763       *explicit* instantiations or not.  We choose to be generous,
9764       and not set DECL_EXPLICIT_INSTANTIATION.  Therefore, we allow
9765       the explicit instantiation of a class where some of the members
9766       have no definition in the current translation unit.  */
9767
9768    if (! static_p)
9769      for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
9770	if (TREE_CODE (tmp) == FUNCTION_DECL
9771	    && DECL_TEMPLATE_INSTANTIATION (tmp))
9772	  {
9773	    mark_decl_instantiated (tmp, extern_p);
9774	    repo_template_instantiated (tmp, extern_p);
9775	    if (! extern_p)
9776	      instantiate_decl (tmp, /*defer_ok=*/1);
9777	  }
9778
9779    for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
9780      if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
9781	{
9782	  mark_decl_instantiated (tmp, extern_p);
9783	  repo_template_instantiated (tmp, extern_p);
9784	  if (! extern_p)
9785	    instantiate_decl (tmp, /*defer_ok=*/1);
9786	}
9787
9788    for (tmp = CLASSTYPE_TAGS (t); tmp; tmp = TREE_CHAIN (tmp))
9789      if (IS_AGGR_TYPE (TREE_VALUE (tmp))
9790	  && !uses_template_parms (CLASSTYPE_TI_ARGS (TREE_VALUE (tmp))))
9791	do_type_instantiation (TYPE_MAIN_DECL (TREE_VALUE (tmp)), storage, 0);
9792  }
9793}
9794
9795/* Given a function DECL, which is a specialization of TMPL, modify
9796   DECL to be a re-instantiation of TMPL with the same template
9797   arguments.  TMPL should be the template into which tsubst'ing
9798   should occur for DECL, not the most general template.
9799
9800   One reason for doing this is a scenario like this:
9801
9802     template <class T>
9803     void f(const T&, int i);
9804
9805     void g() { f(3, 7); }
9806
9807     template <class T>
9808     void f(const T& t, const int i) { }
9809
9810   Note that when the template is first instantiated, with
9811   instantiate_template, the resulting DECL will have no name for the
9812   first parameter, and the wrong type for the second.  So, when we go
9813   to instantiate the DECL, we regenerate it.  */
9814
9815static void
9816regenerate_decl_from_template (decl, tmpl)
9817     tree decl;
9818     tree tmpl;
9819{
9820  /* The most general version of TMPL.  */
9821  tree gen_tmpl;
9822  /* The arguments used to instantiate DECL, from the most general
9823     template.  */
9824  tree args;
9825  tree code_pattern;
9826  tree new_decl;
9827  int unregistered;
9828
9829  args = DECL_TI_ARGS (decl);
9830  code_pattern = DECL_TEMPLATE_RESULT (tmpl);
9831
9832  /* Unregister the specialization so that when we tsubst we will not
9833     just return DECL.  We don't have to unregister DECL from TMPL
9834     because if would only be registered there if it were a partial
9835     instantiation of a specialization, which it isn't: it's a full
9836     instantiation.  */
9837  gen_tmpl = most_general_template (tmpl);
9838  unregistered = unregister_specialization (decl, gen_tmpl);
9839
9840  /* If the DECL was not unregistered then something peculiar is
9841     happening: we created a specialization but did not call
9842     register_specialization for it.  */
9843  my_friendly_assert (unregistered, 0);
9844
9845  if (TREE_CODE (decl) == VAR_DECL)
9846    /* Make sure that we can see identifiers, and compute access
9847       correctly, for the class members used in the declaration of
9848       this static variable.  */
9849    pushclass (DECL_CONTEXT (decl), 2);
9850
9851  /* Do the substitution to get the new declaration.  */
9852  new_decl = tsubst (code_pattern, args, tf_error, NULL_TREE);
9853
9854  if (TREE_CODE (decl) == VAR_DECL)
9855    {
9856      /* Set up DECL_INITIAL, since tsubst doesn't.  */
9857      DECL_INITIAL (new_decl) =
9858	tsubst_expr (DECL_INITIAL (code_pattern), args,
9859		     tf_error, DECL_TI_TEMPLATE (decl));
9860      /* Pop the class context we pushed above.  */
9861      popclass ();
9862    }
9863  else if (TREE_CODE (decl) == FUNCTION_DECL)
9864    {
9865      /* Convince duplicate_decls to use the DECL_ARGUMENTS from the
9866	 new decl.  */
9867      DECL_INITIAL (new_decl) = error_mark_node;
9868      /* And don't complain about a duplicate definition.  */
9869      DECL_INITIAL (decl) = NULL_TREE;
9870    }
9871
9872  /* The immediate parent of the new template is still whatever it was
9873     before, even though tsubst sets DECL_TI_TEMPLATE up as the most
9874     general template.  We also reset the DECL_ASSEMBLER_NAME since
9875     tsubst always calculates the name as if the function in question
9876     were really a template instance, and sometimes, with friend
9877     functions, this is not so.  See tsubst_friend_function for
9878     details.  */
9879  DECL_TI_TEMPLATE (new_decl) = DECL_TI_TEMPLATE (decl);
9880  COPY_DECL_ASSEMBLER_NAME (decl, new_decl);
9881  COPY_DECL_RTL (decl, new_decl);
9882  DECL_USE_TEMPLATE (new_decl) = DECL_USE_TEMPLATE (decl);
9883
9884  /* Call duplicate decls to merge the old and new declarations.  */
9885  duplicate_decls (new_decl, decl);
9886
9887  /* Now, re-register the specialization.  */
9888  register_specialization (decl, gen_tmpl, args);
9889}
9890
9891/* Produce the definition of D, a _DECL generated from a template.  If
9892   DEFER_OK is non-zero, then we don't have to actually do the
9893   instantiation now; we just have to do it sometime.  */
9894
9895tree
9896instantiate_decl (d, defer_ok)
9897     tree d;
9898     int defer_ok;
9899{
9900  tree tmpl = DECL_TI_TEMPLATE (d);
9901  tree args = DECL_TI_ARGS (d);
9902  tree td;
9903  tree code_pattern;
9904  tree spec;
9905  tree gen_tmpl;
9906  int pattern_defined;
9907  int line = lineno;
9908  int need_push;
9909  const char *file = input_filename;
9910
9911  /* This function should only be used to instantiate templates for
9912     functions and static member variables.  */
9913  my_friendly_assert (TREE_CODE (d) == FUNCTION_DECL
9914		      || TREE_CODE (d) == VAR_DECL, 0);
9915
9916  /* Don't instantiate cloned functions.  Instead, instantiate the
9917     functions they cloned.  */
9918  if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
9919    d = DECL_CLONED_FUNCTION (d);
9920
9921  if (DECL_TEMPLATE_INSTANTIATED (d))
9922    /* D has already been instantiated.  It might seem reasonable to
9923       check whether or not D is an explicit instantiation, and, if so,
9924       stop here.  But when an explicit instantiation is deferred
9925       until the end of the compilation, DECL_EXPLICIT_INSTANTIATION
9926       is set, even though we still need to do the instantiation.  */
9927    return d;
9928
9929  /* If we already have a specialization of this declaration, then
9930     there's no reason to instantiate it.  Note that
9931     retrieve_specialization gives us both instantiations and
9932     specializations, so we must explicitly check
9933     DECL_TEMPLATE_SPECIALIZATION.  */
9934  gen_tmpl = most_general_template (tmpl);
9935  spec = retrieve_specialization (gen_tmpl, args);
9936  if (spec != NULL_TREE && DECL_TEMPLATE_SPECIALIZATION (spec))
9937    return spec;
9938
9939  /* This needs to happen before any tsubsting.  */
9940  if (! push_tinst_level (d))
9941    return d;
9942
9943  timevar_push (TV_PARSE);
9944
9945  /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
9946     for the instantiation.  This is not always the most general
9947     template.  Consider, for example:
9948
9949        template <class T>
9950	struct S { template <class U> void f();
9951	           template <> void f<int>(); };
9952
9953     and an instantiation of S<double>::f<int>.  We want TD to be the
9954     specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
9955  td = tmpl;
9956  while (/* An instantiation cannot have a definition, so we need a
9957	    more general template.  */
9958	 DECL_TEMPLATE_INSTANTIATION (td)
9959	   /* We must also deal with friend templates.  Given:
9960
9961		template <class T> struct S {
9962		  template <class U> friend void f() {};
9963		};
9964
9965	      S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
9966	      so far as the language is concerned, but that's still
9967	      where we get the pattern for the instantiation from.  On
9968	      other hand, if the definition comes outside the class, say:
9969
9970		template <class T> struct S {
9971		  template <class U> friend void f();
9972		};
9973		template <class U> friend void f() {}
9974
9975	      we don't need to look any further.  That's what the check for
9976	      DECL_INITIAL is for.  */
9977	  || (TREE_CODE (d) == FUNCTION_DECL
9978	      && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (td)
9979	      && !DECL_INITIAL (DECL_TEMPLATE_RESULT (td))))
9980    {
9981      /* The present template, TD, should not be a definition.  If it
9982	 were a definition, we should be using it!  Note that we
9983	 cannot restructure the loop to just keep going until we find
9984	 a template with a definition, since that might go too far if
9985	 a specialization was declared, but not defined.  */
9986      my_friendly_assert (!(TREE_CODE (d) == VAR_DECL
9987			    && !DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (td))),
9988			  0);
9989
9990      /* Fetch the more general template.  */
9991      td = DECL_TI_TEMPLATE (td);
9992    }
9993
9994  code_pattern = DECL_TEMPLATE_RESULT (td);
9995
9996  if (TREE_CODE (d) == FUNCTION_DECL)
9997    pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
9998  else
9999    pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
10000
10001  lineno = DECL_SOURCE_LINE (d);
10002  input_filename = DECL_SOURCE_FILE (d);
10003
10004  if (pattern_defined)
10005    {
10006      /* Let the repository code that this template definition is
10007	 available.
10008
10009	 The repository doesn't need to know about cloned functions
10010	 because they never actually show up in the object file.  It
10011	 does need to know about the clones; those are the symbols
10012	 that the linker will be emitting error messages about.  */
10013      if (DECL_MAYBE_IN_CHARGE_CONSTRUCTOR_P (d)
10014	  || DECL_MAYBE_IN_CHARGE_DESTRUCTOR_P (d))
10015	{
10016	  tree t;
10017
10018	  for (t = TREE_CHAIN (d);
10019	       t && DECL_CLONED_FUNCTION_P (t);
10020	       t = TREE_CHAIN (t))
10021	    repo_template_used (t);
10022	}
10023      else
10024	repo_template_used (d);
10025
10026      if (flag_external_templates && ! DECL_INTERFACE_KNOWN (d))
10027	{
10028	  if (flag_alt_external_templates)
10029	    {
10030	      if (interface_unknown)
10031		warn_if_unknown_interface (d);
10032	    }
10033	  else if (DECL_INTERFACE_KNOWN (code_pattern))
10034	    {
10035	      DECL_INTERFACE_KNOWN (d) = 1;
10036	      DECL_NOT_REALLY_EXTERN (d) = ! DECL_EXTERNAL (code_pattern);
10037	    }
10038	  else
10039	    warn_if_unknown_interface (code_pattern);
10040	}
10041
10042      if (at_eof)
10043	import_export_decl (d);
10044    }
10045
10046  if (!defer_ok)
10047    {
10048      /* Recheck the substitutions to obtain any warning messages
10049	 about ignoring cv qualifiers.  */
10050      tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
10051      tree type = TREE_TYPE (gen);
10052
10053      if (TREE_CODE (gen) == FUNCTION_DECL)
10054	{
10055	  tsubst (DECL_ARGUMENTS (gen), args, tf_error | tf_warning, d);
10056	  tsubst (TYPE_RAISES_EXCEPTIONS (type), args,
10057		  tf_error | tf_warning, d);
10058	  /* Don't simply tsubst the function type, as that will give
10059	     duplicate warnings about poor parameter qualifications.
10060	     The function arguments are the same as the decl_arguments
10061	     without the top level cv qualifiers. */
10062	  type = TREE_TYPE (type);
10063	}
10064      tsubst (type, args, tf_error | tf_warning, d);
10065    }
10066
10067  if (TREE_CODE (d) == VAR_DECL && DECL_INITIALIZED_IN_CLASS_P (d)
10068      && DECL_INITIAL (d) == NULL_TREE)
10069    /* We should have set up DECL_INITIAL in instantiate_class_template.  */
10070    abort ();
10071  /* Reject all external templates except inline functions.  */
10072  else if (DECL_INTERFACE_KNOWN (d)
10073	   && ! DECL_NOT_REALLY_EXTERN (d)
10074	   && ! (TREE_CODE (d) == FUNCTION_DECL
10075		 && DECL_INLINE (d)))
10076    goto out;
10077  /* Defer all other templates, unless we have been explicitly
10078     forbidden from doing so.  We restore the source position here
10079     because it's used by add_pending_template.  */
10080  else if (! pattern_defined || defer_ok)
10081    {
10082      lineno = line;
10083      input_filename = file;
10084
10085      if (at_eof && !pattern_defined
10086	  && DECL_EXPLICIT_INSTANTIATION (d))
10087	/* [temp.explicit]
10088
10089	   The definition of a non-exported function template, a
10090	   non-exported member function template, or a non-exported
10091	   member function or static data member of a class template
10092	   shall be present in every translation unit in which it is
10093	   explicitly instantiated.  */
10094	pedwarn
10095	  ("explicit instantiation of `%D' but no definition available", d);
10096
10097      add_pending_template (d);
10098      goto out;
10099    }
10100
10101  need_push = !global_bindings_p ();
10102  if (need_push)
10103    push_to_top_level ();
10104
10105  /* We're now committed to instantiating this template.  Mark it as
10106     instantiated so that recursive calls to instantiate_decl do not
10107     try to instantiate it again.  */
10108  DECL_TEMPLATE_INSTANTIATED (d) = 1;
10109
10110  /* Regenerate the declaration in case the template has been modified
10111     by a subsequent redeclaration.  */
10112  regenerate_decl_from_template (d, td);
10113
10114  /* We already set the file and line above.  Reset them now in case
10115     they changed as a result of calling regenerate_decl_from_template.  */
10116  lineno = DECL_SOURCE_LINE (d);
10117  input_filename = DECL_SOURCE_FILE (d);
10118
10119  if (TREE_CODE (d) == VAR_DECL)
10120    {
10121      DECL_IN_AGGR_P (d) = 0;
10122      if (DECL_INTERFACE_KNOWN (d))
10123	DECL_EXTERNAL (d) = ! DECL_NOT_REALLY_EXTERN (d);
10124      else
10125	{
10126	  DECL_EXTERNAL (d) = 1;
10127	  DECL_NOT_REALLY_EXTERN (d) = 1;
10128	}
10129      cp_finish_decl (d, DECL_INITIAL (d), NULL_TREE, 0);
10130    }
10131  else if (TREE_CODE (d) == FUNCTION_DECL)
10132    {
10133      htab_t saved_local_specializations;
10134
10135      /* Save away the current list, in case we are instantiating one
10136	 template from within the body of another.  */
10137      saved_local_specializations = local_specializations;
10138
10139      /* Set up the list of local specializations.  */
10140      local_specializations = htab_create (37,
10141					   htab_hash_pointer,
10142					   htab_eq_pointer,
10143					   NULL);
10144
10145      /* Set up context.  */
10146      start_function (NULL_TREE, d, NULL_TREE, SF_PRE_PARSED);
10147
10148      /* Substitute into the body of the function.  */
10149      tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
10150		   tf_error | tf_warning, tmpl);
10151
10152      /* We don't need the local specializations any more.  */
10153      htab_delete (local_specializations);
10154      local_specializations = saved_local_specializations;
10155
10156      /* Finish the function.  */
10157      expand_body (finish_function (0));
10158    }
10159
10160  /* We're not deferring instantiation any more.  */
10161  TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
10162
10163  if (need_push)
10164    pop_from_top_level ();
10165
10166out:
10167  lineno = line;
10168  input_filename = file;
10169
10170  pop_tinst_level ();
10171
10172  timevar_pop (TV_PARSE);
10173
10174  return d;
10175}
10176
10177/* Run through the list of templates that we wish we could
10178   instantiate, and instantiate any we can.  */
10179
10180int
10181instantiate_pending_templates ()
10182{
10183  tree *t;
10184  tree last = NULL_TREE;
10185  int instantiated_something = 0;
10186  int reconsider;
10187
10188  do
10189    {
10190      reconsider = 0;
10191
10192      t = &pending_templates;
10193      while (*t)
10194	{
10195	  tree instantiation = TREE_VALUE (*t);
10196
10197	  reopen_tinst_level (TREE_PURPOSE (*t));
10198
10199	  if (TYPE_P (instantiation))
10200	    {
10201	      tree fn;
10202
10203	      if (!COMPLETE_TYPE_P (instantiation))
10204		{
10205		  instantiate_class_template (instantiation);
10206		  if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
10207		    for (fn = TYPE_METHODS (instantiation);
10208			 fn;
10209			 fn = TREE_CHAIN (fn))
10210		      if (! DECL_ARTIFICIAL (fn))
10211			instantiate_decl (fn, /*defer_ok=*/0);
10212		  if (COMPLETE_TYPE_P (instantiation))
10213		    {
10214		      instantiated_something = 1;
10215		      reconsider = 1;
10216		    }
10217		}
10218
10219	      if (COMPLETE_TYPE_P (instantiation))
10220		/* If INSTANTIATION has been instantiated, then we don't
10221		   need to consider it again in the future.  */
10222		*t = TREE_CHAIN (*t);
10223	      else
10224		{
10225		  last = *t;
10226		  t = &TREE_CHAIN (*t);
10227		}
10228	    }
10229	  else
10230	    {
10231	      if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
10232		  && !DECL_TEMPLATE_INSTANTIATED (instantiation))
10233		{
10234		  instantiation = instantiate_decl (instantiation,
10235						    /*defer_ok=*/0);
10236		  if (DECL_TEMPLATE_INSTANTIATED (instantiation))
10237		    {
10238		      instantiated_something = 1;
10239		      reconsider = 1;
10240		    }
10241		}
10242
10243	      if (DECL_TEMPLATE_SPECIALIZATION (instantiation)
10244		  || DECL_TEMPLATE_INSTANTIATED (instantiation))
10245		/* If INSTANTIATION has been instantiated, then we don't
10246		   need to consider it again in the future.  */
10247		*t = TREE_CHAIN (*t);
10248	      else
10249		{
10250		  last = *t;
10251		  t = &TREE_CHAIN (*t);
10252		}
10253	    }
10254	  tinst_depth = 0;
10255	  current_tinst_level = NULL_TREE;
10256	}
10257      last_pending_template = last;
10258    }
10259  while (reconsider);
10260
10261  return instantiated_something;
10262}
10263
10264/* Substitute ARGVEC into T, which is a list of initializers for
10265   either base class or a non-static data member.  The TREE_PURPOSEs
10266   are DECLs, and the TREE_VALUEs are the initializer values.  Used by
10267   instantiate_decl.  */
10268
10269static tree
10270tsubst_initializer_list (t, argvec)
10271     tree t, argvec;
10272{
10273  tree first = NULL_TREE;
10274  tree *p = &first;
10275
10276  for (; t; t = TREE_CHAIN (t))
10277    {
10278      tree decl;
10279      tree init;
10280      tree val;
10281
10282      decl = tsubst_copy (TREE_PURPOSE (t), argvec, tf_error | tf_warning,
10283			  NULL_TREE);
10284      init = tsubst_expr (TREE_VALUE (t), argvec, tf_error | tf_warning,
10285			  NULL_TREE);
10286
10287      if (!init)
10288	;
10289      else if (TREE_CODE (init) == TREE_LIST)
10290	for (val = init; val; val = TREE_CHAIN (val))
10291	  TREE_VALUE (val) = convert_from_reference (TREE_VALUE (val));
10292      else
10293	init = convert_from_reference (init);
10294
10295      *p = expand_member_init (current_class_ref, decl,
10296			       init ? init : void_type_node);
10297      if (*p)
10298	p = &TREE_CHAIN (*p);
10299    }
10300  return first;
10301}
10302
10303/* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
10304
10305static void
10306set_current_access_from_decl (decl)
10307     tree decl;
10308{
10309  if (TREE_PRIVATE (decl))
10310    current_access_specifier = access_private_node;
10311  else if (TREE_PROTECTED (decl))
10312    current_access_specifier = access_protected_node;
10313  else
10314    current_access_specifier = access_public_node;
10315}
10316
10317/* Instantiate an enumerated type.  TAG is the template type, NEWTAG
10318   is the instantiation (which should have been created with
10319   start_enum) and ARGS are the template arguments to use.  */
10320
10321static void
10322tsubst_enum (tag, newtag, args)
10323     tree tag;
10324     tree newtag;
10325     tree args;
10326{
10327  tree e;
10328
10329  for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
10330    {
10331      tree value;
10332
10333      /* Note that in a template enum, the TREE_VALUE is the
10334	 CONST_DECL, not the corresponding INTEGER_CST.  */
10335      value = tsubst_expr (DECL_INITIAL (TREE_VALUE (e)),
10336			   args, tf_error | tf_warning,
10337			   NULL_TREE);
10338
10339      /* Give this enumeration constant the correct access.  */
10340      set_current_access_from_decl (TREE_VALUE (e));
10341
10342      /* Actually build the enumerator itself.  */
10343      build_enumerator (TREE_PURPOSE (e), value, newtag);
10344    }
10345
10346  finish_enum (newtag);
10347  DECL_SOURCE_LINE (TYPE_NAME (newtag)) = DECL_SOURCE_LINE (TYPE_NAME (tag));
10348  DECL_SOURCE_FILE (TYPE_NAME (newtag)) = DECL_SOURCE_FILE (TYPE_NAME (tag));
10349}
10350
10351/* DECL is a FUNCTION_DECL that is a template specialization.  Return
10352   its type -- but without substituting the innermost set of template
10353   arguments.  So, innermost set of template parameters will appear in
10354   the type.  If CONTEXTP is non-NULL, then the partially substituted
10355   DECL_CONTEXT (if any) will also be filled in.  Similarly, TPARMSP
10356   will be filled in with the substituted template parameters, if it
10357   is non-NULL.  */
10358
10359tree
10360get_mostly_instantiated_function_type (decl, contextp, tparmsp)
10361     tree decl;
10362     tree *contextp;
10363     tree *tparmsp;
10364{
10365  tree context = NULL_TREE;
10366  tree fn_type;
10367  tree tmpl;
10368  tree targs;
10369  tree tparms;
10370  int parm_depth;
10371
10372  tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
10373  targs = DECL_TI_ARGS (decl);
10374  tparms = DECL_TEMPLATE_PARMS (tmpl);
10375  parm_depth = TMPL_PARMS_DEPTH (tparms);
10376
10377  /* There should be as many levels of arguments as there are levels
10378     of parameters.  */
10379  my_friendly_assert (parm_depth == TMPL_ARGS_DEPTH (targs), 0);
10380
10381  fn_type = TREE_TYPE (tmpl);
10382  if (DECL_STATIC_FUNCTION_P (decl))
10383    context = DECL_CONTEXT (decl);
10384
10385  if (parm_depth == 1)
10386    /* No substitution is necessary.  */
10387    ;
10388  else
10389    {
10390      int i;
10391      tree partial_args;
10392
10393      /* Replace the innermost level of the TARGS with NULL_TREEs to
10394	 let tsubst know not to substitute for those parameters.  */
10395      partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
10396      for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
10397	SET_TMPL_ARGS_LEVEL (partial_args, i,
10398			     TMPL_ARGS_LEVEL (targs, i));
10399      SET_TMPL_ARGS_LEVEL (partial_args,
10400			   TMPL_ARGS_DEPTH (targs),
10401			   make_tree_vec (DECL_NTPARMS (tmpl)));
10402
10403      /* Now, do the (partial) substitution to figure out the
10404	 appropriate function type.  */
10405      fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
10406      if (DECL_STATIC_FUNCTION_P (decl))
10407	context = tsubst (context, partial_args, tf_error, NULL_TREE);
10408
10409      /* Substitute into the template parameters to obtain the real
10410	 innermost set of parameters.  This step is important if the
10411	 innermost set of template parameters contains value
10412	 parameters whose types depend on outer template parameters.  */
10413      TREE_VEC_LENGTH (partial_args)--;
10414      tparms = tsubst_template_parms (tparms, partial_args, tf_error);
10415    }
10416
10417  if (contextp)
10418    *contextp = context;
10419  if (tparmsp)
10420    *tparmsp = tparms;
10421
10422  return fn_type;
10423}
10424
10425/* Return truthvalue if we're processing a template different from
10426   the last one involved in diagnostics.  */
10427int
10428problematic_instantiation_changed ()
10429{
10430  return last_template_error_tick != tinst_level_tick;
10431}
10432
10433/* Remember current template involved in diagnostics.  */
10434void
10435record_last_problematic_instantiation ()
10436{
10437  last_template_error_tick = tinst_level_tick;
10438}
10439
10440tree
10441current_instantiation ()
10442{
10443  return current_tinst_level;
10444}
10445
10446/* [temp.param] Check that template non-type parm TYPE is of an allowable
10447   type. Return zero for ok, non-zero for disallowed. Issue error and
10448   warning messages under control of COMPLAIN.  */
10449
10450static int
10451invalid_nontype_parm_type_p (type, complain)
10452     tree type;
10453     tsubst_flags_t complain;
10454{
10455  if (INTEGRAL_TYPE_P (type))
10456    return 0;
10457  else if (POINTER_TYPE_P (type))
10458    return 0;
10459  else if (TYPE_PTRMEM_P (type))
10460    return 0;
10461  else if (TYPE_PTRMEMFUNC_P (type))
10462    return 0;
10463  else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
10464    return 0;
10465  else if (TREE_CODE (type) == TYPENAME_TYPE)
10466    return 0;
10467
10468  if (complain & tf_error)
10469    error ("`%#T' is not a valid type for a template constant parameter",
10470              type);
10471  return 1;
10472}
10473