OSDN Git Service

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