OSDN Git Service

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