OSDN Git Service

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