OSDN Git Service

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