OSDN Git Service

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