OSDN Git Service

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