OSDN Git Service

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