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