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