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