OSDN Git Service

cp/:
[pf3gnuchains/gcc-fork.git] / gcc / cp / pt.c
1 /* Handle parameterized types (templates) for GNU C++.
2    Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
3    2001, 2002, 2003, 2004, 2005, 2007, 2008, 2009
4    Free Software Foundation, Inc.
5    Written by Ken Raeburn (raeburn@cygnus.com) while at Watchmaker Computing.
6    Rewritten by Jason Merrill (jason@cygnus.com).
7
8 This file is part of GCC.
9
10 GCC is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 3, or (at your option)
13 any later version.
14
15 GCC is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 GNU General Public License for more details.
19
20 You should have received a copy of the GNU General Public License
21 along with GCC; see the file COPYING3.  If not see
22 <http://www.gnu.org/licenses/>.  */
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 struct pending_template GTY (()) {
58   struct pending_template *next;
59   struct tinst_level *tinst;
60 };
61
62 static GTY(()) struct pending_template *pending_templates;
63 static GTY(()) struct pending_template *last_pending_template;
64
65 int processing_template_parmlist;
66 static int template_header_count;
67
68 static GTY(()) tree saved_trees;
69 static VEC(int,heap) *inline_parm_levels;
70
71 static GTY(()) struct tinst_level *current_tinst_level;
72
73 static GTY(()) tree saved_access_scope;
74
75 /* Live only within one (recursive) call to tsubst_expr.  We use
76    this to pass the statement expression node from the STMT_EXPR
77    to the EXPR_STMT that is its result.  */
78 static tree cur_stmt_expr;
79
80 /* A map from local variable declarations in the body of the template
81    presently being instantiated to the corresponding instantiated
82    local variables.  */
83 static htab_t local_specializations;
84
85 /* Contains canonical template parameter types. The vector is indexed by
86    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
87    TREE_LIST, whose TREE_VALUEs contain the canonical template
88    parameters of various types and levels.  */
89 static GTY(()) VEC(tree,gc) *canonical_template_parms;
90
91 #define UNIFY_ALLOW_NONE 0
92 #define UNIFY_ALLOW_MORE_CV_QUAL 1
93 #define UNIFY_ALLOW_LESS_CV_QUAL 2
94 #define UNIFY_ALLOW_DERIVED 4
95 #define UNIFY_ALLOW_INTEGER 8
96 #define UNIFY_ALLOW_OUTER_LEVEL 16
97 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
98 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
99
100 static void push_access_scope (tree);
101 static void pop_access_scope (tree);
102 static bool resolve_overloaded_unification (tree, tree, tree, tree,
103                                             unification_kind_t, int);
104 static int try_one_overload (tree, tree, tree, tree, tree,
105                              unification_kind_t, int, bool);
106 static int unify (tree, tree, tree, tree, int);
107 static void add_pending_template (tree);
108 static int push_tinst_level (tree);
109 static void pop_tinst_level (void);
110 static tree reopen_tinst_level (struct tinst_level *);
111 static tree tsubst_initializer_list (tree, tree);
112 static tree get_class_bindings (tree, tree, tree);
113 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
114                                    bool, bool);
115 static void tsubst_enum (tree, tree, tree);
116 static tree add_to_template_args (tree, tree);
117 static tree add_outermost_template_args (tree, tree);
118 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
119 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
120                                              tree);
121 static int  type_unification_real (tree, tree, tree, tree,
122                                    int, unification_kind_t, int);
123 static void note_template_header (int);
124 static tree convert_nontype_argument_function (tree, tree);
125 static tree convert_nontype_argument (tree, tree);
126 static tree convert_template_argument (tree, tree, tree,
127                                        tsubst_flags_t, int, tree);
128 static int for_each_template_parm (tree, tree_fn_t, void*,
129                                    struct pointer_set_t*, bool);
130 static tree expand_template_argument_pack (tree);
131 static tree build_template_parm_index (int, int, int, tree, tree);
132 static bool inline_needs_template_parms (tree);
133 static void push_inline_template_parms_recursive (tree, int);
134 static tree retrieve_local_specialization (tree);
135 static void register_local_specialization (tree, tree);
136 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
137 static int mark_template_parm (tree, void *);
138 static int template_parm_this_level_p (tree, void *);
139 static tree tsubst_friend_function (tree, tree);
140 static tree tsubst_friend_class (tree, tree);
141 static int can_complete_type_without_circularity (tree);
142 static tree get_bindings (tree, tree, tree, bool);
143 static int template_decl_level (tree);
144 static int check_cv_quals_for_unify (int, tree, tree);
145 static void template_parm_level_and_index (tree, int*, int*);
146 static int unify_pack_expansion (tree, tree, tree, tree, int, bool, bool);
147 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
148 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
149 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
150 static void regenerate_decl_from_template (tree, tree);
151 static tree most_specialized_class (tree, tree);
152 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
153 static tree tsubst_arg_types (tree, tree, tsubst_flags_t, tree);
154 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
155 static bool check_specialization_scope (void);
156 static tree process_partial_specialization (tree);
157 static void set_current_access_from_decl (tree);
158 static tree get_template_base (tree, tree, tree, tree);
159 static tree try_class_unification (tree, tree, tree, tree);
160 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
161                                            tree, tree);
162 static bool template_template_parm_bindings_ok_p (tree, tree);
163 static int template_args_equal (tree, tree);
164 static void tsubst_default_arguments (tree);
165 static tree for_each_template_parm_r (tree *, int *, void *);
166 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
167 static void copy_default_args_to_explicit_spec (tree);
168 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
169 static int eq_local_specializations (const void *, const void *);
170 static bool dependent_template_arg_p (tree);
171 static bool any_template_arguments_need_structural_equality_p (tree);
172 static bool dependent_type_p_r (tree);
173 static tree tsubst (tree, tree, tsubst_flags_t, tree);
174 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree, bool);
175 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
176 static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
177
178 /* Make the current scope suitable for access checking when we are
179    processing T.  T can be FUNCTION_DECL for instantiated function
180    template, or VAR_DECL for static member variable (need by
181    instantiate_decl).  */
182
183 static void
184 push_access_scope (tree t)
185 {
186   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
187               || TREE_CODE (t) == VAR_DECL);
188
189   if (DECL_FRIEND_CONTEXT (t))
190     push_nested_class (DECL_FRIEND_CONTEXT (t));
191   else if (DECL_CLASS_SCOPE_P (t))
192     push_nested_class (DECL_CONTEXT (t));
193   else
194     push_to_top_level ();
195
196   if (TREE_CODE (t) == FUNCTION_DECL)
197     {
198       saved_access_scope = tree_cons
199         (NULL_TREE, current_function_decl, saved_access_scope);
200       current_function_decl = t;
201     }
202 }
203
204 /* Restore the scope set up by push_access_scope.  T is the node we
205    are processing.  */
206
207 static void
208 pop_access_scope (tree t)
209 {
210   if (TREE_CODE (t) == FUNCTION_DECL)
211     {
212       current_function_decl = TREE_VALUE (saved_access_scope);
213       saved_access_scope = TREE_CHAIN (saved_access_scope);
214     }
215
216   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
217     pop_nested_class ();
218   else
219     pop_from_top_level ();
220 }
221
222 /* Do any processing required when DECL (a member template
223    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
224    to DECL, unless it is a specialization, in which case the DECL
225    itself is returned.  */
226
227 tree
228 finish_member_template_decl (tree decl)
229 {
230   if (decl == error_mark_node)
231     return error_mark_node;
232
233   gcc_assert (DECL_P (decl));
234
235   if (TREE_CODE (decl) == TYPE_DECL)
236     {
237       tree type;
238
239       type = TREE_TYPE (decl);
240       if (type == error_mark_node)
241         return error_mark_node;
242       if (MAYBE_CLASS_TYPE_P (type)
243           && CLASSTYPE_TEMPLATE_INFO (type)
244           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
245         {
246           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
247           check_member_template (tmpl);
248           return tmpl;
249         }
250       return NULL_TREE;
251     }
252   else if (TREE_CODE (decl) == FIELD_DECL)
253     error ("data member %qD cannot be a member template", decl);
254   else if (DECL_TEMPLATE_INFO (decl))
255     {
256       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
257         {
258           check_member_template (DECL_TI_TEMPLATE (decl));
259           return DECL_TI_TEMPLATE (decl);
260         }
261       else
262         return decl;
263     }
264   else
265     error ("invalid member template declaration %qD", decl);
266
267   return error_mark_node;
268 }
269
270 /* Return the template info node corresponding to T, whatever T is.  */
271
272 tree
273 get_template_info (tree t)
274 {
275   tree tinfo = NULL_TREE;
276
277   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
278     tinfo = DECL_TEMPLATE_INFO (t);
279
280   if (!tinfo && TREE_CODE (t) == TYPE_DECL)
281     t = TREE_TYPE (t);
282
283   if (TAGGED_TYPE_P (t))
284     tinfo = TYPE_TEMPLATE_INFO (t);
285
286   return tinfo;
287 }
288
289 /* Returns the template nesting level of the indicated class TYPE.
290
291    For example, in:
292      template <class T>
293      struct A
294      {
295        template <class U>
296        struct B {};
297      };
298
299    A<T>::B<U> has depth two, while A<T> has depth one.
300    Both A<T>::B<int> and A<int>::B<U> have depth one, if
301    they are instantiations, not specializations.
302
303    This function is guaranteed to return 0 if passed NULL_TREE so
304    that, for example, `template_class_depth (current_class_type)' is
305    always safe.  */
306
307 int
308 template_class_depth (tree type)
309 {
310   int depth;
311
312   for (depth = 0;
313        type && TREE_CODE (type) != NAMESPACE_DECL;
314        type = (TREE_CODE (type) == FUNCTION_DECL)
315          ? CP_DECL_CONTEXT (type) : TYPE_CONTEXT (type))
316     {
317       tree tinfo = get_template_info (type);
318
319       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
320           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
321         ++depth;
322     }
323
324   return depth;
325 }
326
327 /* Subroutine of maybe_begin_member_template_processing.
328    Returns true if processing DECL needs us to push template parms.  */
329
330 static bool
331 inline_needs_template_parms (tree decl)
332 {
333   if (! DECL_TEMPLATE_INFO (decl))
334     return false;
335
336   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
337           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
338 }
339
340 /* Subroutine of maybe_begin_member_template_processing.
341    Push the template parms in PARMS, starting from LEVELS steps into the
342    chain, and ending at the beginning, since template parms are listed
343    innermost first.  */
344
345 static void
346 push_inline_template_parms_recursive (tree parmlist, int levels)
347 {
348   tree parms = TREE_VALUE (parmlist);
349   int i;
350
351   if (levels > 1)
352     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
353
354   ++processing_template_decl;
355   current_template_parms
356     = tree_cons (size_int (processing_template_decl),
357                  parms, current_template_parms);
358   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
359
360   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
361                NULL);
362   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
363     {
364       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
365
366       if (parm == error_mark_node)
367         continue;
368
369       gcc_assert (DECL_P (parm));
370
371       switch (TREE_CODE (parm))
372         {
373         case TYPE_DECL:
374         case TEMPLATE_DECL:
375           pushdecl (parm);
376           break;
377
378         case PARM_DECL:
379           {
380             /* Make a CONST_DECL as is done in process_template_parm.
381                It is ugly that we recreate this here; the original
382                version built in process_template_parm is no longer
383                available.  */
384             tree decl = build_decl (CONST_DECL, DECL_NAME (parm),
385                                     TREE_TYPE (parm));
386             DECL_ARTIFICIAL (decl) = 1;
387             TREE_CONSTANT (decl) = 1;
388             TREE_READONLY (decl) = 1;
389             DECL_INITIAL (decl) = DECL_INITIAL (parm);
390             SET_DECL_TEMPLATE_PARM_P (decl);
391             pushdecl (decl);
392           }
393           break;
394
395         default:
396           gcc_unreachable ();
397         }
398     }
399 }
400
401 /* Restore the template parameter context for a member template or
402    a friend template defined in a class definition.  */
403
404 void
405 maybe_begin_member_template_processing (tree decl)
406 {
407   tree parms;
408   int levels = 0;
409
410   if (inline_needs_template_parms (decl))
411     {
412       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
413       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
414
415       if (DECL_TEMPLATE_SPECIALIZATION (decl))
416         {
417           --levels;
418           parms = TREE_CHAIN (parms);
419         }
420
421       push_inline_template_parms_recursive (parms, levels);
422     }
423
424   /* Remember how many levels of template parameters we pushed so that
425      we can pop them later.  */
426   VEC_safe_push (int, heap, inline_parm_levels, levels);
427 }
428
429 /* Undo the effects of maybe_begin_member_template_processing.  */
430
431 void
432 maybe_end_member_template_processing (void)
433 {
434   int i;
435   int last;
436
437   if (VEC_length (int, inline_parm_levels) == 0)
438     return;
439
440   last = VEC_pop (int, inline_parm_levels);
441   for (i = 0; i < last; ++i)
442     {
443       --processing_template_decl;
444       current_template_parms = TREE_CHAIN (current_template_parms);
445       poplevel (0, 0, 0);
446     }
447 }
448
449 /* Return a new template argument vector which contains all of ARGS,
450    but has as its innermost set of arguments the EXTRA_ARGS.  */
451
452 static tree
453 add_to_template_args (tree args, tree extra_args)
454 {
455   tree new_args;
456   int extra_depth;
457   int i;
458   int j;
459
460   extra_depth = TMPL_ARGS_DEPTH (extra_args);
461   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
462
463   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
464     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
465
466   for (j = 1; j <= extra_depth; ++j, ++i)
467     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
468
469   return new_args;
470 }
471
472 /* Like add_to_template_args, but only the outermost ARGS are added to
473    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
474    (EXTRA_ARGS) levels are added.  This function is used to combine
475    the template arguments from a partial instantiation with the
476    template arguments used to attain the full instantiation from the
477    partial instantiation.  */
478
479 static tree
480 add_outermost_template_args (tree args, tree extra_args)
481 {
482   tree new_args;
483
484   /* If there are more levels of EXTRA_ARGS than there are ARGS,
485      something very fishy is going on.  */
486   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
487
488   /* If *all* the new arguments will be the EXTRA_ARGS, just return
489      them.  */
490   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
491     return extra_args;
492
493   /* For the moment, we make ARGS look like it contains fewer levels.  */
494   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
495
496   new_args = add_to_template_args (args, extra_args);
497
498   /* Now, we restore ARGS to its full dimensions.  */
499   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
500
501   return new_args;
502 }
503
504 /* Return the N levels of innermost template arguments from the ARGS.  */
505
506 tree
507 get_innermost_template_args (tree args, int n)
508 {
509   tree new_args;
510   int extra_levels;
511   int i;
512
513   gcc_assert (n >= 0);
514
515   /* If N is 1, just return the innermost set of template arguments.  */
516   if (n == 1)
517     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
518
519   /* If we're not removing anything, just return the arguments we were
520      given.  */
521   extra_levels = TMPL_ARGS_DEPTH (args) - n;
522   gcc_assert (extra_levels >= 0);
523   if (extra_levels == 0)
524     return args;
525
526   /* Make a new set of arguments, not containing the outer arguments.  */
527   new_args = make_tree_vec (n);
528   for (i = 1; i <= n; ++i)
529     SET_TMPL_ARGS_LEVEL (new_args, i,
530                          TMPL_ARGS_LEVEL (args, i + extra_levels));
531
532   return new_args;
533 }
534
535 /* The inverse of get_innermost_template_args: Return all but the innermost
536    EXTRA_LEVELS levels of template arguments from the ARGS.  */
537
538 static tree
539 strip_innermost_template_args (tree args, int extra_levels)
540 {
541   tree new_args;
542   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
543   int i;
544
545   gcc_assert (n >= 0);
546
547   /* If N is 1, just return the outermost set of template arguments.  */
548   if (n == 1)
549     return TMPL_ARGS_LEVEL (args, 1);
550
551   /* If we're not removing anything, just return the arguments we were
552      given.  */
553   gcc_assert (extra_levels >= 0);
554   if (extra_levels == 0)
555     return args;
556
557   /* Make a new set of arguments, not containing the inner arguments.  */
558   new_args = make_tree_vec (n);
559   for (i = 1; i <= n; ++i)
560     SET_TMPL_ARGS_LEVEL (new_args, i,
561                          TMPL_ARGS_LEVEL (args, i));
562
563   return new_args;
564 }
565
566 /* We've got a template header coming up; push to a new level for storing
567    the parms.  */
568
569 void
570 begin_template_parm_list (void)
571 {
572   /* We use a non-tag-transparent scope here, which causes pushtag to
573      put tags in this scope, rather than in the enclosing class or
574      namespace scope.  This is the right thing, since we want
575      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
576      global template class, push_template_decl handles putting the
577      TEMPLATE_DECL into top-level scope.  For a nested template class,
578      e.g.:
579
580        template <class T> struct S1 {
581          template <class T> struct S2 {};
582        };
583
584      pushtag contains special code to call pushdecl_with_scope on the
585      TEMPLATE_DECL for S2.  */
586   begin_scope (sk_template_parms, NULL);
587   ++processing_template_decl;
588   ++processing_template_parmlist;
589   note_template_header (0);
590 }
591
592 /* This routine is called when a specialization is declared.  If it is
593    invalid to declare a specialization here, an error is reported and
594    false is returned, otherwise this routine will return true.  */
595
596 static bool
597 check_specialization_scope (void)
598 {
599   tree scope = current_scope ();
600
601   /* [temp.expl.spec]
602
603      An explicit specialization shall be declared in the namespace of
604      which the template is a member, or, for member templates, in the
605      namespace of which the enclosing class or enclosing class
606      template is a member.  An explicit specialization of a member
607      function, member class or static data member of a class template
608      shall be declared in the namespace of which the class template
609      is a member.  */
610   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
611     {
612       error ("explicit specialization in non-namespace scope %qD", scope);
613       return false;
614     }
615
616   /* [temp.expl.spec]
617
618      In an explicit specialization declaration for a member of a class
619      template or a member template that appears in namespace scope,
620      the member template and some of its enclosing class templates may
621      remain unspecialized, except that the declaration shall not
622      explicitly specialize a class member template if its enclosing
623      class templates are not explicitly specialized as well.  */
624   if (current_template_parms)
625     {
626       error ("enclosing class templates are not explicitly specialized");
627       return false;
628     }
629
630   return true;
631 }
632
633 /* We've just seen template <>.  */
634
635 bool
636 begin_specialization (void)
637 {
638   begin_scope (sk_template_spec, NULL);
639   note_template_header (1);
640   return check_specialization_scope ();
641 }
642
643 /* Called at then end of processing a declaration preceded by
644    template<>.  */
645
646 void
647 end_specialization (void)
648 {
649   finish_scope ();
650   reset_specialization ();
651 }
652
653 /* Any template <>'s that we have seen thus far are not referring to a
654    function specialization.  */
655
656 void
657 reset_specialization (void)
658 {
659   processing_specialization = 0;
660   template_header_count = 0;
661 }
662
663 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
664    it was of the form template <>.  */
665
666 static void
667 note_template_header (int specialization)
668 {
669   processing_specialization = specialization;
670   template_header_count++;
671 }
672
673 /* We're beginning an explicit instantiation.  */
674
675 void
676 begin_explicit_instantiation (void)
677 {
678   gcc_assert (!processing_explicit_instantiation);
679   processing_explicit_instantiation = true;
680 }
681
682
683 void
684 end_explicit_instantiation (void)
685 {
686   gcc_assert (processing_explicit_instantiation);
687   processing_explicit_instantiation = false;
688 }
689
690 /* An explicit specialization or partial specialization TMPL is being
691    declared.  Check that the namespace in which the specialization is
692    occurring is permissible.  Returns false iff it is invalid to
693    specialize TMPL in the current namespace.  */
694
695 static bool
696 check_specialization_namespace (tree tmpl)
697 {
698   tree tpl_ns = decl_namespace_context (tmpl);
699
700   /* [tmpl.expl.spec]
701
702      An explicit specialization shall be declared in the namespace of
703      which the template is a member, or, for member templates, in the
704      namespace of which the enclosing class or enclosing class
705      template is a member.  An explicit specialization of a member
706      function, member class or static data member of a class template
707      shall be declared in the namespace of which the class template is
708      a member.  */
709   if (is_associated_namespace (current_namespace, tpl_ns))
710     /* Same or super-using namespace.  */
711     return true;
712   else
713     {
714       permerror (input_location, "specialization of %qD in different namespace", tmpl);
715       permerror (input_location, "  from definition of %q+#D", tmpl);
716       return false;
717     }
718 }
719
720 /* SPEC is an explicit instantiation.  Check that it is valid to
721    perform this explicit instantiation in the current namespace.  */
722
723 static void
724 check_explicit_instantiation_namespace (tree spec)
725 {
726   tree ns;
727
728   /* DR 275: An explicit instantiation shall appear in an enclosing
729      namespace of its template.  */
730   ns = decl_namespace_context (spec);
731   if (!is_ancestor (current_namespace, ns))
732     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
733                "(which does not enclose namespace %qD)",
734                spec, current_namespace, ns);
735 }
736
737 /* The TYPE is being declared.  If it is a template type, that means it
738    is a partial specialization.  Do appropriate error-checking.  */
739
740 tree
741 maybe_process_partial_specialization (tree type)
742 {
743   tree context;
744
745   if (type == error_mark_node)
746     return error_mark_node;
747
748   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
749     {
750       error ("name of class shadows template template parameter %qD",
751              TYPE_NAME (type));
752       return error_mark_node;
753     }
754
755   context = TYPE_CONTEXT (type);
756
757   if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
758     {
759       /* This is for ordinary explicit specialization and partial
760          specialization of a template class such as:
761
762            template <> class C<int>;
763
764          or:
765
766            template <class T> class C<T*>;
767
768          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
769
770       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
771           && !COMPLETE_TYPE_P (type))
772         {
773           check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
774           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
775           if (processing_template_decl)
776             {
777               if (push_template_decl (TYPE_MAIN_DECL (type))
778                   == error_mark_node)
779                 return error_mark_node;
780             }
781         }
782       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
783         error ("specialization of %qT after instantiation", type);
784     }
785   else if (CLASS_TYPE_P (type)
786            && !CLASSTYPE_USE_TEMPLATE (type)
787            && CLASSTYPE_TEMPLATE_INFO (type)
788            && context && CLASS_TYPE_P (context)
789            && CLASSTYPE_TEMPLATE_INFO (context))
790     {
791       /* This is for an explicit specialization of member class
792          template according to [temp.expl.spec/18]:
793
794            template <> template <class U> class C<int>::D;
795
796          The context `C<int>' must be an implicit instantiation.
797          Otherwise this is just a member class template declared
798          earlier like:
799
800            template <> class C<int> { template <class U> class D; };
801            template <> template <class U> class C<int>::D;
802
803          In the first case, `C<int>::D' is a specialization of `C<T>::D'
804          while in the second case, `C<int>::D' is a primary template
805          and `C<T>::D' may not exist.  */
806
807       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
808           && !COMPLETE_TYPE_P (type))
809         {
810           tree t;
811
812           if (current_namespace
813               != decl_namespace_context (CLASSTYPE_TI_TEMPLATE (type)))
814             {
815               permerror (input_location, "specializing %q#T in different namespace", type);
816               permerror (input_location, "  from definition of %q+#D",
817                          CLASSTYPE_TI_TEMPLATE (type));
818             }
819
820           /* Check for invalid specialization after instantiation:
821
822                template <> template <> class C<int>::D<int>;
823                template <> template <class U> class C<int>::D;  */
824
825           for (t = DECL_TEMPLATE_INSTANTIATIONS
826                  (most_general_template (CLASSTYPE_TI_TEMPLATE (type)));
827                t; t = TREE_CHAIN (t))
828             if (TREE_VALUE (t) != type
829                 && TYPE_CONTEXT (TREE_VALUE (t)) == context)
830               error ("specialization %qT after instantiation %qT",
831                      type, TREE_VALUE (t));
832
833           /* Mark TYPE as a specialization.  And as a result, we only
834              have one level of template argument for the innermost
835              class template.  */
836           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
837           CLASSTYPE_TI_ARGS (type)
838             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
839         }
840     }
841   else if (processing_specialization)
842     {
843       error ("explicit specialization of non-template %qT", type);
844       return error_mark_node;
845     }
846
847   return type;
848 }
849
850 /* Returns nonzero if we can optimize the retrieval of specializations
851    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
852    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
853
854 static inline bool
855 optimize_specialization_lookup_p (tree tmpl)
856 {
857   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
858           && DECL_CLASS_SCOPE_P (tmpl)
859           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
860              parameter.  */
861           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
862           /* The optimized lookup depends on the fact that the
863              template arguments for the member function template apply
864              purely to the containing class, which is not true if the
865              containing class is an explicit or partial
866              specialization.  */
867           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
868           && !DECL_MEMBER_TEMPLATE_P (tmpl)
869           && !DECL_CONV_FN_P (tmpl)
870           /* It is possible to have a template that is not a member
871              template and is not a member of a template class:
872
873              template <typename T>
874              struct S { friend A::f(); };
875
876              Here, the friend function is a template, but the context does
877              not have template information.  The optimized lookup relies
878              on having ARGS be the template arguments for both the class
879              and the function template.  */
880           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
881 }
882
883 /* Retrieve the specialization (in the sense of [temp.spec] - a
884    specialization is either an instantiation or an explicit
885    specialization) of TMPL for the given template ARGS.  If there is
886    no such specialization, return NULL_TREE.  The ARGS are a vector of
887    arguments, or a vector of vectors of arguments, in the case of
888    templates with more than one level of parameters.
889
890    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
891    then we search for a partial specialization matching ARGS.  This
892    parameter is ignored if TMPL is not a class template.  */
893
894 static tree
895 retrieve_specialization (tree tmpl, tree args,
896                          bool class_specializations_p)
897 {
898   if (args == error_mark_node)
899     return NULL_TREE;
900
901   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
902
903   /* There should be as many levels of arguments as there are
904      levels of parameters.  */
905   gcc_assert (TMPL_ARGS_DEPTH (args)
906               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
907
908   if (optimize_specialization_lookup_p (tmpl))
909     {
910       tree class_template;
911       tree class_specialization;
912       VEC(tree,gc) *methods;
913       tree fns;
914       int idx;
915
916       /* The template arguments actually apply to the containing
917          class.  Find the class specialization with those
918          arguments.  */
919       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
920       class_specialization
921         = retrieve_specialization (class_template, args,
922                                    /*class_specializations_p=*/false);
923       if (!class_specialization)
924         return NULL_TREE;
925       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
926          for the specialization.  */
927       idx = class_method_index_for_fn (class_specialization, tmpl);
928       if (idx == -1)
929         return NULL_TREE;
930       /* Iterate through the methods with the indicated name, looking
931          for the one that has an instance of TMPL.  */
932       methods = CLASSTYPE_METHOD_VEC (class_specialization);
933       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
934         {
935           tree fn = OVL_CURRENT (fns);
936           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl)
937             return fn;
938         }
939       return NULL_TREE;
940     }
941   else
942     {
943       tree *sp;
944       tree *head;
945
946       /* Class templates store their instantiations on the
947          DECL_TEMPLATE_INSTANTIATIONS list; other templates use the
948          DECL_TEMPLATE_SPECIALIZATIONS list.  */
949       if (!class_specializations_p
950           && TREE_CODE (DECL_TEMPLATE_RESULT (tmpl)) == TYPE_DECL
951           && TAGGED_TYPE_P (TREE_TYPE (tmpl)))
952         sp = &DECL_TEMPLATE_INSTANTIATIONS (tmpl);
953       else
954         sp = &DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
955       head = sp;
956       /* Iterate through the list until we find a matching template.  */
957       while (*sp != NULL_TREE)
958         {
959           tree spec = *sp;
960
961           if (comp_template_args (TREE_PURPOSE (spec), args))
962             {
963               /* Use the move-to-front heuristic to speed up future
964                  searches.  */
965               if (spec != *head)
966                 {
967                   *sp = TREE_CHAIN (*sp);
968                   TREE_CHAIN (spec) = *head;
969                   *head = spec;
970                 }
971               return TREE_VALUE (spec);
972             }
973           sp = &TREE_CHAIN (spec);
974         }
975     }
976
977   return NULL_TREE;
978 }
979
980 /* Like retrieve_specialization, but for local declarations.  */
981
982 static tree
983 retrieve_local_specialization (tree tmpl)
984 {
985   tree spec;
986
987   if (local_specializations == NULL)
988     return NULL_TREE;
989
990   spec = (tree) htab_find_with_hash (local_specializations, tmpl,
991                                      htab_hash_pointer (tmpl));
992   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
993 }
994
995 /* Returns nonzero iff DECL is a specialization of TMPL.  */
996
997 int
998 is_specialization_of (tree decl, tree tmpl)
999 {
1000   tree t;
1001
1002   if (TREE_CODE (decl) == FUNCTION_DECL)
1003     {
1004       for (t = decl;
1005            t != NULL_TREE;
1006            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1007         if (t == tmpl)
1008           return 1;
1009     }
1010   else
1011     {
1012       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1013
1014       for (t = TREE_TYPE (decl);
1015            t != NULL_TREE;
1016            t = CLASSTYPE_USE_TEMPLATE (t)
1017              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1018         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1019           return 1;
1020     }
1021
1022   return 0;
1023 }
1024
1025 /* Returns nonzero iff DECL is a specialization of friend declaration
1026    FRIEND_DECL according to [temp.friend].  */
1027
1028 bool
1029 is_specialization_of_friend (tree decl, tree friend_decl)
1030 {
1031   bool need_template = true;
1032   int template_depth;
1033
1034   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1035               || TREE_CODE (decl) == TYPE_DECL);
1036
1037   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1038      of a template class, we want to check if DECL is a specialization
1039      if this.  */
1040   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1041       && DECL_TEMPLATE_INFO (friend_decl)
1042       && !DECL_USE_TEMPLATE (friend_decl))
1043     {
1044       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1045       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1046       need_template = false;
1047     }
1048   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1049            && !PRIMARY_TEMPLATE_P (friend_decl))
1050     need_template = false;
1051
1052   /* There is nothing to do if this is not a template friend.  */
1053   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1054     return false;
1055
1056   if (is_specialization_of (decl, friend_decl))
1057     return true;
1058
1059   /* [temp.friend/6]
1060      A member of a class template may be declared to be a friend of a
1061      non-template class.  In this case, the corresponding member of
1062      every specialization of the class template is a friend of the
1063      class granting friendship.
1064
1065      For example, given a template friend declaration
1066
1067        template <class T> friend void A<T>::f();
1068
1069      the member function below is considered a friend
1070
1071        template <> struct A<int> {
1072          void f();
1073        };
1074
1075      For this type of template friend, TEMPLATE_DEPTH below will be
1076      nonzero.  To determine if DECL is a friend of FRIEND, we first
1077      check if the enclosing class is a specialization of another.  */
1078
1079   template_depth = template_class_depth (DECL_CONTEXT (friend_decl));
1080   if (template_depth
1081       && DECL_CLASS_SCOPE_P (decl)
1082       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1083                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1084     {
1085       /* Next, we check the members themselves.  In order to handle
1086          a few tricky cases, such as when FRIEND_DECL's are
1087
1088            template <class T> friend void A<T>::g(T t);
1089            template <class T> template <T t> friend void A<T>::h();
1090
1091          and DECL's are
1092
1093            void A<int>::g(int);
1094            template <int> void A<int>::h();
1095
1096          we need to figure out ARGS, the template arguments from
1097          the context of DECL.  This is required for template substitution
1098          of `T' in the function parameter of `g' and template parameter
1099          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1100
1101       tree context = DECL_CONTEXT (decl);
1102       tree args = NULL_TREE;
1103       int current_depth = 0;
1104
1105       while (current_depth < template_depth)
1106         {
1107           if (CLASSTYPE_TEMPLATE_INFO (context))
1108             {
1109               if (current_depth == 0)
1110                 args = TYPE_TI_ARGS (context);
1111               else
1112                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1113               current_depth++;
1114             }
1115           context = TYPE_CONTEXT (context);
1116         }
1117
1118       if (TREE_CODE (decl) == FUNCTION_DECL)
1119         {
1120           bool is_template;
1121           tree friend_type;
1122           tree decl_type;
1123           tree friend_args_type;
1124           tree decl_args_type;
1125
1126           /* Make sure that both DECL and FRIEND_DECL are templates or
1127              non-templates.  */
1128           is_template = DECL_TEMPLATE_INFO (decl)
1129                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1130           if (need_template ^ is_template)
1131             return false;
1132           else if (is_template)
1133             {
1134               /* If both are templates, check template parameter list.  */
1135               tree friend_parms
1136                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1137                                          args, tf_none);
1138               if (!comp_template_parms
1139                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1140                       friend_parms))
1141                 return false;
1142
1143               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1144             }
1145           else
1146             decl_type = TREE_TYPE (decl);
1147
1148           friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1149                                               tf_none, NULL_TREE);
1150           if (friend_type == error_mark_node)
1151             return false;
1152
1153           /* Check if return types match.  */
1154           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1155             return false;
1156
1157           /* Check if function parameter types match, ignoring the
1158              `this' parameter.  */
1159           friend_args_type = TYPE_ARG_TYPES (friend_type);
1160           decl_args_type = TYPE_ARG_TYPES (decl_type);
1161           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1162             friend_args_type = TREE_CHAIN (friend_args_type);
1163           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1164             decl_args_type = TREE_CHAIN (decl_args_type);
1165
1166           return compparms (decl_args_type, friend_args_type);
1167         }
1168       else
1169         {
1170           /* DECL is a TYPE_DECL */
1171           bool is_template;
1172           tree decl_type = TREE_TYPE (decl);
1173
1174           /* Make sure that both DECL and FRIEND_DECL are templates or
1175              non-templates.  */
1176           is_template
1177             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1178               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1179
1180           if (need_template ^ is_template)
1181             return false;
1182           else if (is_template)
1183             {
1184               tree friend_parms;
1185               /* If both are templates, check the name of the two
1186                  TEMPLATE_DECL's first because is_friend didn't.  */
1187               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1188                   != DECL_NAME (friend_decl))
1189                 return false;
1190
1191               /* Now check template parameter list.  */
1192               friend_parms
1193                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1194                                          args, tf_none);
1195               return comp_template_parms
1196                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1197                  friend_parms);
1198             }
1199           else
1200             return (DECL_NAME (decl)
1201                     == DECL_NAME (friend_decl));
1202         }
1203     }
1204   return false;
1205 }
1206
1207 /* Register the specialization SPEC as a specialization of TMPL with
1208    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1209    is actually just a friend declaration.  Returns SPEC, or an
1210    equivalent prior declaration, if available.  */
1211
1212 static tree
1213 register_specialization (tree spec, tree tmpl, tree args, bool is_friend)
1214 {
1215   tree fn;
1216
1217   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
1218
1219   if (TREE_CODE (spec) == FUNCTION_DECL
1220       && uses_template_parms (DECL_TI_ARGS (spec)))
1221     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1222        register it; we want the corresponding TEMPLATE_DECL instead.
1223        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1224        the more obvious `uses_template_parms (spec)' to avoid problems
1225        with default function arguments.  In particular, given
1226        something like this:
1227
1228           template <class T> void f(T t1, T t = T())
1229
1230        the default argument expression is not substituted for in an
1231        instantiation unless and until it is actually needed.  */
1232     return spec;
1233
1234   fn = retrieve_specialization (tmpl, args,
1235                                 /*class_specializations_p=*/false);
1236   /* We can sometimes try to re-register a specialization that we've
1237      already got.  In particular, regenerate_decl_from_template calls
1238      duplicate_decls which will update the specialization list.  But,
1239      we'll still get called again here anyhow.  It's more convenient
1240      to simply allow this than to try to prevent it.  */
1241   if (fn == spec)
1242     return spec;
1243   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1244     {
1245       if (DECL_TEMPLATE_INSTANTIATION (fn))
1246         {
1247           if (TREE_USED (fn)
1248               || DECL_EXPLICIT_INSTANTIATION (fn))
1249             {
1250               error ("specialization of %qD after instantiation",
1251                      fn);
1252               return error_mark_node;
1253             }
1254           else
1255             {
1256               tree clone;
1257               /* This situation should occur only if the first
1258                  specialization is an implicit instantiation, the
1259                  second is an explicit specialization, and the
1260                  implicit instantiation has not yet been used.  That
1261                  situation can occur if we have implicitly
1262                  instantiated a member function and then specialized
1263                  it later.
1264
1265                  We can also wind up here if a friend declaration that
1266                  looked like an instantiation turns out to be a
1267                  specialization:
1268
1269                    template <class T> void foo(T);
1270                    class S { friend void foo<>(int) };
1271                    template <> void foo(int);
1272
1273                  We transform the existing DECL in place so that any
1274                  pointers to it become pointers to the updated
1275                  declaration.
1276
1277                  If there was a definition for the template, but not
1278                  for the specialization, we want this to look as if
1279                  there were no definition, and vice versa.  */
1280               DECL_INITIAL (fn) = NULL_TREE;
1281               duplicate_decls (spec, fn, is_friend);
1282               /* The call to duplicate_decls will have applied
1283                  [temp.expl.spec]:
1284
1285                    An explicit specialization of a function template
1286                    is inline only if it is explicitly declared to be,
1287                    and independently of whether its function template
1288                    is.
1289
1290                 to the primary function; now copy the inline bits to
1291                 the various clones.  */
1292               FOR_EACH_CLONE (clone, fn)
1293                 DECL_DECLARED_INLINE_P (clone)
1294                   = DECL_DECLARED_INLINE_P (fn);
1295               check_specialization_namespace (fn);
1296
1297               return fn;
1298             }
1299         }
1300       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1301         {
1302           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1303             /* Dup decl failed, but this is a new definition. Set the
1304                line number so any errors match this new
1305                definition.  */
1306             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1307
1308           return fn;
1309         }
1310     }
1311
1312   /* A specialization must be declared in the same namespace as the
1313      template it is specializing.  */
1314   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1315       && !check_specialization_namespace (tmpl))
1316     DECL_CONTEXT (spec) = FROB_CONTEXT (decl_namespace_context (tmpl));
1317
1318   if (!optimize_specialization_lookup_p (tmpl))
1319     DECL_TEMPLATE_SPECIALIZATIONS (tmpl)
1320       = tree_cons (args, spec, DECL_TEMPLATE_SPECIALIZATIONS (tmpl));
1321
1322   return spec;
1323 }
1324
1325 /* Unregister the specialization SPEC as a specialization of TMPL.
1326    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1327    if the SPEC was listed as a specialization of TMPL.  */
1328
1329 bool
1330 reregister_specialization (tree spec, tree tmpl, tree new_spec)
1331 {
1332   tree* s;
1333
1334   for (s = &DECL_TEMPLATE_SPECIALIZATIONS (tmpl);
1335        *s != NULL_TREE;
1336        s = &TREE_CHAIN (*s))
1337     if (TREE_VALUE (*s) == spec)
1338       {
1339         if (!new_spec)
1340           *s = TREE_CHAIN (*s);
1341         else
1342           TREE_VALUE (*s) = new_spec;
1343         return 1;
1344       }
1345
1346   return 0;
1347 }
1348
1349 /* Compare an entry in the local specializations hash table P1 (which
1350    is really a pointer to a TREE_LIST) with P2 (which is really a
1351    DECL).  */
1352
1353 static int
1354 eq_local_specializations (const void *p1, const void *p2)
1355 {
1356   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1357 }
1358
1359 /* Hash P1, an entry in the local specializations table.  */
1360
1361 static hashval_t
1362 hash_local_specialization (const void* p1)
1363 {
1364   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1365 }
1366
1367 /* Like register_specialization, but for local declarations.  We are
1368    registering SPEC, an instantiation of TMPL.  */
1369
1370 static void
1371 register_local_specialization (tree spec, tree tmpl)
1372 {
1373   void **slot;
1374
1375   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1376                                    htab_hash_pointer (tmpl), INSERT);
1377   *slot = build_tree_list (spec, tmpl);
1378 }
1379
1380 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1381    specialized class.  */
1382
1383 bool
1384 explicit_class_specialization_p (tree type)
1385 {
1386   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1387     return false;
1388   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1389 }
1390
1391 /* Print the list of candidate FNS in an error message.  */
1392
1393 void
1394 print_candidates (tree fns)
1395 {
1396   tree fn;
1397
1398   const char *str = "candidates are:";
1399
1400   for (fn = fns; fn != NULL_TREE; fn = TREE_CHAIN (fn))
1401     {
1402       tree f;
1403
1404       for (f = TREE_VALUE (fn); f; f = OVL_NEXT (f))
1405         error ("%s %+#D", str, OVL_CURRENT (f));
1406       str = "               ";
1407     }
1408 }
1409
1410 /* Returns the template (one of the functions given by TEMPLATE_ID)
1411    which can be specialized to match the indicated DECL with the
1412    explicit template args given in TEMPLATE_ID.  The DECL may be
1413    NULL_TREE if none is available.  In that case, the functions in
1414    TEMPLATE_ID are non-members.
1415
1416    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1417    specialization of a member template.
1418
1419    The TEMPLATE_COUNT is the number of references to qualifying
1420    template classes that appeared in the name of the function. See
1421    check_explicit_specialization for a more accurate description.
1422
1423    TSK indicates what kind of template declaration (if any) is being
1424    declared.  TSK_TEMPLATE indicates that the declaration given by
1425    DECL, though a FUNCTION_DECL, has template parameters, and is
1426    therefore a template function.
1427
1428    The template args (those explicitly specified and those deduced)
1429    are output in a newly created vector *TARGS_OUT.
1430
1431    If it is impossible to determine the result, an error message is
1432    issued.  The error_mark_node is returned to indicate failure.  */
1433
1434 static tree
1435 determine_specialization (tree template_id,
1436                           tree decl,
1437                           tree* targs_out,
1438                           int need_member_template,
1439                           int template_count,
1440                           tmpl_spec_kind tsk)
1441 {
1442   tree fns;
1443   tree targs;
1444   tree explicit_targs;
1445   tree candidates = NULL_TREE;
1446   /* A TREE_LIST of templates of which DECL may be a specialization.
1447      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1448      corresponding TREE_PURPOSE is the set of template arguments that,
1449      when used to instantiate the template, would produce a function
1450      with the signature of DECL.  */
1451   tree templates = NULL_TREE;
1452   int header_count;
1453   struct cp_binding_level *b;
1454
1455   *targs_out = NULL_TREE;
1456
1457   if (template_id == error_mark_node || decl == error_mark_node)
1458     return error_mark_node;
1459
1460   fns = TREE_OPERAND (template_id, 0);
1461   explicit_targs = TREE_OPERAND (template_id, 1);
1462
1463   if (fns == error_mark_node)
1464     return error_mark_node;
1465
1466   /* Check for baselinks.  */
1467   if (BASELINK_P (fns))
1468     fns = BASELINK_FUNCTIONS (fns);
1469
1470   if (!is_overloaded_fn (fns))
1471     {
1472       error ("%qD is not a function template", fns);
1473       return error_mark_node;
1474     }
1475
1476   /* Count the number of template headers specified for this
1477      specialization.  */
1478   header_count = 0;
1479   for (b = current_binding_level;
1480        b->kind == sk_template_parms;
1481        b = b->level_chain)
1482     ++header_count;
1483
1484   for (; fns; fns = OVL_NEXT (fns))
1485     {
1486       tree fn = OVL_CURRENT (fns);
1487
1488       if (TREE_CODE (fn) == TEMPLATE_DECL)
1489         {
1490           tree decl_arg_types;
1491           tree fn_arg_types;
1492
1493           /* In case of explicit specialization, we need to check if
1494              the number of template headers appearing in the specialization
1495              is correct. This is usually done in check_explicit_specialization,
1496              but the check done there cannot be exhaustive when specializing
1497              member functions. Consider the following code:
1498
1499              template <> void A<int>::f(int);
1500              template <> template <> void A<int>::f(int);
1501
1502              Assuming that A<int> is not itself an explicit specialization
1503              already, the first line specializes "f" which is a non-template
1504              member function, whilst the second line specializes "f" which
1505              is a template member function. So both lines are syntactically
1506              correct, and check_explicit_specialization does not reject
1507              them.
1508
1509              Here, we can do better, as we are matching the specialization
1510              against the declarations. We count the number of template
1511              headers, and we check if they match TEMPLATE_COUNT + 1
1512              (TEMPLATE_COUNT is the number of qualifying template classes,
1513              plus there must be another header for the member template
1514              itself).
1515
1516              Notice that if header_count is zero, this is not a
1517              specialization but rather a template instantiation, so there
1518              is no check we can perform here.  */
1519           if (header_count && header_count != template_count + 1)
1520             continue;
1521
1522           /* Check that the number of template arguments at the
1523              innermost level for DECL is the same as for FN.  */
1524           if (current_binding_level->kind == sk_template_parms
1525               && !current_binding_level->explicit_spec_p
1526               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1527                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1528                                       (current_template_parms))))
1529             continue;
1530
1531           /* DECL might be a specialization of FN.  */
1532           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1533           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1534
1535           /* For a non-static member function, we need to make sure
1536              that the const qualification is the same.  Since
1537              get_bindings does not try to merge the "this" parameter,
1538              we must do the comparison explicitly.  */
1539           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1540               && !same_type_p (TREE_VALUE (fn_arg_types),
1541                                TREE_VALUE (decl_arg_types)))
1542             continue;
1543
1544           /* Skip the "this" parameter and, for constructors of
1545              classes with virtual bases, the VTT parameter.  A
1546              full specialization of a constructor will have a VTT
1547              parameter, but a template never will.  */ 
1548           decl_arg_types 
1549             = skip_artificial_parms_for (decl, decl_arg_types);
1550           fn_arg_types 
1551             = skip_artificial_parms_for (fn, fn_arg_types);
1552
1553           /* Check that the number of function parameters matches.
1554              For example,
1555                template <class T> void f(int i = 0);
1556                template <> void f<int>();
1557              The specialization f<int> is invalid but is not caught
1558              by get_bindings below.  */
1559           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1560             continue;
1561
1562           /* Function templates cannot be specializations; there are
1563              no partial specializations of functions.  Therefore, if
1564              the type of DECL does not match FN, there is no
1565              match.  */
1566           if (tsk == tsk_template)
1567             {
1568               if (compparms (fn_arg_types, decl_arg_types))
1569                 candidates = tree_cons (NULL_TREE, fn, candidates);
1570               continue;
1571             }
1572
1573           /* See whether this function might be a specialization of this
1574              template.  */
1575           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1576
1577           if (!targs)
1578             /* We cannot deduce template arguments that when used to
1579                specialize TMPL will produce DECL.  */
1580             continue;
1581
1582           /* Save this template, and the arguments deduced.  */
1583           templates = tree_cons (targs, fn, templates);
1584         }
1585       else if (need_member_template)
1586         /* FN is an ordinary member function, and we need a
1587            specialization of a member template.  */
1588         ;
1589       else if (TREE_CODE (fn) != FUNCTION_DECL)
1590         /* We can get IDENTIFIER_NODEs here in certain erroneous
1591            cases.  */
1592         ;
1593       else if (!DECL_FUNCTION_MEMBER_P (fn))
1594         /* This is just an ordinary non-member function.  Nothing can
1595            be a specialization of that.  */
1596         ;
1597       else if (DECL_ARTIFICIAL (fn))
1598         /* Cannot specialize functions that are created implicitly.  */
1599         ;
1600       else
1601         {
1602           tree decl_arg_types;
1603
1604           /* This is an ordinary member function.  However, since
1605              we're here, we can assume it's enclosing class is a
1606              template class.  For example,
1607
1608                template <typename T> struct S { void f(); };
1609                template <> void S<int>::f() {}
1610
1611              Here, S<int>::f is a non-template, but S<int> is a
1612              template class.  If FN has the same type as DECL, we
1613              might be in business.  */
1614
1615           if (!DECL_TEMPLATE_INFO (fn))
1616             /* Its enclosing class is an explicit specialization
1617                of a template class.  This is not a candidate.  */
1618             continue;
1619
1620           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1621                             TREE_TYPE (TREE_TYPE (fn))))
1622             /* The return types differ.  */
1623             continue;
1624
1625           /* Adjust the type of DECL in case FN is a static member.  */
1626           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1627           if (DECL_STATIC_FUNCTION_P (fn)
1628               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1629             decl_arg_types = TREE_CHAIN (decl_arg_types);
1630
1631           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1632                          decl_arg_types))
1633             /* They match!  */
1634             candidates = tree_cons (NULL_TREE, fn, candidates);
1635         }
1636     }
1637
1638   if (templates && TREE_CHAIN (templates))
1639     {
1640       /* We have:
1641
1642            [temp.expl.spec]
1643
1644            It is possible for a specialization with a given function
1645            signature to be instantiated from more than one function
1646            template.  In such cases, explicit specification of the
1647            template arguments must be used to uniquely identify the
1648            function template specialization being specialized.
1649
1650          Note that here, there's no suggestion that we're supposed to
1651          determine which of the candidate templates is most
1652          specialized.  However, we, also have:
1653
1654            [temp.func.order]
1655
1656            Partial ordering of overloaded function template
1657            declarations is used in the following contexts to select
1658            the function template to which a function template
1659            specialization refers:
1660
1661            -- when an explicit specialization refers to a function
1662               template.
1663
1664          So, we do use the partial ordering rules, at least for now.
1665          This extension can only serve to make invalid programs valid,
1666          so it's safe.  And, there is strong anecdotal evidence that
1667          the committee intended the partial ordering rules to apply;
1668          the EDG front end has that behavior, and John Spicer claims
1669          that the committee simply forgot to delete the wording in
1670          [temp.expl.spec].  */
1671       tree tmpl = most_specialized_instantiation (templates);
1672       if (tmpl != error_mark_node)
1673         {
1674           templates = tmpl;
1675           TREE_CHAIN (templates) = NULL_TREE;
1676         }
1677     }
1678
1679   if (templates == NULL_TREE && candidates == NULL_TREE)
1680     {
1681       error ("template-id %qD for %q+D does not match any template "
1682              "declaration", template_id, decl);
1683       return error_mark_node;
1684     }
1685   else if ((templates && TREE_CHAIN (templates))
1686            || (candidates && TREE_CHAIN (candidates))
1687            || (templates && candidates))
1688     {
1689       error ("ambiguous template specialization %qD for %q+D",
1690              template_id, decl);
1691       chainon (candidates, templates);
1692       print_candidates (candidates);
1693       return error_mark_node;
1694     }
1695
1696   /* We have one, and exactly one, match.  */
1697   if (candidates)
1698     {
1699       tree fn = TREE_VALUE (candidates);
1700       /* DECL is a re-declaration of a template function.  */
1701       if (TREE_CODE (fn) == TEMPLATE_DECL)
1702         return fn;
1703       /* It was a specialization of an ordinary member function in a
1704          template class.  */
1705       *targs_out = copy_node (DECL_TI_ARGS (fn));
1706       return DECL_TI_TEMPLATE (fn);
1707     }
1708
1709   /* It was a specialization of a template.  */
1710   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
1711   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
1712     {
1713       *targs_out = copy_node (targs);
1714       SET_TMPL_ARGS_LEVEL (*targs_out,
1715                            TMPL_ARGS_DEPTH (*targs_out),
1716                            TREE_PURPOSE (templates));
1717     }
1718   else
1719     *targs_out = TREE_PURPOSE (templates);
1720   return TREE_VALUE (templates);
1721 }
1722
1723 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
1724    but with the default argument values filled in from those in the
1725    TMPL_TYPES.  */
1726
1727 static tree
1728 copy_default_args_to_explicit_spec_1 (tree spec_types,
1729                                       tree tmpl_types)
1730 {
1731   tree new_spec_types;
1732
1733   if (!spec_types)
1734     return NULL_TREE;
1735
1736   if (spec_types == void_list_node)
1737     return void_list_node;
1738
1739   /* Substitute into the rest of the list.  */
1740   new_spec_types =
1741     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
1742                                           TREE_CHAIN (tmpl_types));
1743
1744   /* Add the default argument for this parameter.  */
1745   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
1746                          TREE_VALUE (spec_types),
1747                          new_spec_types);
1748 }
1749
1750 /* DECL is an explicit specialization.  Replicate default arguments
1751    from the template it specializes.  (That way, code like:
1752
1753      template <class T> void f(T = 3);
1754      template <> void f(double);
1755      void g () { f (); }
1756
1757    works, as required.)  An alternative approach would be to look up
1758    the correct default arguments at the call-site, but this approach
1759    is consistent with how implicit instantiations are handled.  */
1760
1761 static void
1762 copy_default_args_to_explicit_spec (tree decl)
1763 {
1764   tree tmpl;
1765   tree spec_types;
1766   tree tmpl_types;
1767   tree new_spec_types;
1768   tree old_type;
1769   tree new_type;
1770   tree t;
1771   tree object_type = NULL_TREE;
1772   tree in_charge = NULL_TREE;
1773   tree vtt = NULL_TREE;
1774
1775   /* See if there's anything we need to do.  */
1776   tmpl = DECL_TI_TEMPLATE (decl);
1777   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
1778   for (t = tmpl_types; t; t = TREE_CHAIN (t))
1779     if (TREE_PURPOSE (t))
1780       break;
1781   if (!t)
1782     return;
1783
1784   old_type = TREE_TYPE (decl);
1785   spec_types = TYPE_ARG_TYPES (old_type);
1786
1787   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1788     {
1789       /* Remove the this pointer, but remember the object's type for
1790          CV quals.  */
1791       object_type = TREE_TYPE (TREE_VALUE (spec_types));
1792       spec_types = TREE_CHAIN (spec_types);
1793       tmpl_types = TREE_CHAIN (tmpl_types);
1794
1795       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
1796         {
1797           /* DECL may contain more parameters than TMPL due to the extra
1798              in-charge parameter in constructors and destructors.  */
1799           in_charge = spec_types;
1800           spec_types = TREE_CHAIN (spec_types);
1801         }
1802       if (DECL_HAS_VTT_PARM_P (decl))
1803         {
1804           vtt = spec_types;
1805           spec_types = TREE_CHAIN (spec_types);
1806         }
1807     }
1808
1809   /* Compute the merged default arguments.  */
1810   new_spec_types =
1811     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
1812
1813   /* Compute the new FUNCTION_TYPE.  */
1814   if (object_type)
1815     {
1816       if (vtt)
1817         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
1818                                          TREE_VALUE (vtt),
1819                                          new_spec_types);
1820
1821       if (in_charge)
1822         /* Put the in-charge parameter back.  */
1823         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
1824                                          TREE_VALUE (in_charge),
1825                                          new_spec_types);
1826
1827       new_type = build_method_type_directly (object_type,
1828                                              TREE_TYPE (old_type),
1829                                              new_spec_types);
1830     }
1831   else
1832     new_type = build_function_type (TREE_TYPE (old_type),
1833                                     new_spec_types);
1834   new_type = cp_build_type_attribute_variant (new_type,
1835                                               TYPE_ATTRIBUTES (old_type));
1836   new_type = build_exception_variant (new_type,
1837                                       TYPE_RAISES_EXCEPTIONS (old_type));
1838   TREE_TYPE (decl) = new_type;
1839 }
1840
1841 /* Check to see if the function just declared, as indicated in
1842    DECLARATOR, and in DECL, is a specialization of a function
1843    template.  We may also discover that the declaration is an explicit
1844    instantiation at this point.
1845
1846    Returns DECL, or an equivalent declaration that should be used
1847    instead if all goes well.  Issues an error message if something is
1848    amiss.  Returns error_mark_node if the error is not easily
1849    recoverable.
1850
1851    FLAGS is a bitmask consisting of the following flags:
1852
1853    2: The function has a definition.
1854    4: The function is a friend.
1855
1856    The TEMPLATE_COUNT is the number of references to qualifying
1857    template classes that appeared in the name of the function.  For
1858    example, in
1859
1860      template <class T> struct S { void f(); };
1861      void S<int>::f();
1862
1863    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
1864    classes are not counted in the TEMPLATE_COUNT, so that in
1865
1866      template <class T> struct S {};
1867      template <> struct S<int> { void f(); }
1868      template <> void S<int>::f();
1869
1870    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
1871    invalid; there should be no template <>.)
1872
1873    If the function is a specialization, it is marked as such via
1874    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
1875    is set up correctly, and it is added to the list of specializations
1876    for that template.  */
1877
1878 tree
1879 check_explicit_specialization (tree declarator,
1880                                tree decl,
1881                                int template_count,
1882                                int flags)
1883 {
1884   int have_def = flags & 2;
1885   int is_friend = flags & 4;
1886   int specialization = 0;
1887   int explicit_instantiation = 0;
1888   int member_specialization = 0;
1889   tree ctype = DECL_CLASS_CONTEXT (decl);
1890   tree dname = DECL_NAME (decl);
1891   tmpl_spec_kind tsk;
1892
1893   if (is_friend)
1894     {
1895       if (!processing_specialization)
1896         tsk = tsk_none;
1897       else
1898         tsk = tsk_excessive_parms;
1899     }
1900   else
1901     tsk = current_tmpl_spec_kind (template_count);
1902
1903   switch (tsk)
1904     {
1905     case tsk_none:
1906       if (processing_specialization)
1907         {
1908           specialization = 1;
1909           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
1910         }
1911       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
1912         {
1913           if (is_friend)
1914             /* This could be something like:
1915
1916                template <class T> void f(T);
1917                class S { friend void f<>(int); }  */
1918             specialization = 1;
1919           else
1920             {
1921               /* This case handles bogus declarations like template <>
1922                  template <class T> void f<int>(); */
1923
1924               error ("template-id %qD in declaration of primary template",
1925                      declarator);
1926               return decl;
1927             }
1928         }
1929       break;
1930
1931     case tsk_invalid_member_spec:
1932       /* The error has already been reported in
1933          check_specialization_scope.  */
1934       return error_mark_node;
1935
1936     case tsk_invalid_expl_inst:
1937       error ("template parameter list used in explicit instantiation");
1938
1939       /* Fall through.  */
1940
1941     case tsk_expl_inst:
1942       if (have_def)
1943         error ("definition provided for explicit instantiation");
1944
1945       explicit_instantiation = 1;
1946       break;
1947
1948     case tsk_excessive_parms:
1949     case tsk_insufficient_parms:
1950       if (tsk == tsk_excessive_parms)
1951         error ("too many template parameter lists in declaration of %qD",
1952                decl);
1953       else if (template_header_count)
1954         error("too few template parameter lists in declaration of %qD", decl);
1955       else
1956         error("explicit specialization of %qD must be introduced by "
1957               "%<template <>%>", decl);
1958
1959       /* Fall through.  */
1960     case tsk_expl_spec:
1961       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
1962       if (ctype)
1963         member_specialization = 1;
1964       else
1965         specialization = 1;
1966       break;
1967
1968     case tsk_template:
1969       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
1970         {
1971           /* This case handles bogus declarations like template <>
1972              template <class T> void f<int>(); */
1973
1974           if (uses_template_parms (declarator))
1975             error ("function template partial specialization %qD "
1976                    "is not allowed", declarator);
1977           else
1978             error ("template-id %qD in declaration of primary template",
1979                    declarator);
1980           return decl;
1981         }
1982
1983       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
1984         /* This is a specialization of a member template, without
1985            specialization the containing class.  Something like:
1986
1987              template <class T> struct S {
1988                template <class U> void f (U);
1989              };
1990              template <> template <class U> void S<int>::f(U) {}
1991
1992            That's a specialization -- but of the entire template.  */
1993         specialization = 1;
1994       break;
1995
1996     default:
1997       gcc_unreachable ();
1998     }
1999
2000   if (specialization || member_specialization)
2001     {
2002       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2003       for (; t; t = TREE_CHAIN (t))
2004         if (TREE_PURPOSE (t))
2005           {
2006             permerror (input_location, 
2007                        "default argument specified in explicit specialization");
2008             break;
2009           }
2010     }
2011
2012   if (specialization || member_specialization || explicit_instantiation)
2013     {
2014       tree tmpl = NULL_TREE;
2015       tree targs = NULL_TREE;
2016
2017       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2018       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2019         {
2020           tree fns;
2021
2022           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2023           if (ctype)
2024             fns = dname;
2025           else
2026             {
2027               /* If there is no class context, the explicit instantiation
2028                  must be at namespace scope.  */
2029               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2030
2031               /* Find the namespace binding, using the declaration
2032                  context.  */
2033               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2034                                            false, true);
2035               if (fns == error_mark_node || !is_overloaded_fn (fns))
2036                 {
2037                   error ("%qD is not a template function", dname);
2038                   fns = error_mark_node;
2039                 }
2040               else
2041                 {
2042                   tree fn = OVL_CURRENT (fns);
2043                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2044                                                 CP_DECL_CONTEXT (fn)))
2045                     error ("%qD is not declared in %qD",
2046                            decl, current_namespace);
2047                 }
2048             }
2049
2050           declarator = lookup_template_function (fns, NULL_TREE);
2051         }
2052
2053       if (declarator == error_mark_node)
2054         return error_mark_node;
2055
2056       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2057         {
2058           if (!explicit_instantiation)
2059             /* A specialization in class scope.  This is invalid,
2060                but the error will already have been flagged by
2061                check_specialization_scope.  */
2062             return error_mark_node;
2063           else
2064             {
2065               /* It's not valid to write an explicit instantiation in
2066                  class scope, e.g.:
2067
2068                    class C { template void f(); }
2069
2070                    This case is caught by the parser.  However, on
2071                    something like:
2072
2073                    template class C { void f(); };
2074
2075                    (which is invalid) we can get here.  The error will be
2076                    issued later.  */
2077               ;
2078             }
2079
2080           return decl;
2081         }
2082       else if (ctype != NULL_TREE
2083                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2084                    IDENTIFIER_NODE))
2085         {
2086           /* Find the list of functions in ctype that have the same
2087              name as the declared function.  */
2088           tree name = TREE_OPERAND (declarator, 0);
2089           tree fns = NULL_TREE;
2090           int idx;
2091
2092           if (constructor_name_p (name, ctype))
2093             {
2094               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2095
2096               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2097                   : !CLASSTYPE_DESTRUCTORS (ctype))
2098                 {
2099                   /* From [temp.expl.spec]:
2100
2101                      If such an explicit specialization for the member
2102                      of a class template names an implicitly-declared
2103                      special member function (clause _special_), the
2104                      program is ill-formed.
2105
2106                      Similar language is found in [temp.explicit].  */
2107                   error ("specialization of implicitly-declared special member function");
2108                   return error_mark_node;
2109                 }
2110
2111               name = is_constructor ? ctor_identifier : dtor_identifier;
2112             }
2113
2114           if (!DECL_CONV_FN_P (decl))
2115             {
2116               idx = lookup_fnfields_1 (ctype, name);
2117               if (idx >= 0)
2118                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2119             }
2120           else
2121             {
2122               VEC(tree,gc) *methods;
2123               tree ovl;
2124
2125               /* For a type-conversion operator, we cannot do a
2126                  name-based lookup.  We might be looking for `operator
2127                  int' which will be a specialization of `operator T'.
2128                  So, we find *all* the conversion operators, and then
2129                  select from them.  */
2130               fns = NULL_TREE;
2131
2132               methods = CLASSTYPE_METHOD_VEC (ctype);
2133               if (methods)
2134                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2135                      VEC_iterate (tree, methods, idx, ovl);
2136                      ++idx)
2137                   {
2138                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2139                       /* There are no more conversion functions.  */
2140                       break;
2141
2142                     /* Glue all these conversion functions together
2143                        with those we already have.  */
2144                     for (; ovl; ovl = OVL_NEXT (ovl))
2145                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2146                   }
2147             }
2148
2149           if (fns == NULL_TREE)
2150             {
2151               error ("no member function %qD declared in %qT", name, ctype);
2152               return error_mark_node;
2153             }
2154           else
2155             TREE_OPERAND (declarator, 0) = fns;
2156         }
2157
2158       /* Figure out what exactly is being specialized at this point.
2159          Note that for an explicit instantiation, even one for a
2160          member function, we cannot tell apriori whether the
2161          instantiation is for a member template, or just a member
2162          function of a template class.  Even if a member template is
2163          being instantiated, the member template arguments may be
2164          elided if they can be deduced from the rest of the
2165          declaration.  */
2166       tmpl = determine_specialization (declarator, decl,
2167                                        &targs,
2168                                        member_specialization,
2169                                        template_count,
2170                                        tsk);
2171
2172       if (!tmpl || tmpl == error_mark_node)
2173         /* We couldn't figure out what this declaration was
2174            specializing.  */
2175         return error_mark_node;
2176       else
2177         {
2178           tree gen_tmpl = most_general_template (tmpl);
2179
2180           if (explicit_instantiation)
2181             {
2182               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2183                  is done by do_decl_instantiation later.  */
2184
2185               int arg_depth = TMPL_ARGS_DEPTH (targs);
2186               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2187
2188               if (arg_depth > parm_depth)
2189                 {
2190                   /* If TMPL is not the most general template (for
2191                      example, if TMPL is a friend template that is
2192                      injected into namespace scope), then there will
2193                      be too many levels of TARGS.  Remove some of them
2194                      here.  */
2195                   int i;
2196                   tree new_targs;
2197
2198                   new_targs = make_tree_vec (parm_depth);
2199                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2200                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2201                       = TREE_VEC_ELT (targs, i);
2202                   targs = new_targs;
2203                 }
2204
2205               return instantiate_template (tmpl, targs, tf_error);
2206             }
2207
2208           /* If we thought that the DECL was a member function, but it
2209              turns out to be specializing a static member function,
2210              make DECL a static member function as well.  */
2211           if (DECL_STATIC_FUNCTION_P (tmpl)
2212               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2213             revert_static_member_fn (decl);
2214
2215           /* If this is a specialization of a member template of a
2216              template class, we want to return the TEMPLATE_DECL, not
2217              the specialization of it.  */
2218           if (tsk == tsk_template)
2219             {
2220               tree result = DECL_TEMPLATE_RESULT (tmpl);
2221               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2222               DECL_INITIAL (result) = NULL_TREE;
2223               if (have_def)
2224                 {
2225                   tree parm;
2226                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2227                   DECL_SOURCE_LOCATION (result)
2228                     = DECL_SOURCE_LOCATION (decl);
2229                   /* We want to use the argument list specified in the
2230                      definition, not in the original declaration.  */
2231                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2232                   for (parm = DECL_ARGUMENTS (result); parm;
2233                        parm = TREE_CHAIN (parm))
2234                     DECL_CONTEXT (parm) = result;
2235                 }
2236               return tmpl;
2237             }
2238
2239           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2240           DECL_TEMPLATE_INFO (decl) = tree_cons (tmpl, targs, NULL_TREE);
2241
2242           /* Inherit default function arguments from the template
2243              DECL is specializing.  */
2244           copy_default_args_to_explicit_spec (decl);
2245
2246           /* This specialization has the same protection as the
2247              template it specializes.  */
2248           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2249           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2250
2251           /* 7.1.1-1 [dcl.stc]
2252
2253              A storage-class-specifier shall not be specified in an
2254              explicit specialization...
2255
2256              The parser rejects these, so unless action is taken here,
2257              explicit function specializations will always appear with
2258              global linkage.
2259
2260              The action recommended by the C++ CWG in response to C++
2261              defect report 605 is to make the storage class and linkage
2262              of the explicit specialization match the templated function:
2263
2264              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2265            */
2266           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2267             {
2268               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2269               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2270
2271               /* This specialization has the same linkage and visibility as
2272                  the function template it specializes.  */
2273               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2274               if (! TREE_PUBLIC (decl))
2275                 {
2276                   DECL_INTERFACE_KNOWN (decl) = 1;
2277                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2278                 }
2279               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2280               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2281                 {
2282                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2283                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2284                 }
2285             }
2286
2287           /* If DECL is a friend declaration, declared using an
2288              unqualified name, the namespace associated with DECL may
2289              have been set incorrectly.  For example, in:
2290
2291                template <typename T> void f(T);
2292                namespace N {
2293                  struct S { friend void f<int>(int); }
2294                }
2295
2296              we will have set the DECL_CONTEXT for the friend
2297              declaration to N, rather than to the global namespace.  */
2298           if (DECL_NAMESPACE_SCOPE_P (decl))
2299             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2300
2301           if (is_friend && !have_def)
2302             /* This is not really a declaration of a specialization.
2303                It's just the name of an instantiation.  But, it's not
2304                a request for an instantiation, either.  */
2305             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2306           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2307             /* This is indeed a specialization.  In case of constructors
2308                and destructors, we need in-charge and not-in-charge
2309                versions in V3 ABI.  */
2310             clone_function_decl (decl, /*update_method_vec_p=*/0);
2311
2312           /* Register this specialization so that we can find it
2313              again.  */
2314           decl = register_specialization (decl, gen_tmpl, targs, is_friend);
2315         }
2316     }
2317
2318   return decl;
2319 }
2320
2321 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2322    parameters.  These are represented in the same format used for
2323    DECL_TEMPLATE_PARMS.  */
2324
2325 int
2326 comp_template_parms (const_tree parms1, const_tree parms2)
2327 {
2328   const_tree p1;
2329   const_tree p2;
2330
2331   if (parms1 == parms2)
2332     return 1;
2333
2334   for (p1 = parms1, p2 = parms2;
2335        p1 != NULL_TREE && p2 != NULL_TREE;
2336        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2337     {
2338       tree t1 = TREE_VALUE (p1);
2339       tree t2 = TREE_VALUE (p2);
2340       int i;
2341
2342       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2343       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2344
2345       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2346         return 0;
2347
2348       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2349         {
2350           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2351           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2352
2353           /* If either of the template parameters are invalid, assume
2354              they match for the sake of error recovery. */
2355           if (parm1 == error_mark_node || parm2 == error_mark_node)
2356             return 1;
2357
2358           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2359             return 0;
2360
2361           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2362               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2363                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2364             continue;
2365           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2366             return 0;
2367         }
2368     }
2369
2370   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2371     /* One set of parameters has more parameters lists than the
2372        other.  */
2373     return 0;
2374
2375   return 1;
2376 }
2377
2378 /* Determine whether PARM is a parameter pack.  */
2379 bool 
2380 template_parameter_pack_p (const_tree parm)
2381 {
2382   /* Determine if we have a non-type template parameter pack.  */
2383   if (TREE_CODE (parm) == PARM_DECL)
2384     return (DECL_TEMPLATE_PARM_P (parm) 
2385             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2386
2387   /* If this is a list of template parameters, we could get a
2388      TYPE_DECL or a TEMPLATE_DECL.  */ 
2389   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2390     parm = TREE_TYPE (parm);
2391
2392   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2393            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2394           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2395 }
2396
2397 /* Determine whether ARGS describes a variadic template args list,
2398    i.e., one that is terminated by a template argument pack.  */
2399 static bool 
2400 template_args_variadic_p (tree args)
2401 {
2402   int nargs;
2403   tree last_parm;
2404
2405   if (args == NULL_TREE)
2406     return false;
2407
2408   args = INNERMOST_TEMPLATE_ARGS (args);
2409   nargs = TREE_VEC_LENGTH (args);
2410
2411   if (nargs == 0)
2412     return false;
2413
2414   last_parm = TREE_VEC_ELT (args, nargs - 1);
2415
2416   return ARGUMENT_PACK_P (last_parm);
2417 }
2418
2419 /* Generate a new name for the parameter pack name NAME (an
2420    IDENTIFIER_NODE) that incorporates its */
2421 static tree
2422 make_ith_pack_parameter_name (tree name, int i)
2423 {
2424   /* Munge the name to include the parameter index.  */
2425   char numbuf[128];
2426   char* newname;
2427   
2428   sprintf(numbuf, "%i", i);
2429   newname = (char*)alloca (IDENTIFIER_LENGTH (name) + strlen(numbuf) + 2);
2430   sprintf(newname, "%s#%i", IDENTIFIER_POINTER (name), i);
2431   return get_identifier (newname);
2432 }
2433
2434 /* Structure used to track the progress of find_parameter_packs_r.  */
2435 struct find_parameter_pack_data 
2436 {
2437   /* TREE_LIST that will contain all of the parameter packs found by
2438      the traversal.  */
2439   tree* parameter_packs;
2440
2441   /* Set of AST nodes that have been visited by the traversal.  */
2442   struct pointer_set_t *visited;
2443 };
2444
2445 /* Identifies all of the argument packs that occur in a template
2446    argument and appends them to the TREE_LIST inside DATA, which is a
2447    find_parameter_pack_data structure. This is a subroutine of
2448    make_pack_expansion and uses_parameter_packs.  */
2449 static tree
2450 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2451 {
2452   tree t = *tp;
2453   struct find_parameter_pack_data* ppd = 
2454     (struct find_parameter_pack_data*)data;
2455   bool parameter_pack_p = false;
2456
2457   /* Identify whether this is a parameter pack or not.  */
2458   switch (TREE_CODE (t))
2459     {
2460     case TEMPLATE_PARM_INDEX:
2461       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2462         parameter_pack_p = true;
2463       break;
2464
2465     case TEMPLATE_TYPE_PARM:
2466     case TEMPLATE_TEMPLATE_PARM:
2467       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2468         parameter_pack_p = true;
2469       break;
2470
2471     case PARM_DECL:
2472       if (FUNCTION_PARAMETER_PACK_P (t))
2473         {
2474           /* We don't want to walk into the type of a PARM_DECL,
2475              because we don't want to see the type parameter pack.  */
2476           *walk_subtrees = 0;
2477           parameter_pack_p = true;
2478         }
2479       break;
2480
2481     default:
2482       /* Not a parameter pack.  */
2483       break;
2484     }
2485
2486   if (parameter_pack_p)
2487     {
2488       /* Add this parameter pack to the list.  */
2489       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2490     }
2491
2492   if (TYPE_P (t))
2493     cp_walk_tree (&TYPE_CONTEXT (t), 
2494                   &find_parameter_packs_r, ppd, ppd->visited);
2495
2496   /* This switch statement will return immediately if we don't find a
2497      parameter pack.  */
2498   switch (TREE_CODE (t)) 
2499     {
2500     case TEMPLATE_PARM_INDEX:
2501       return NULL_TREE;
2502
2503     case BOUND_TEMPLATE_TEMPLATE_PARM:
2504       /* Check the template itself.  */
2505       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
2506                     &find_parameter_packs_r, ppd, ppd->visited);
2507       /* Check the template arguments.  */
2508       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
2509                     ppd->visited);
2510       *walk_subtrees = 0;
2511       return NULL_TREE;
2512
2513     case TEMPLATE_TYPE_PARM:
2514     case TEMPLATE_TEMPLATE_PARM:
2515       return NULL_TREE;
2516
2517     case PARM_DECL:
2518       return NULL_TREE;
2519
2520     case RECORD_TYPE:
2521       if (TYPE_PTRMEMFUNC_P (t))
2522         return NULL_TREE;
2523       /* Fall through.  */
2524
2525     case UNION_TYPE:
2526     case ENUMERAL_TYPE:
2527       if (TYPE_TEMPLATE_INFO (t))
2528         cp_walk_tree (&TREE_VALUE (TYPE_TEMPLATE_INFO (t)), 
2529                       &find_parameter_packs_r, ppd, ppd->visited);
2530
2531       *walk_subtrees = 0;
2532       return NULL_TREE;
2533
2534     case TEMPLATE_DECL:
2535       cp_walk_tree (&TREE_TYPE (t),
2536                     &find_parameter_packs_r, ppd, ppd->visited);
2537       return NULL_TREE;
2538  
2539     case TYPENAME_TYPE:
2540       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
2541                    ppd, ppd->visited);
2542       *walk_subtrees = 0;
2543       return NULL_TREE;
2544       
2545     case TYPE_PACK_EXPANSION:
2546     case EXPR_PACK_EXPANSION:
2547       *walk_subtrees = 0;
2548       return NULL_TREE;
2549
2550     case INTEGER_TYPE:
2551       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
2552                     ppd, ppd->visited);
2553       *walk_subtrees = 0;
2554       return NULL_TREE;
2555
2556     case IDENTIFIER_NODE:
2557       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
2558                     ppd->visited);
2559       *walk_subtrees = 0;
2560       return NULL_TREE;
2561
2562     default:
2563       return NULL_TREE;
2564     }
2565
2566   return NULL_TREE;
2567 }
2568
2569 /* Determines if the expression or type T uses any parameter packs.  */
2570 bool
2571 uses_parameter_packs (tree t)
2572 {
2573   tree parameter_packs = NULL_TREE;
2574   struct find_parameter_pack_data ppd;
2575   ppd.parameter_packs = &parameter_packs;
2576   ppd.visited = pointer_set_create ();
2577   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
2578   pointer_set_destroy (ppd.visited);
2579   return parameter_packs != NULL_TREE;
2580 }
2581
2582 /* Turn ARG, which may be an expression, type, or a TREE_LIST
2583    representation a base-class initializer into a parameter pack
2584    expansion. If all goes well, the resulting node will be an
2585    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
2586    respectively.  */
2587 tree 
2588 make_pack_expansion (tree arg)
2589 {
2590   tree result;
2591   tree parameter_packs = NULL_TREE;
2592   bool for_types = false;
2593   struct find_parameter_pack_data ppd;
2594
2595   if (!arg || arg == error_mark_node)
2596     return arg;
2597
2598   if (TREE_CODE (arg) == TREE_LIST)
2599     {
2600       /* The only time we will see a TREE_LIST here is for a base
2601          class initializer.  In this case, the TREE_PURPOSE will be a
2602          _TYPE node (representing the base class expansion we're
2603          initializing) and the TREE_VALUE will be a TREE_LIST
2604          containing the initialization arguments. 
2605
2606          The resulting expansion looks somewhat different from most
2607          expansions. Rather than returning just one _EXPANSION, we
2608          return a TREE_LIST whose TREE_PURPOSE is a
2609          TYPE_PACK_EXPANSION containing the bases that will be
2610          initialized.  The TREE_VALUE will be identical to the
2611          original TREE_VALUE, which is a list of arguments that will
2612          be passed to each base.  We do not introduce any new pack
2613          expansion nodes into the TREE_VALUE (although it is possible
2614          that some already exist), because the TREE_PURPOSE and
2615          TREE_VALUE all need to be expanded together with the same
2616          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
2617          resulting TREE_PURPOSE will mention the parameter packs in
2618          both the bases and the arguments to the bases.  */
2619       tree purpose;
2620       tree value;
2621       tree parameter_packs = NULL_TREE;
2622
2623       /* Determine which parameter packs will be used by the base
2624          class expansion.  */
2625       ppd.visited = pointer_set_create ();
2626       ppd.parameter_packs = &parameter_packs;
2627       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
2628                     &ppd, ppd.visited);
2629
2630       if (parameter_packs == NULL_TREE)
2631         {
2632           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
2633           pointer_set_destroy (ppd.visited);
2634           return error_mark_node;
2635         }
2636
2637       if (TREE_VALUE (arg) != void_type_node)
2638         {
2639           /* Collect the sets of parameter packs used in each of the
2640              initialization arguments.  */
2641           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
2642             {
2643               /* Determine which parameter packs will be expanded in this
2644                  argument.  */
2645               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
2646                             &ppd, ppd.visited);
2647             }
2648         }
2649
2650       pointer_set_destroy (ppd.visited);
2651
2652       /* Create the pack expansion type for the base type.  */
2653       purpose = make_node (TYPE_PACK_EXPANSION);
2654       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
2655       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
2656
2657       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
2658          they will rarely be compared to anything.  */
2659       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
2660
2661       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
2662     }
2663
2664   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
2665     for_types = true;
2666
2667   /* Build the PACK_EXPANSION_* node.  */
2668   result = make_node (for_types ? TYPE_PACK_EXPANSION : EXPR_PACK_EXPANSION);
2669   SET_PACK_EXPANSION_PATTERN (result, arg);
2670   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
2671     {
2672       /* Propagate type and const-expression information.  */
2673       TREE_TYPE (result) = TREE_TYPE (arg);
2674       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
2675     }
2676   else
2677     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
2678        they will rarely be compared to anything.  */
2679     SET_TYPE_STRUCTURAL_EQUALITY (result);
2680
2681   /* Determine which parameter packs will be expanded.  */
2682   ppd.parameter_packs = &parameter_packs;
2683   ppd.visited = pointer_set_create ();
2684   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
2685   pointer_set_destroy (ppd.visited);
2686
2687   /* Make sure we found some parameter packs.  */
2688   if (parameter_packs == NULL_TREE)
2689     {
2690       if (TYPE_P (arg))
2691         error ("expansion pattern %<%T%> contains no argument packs", arg);
2692       else
2693         error ("expansion pattern %<%E%> contains no argument packs", arg);
2694       return error_mark_node;
2695     }
2696   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
2697
2698   return result;
2699 }
2700
2701 /* Checks T for any "bare" parameter packs, which have not yet been
2702    expanded, and issues an error if any are found. This operation can
2703    only be done on full expressions or types (e.g., an expression
2704    statement, "if" condition, etc.), because we could have expressions like:
2705
2706      foo(f(g(h(args)))...)
2707
2708    where "args" is a parameter pack. check_for_bare_parameter_packs
2709    should not be called for the subexpressions args, h(args),
2710    g(h(args)), or f(g(h(args))), because we would produce erroneous
2711    error messages. 
2712
2713    Returns TRUE and emits an error if there were bare parameter packs,
2714    returns FALSE otherwise.  */
2715 bool 
2716 check_for_bare_parameter_packs (tree t)
2717 {
2718   tree parameter_packs = NULL_TREE;
2719   struct find_parameter_pack_data ppd;
2720
2721   if (!processing_template_decl || !t || t == error_mark_node)
2722     return false;
2723
2724   if (TREE_CODE (t) == TYPE_DECL)
2725     t = TREE_TYPE (t);
2726
2727   ppd.parameter_packs = &parameter_packs;
2728   ppd.visited = pointer_set_create ();
2729   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
2730   pointer_set_destroy (ppd.visited);
2731
2732   if (parameter_packs) 
2733     {
2734       error ("parameter packs not expanded with %<...%>:");
2735       while (parameter_packs)
2736         {
2737           tree pack = TREE_VALUE (parameter_packs);
2738           tree name = NULL_TREE;
2739
2740           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
2741               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
2742             name = TYPE_NAME (pack);
2743           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
2744             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
2745           else
2746             name = DECL_NAME (pack);
2747
2748           if (name)
2749             inform (input_location, "        %qD", name);
2750           else
2751             inform (input_location, "        <anonymous>");
2752
2753           parameter_packs = TREE_CHAIN (parameter_packs);
2754         }
2755
2756       return true;
2757     }
2758
2759   return false;
2760 }
2761
2762 /* Expand any parameter packs that occur in the template arguments in
2763    ARGS.  */
2764 tree
2765 expand_template_argument_pack (tree args)
2766 {
2767   tree result_args = NULL_TREE;
2768   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
2769   int num_result_args = -1;
2770
2771   /* First, determine if we need to expand anything, and the number of
2772      slots we'll need.  */
2773   for (in_arg = 0; in_arg < nargs; ++in_arg)
2774     {
2775       tree arg = TREE_VEC_ELT (args, in_arg);
2776       if (ARGUMENT_PACK_P (arg))
2777         {
2778           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
2779           if (num_result_args < 0)
2780             num_result_args = in_arg + num_packed;
2781           else
2782             num_result_args += num_packed;
2783         }
2784       else
2785         {
2786           if (num_result_args >= 0)
2787             num_result_args++;
2788         }
2789     }
2790
2791   /* If no expansion is necessary, we're done.  */
2792   if (num_result_args < 0)
2793     return args;
2794
2795   /* Expand arguments.  */
2796   result_args = make_tree_vec (num_result_args);
2797   for (in_arg = 0; in_arg < nargs; ++in_arg)
2798     {
2799       tree arg = TREE_VEC_ELT (args, in_arg);
2800       if (ARGUMENT_PACK_P (arg))
2801         {
2802           tree packed = ARGUMENT_PACK_ARGS (arg);
2803           int i, num_packed = TREE_VEC_LENGTH (packed);
2804           for (i = 0; i < num_packed; ++i, ++out_arg)
2805             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
2806         }
2807       else
2808         {
2809           TREE_VEC_ELT (result_args, out_arg) = arg;
2810           ++out_arg;
2811         }
2812     }
2813
2814   return result_args;
2815 }
2816
2817 /* Checks if DECL shadows a template parameter.
2818
2819    [temp.local]: A template-parameter shall not be redeclared within its
2820    scope (including nested scopes).
2821
2822    Emits an error and returns TRUE if the DECL shadows a parameter,
2823    returns FALSE otherwise.  */
2824
2825 bool
2826 check_template_shadow (tree decl)
2827 {
2828   tree olddecl;
2829
2830   /* If we're not in a template, we can't possibly shadow a template
2831      parameter.  */
2832   if (!current_template_parms)
2833     return true;
2834
2835   /* Figure out what we're shadowing.  */
2836   if (TREE_CODE (decl) == OVERLOAD)
2837     decl = OVL_CURRENT (decl);
2838   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
2839
2840   /* If there's no previous binding for this name, we're not shadowing
2841      anything, let alone a template parameter.  */
2842   if (!olddecl)
2843     return true;
2844
2845   /* If we're not shadowing a template parameter, we're done.  Note
2846      that OLDDECL might be an OVERLOAD (or perhaps even an
2847      ERROR_MARK), so we can't just blithely assume it to be a _DECL
2848      node.  */
2849   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
2850     return true;
2851
2852   /* We check for decl != olddecl to avoid bogus errors for using a
2853      name inside a class.  We check TPFI to avoid duplicate errors for
2854      inline member templates.  */
2855   if (decl == olddecl
2856       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
2857     return true;
2858
2859   error ("declaration of %q+#D", decl);
2860   error (" shadows template parm %q+#D", olddecl);
2861   return false;
2862 }
2863
2864 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
2865    ORIG_LEVEL, DECL, and TYPE.  */
2866
2867 static tree
2868 build_template_parm_index (int index,
2869                            int level,
2870                            int orig_level,
2871                            tree decl,
2872                            tree type)
2873 {
2874   tree t = make_node (TEMPLATE_PARM_INDEX);
2875   TEMPLATE_PARM_IDX (t) = index;
2876   TEMPLATE_PARM_LEVEL (t) = level;
2877   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
2878   TEMPLATE_PARM_DECL (t) = decl;
2879   TREE_TYPE (t) = type;
2880   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
2881   TREE_READONLY (t) = TREE_READONLY (decl);
2882
2883   return t;
2884 }
2885
2886 /* Find the canonical type parameter for the given template type
2887    parameter.  Returns the canonical type parameter, which may be TYPE
2888    if no such parameter existed.  */
2889 static tree
2890 canonical_type_parameter (tree type)
2891 {
2892   tree list;
2893   int idx = TEMPLATE_TYPE_IDX (type);
2894   if (!canonical_template_parms)
2895     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
2896
2897   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
2898     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
2899
2900   list = VEC_index (tree, canonical_template_parms, idx);
2901   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
2902     list = TREE_CHAIN (list);
2903
2904   if (list)
2905     return TREE_VALUE (list);
2906   else
2907     {
2908       VEC_replace(tree, canonical_template_parms, idx,
2909                   tree_cons (NULL_TREE, type, 
2910                              VEC_index (tree, canonical_template_parms, idx)));
2911       return type;
2912     }
2913 }
2914
2915 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
2916    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
2917    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
2918    new one is created.  */
2919
2920 static tree
2921 reduce_template_parm_level (tree index, tree type, int levels, tree args,
2922                             tsubst_flags_t complain)
2923 {
2924   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
2925       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
2926           != TEMPLATE_PARM_LEVEL (index) - levels))
2927     {
2928       tree orig_decl = TEMPLATE_PARM_DECL (index);
2929       tree decl, t;
2930
2931       decl = build_decl (TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
2932       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
2933       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
2934       DECL_ARTIFICIAL (decl) = 1;
2935       SET_DECL_TEMPLATE_PARM_P (decl);
2936
2937       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
2938                                      TEMPLATE_PARM_LEVEL (index) - levels,
2939                                      TEMPLATE_PARM_ORIG_LEVEL (index),
2940                                      decl, type);
2941       TEMPLATE_PARM_DESCENDANTS (index) = t;
2942       TEMPLATE_PARM_PARAMETER_PACK (t) 
2943         = TEMPLATE_PARM_PARAMETER_PACK (index);
2944
2945         /* Template template parameters need this.  */
2946       if (TREE_CODE (decl) == TEMPLATE_DECL)
2947         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
2948           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
2949            args, complain);
2950     }
2951
2952   return TEMPLATE_PARM_DESCENDANTS (index);
2953 }
2954
2955 /* Process information from new template parameter PARM and append it to the
2956    LIST being built.  This new parameter is a non-type parameter iff
2957    IS_NON_TYPE is true. This new parameter is a parameter
2958    pack iff IS_PARAMETER_PACK is true.  */
2959
2960 tree
2961 process_template_parm (tree list, tree parm, bool is_non_type, 
2962                        bool is_parameter_pack)
2963 {
2964   tree decl = 0;
2965   tree defval;
2966   tree err_parm_list;
2967   int idx = 0;
2968
2969   gcc_assert (TREE_CODE (parm) == TREE_LIST);
2970   defval = TREE_PURPOSE (parm);
2971
2972   if (list)
2973     {
2974       tree p = tree_last (list);
2975
2976       if (p && TREE_VALUE (p) != error_mark_node)
2977         {
2978           p = TREE_VALUE (p);
2979           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
2980             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
2981           else
2982             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
2983         }
2984
2985       ++idx;
2986     }
2987   else
2988     idx = 0;
2989
2990   if (is_non_type)
2991     {
2992       parm = TREE_VALUE (parm);
2993
2994       SET_DECL_TEMPLATE_PARM_P (parm);
2995
2996       if (TREE_TYPE (parm) == error_mark_node)
2997         {
2998           err_parm_list = build_tree_list (defval, parm);
2999           TREE_VALUE (err_parm_list) = error_mark_node;
3000            return chainon (list, err_parm_list);
3001         }
3002       else
3003       {
3004         /* [temp.param]
3005
3006            The top-level cv-qualifiers on the template-parameter are
3007            ignored when determining its type.  */
3008         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3009         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3010           {
3011             err_parm_list = build_tree_list (defval, parm);
3012             TREE_VALUE (err_parm_list) = error_mark_node;
3013              return chainon (list, err_parm_list);
3014           }
3015
3016         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3017           {
3018             /* This template parameter is not a parameter pack, but it
3019                should be. Complain about "bare" parameter packs.  */
3020             check_for_bare_parameter_packs (TREE_TYPE (parm));
3021             
3022             /* Recover by calling this a parameter pack.  */
3023             is_parameter_pack = true;
3024           }
3025       }
3026
3027       /* A template parameter is not modifiable.  */
3028       TREE_CONSTANT (parm) = 1;
3029       TREE_READONLY (parm) = 1;
3030       decl = build_decl (CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3031       TREE_CONSTANT (decl) = 1;
3032       TREE_READONLY (decl) = 1;
3033       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3034         = build_template_parm_index (idx, processing_template_decl,
3035                                      processing_template_decl,
3036                                      decl, TREE_TYPE (parm));
3037
3038       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3039         = is_parameter_pack;
3040     }
3041   else
3042     {
3043       tree t;
3044       parm = TREE_VALUE (TREE_VALUE (parm));
3045
3046       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3047         {
3048           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3049           /* This is for distinguishing between real templates and template
3050              template parameters */
3051           TREE_TYPE (parm) = t;
3052           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3053           decl = parm;
3054         }
3055       else
3056         {
3057           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3058           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3059           decl = build_decl (TYPE_DECL, parm, t);
3060         }
3061
3062       TYPE_NAME (t) = decl;
3063       TYPE_STUB_DECL (t) = decl;
3064       parm = decl;
3065       TEMPLATE_TYPE_PARM_INDEX (t)
3066         = build_template_parm_index (idx, processing_template_decl,
3067                                      processing_template_decl,
3068                                      decl, TREE_TYPE (parm));
3069       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3070       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3071     }
3072   DECL_ARTIFICIAL (decl) = 1;
3073   SET_DECL_TEMPLATE_PARM_P (decl);
3074   pushdecl (decl);
3075   parm = build_tree_list (defval, parm);
3076   return chainon (list, parm);
3077 }
3078
3079 /* The end of a template parameter list has been reached.  Process the
3080    tree list into a parameter vector, converting each parameter into a more
3081    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3082    as PARM_DECLs.  */
3083
3084 tree
3085 end_template_parm_list (tree parms)
3086 {
3087   int nparms;
3088   tree parm, next;
3089   tree saved_parmlist = make_tree_vec (list_length (parms));
3090
3091   current_template_parms
3092     = tree_cons (size_int (processing_template_decl),
3093                  saved_parmlist, current_template_parms);
3094
3095   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3096     {
3097       next = TREE_CHAIN (parm);
3098       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3099       TREE_CHAIN (parm) = NULL_TREE;
3100     }
3101
3102   --processing_template_parmlist;
3103
3104   return saved_parmlist;
3105 }
3106
3107 /* end_template_decl is called after a template declaration is seen.  */
3108
3109 void
3110 end_template_decl (void)
3111 {
3112   reset_specialization ();
3113
3114   if (! processing_template_decl)
3115     return;
3116
3117   /* This matches the pushlevel in begin_template_parm_list.  */
3118   finish_scope ();
3119
3120   --processing_template_decl;
3121   current_template_parms = TREE_CHAIN (current_template_parms);
3122 }
3123
3124 /* Within the declaration of a template, return all levels of template
3125    parameters that apply.  The template parameters are represented as
3126    a TREE_VEC, in the form documented in cp-tree.h for template
3127    arguments.  */
3128
3129 static tree
3130 current_template_args (void)
3131 {
3132   tree header;
3133   tree args = NULL_TREE;
3134   int length = TMPL_PARMS_DEPTH (current_template_parms);
3135   int l = length;
3136
3137   /* If there is only one level of template parameters, we do not
3138      create a TREE_VEC of TREE_VECs.  Instead, we return a single
3139      TREE_VEC containing the arguments.  */
3140   if (length > 1)
3141     args = make_tree_vec (length);
3142
3143   for (header = current_template_parms; header; header = TREE_CHAIN (header))
3144     {
3145       tree a = copy_node (TREE_VALUE (header));
3146       int i;
3147
3148       TREE_TYPE (a) = NULL_TREE;
3149       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3150         {
3151           tree t = TREE_VEC_ELT (a, i);
3152
3153           /* T will be a list if we are called from within a
3154              begin/end_template_parm_list pair, but a vector directly
3155              if within a begin/end_member_template_processing pair.  */
3156           if (TREE_CODE (t) == TREE_LIST)
3157             {
3158               t = TREE_VALUE (t);
3159
3160               if (!error_operand_p (t))
3161                 {
3162                   if (TREE_CODE (t) == TYPE_DECL
3163                       || TREE_CODE (t) == TEMPLATE_DECL)
3164                     {
3165                       t = TREE_TYPE (t);
3166                       
3167                       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3168                         {
3169                           /* Turn this argument into a TYPE_ARGUMENT_PACK
3170                              with a single element, which expands T.  */
3171                           tree vec = make_tree_vec (1);
3172                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3173                           
3174                           t = make_node (TYPE_ARGUMENT_PACK);
3175                           SET_ARGUMENT_PACK_ARGS (t, vec);
3176                         }
3177                     }
3178                   else
3179                     {
3180                       t = DECL_INITIAL (t);
3181                       
3182                       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3183                         {
3184                           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3185                              with a single element, which expands T.  */
3186                           tree vec = make_tree_vec (1);
3187                           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3188                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3189                           
3190                           t  = make_node (NONTYPE_ARGUMENT_PACK);
3191                           SET_ARGUMENT_PACK_ARGS (t, vec);
3192                           TREE_TYPE (t) = type;
3193                         }
3194                     }
3195                   TREE_VEC_ELT (a, i) = t;
3196                 }
3197             }
3198         }
3199
3200       if (length > 1)
3201         TREE_VEC_ELT (args, --l) = a;
3202       else
3203         args = a;
3204     }
3205
3206   return args;
3207 }
3208
3209 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
3210    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
3211    a member template.  Used by push_template_decl below.  */
3212
3213 static tree
3214 build_template_decl (tree decl, tree parms, bool member_template_p)
3215 {
3216   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
3217   DECL_TEMPLATE_PARMS (tmpl) = parms;
3218   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
3219   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
3220   if (DECL_LANG_SPECIFIC (decl))
3221     {
3222       DECL_STATIC_FUNCTION_P (tmpl) = DECL_STATIC_FUNCTION_P (decl);
3223       DECL_CONSTRUCTOR_P (tmpl) = DECL_CONSTRUCTOR_P (decl);
3224       DECL_DESTRUCTOR_P (tmpl) = DECL_DESTRUCTOR_P (decl);
3225       DECL_NONCONVERTING_P (tmpl) = DECL_NONCONVERTING_P (decl);
3226       DECL_ASSIGNMENT_OPERATOR_P (tmpl) = DECL_ASSIGNMENT_OPERATOR_P (decl);
3227       if (DECL_OVERLOADED_OPERATOR_P (decl))
3228         SET_OVERLOADED_OPERATOR_CODE (tmpl,
3229                                       DECL_OVERLOADED_OPERATOR_P (decl));
3230     }
3231
3232   return tmpl;
3233 }
3234
3235 struct template_parm_data
3236 {
3237   /* The level of the template parameters we are currently
3238      processing.  */
3239   int level;
3240
3241   /* The index of the specialization argument we are currently
3242      processing.  */
3243   int current_arg;
3244
3245   /* An array whose size is the number of template parameters.  The
3246      elements are nonzero if the parameter has been used in any one
3247      of the arguments processed so far.  */
3248   int* parms;
3249
3250   /* An array whose size is the number of template arguments.  The
3251      elements are nonzero if the argument makes use of template
3252      parameters of this level.  */
3253   int* arg_uses_template_parms;
3254 };
3255
3256 /* Subroutine of push_template_decl used to see if each template
3257    parameter in a partial specialization is used in the explicit
3258    argument list.  If T is of the LEVEL given in DATA (which is
3259    treated as a template_parm_data*), then DATA->PARMS is marked
3260    appropriately.  */
3261
3262 static int
3263 mark_template_parm (tree t, void* data)
3264 {
3265   int level;
3266   int idx;
3267   struct template_parm_data* tpd = (struct template_parm_data*) data;
3268
3269   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3270     {
3271       level = TEMPLATE_PARM_LEVEL (t);
3272       idx = TEMPLATE_PARM_IDX (t);
3273     }
3274   else
3275     {
3276       level = TEMPLATE_TYPE_LEVEL (t);
3277       idx = TEMPLATE_TYPE_IDX (t);
3278     }
3279
3280   if (level == tpd->level)
3281     {
3282       tpd->parms[idx] = 1;
3283       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
3284     }
3285
3286   /* Return zero so that for_each_template_parm will continue the
3287      traversal of the tree; we want to mark *every* template parm.  */
3288   return 0;
3289 }
3290
3291 /* Process the partial specialization DECL.  */
3292
3293 static tree
3294 process_partial_specialization (tree decl)
3295 {
3296   tree type = TREE_TYPE (decl);
3297   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
3298   tree specargs = CLASSTYPE_TI_ARGS (type);
3299   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
3300   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
3301   tree inner_parms;
3302   int nargs = TREE_VEC_LENGTH (inner_args);
3303   int ntparms;
3304   int  i;
3305   int did_error_intro = 0;
3306   struct template_parm_data tpd;
3307   struct template_parm_data tpd2;
3308
3309   gcc_assert (current_template_parms);
3310
3311   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3312   ntparms = TREE_VEC_LENGTH (inner_parms);
3313
3314   /* We check that each of the template parameters given in the
3315      partial specialization is used in the argument list to the
3316      specialization.  For example:
3317
3318        template <class T> struct S;
3319        template <class T> struct S<T*>;
3320
3321      The second declaration is OK because `T*' uses the template
3322      parameter T, whereas
3323
3324        template <class T> struct S<int>;
3325
3326      is no good.  Even trickier is:
3327
3328        template <class T>
3329        struct S1
3330        {
3331           template <class U>
3332           struct S2;
3333           template <class U>
3334           struct S2<T>;
3335        };
3336
3337      The S2<T> declaration is actually invalid; it is a
3338      full-specialization.  Of course,
3339
3340           template <class U>
3341           struct S2<T (*)(U)>;
3342
3343      or some such would have been OK.  */
3344   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
3345   tpd.parms = (int *) alloca (sizeof (int) * ntparms);
3346   memset (tpd.parms, 0, sizeof (int) * ntparms);
3347
3348   tpd.arg_uses_template_parms = (int *) alloca (sizeof (int) * nargs);
3349   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
3350   for (i = 0; i < nargs; ++i)
3351     {
3352       tpd.current_arg = i;
3353       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
3354                               &mark_template_parm,
3355                               &tpd,
3356                               NULL,
3357                               /*include_nondeduced_p=*/false);
3358     }
3359   for (i = 0; i < ntparms; ++i)
3360     if (tpd.parms[i] == 0)
3361       {
3362         /* One of the template parms was not used in the
3363            specialization.  */
3364         if (!did_error_intro)
3365           {
3366             error ("template parameters not used in partial specialization:");
3367             did_error_intro = 1;
3368           }
3369
3370         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
3371       }
3372
3373   /* [temp.class.spec]
3374
3375      The argument list of the specialization shall not be identical to
3376      the implicit argument list of the primary template.  */
3377   if (comp_template_args
3378       (inner_args,
3379        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
3380                                                    (maintmpl)))))
3381     error ("partial specialization %qT does not specialize any template arguments", type);
3382
3383   /* [temp.class.spec]
3384
3385      A partially specialized non-type argument expression shall not
3386      involve template parameters of the partial specialization except
3387      when the argument expression is a simple identifier.
3388
3389      The type of a template parameter corresponding to a specialized
3390      non-type argument shall not be dependent on a parameter of the
3391      specialization. 
3392
3393      Also, we verify that pack expansions only occur at the
3394      end of the argument list.  */
3395   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
3396   tpd2.parms = 0;
3397   for (i = 0; i < nargs; ++i)
3398     {
3399       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
3400       tree arg = TREE_VEC_ELT (inner_args, i);
3401       tree packed_args = NULL_TREE;
3402       int j, len = 1;
3403
3404       if (ARGUMENT_PACK_P (arg))
3405         {
3406           /* Extract the arguments from the argument pack. We'll be
3407              iterating over these in the following loop.  */
3408           packed_args = ARGUMENT_PACK_ARGS (arg);
3409           len = TREE_VEC_LENGTH (packed_args);
3410         }
3411
3412       for (j = 0; j < len; j++)
3413         {
3414           if (packed_args)
3415             /* Get the Jth argument in the parameter pack.  */
3416             arg = TREE_VEC_ELT (packed_args, j);
3417
3418           if (PACK_EXPANSION_P (arg))
3419             {
3420               /* Pack expansions must come at the end of the
3421                  argument list.  */
3422               if ((packed_args && j < len - 1)
3423                   || (!packed_args && i < nargs - 1))
3424                 {
3425                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3426                     error ("parameter pack argument %qE must be at the end of the template argument list", arg);
3427                   else
3428                     error ("parameter pack argument %qT must be at the end of the template argument list", arg);
3429
3430                   if (packed_args)
3431                     TREE_VEC_ELT (packed_args, j) = error_mark_node;
3432                 }
3433             }
3434
3435           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3436             /* We only care about the pattern.  */
3437             arg = PACK_EXPANSION_PATTERN (arg);
3438
3439           if (/* These first two lines are the `non-type' bit.  */
3440               !TYPE_P (arg)
3441               && TREE_CODE (arg) != TEMPLATE_DECL
3442               /* This next line is the `argument expression is not just a
3443                  simple identifier' condition and also the `specialized
3444                  non-type argument' bit.  */
3445               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
3446             {
3447               if ((!packed_args && tpd.arg_uses_template_parms[i])
3448                   || (packed_args && uses_template_parms (arg)))
3449                 error ("template argument %qE involves template parameter(s)",
3450                        arg);
3451               else 
3452                 {
3453                   /* Look at the corresponding template parameter,
3454                      marking which template parameters its type depends
3455                      upon.  */
3456                   tree type = TREE_TYPE (parm);
3457
3458                   if (!tpd2.parms)
3459                     {
3460                       /* We haven't yet initialized TPD2.  Do so now.  */
3461                       tpd2.arg_uses_template_parms 
3462                         = (int *) alloca (sizeof (int) * nargs);
3463                       /* The number of parameters here is the number in the
3464                          main template, which, as checked in the assertion
3465                          above, is NARGS.  */
3466                       tpd2.parms = (int *) alloca (sizeof (int) * nargs);
3467                       tpd2.level = 
3468                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
3469                     }
3470
3471                   /* Mark the template parameters.  But this time, we're
3472                      looking for the template parameters of the main
3473                      template, not in the specialization.  */
3474                   tpd2.current_arg = i;
3475                   tpd2.arg_uses_template_parms[i] = 0;
3476                   memset (tpd2.parms, 0, sizeof (int) * nargs);
3477                   for_each_template_parm (type,
3478                                           &mark_template_parm,
3479                                           &tpd2,
3480                                           NULL,
3481                                           /*include_nondeduced_p=*/false);
3482
3483                   if (tpd2.arg_uses_template_parms [i])
3484                     {
3485                       /* The type depended on some template parameters.
3486                          If they are fully specialized in the
3487                          specialization, that's OK.  */
3488                       int j;
3489                       for (j = 0; j < nargs; ++j)
3490                         if (tpd2.parms[j] != 0
3491                             && tpd.arg_uses_template_parms [j])
3492                           {
3493                             error ("type %qT of template argument %qE depends "
3494                                    "on template parameter(s)", 
3495                                    type,
3496                                    arg);
3497                             break;
3498                           }
3499                     }
3500                 }
3501             }
3502         }
3503     }
3504
3505   if (retrieve_specialization (maintmpl, specargs,
3506                                /*class_specializations_p=*/true))
3507     /* We've already got this specialization.  */
3508     return decl;
3509
3510   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
3511     = tree_cons (specargs, inner_parms,
3512                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
3513   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
3514   return decl;
3515 }
3516
3517 /* Check that a template declaration's use of default arguments and
3518    parameter packs is not invalid.  Here, PARMS are the template
3519    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
3520    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
3521    specialization.
3522    
3523
3524    IS_FRIEND_DECL is nonzero if DECL is a friend function template
3525    declaration (but not a definition); 1 indicates a declaration, 2
3526    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
3527    emitted for extraneous default arguments.
3528
3529    Returns TRUE if there were no errors found, FALSE otherwise. */
3530
3531 bool
3532 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
3533                          int is_partial, int is_friend_decl)
3534 {
3535   const char *msg;
3536   int last_level_to_check;
3537   tree parm_level;
3538   bool no_errors = true;
3539
3540   /* [temp.param]
3541
3542      A default template-argument shall not be specified in a
3543      function template declaration or a function template definition, nor
3544      in the template-parameter-list of the definition of a member of a
3545      class template.  */
3546
3547   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
3548     /* You can't have a function template declaration in a local
3549        scope, nor you can you define a member of a class template in a
3550        local scope.  */
3551     return true;
3552
3553   if (current_class_type
3554       && !TYPE_BEING_DEFINED (current_class_type)
3555       && DECL_LANG_SPECIFIC (decl)
3556       /* If this is either a friend defined in the scope of the class
3557          or a member function.  */
3558       && (DECL_FUNCTION_MEMBER_P (decl)
3559           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
3560           : DECL_FRIEND_CONTEXT (decl)
3561           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
3562           : false)
3563       /* And, if it was a member function, it really was defined in
3564          the scope of the class.  */
3565       && (!DECL_FUNCTION_MEMBER_P (decl)
3566           || DECL_INITIALIZED_IN_CLASS_P (decl)))
3567     /* We already checked these parameters when the template was
3568        declared, so there's no need to do it again now.  This function
3569        was defined in class scope, but we're processing it's body now
3570        that the class is complete.  */
3571     return true;
3572
3573   /* Core issue 226 (C++0x only): the following only applies to class
3574      templates.  */
3575   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
3576     {
3577       /* [temp.param]
3578
3579          If a template-parameter has a default template-argument, all
3580          subsequent template-parameters shall have a default
3581          template-argument supplied.  */
3582       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
3583         {
3584           tree inner_parms = TREE_VALUE (parm_level);
3585           int ntparms = TREE_VEC_LENGTH (inner_parms);
3586           int seen_def_arg_p = 0;
3587           int i;
3588
3589           for (i = 0; i < ntparms; ++i)
3590             {
3591               tree parm = TREE_VEC_ELT (inner_parms, i);
3592
3593               if (parm == error_mark_node)
3594                 continue;
3595
3596               if (TREE_PURPOSE (parm))
3597                 seen_def_arg_p = 1;
3598               else if (seen_def_arg_p
3599                        && !template_parameter_pack_p (TREE_VALUE (parm)))
3600                 {
3601                   error ("no default argument for %qD", TREE_VALUE (parm));
3602                   /* For better subsequent error-recovery, we indicate that
3603                      there should have been a default argument.  */
3604                   TREE_PURPOSE (parm) = error_mark_node;
3605                   no_errors = false;
3606                 }
3607               else if (is_primary
3608                        && !is_partial
3609                        && !is_friend_decl
3610                        /* Don't complain about an enclosing partial
3611                           specialization.  */
3612                        && parm_level == parms
3613                        && TREE_CODE (decl) == TYPE_DECL
3614                        && i < ntparms - 1
3615                        && template_parameter_pack_p (TREE_VALUE (parm)))
3616                 {
3617                   /* A primary class template can only have one
3618                      parameter pack, at the end of the template
3619                      parameter list.  */
3620
3621                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
3622                     error ("parameter pack %qE must be at the end of the"
3623                            " template parameter list", TREE_VALUE (parm));
3624                   else
3625                     error ("parameter pack %qT must be at the end of the"
3626                            " template parameter list", 
3627                            TREE_TYPE (TREE_VALUE (parm)));
3628
3629                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
3630                     = error_mark_node;
3631                   no_errors = false;
3632                 }
3633             }
3634         }
3635     }
3636
3637   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
3638       || is_partial 
3639       || !is_primary
3640       || is_friend_decl)
3641     /* For an ordinary class template, default template arguments are
3642        allowed at the innermost level, e.g.:
3643          template <class T = int>
3644          struct S {};
3645        but, in a partial specialization, they're not allowed even
3646        there, as we have in [temp.class.spec]:
3647
3648          The template parameter list of a specialization shall not
3649          contain default template argument values.
3650
3651        So, for a partial specialization, or for a function template
3652        (in C++98/C++03), we look at all of them.  */
3653     ;
3654   else
3655     /* But, for a primary class template that is not a partial
3656        specialization we look at all template parameters except the
3657        innermost ones.  */
3658     parms = TREE_CHAIN (parms);
3659
3660   /* Figure out what error message to issue.  */
3661   if (is_friend_decl == 2)
3662     msg = "default template arguments may not be used in function template friend re-declaration";
3663   else if (is_friend_decl)
3664     msg = "default template arguments may not be used in function template friend declarations";
3665   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
3666     msg = "default template arguments may not be used in function templates";
3667   else if (is_partial)
3668     msg = "default template arguments may not be used in partial specializations";
3669   else
3670     msg = "default argument for template parameter for class enclosing %qD";
3671
3672   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
3673     /* If we're inside a class definition, there's no need to
3674        examine the parameters to the class itself.  On the one
3675        hand, they will be checked when the class is defined, and,
3676        on the other, default arguments are valid in things like:
3677          template <class T = double>
3678          struct S { template <class U> void f(U); };
3679        Here the default argument for `S' has no bearing on the
3680        declaration of `f'.  */
3681     last_level_to_check = template_class_depth (current_class_type) + 1;
3682   else
3683     /* Check everything.  */
3684     last_level_to_check = 0;
3685
3686   for (parm_level = parms;
3687        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
3688        parm_level = TREE_CHAIN (parm_level))
3689     {
3690       tree inner_parms = TREE_VALUE (parm_level);
3691       int i;
3692       int ntparms;
3693
3694       ntparms = TREE_VEC_LENGTH (inner_parms);
3695       for (i = 0; i < ntparms; ++i)
3696         {
3697           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
3698             continue;
3699
3700           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
3701             {
3702               if (msg)
3703                 {
3704                   no_errors = false;
3705                   if (is_friend_decl == 2)
3706                     return no_errors;
3707
3708                   error (msg, decl);
3709                   msg = 0;
3710                 }
3711
3712               /* Clear out the default argument so that we are not
3713                  confused later.  */
3714               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
3715             }
3716         }
3717
3718       /* At this point, if we're still interested in issuing messages,
3719          they must apply to classes surrounding the object declared.  */
3720       if (msg)
3721         msg = "default argument for template parameter for class enclosing %qD";
3722     }
3723
3724   return no_errors;
3725 }
3726
3727 /* Worker for push_template_decl_real, called via
3728    for_each_template_parm.  DATA is really an int, indicating the
3729    level of the parameters we are interested in.  If T is a template
3730    parameter of that level, return nonzero.  */
3731
3732 static int
3733 template_parm_this_level_p (tree t, void* data)
3734 {
3735   int this_level = *(int *)data;
3736   int level;
3737
3738   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3739     level = TEMPLATE_PARM_LEVEL (t);
3740   else
3741     level = TEMPLATE_TYPE_LEVEL (t);
3742   return level == this_level;
3743 }
3744
3745 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
3746    parameters given by current_template_args, or reuses a
3747    previously existing one, if appropriate.  Returns the DECL, or an
3748    equivalent one, if it is replaced via a call to duplicate_decls.
3749
3750    If IS_FRIEND is true, DECL is a friend declaration.  */
3751
3752 tree
3753 push_template_decl_real (tree decl, bool is_friend)
3754 {
3755   tree tmpl;
3756   tree args;
3757   tree info;
3758   tree ctx;
3759   int primary;
3760   int is_partial;
3761   int new_template_p = 0;
3762   /* True if the template is a member template, in the sense of
3763      [temp.mem].  */
3764   bool member_template_p = false;
3765
3766   if (decl == error_mark_node || !current_template_parms)
3767     return error_mark_node;
3768
3769   /* See if this is a partial specialization.  */
3770   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
3771                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
3772                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
3773
3774   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
3775     is_friend = true;
3776
3777   if (is_friend)
3778     /* For a friend, we want the context of the friend function, not
3779        the type of which it is a friend.  */
3780     ctx = DECL_CONTEXT (decl);
3781   else if (CP_DECL_CONTEXT (decl)
3782            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
3783     /* In the case of a virtual function, we want the class in which
3784        it is defined.  */
3785     ctx = CP_DECL_CONTEXT (decl);
3786   else
3787     /* Otherwise, if we're currently defining some class, the DECL
3788        is assumed to be a member of the class.  */
3789     ctx = current_scope ();
3790
3791   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
3792     ctx = NULL_TREE;
3793
3794   if (!DECL_CONTEXT (decl))
3795     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
3796
3797   /* See if this is a primary template.  */
3798   if (is_friend && ctx)
3799     /* A friend template that specifies a class context, i.e.
3800          template <typename T> friend void A<T>::f();
3801        is not primary.  */
3802     primary = 0;
3803   else
3804     primary = template_parm_scope_p ();
3805
3806   if (primary)
3807     {
3808       if (DECL_CLASS_SCOPE_P (decl))
3809         member_template_p = true;
3810       if (TREE_CODE (decl) == TYPE_DECL
3811           && ANON_AGGRNAME_P (DECL_NAME (decl)))
3812         {
3813           error ("template class without a name");
3814           return error_mark_node;
3815         }
3816       else if (TREE_CODE (decl) == FUNCTION_DECL)
3817         {
3818           if (DECL_DESTRUCTOR_P (decl))
3819             {
3820               /* [temp.mem]
3821
3822                  A destructor shall not be a member template.  */
3823               error ("destructor %qD declared as member template", decl);
3824               return error_mark_node;
3825             }
3826           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
3827               && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
3828                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
3829                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
3830                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
3831                       == void_list_node)))
3832             {
3833               /* [basic.stc.dynamic.allocation]
3834
3835                  An allocation function can be a function
3836                  template. ... Template allocation functions shall
3837                  have two or more parameters.  */
3838               error ("invalid template declaration of %qD", decl);
3839               return error_mark_node;
3840             }
3841         }
3842       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
3843                && CLASS_TYPE_P (TREE_TYPE (decl)))
3844         /* OK */;
3845       else
3846         {
3847           error ("template declaration of %q#D", decl);
3848           return error_mark_node;
3849         }
3850     }
3851
3852   /* Check to see that the rules regarding the use of default
3853      arguments are not being violated.  */
3854   check_default_tmpl_args (decl, current_template_parms,
3855                            primary, is_partial, /*is_friend_decl=*/0);
3856
3857   /* Ensure that there are no parameter packs in the type of this
3858      declaration that have not been expanded.  */
3859   if (TREE_CODE (decl) == FUNCTION_DECL)
3860     {
3861       /* Check each of the arguments individually to see if there are
3862          any bare parameter packs.  */
3863       tree type = TREE_TYPE (decl);
3864       tree arg = DECL_ARGUMENTS (decl);
3865       tree argtype = TYPE_ARG_TYPES (type);
3866
3867       while (arg && argtype)
3868         {
3869           if (!FUNCTION_PARAMETER_PACK_P (arg)
3870               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
3871             {
3872             /* This is a PARM_DECL that contains unexpanded parameter
3873                packs. We have already complained about this in the
3874                check_for_bare_parameter_packs call, so just replace
3875                these types with ERROR_MARK_NODE.  */
3876               TREE_TYPE (arg) = error_mark_node;
3877               TREE_VALUE (argtype) = error_mark_node;
3878             }
3879
3880           arg = TREE_CHAIN (arg);
3881           argtype = TREE_CHAIN (argtype);
3882         }
3883
3884       /* Check for bare parameter packs in the return type and the
3885          exception specifiers.  */
3886       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
3887         /* Errors were already issued, set return type to int
3888            as the frontend doesn't expect error_mark_node as
3889            the return type.  */
3890         TREE_TYPE (type) = integer_type_node;
3891       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
3892         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
3893     }
3894   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
3895     {
3896       TREE_TYPE (decl) = error_mark_node;
3897       return error_mark_node;
3898     }
3899
3900   if (is_partial)
3901     return process_partial_specialization (decl);
3902
3903   args = current_template_args ();
3904
3905   if (!ctx
3906       || TREE_CODE (ctx) == FUNCTION_DECL
3907       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
3908       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
3909     {
3910       if (DECL_LANG_SPECIFIC (decl)
3911           && DECL_TEMPLATE_INFO (decl)
3912           && DECL_TI_TEMPLATE (decl))
3913         tmpl = DECL_TI_TEMPLATE (decl);
3914       /* If DECL is a TYPE_DECL for a class-template, then there won't
3915          be DECL_LANG_SPECIFIC.  The information equivalent to
3916          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
3917       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
3918                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
3919                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
3920         {
3921           /* Since a template declaration already existed for this
3922              class-type, we must be redeclaring it here.  Make sure
3923              that the redeclaration is valid.  */
3924           redeclare_class_template (TREE_TYPE (decl),
3925                                     current_template_parms);
3926           /* We don't need to create a new TEMPLATE_DECL; just use the
3927              one we already had.  */
3928           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
3929         }
3930       else
3931         {
3932           tmpl = build_template_decl (decl, current_template_parms,
3933                                       member_template_p);
3934           new_template_p = 1;
3935
3936           if (DECL_LANG_SPECIFIC (decl)
3937               && DECL_TEMPLATE_SPECIALIZATION (decl))
3938             {
3939               /* A specialization of a member template of a template
3940                  class.  */
3941               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
3942               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
3943               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
3944             }
3945         }
3946     }
3947   else
3948     {
3949       tree a, t, current, parms;
3950       int i;
3951       tree tinfo = get_template_info (decl);
3952
3953       if (!tinfo)
3954         {
3955           error ("template definition of non-template %q#D", decl);
3956           return error_mark_node;
3957         }
3958
3959       tmpl = TI_TEMPLATE (tinfo);
3960
3961       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
3962           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
3963           && DECL_TEMPLATE_SPECIALIZATION (decl)
3964           && DECL_MEMBER_TEMPLATE_P (tmpl))
3965         {
3966           tree new_tmpl;
3967
3968           /* The declaration is a specialization of a member
3969              template, declared outside the class.  Therefore, the
3970              innermost template arguments will be NULL, so we
3971              replace them with the arguments determined by the
3972              earlier call to check_explicit_specialization.  */
3973           args = DECL_TI_ARGS (decl);
3974
3975           new_tmpl
3976             = build_template_decl (decl, current_template_parms,
3977                                    member_template_p);
3978           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
3979           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
3980           DECL_TI_TEMPLATE (decl) = new_tmpl;
3981           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
3982           DECL_TEMPLATE_INFO (new_tmpl)
3983             = tree_cons (tmpl, args, NULL_TREE);
3984
3985           register_specialization (new_tmpl,
3986                                    most_general_template (tmpl),
3987                                    args,
3988                                    is_friend);
3989           return decl;
3990         }
3991
3992       /* Make sure the template headers we got make sense.  */
3993
3994       parms = DECL_TEMPLATE_PARMS (tmpl);
3995       i = TMPL_PARMS_DEPTH (parms);
3996       if (TMPL_ARGS_DEPTH (args) != i)
3997         {
3998           error ("expected %d levels of template parms for %q#D, got %d",
3999                  i, decl, TMPL_ARGS_DEPTH (args));
4000         }
4001       else
4002         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4003           {
4004             a = TMPL_ARGS_LEVEL (args, i);
4005             t = INNERMOST_TEMPLATE_PARMS (parms);
4006
4007             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4008               {
4009                 if (current == decl)
4010                   error ("got %d template parameters for %q#D",
4011                          TREE_VEC_LENGTH (a), decl);
4012                 else
4013                   error ("got %d template parameters for %q#T",
4014                          TREE_VEC_LENGTH (a), current);
4015                 error ("  but %d required", TREE_VEC_LENGTH (t));
4016                 return error_mark_node;
4017               }
4018
4019             if (current == decl)
4020               current = ctx;
4021             else
4022               current = (TYPE_P (current)
4023                          ? TYPE_CONTEXT (current)
4024                          : DECL_CONTEXT (current));
4025           }
4026
4027       /* Check that the parms are used in the appropriate qualifying scopes
4028          in the declarator.  */
4029       if (!comp_template_args
4030           (TI_ARGS (tinfo),
4031            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4032         {
4033           error ("\
4034 template arguments to %qD do not match original template %qD",
4035                  decl, DECL_TEMPLATE_RESULT (tmpl));
4036           if (!uses_template_parms (TI_ARGS (tinfo)))
4037             inform (input_location, "use template<> for an explicit specialization");
4038           /* Avoid crash in import_export_decl.  */
4039           DECL_INTERFACE_KNOWN (decl) = 1;
4040           return error_mark_node;
4041         }
4042     }
4043
4044   DECL_TEMPLATE_RESULT (tmpl) = decl;
4045   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4046
4047   /* Push template declarations for global functions and types.  Note
4048      that we do not try to push a global template friend declared in a
4049      template class; such a thing may well depend on the template
4050      parameters of the class.  */
4051   if (new_template_p && !ctx
4052       && !(is_friend && template_class_depth (current_class_type) > 0))
4053     {
4054       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4055       if (tmpl == error_mark_node)
4056         return error_mark_node;
4057
4058       /* Hide template friend classes that haven't been declared yet.  */
4059       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4060         {
4061           DECL_ANTICIPATED (tmpl) = 1;
4062           DECL_FRIEND_P (tmpl) = 1;
4063         }
4064     }
4065
4066   if (primary)
4067     {
4068       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4069       int i;
4070
4071       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4072       if (DECL_CONV_FN_P (tmpl))
4073         {
4074           int depth = TMPL_PARMS_DEPTH (parms);
4075
4076           /* It is a conversion operator. See if the type converted to
4077              depends on innermost template operands.  */
4078
4079           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4080                                          depth))
4081             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4082         }
4083
4084       /* Give template template parms a DECL_CONTEXT of the template
4085          for which they are a parameter.  */
4086       parms = INNERMOST_TEMPLATE_PARMS (parms);
4087       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
4088         {
4089           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4090           if (TREE_CODE (parm) == TEMPLATE_DECL)
4091             DECL_CONTEXT (parm) = tmpl;
4092         }
4093     }
4094
4095   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
4096      back to its most general template.  If TMPL is a specialization,
4097      ARGS may only have the innermost set of arguments.  Add the missing
4098      argument levels if necessary.  */
4099   if (DECL_TEMPLATE_INFO (tmpl))
4100     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
4101
4102   info = tree_cons (tmpl, args, NULL_TREE);
4103
4104   if (DECL_IMPLICIT_TYPEDEF_P (decl))
4105     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
4106   else if (DECL_LANG_SPECIFIC (decl))
4107     DECL_TEMPLATE_INFO (decl) = info;
4108
4109   return DECL_TEMPLATE_RESULT (tmpl);
4110 }
4111
4112 tree
4113 push_template_decl (tree decl)
4114 {
4115   return push_template_decl_real (decl, false);
4116 }
4117
4118 /* Called when a class template TYPE is redeclared with the indicated
4119    template PARMS, e.g.:
4120
4121      template <class T> struct S;
4122      template <class T> struct S {};  */
4123
4124 bool
4125 redeclare_class_template (tree type, tree parms)
4126 {
4127   tree tmpl;
4128   tree tmpl_parms;
4129   int i;
4130
4131   if (!TYPE_TEMPLATE_INFO (type))
4132     {
4133       error ("%qT is not a template type", type);
4134       return false;
4135     }
4136
4137   tmpl = TYPE_TI_TEMPLATE (type);
4138   if (!PRIMARY_TEMPLATE_P (tmpl))
4139     /* The type is nested in some template class.  Nothing to worry
4140        about here; there are no new template parameters for the nested
4141        type.  */
4142     return true;
4143
4144   if (!parms)
4145     {
4146       error ("template specifiers not specified in declaration of %qD",
4147              tmpl);
4148       return false;
4149     }
4150
4151   parms = INNERMOST_TEMPLATE_PARMS (parms);
4152   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
4153
4154   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
4155     {
4156       error ("redeclared with %d template parameter(s)", 
4157              TREE_VEC_LENGTH (parms));
4158       inform (input_location, "previous declaration %q+D used %d template parameter(s)", 
4159              tmpl, TREE_VEC_LENGTH (tmpl_parms));
4160       return false;
4161     }
4162
4163   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
4164     {
4165       tree tmpl_parm;
4166       tree parm;
4167       tree tmpl_default;
4168       tree parm_default;
4169
4170       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
4171           || TREE_VEC_ELT (parms, i) == error_mark_node)
4172         continue;
4173
4174       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
4175       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4176       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
4177       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
4178
4179       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
4180          TEMPLATE_DECL.  */
4181       if (tmpl_parm != error_mark_node
4182           && (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
4183               || (TREE_CODE (tmpl_parm) != TYPE_DECL
4184                   && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
4185               || (TREE_CODE (tmpl_parm) != PARM_DECL
4186                   && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
4187                       != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
4188               || (TREE_CODE (tmpl_parm) == PARM_DECL
4189                   && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
4190                       != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))))))
4191         {
4192           error ("template parameter %q+#D", tmpl_parm);
4193           error ("redeclared here as %q#D", parm);
4194           return false;
4195         }
4196
4197       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
4198         {
4199           /* We have in [temp.param]:
4200
4201              A template-parameter may not be given default arguments
4202              by two different declarations in the same scope.  */
4203           error ("redefinition of default argument for %q#D", parm);
4204           inform (input_location, "%Joriginal definition appeared here", tmpl_parm);
4205           return false;
4206         }
4207
4208       if (parm_default != NULL_TREE)
4209         /* Update the previous template parameters (which are the ones
4210            that will really count) with the new default value.  */
4211         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
4212       else if (tmpl_default != NULL_TREE)
4213         /* Update the new parameters, too; they'll be used as the
4214            parameters for any members.  */
4215         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
4216     }
4217
4218     return true;
4219 }
4220
4221 /* Simplify EXPR if it is a non-dependent expression.  Returns the
4222    (possibly simplified) expression.  */
4223
4224 tree
4225 fold_non_dependent_expr (tree expr)
4226 {
4227   if (expr == NULL_TREE)
4228     return NULL_TREE;
4229
4230   /* If we're in a template, but EXPR isn't value dependent, simplify
4231      it.  We're supposed to treat:
4232
4233        template <typename T> void f(T[1 + 1]);
4234        template <typename T> void f(T[2]);
4235
4236      as two declarations of the same function, for example.  */
4237   if (processing_template_decl
4238       && !type_dependent_expression_p (expr)
4239       && !value_dependent_expression_p (expr))
4240     {
4241       HOST_WIDE_INT saved_processing_template_decl;
4242
4243       saved_processing_template_decl = processing_template_decl;
4244       processing_template_decl = 0;
4245       expr = tsubst_copy_and_build (expr,
4246                                     /*args=*/NULL_TREE,
4247                                     tf_error,
4248                                     /*in_decl=*/NULL_TREE,
4249                                     /*function_p=*/false,
4250                                     /*integral_constant_expression_p=*/true);
4251       processing_template_decl = saved_processing_template_decl;
4252     }
4253   return expr;
4254 }
4255
4256 /* EXPR is an expression which is used in a constant-expression context.
4257    For instance, it could be a VAR_DECL with a constant initializer.
4258    Extract the innermost constant expression.
4259
4260    This is basically a more powerful version of
4261    integral_constant_value, which can be used also in templates where
4262    initializers can maintain a syntactic rather than semantic form
4263    (even if they are non-dependent, for access-checking purposes).  */
4264
4265 static tree
4266 fold_decl_constant_value (tree expr)
4267 {
4268   tree const_expr = expr;
4269   do
4270     {
4271       expr = fold_non_dependent_expr (const_expr);
4272       const_expr = integral_constant_value (expr);
4273     }
4274   while (expr != const_expr);
4275
4276   return expr;
4277 }
4278
4279 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
4280    must be a function or a pointer-to-function type, as specified
4281    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
4282    and check that the resulting function has external linkage.  */
4283
4284 static tree
4285 convert_nontype_argument_function (tree type, tree expr)
4286 {
4287   tree fns = expr;
4288   tree fn, fn_no_ptr;
4289
4290   fn = instantiate_type (type, fns, tf_none);
4291   if (fn == error_mark_node)
4292     return error_mark_node;
4293
4294   fn_no_ptr = fn;
4295   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
4296     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
4297   if (TREE_CODE (fn_no_ptr) == BASELINK)
4298     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
4299  
4300   /* [temp.arg.nontype]/1
4301
4302      A template-argument for a non-type, non-template template-parameter
4303      shall be one of:
4304      [...]
4305      -- the address of an object or function with external linkage.  */
4306   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
4307     {
4308       error ("%qE is not a valid template argument for type %qT "
4309              "because function %qD has not external linkage",
4310              expr, type, fn_no_ptr);
4311       return NULL_TREE;
4312     }
4313
4314   return fn;
4315 }
4316
4317 /* Attempt to convert the non-type template parameter EXPR to the
4318    indicated TYPE.  If the conversion is successful, return the
4319    converted value.  If the conversion is unsuccessful, return
4320    NULL_TREE if we issued an error message, or error_mark_node if we
4321    did not.  We issue error messages for out-and-out bad template
4322    parameters, but not simply because the conversion failed, since we
4323    might be just trying to do argument deduction.  Both TYPE and EXPR
4324    must be non-dependent.
4325
4326    The conversion follows the special rules described in
4327    [temp.arg.nontype], and it is much more strict than an implicit
4328    conversion.
4329
4330    This function is called twice for each template argument (see
4331    lookup_template_class for a more accurate description of this
4332    problem). This means that we need to handle expressions which
4333    are not valid in a C++ source, but can be created from the
4334    first call (for instance, casts to perform conversions). These
4335    hacks can go away after we fix the double coercion problem.  */
4336
4337 static tree
4338 convert_nontype_argument (tree type, tree expr)
4339 {
4340   tree expr_type;
4341
4342   /* Detect immediately string literals as invalid non-type argument.
4343      This special-case is not needed for correctness (we would easily
4344      catch this later), but only to provide better diagnostic for this
4345      common user mistake. As suggested by DR 100, we do not mention
4346      linkage issues in the diagnostic as this is not the point.  */
4347   if (TREE_CODE (expr) == STRING_CST)
4348     {
4349       error ("%qE is not a valid template argument for type %qT "
4350              "because string literals can never be used in this context",
4351              expr, type);
4352       return NULL_TREE;
4353     }
4354
4355   /* If we are in a template, EXPR may be non-dependent, but still
4356      have a syntactic, rather than semantic, form.  For example, EXPR
4357      might be a SCOPE_REF, rather than the VAR_DECL to which the
4358      SCOPE_REF refers.  Preserving the qualifying scope is necessary
4359      so that access checking can be performed when the template is
4360      instantiated -- but here we need the resolved form so that we can
4361      convert the argument.  */
4362   expr = fold_non_dependent_expr (expr);
4363   if (error_operand_p (expr))
4364     return error_mark_node;
4365   expr_type = TREE_TYPE (expr);
4366
4367   /* HACK: Due to double coercion, we can get a
4368      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
4369      which is the tree that we built on the first call (see
4370      below when coercing to reference to object or to reference to
4371      function). We just strip everything and get to the arg.
4372      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
4373      for examples.  */
4374   if (TREE_CODE (expr) == NOP_EXPR)
4375     {
4376       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
4377         {
4378           /* ??? Maybe we could use convert_from_reference here, but we
4379              would need to relax its constraints because the NOP_EXPR
4380              could actually change the type to something more cv-qualified,
4381              and this is not folded by convert_from_reference.  */
4382           tree addr = TREE_OPERAND (expr, 0);
4383           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
4384           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
4385           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
4386           gcc_assert (same_type_ignoring_top_level_qualifiers_p
4387                       (TREE_TYPE (expr_type),
4388                        TREE_TYPE (TREE_TYPE (addr))));
4389
4390           expr = TREE_OPERAND (addr, 0);
4391           expr_type = TREE_TYPE (expr);
4392         }
4393
4394       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
4395          parameter is a pointer to object, through decay and
4396          qualification conversion. Let's strip everything.  */
4397       else if (TYPE_PTROBV_P (type))
4398         {
4399           STRIP_NOPS (expr);
4400           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
4401           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
4402           /* Skip the ADDR_EXPR only if it is part of the decay for
4403              an array. Otherwise, it is part of the original argument
4404              in the source code.  */
4405           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
4406             expr = TREE_OPERAND (expr, 0);
4407           expr_type = TREE_TYPE (expr);
4408         }
4409     }
4410
4411   /* [temp.arg.nontype]/5, bullet 1
4412
4413      For a non-type template-parameter of integral or enumeration type,
4414      integral promotions (_conv.prom_) and integral conversions
4415      (_conv.integral_) are applied.  */
4416   if (INTEGRAL_TYPE_P (type))
4417     {
4418       if (!INTEGRAL_TYPE_P (expr_type))
4419         return error_mark_node;
4420
4421       expr = fold_decl_constant_value (expr);
4422       /* Notice that there are constant expressions like '4 % 0' which
4423          do not fold into integer constants.  */
4424       if (TREE_CODE (expr) != INTEGER_CST)
4425         {
4426           error ("%qE is not a valid template argument for type %qT "
4427                  "because it is a non-constant expression", expr, type);
4428           return NULL_TREE;
4429         }
4430
4431       /* At this point, an implicit conversion does what we want,
4432          because we already know that the expression is of integral
4433          type.  */
4434       expr = ocp_convert (type, expr, CONV_IMPLICIT, LOOKUP_PROTECT);
4435       if (expr == error_mark_node)
4436         return error_mark_node;
4437
4438       /* Conversion was allowed: fold it to a bare integer constant.  */
4439       expr = fold (expr);
4440     }
4441   /* [temp.arg.nontype]/5, bullet 2
4442
4443      For a non-type template-parameter of type pointer to object,
4444      qualification conversions (_conv.qual_) and the array-to-pointer
4445      conversion (_conv.array_) are applied.  */
4446   else if (TYPE_PTROBV_P (type))
4447     {
4448       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
4449
4450          A template-argument for a non-type, non-template template-parameter
4451          shall be one of: [...]
4452
4453          -- the name of a non-type template-parameter;
4454          -- the address of an object or function with external linkage, [...]
4455             expressed as "& id-expression" where the & is optional if the name
4456             refers to a function or array, or if the corresponding
4457             template-parameter is a reference.
4458
4459         Here, we do not care about functions, as they are invalid anyway
4460         for a parameter of type pointer-to-object.  */
4461
4462       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
4463         /* Non-type template parameters are OK.  */
4464         ;
4465       else if (TREE_CODE (expr) != ADDR_EXPR
4466                && TREE_CODE (expr_type) != ARRAY_TYPE)
4467         {
4468           if (TREE_CODE (expr) == VAR_DECL)
4469             {
4470               error ("%qD is not a valid template argument "
4471                      "because %qD is a variable, not the address of "
4472                      "a variable",
4473                      expr, expr);
4474               return NULL_TREE;
4475             }
4476           /* Other values, like integer constants, might be valid
4477              non-type arguments of some other type.  */
4478           return error_mark_node;
4479         }
4480       else
4481         {
4482           tree decl;
4483
4484           decl = ((TREE_CODE (expr) == ADDR_EXPR)
4485                   ? TREE_OPERAND (expr, 0) : expr);
4486           if (TREE_CODE (decl) != VAR_DECL)
4487             {
4488               error ("%qE is not a valid template argument of type %qT "
4489                      "because %qE is not a variable",
4490                      expr, type, decl);
4491               return NULL_TREE;
4492             }
4493           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
4494             {
4495               error ("%qE is not a valid template argument of type %qT "
4496                      "because %qD does not have external linkage",
4497                      expr, type, decl);
4498               return NULL_TREE;
4499             }
4500         }
4501
4502       expr = decay_conversion (expr);
4503       if (expr == error_mark_node)
4504         return error_mark_node;
4505
4506       expr = perform_qualification_conversions (type, expr);
4507       if (expr == error_mark_node)
4508         return error_mark_node;
4509     }
4510   /* [temp.arg.nontype]/5, bullet 3
4511
4512      For a non-type template-parameter of type reference to object, no
4513      conversions apply. The type referred to by the reference may be more
4514      cv-qualified than the (otherwise identical) type of the
4515      template-argument. The template-parameter is bound directly to the
4516      template-argument, which must be an lvalue.  */
4517   else if (TYPE_REF_OBJ_P (type))
4518     {
4519       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
4520                                                       expr_type))
4521         return error_mark_node;
4522
4523       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
4524         {
4525           error ("%qE is not a valid template argument for type %qT "
4526                  "because of conflicts in cv-qualification", expr, type);
4527           return NULL_TREE;
4528         }
4529
4530       if (!real_lvalue_p (expr))
4531         {
4532           error ("%qE is not a valid template argument for type %qT "
4533                  "because it is not an lvalue", expr, type);
4534           return NULL_TREE;
4535         }
4536
4537       /* [temp.arg.nontype]/1
4538
4539          A template-argument for a non-type, non-template template-parameter
4540          shall be one of: [...]
4541
4542          -- the address of an object or function with external linkage.  */
4543       if (!DECL_EXTERNAL_LINKAGE_P (expr))
4544         {
4545           error ("%qE is not a valid template argument for type %qT "
4546                  "because object %qD has not external linkage",
4547                  expr, type, expr);
4548           return NULL_TREE;
4549         }
4550
4551       expr = build_nop (type, build_address (expr));
4552     }
4553   /* [temp.arg.nontype]/5, bullet 4
4554
4555      For a non-type template-parameter of type pointer to function, only
4556      the function-to-pointer conversion (_conv.func_) is applied. If the
4557      template-argument represents a set of overloaded functions (or a
4558      pointer to such), the matching function is selected from the set
4559      (_over.over_).  */
4560   else if (TYPE_PTRFN_P (type))
4561     {
4562       /* If the argument is a template-id, we might not have enough
4563          context information to decay the pointer.  */
4564       if (!type_unknown_p (expr_type))
4565         {
4566           expr = decay_conversion (expr);
4567           if (expr == error_mark_node)
4568             return error_mark_node;
4569         }
4570
4571       expr = convert_nontype_argument_function (type, expr);
4572       if (!expr || expr == error_mark_node)
4573         return expr;
4574
4575       if (TREE_CODE (expr) != ADDR_EXPR)
4576         {
4577           error ("%qE is not a valid template argument for type %qT", expr, type);
4578           error ("it must be the address of a function with external linkage");
4579           return NULL_TREE;
4580         }
4581     }
4582   /* [temp.arg.nontype]/5, bullet 5
4583
4584      For a non-type template-parameter of type reference to function, no
4585      conversions apply. If the template-argument represents a set of
4586      overloaded functions, the matching function is selected from the set
4587      (_over.over_).  */
4588   else if (TYPE_REFFN_P (type))
4589     {
4590       if (TREE_CODE (expr) == ADDR_EXPR)
4591         {
4592           error ("%qE is not a valid template argument for type %qT "
4593                  "because it is a pointer", expr, type);
4594           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
4595           return NULL_TREE;
4596         }
4597
4598       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
4599       if (!expr || expr == error_mark_node)
4600         return expr;
4601
4602       expr = build_nop (type, build_address (expr));
4603     }
4604   /* [temp.arg.nontype]/5, bullet 6
4605
4606      For a non-type template-parameter of type pointer to member function,
4607      no conversions apply. If the template-argument represents a set of
4608      overloaded member functions, the matching member function is selected
4609      from the set (_over.over_).  */
4610   else if (TYPE_PTRMEMFUNC_P (type))
4611     {
4612       expr = instantiate_type (type, expr, tf_none);
4613       if (expr == error_mark_node)
4614         return error_mark_node;
4615
4616       /* There is no way to disable standard conversions in
4617          resolve_address_of_overloaded_function (called by
4618          instantiate_type). It is possible that the call succeeded by
4619          converting &B::I to &D::I (where B is a base of D), so we need
4620          to reject this conversion here.
4621
4622          Actually, even if there was a way to disable standard conversions,
4623          it would still be better to reject them here so that we can
4624          provide a superior diagnostic.  */
4625       if (!same_type_p (TREE_TYPE (expr), type))
4626         {
4627           /* Make sure we are just one standard conversion off.  */
4628           gcc_assert (can_convert (type, TREE_TYPE (expr)));
4629           error ("%qE is not a valid template argument for type %qT "
4630                  "because it is of type %qT", expr, type,
4631                  TREE_TYPE (expr));
4632           inform (input_location, "standard conversions are not allowed in this context");
4633           return NULL_TREE;
4634         }
4635     }
4636   /* [temp.arg.nontype]/5, bullet 7
4637
4638      For a non-type template-parameter of type pointer to data member,
4639      qualification conversions (_conv.qual_) are applied.  */
4640   else if (TYPE_PTRMEM_P (type))
4641     {
4642       expr = perform_qualification_conversions (type, expr);
4643       if (expr == error_mark_node)
4644         return expr;
4645     }
4646   /* A template non-type parameter must be one of the above.  */
4647   else
4648     gcc_unreachable ();
4649
4650   /* Sanity check: did we actually convert the argument to the
4651      right type?  */
4652   gcc_assert (same_type_p (type, TREE_TYPE (expr)));
4653   return expr;
4654 }
4655
4656 /* Subroutine of coerce_template_template_parms, which returns 1 if
4657    PARM_PARM and ARG_PARM match using the rule for the template
4658    parameters of template template parameters. Both PARM and ARG are
4659    template parameters; the rest of the arguments are the same as for
4660    coerce_template_template_parms.
4661  */
4662 static int
4663 coerce_template_template_parm (tree parm,
4664                               tree arg,
4665                               tsubst_flags_t complain,
4666                               tree in_decl,
4667                               tree outer_args)
4668 {
4669   if (arg == NULL_TREE || arg == error_mark_node
4670       || parm == NULL_TREE || parm == error_mark_node)
4671     return 0;
4672   
4673   if (TREE_CODE (arg) != TREE_CODE (parm))
4674     return 0;
4675   
4676   switch (TREE_CODE (parm))
4677     {
4678     case TEMPLATE_DECL:
4679       /* We encounter instantiations of templates like
4680          template <template <template <class> class> class TT>
4681          class C;  */
4682       {
4683         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
4684         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
4685         
4686         if (!coerce_template_template_parms
4687             (parmparm, argparm, complain, in_decl, outer_args))
4688           return 0;
4689       }
4690       /* Fall through.  */
4691       
4692     case TYPE_DECL:
4693       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
4694           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
4695         /* Argument is a parameter pack but parameter is not.  */
4696         return 0;
4697       break;
4698       
4699     case PARM_DECL:
4700       /* The tsubst call is used to handle cases such as
4701          
4702            template <int> class C {};
4703            template <class T, template <T> class TT> class D {};
4704            D<int, C> d;
4705
4706          i.e. the parameter list of TT depends on earlier parameters.  */
4707       if (!uses_template_parms (TREE_TYPE (arg))
4708           && !same_type_p
4709                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
4710                  TREE_TYPE (arg)))
4711         return 0;
4712       
4713       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
4714           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
4715         /* Argument is a parameter pack but parameter is not.  */
4716         return 0;
4717       
4718       break;
4719
4720     default:
4721       gcc_unreachable ();
4722     }
4723
4724   return 1;
4725 }
4726
4727
4728 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
4729    template template parameters.  Both PARM_PARMS and ARG_PARMS are
4730    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
4731    or PARM_DECL.
4732
4733    Consider the example:
4734      template <class T> class A;
4735      template<template <class U> class TT> class B;
4736
4737    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
4738    the parameters to A, and OUTER_ARGS contains A.  */
4739
4740 static int
4741 coerce_template_template_parms (tree parm_parms,
4742                                 tree arg_parms,
4743                                 tsubst_flags_t complain,
4744                                 tree in_decl,
4745                                 tree outer_args)
4746 {
4747   int nparms, nargs, i;
4748   tree parm, arg;
4749   int variadic_p = 0;
4750
4751   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
4752   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
4753
4754   nparms = TREE_VEC_LENGTH (parm_parms);
4755   nargs = TREE_VEC_LENGTH (arg_parms);
4756
4757   /* Determine whether we have a parameter pack at the end of the
4758      template template parameter's template parameter list.  */
4759   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
4760     {
4761       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
4762       
4763       if (parm == error_mark_node)
4764         return 0;
4765
4766       switch (TREE_CODE (parm))
4767         {
4768         case TEMPLATE_DECL:
4769         case TYPE_DECL:
4770           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
4771             variadic_p = 1;
4772           break;
4773           
4774         case PARM_DECL:
4775           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
4776             variadic_p = 1;
4777           break;
4778           
4779         default:
4780           gcc_unreachable ();
4781         }
4782     }
4783  
4784   if (nargs != nparms
4785       && !(variadic_p && nargs >= nparms - 1))
4786     return 0;
4787
4788   /* Check all of the template parameters except the parameter pack at
4789      the end (if any).  */
4790   for (i = 0; i < nparms - variadic_p; ++i)
4791     {
4792       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
4793           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
4794         continue;
4795
4796       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
4797       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
4798
4799       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
4800                                           outer_args))
4801         return 0;
4802
4803     }
4804
4805   if (variadic_p)
4806     {
4807       /* Check each of the template parameters in the template
4808          argument against the template parameter pack at the end of
4809          the template template parameter.  */
4810       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
4811         return 0;
4812
4813       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
4814
4815       for (; i < nargs; ++i)
4816         {
4817           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
4818             continue;
4819  
4820           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
4821  
4822           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
4823                                               outer_args))
4824             return 0;
4825         }
4826     }
4827
4828   return 1;
4829 }
4830
4831 /* Verifies that the deduced template arguments (in TARGS) for the
4832    template template parameters (in TPARMS) represent valid bindings,
4833    by comparing the template parameter list of each template argument
4834    to the template parameter list of its corresponding template
4835    template parameter, in accordance with DR150. This
4836    routine can only be called after all template arguments have been
4837    deduced. It will return TRUE if all of the template template
4838    parameter bindings are okay, FALSE otherwise.  */
4839 bool 
4840 template_template_parm_bindings_ok_p (tree tparms, tree targs)
4841 {
4842   int i, ntparms = TREE_VEC_LENGTH (tparms);
4843   bool ret = true;
4844
4845   /* We're dealing with template parms in this process.  */
4846   ++processing_template_decl;
4847
4848   targs = INNERMOST_TEMPLATE_ARGS (targs);
4849
4850   for (i = 0; i < ntparms; ++i)
4851     {
4852       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
4853       tree targ = TREE_VEC_ELT (targs, i);
4854
4855       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
4856         {
4857           tree packed_args = NULL_TREE;
4858           int idx, len = 1;
4859
4860           if (ARGUMENT_PACK_P (targ))
4861             {
4862               /* Look inside the argument pack.  */
4863               packed_args = ARGUMENT_PACK_ARGS (targ);
4864               len = TREE_VEC_LENGTH (packed_args);
4865             }
4866
4867           for (idx = 0; idx < len; ++idx)
4868             {
4869               tree targ_parms = NULL_TREE;
4870
4871               if (packed_args)
4872                 /* Extract the next argument from the argument
4873                    pack.  */
4874                 targ = TREE_VEC_ELT (packed_args, idx);
4875
4876               if (PACK_EXPANSION_P (targ))
4877                 /* Look at the pattern of the pack expansion.  */
4878                 targ = PACK_EXPANSION_PATTERN (targ);
4879
4880               /* Extract the template parameters from the template
4881                  argument.  */
4882               if (TREE_CODE (targ) == TEMPLATE_DECL)
4883                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
4884               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
4885                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
4886
4887               /* Verify that we can coerce the template template
4888                  parameters from the template argument to the template
4889                  parameter.  This requires an exact match.  */
4890               if (targ_parms
4891                   && !coerce_template_template_parms
4892                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
4893                         targ_parms,
4894                         tf_none,
4895                         tparm,
4896                         targs))
4897                 {
4898                   ret = false;
4899                   goto out;
4900                 }
4901             }
4902         }
4903     }
4904
4905  out:
4906
4907   --processing_template_decl;
4908   return ret;
4909 }
4910
4911 /* Convert the indicated template ARG as necessary to match the
4912    indicated template PARM.  Returns the converted ARG, or
4913    error_mark_node if the conversion was unsuccessful.  Error and
4914    warning messages are issued under control of COMPLAIN.  This
4915    conversion is for the Ith parameter in the parameter list.  ARGS is
4916    the full set of template arguments deduced so far.  */
4917
4918 static tree
4919 convert_template_argument (tree parm,
4920                            tree arg,
4921                            tree args,
4922                            tsubst_flags_t complain,
4923                            int i,
4924                            tree in_decl)
4925 {
4926   tree orig_arg;
4927   tree val;
4928   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
4929
4930   if (TREE_CODE (arg) == TREE_LIST
4931       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
4932     {
4933       /* The template argument was the name of some
4934          member function.  That's usually
4935          invalid, but static members are OK.  In any
4936          case, grab the underlying fields/functions
4937          and issue an error later if required.  */
4938       orig_arg = TREE_VALUE (arg);
4939       TREE_TYPE (arg) = unknown_type_node;
4940     }
4941
4942   orig_arg = arg;
4943
4944   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
4945   requires_type = (TREE_CODE (parm) == TYPE_DECL
4946                    || requires_tmpl_type);
4947
4948   /* When determining whether an argument pack expansion is a template,
4949      look at the pattern.  */
4950   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
4951     arg = PACK_EXPANSION_PATTERN (arg);
4952
4953   is_tmpl_type = 
4954     ((TREE_CODE (arg) == TEMPLATE_DECL
4955       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
4956      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
4957      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
4958
4959   if (is_tmpl_type
4960       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
4961           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
4962     arg = TYPE_STUB_DECL (arg);
4963
4964   is_type = TYPE_P (arg) || is_tmpl_type;
4965
4966   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
4967       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
4968     {
4969       permerror (input_location, "to refer to a type member of a template parameter, "
4970                  "use %<typename %E%>", orig_arg);
4971
4972       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
4973                                      TREE_OPERAND (arg, 1),
4974                                      typename_type,
4975                                      complain & tf_error);
4976       arg = orig_arg;
4977       is_type = 1;
4978     }
4979   if (is_type != requires_type)
4980     {
4981       if (in_decl)
4982         {
4983           if (complain & tf_error)
4984             {
4985               error ("type/value mismatch at argument %d in template "
4986                      "parameter list for %qD",
4987                      i + 1, in_decl);
4988               if (is_type)
4989                 error ("  expected a constant of type %qT, got %qT",
4990                        TREE_TYPE (parm),
4991                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
4992               else if (requires_tmpl_type)
4993                 error ("  expected a class template, got %qE", orig_arg);
4994               else
4995                 error ("  expected a type, got %qE", orig_arg);
4996             }
4997         }
4998       return error_mark_node;
4999     }
5000   if (is_tmpl_type ^ requires_tmpl_type)
5001     {
5002       if (in_decl && (complain & tf_error))
5003         {
5004           error ("type/value mismatch at argument %d in template "
5005                  "parameter list for %qD",
5006                  i + 1, in_decl);
5007           if (is_tmpl_type)
5008             error ("  expected a type, got %qT", DECL_NAME (arg));
5009           else
5010             error ("  expected a class template, got %qT", orig_arg);
5011         }
5012       return error_mark_node;
5013     }
5014
5015   if (is_type)
5016     {
5017       if (requires_tmpl_type)
5018         {
5019           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
5020             /* The number of argument required is not known yet.
5021                Just accept it for now.  */
5022             val = TREE_TYPE (arg);
5023           else
5024             {
5025               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5026               tree argparm;
5027
5028               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5029
5030               if (coerce_template_template_parms (parmparm, argparm,
5031                                                   complain, in_decl,
5032                                                   args))
5033                 {
5034                   val = orig_arg;
5035
5036                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
5037                      TEMPLATE_DECL.  */
5038                   if (val != error_mark_node)
5039                     {
5040                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
5041                         val = TREE_TYPE (val);
5042                       else if (TREE_CODE (val) == TYPE_PACK_EXPANSION
5043                                && DECL_TEMPLATE_TEMPLATE_PARM_P (arg))
5044                         {
5045                           val = TREE_TYPE (arg);
5046                           val = make_pack_expansion (val);
5047                         }
5048                     }
5049                 }
5050               else
5051                 {
5052                   if (in_decl && (complain & tf_error))
5053                     {
5054                       error ("type/value mismatch at argument %d in "
5055                              "template parameter list for %qD",
5056                              i + 1, in_decl);
5057                       error ("  expected a template of type %qD, got %qD",
5058                              parm, orig_arg);
5059                     }
5060
5061                   val = error_mark_node;
5062                 }
5063             }
5064         }
5065       else
5066         val = orig_arg;
5067       /* We only form one instance of each template specialization.
5068          Therefore, if we use a non-canonical variant (i.e., a
5069          typedef), any future messages referring to the type will use
5070          the typedef, which is confusing if those future uses do not
5071          themselves also use the typedef.  */
5072       if (TYPE_P (val))
5073         val = canonical_type_variant (val);
5074     }
5075   else
5076     {
5077       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
5078
5079       if (invalid_nontype_parm_type_p (t, complain))
5080         return error_mark_node;
5081
5082       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
5083         {
5084           if (same_type_p (t, TREE_TYPE (orig_arg)))
5085             val = orig_arg;
5086           else
5087             {
5088               /* Not sure if this is reachable, but it doesn't hurt
5089                  to be robust.  */
5090               error ("type mismatch in nontype parameter pack");
5091               val = error_mark_node;
5092             }
5093         }
5094       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
5095         /* We used to call digest_init here.  However, digest_init
5096            will report errors, which we don't want when complain
5097            is zero.  More importantly, digest_init will try too
5098            hard to convert things: for example, `0' should not be
5099            converted to pointer type at this point according to
5100            the standard.  Accepting this is not merely an
5101            extension, since deciding whether or not these
5102            conversions can occur is part of determining which
5103            function template to call, or whether a given explicit
5104            argument specification is valid.  */
5105         val = convert_nontype_argument (t, orig_arg);
5106       else
5107         val = orig_arg;
5108
5109       if (val == NULL_TREE)
5110         val = error_mark_node;
5111       else if (val == error_mark_node && (complain & tf_error))
5112         error ("could not convert template argument %qE to %qT",  orig_arg, t);
5113     }
5114
5115   return val;
5116 }
5117
5118 /* Coerces the remaining template arguments in INNER_ARGS (from
5119    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
5120    Returns the coerced argument pack. PARM_IDX is the position of this
5121    parameter in the template parameter list. ARGS is the original
5122    template argument list.  */
5123 static tree
5124 coerce_template_parameter_pack (tree parms,
5125                                 int parm_idx,
5126                                 tree args,
5127                                 tree inner_args,
5128                                 int arg_idx,
5129                                 tree new_args,
5130                                 int* lost,
5131                                 tree in_decl,
5132                                 tsubst_flags_t complain)
5133 {
5134   tree parm = TREE_VEC_ELT (parms, parm_idx);
5135   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5136   tree packed_args;
5137   tree argument_pack;
5138   tree packed_types = NULL_TREE;
5139
5140   if (arg_idx > nargs)
5141     arg_idx = nargs;
5142
5143   packed_args = make_tree_vec (nargs - arg_idx);
5144
5145   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
5146       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
5147     {
5148       /* When the template parameter is a non-type template
5149          parameter pack whose type uses parameter packs, we need
5150          to look at each of the template arguments
5151          separately. Build a vector of the types for these
5152          non-type template parameters in PACKED_TYPES.  */
5153       tree expansion 
5154         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
5155       packed_types = tsubst_pack_expansion (expansion, args,
5156                                             complain, in_decl);
5157
5158       if (packed_types == error_mark_node)
5159         return error_mark_node;
5160
5161       /* Check that we have the right number of arguments.  */
5162       if (arg_idx < nargs
5163           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
5164           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
5165         {
5166           int needed_parms 
5167             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
5168           error ("wrong number of template arguments (%d, should be %d)",
5169                  nargs, needed_parms);
5170           return error_mark_node;
5171         }
5172
5173       /* If we aren't able to check the actual arguments now
5174          (because they haven't been expanded yet), we can at least
5175          verify that all of the types used for the non-type
5176          template parameter pack are, in fact, valid for non-type
5177          template parameters.  */
5178       if (arg_idx < nargs 
5179           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
5180         {
5181           int j, len = TREE_VEC_LENGTH (packed_types);
5182           for (j = 0; j < len; ++j)
5183             {
5184               tree t = TREE_VEC_ELT (packed_types, j);
5185               if (invalid_nontype_parm_type_p (t, complain))
5186                 return error_mark_node;
5187             }
5188         }
5189     }
5190
5191   /* Convert the remaining arguments, which will be a part of the
5192      parameter pack "parm".  */
5193   for (; arg_idx < nargs; ++arg_idx)
5194     {
5195       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
5196       tree actual_parm = TREE_VALUE (parm);
5197
5198       if (packed_types && !PACK_EXPANSION_P (arg))
5199         {
5200           /* When we have a vector of types (corresponding to the
5201              non-type template parameter pack that uses parameter
5202              packs in its type, as mention above), and the
5203              argument is not an expansion (which expands to a
5204              currently unknown number of arguments), clone the
5205              parm and give it the next type in PACKED_TYPES.  */
5206           actual_parm = copy_node (actual_parm);
5207           TREE_TYPE (actual_parm) = 
5208             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
5209         }
5210
5211       if (arg != error_mark_node)
5212         arg = convert_template_argument (actual_parm, 
5213                                          arg, new_args, complain, parm_idx,
5214                                          in_decl);
5215       if (arg == error_mark_node)
5216         (*lost)++;
5217       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
5218     }
5219
5220   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
5221       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
5222     argument_pack = make_node (TYPE_ARGUMENT_PACK);
5223   else
5224     {
5225       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
5226       TREE_TYPE (argument_pack) 
5227         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
5228       TREE_CONSTANT (argument_pack) = 1;
5229     }
5230
5231   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
5232   return argument_pack;
5233 }
5234
5235 /* Convert all template arguments to their appropriate types, and
5236    return a vector containing the innermost resulting template
5237    arguments.  If any error occurs, return error_mark_node. Error and
5238    warning messages are issued under control of COMPLAIN.
5239
5240    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
5241    for arguments not specified in ARGS.  Otherwise, if
5242    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
5243    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
5244    USE_DEFAULT_ARGS is false, then all arguments must be specified in
5245    ARGS.  */
5246
5247 static tree
5248 coerce_template_parms (tree parms,
5249                        tree args,
5250                        tree in_decl,
5251                        tsubst_flags_t complain,
5252                        bool require_all_args,
5253                        bool use_default_args)
5254 {
5255   int nparms, nargs, parm_idx, arg_idx, lost = 0;
5256   tree inner_args;
5257   tree new_args;
5258   tree new_inner_args;
5259   bool saved_skip_evaluation;
5260
5261   /* When used as a boolean value, indicates whether this is a
5262      variadic template parameter list. Since it's an int, we can also
5263      subtract it from nparms to get the number of non-variadic
5264      parameters.  */
5265   int variadic_p = 0;
5266
5267   nparms = TREE_VEC_LENGTH (parms);
5268
5269   /* Determine if there are any parameter packs.  */
5270   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
5271     {
5272       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
5273       if (template_parameter_pack_p (tparm))
5274         ++variadic_p;
5275     }
5276
5277   inner_args = INNERMOST_TEMPLATE_ARGS (args);
5278   /* If there are 0 or 1 parameter packs, we need to expand any argument
5279      packs so that we can deduce a parameter pack from some non-packed args
5280      followed by an argument pack, as in variadic85.C.  If there are more
5281      than that, we need to leave argument packs intact so the arguments are
5282      assigned to the right parameter packs.  This should only happen when
5283      dealing with a nested class inside a partial specialization of a class
5284      template, as in variadic92.C.  */
5285   if (variadic_p <= 1)
5286     inner_args = expand_template_argument_pack (inner_args);
5287
5288   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5289   if ((nargs > nparms && !variadic_p)
5290       || (nargs < nparms - variadic_p
5291           && require_all_args
5292           && (!use_default_args
5293               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
5294                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
5295     {
5296       if (complain & tf_error)
5297         {
5298           const char *or_more = "";
5299           if (variadic_p)
5300             {
5301               or_more = " or more";
5302               --nparms;
5303             }
5304
5305           error ("wrong number of template arguments (%d, should be %d%s)",
5306                  nargs, nparms, or_more);
5307
5308           if (in_decl)
5309             error ("provided for %q+D", in_decl);
5310         }
5311
5312       return error_mark_node;
5313     }
5314
5315   /* We need to evaluate the template arguments, even though this
5316      template-id may be nested within a "sizeof".  */
5317   saved_skip_evaluation = skip_evaluation;
5318   skip_evaluation = false;
5319   new_inner_args = make_tree_vec (nparms);
5320   new_args = add_outermost_template_args (args, new_inner_args);
5321   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
5322     {
5323       tree arg;
5324       tree parm;
5325
5326       /* Get the Ith template parameter.  */
5327       parm = TREE_VEC_ELT (parms, parm_idx);
5328  
5329       if (parm == error_mark_node)
5330       {
5331         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
5332         continue;
5333       }
5334
5335       /* Calculate the next argument.  */
5336       if (arg_idx < nargs)
5337         arg = TREE_VEC_ELT (inner_args, arg_idx);
5338       else
5339         arg = NULL_TREE;
5340
5341       if (template_parameter_pack_p (TREE_VALUE (parm))
5342           && !(arg && ARGUMENT_PACK_P (arg)))
5343         {
5344           /* All remaining arguments will be placed in the
5345              template parameter pack PARM.  */
5346           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
5347                                                 inner_args, arg_idx,
5348                                                 new_args, &lost,
5349                                                 in_decl, complain);
5350
5351           /* Store this argument.  */
5352           if (arg == error_mark_node)
5353             lost++;
5354           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
5355
5356           /* We are done with all of the arguments.  */
5357           arg_idx = nargs;
5358           
5359           continue;
5360         }
5361       else if (arg)
5362         {
5363           if (PACK_EXPANSION_P (arg))
5364             {
5365               if (complain & tf_error)
5366                 {
5367                   /* FIXME this restriction was removed by N2555; see
5368                      bug 35722.  */
5369                   /* If ARG is a pack expansion, but PARM is not a
5370                      template parameter pack (if it were, we would have
5371                      handled it above), we're trying to expand into a
5372                      fixed-length argument list.  */
5373                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5374                     sorry ("cannot expand %<%E%> into a fixed-length "
5375                            "argument list", arg);
5376                   else
5377                     sorry ("cannot expand %<%T%> into a fixed-length "
5378                            "argument list", arg);
5379                 }
5380               return error_mark_node;
5381             }
5382         }
5383       else if (require_all_args)
5384         /* There must be a default arg in this case.  */
5385         arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
5386                                    complain, in_decl);
5387       else
5388         break;
5389
5390       if (arg == error_mark_node)
5391         {
5392           if (complain & tf_error)
5393             error ("template argument %d is invalid", arg_idx + 1);
5394         }
5395       else if (!arg)
5396         /* This only occurs if there was an error in the template
5397            parameter list itself (which we would already have
5398            reported) that we are trying to recover from, e.g., a class
5399            template with a parameter list such as
5400            template<typename..., typename>.  */
5401         return error_mark_node;
5402       else
5403         arg = convert_template_argument (TREE_VALUE (parm),
5404                                          arg, new_args, complain, 
5405                                          parm_idx, in_decl);
5406
5407       if (arg == error_mark_node)
5408         lost++;
5409       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
5410     }
5411   skip_evaluation = saved_skip_evaluation;
5412
5413   if (lost)
5414     return error_mark_node;
5415
5416   return new_inner_args;
5417 }
5418
5419 /* Returns 1 if template args OT and NT are equivalent.  */
5420
5421 static int
5422 template_args_equal (tree ot, tree nt)
5423 {
5424   if (nt == ot)
5425     return 1;
5426
5427   if (TREE_CODE (nt) == TREE_VEC)
5428     /* For member templates */
5429     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
5430   else if (PACK_EXPANSION_P (ot))
5431     return PACK_EXPANSION_P (nt) 
5432       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
5433                               PACK_EXPANSION_PATTERN (nt));
5434   else if (ARGUMENT_PACK_P (ot))
5435     {
5436       int i, len;
5437       tree opack, npack;
5438
5439       if (!ARGUMENT_PACK_P (nt))
5440         return 0;
5441
5442       opack = ARGUMENT_PACK_ARGS (ot);
5443       npack = ARGUMENT_PACK_ARGS (nt);
5444       len = TREE_VEC_LENGTH (opack);
5445       if (TREE_VEC_LENGTH (npack) != len)
5446         return 0;
5447       for (i = 0; i < len; ++i)
5448         if (!template_args_equal (TREE_VEC_ELT (opack, i),
5449                                   TREE_VEC_ELT (npack, i)))
5450           return 0;
5451       return 1;
5452     }
5453   else if (TYPE_P (nt))
5454     return TYPE_P (ot) && same_type_p (ot, nt);
5455   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
5456     return 0;
5457   else
5458     return cp_tree_equal (ot, nt);
5459 }
5460
5461 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
5462    of template arguments.  Returns 0 otherwise.  */
5463
5464 int
5465 comp_template_args (tree oldargs, tree newargs)
5466 {
5467   int i;
5468
5469   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
5470     return 0;
5471
5472   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
5473     {
5474       tree nt = TREE_VEC_ELT (newargs, i);
5475       tree ot = TREE_VEC_ELT (oldargs, i);
5476
5477       if (! template_args_equal (ot, nt))
5478         return 0;
5479     }
5480   return 1;
5481 }
5482
5483 static void
5484 add_pending_template (tree d)
5485 {
5486   tree ti = (TYPE_P (d)
5487              ? CLASSTYPE_TEMPLATE_INFO (d)
5488              : DECL_TEMPLATE_INFO (d));
5489   struct pending_template *pt;
5490   int level;
5491
5492   if (TI_PENDING_TEMPLATE_FLAG (ti))
5493     return;
5494
5495   /* We are called both from instantiate_decl, where we've already had a
5496      tinst_level pushed, and instantiate_template, where we haven't.
5497      Compensate.  */
5498   level = !current_tinst_level || current_tinst_level->decl != d;
5499
5500   if (level)
5501     push_tinst_level (d);
5502
5503   pt = GGC_NEW (struct pending_template);
5504   pt->next = NULL;
5505   pt->tinst = current_tinst_level;
5506   if (last_pending_template)
5507     last_pending_template->next = pt;
5508   else
5509     pending_templates = pt;
5510
5511   last_pending_template = pt;
5512
5513   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
5514
5515   if (level)
5516     pop_tinst_level ();
5517 }
5518
5519
5520 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
5521    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
5522    documentation for TEMPLATE_ID_EXPR.  */
5523
5524 tree
5525 lookup_template_function (tree fns, tree arglist)
5526 {
5527   tree type;
5528
5529   if (fns == error_mark_node || arglist == error_mark_node)
5530     return error_mark_node;
5531
5532   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
5533   gcc_assert (fns && (is_overloaded_fn (fns)
5534                       || TREE_CODE (fns) == IDENTIFIER_NODE));
5535
5536   if (BASELINK_P (fns))
5537     {
5538       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
5539                                          unknown_type_node,
5540                                          BASELINK_FUNCTIONS (fns),
5541                                          arglist);
5542       return fns;
5543     }
5544
5545   type = TREE_TYPE (fns);
5546   if (TREE_CODE (fns) == OVERLOAD || !type)
5547     type = unknown_type_node;
5548
5549   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
5550 }
5551
5552 /* Within the scope of a template class S<T>, the name S gets bound
5553    (in build_self_reference) to a TYPE_DECL for the class, not a
5554    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
5555    or one of its enclosing classes, and that type is a template,
5556    return the associated TEMPLATE_DECL.  Otherwise, the original
5557    DECL is returned.  */
5558
5559 tree
5560 maybe_get_template_decl_from_type_decl (tree decl)
5561 {
5562   return (decl != NULL_TREE
5563           && TREE_CODE (decl) == TYPE_DECL
5564           && DECL_ARTIFICIAL (decl)
5565           && CLASS_TYPE_P (TREE_TYPE (decl))
5566           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
5567     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
5568 }
5569
5570 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
5571    parameters, find the desired type.
5572
5573    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
5574
5575    IN_DECL, if non-NULL, is the template declaration we are trying to
5576    instantiate.
5577
5578    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
5579    the class we are looking up.
5580
5581    Issue error and warning messages under control of COMPLAIN.
5582
5583    If the template class is really a local class in a template
5584    function, then the FUNCTION_CONTEXT is the function in which it is
5585    being instantiated.
5586
5587    ??? Note that this function is currently called *twice* for each
5588    template-id: the first time from the parser, while creating the
5589    incomplete type (finish_template_type), and the second type during the
5590    real instantiation (instantiate_template_class). This is surely something
5591    that we want to avoid. It also causes some problems with argument
5592    coercion (see convert_nontype_argument for more information on this).  */
5593
5594 tree
5595 lookup_template_class (tree d1,
5596                        tree arglist,
5597                        tree in_decl,
5598                        tree context,
5599                        int entering_scope,
5600                        tsubst_flags_t complain)
5601 {
5602   tree templ = NULL_TREE, parmlist;
5603   tree t;
5604
5605   timevar_push (TV_NAME_LOOKUP);
5606
5607   if (TREE_CODE (d1) == IDENTIFIER_NODE)
5608     {
5609       tree value = innermost_non_namespace_value (d1);
5610       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
5611         templ = value;
5612       else
5613         {
5614           if (context)
5615             push_decl_namespace (context);
5616           templ = lookup_name (d1);
5617           templ = maybe_get_template_decl_from_type_decl (templ);
5618           if (context)
5619             pop_decl_namespace ();
5620         }
5621       if (templ)
5622         context = DECL_CONTEXT (templ);
5623     }
5624   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
5625     {
5626       tree type = TREE_TYPE (d1);
5627
5628       /* If we are declaring a constructor, say A<T>::A<T>, we will get
5629          an implicit typename for the second A.  Deal with it.  */
5630       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
5631         type = TREE_TYPE (type);
5632
5633       if (CLASSTYPE_TEMPLATE_INFO (type))
5634         {
5635           templ = CLASSTYPE_TI_TEMPLATE (type);
5636           d1 = DECL_NAME (templ);
5637         }
5638     }
5639   else if (TREE_CODE (d1) == ENUMERAL_TYPE
5640            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
5641     {
5642       templ = TYPE_TI_TEMPLATE (d1);
5643       d1 = DECL_NAME (templ);
5644     }
5645   else if (TREE_CODE (d1) == TEMPLATE_DECL
5646            && DECL_TEMPLATE_RESULT (d1)
5647            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
5648     {
5649       templ = d1;
5650       d1 = DECL_NAME (templ);
5651       context = DECL_CONTEXT (templ);
5652     }
5653
5654   /* Issue an error message if we didn't find a template.  */
5655   if (! templ)
5656     {
5657       if (complain & tf_error)
5658         error ("%qT is not a template", d1);
5659       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5660     }
5661
5662   if (TREE_CODE (templ) != TEMPLATE_DECL
5663          /* Make sure it's a user visible template, if it was named by
5664             the user.  */
5665       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
5666           && !PRIMARY_TEMPLATE_P (templ)))
5667     {
5668       if (complain & tf_error)
5669         {
5670           error ("non-template type %qT used as a template", d1);
5671           if (in_decl)
5672             error ("for template declaration %q+D", in_decl);
5673         }
5674       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5675     }
5676
5677   complain &= ~tf_user;
5678
5679   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
5680     {
5681       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
5682          template arguments */
5683
5684       tree parm;
5685       tree arglist2;
5686       tree outer;
5687
5688       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
5689
5690       /* Consider an example where a template template parameter declared as
5691
5692            template <class T, class U = std::allocator<T> > class TT
5693
5694          The template parameter level of T and U are one level larger than
5695          of TT.  To proper process the default argument of U, say when an
5696          instantiation `TT<int>' is seen, we need to build the full
5697          arguments containing {int} as the innermost level.  Outer levels,
5698          available when not appearing as default template argument, can be
5699          obtained from the arguments of the enclosing template.
5700
5701          Suppose that TT is later substituted with std::vector.  The above
5702          instantiation is `TT<int, std::allocator<T> >' with TT at
5703          level 1, and T at level 2, while the template arguments at level 1
5704          becomes {std::vector} and the inner level 2 is {int}.  */
5705
5706       outer = DECL_CONTEXT (templ);
5707       if (outer)
5708         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
5709       else if (current_template_parms)
5710         /* This is an argument of the current template, so we haven't set
5711            DECL_CONTEXT yet.  */
5712         outer = current_template_args ();
5713
5714       if (outer)
5715         arglist = add_to_template_args (outer, arglist);
5716
5717       arglist2 = coerce_template_parms (parmlist, arglist, templ,
5718                                         complain,
5719                                         /*require_all_args=*/true,
5720                                         /*use_default_args=*/true);
5721       if (arglist2 == error_mark_node
5722           || (!uses_template_parms (arglist2)
5723               && check_instantiated_args (templ, arglist2, complain)))
5724         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5725
5726       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
5727       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
5728     }
5729   else
5730     {
5731       tree template_type = TREE_TYPE (templ);
5732       tree gen_tmpl;
5733       tree type_decl;
5734       tree found = NULL_TREE;
5735       int arg_depth;
5736       int parm_depth;
5737       int is_partial_instantiation;
5738
5739       gen_tmpl = most_general_template (templ);
5740       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
5741       parm_depth = TMPL_PARMS_DEPTH (parmlist);
5742       arg_depth = TMPL_ARGS_DEPTH (arglist);
5743
5744       if (arg_depth == 1 && parm_depth > 1)
5745         {
5746           /* We've been given an incomplete set of template arguments.
5747              For example, given:
5748
5749                template <class T> struct S1 {
5750                  template <class U> struct S2 {};
5751                  template <class U> struct S2<U*> {};
5752                 };
5753
5754              we will be called with an ARGLIST of `U*', but the
5755              TEMPLATE will be `template <class T> template
5756              <class U> struct S1<T>::S2'.  We must fill in the missing
5757              arguments.  */
5758           arglist
5759             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
5760                                            arglist);
5761           arg_depth = TMPL_ARGS_DEPTH (arglist);
5762         }
5763
5764       /* Now we should have enough arguments.  */
5765       gcc_assert (parm_depth == arg_depth);
5766
5767       /* From here on, we're only interested in the most general
5768          template.  */
5769       templ = gen_tmpl;
5770
5771       /* Calculate the BOUND_ARGS.  These will be the args that are
5772          actually tsubst'd into the definition to create the
5773          instantiation.  */
5774       if (parm_depth > 1)
5775         {
5776           /* We have multiple levels of arguments to coerce, at once.  */
5777           int i;
5778           int saved_depth = TMPL_ARGS_DEPTH (arglist);
5779
5780           tree bound_args = make_tree_vec (parm_depth);
5781
5782           for (i = saved_depth,
5783                  t = DECL_TEMPLATE_PARMS (templ);
5784                i > 0 && t != NULL_TREE;
5785                --i, t = TREE_CHAIN (t))
5786             {
5787               tree a = coerce_template_parms (TREE_VALUE (t),
5788                                               arglist, templ,
5789                                               complain,
5790                                               /*require_all_args=*/true,
5791                                               /*use_default_args=*/true);
5792
5793               /* Don't process further if one of the levels fails.  */
5794               if (a == error_mark_node)
5795                 {
5796                   /* Restore the ARGLIST to its full size.  */
5797                   TREE_VEC_LENGTH (arglist) = saved_depth;
5798                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5799                 }
5800
5801               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
5802
5803               /* We temporarily reduce the length of the ARGLIST so
5804                  that coerce_template_parms will see only the arguments
5805                  corresponding to the template parameters it is
5806                  examining.  */
5807               TREE_VEC_LENGTH (arglist)--;
5808             }
5809
5810           /* Restore the ARGLIST to its full size.  */
5811           TREE_VEC_LENGTH (arglist) = saved_depth;
5812
5813           arglist = bound_args;
5814         }
5815       else
5816         arglist
5817           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
5818                                    INNERMOST_TEMPLATE_ARGS (arglist),
5819                                    templ,
5820                                    complain,
5821                                    /*require_all_args=*/true,
5822                                    /*use_default_args=*/true);
5823
5824       if (arglist == error_mark_node)
5825         /* We were unable to bind the arguments.  */
5826         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5827
5828       /* In the scope of a template class, explicit references to the
5829          template class refer to the type of the template, not any
5830          instantiation of it.  For example, in:
5831
5832            template <class T> class C { void f(C<T>); }
5833
5834          the `C<T>' is just the same as `C'.  Outside of the
5835          class, however, such a reference is an instantiation.  */
5836       if (comp_template_args (TYPE_TI_ARGS (template_type),
5837                               arglist))
5838         {
5839           found = template_type;
5840
5841           if (!entering_scope && PRIMARY_TEMPLATE_P (templ))
5842             {
5843               tree ctx;
5844
5845               for (ctx = current_class_type;
5846                    ctx && TREE_CODE (ctx) != NAMESPACE_DECL;
5847                    ctx = (TYPE_P (ctx)
5848                           ? TYPE_CONTEXT (ctx)
5849                           : DECL_CONTEXT (ctx)))
5850                 if (TYPE_P (ctx) && same_type_p (ctx, template_type))
5851                   goto found_ctx;
5852
5853               /* We're not in the scope of the class, so the
5854                  TEMPLATE_TYPE is not the type we want after all.  */
5855               found = NULL_TREE;
5856             found_ctx:;
5857             }
5858         }
5859       if (found)
5860         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5861
5862       /* If we already have this specialization, return it.  */
5863       found = retrieve_specialization (templ, arglist,
5864                                        /*class_specializations_p=*/false);
5865       if (found)
5866         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5867
5868       /* This type is a "partial instantiation" if any of the template
5869          arguments still involve template parameters.  Note that we set
5870          IS_PARTIAL_INSTANTIATION for partial specializations as
5871          well.  */
5872       is_partial_instantiation = uses_template_parms (arglist);
5873
5874       /* If the deduced arguments are invalid, then the binding
5875          failed.  */
5876       if (!is_partial_instantiation
5877           && check_instantiated_args (templ,
5878                                       INNERMOST_TEMPLATE_ARGS (arglist),
5879                                       complain))
5880         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
5881
5882       if (!is_partial_instantiation
5883           && !PRIMARY_TEMPLATE_P (templ)
5884           && TREE_CODE (CP_DECL_CONTEXT (templ)) == NAMESPACE_DECL)
5885         {
5886           found = xref_tag_from_type (TREE_TYPE (templ),
5887                                       DECL_NAME (templ),
5888                                       /*tag_scope=*/ts_global);
5889           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
5890         }
5891
5892       context = tsubst (DECL_CONTEXT (templ), arglist,
5893                         complain, in_decl);
5894       if (!context)
5895         context = global_namespace;
5896
5897       /* Create the type.  */
5898       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
5899         {
5900           if (!is_partial_instantiation)
5901             {
5902               set_current_access_from_decl (TYPE_NAME (template_type));
5903               t = start_enum (TYPE_IDENTIFIER (template_type),
5904                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
5905                                       arglist, complain, in_decl),
5906                               SCOPED_ENUM_P (template_type));
5907             }
5908           else
5909             {
5910               /* We don't want to call start_enum for this type, since
5911                  the values for the enumeration constants may involve
5912                  template parameters.  And, no one should be interested
5913                  in the enumeration constants for such a type.  */
5914               t = make_node (ENUMERAL_TYPE);
5915               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
5916             }
5917         }
5918       else
5919         {
5920           t = make_class_type (TREE_CODE (template_type));
5921           CLASSTYPE_DECLARED_CLASS (t)
5922             = CLASSTYPE_DECLARED_CLASS (template_type);
5923           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
5924           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
5925
5926           /* A local class.  Make sure the decl gets registered properly.  */
5927           if (context == current_function_decl)
5928             pushtag (DECL_NAME (templ), t, /*tag_scope=*/ts_current);
5929
5930           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
5931             /* This instantiation is another name for the primary
5932                template type. Set the TYPE_CANONICAL field
5933                appropriately. */
5934             TYPE_CANONICAL (t) = template_type;
5935           else if (any_template_arguments_need_structural_equality_p (arglist))
5936             /* Some of the template arguments require structural
5937                equality testing, so this template class requires
5938                structural equality testing. */
5939             SET_TYPE_STRUCTURAL_EQUALITY (t);
5940         }
5941
5942       /* If we called start_enum or pushtag above, this information
5943          will already be set up.  */
5944       if (!TYPE_NAME (t))
5945         {
5946           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
5947
5948           type_decl = create_implicit_typedef (DECL_NAME (templ), t);
5949           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
5950           TYPE_STUB_DECL (t) = type_decl;
5951           DECL_SOURCE_LOCATION (type_decl)
5952             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
5953         }
5954       else
5955         type_decl = TYPE_NAME (t);
5956
5957       TREE_PRIVATE (type_decl)
5958         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
5959       TREE_PROTECTED (type_decl)
5960         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
5961       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
5962         {
5963           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
5964           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
5965         }
5966
5967       /* Set up the template information.  We have to figure out which
5968          template is the immediate parent if this is a full
5969          instantiation.  */
5970       if (parm_depth == 1 || is_partial_instantiation
5971           || !PRIMARY_TEMPLATE_P (templ))
5972         /* This case is easy; there are no member templates involved.  */
5973         found = templ;
5974       else
5975         {
5976           /* This is a full instantiation of a member template.  Look
5977              for a partial instantiation of which this is an instance.  */
5978
5979           for (found = DECL_TEMPLATE_INSTANTIATIONS (templ);
5980                found; found = TREE_CHAIN (found))
5981             {
5982               int success;
5983               tree tmpl = CLASSTYPE_TI_TEMPLATE (TREE_VALUE (found));
5984
5985               /* We only want partial instantiations, here, not
5986                  specializations or full instantiations.  */
5987               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_VALUE (found))
5988                   || !uses_template_parms (TREE_VALUE (found)))
5989                 continue;
5990
5991               /* Temporarily reduce by one the number of levels in the
5992                  ARGLIST and in FOUND so as to avoid comparing the
5993                  last set of arguments.  */
5994               TREE_VEC_LENGTH (arglist)--;
5995               TREE_VEC_LENGTH (TREE_PURPOSE (found)) --;
5996
5997               /* See if the arguments match.  If they do, then TMPL is
5998                  the partial instantiation we want.  */
5999               success = comp_template_args (TREE_PURPOSE (found), arglist);
6000
6001               /* Restore the argument vectors to their full size.  */
6002               TREE_VEC_LENGTH (arglist)++;
6003               TREE_VEC_LENGTH (TREE_PURPOSE (found))++;
6004
6005               if (success)
6006                 {
6007                   found = tmpl;
6008                   break;
6009                 }
6010             }
6011
6012           if (!found)
6013             {
6014               /* There was no partial instantiation. This happens
6015                  where C<T> is a member template of A<T> and it's used
6016                  in something like
6017
6018                   template <typename T> struct B { A<T>::C<int> m; };
6019                   B<float>;
6020
6021                  Create the partial instantiation.
6022                */
6023               TREE_VEC_LENGTH (arglist)--;
6024               found = tsubst (templ, arglist, complain, NULL_TREE);
6025               TREE_VEC_LENGTH (arglist)++;
6026             }
6027         }
6028
6029       SET_TYPE_TEMPLATE_INFO (t, tree_cons (found, arglist, NULL_TREE));
6030       DECL_TEMPLATE_INSTANTIATIONS (templ)
6031         = tree_cons (arglist, t,
6032                      DECL_TEMPLATE_INSTANTIATIONS (templ));
6033
6034       if (TREE_CODE (t) == ENUMERAL_TYPE
6035           && !is_partial_instantiation)
6036         /* Now that the type has been registered on the instantiations
6037            list, we set up the enumerators.  Because the enumeration
6038            constants may involve the enumeration type itself, we make
6039            sure to register the type first, and then create the
6040            constants.  That way, doing tsubst_expr for the enumeration
6041            constants won't result in recursive calls here; we'll find
6042            the instantiation and exit above.  */
6043         tsubst_enum (template_type, t, arglist);
6044
6045       if (is_partial_instantiation)
6046         /* If the type makes use of template parameters, the
6047            code that generates debugging information will crash.  */
6048         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
6049
6050       /* Possibly limit visibility based on template args.  */
6051       TREE_PUBLIC (type_decl) = 1;
6052       determine_visibility (type_decl);
6053
6054       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
6055     }
6056   timevar_pop (TV_NAME_LOOKUP);
6057 }
6058 \f
6059 struct pair_fn_data
6060 {
6061   tree_fn_t fn;
6062   void *data;
6063   /* True when we should also visit template parameters that occur in
6064      non-deduced contexts.  */
6065   bool include_nondeduced_p;
6066   struct pointer_set_t *visited;
6067 };
6068
6069 /* Called from for_each_template_parm via walk_tree.  */
6070
6071 static tree
6072 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
6073 {
6074   tree t = *tp;
6075   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
6076   tree_fn_t fn = pfd->fn;
6077   void *data = pfd->data;
6078
6079   if (TYPE_P (t)
6080       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
6081       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
6082                                  pfd->include_nondeduced_p))
6083     return error_mark_node;
6084
6085   switch (TREE_CODE (t))
6086     {
6087     case RECORD_TYPE:
6088       if (TYPE_PTRMEMFUNC_P (t))
6089         break;
6090       /* Fall through.  */
6091
6092     case UNION_TYPE:
6093     case ENUMERAL_TYPE:
6094       if (!TYPE_TEMPLATE_INFO (t))
6095         *walk_subtrees = 0;
6096       else if (for_each_template_parm (TREE_VALUE (TYPE_TEMPLATE_INFO (t)),
6097                                        fn, data, pfd->visited, 
6098                                        pfd->include_nondeduced_p))
6099         return error_mark_node;
6100       break;
6101
6102     case INTEGER_TYPE:
6103       if (for_each_template_parm (TYPE_MIN_VALUE (t),
6104                                   fn, data, pfd->visited, 
6105                                   pfd->include_nondeduced_p)
6106           || for_each_template_parm (TYPE_MAX_VALUE (t),
6107                                      fn, data, pfd->visited,
6108                                      pfd->include_nondeduced_p))
6109         return error_mark_node;
6110       break;
6111
6112     case METHOD_TYPE:
6113       /* Since we're not going to walk subtrees, we have to do this
6114          explicitly here.  */
6115       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
6116                                   pfd->visited, pfd->include_nondeduced_p))
6117         return error_mark_node;
6118       /* Fall through.  */
6119
6120     case FUNCTION_TYPE:
6121       /* Check the return type.  */
6122       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6123                                   pfd->include_nondeduced_p))
6124         return error_mark_node;
6125
6126       /* Check the parameter types.  Since default arguments are not
6127          instantiated until they are needed, the TYPE_ARG_TYPES may
6128          contain expressions that involve template parameters.  But,
6129          no-one should be looking at them yet.  And, once they're
6130          instantiated, they don't contain template parameters, so
6131          there's no point in looking at them then, either.  */
6132       {
6133         tree parm;
6134
6135         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
6136           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
6137                                       pfd->visited, pfd->include_nondeduced_p))
6138             return error_mark_node;
6139
6140         /* Since we've already handled the TYPE_ARG_TYPES, we don't
6141            want walk_tree walking into them itself.  */
6142         *walk_subtrees = 0;
6143       }
6144       break;
6145
6146     case TYPEOF_TYPE:
6147       if (pfd->include_nondeduced_p
6148           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
6149                                      pfd->visited, 
6150                                      pfd->include_nondeduced_p))
6151         return error_mark_node;
6152       break;
6153
6154     case FUNCTION_DECL:
6155     case VAR_DECL:
6156       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
6157           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
6158                                      pfd->visited, pfd->include_nondeduced_p))
6159         return error_mark_node;
6160       /* Fall through.  */
6161
6162     case PARM_DECL:
6163     case CONST_DECL:
6164       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
6165           && for_each_template_parm (DECL_INITIAL (t), fn, data,
6166                                      pfd->visited, pfd->include_nondeduced_p))
6167         return error_mark_node;
6168       if (DECL_CONTEXT (t)
6169           && pfd->include_nondeduced_p
6170           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
6171                                      pfd->visited, pfd->include_nondeduced_p))
6172         return error_mark_node;
6173       break;
6174
6175     case BOUND_TEMPLATE_TEMPLATE_PARM:
6176       /* Record template parameters such as `T' inside `TT<T>'.  */
6177       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
6178                                   pfd->include_nondeduced_p))
6179         return error_mark_node;
6180       /* Fall through.  */
6181
6182     case TEMPLATE_TEMPLATE_PARM:
6183     case TEMPLATE_TYPE_PARM:
6184     case TEMPLATE_PARM_INDEX:
6185       if (fn && (*fn)(t, data))
6186         return error_mark_node;
6187       else if (!fn)
6188         return error_mark_node;
6189       break;
6190
6191     case TEMPLATE_DECL:
6192       /* A template template parameter is encountered.  */
6193       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
6194           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6195                                      pfd->include_nondeduced_p))
6196         return error_mark_node;
6197
6198       /* Already substituted template template parameter */
6199       *walk_subtrees = 0;
6200       break;
6201
6202     case TYPENAME_TYPE:
6203       if (!fn
6204           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
6205                                      data, pfd->visited, 
6206                                      pfd->include_nondeduced_p))
6207         return error_mark_node;
6208       break;
6209
6210     case CONSTRUCTOR:
6211       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
6212           && pfd->include_nondeduced_p
6213           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
6214                                      (TREE_TYPE (t)), fn, data,
6215                                      pfd->visited, pfd->include_nondeduced_p))
6216         return error_mark_node;
6217       break;
6218
6219     case INDIRECT_REF:
6220     case COMPONENT_REF:
6221       /* If there's no type, then this thing must be some expression
6222          involving template parameters.  */
6223       if (!fn && !TREE_TYPE (t))
6224         return error_mark_node;
6225       break;
6226
6227     case MODOP_EXPR:
6228     case CAST_EXPR:
6229     case REINTERPRET_CAST_EXPR:
6230     case CONST_CAST_EXPR:
6231     case STATIC_CAST_EXPR:
6232     case DYNAMIC_CAST_EXPR:
6233     case ARROW_EXPR:
6234     case DOTSTAR_EXPR:
6235     case TYPEID_EXPR:
6236     case PSEUDO_DTOR_EXPR:
6237       if (!fn)
6238         return error_mark_node;
6239       break;
6240
6241     default:
6242       break;
6243     }
6244
6245   /* We didn't find any template parameters we liked.  */
6246   return NULL_TREE;
6247 }
6248
6249 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
6250    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
6251    call FN with the parameter and the DATA.
6252    If FN returns nonzero, the iteration is terminated, and
6253    for_each_template_parm returns 1.  Otherwise, the iteration
6254    continues.  If FN never returns a nonzero value, the value
6255    returned by for_each_template_parm is 0.  If FN is NULL, it is
6256    considered to be the function which always returns 1.
6257
6258    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
6259    parameters that occur in non-deduced contexts.  When false, only
6260    visits those template parameters that can be deduced.  */
6261
6262 static int
6263 for_each_template_parm (tree t, tree_fn_t fn, void* data,
6264                         struct pointer_set_t *visited,
6265                         bool include_nondeduced_p)
6266 {
6267   struct pair_fn_data pfd;
6268   int result;
6269
6270   /* Set up.  */
6271   pfd.fn = fn;
6272   pfd.data = data;
6273   pfd.include_nondeduced_p = include_nondeduced_p;
6274
6275   /* Walk the tree.  (Conceptually, we would like to walk without
6276      duplicates, but for_each_template_parm_r recursively calls
6277      for_each_template_parm, so we would need to reorganize a fair
6278      bit to use walk_tree_without_duplicates, so we keep our own
6279      visited list.)  */
6280   if (visited)
6281     pfd.visited = visited;
6282   else
6283     pfd.visited = pointer_set_create ();
6284   result = cp_walk_tree (&t,
6285                          for_each_template_parm_r,
6286                          &pfd,
6287                          pfd.visited) != NULL_TREE;
6288
6289   /* Clean up.  */
6290   if (!visited)
6291     {
6292       pointer_set_destroy (pfd.visited);
6293       pfd.visited = 0;
6294     }
6295
6296   return result;
6297 }
6298
6299 /* Returns true if T depends on any template parameter.  */
6300
6301 int
6302 uses_template_parms (tree t)
6303 {
6304   bool dependent_p;
6305   int saved_processing_template_decl;
6306
6307   saved_processing_template_decl = processing_template_decl;
6308   if (!saved_processing_template_decl)
6309     processing_template_decl = 1;
6310   if (TYPE_P (t))
6311     dependent_p = dependent_type_p (t);
6312   else if (TREE_CODE (t) == TREE_VEC)
6313     dependent_p = any_dependent_template_arguments_p (t);
6314   else if (TREE_CODE (t) == TREE_LIST)
6315     dependent_p = (uses_template_parms (TREE_VALUE (t))
6316                    || uses_template_parms (TREE_CHAIN (t)));
6317   else if (TREE_CODE (t) == TYPE_DECL)
6318     dependent_p = dependent_type_p (TREE_TYPE (t));
6319   else if (DECL_P (t)
6320            || EXPR_P (t)
6321            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
6322            || TREE_CODE (t) == OVERLOAD
6323            || TREE_CODE (t) == BASELINK
6324            || TREE_CODE (t) == IDENTIFIER_NODE
6325            || TREE_CODE (t) == TRAIT_EXPR
6326            || CONSTANT_CLASS_P (t))
6327     dependent_p = (type_dependent_expression_p (t)
6328                    || value_dependent_expression_p (t));
6329   else
6330     {
6331       gcc_assert (t == error_mark_node);
6332       dependent_p = false;
6333     }
6334
6335   processing_template_decl = saved_processing_template_decl;
6336
6337   return dependent_p;
6338 }
6339
6340 /* Returns true if T depends on any template parameter with level LEVEL.  */
6341
6342 int
6343 uses_template_parms_level (tree t, int level)
6344 {
6345   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
6346                                  /*include_nondeduced_p=*/true);
6347 }
6348
6349 static int tinst_depth;
6350 extern int max_tinst_depth;
6351 #ifdef GATHER_STATISTICS
6352 int depth_reached;
6353 #endif
6354 static int tinst_level_tick;
6355 static int last_template_error_tick;
6356
6357 /* We're starting to instantiate D; record the template instantiation context
6358    for diagnostics and to restore it later.  */
6359
6360 static int
6361 push_tinst_level (tree d)
6362 {
6363   struct tinst_level *new_level;
6364
6365   if (tinst_depth >= max_tinst_depth)
6366     {
6367       /* If the instantiation in question still has unbound template parms,
6368          we don't really care if we can't instantiate it, so just return.
6369          This happens with base instantiation for implicit `typename'.  */
6370       if (uses_template_parms (d))
6371         return 0;
6372
6373       last_template_error_tick = tinst_level_tick;
6374       error ("template instantiation depth exceeds maximum of %d (use "
6375              "-ftemplate-depth-NN to increase the maximum) instantiating %qD",
6376              max_tinst_depth, d);
6377
6378       print_instantiation_context ();
6379
6380       return 0;
6381     }
6382
6383   new_level = GGC_NEW (struct tinst_level);
6384   new_level->decl = d;
6385   new_level->locus = input_location;
6386   new_level->in_system_header_p = in_system_header;
6387   new_level->next = current_tinst_level;
6388   current_tinst_level = new_level;
6389
6390   ++tinst_depth;
6391 #ifdef GATHER_STATISTICS
6392   if (tinst_depth > depth_reached)
6393     depth_reached = tinst_depth;
6394 #endif
6395
6396   ++tinst_level_tick;
6397   return 1;
6398 }
6399
6400 /* We're done instantiating this template; return to the instantiation
6401    context.  */
6402
6403 static void
6404 pop_tinst_level (void)
6405 {
6406   /* Restore the filename and line number stashed away when we started
6407      this instantiation.  */
6408   input_location = current_tinst_level->locus;
6409   current_tinst_level = current_tinst_level->next;
6410   --tinst_depth;
6411   ++tinst_level_tick;
6412 }
6413
6414 /* We're instantiating a deferred template; restore the template
6415    instantiation context in which the instantiation was requested, which
6416    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
6417
6418 static tree
6419 reopen_tinst_level (struct tinst_level *level)
6420 {
6421   struct tinst_level *t;
6422
6423   tinst_depth = 0;
6424   for (t = level; t; t = t->next)
6425     ++tinst_depth;
6426
6427   current_tinst_level = level;
6428   pop_tinst_level ();
6429   return level->decl;
6430 }
6431
6432 /* Returns the TINST_LEVEL which gives the original instantiation
6433    context.  */
6434
6435 struct tinst_level *
6436 outermost_tinst_level (void)
6437 {
6438   struct tinst_level *level = current_tinst_level;
6439   if (level)
6440     while (level->next)
6441       level = level->next;
6442   return level;
6443 }
6444
6445 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
6446
6447 bool
6448 parameter_of_template_p (tree parm, tree templ)
6449 {
6450   tree parms;
6451   int i;
6452
6453   if (!parm || !templ)
6454     return false;
6455
6456   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
6457   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
6458
6459   parms = DECL_TEMPLATE_PARMS (templ);
6460   parms = INNERMOST_TEMPLATE_PARMS (parms);
6461
6462   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
6463     if (parm == TREE_VALUE (TREE_VEC_ELT (parms, i)))
6464       return true;
6465
6466   return false;
6467 }
6468
6469 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
6470    vector of template arguments, as for tsubst.
6471
6472    Returns an appropriate tsubst'd friend declaration.  */
6473
6474 static tree
6475 tsubst_friend_function (tree decl, tree args)
6476 {
6477   tree new_friend;
6478
6479   if (TREE_CODE (decl) == FUNCTION_DECL
6480       && DECL_TEMPLATE_INSTANTIATION (decl)
6481       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
6482     /* This was a friend declared with an explicit template
6483        argument list, e.g.:
6484
6485        friend void f<>(T);
6486
6487        to indicate that f was a template instantiation, not a new
6488        function declaration.  Now, we have to figure out what
6489        instantiation of what template.  */
6490     {
6491       tree template_id, arglist, fns;
6492       tree new_args;
6493       tree tmpl;
6494       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
6495
6496       /* Friend functions are looked up in the containing namespace scope.
6497          We must enter that scope, to avoid finding member functions of the
6498          current class with same name.  */
6499       push_nested_namespace (ns);
6500       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
6501                          tf_warning_or_error, NULL_TREE,
6502                          /*integral_constant_expression_p=*/false);
6503       pop_nested_namespace (ns);
6504       arglist = tsubst (DECL_TI_ARGS (decl), args,
6505                         tf_warning_or_error, NULL_TREE);
6506       template_id = lookup_template_function (fns, arglist);
6507
6508       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6509       tmpl = determine_specialization (template_id, new_friend,
6510                                        &new_args,
6511                                        /*need_member_template=*/0,
6512                                        TREE_VEC_LENGTH (args),
6513                                        tsk_none);
6514       return instantiate_template (tmpl, new_args, tf_error);
6515     }
6516
6517   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6518
6519   /* The NEW_FRIEND will look like an instantiation, to the
6520      compiler, but is not an instantiation from the point of view of
6521      the language.  For example, we might have had:
6522
6523      template <class T> struct S {
6524        template <class U> friend void f(T, U);
6525      };
6526
6527      Then, in S<int>, template <class U> void f(int, U) is not an
6528      instantiation of anything.  */
6529   if (new_friend == error_mark_node)
6530     return error_mark_node;
6531
6532   DECL_USE_TEMPLATE (new_friend) = 0;
6533   if (TREE_CODE (decl) == TEMPLATE_DECL)
6534     {
6535       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
6536       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
6537         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
6538     }
6539
6540   /* The mangled name for the NEW_FRIEND is incorrect.  The function
6541      is not a template instantiation and should not be mangled like
6542      one.  Therefore, we forget the mangling here; we'll recompute it
6543      later if we need it.  */
6544   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
6545     {
6546       SET_DECL_RTL (new_friend, NULL_RTX);
6547       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
6548     }
6549
6550   if (DECL_NAMESPACE_SCOPE_P (new_friend))
6551     {
6552       tree old_decl;
6553       tree new_friend_template_info;
6554       tree new_friend_result_template_info;
6555       tree ns;
6556       int  new_friend_is_defn;
6557
6558       /* We must save some information from NEW_FRIEND before calling
6559          duplicate decls since that function will free NEW_FRIEND if
6560          possible.  */
6561       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
6562       new_friend_is_defn =
6563             (DECL_INITIAL (DECL_TEMPLATE_RESULT
6564                            (template_for_substitution (new_friend)))
6565              != NULL_TREE);
6566       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
6567         {
6568           /* This declaration is a `primary' template.  */
6569           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
6570
6571           new_friend_result_template_info
6572             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
6573         }
6574       else
6575         new_friend_result_template_info = NULL_TREE;
6576
6577       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
6578       if (new_friend_is_defn)
6579         DECL_INITIAL (new_friend) = error_mark_node;
6580
6581       /* Inside pushdecl_namespace_level, we will push into the
6582          current namespace. However, the friend function should go
6583          into the namespace of the template.  */
6584       ns = decl_namespace_context (new_friend);
6585       push_nested_namespace (ns);
6586       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
6587       pop_nested_namespace (ns);
6588
6589       if (old_decl == error_mark_node)
6590         return error_mark_node;
6591
6592       if (old_decl != new_friend)
6593         {
6594           /* This new friend declaration matched an existing
6595              declaration.  For example, given:
6596
6597                template <class T> void f(T);
6598                template <class U> class C {
6599                  template <class T> friend void f(T) {}
6600                };
6601
6602              the friend declaration actually provides the definition
6603              of `f', once C has been instantiated for some type.  So,
6604              old_decl will be the out-of-class template declaration,
6605              while new_friend is the in-class definition.
6606
6607              But, if `f' was called before this point, the
6608              instantiation of `f' will have DECL_TI_ARGS corresponding
6609              to `T' but not to `U', references to which might appear
6610              in the definition of `f'.  Previously, the most general
6611              template for an instantiation of `f' was the out-of-class
6612              version; now it is the in-class version.  Therefore, we
6613              run through all specialization of `f', adding to their
6614              DECL_TI_ARGS appropriately.  In particular, they need a
6615              new set of outer arguments, corresponding to the
6616              arguments for this class instantiation.
6617
6618              The same situation can arise with something like this:
6619
6620                friend void f(int);
6621                template <class T> class C {
6622                  friend void f(T) {}
6623                };
6624
6625              when `C<int>' is instantiated.  Now, `f(int)' is defined
6626              in the class.  */
6627
6628           if (!new_friend_is_defn)
6629             /* On the other hand, if the in-class declaration does
6630                *not* provide a definition, then we don't want to alter
6631                existing definitions.  We can just leave everything
6632                alone.  */
6633             ;
6634           else
6635             {
6636               /* Overwrite whatever template info was there before, if
6637                  any, with the new template information pertaining to
6638                  the declaration.  */
6639               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
6640
6641               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
6642                 reregister_specialization (new_friend,
6643                                            most_general_template (old_decl),
6644                                            old_decl);
6645               else
6646                 {
6647                   tree t;
6648                   tree new_friend_args;
6649
6650                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
6651                     = new_friend_result_template_info;
6652
6653                   new_friend_args = TI_ARGS (new_friend_template_info);
6654                   for (t = DECL_TEMPLATE_SPECIALIZATIONS (old_decl);
6655                        t != NULL_TREE;
6656                        t = TREE_CHAIN (t))
6657                     {
6658                       tree spec = TREE_VALUE (t);
6659
6660                       DECL_TI_ARGS (spec)
6661                         = add_outermost_template_args (new_friend_args,
6662                                                        DECL_TI_ARGS (spec));
6663                     }
6664
6665                   /* Now, since specializations are always supposed to
6666                      hang off of the most general template, we must move
6667                      them.  */
6668                   t = most_general_template (old_decl);
6669                   if (t != old_decl)
6670                     {
6671                       DECL_TEMPLATE_SPECIALIZATIONS (t)
6672                         = chainon (DECL_TEMPLATE_SPECIALIZATIONS (t),
6673                                    DECL_TEMPLATE_SPECIALIZATIONS (old_decl));
6674                       DECL_TEMPLATE_SPECIALIZATIONS (old_decl) = NULL_TREE;
6675                     }
6676                 }
6677             }
6678
6679           /* The information from NEW_FRIEND has been merged into OLD_DECL
6680              by duplicate_decls.  */
6681           new_friend = old_decl;
6682         }
6683     }
6684   else
6685     {
6686       tree context = DECL_CONTEXT (new_friend);
6687       bool dependent_p;
6688
6689       /* In the code
6690            template <class T> class C {
6691              template <class U> friend void C1<U>::f (); // case 1
6692              friend void C2<T>::f ();                    // case 2
6693            };
6694          we only need to make sure CONTEXT is a complete type for
6695          case 2.  To distinguish between the two cases, we note that
6696          CONTEXT of case 1 remains dependent type after tsubst while
6697          this isn't true for case 2.  */
6698       ++processing_template_decl;
6699       dependent_p = dependent_type_p (context);
6700       --processing_template_decl;
6701
6702       if (!dependent_p
6703           && !complete_type_or_else (context, NULL_TREE))
6704         return error_mark_node;
6705
6706       if (COMPLETE_TYPE_P (context))
6707         {
6708           /* Check to see that the declaration is really present, and,
6709              possibly obtain an improved declaration.  */
6710           tree fn = check_classfn (context,
6711                                    new_friend, NULL_TREE);
6712
6713           if (fn)
6714             new_friend = fn;
6715         }
6716     }
6717
6718   return new_friend;
6719 }
6720
6721 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
6722    template arguments, as for tsubst.
6723
6724    Returns an appropriate tsubst'd friend type or error_mark_node on
6725    failure.  */
6726
6727 static tree
6728 tsubst_friend_class (tree friend_tmpl, tree args)
6729 {
6730   tree friend_type;
6731   tree tmpl;
6732   tree context;
6733
6734   context = DECL_CONTEXT (friend_tmpl);
6735
6736   if (context)
6737     {
6738       if (TREE_CODE (context) == NAMESPACE_DECL)
6739         push_nested_namespace (context);
6740       else
6741         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
6742     }
6743
6744   /* Look for a class template declaration.  We look for hidden names
6745      because two friend declarations of the same template are the
6746      same.  For example, in:
6747
6748        struct A { 
6749          template <typename> friend class F;
6750        };
6751        template <typename> struct B { 
6752          template <typename> friend class F;
6753        };
6754
6755      both F templates are the same.  */
6756   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
6757                            /*block_p=*/true, 0, 
6758                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
6759
6760   /* But, if we don't find one, it might be because we're in a
6761      situation like this:
6762
6763        template <class T>
6764        struct S {
6765          template <class U>
6766          friend struct S;
6767        };
6768
6769      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
6770      for `S<int>', not the TEMPLATE_DECL.  */
6771   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
6772     {
6773       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
6774       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
6775     }
6776
6777   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
6778     {
6779       /* The friend template has already been declared.  Just
6780          check to see that the declarations match, and install any new
6781          default parameters.  We must tsubst the default parameters,
6782          of course.  We only need the innermost template parameters
6783          because that is all that redeclare_class_template will look
6784          at.  */
6785       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
6786           > TMPL_ARGS_DEPTH (args))
6787         {
6788           tree parms;
6789           location_t saved_input_location;
6790           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
6791                                          args, tf_warning_or_error);
6792
6793           saved_input_location = input_location;
6794           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
6795           redeclare_class_template (TREE_TYPE (tmpl), parms);
6796           input_location = saved_input_location;
6797           
6798         }
6799
6800       friend_type = TREE_TYPE (tmpl);
6801     }
6802   else
6803     {
6804       /* The friend template has not already been declared.  In this
6805          case, the instantiation of the template class will cause the
6806          injection of this template into the global scope.  */
6807       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
6808       if (tmpl == error_mark_node)
6809         return error_mark_node;
6810
6811       /* The new TMPL is not an instantiation of anything, so we
6812          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
6813          the new type because that is supposed to be the corresponding
6814          template decl, i.e., TMPL.  */
6815       DECL_USE_TEMPLATE (tmpl) = 0;
6816       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
6817       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
6818       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
6819         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
6820
6821       /* Inject this template into the global scope.  */
6822       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
6823     }
6824
6825   if (context)
6826     {
6827       if (TREE_CODE (context) == NAMESPACE_DECL)
6828         pop_nested_namespace (context);
6829       else
6830         pop_nested_class ();
6831     }
6832
6833   return friend_type;
6834 }
6835
6836 /* Returns zero if TYPE cannot be completed later due to circularity.
6837    Otherwise returns one.  */
6838
6839 static int
6840 can_complete_type_without_circularity (tree type)
6841 {
6842   if (type == NULL_TREE || type == error_mark_node)
6843     return 0;
6844   else if (COMPLETE_TYPE_P (type))
6845     return 1;
6846   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
6847     return can_complete_type_without_circularity (TREE_TYPE (type));
6848   else if (CLASS_TYPE_P (type)
6849            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
6850     return 0;
6851   else
6852     return 1;
6853 }
6854
6855 /* Apply any attributes which had to be deferred until instantiation
6856    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
6857    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
6858
6859 static void
6860 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
6861                                 tree args, tsubst_flags_t complain, tree in_decl)
6862 {
6863   tree last_dep = NULL_TREE;
6864   tree t;
6865   tree *p;
6866
6867   for (t = attributes; t; t = TREE_CHAIN (t))
6868     if (ATTR_IS_DEPENDENT (t))
6869       {
6870         last_dep = t;
6871         attributes = copy_list (attributes);
6872         break;
6873       }
6874
6875   if (DECL_P (*decl_p))
6876     {
6877       if (TREE_TYPE (*decl_p) == error_mark_node)
6878         return;
6879       p = &DECL_ATTRIBUTES (*decl_p);
6880     }
6881   else
6882     p = &TYPE_ATTRIBUTES (*decl_p);
6883
6884   if (last_dep)
6885     {
6886       tree late_attrs = NULL_TREE;
6887       tree *q = &late_attrs;
6888
6889       for (*p = attributes; *p; )
6890         {
6891           t = *p;
6892           if (ATTR_IS_DEPENDENT (t))
6893             {
6894               *p = TREE_CHAIN (t);
6895               TREE_CHAIN (t) = NULL_TREE;
6896               /* If the first attribute argument is an identifier, don't
6897                  pass it through tsubst.  Attributes like mode, format,
6898                  cleanup and several target specific attributes expect it
6899                  unmodified.  */
6900               if (TREE_VALUE (t)
6901                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
6902                   && TREE_VALUE (TREE_VALUE (t))
6903                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
6904                       == IDENTIFIER_NODE))
6905                 {
6906                   tree chain
6907                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
6908                                    in_decl,
6909                                    /*integral_constant_expression_p=*/false);
6910                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
6911                     TREE_VALUE (t)
6912                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
6913                                    chain);
6914                 }
6915               else
6916                 TREE_VALUE (t)
6917                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
6918                                  /*integral_constant_expression_p=*/false);
6919               *q = t;
6920               q = &TREE_CHAIN (t);
6921             }
6922           else
6923             p = &TREE_CHAIN (t);
6924         }
6925
6926       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
6927     }
6928 }
6929
6930 tree
6931 instantiate_class_template (tree type)
6932 {
6933   tree templ, args, pattern, t, member;
6934   tree typedecl;
6935   tree pbinfo;
6936   tree base_list;
6937
6938   if (type == error_mark_node)
6939     return error_mark_node;
6940
6941   if (TYPE_BEING_DEFINED (type)
6942       || COMPLETE_TYPE_P (type)
6943       || dependent_type_p (type))
6944     return type;
6945
6946   /* Figure out which template is being instantiated.  */
6947   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
6948   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
6949
6950   /* Determine what specialization of the original template to
6951      instantiate.  */
6952   t = most_specialized_class (type, templ);
6953   if (t == error_mark_node)
6954     {
6955       TYPE_BEING_DEFINED (type) = 1;
6956       return error_mark_node;
6957     }
6958   else if (t)
6959     {
6960       /* This TYPE is actually an instantiation of a partial
6961          specialization.  We replace the innermost set of ARGS with
6962          the arguments appropriate for substitution.  For example,
6963          given:
6964
6965            template <class T> struct S {};
6966            template <class T> struct S<T*> {};
6967
6968          and supposing that we are instantiating S<int*>, ARGS will
6969          presently be {int*} -- but we need {int}.  */
6970       pattern = TREE_TYPE (t);
6971       args = TREE_PURPOSE (t);
6972     }
6973   else
6974     {
6975       pattern = TREE_TYPE (templ);
6976       args = CLASSTYPE_TI_ARGS (type);
6977     }
6978
6979   /* If the template we're instantiating is incomplete, then clearly
6980      there's nothing we can do.  */
6981   if (!COMPLETE_TYPE_P (pattern))
6982     return type;
6983
6984   /* If we've recursively instantiated too many templates, stop.  */
6985   if (! push_tinst_level (type))
6986     return type;
6987
6988   /* Now we're really doing the instantiation.  Mark the type as in
6989      the process of being defined.  */
6990   TYPE_BEING_DEFINED (type) = 1;
6991
6992   /* We may be in the middle of deferred access check.  Disable
6993      it now.  */
6994   push_deferring_access_checks (dk_no_deferred);
6995
6996   push_to_top_level ();
6997
6998   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
6999
7000   /* Set the input location to the template definition. This is needed
7001      if tsubsting causes an error.  */
7002   typedecl = TYPE_MAIN_DECL (type);
7003   input_location = DECL_SOURCE_LOCATION (typedecl);
7004
7005   TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
7006   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
7007   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
7008   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
7009   TYPE_HAS_ASSIGN_REF (type) = TYPE_HAS_ASSIGN_REF (pattern);
7010   TYPE_HAS_CONST_ASSIGN_REF (type) = TYPE_HAS_CONST_ASSIGN_REF (pattern);
7011   TYPE_HAS_INIT_REF (type) = TYPE_HAS_INIT_REF (pattern);
7012   TYPE_HAS_CONST_INIT_REF (type) = TYPE_HAS_CONST_INIT_REF (pattern);
7013   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
7014   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
7015   TYPE_PACKED (type) = TYPE_PACKED (pattern);
7016   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
7017   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
7018   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
7019   if (ANON_AGGR_TYPE_P (pattern))
7020     SET_ANON_AGGR_TYPE_P (type);
7021   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
7022     {
7023       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
7024       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
7025     }
7026
7027   pbinfo = TYPE_BINFO (pattern);
7028
7029   /* We should never instantiate a nested class before its enclosing
7030      class; we need to look up the nested class by name before we can
7031      instantiate it, and that lookup should instantiate the enclosing
7032      class.  */
7033   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
7034               || COMPLETE_TYPE_P (TYPE_CONTEXT (type))
7035               || TYPE_BEING_DEFINED (TYPE_CONTEXT (type)));
7036
7037   base_list = NULL_TREE;
7038   if (BINFO_N_BASE_BINFOS (pbinfo))
7039     {
7040       tree pbase_binfo;
7041       tree context = TYPE_CONTEXT (type);
7042       tree pushed_scope;
7043       int i;
7044
7045       /* We must enter the scope containing the type, as that is where
7046          the accessibility of types named in dependent bases are
7047          looked up from.  */
7048       pushed_scope = push_scope (context ? context : global_namespace);
7049
7050       /* Substitute into each of the bases to determine the actual
7051          basetypes.  */
7052       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
7053         {
7054           tree base;
7055           tree access = BINFO_BASE_ACCESS (pbinfo, i);
7056           tree expanded_bases = NULL_TREE;
7057           int idx, len = 1;
7058
7059           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
7060             {
7061               expanded_bases = 
7062                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
7063                                        args, tf_error, NULL_TREE);
7064               if (expanded_bases == error_mark_node)
7065                 continue;
7066
7067               len = TREE_VEC_LENGTH (expanded_bases);
7068             }
7069
7070           for (idx = 0; idx < len; idx++)
7071             {
7072               if (expanded_bases)
7073                 /* Extract the already-expanded base class.  */
7074                 base = TREE_VEC_ELT (expanded_bases, idx);
7075               else
7076                 /* Substitute to figure out the base class.  */
7077                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
7078                                NULL_TREE);
7079
7080               if (base == error_mark_node)
7081                 continue;
7082
7083               base_list = tree_cons (access, base, base_list);
7084               if (BINFO_VIRTUAL_P (pbase_binfo))
7085                 TREE_TYPE (base_list) = integer_type_node;
7086             }
7087         }
7088
7089       /* The list is now in reverse order; correct that.  */
7090       base_list = nreverse (base_list);
7091
7092       if (pushed_scope)
7093         pop_scope (pushed_scope);
7094     }
7095   /* Now call xref_basetypes to set up all the base-class
7096      information.  */
7097   xref_basetypes (type, base_list);
7098
7099   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
7100                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
7101                                   args, tf_error, NULL_TREE);
7102
7103   /* Now that our base classes are set up, enter the scope of the
7104      class, so that name lookups into base classes, etc. will work
7105      correctly.  This is precisely analogous to what we do in
7106      begin_class_definition when defining an ordinary non-template
7107      class, except we also need to push the enclosing classes.  */
7108   push_nested_class (type);
7109
7110   /* Now members are processed in the order of declaration.  */
7111   for (member = CLASSTYPE_DECL_LIST (pattern);
7112        member; member = TREE_CHAIN (member))
7113     {
7114       tree t = TREE_VALUE (member);
7115
7116       if (TREE_PURPOSE (member))
7117         {
7118           if (TYPE_P (t))
7119             {
7120               /* Build new CLASSTYPE_NESTED_UTDS.  */
7121
7122               tree newtag;
7123               bool class_template_p;
7124
7125               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
7126                                   && TYPE_LANG_SPECIFIC (t)
7127                                   && CLASSTYPE_IS_TEMPLATE (t));
7128               /* If the member is a class template, then -- even after
7129                  substitution -- there may be dependent types in the
7130                  template argument list for the class.  We increment
7131                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
7132                  that function will assume that no types are dependent
7133                  when outside of a template.  */
7134               if (class_template_p)
7135                 ++processing_template_decl;
7136               newtag = tsubst (t, args, tf_error, NULL_TREE);
7137               if (class_template_p)
7138                 --processing_template_decl;
7139               if (newtag == error_mark_node)
7140                 continue;
7141
7142               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
7143                 {
7144                   tree name = TYPE_IDENTIFIER (t);
7145
7146                   if (class_template_p)
7147                     /* Unfortunately, lookup_template_class sets
7148                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
7149                        instantiation (i.e., for the type of a member
7150                        template class nested within a template class.)
7151                        This behavior is required for
7152                        maybe_process_partial_specialization to work
7153                        correctly, but is not accurate in this case;
7154                        the TAG is not an instantiation of anything.
7155                        (The corresponding TEMPLATE_DECL is an
7156                        instantiation, but the TYPE is not.) */
7157                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
7158
7159                   /* Now, we call pushtag to put this NEWTAG into the scope of
7160                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
7161                      pushtag calling push_template_decl.  We don't have to do
7162                      this for enums because it will already have been done in
7163                      tsubst_enum.  */
7164                   if (name)
7165                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
7166                   pushtag (name, newtag, /*tag_scope=*/ts_current);
7167                 }
7168             }
7169           else if (TREE_CODE (t) == FUNCTION_DECL
7170                    || DECL_FUNCTION_TEMPLATE_P (t))
7171             {
7172               /* Build new TYPE_METHODS.  */
7173               tree r;
7174
7175               if (TREE_CODE (t) == TEMPLATE_DECL)
7176                 ++processing_template_decl;
7177               r = tsubst (t, args, tf_error, NULL_TREE);
7178               if (TREE_CODE (t) == TEMPLATE_DECL)
7179                 --processing_template_decl;
7180               set_current_access_from_decl (r);
7181               finish_member_declaration (r);
7182             }
7183           else
7184             {
7185               /* Build new TYPE_FIELDS.  */
7186               if (TREE_CODE (t) == STATIC_ASSERT)
7187                 {
7188                   tree condition = 
7189                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
7190                                  tf_warning_or_error, NULL_TREE,
7191                                  /*integral_constant_expression_p=*/true);
7192                   finish_static_assert (condition,
7193                                         STATIC_ASSERT_MESSAGE (t), 
7194                                         STATIC_ASSERT_SOURCE_LOCATION (t),
7195                                         /*member_p=*/true);
7196                 }
7197               else if (TREE_CODE (t) != CONST_DECL)
7198                 {
7199                   tree r;
7200
7201                   /* The file and line for this declaration, to
7202                      assist in error message reporting.  Since we
7203                      called push_tinst_level above, we don't need to
7204                      restore these.  */
7205                   input_location = DECL_SOURCE_LOCATION (t);
7206
7207                   if (TREE_CODE (t) == TEMPLATE_DECL)
7208                     ++processing_template_decl;
7209                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
7210                   if (TREE_CODE (t) == TEMPLATE_DECL)
7211                     --processing_template_decl;
7212                   if (TREE_CODE (r) == VAR_DECL)
7213                     {
7214                       /* In [temp.inst]:
7215
7216                            [t]he initialization (and any associated
7217                            side-effects) of a static data member does
7218                            not occur unless the static data member is
7219                            itself used in a way that requires the
7220                            definition of the static data member to
7221                            exist.
7222
7223                          Therefore, we do not substitute into the
7224                          initialized for the static data member here.  */
7225                       finish_static_data_member_decl
7226                         (r,
7227                          /*init=*/NULL_TREE,
7228                          /*init_const_expr_p=*/false,
7229                          /*asmspec_tree=*/NULL_TREE,
7230                          /*flags=*/0);
7231                       if (DECL_INITIALIZED_IN_CLASS_P (r))
7232                         check_static_variable_definition (r, TREE_TYPE (r));
7233                     }
7234                   else if (TREE_CODE (r) == FIELD_DECL)
7235                     {
7236                       /* Determine whether R has a valid type and can be
7237                          completed later.  If R is invalid, then it is
7238                          replaced by error_mark_node so that it will not be
7239                          added to TYPE_FIELDS.  */
7240                       tree rtype = TREE_TYPE (r);
7241                       if (can_complete_type_without_circularity (rtype))
7242                         complete_type (rtype);
7243
7244                       if (!COMPLETE_TYPE_P (rtype))
7245                         {
7246                           cxx_incomplete_type_error (r, rtype);
7247                           r = error_mark_node;
7248                         }
7249                     }
7250
7251                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
7252                      such a thing will already have been added to the field
7253                      list by tsubst_enum in finish_member_declaration in the
7254                      CLASSTYPE_NESTED_UTDS case above.  */
7255                   if (!(TREE_CODE (r) == TYPE_DECL
7256                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
7257                         && DECL_ARTIFICIAL (r)))
7258                     {
7259                       set_current_access_from_decl (r);
7260                       finish_member_declaration (r);
7261                     }
7262                 }
7263             }
7264         }
7265       else
7266         {
7267           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
7268             {
7269               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
7270
7271               tree friend_type = t;
7272               bool adjust_processing_template_decl = false;
7273
7274               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7275                 {
7276                   /* template <class T> friend class C;  */
7277                   friend_type = tsubst_friend_class (friend_type, args);
7278                   adjust_processing_template_decl = true;
7279                 }
7280               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
7281                 {
7282                   /* template <class T> friend class C::D;  */
7283                   friend_type = tsubst (friend_type, args,
7284                                         tf_warning_or_error, NULL_TREE);
7285                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7286                     friend_type = TREE_TYPE (friend_type);
7287                   adjust_processing_template_decl = true;
7288                 }
7289               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
7290                 {
7291                   /* This could be either
7292
7293                        friend class T::C;
7294
7295                      when dependent_type_p is false or
7296
7297                        template <class U> friend class T::C;
7298
7299                      otherwise.  */
7300                   friend_type = tsubst (friend_type, args,
7301                                         tf_warning_or_error, NULL_TREE);
7302                   /* Bump processing_template_decl for correct
7303                      dependent_type_p calculation.  */
7304                   ++processing_template_decl;
7305                   if (dependent_type_p (friend_type))
7306                     adjust_processing_template_decl = true;
7307                   --processing_template_decl;
7308                 }
7309               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
7310                        && hidden_name_p (TYPE_NAME (friend_type)))
7311                 {
7312                   /* friend class C;
7313
7314                      where C hasn't been declared yet.  Let's lookup name
7315                      from namespace scope directly, bypassing any name that
7316                      come from dependent base class.  */
7317                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
7318
7319                   /* The call to xref_tag_from_type does injection for friend
7320                      classes.  */
7321                   push_nested_namespace (ns);
7322                   friend_type =
7323                     xref_tag_from_type (friend_type, NULL_TREE,
7324                                         /*tag_scope=*/ts_current);
7325                   pop_nested_namespace (ns);
7326                 }
7327               else if (uses_template_parms (friend_type))
7328                 /* friend class C<T>;  */
7329                 friend_type = tsubst (friend_type, args,
7330                                       tf_warning_or_error, NULL_TREE);
7331               /* Otherwise it's
7332
7333                    friend class C;
7334
7335                  where C is already declared or
7336
7337                    friend class C<int>;
7338
7339                  We don't have to do anything in these cases.  */
7340
7341               if (adjust_processing_template_decl)
7342                 /* Trick make_friend_class into realizing that the friend
7343                    we're adding is a template, not an ordinary class.  It's
7344                    important that we use make_friend_class since it will
7345                    perform some error-checking and output cross-reference
7346                    information.  */
7347                 ++processing_template_decl;
7348
7349               if (friend_type != error_mark_node)
7350                 make_friend_class (type, friend_type, /*complain=*/false);
7351
7352               if (adjust_processing_template_decl)
7353                 --processing_template_decl;
7354             }
7355           else
7356             {
7357               /* Build new DECL_FRIENDLIST.  */
7358               tree r;
7359
7360               /* The file and line for this declaration, to
7361                  assist in error message reporting.  Since we
7362                  called push_tinst_level above, we don't need to
7363                  restore these.  */
7364               input_location = DECL_SOURCE_LOCATION (t);
7365
7366               if (TREE_CODE (t) == TEMPLATE_DECL)
7367                 {
7368                   ++processing_template_decl;
7369                   push_deferring_access_checks (dk_no_check);
7370                 }
7371
7372               r = tsubst_friend_function (t, args);
7373               add_friend (type, r, /*complain=*/false);
7374               if (TREE_CODE (t) == TEMPLATE_DECL)
7375                 {
7376                   pop_deferring_access_checks ();
7377                   --processing_template_decl;
7378                 }
7379             }
7380         }
7381     }
7382
7383   /* Set the file and line number information to whatever is given for
7384      the class itself.  This puts error messages involving generated
7385      implicit functions at a predictable point, and the same point
7386      that would be used for non-template classes.  */
7387   input_location = DECL_SOURCE_LOCATION (typedecl);
7388
7389   unreverse_member_declarations (type);
7390   finish_struct_1 (type);
7391   TYPE_BEING_DEFINED (type) = 0;
7392
7393   /* Now that the class is complete, instantiate default arguments for
7394      any member functions.  We don't do this earlier because the
7395      default arguments may reference members of the class.  */
7396   if (!PRIMARY_TEMPLATE_P (templ))
7397     for (t = TYPE_METHODS (type); t; t = TREE_CHAIN (t))
7398       if (TREE_CODE (t) == FUNCTION_DECL
7399           /* Implicitly generated member functions will not have template
7400              information; they are not instantiations, but instead are
7401              created "fresh" for each instantiation.  */
7402           && DECL_TEMPLATE_INFO (t))
7403         tsubst_default_arguments (t);
7404
7405   pop_nested_class ();
7406   pop_from_top_level ();
7407   pop_deferring_access_checks ();
7408   pop_tinst_level ();
7409
7410   /* The vtable for a template class can be emitted in any translation
7411      unit in which the class is instantiated.  When there is no key
7412      method, however, finish_struct_1 will already have added TYPE to
7413      the keyed_classes list.  */
7414   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
7415     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
7416
7417   return type;
7418 }
7419
7420 static tree
7421 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7422 {
7423   tree r;
7424
7425   if (!t)
7426     r = t;
7427   else if (TYPE_P (t))
7428     r = tsubst (t, args, complain, in_decl);
7429   else
7430     {
7431       r = tsubst_expr (t, args, complain, in_decl,
7432                        /*integral_constant_expression_p=*/true);
7433       r = fold_non_dependent_expr (r);
7434     }
7435   return r;
7436 }
7437
7438 /* Substitute ARGS into T, which is an pack expansion
7439    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
7440    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
7441    (if only a partial substitution could be performed) or
7442    ERROR_MARK_NODE if there was an error.  */
7443 tree
7444 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
7445                        tree in_decl)
7446 {
7447   tree pattern;
7448   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
7449   tree first_arg_pack; int i, len = -1;
7450   tree result;
7451   int incomplete = 0;
7452
7453   gcc_assert (PACK_EXPANSION_P (t));
7454   pattern = PACK_EXPANSION_PATTERN (t);
7455
7456   /* Determine the argument packs that will instantiate the parameter
7457      packs used in the expansion expression. While we're at it,
7458      compute the number of arguments to be expanded and make sure it
7459      is consistent.  */
7460   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
7461        pack = TREE_CHAIN (pack))
7462     {
7463       tree parm_pack = TREE_VALUE (pack);
7464       tree arg_pack = NULL_TREE;
7465       tree orig_arg = NULL_TREE;
7466
7467       if (TREE_CODE (parm_pack) == PARM_DECL)
7468         arg_pack = retrieve_local_specialization (parm_pack);
7469       else
7470         {
7471           int level, idx, levels;
7472           template_parm_level_and_index (parm_pack, &level, &idx);
7473
7474           levels = TMPL_ARGS_DEPTH (args);
7475           if (level <= levels)
7476             arg_pack = TMPL_ARG (args, level, idx);
7477         }
7478
7479       orig_arg = arg_pack;
7480       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
7481         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
7482       
7483       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
7484         /* This can only happen if we forget to expand an argument
7485            pack somewhere else. Just return an error, silently.  */
7486         {
7487           result = make_tree_vec (1);
7488           TREE_VEC_ELT (result, 0) = error_mark_node;
7489           return result;
7490         }
7491
7492       if (arg_pack
7493           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
7494           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
7495         {
7496           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
7497           tree pattern = PACK_EXPANSION_PATTERN (expansion);
7498           if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
7499               || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
7500             /* The argument pack that the parameter maps to is just an
7501                expansion of the parameter itself, such as one would
7502                find in the implicit typedef of a class inside the
7503                class itself.  Consider this parameter "unsubstituted",
7504                so that we will maintain the outer pack expansion.  */
7505             arg_pack = NULL_TREE;
7506         }
7507           
7508       if (arg_pack)
7509         {
7510           int my_len = 
7511             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
7512
7513           /* It's all-or-nothing with incomplete argument packs.  */
7514           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
7515             return error_mark_node;
7516           
7517           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
7518             incomplete = 1;
7519
7520           if (len < 0)
7521             {
7522               len = my_len;
7523               first_arg_pack = arg_pack;
7524             }
7525           else if (len != my_len)
7526             {
7527               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
7528                 error ("mismatched argument pack lengths while expanding "
7529                        "%<%T%>",
7530                        pattern);
7531               else
7532                 error ("mismatched argument pack lengths while expanding "
7533                        "%<%E%>",
7534                        pattern);
7535               return error_mark_node;
7536             }
7537
7538           /* Keep track of the parameter packs and their corresponding
7539              argument packs.  */
7540           packs = tree_cons (parm_pack, arg_pack, packs);
7541           TREE_TYPE (packs) = orig_arg;
7542         }
7543       else
7544         /* We can't substitute for this parameter pack.  */
7545         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
7546                                          TREE_VALUE (pack),
7547                                          unsubstituted_packs);
7548     }
7549
7550   /* We cannot expand this expansion expression, because we don't have
7551      all of the argument packs we need. Substitute into the pattern
7552      and return a PACK_EXPANSION_*. The caller will need to deal with
7553      that.  */
7554   if (unsubstituted_packs)
7555     return make_pack_expansion (tsubst (pattern, args, complain, 
7556                                         in_decl));
7557
7558   /* We could not find any argument packs that work.  */
7559   if (len < 0)
7560     return error_mark_node;
7561
7562   /* For each argument in each argument pack, substitute into the
7563      pattern.  */
7564   result = make_tree_vec (len + incomplete);
7565   for (i = 0; i < len + incomplete; ++i)
7566     {
7567       /* For parameter pack, change the substitution of the parameter
7568          pack to the ith argument in its argument pack, then expand
7569          the pattern.  */
7570       for (pack = packs; pack; pack = TREE_CHAIN (pack))
7571         {
7572           tree parm = TREE_PURPOSE (pack);
7573
7574           if (TREE_CODE (parm) == PARM_DECL)
7575             {
7576               /* Select the Ith argument from the pack.  */
7577               tree arg = make_node (ARGUMENT_PACK_SELECT);
7578               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
7579               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
7580               mark_used (parm);
7581               register_local_specialization (arg, parm);
7582             }
7583           else
7584             {
7585               tree value = parm;
7586               int idx, level;
7587               template_parm_level_and_index (parm, &level, &idx);
7588               
7589               if (i < len) 
7590                 {
7591                   /* Select the Ith argument from the pack. */
7592                   value = make_node (ARGUMENT_PACK_SELECT);
7593                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
7594                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
7595                 }
7596
7597               /* Update the corresponding argument.  */
7598               TMPL_ARG (args, level, idx) = value;
7599             }
7600         }
7601
7602       /* Substitute into the PATTERN with the altered arguments.  */
7603       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
7604         TREE_VEC_ELT (result, i) = 
7605           tsubst_expr (pattern, args, complain, in_decl,
7606                        /*integral_constant_expression_p=*/false);
7607       else
7608         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
7609
7610       if (i == len)
7611         /* When we have incomplete argument packs, the last "expanded"
7612            result is itself a pack expansion, which allows us
7613            to deduce more arguments.  */
7614         TREE_VEC_ELT (result, i) = 
7615           make_pack_expansion (TREE_VEC_ELT (result, i));
7616
7617       if (TREE_VEC_ELT (result, i) == error_mark_node)
7618         {
7619           result = error_mark_node;
7620           break;
7621         }
7622     }
7623   
7624   /* Update ARGS to restore the substitution from parameter packs to
7625      their argument packs.  */
7626   for (pack = packs; pack; pack = TREE_CHAIN (pack))
7627     {
7628       tree parm = TREE_PURPOSE (pack);
7629
7630       if (TREE_CODE (parm) == PARM_DECL)
7631         register_local_specialization (TREE_TYPE (pack), parm);
7632       else
7633         {
7634           int idx, level;
7635           template_parm_level_and_index (parm, &level, &idx);
7636           
7637           /* Update the corresponding argument.  */
7638           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
7639             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
7640               TREE_TYPE (pack);
7641           else
7642             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
7643         }
7644     }
7645
7646   return result;
7647 }
7648
7649 /* Substitute ARGS into the vector or list of template arguments T.  */
7650
7651 static tree
7652 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7653 {
7654   tree orig_t = t;
7655   int len = TREE_VEC_LENGTH (t);
7656   int need_new = 0, i, expanded_len_adjust = 0, out;
7657   tree *elts = (tree *) alloca (len * sizeof (tree));
7658
7659   for (i = 0; i < len; i++)
7660     {
7661       tree orig_arg = TREE_VEC_ELT (t, i);
7662       tree new_arg;
7663
7664       if (TREE_CODE (orig_arg) == TREE_VEC)
7665         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
7666       else if (PACK_EXPANSION_P (orig_arg))
7667         {
7668           /* Substitute into an expansion expression.  */
7669           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
7670
7671           if (TREE_CODE (new_arg) == TREE_VEC)
7672             /* Add to the expanded length adjustment the number of
7673                expanded arguments. We subtract one from this
7674                measurement, because the argument pack expression
7675                itself is already counted as 1 in
7676                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
7677                the argument pack is empty.  */
7678             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
7679         }
7680       else if (ARGUMENT_PACK_P (orig_arg))
7681         {
7682           /* Substitute into each of the arguments.  */
7683           new_arg = make_node (TREE_CODE (orig_arg));
7684           
7685           SET_ARGUMENT_PACK_ARGS (
7686             new_arg,
7687             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
7688                                   args, complain, in_decl));
7689
7690           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
7691             new_arg = error_mark_node;
7692
7693           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
7694             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
7695                                           complain, in_decl);
7696             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
7697
7698             if (TREE_TYPE (new_arg) == error_mark_node)
7699               new_arg = error_mark_node;
7700           }
7701         }
7702       else
7703         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
7704
7705       if (new_arg == error_mark_node)
7706         return error_mark_node;
7707
7708       elts[i] = new_arg;
7709       if (new_arg != orig_arg)
7710         need_new = 1;
7711     }
7712
7713   if (!need_new)
7714     return t;
7715
7716   /* Make space for the expanded arguments coming from template
7717      argument packs.  */
7718   t = make_tree_vec (len + expanded_len_adjust);
7719   for (i = 0, out = 0; i < len; i++)
7720     {
7721       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
7722            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
7723           && TREE_CODE (elts[i]) == TREE_VEC)
7724         {
7725           int idx;
7726
7727           /* Now expand the template argument pack "in place".  */
7728           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
7729             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
7730         }
7731       else
7732         {
7733           TREE_VEC_ELT (t, out) = elts[i];
7734           out++;
7735         }
7736     }
7737
7738   return t;
7739 }
7740
7741 /* Return the result of substituting ARGS into the template parameters
7742    given by PARMS.  If there are m levels of ARGS and m + n levels of
7743    PARMS, then the result will contain n levels of PARMS.  For
7744    example, if PARMS is `template <class T> template <class U>
7745    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
7746    result will be `template <int*, double, class V>'.  */
7747
7748 static tree
7749 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
7750 {
7751   tree r = NULL_TREE;
7752   tree* new_parms;
7753
7754   /* When substituting into a template, we must set
7755      PROCESSING_TEMPLATE_DECL as the template parameters may be
7756      dependent if they are based on one-another, and the dependency
7757      predicates are short-circuit outside of templates.  */
7758   ++processing_template_decl;
7759
7760   for (new_parms = &r;
7761        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
7762        new_parms = &(TREE_CHAIN (*new_parms)),
7763          parms = TREE_CHAIN (parms))
7764     {
7765       tree new_vec =
7766         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
7767       int i;
7768
7769       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
7770         {
7771           tree tuple;
7772           tree default_value;
7773           tree parm_decl;
7774
7775           if (parms == error_mark_node)
7776             continue;
7777
7778           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
7779
7780           if (tuple == error_mark_node)
7781             continue;
7782
7783           default_value = TREE_PURPOSE (tuple);
7784           parm_decl = TREE_VALUE (tuple);
7785
7786           parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
7787           if (TREE_CODE (parm_decl) == PARM_DECL
7788               && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
7789             parm_decl = error_mark_node;
7790           default_value = tsubst_template_arg (default_value, args,
7791                                                complain, NULL_TREE);
7792
7793           tuple = build_tree_list (default_value, parm_decl);
7794           TREE_VEC_ELT (new_vec, i) = tuple;
7795         }
7796
7797       *new_parms =
7798         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
7799                              - TMPL_ARGS_DEPTH (args)),
7800                    new_vec, NULL_TREE);
7801     }
7802
7803   --processing_template_decl;
7804
7805   return r;
7806 }
7807
7808 /* Substitute the ARGS into the indicated aggregate (or enumeration)
7809    type T.  If T is not an aggregate or enumeration type, it is
7810    handled as if by tsubst.  IN_DECL is as for tsubst.  If
7811    ENTERING_SCOPE is nonzero, T is the context for a template which
7812    we are presently tsubst'ing.  Return the substituted value.  */
7813
7814 static tree
7815 tsubst_aggr_type (tree t,
7816                   tree args,
7817                   tsubst_flags_t complain,
7818                   tree in_decl,
7819                   int entering_scope)
7820 {
7821   if (t == NULL_TREE)
7822     return NULL_TREE;
7823
7824   switch (TREE_CODE (t))
7825     {
7826     case RECORD_TYPE:
7827       if (TYPE_PTRMEMFUNC_P (t))
7828         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
7829
7830       /* Else fall through.  */
7831     case ENUMERAL_TYPE:
7832     case UNION_TYPE:
7833       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
7834         {
7835           tree argvec;
7836           tree context;
7837           tree r;
7838           bool saved_skip_evaluation;
7839
7840           /* In "sizeof(X<I>)" we need to evaluate "I".  */
7841           saved_skip_evaluation = skip_evaluation;
7842           skip_evaluation = false;
7843
7844           /* First, determine the context for the type we are looking
7845              up.  */
7846           context = TYPE_CONTEXT (t);
7847           if (context)
7848             {
7849               context = tsubst_aggr_type (context, args, complain,
7850                                           in_decl, /*entering_scope=*/1);
7851               /* If context is a nested class inside a class template,
7852                  it may still need to be instantiated (c++/33959).  */
7853               if (TYPE_P (context))
7854                 context = complete_type (context);
7855             }
7856
7857           /* Then, figure out what arguments are appropriate for the
7858              type we are trying to find.  For example, given:
7859
7860                template <class T> struct S;
7861                template <class T, class U> void f(T, U) { S<U> su; }
7862
7863              and supposing that we are instantiating f<int, double>,
7864              then our ARGS will be {int, double}, but, when looking up
7865              S we only want {double}.  */
7866           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
7867                                          complain, in_decl);
7868           if (argvec == error_mark_node)
7869             r = error_mark_node;
7870           else
7871             {
7872               r = lookup_template_class (t, argvec, in_decl, context,
7873                                          entering_scope, complain);
7874               r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
7875             }
7876
7877           skip_evaluation = saved_skip_evaluation;
7878
7879           return r;
7880         }
7881       else
7882         /* This is not a template type, so there's nothing to do.  */
7883         return t;
7884
7885     default:
7886       return tsubst (t, args, complain, in_decl);
7887     }
7888 }
7889
7890 /* Substitute into the default argument ARG (a default argument for
7891    FN), which has the indicated TYPE.  */
7892
7893 tree
7894 tsubst_default_argument (tree fn, tree type, tree arg)
7895 {
7896   tree saved_class_ptr = NULL_TREE;
7897   tree saved_class_ref = NULL_TREE;
7898
7899   /* This default argument came from a template.  Instantiate the
7900      default argument here, not in tsubst.  In the case of
7901      something like:
7902
7903        template <class T>
7904        struct S {
7905          static T t();
7906          void f(T = t());
7907        };
7908
7909      we must be careful to do name lookup in the scope of S<T>,
7910      rather than in the current class.  */
7911   push_access_scope (fn);
7912   /* The "this" pointer is not valid in a default argument.  */
7913   if (cfun)
7914     {
7915       saved_class_ptr = current_class_ptr;
7916       cp_function_chain->x_current_class_ptr = NULL_TREE;
7917       saved_class_ref = current_class_ref;
7918       cp_function_chain->x_current_class_ref = NULL_TREE;
7919     }
7920
7921   push_deferring_access_checks(dk_no_deferred);
7922   /* The default argument expression may cause implicitly defined
7923      member functions to be synthesized, which will result in garbage
7924      collection.  We must treat this situation as if we were within
7925      the body of function so as to avoid collecting live data on the
7926      stack.  */
7927   ++function_depth;
7928   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
7929                      tf_warning_or_error, NULL_TREE,
7930                      /*integral_constant_expression_p=*/false);
7931   --function_depth;
7932   pop_deferring_access_checks();
7933
7934   /* Restore the "this" pointer.  */
7935   if (cfun)
7936     {
7937       cp_function_chain->x_current_class_ptr = saved_class_ptr;
7938       cp_function_chain->x_current_class_ref = saved_class_ref;
7939     }
7940
7941   pop_access_scope (fn);
7942
7943   /* Make sure the default argument is reasonable.  */
7944   arg = check_default_argument (type, arg);
7945
7946   return arg;
7947 }
7948
7949 /* Substitute into all the default arguments for FN.  */
7950
7951 static void
7952 tsubst_default_arguments (tree fn)
7953 {
7954   tree arg;
7955   tree tmpl_args;
7956
7957   tmpl_args = DECL_TI_ARGS (fn);
7958
7959   /* If this function is not yet instantiated, we certainly don't need
7960      its default arguments.  */
7961   if (uses_template_parms (tmpl_args))
7962     return;
7963
7964   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
7965        arg;
7966        arg = TREE_CHAIN (arg))
7967     if (TREE_PURPOSE (arg))
7968       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
7969                                                     TREE_VALUE (arg),
7970                                                     TREE_PURPOSE (arg));
7971 }
7972
7973 /* Substitute the ARGS into the T, which is a _DECL.  Return the
7974    result of the substitution.  Issue error and warning messages under
7975    control of COMPLAIN.  */
7976
7977 static tree
7978 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
7979 {
7980   location_t saved_loc;
7981   tree r = NULL_TREE;
7982   tree in_decl = t;
7983
7984   /* Set the filename and linenumber to improve error-reporting.  */
7985   saved_loc = input_location;
7986   input_location = DECL_SOURCE_LOCATION (t);
7987
7988   switch (TREE_CODE (t))
7989     {
7990     case TEMPLATE_DECL:
7991       {
7992         /* We can get here when processing a member function template,
7993            member class template, and template template parameter of
7994            a template class.  */
7995         tree decl = DECL_TEMPLATE_RESULT (t);
7996         tree spec;
7997         tree tmpl_args;
7998         tree full_args;
7999
8000         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
8001           {
8002             /* Template template parameter is treated here.  */
8003             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8004             if (new_type == error_mark_node)
8005               return error_mark_node;
8006
8007             r = copy_decl (t);
8008             TREE_CHAIN (r) = NULL_TREE;
8009             TREE_TYPE (r) = new_type;
8010             DECL_TEMPLATE_RESULT (r)
8011               = build_decl (TYPE_DECL, DECL_NAME (decl), new_type);
8012             DECL_TEMPLATE_PARMS (r)
8013               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8014                                        complain);
8015             TYPE_NAME (new_type) = r;
8016             break;
8017           }
8018
8019         /* We might already have an instance of this template.
8020            The ARGS are for the surrounding class type, so the
8021            full args contain the tsubst'd args for the context,
8022            plus the innermost args from the template decl.  */
8023         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
8024           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
8025           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
8026         /* Because this is a template, the arguments will still be
8027            dependent, even after substitution.  If
8028            PROCESSING_TEMPLATE_DECL is not set, the dependency
8029            predicates will short-circuit.  */
8030         ++processing_template_decl;
8031         full_args = tsubst_template_args (tmpl_args, args,
8032                                           complain, in_decl);
8033         --processing_template_decl;
8034         if (full_args == error_mark_node)
8035           return error_mark_node;
8036
8037         /* tsubst_template_args doesn't copy the vector if
8038            nothing changed.  But, *something* should have
8039            changed.  */
8040         gcc_assert (full_args != tmpl_args);
8041
8042         spec = retrieve_specialization (t, full_args,
8043                                         /*class_specializations_p=*/true);
8044         if (spec != NULL_TREE)
8045           {
8046             r = spec;
8047             break;
8048           }
8049
8050         /* Make a new template decl.  It will be similar to the
8051            original, but will record the current template arguments.
8052            We also create a new function declaration, which is just
8053            like the old one, but points to this new template, rather
8054            than the old one.  */
8055         r = copy_decl (t);
8056         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
8057         TREE_CHAIN (r) = NULL_TREE;
8058
8059         DECL_TEMPLATE_INFO (r) = build_tree_list (t, args);
8060
8061         if (TREE_CODE (decl) == TYPE_DECL)
8062           {
8063             tree new_type;
8064             ++processing_template_decl;
8065             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8066             --processing_template_decl;
8067             if (new_type == error_mark_node)
8068               return error_mark_node;
8069
8070             TREE_TYPE (r) = new_type;
8071             CLASSTYPE_TI_TEMPLATE (new_type) = r;
8072             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
8073             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
8074             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
8075           }
8076         else
8077           {
8078             tree new_decl;
8079             ++processing_template_decl;
8080             new_decl = tsubst (decl, args, complain, in_decl);
8081             --processing_template_decl;
8082             if (new_decl == error_mark_node)
8083               return error_mark_node;
8084
8085             DECL_TEMPLATE_RESULT (r) = new_decl;
8086             DECL_TI_TEMPLATE (new_decl) = r;
8087             TREE_TYPE (r) = TREE_TYPE (new_decl);
8088             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
8089             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
8090           }
8091
8092         SET_DECL_IMPLICIT_INSTANTIATION (r);
8093         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
8094         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
8095
8096         /* The template parameters for this new template are all the
8097            template parameters for the old template, except the
8098            outermost level of parameters.  */
8099         DECL_TEMPLATE_PARMS (r)
8100           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8101                                    complain);
8102
8103         if (PRIMARY_TEMPLATE_P (t))
8104           DECL_PRIMARY_TEMPLATE (r) = r;
8105
8106         if (TREE_CODE (decl) != TYPE_DECL)
8107           /* Record this non-type partial instantiation.  */
8108           register_specialization (r, t,
8109                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
8110                                    false);
8111       }
8112       break;
8113
8114     case FUNCTION_DECL:
8115       {
8116         tree ctx;
8117         tree argvec = NULL_TREE;
8118         tree *friends;
8119         tree gen_tmpl;
8120         tree type;
8121         int member;
8122         int args_depth;
8123         int parms_depth;
8124
8125         /* Nobody should be tsubst'ing into non-template functions.  */
8126         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
8127
8128         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
8129           {
8130             tree spec;
8131             bool dependent_p;
8132
8133             /* If T is not dependent, just return it.  We have to
8134                increment PROCESSING_TEMPLATE_DECL because
8135                value_dependent_expression_p assumes that nothing is
8136                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
8137             ++processing_template_decl;
8138             dependent_p = value_dependent_expression_p (t);
8139             --processing_template_decl;
8140             if (!dependent_p)
8141               return t;
8142
8143             /* Calculate the most general template of which R is a
8144                specialization, and the complete set of arguments used to
8145                specialize R.  */
8146             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
8147             argvec = tsubst_template_args (DECL_TI_ARGS
8148                                            (DECL_TEMPLATE_RESULT (gen_tmpl)),
8149                                            args, complain, in_decl);
8150
8151             /* Check to see if we already have this specialization.  */
8152             spec = retrieve_specialization (gen_tmpl, argvec,
8153                                             /*class_specializations_p=*/false);
8154
8155             if (spec)
8156               {
8157                 r = spec;
8158                 break;
8159               }
8160
8161             /* We can see more levels of arguments than parameters if
8162                there was a specialization of a member template, like
8163                this:
8164
8165                  template <class T> struct S { template <class U> void f(); }
8166                  template <> template <class U> void S<int>::f(U);
8167
8168                Here, we'll be substituting into the specialization,
8169                because that's where we can find the code we actually
8170                want to generate, but we'll have enough arguments for
8171                the most general template.
8172
8173                We also deal with the peculiar case:
8174
8175                  template <class T> struct S {
8176                    template <class U> friend void f();
8177                  };
8178                  template <class U> void f() {}
8179                  template S<int>;
8180                  template void f<double>();
8181
8182                Here, the ARGS for the instantiation of will be {int,
8183                double}.  But, we only need as many ARGS as there are
8184                levels of template parameters in CODE_PATTERN.  We are
8185                careful not to get fooled into reducing the ARGS in
8186                situations like:
8187
8188                  template <class T> struct S { template <class U> void f(U); }
8189                  template <class T> template <> void S<T>::f(int) {}
8190
8191                which we can spot because the pattern will be a
8192                specialization in this case.  */
8193             args_depth = TMPL_ARGS_DEPTH (args);
8194             parms_depth =
8195               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
8196             if (args_depth > parms_depth
8197                 && !DECL_TEMPLATE_SPECIALIZATION (t))
8198               args = get_innermost_template_args (args, parms_depth);
8199           }
8200         else
8201           {
8202             /* This special case arises when we have something like this:
8203
8204                  template <class T> struct S {
8205                    friend void f<int>(int, double);
8206                  };
8207
8208                Here, the DECL_TI_TEMPLATE for the friend declaration
8209                will be an IDENTIFIER_NODE.  We are being called from
8210                tsubst_friend_function, and we want only to create a
8211                new decl (R) with appropriate types so that we can call
8212                determine_specialization.  */
8213             gen_tmpl = NULL_TREE;
8214           }
8215
8216         if (DECL_CLASS_SCOPE_P (t))
8217           {
8218             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
8219               member = 2;
8220             else
8221               member = 1;
8222             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
8223                                     complain, t, /*entering_scope=*/1);
8224           }
8225         else
8226           {
8227             member = 0;
8228             ctx = DECL_CONTEXT (t);
8229           }
8230         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8231         if (type == error_mark_node)
8232           return error_mark_node;
8233
8234         /* We do NOT check for matching decls pushed separately at this
8235            point, as they may not represent instantiations of this
8236            template, and in any case are considered separate under the
8237            discrete model.  */
8238         r = copy_decl (t);
8239         DECL_USE_TEMPLATE (r) = 0;
8240         TREE_TYPE (r) = type;
8241         /* Clear out the mangled name and RTL for the instantiation.  */
8242         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
8243         SET_DECL_RTL (r, NULL_RTX);
8244         /* Leave DECL_INITIAL set on deleted instantiations.  */
8245         if (!DECL_DELETED_FN (r))
8246           DECL_INITIAL (r) = NULL_TREE;
8247         DECL_CONTEXT (r) = ctx;
8248
8249         if (member && DECL_CONV_FN_P (r))
8250           /* Type-conversion operator.  Reconstruct the name, in
8251              case it's the name of one of the template's parameters.  */
8252           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
8253
8254         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
8255                                      complain, t);
8256         DECL_RESULT (r) = NULL_TREE;
8257
8258         TREE_STATIC (r) = 0;
8259         TREE_PUBLIC (r) = TREE_PUBLIC (t);
8260         DECL_EXTERNAL (r) = 1;
8261         /* If this is an instantiation of a function with internal
8262            linkage, we already know what object file linkage will be
8263            assigned to the instantiation.  */
8264         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
8265         DECL_DEFER_OUTPUT (r) = 0;
8266         TREE_CHAIN (r) = NULL_TREE;
8267         DECL_PENDING_INLINE_INFO (r) = 0;
8268         DECL_PENDING_INLINE_P (r) = 0;
8269         DECL_SAVED_TREE (r) = NULL_TREE;
8270         DECL_STRUCT_FUNCTION (r) = NULL;
8271         TREE_USED (r) = 0;
8272         if (DECL_CLONED_FUNCTION (r))
8273           {
8274             DECL_CLONED_FUNCTION (r) = tsubst (DECL_CLONED_FUNCTION (t),
8275                                                args, complain, t);
8276             TREE_CHAIN (r) = TREE_CHAIN (DECL_CLONED_FUNCTION (r));
8277             TREE_CHAIN (DECL_CLONED_FUNCTION (r)) = r;
8278           }
8279
8280         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
8281            this in the special friend case mentioned above where
8282            GEN_TMPL is NULL.  */
8283         if (gen_tmpl)
8284           {
8285             DECL_TEMPLATE_INFO (r)
8286               = tree_cons (gen_tmpl, argvec, NULL_TREE);
8287             SET_DECL_IMPLICIT_INSTANTIATION (r);
8288             register_specialization (r, gen_tmpl, argvec, false);
8289
8290             /* We're not supposed to instantiate default arguments
8291                until they are called, for a template.  But, for a
8292                declaration like:
8293
8294                  template <class T> void f ()
8295                  { extern void g(int i = T()); }
8296
8297                we should do the substitution when the template is
8298                instantiated.  We handle the member function case in
8299                instantiate_class_template since the default arguments
8300                might refer to other members of the class.  */
8301             if (!member
8302                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
8303                 && !uses_template_parms (argvec))
8304               tsubst_default_arguments (r);
8305           }
8306         else
8307           DECL_TEMPLATE_INFO (r) = NULL_TREE;
8308
8309         /* Copy the list of befriending classes.  */
8310         for (friends = &DECL_BEFRIENDING_CLASSES (r);
8311              *friends;
8312              friends = &TREE_CHAIN (*friends))
8313           {
8314             *friends = copy_node (*friends);
8315             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
8316                                             args, complain,
8317                                             in_decl);
8318           }
8319
8320         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
8321           {
8322             maybe_retrofit_in_chrg (r);
8323             if (DECL_CONSTRUCTOR_P (r))
8324               grok_ctor_properties (ctx, r);
8325             /* If this is an instantiation of a member template, clone it.
8326                If it isn't, that'll be handled by
8327                clone_constructors_and_destructors.  */
8328             if (PRIMARY_TEMPLATE_P (gen_tmpl))
8329               clone_function_decl (r, /*update_method_vec_p=*/0);
8330           }
8331         else if (IDENTIFIER_OPNAME_P (DECL_NAME (r))
8332                  && !grok_op_properties (r, (complain & tf_error) != 0))
8333           return error_mark_node;
8334
8335         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
8336           SET_DECL_FRIEND_CONTEXT (r,
8337                                    tsubst (DECL_FRIEND_CONTEXT (t),
8338                                             args, complain, in_decl));
8339
8340         /* Possibly limit visibility based on template args.  */
8341         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
8342         if (DECL_VISIBILITY_SPECIFIED (t))
8343           {
8344             DECL_VISIBILITY_SPECIFIED (r) = 0;
8345             DECL_ATTRIBUTES (r)
8346               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
8347           }
8348         determine_visibility (r);
8349
8350         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8351                                         args, complain, in_decl);
8352       }
8353       break;
8354
8355     case PARM_DECL:
8356       {
8357         tree type = NULL_TREE;
8358         int i, len = 1;
8359         tree expanded_types = NULL_TREE;
8360         tree prev_r = NULL_TREE;
8361         tree first_r = NULL_TREE;
8362
8363         if (FUNCTION_PARAMETER_PACK_P (t))
8364           {
8365             /* If there is a local specialization that isn't a
8366                parameter pack, it means that we're doing a "simple"
8367                substitution from inside tsubst_pack_expansion. Just
8368                return the local specialization (which will be a single
8369                parm).  */
8370             tree spec = retrieve_local_specialization (t);
8371             if (spec 
8372                 && TREE_CODE (spec) == PARM_DECL
8373                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
8374               return spec;
8375
8376             /* Expand the TYPE_PACK_EXPANSION that provides the types for
8377                the parameters in this function parameter pack.  */
8378             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
8379                                                     complain, in_decl);
8380             if (TREE_CODE (expanded_types) == TREE_VEC)
8381               {
8382                 len = TREE_VEC_LENGTH (expanded_types);
8383
8384                 /* Zero-length parameter packs are boring. Just substitute
8385                    into the chain.  */
8386                 if (len == 0)
8387                   return tsubst (TREE_CHAIN (t), args, complain, 
8388                                  TREE_CHAIN (t));
8389               }
8390             else
8391               {
8392                 /* All we did was update the type. Make a note of that.  */
8393                 type = expanded_types;
8394                 expanded_types = NULL_TREE;
8395               }
8396           }
8397
8398         /* Loop through all of the parameter's we'll build. When T is
8399            a function parameter pack, LEN is the number of expanded
8400            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
8401         r = NULL_TREE;
8402         for (i = 0; i < len; ++i)
8403           {
8404             prev_r = r;
8405             r = copy_node (t);
8406             if (DECL_TEMPLATE_PARM_P (t))
8407               SET_DECL_TEMPLATE_PARM_P (r);
8408
8409             if (expanded_types)
8410               /* We're on the Ith parameter of the function parameter
8411                  pack.  */
8412               {
8413                 /* Get the Ith type.  */
8414                 type = TREE_VEC_ELT (expanded_types, i);
8415
8416                 if (DECL_NAME (r))
8417                   /* Rename the parameter to include the index.  */
8418                   DECL_NAME (r) =
8419                     make_ith_pack_parameter_name (DECL_NAME (r), i);
8420               }
8421             else if (!type)
8422               /* We're dealing with a normal parameter.  */
8423               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8424
8425             type = type_decays_to (type);
8426             TREE_TYPE (r) = type;
8427             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8428
8429             if (DECL_INITIAL (r))
8430               {
8431                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
8432                   DECL_INITIAL (r) = TREE_TYPE (r);
8433                 else
8434                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
8435                                              complain, in_decl);
8436               }
8437
8438             DECL_CONTEXT (r) = NULL_TREE;
8439
8440             if (!DECL_TEMPLATE_PARM_P (r))
8441               DECL_ARG_TYPE (r) = type_passed_as (type);
8442
8443             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8444                                             args, complain, in_decl);
8445
8446             /* Keep track of the first new parameter we
8447                generate. That's what will be returned to the
8448                caller.  */
8449             if (!first_r)
8450               first_r = r;
8451
8452             /* Build a proper chain of parameters when substituting
8453                into a function parameter pack.  */
8454             if (prev_r)
8455               TREE_CHAIN (prev_r) = r;
8456           }
8457
8458         if (TREE_CHAIN (t))
8459           TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args,
8460                                    complain, TREE_CHAIN (t));
8461
8462         /* FIRST_R contains the start of the chain we've built.  */
8463         r = first_r;
8464       }
8465       break;
8466
8467     case FIELD_DECL:
8468       {
8469         tree type;
8470
8471         r = copy_decl (t);
8472         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8473         if (type == error_mark_node)
8474           return error_mark_node;
8475         TREE_TYPE (r) = type;
8476         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8477
8478         /* DECL_INITIAL gives the number of bits in a bit-field.  */
8479         DECL_INITIAL (r)
8480           = tsubst_expr (DECL_INITIAL (t), args,
8481                          complain, in_decl,
8482                          /*integral_constant_expression_p=*/true);
8483         /* We don't have to set DECL_CONTEXT here; it is set by
8484            finish_member_declaration.  */
8485         TREE_CHAIN (r) = NULL_TREE;
8486         if (VOID_TYPE_P (type))
8487           error ("instantiation of %q+D as type %qT", r, type);
8488
8489         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8490                                         args, complain, in_decl);
8491       }
8492       break;
8493
8494     case USING_DECL:
8495       /* We reach here only for member using decls.  */
8496       if (DECL_DEPENDENT_P (t))
8497         {
8498           r = do_class_using_decl
8499             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
8500              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
8501           if (!r)
8502             r = error_mark_node;
8503           else
8504             {
8505               TREE_PROTECTED (r) = TREE_PROTECTED (t);
8506               TREE_PRIVATE (r) = TREE_PRIVATE (t);
8507             }
8508         }
8509       else
8510         {
8511           r = copy_node (t);
8512           TREE_CHAIN (r) = NULL_TREE;
8513         }
8514       break;
8515
8516     case TYPE_DECL:
8517     case VAR_DECL:
8518       {
8519         tree argvec = NULL_TREE;
8520         tree gen_tmpl = NULL_TREE;
8521         tree spec;
8522         tree tmpl = NULL_TREE;
8523         tree ctx;
8524         tree type = NULL_TREE;
8525         bool local_p;
8526
8527         if (TREE_CODE (t) == TYPE_DECL
8528             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
8529           {
8530             /* If this is the canonical decl, we don't have to
8531                mess with instantiations, and often we can't (for
8532                typename, template type parms and such).  Note that
8533                TYPE_NAME is not correct for the above test if
8534                we've copied the type for a typedef.  */
8535             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8536             if (type == error_mark_node)
8537               return error_mark_node;
8538             r = TYPE_NAME (type);
8539             break;
8540           }
8541
8542         /* Check to see if we already have the specialization we
8543            need.  */
8544         spec = NULL_TREE;
8545         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
8546           {
8547             /* T is a static data member or namespace-scope entity.
8548                We have to substitute into namespace-scope variables
8549                (even though such entities are never templates) because
8550                of cases like:
8551                
8552                  template <class T> void f() { extern T t; }
8553
8554                where the entity referenced is not known until
8555                instantiation time.  */
8556             local_p = false;
8557             ctx = DECL_CONTEXT (t);
8558             if (DECL_CLASS_SCOPE_P (t))
8559               {
8560                 ctx = tsubst_aggr_type (ctx, args,
8561                                         complain,
8562                                         in_decl, /*entering_scope=*/1);
8563                 /* If CTX is unchanged, then T is in fact the
8564                    specialization we want.  That situation occurs when
8565                    referencing a static data member within in its own
8566                    class.  We can use pointer equality, rather than
8567                    same_type_p, because DECL_CONTEXT is always
8568                    canonical.  */
8569                 if (ctx == DECL_CONTEXT (t))
8570                   spec = t;
8571               }
8572
8573             if (!spec)
8574               {
8575                 tmpl = DECL_TI_TEMPLATE (t);
8576                 gen_tmpl = most_general_template (tmpl);
8577                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
8578                 spec = (retrieve_specialization 
8579                         (gen_tmpl, argvec,
8580                          /*class_specializations_p=*/false));
8581               }
8582           }
8583         else
8584           {
8585             /* A local variable.  */
8586             local_p = true;
8587             /* Subsequent calls to pushdecl will fill this in.  */
8588             ctx = NULL_TREE;
8589             spec = retrieve_local_specialization (t);
8590           }
8591         /* If we already have the specialization we need, there is
8592            nothing more to do.  */ 
8593         if (spec)
8594           {
8595             r = spec;
8596             break;
8597           }
8598
8599         /* Create a new node for the specialization we need.  */
8600         r = copy_decl (t);
8601         if (type == NULL_TREE)
8602           type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8603         if (TREE_CODE (r) == VAR_DECL)
8604           {
8605             /* Even if the original location is out of scope, the
8606                newly substituted one is not.  */
8607             DECL_DEAD_FOR_LOCAL (r) = 0;
8608             DECL_INITIALIZED_P (r) = 0;
8609             DECL_TEMPLATE_INSTANTIATED (r) = 0;
8610             if (type == error_mark_node)
8611               return error_mark_node;
8612             if (TREE_CODE (type) == FUNCTION_TYPE)
8613               {
8614                 /* It may seem that this case cannot occur, since:
8615
8616                      typedef void f();
8617                      void g() { f x; }
8618
8619                    declares a function, not a variable.  However:
8620       
8621                      typedef void f();
8622                      template <typename T> void g() { T t; }
8623                      template void g<f>();
8624
8625                    is an attempt to declare a variable with function
8626                    type.  */
8627                 error ("variable %qD has function type",
8628                        /* R is not yet sufficiently initialized, so we
8629                           just use its name.  */
8630                        DECL_NAME (r));
8631                 return error_mark_node;
8632               }
8633             type = complete_type (type);
8634             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
8635               = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t);
8636             type = check_var_type (DECL_NAME (r), type);
8637
8638             if (DECL_HAS_VALUE_EXPR_P (t))
8639               {
8640                 tree ve = DECL_VALUE_EXPR (t);
8641                 ve = tsubst_expr (ve, args, complain, in_decl,
8642                                   /*constant_expression_p=*/false);
8643                 SET_DECL_VALUE_EXPR (r, ve);
8644               }
8645           }
8646         else if (DECL_SELF_REFERENCE_P (t))
8647           SET_DECL_SELF_REFERENCE_P (r);
8648         TREE_TYPE (r) = type;
8649         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
8650         DECL_CONTEXT (r) = ctx;
8651         /* Clear out the mangled name and RTL for the instantiation.  */
8652         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
8653         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
8654           SET_DECL_RTL (r, NULL_RTX);
8655         /* The initializer must not be expanded until it is required;
8656            see [temp.inst].  */
8657         DECL_INITIAL (r) = NULL_TREE;
8658         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
8659           SET_DECL_RTL (r, NULL_RTX);
8660         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
8661         if (TREE_CODE (r) == VAR_DECL)
8662           {
8663             /* Possibly limit visibility based on template args.  */
8664             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
8665             if (DECL_VISIBILITY_SPECIFIED (t))
8666               {
8667                 DECL_VISIBILITY_SPECIFIED (r) = 0;
8668                 DECL_ATTRIBUTES (r)
8669                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
8670               }
8671             determine_visibility (r);
8672           }
8673         /* Preserve a typedef that names a type.  */
8674         else if (TREE_CODE (r) == TYPE_DECL
8675                  && DECL_ORIGINAL_TYPE (t)
8676                  && type != error_mark_node)
8677           {
8678             DECL_ORIGINAL_TYPE (r) = tsubst (DECL_ORIGINAL_TYPE (t),
8679                                              args, complain, in_decl);
8680             TREE_TYPE (r) = type = build_variant_type_copy (type);
8681             TYPE_NAME (type) = r;
8682           }
8683
8684         if (!local_p)
8685           {
8686             /* A static data member declaration is always marked
8687                external when it is declared in-class, even if an
8688                initializer is present.  We mimic the non-template
8689                processing here.  */
8690             DECL_EXTERNAL (r) = 1;
8691
8692             register_specialization (r, gen_tmpl, argvec, false);
8693             DECL_TEMPLATE_INFO (r) = tree_cons (tmpl, argvec, NULL_TREE);
8694             SET_DECL_IMPLICIT_INSTANTIATION (r);
8695           }
8696         else
8697           register_local_specialization (r, t);
8698
8699         TREE_CHAIN (r) = NULL_TREE;
8700
8701         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
8702                                         (int) ATTR_FLAG_TYPE_IN_PLACE,
8703                                         args, complain, in_decl);
8704         layout_decl (r, 0);
8705       }
8706       break;
8707
8708     default:
8709       gcc_unreachable ();
8710     }
8711
8712   /* Restore the file and line information.  */
8713   input_location = saved_loc;
8714
8715   return r;
8716 }
8717
8718 /* Substitute into the ARG_TYPES of a function type.  */
8719
8720 static tree
8721 tsubst_arg_types (tree arg_types,
8722                   tree args,
8723                   tsubst_flags_t complain,
8724                   tree in_decl)
8725 {
8726   tree remaining_arg_types;
8727   tree type = NULL_TREE;
8728   int i = 1;
8729   tree expanded_args = NULL_TREE;
8730   tree default_arg;
8731
8732   if (!arg_types || arg_types == void_list_node)
8733     return arg_types;
8734
8735   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
8736                                           args, complain, in_decl);
8737   if (remaining_arg_types == error_mark_node)
8738     return error_mark_node;
8739
8740   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
8741     {
8742       /* For a pack expansion, perform substitution on the
8743          entire expression. Later on, we'll handle the arguments
8744          one-by-one.  */
8745       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
8746                                             args, complain, in_decl);
8747
8748       if (TREE_CODE (expanded_args) == TREE_VEC)
8749         /* So that we'll spin through the parameters, one by one.  */
8750         i = TREE_VEC_LENGTH (expanded_args);
8751       else
8752         {
8753           /* We only partially substituted into the parameter
8754              pack. Our type is TYPE_PACK_EXPANSION.  */
8755           type = expanded_args;
8756           expanded_args = NULL_TREE;
8757         }
8758     }
8759
8760   while (i > 0) {
8761     --i;
8762     
8763     if (expanded_args)
8764       type = TREE_VEC_ELT (expanded_args, i);
8765     else if (!type)
8766       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
8767
8768     if (type == error_mark_node)
8769       return error_mark_node;
8770     if (VOID_TYPE_P (type))
8771       {
8772         if (complain & tf_error)
8773           {
8774             error ("invalid parameter type %qT", type);
8775             if (in_decl)
8776               error ("in declaration %q+D", in_decl);
8777           }
8778         return error_mark_node;
8779     }
8780     
8781     /* Do array-to-pointer, function-to-pointer conversion, and ignore
8782        top-level qualifiers as required.  */
8783     type = TYPE_MAIN_VARIANT (type_decays_to (type));
8784
8785     /* We do not substitute into default arguments here.  The standard
8786        mandates that they be instantiated only when needed, which is
8787        done in build_over_call.  */
8788     default_arg = TREE_PURPOSE (arg_types);
8789
8790     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
8791       {
8792         /* We've instantiated a template before its default arguments
8793            have been parsed.  This can happen for a nested template
8794            class, and is not an error unless we require the default
8795            argument in a call of this function.  */
8796         remaining_arg_types = 
8797           tree_cons (default_arg, type, remaining_arg_types);
8798         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
8799                        remaining_arg_types);
8800       }
8801     else
8802       remaining_arg_types = 
8803         hash_tree_cons (default_arg, type, remaining_arg_types);
8804   }
8805         
8806   return remaining_arg_types;
8807 }
8808
8809 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
8810    *not* handle the exception-specification for FNTYPE, because the
8811    initial substitution of explicitly provided template parameters
8812    during argument deduction forbids substitution into the
8813    exception-specification:
8814
8815      [temp.deduct]
8816
8817      All references in the function type of the function template to  the
8818      corresponding template parameters are replaced by the specified tem-
8819      plate argument values.  If a substitution in a template parameter or
8820      in  the function type of the function template results in an invalid
8821      type, type deduction fails.  [Note: The equivalent  substitution  in
8822      exception specifications is done only when the function is instanti-
8823      ated, at which point a program is  ill-formed  if  the  substitution
8824      results in an invalid type.]  */
8825
8826 static tree
8827 tsubst_function_type (tree t,
8828                       tree args,
8829                       tsubst_flags_t complain,
8830                       tree in_decl)
8831 {
8832   tree return_type;
8833   tree arg_types;
8834   tree fntype;
8835
8836   /* The TYPE_CONTEXT is not used for function/method types.  */
8837   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
8838
8839   /* Substitute the return type.  */
8840   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8841   if (return_type == error_mark_node)
8842     return error_mark_node;
8843   /* The standard does not presently indicate that creation of a
8844      function type with an invalid return type is a deduction failure.
8845      However, that is clearly analogous to creating an array of "void"
8846      or a reference to a reference.  This is core issue #486.  */
8847   if (TREE_CODE (return_type) == ARRAY_TYPE
8848       || TREE_CODE (return_type) == FUNCTION_TYPE)
8849     {
8850       if (complain & tf_error)
8851         {
8852           if (TREE_CODE (return_type) == ARRAY_TYPE)
8853             error ("function returning an array");
8854           else
8855             error ("function returning a function");
8856         }
8857       return error_mark_node;
8858     }
8859
8860   /* Substitute the argument types.  */
8861   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
8862                                 complain, in_decl);
8863   if (arg_types == error_mark_node)
8864     return error_mark_node;
8865
8866   /* Construct a new type node and return it.  */
8867   if (TREE_CODE (t) == FUNCTION_TYPE)
8868     fntype = build_function_type (return_type, arg_types);
8869   else
8870     {
8871       tree r = TREE_TYPE (TREE_VALUE (arg_types));
8872       if (! MAYBE_CLASS_TYPE_P (r))
8873         {
8874           /* [temp.deduct]
8875
8876              Type deduction may fail for any of the following
8877              reasons:
8878
8879              -- Attempting to create "pointer to member of T" when T
8880              is not a class type.  */
8881           if (complain & tf_error)
8882             error ("creating pointer to member function of non-class type %qT",
8883                       r);
8884           return error_mark_node;
8885         }
8886
8887       fntype = build_method_type_directly (r, return_type,
8888                                            TREE_CHAIN (arg_types));
8889     }
8890   fntype = cp_build_qualified_type_real (fntype, TYPE_QUALS (t), complain);
8891   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
8892
8893   return fntype;
8894 }
8895
8896 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
8897    ARGS into that specification, and return the substituted
8898    specification.  If there is no specification, return NULL_TREE.  */
8899
8900 static tree
8901 tsubst_exception_specification (tree fntype,
8902                                 tree args,
8903                                 tsubst_flags_t complain,
8904                                 tree in_decl)
8905 {
8906   tree specs;
8907   tree new_specs;
8908
8909   specs = TYPE_RAISES_EXCEPTIONS (fntype);
8910   new_specs = NULL_TREE;
8911   if (specs)
8912     {
8913       if (! TREE_VALUE (specs))
8914         new_specs = specs;
8915       else
8916         while (specs)
8917           {
8918             tree spec;
8919             int i, len = 1;
8920             tree expanded_specs = NULL_TREE;
8921
8922             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
8923               {
8924                 /* Expand the pack expansion type.  */
8925                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
8926                                                        args, complain,
8927                                                        in_decl);
8928
8929                 if (expanded_specs == error_mark_node)
8930                   return error_mark_node;
8931                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
8932                   len = TREE_VEC_LENGTH (expanded_specs);
8933                 else
8934                   {
8935                     /* We're substituting into a member template, so
8936                        we got a TYPE_PACK_EXPANSION back.  Add that
8937                        expansion and move on.  */
8938                     gcc_assert (TREE_CODE (expanded_specs) 
8939                                 == TYPE_PACK_EXPANSION);
8940                     new_specs = add_exception_specifier (new_specs,
8941                                                          expanded_specs,
8942                                                          complain);
8943                     specs = TREE_CHAIN (specs);
8944                     continue;
8945                   }
8946               }
8947
8948             for (i = 0; i < len; ++i)
8949               {
8950                 if (expanded_specs)
8951                   spec = TREE_VEC_ELT (expanded_specs, i);
8952                 else
8953                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
8954                 if (spec == error_mark_node)
8955                   return spec;
8956                 new_specs = add_exception_specifier (new_specs, spec, 
8957                                                      complain);
8958               }
8959
8960             specs = TREE_CHAIN (specs);
8961           }
8962     }
8963   return new_specs;
8964 }
8965
8966 /* Take the tree structure T and replace template parameters used
8967    therein with the argument vector ARGS.  IN_DECL is an associated
8968    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
8969    Issue error and warning messages under control of COMPLAIN.  Note
8970    that we must be relatively non-tolerant of extensions here, in
8971    order to preserve conformance; if we allow substitutions that
8972    should not be allowed, we may allow argument deductions that should
8973    not succeed, and therefore report ambiguous overload situations
8974    where there are none.  In theory, we could allow the substitution,
8975    but indicate that it should have failed, and allow our caller to
8976    make sure that the right thing happens, but we don't try to do this
8977    yet.
8978
8979    This function is used for dealing with types, decls and the like;
8980    for expressions, use tsubst_expr or tsubst_copy.  */
8981
8982 static tree
8983 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8984 {
8985   tree type, r;
8986
8987   if (t == NULL_TREE || t == error_mark_node
8988       || t == integer_type_node
8989       || t == void_type_node
8990       || t == char_type_node
8991       || t == unknown_type_node
8992       || TREE_CODE (t) == NAMESPACE_DECL)
8993     return t;
8994
8995   if (DECL_P (t))
8996     return tsubst_decl (t, args, complain);
8997
8998   if (args == NULL_TREE)
8999     return t;
9000
9001   if (TREE_CODE (t) == IDENTIFIER_NODE)
9002     type = IDENTIFIER_TYPE_VALUE (t);
9003   else
9004     type = TREE_TYPE (t);
9005
9006   gcc_assert (type != unknown_type_node);
9007
9008   /* Reuse typedefs.  We need to do this to handle dependent attributes,
9009      such as attribute aligned.  */
9010   if (TYPE_P (t)
9011       && TYPE_NAME (t)
9012       && TYPE_NAME (t) != TYPE_MAIN_DECL (t))
9013     {
9014       tree decl = TYPE_NAME (t);
9015       
9016       if (DECL_CLASS_SCOPE_P (decl)
9017           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
9018           && uses_template_parms (DECL_CONTEXT (decl)))
9019         {
9020           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
9021           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
9022           r = retrieve_specialization (tmpl, gen_args, false);
9023         }
9024       else if (DECL_FUNCTION_SCOPE_P (decl)
9025                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
9026                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
9027         r = retrieve_local_specialization (decl);
9028       else
9029         /* The typedef is from a non-template context.  */
9030         return t;
9031
9032       if (r)
9033         {
9034           r = TREE_TYPE (r);
9035           r = cp_build_qualified_type_real
9036             (r, cp_type_quals (t) | cp_type_quals (r),
9037              complain | tf_ignore_bad_quals);
9038           return r;
9039         }
9040       /* Else we must be instantiating the typedef, so fall through.  */
9041     }
9042
9043   if (type
9044       && TREE_CODE (t) != TYPENAME_TYPE
9045       && TREE_CODE (t) != IDENTIFIER_NODE
9046       && TREE_CODE (t) != FUNCTION_TYPE
9047       && TREE_CODE (t) != METHOD_TYPE)
9048     type = tsubst (type, args, complain, in_decl);
9049   if (type == error_mark_node)
9050     return error_mark_node;
9051
9052   switch (TREE_CODE (t))
9053     {
9054     case RECORD_TYPE:
9055     case UNION_TYPE:
9056     case ENUMERAL_TYPE:
9057       return tsubst_aggr_type (t, args, complain, in_decl,
9058                                /*entering_scope=*/0);
9059
9060     case ERROR_MARK:
9061     case IDENTIFIER_NODE:
9062     case VOID_TYPE:
9063     case REAL_TYPE:
9064     case COMPLEX_TYPE:
9065     case VECTOR_TYPE:
9066     case BOOLEAN_TYPE:
9067     case INTEGER_CST:
9068     case REAL_CST:
9069     case STRING_CST:
9070       return t;
9071
9072     case INTEGER_TYPE:
9073       if (t == integer_type_node)
9074         return t;
9075
9076       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
9077           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
9078         return t;
9079
9080       {
9081         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
9082
9083         max = tsubst_expr (omax, args, complain, in_decl,
9084                            /*integral_constant_expression_p=*/false);
9085         max = fold_decl_constant_value (max);
9086
9087         if (TREE_CODE (max) != INTEGER_CST
9088             && !at_function_scope_p ()
9089             && !value_dependent_expression_p (max))
9090           {
9091             if (complain & tf_error)
9092               error ("array bound is not an integer constant");
9093             return error_mark_node;
9094           }
9095
9096         /* [temp.deduct]
9097
9098            Type deduction may fail for any of the following
9099            reasons:
9100
9101              Attempting to create an array with a size that is
9102              zero or negative.  */
9103         if (integer_zerop (max) && !(complain & tf_error))
9104           /* We must fail if performing argument deduction (as
9105              indicated by the state of complain), so that
9106              another substitution can be found.  */
9107           return error_mark_node;
9108         else if (TREE_CODE (max) == INTEGER_CST
9109                  && INT_CST_LT (max, integer_zero_node))
9110           {
9111             if (complain & tf_error)
9112               error ("creating array with negative size (%qE)", max);
9113
9114             return error_mark_node;
9115           }
9116
9117         return compute_array_index_type (NULL_TREE, max);
9118       }
9119
9120     case TEMPLATE_TYPE_PARM:
9121     case TEMPLATE_TEMPLATE_PARM:
9122     case BOUND_TEMPLATE_TEMPLATE_PARM:
9123     case TEMPLATE_PARM_INDEX:
9124       {
9125         int idx;
9126         int level;
9127         int levels;
9128         tree arg = NULL_TREE;
9129
9130         r = NULL_TREE;
9131
9132         gcc_assert (TREE_VEC_LENGTH (args) > 0);
9133         template_parm_level_and_index (t, &level, &idx); 
9134
9135         levels = TMPL_ARGS_DEPTH (args);
9136         if (level <= levels)
9137           {
9138             arg = TMPL_ARG (args, level, idx);
9139
9140             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
9141               /* See through ARGUMENT_PACK_SELECT arguments. */
9142               arg = ARGUMENT_PACK_SELECT_ARG (arg);
9143           }
9144
9145         if (arg == error_mark_node)
9146           return error_mark_node;
9147         else if (arg != NULL_TREE)
9148           {
9149             if (ARGUMENT_PACK_P (arg))
9150               /* If ARG is an argument pack, we don't actually want to
9151                  perform a substitution here, because substitutions
9152                  for argument packs are only done
9153                  element-by-element. We can get to this point when
9154                  substituting the type of a non-type template
9155                  parameter pack, when that type actually contains
9156                  template parameter packs from an outer template, e.g.,
9157
9158                  template<typename... Types> struct A {
9159                    template<Types... Values> struct B { };
9160                  };  */
9161               return t;
9162
9163             if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
9164               {
9165                 int quals;
9166                 gcc_assert (TYPE_P (arg));
9167
9168                 /* cv-quals from the template are discarded when
9169                    substituting in a function or reference type.  */
9170                 if (TREE_CODE (arg) == FUNCTION_TYPE
9171                     || TREE_CODE (arg) == METHOD_TYPE
9172                     || TREE_CODE (arg) == REFERENCE_TYPE)
9173                   quals = cp_type_quals (arg);
9174                 else
9175                   quals = cp_type_quals (arg) | cp_type_quals (t);
9176                   
9177                 return cp_build_qualified_type_real
9178                   (arg, quals, complain | tf_ignore_bad_quals);
9179               }
9180             else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9181               {
9182                 /* We are processing a type constructed from a
9183                    template template parameter.  */
9184                 tree argvec = tsubst (TYPE_TI_ARGS (t),
9185                                       args, complain, in_decl);
9186                 if (argvec == error_mark_node)
9187                   return error_mark_node;
9188
9189                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
9190                    are resolving nested-types in the signature of a
9191                    member function templates.  Otherwise ARG is a
9192                    TEMPLATE_DECL and is the real template to be
9193                    instantiated.  */
9194                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
9195                   arg = TYPE_NAME (arg);
9196
9197                 r = lookup_template_class (arg,
9198                                            argvec, in_decl,
9199                                            DECL_CONTEXT (arg),
9200                                             /*entering_scope=*/0,
9201                                            complain);
9202                 return cp_build_qualified_type_real
9203                   (r, TYPE_QUALS (t), complain);
9204               }
9205             else
9206               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
9207               return arg;
9208           }
9209
9210         if (level == 1)
9211           /* This can happen during the attempted tsubst'ing in
9212              unify.  This means that we don't yet have any information
9213              about the template parameter in question.  */
9214           return t;
9215
9216         /* If we get here, we must have been looking at a parm for a
9217            more deeply nested template.  Make a new version of this
9218            template parameter, but with a lower level.  */
9219         switch (TREE_CODE (t))
9220           {
9221           case TEMPLATE_TYPE_PARM:
9222           case TEMPLATE_TEMPLATE_PARM:
9223           case BOUND_TEMPLATE_TEMPLATE_PARM:
9224             if (cp_type_quals (t))
9225               {
9226                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
9227                 r = cp_build_qualified_type_real
9228                   (r, cp_type_quals (t),
9229                    complain | (TREE_CODE (t) == TEMPLATE_TYPE_PARM
9230                                ? tf_ignore_bad_quals : 0));
9231               }
9232             else
9233               {
9234                 r = copy_type (t);
9235                 TEMPLATE_TYPE_PARM_INDEX (r)
9236                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
9237                                                 r, levels, args, complain);
9238                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
9239                 TYPE_MAIN_VARIANT (r) = r;
9240                 TYPE_POINTER_TO (r) = NULL_TREE;
9241                 TYPE_REFERENCE_TO (r) = NULL_TREE;
9242
9243                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
9244                   /* We have reduced the level of the template
9245                      template parameter, but not the levels of its
9246                      template parameters, so canonical_type_parameter
9247                      will not be able to find the canonical template
9248                      template parameter for this level. Thus, we
9249                      require structural equality checking to compare
9250                      TEMPLATE_TEMPLATE_PARMs. */
9251                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9252                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
9253                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9254                 else
9255                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
9256
9257                 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9258                   {
9259                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
9260                                           complain, in_decl);
9261                     if (argvec == error_mark_node)
9262                       return error_mark_node;
9263
9264                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
9265                       = tree_cons (TYPE_TI_TEMPLATE (t), argvec, NULL_TREE);
9266                   }
9267               }
9268             break;
9269
9270           case TEMPLATE_PARM_INDEX:
9271             r = reduce_template_parm_level (t, type, levels, args, complain);
9272             break;
9273
9274           default:
9275             gcc_unreachable ();
9276           }
9277
9278         return r;
9279       }
9280
9281     case TREE_LIST:
9282       {
9283         tree purpose, value, chain;
9284
9285         if (t == void_list_node)
9286           return t;
9287
9288         purpose = TREE_PURPOSE (t);
9289         if (purpose)
9290           {
9291             purpose = tsubst (purpose, args, complain, in_decl);
9292             if (purpose == error_mark_node)
9293               return error_mark_node;
9294           }
9295         value = TREE_VALUE (t);
9296         if (value)
9297           {
9298             value = tsubst (value, args, complain, in_decl);
9299             if (value == error_mark_node)
9300               return error_mark_node;
9301           }
9302         chain = TREE_CHAIN (t);
9303         if (chain && chain != void_type_node)
9304           {
9305             chain = tsubst (chain, args, complain, in_decl);
9306             if (chain == error_mark_node)
9307               return error_mark_node;
9308           }
9309         if (purpose == TREE_PURPOSE (t)
9310             && value == TREE_VALUE (t)
9311             && chain == TREE_CHAIN (t))
9312           return t;
9313         return hash_tree_cons (purpose, value, chain);
9314       }
9315
9316     case TREE_BINFO:
9317       /* We should never be tsubsting a binfo.  */
9318       gcc_unreachable ();
9319
9320     case TREE_VEC:
9321       /* A vector of template arguments.  */
9322       gcc_assert (!type);
9323       return tsubst_template_args (t, args, complain, in_decl);
9324
9325     case POINTER_TYPE:
9326     case REFERENCE_TYPE:
9327       {
9328         enum tree_code code;
9329
9330         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
9331           return t;
9332
9333         code = TREE_CODE (t);
9334
9335
9336         /* [temp.deduct]
9337
9338            Type deduction may fail for any of the following
9339            reasons:
9340
9341            -- Attempting to create a pointer to reference type.
9342            -- Attempting to create a reference to a reference type or
9343               a reference to void.
9344
9345           Core issue 106 says that creating a reference to a reference
9346           during instantiation is no longer a cause for failure. We
9347           only enforce this check in strict C++98 mode.  */
9348         if ((TREE_CODE (type) == REFERENCE_TYPE
9349              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
9350             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
9351           {
9352             static location_t last_loc;
9353
9354             /* We keep track of the last time we issued this error
9355                message to avoid spewing a ton of messages during a
9356                single bad template instantiation.  */
9357             if (complain & tf_error
9358                 && last_loc != input_location)
9359               {
9360                 if (TREE_CODE (type) == VOID_TYPE)
9361                   error ("forming reference to void");
9362                 else
9363                   error ("forming %s to reference type %qT",
9364                          (code == POINTER_TYPE) ? "pointer" : "reference",
9365                          type);
9366                 last_loc = input_location;
9367               }
9368
9369             return error_mark_node;
9370           }
9371         else if (code == POINTER_TYPE)
9372           {
9373             r = build_pointer_type (type);
9374             if (TREE_CODE (type) == METHOD_TYPE)
9375               r = build_ptrmemfunc_type (r);
9376           }
9377         else if (TREE_CODE (type) == REFERENCE_TYPE)
9378           /* In C++0x, during template argument substitution, when there is an
9379              attempt to create a reference to a reference type, reference
9380              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
9381
9382              "If a template-argument for a template-parameter T names a type
9383              that is a reference to a type A, an attempt to create the type
9384              'lvalue reference to cv T' creates the type 'lvalue reference to
9385              A,' while an attempt to create the type type rvalue reference to
9386              cv T' creates the type T"
9387           */
9388           r = cp_build_reference_type
9389               (TREE_TYPE (type),
9390                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
9391         else
9392           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
9393         r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
9394
9395         if (r != error_mark_node)
9396           /* Will this ever be needed for TYPE_..._TO values?  */
9397           layout_type (r);
9398
9399         return r;
9400       }
9401     case OFFSET_TYPE:
9402       {
9403         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
9404         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
9405           {
9406             /* [temp.deduct]
9407
9408                Type deduction may fail for any of the following
9409                reasons:
9410
9411                -- Attempting to create "pointer to member of T" when T
9412                   is not a class type.  */
9413             if (complain & tf_error)
9414               error ("creating pointer to member of non-class type %qT", r);
9415             return error_mark_node;
9416           }
9417         if (TREE_CODE (type) == REFERENCE_TYPE)
9418           {
9419             if (complain & tf_error)
9420               error ("creating pointer to member reference type %qT", type);
9421             return error_mark_node;
9422           }
9423         if (TREE_CODE (type) == VOID_TYPE)
9424           {
9425             if (complain & tf_error)
9426               error ("creating pointer to member of type void");
9427             return error_mark_node;
9428           }
9429         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
9430         if (TREE_CODE (type) == FUNCTION_TYPE)
9431           {
9432             /* The type of the implicit object parameter gets its
9433                cv-qualifiers from the FUNCTION_TYPE. */
9434             tree method_type;
9435             tree this_type = cp_build_qualified_type (TYPE_MAIN_VARIANT (r),
9436                                                       cp_type_quals (type));
9437             tree memptr;
9438             method_type = build_method_type_directly (this_type,
9439                                                       TREE_TYPE (type),
9440                                                       TYPE_ARG_TYPES (type));
9441             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
9442             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
9443                                                  complain);
9444           }
9445         else
9446           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
9447                                                TYPE_QUALS (t),
9448                                                complain);
9449       }
9450     case FUNCTION_TYPE:
9451     case METHOD_TYPE:
9452       {
9453         tree fntype;
9454         tree specs;
9455         fntype = tsubst_function_type (t, args, complain, in_decl);
9456         if (fntype == error_mark_node)
9457           return error_mark_node;
9458
9459         /* Substitute the exception specification.  */
9460         specs = tsubst_exception_specification (t, args, complain,
9461                                                 in_decl);
9462         if (specs == error_mark_node)
9463           return error_mark_node;
9464         if (specs)
9465           fntype = build_exception_variant (fntype, specs);
9466         return fntype;
9467       }
9468     case ARRAY_TYPE:
9469       {
9470         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
9471         if (domain == error_mark_node)
9472           return error_mark_node;
9473
9474         /* As an optimization, we avoid regenerating the array type if
9475            it will obviously be the same as T.  */
9476         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
9477           return t;
9478
9479         /* These checks should match the ones in grokdeclarator.
9480
9481            [temp.deduct]
9482
9483            The deduction may fail for any of the following reasons:
9484
9485            -- Attempting to create an array with an element type that
9486               is void, a function type, or a reference type, or [DR337]
9487               an abstract class type.  */
9488         if (TREE_CODE (type) == VOID_TYPE
9489             || TREE_CODE (type) == FUNCTION_TYPE
9490             || TREE_CODE (type) == REFERENCE_TYPE)
9491           {
9492             if (complain & tf_error)
9493               error ("creating array of %qT", type);
9494             return error_mark_node;
9495           }
9496         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
9497           {
9498             if (complain & tf_error)
9499               error ("creating array of %qT, which is an abstract class type",
9500                      type);
9501             return error_mark_node;
9502           }
9503
9504         r = build_cplus_array_type (type, domain);
9505
9506         if (TYPE_USER_ALIGN (t))
9507           {
9508             TYPE_ALIGN (r) = TYPE_ALIGN (t);
9509             TYPE_USER_ALIGN (r) = 1;
9510           }
9511
9512         return r;
9513       }
9514
9515     case PLUS_EXPR:
9516     case MINUS_EXPR:
9517       {
9518         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9519         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
9520
9521         if (e1 == error_mark_node || e2 == error_mark_node)
9522           return error_mark_node;
9523
9524         return fold_build2 (TREE_CODE (t), TREE_TYPE (t), e1, e2);
9525       }
9526
9527     case NEGATE_EXPR:
9528     case NOP_EXPR:
9529       {
9530         tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9531         if (e == error_mark_node)
9532           return error_mark_node;
9533
9534         return fold_build1 (TREE_CODE (t), TREE_TYPE (t), e);
9535       }
9536
9537     case TYPENAME_TYPE:
9538       {
9539         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
9540                                      in_decl, /*entering_scope=*/1);
9541         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
9542                               complain, in_decl);
9543
9544         if (ctx == error_mark_node || f == error_mark_node)
9545           return error_mark_node;
9546
9547         if (!MAYBE_CLASS_TYPE_P (ctx))
9548           {
9549             if (complain & tf_error)
9550               error ("%qT is not a class, struct, or union type", ctx);
9551             return error_mark_node;
9552           }
9553         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
9554           {
9555             /* Normally, make_typename_type does not require that the CTX
9556                have complete type in order to allow things like:
9557
9558                  template <class T> struct S { typename S<T>::X Y; };
9559
9560                But, such constructs have already been resolved by this
9561                point, so here CTX really should have complete type, unless
9562                it's a partial instantiation.  */
9563             ctx = complete_type (ctx);
9564             if (!COMPLETE_TYPE_P (ctx))
9565               {
9566                 if (complain & tf_error)
9567                   cxx_incomplete_type_error (NULL_TREE, ctx);
9568                 return error_mark_node;
9569               }
9570           }
9571
9572         f = make_typename_type (ctx, f, typename_type,
9573                                 (complain & tf_error) | tf_keep_type_decl);
9574         if (f == error_mark_node)
9575           return f;
9576         if (TREE_CODE (f) == TYPE_DECL)
9577           {
9578             complain |= tf_ignore_bad_quals;
9579             f = TREE_TYPE (f);
9580           }
9581
9582         if (TREE_CODE (f) != TYPENAME_TYPE)
9583           {
9584             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
9585               error ("%qT resolves to %qT, which is not an enumeration type",
9586                      t, f);
9587             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
9588               error ("%qT resolves to %qT, which is is not a class type",
9589                      t, f);
9590           }
9591
9592         return cp_build_qualified_type_real
9593           (f, cp_type_quals (f) | cp_type_quals (t), complain);
9594       }
9595
9596     case UNBOUND_CLASS_TEMPLATE:
9597       {
9598         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
9599                                      in_decl, /*entering_scope=*/1);
9600         tree name = TYPE_IDENTIFIER (t);
9601         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
9602
9603         if (ctx == error_mark_node || name == error_mark_node)
9604           return error_mark_node;
9605
9606         if (parm_list)
9607           parm_list = tsubst_template_parms (parm_list, args, complain);
9608         return make_unbound_class_template (ctx, name, parm_list, complain);
9609       }
9610
9611     case INDIRECT_REF:
9612     case ADDR_EXPR:
9613     case CALL_EXPR:
9614       gcc_unreachable ();
9615
9616     case ARRAY_REF:
9617       {
9618         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9619         tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl,
9620                                /*integral_constant_expression_p=*/false);
9621         if (e1 == error_mark_node || e2 == error_mark_node)
9622           return error_mark_node;
9623
9624         return build_nt (ARRAY_REF, e1, e2, NULL_TREE, NULL_TREE);
9625       }
9626
9627     case SCOPE_REF:
9628       {
9629         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
9630         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
9631         if (e1 == error_mark_node || e2 == error_mark_node)
9632           return error_mark_node;
9633
9634         return build_qualified_name (/*type=*/NULL_TREE,
9635                                      e1, e2, QUALIFIED_NAME_IS_TEMPLATE (t));
9636       }
9637
9638     case TYPEOF_TYPE:
9639       {
9640         tree type;
9641
9642         type = finish_typeof (tsubst_expr 
9643                               (TYPEOF_TYPE_EXPR (t), args,
9644                                complain, in_decl,
9645                                /*integral_constant_expression_p=*/false));
9646         return cp_build_qualified_type_real (type,
9647                                              cp_type_quals (t)
9648                                              | cp_type_quals (type),
9649                                              complain);
9650       }
9651
9652     case DECLTYPE_TYPE:
9653       {
9654         tree type;
9655
9656         ++skip_evaluation;
9657
9658         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
9659                             complain, in_decl,
9660                             /*integral_constant_expression_p=*/false);
9661
9662         --skip_evaluation;
9663
9664         type =
9665           finish_decltype_type (type,
9666                                 DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
9667         return cp_build_qualified_type_real (type,
9668                                              cp_type_quals (t)
9669                                              | cp_type_quals (type),
9670                                              complain);
9671       }
9672
9673     case TYPE_ARGUMENT_PACK:
9674     case NONTYPE_ARGUMENT_PACK:
9675       {
9676         tree r = make_node (TREE_CODE (t));
9677         tree packed_out = 
9678           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
9679                                 args,
9680                                 complain,
9681                                 in_decl);
9682         SET_ARGUMENT_PACK_ARGS (r, packed_out);
9683
9684         /* For template nontype argument packs, also substitute into
9685            the type.  */
9686         if (TREE_CODE (t) == NONTYPE_ARGUMENT_PACK)
9687           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
9688
9689         return r;
9690       }
9691       break;
9692
9693     default:
9694       sorry ("use of %qs in template",
9695              tree_code_name [(int) TREE_CODE (t)]);
9696       return error_mark_node;
9697     }
9698 }
9699
9700 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
9701    type of the expression on the left-hand side of the "." or "->"
9702    operator.  */
9703
9704 static tree
9705 tsubst_baselink (tree baselink, tree object_type,
9706                  tree args, tsubst_flags_t complain, tree in_decl)
9707 {
9708     tree name;
9709     tree qualifying_scope;
9710     tree fns;
9711     tree optype;
9712     tree template_args = 0;
9713     bool template_id_p = false;
9714
9715     /* A baselink indicates a function from a base class.  Both the
9716        BASELINK_ACCESS_BINFO and the base class referenced may
9717        indicate bases of the template class, rather than the
9718        instantiated class.  In addition, lookups that were not
9719        ambiguous before may be ambiguous now.  Therefore, we perform
9720        the lookup again.  */
9721     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
9722     qualifying_scope = tsubst (qualifying_scope, args,
9723                                complain, in_decl);
9724     fns = BASELINK_FUNCTIONS (baselink);
9725     optype = BASELINK_OPTYPE (baselink);
9726     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
9727       {
9728         template_id_p = true;
9729         template_args = TREE_OPERAND (fns, 1);
9730         fns = TREE_OPERAND (fns, 0);
9731         if (template_args)
9732           template_args = tsubst_template_args (template_args, args,
9733                                                 complain, in_decl);
9734       }
9735     name = DECL_NAME (get_first_fn (fns));
9736     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
9737
9738     /* If lookup found a single function, mark it as used at this
9739        point.  (If it lookup found multiple functions the one selected
9740        later by overload resolution will be marked as used at that
9741        point.)  */
9742     if (BASELINK_P (baselink))
9743       fns = BASELINK_FUNCTIONS (baselink);
9744     if (!template_id_p && !really_overloaded_fn (fns))
9745       mark_used (OVL_CURRENT (fns));
9746
9747     /* Add back the template arguments, if present.  */
9748     if (BASELINK_P (baselink) && template_id_p)
9749       BASELINK_FUNCTIONS (baselink)
9750         = build_nt (TEMPLATE_ID_EXPR,
9751                     BASELINK_FUNCTIONS (baselink),
9752                     template_args);
9753     /* Update the conversion operator type.  */
9754     BASELINK_OPTYPE (baselink) 
9755       = tsubst (optype, args, complain, in_decl);
9756
9757     if (!object_type)
9758       object_type = current_class_type;
9759     return adjust_result_of_qualified_name_lookup (baselink,
9760                                                    qualifying_scope,
9761                                                    object_type);
9762 }
9763
9764 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
9765    true if the qualified-id will be a postfix-expression in-and-of
9766    itself; false if more of the postfix-expression follows the
9767    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
9768    of "&".  */
9769
9770 static tree
9771 tsubst_qualified_id (tree qualified_id, tree args,
9772                      tsubst_flags_t complain, tree in_decl,
9773                      bool done, bool address_p)
9774 {
9775   tree expr;
9776   tree scope;
9777   tree name;
9778   bool is_template;
9779   tree template_args;
9780
9781   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
9782
9783   /* Figure out what name to look up.  */
9784   name = TREE_OPERAND (qualified_id, 1);
9785   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
9786     {
9787       is_template = true;
9788       template_args = TREE_OPERAND (name, 1);
9789       if (template_args)
9790         template_args = tsubst_template_args (template_args, args,
9791                                               complain, in_decl);
9792       name = TREE_OPERAND (name, 0);
9793     }
9794   else
9795     {
9796       is_template = false;
9797       template_args = NULL_TREE;
9798     }
9799
9800   /* Substitute into the qualifying scope.  When there are no ARGS, we
9801      are just trying to simplify a non-dependent expression.  In that
9802      case the qualifying scope may be dependent, and, in any case,
9803      substituting will not help.  */
9804   scope = TREE_OPERAND (qualified_id, 0);
9805   if (args)
9806     {
9807       scope = tsubst (scope, args, complain, in_decl);
9808       expr = tsubst_copy (name, args, complain, in_decl);
9809     }
9810   else
9811     expr = name;
9812
9813   if (dependent_type_p (scope))
9814     return build_qualified_name (/*type=*/NULL_TREE,
9815                                  scope, expr,
9816                                  QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
9817
9818   if (!BASELINK_P (name) && !DECL_P (expr))
9819     {
9820       if (TREE_CODE (expr) == BIT_NOT_EXPR)
9821         /* If this were actually a destructor call, it would have been
9822            parsed as such by the parser.  */
9823         expr = error_mark_node;
9824       else
9825         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
9826       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
9827                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
9828         {
9829           if (complain & tf_error)
9830             {
9831               error ("dependent-name %qE is parsed as a non-type, but "
9832                      "instantiation yields a type", qualified_id);
9833               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
9834             }
9835           return error_mark_node;
9836         }
9837     }
9838
9839   if (DECL_P (expr))
9840     {
9841       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
9842                                            scope);
9843       /* Remember that there was a reference to this entity.  */
9844       mark_used (expr);
9845     }
9846
9847   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
9848     {
9849       if (complain & tf_error)
9850         qualified_name_lookup_error (scope,
9851                                      TREE_OPERAND (qualified_id, 1),
9852                                      expr, input_location);
9853       return error_mark_node;
9854     }
9855
9856   if (is_template)
9857     expr = lookup_template_function (expr, template_args);
9858
9859   if (expr == error_mark_node && complain & tf_error)
9860     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
9861                                  expr, input_location);
9862   else if (TYPE_P (scope))
9863     {
9864       expr = (adjust_result_of_qualified_name_lookup
9865               (expr, scope, current_class_type));
9866       expr = (finish_qualified_id_expr
9867               (scope, expr, done, address_p,
9868                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
9869                /*template_arg_p=*/false));
9870     }
9871
9872   /* Expressions do not generally have reference type.  */
9873   if (TREE_CODE (expr) != SCOPE_REF
9874       /* However, if we're about to form a pointer-to-member, we just
9875          want the referenced member referenced.  */
9876       && TREE_CODE (expr) != OFFSET_REF)
9877     expr = convert_from_reference (expr);
9878
9879   return expr;
9880 }
9881
9882 /* Like tsubst, but deals with expressions.  This function just replaces
9883    template parms; to finish processing the resultant expression, use
9884    tsubst_expr.  */
9885
9886 static tree
9887 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9888 {
9889   enum tree_code code;
9890   tree r;
9891
9892   if (t == NULL_TREE || t == error_mark_node)
9893     return t;
9894
9895   code = TREE_CODE (t);
9896
9897   switch (code)
9898     {
9899     case PARM_DECL:
9900       r = retrieve_local_specialization (t);
9901
9902       if (r == NULL)
9903         {
9904           /* This can happen for a parameter name used later in a function
9905              declaration (such as in a late-specified return type).  Just
9906              make a dummy decl, since it's only used for its type.  */
9907           gcc_assert (skip_evaluation);   
9908           r = tsubst_decl (t, args, complain);
9909           /* Give it the template pattern as its context; its true context
9910              hasn't been instantiated yet and this is good enough for
9911              mangling.  */
9912           DECL_CONTEXT (r) = DECL_CONTEXT (t);
9913         }
9914       
9915       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
9916         r = ARGUMENT_PACK_SELECT_ARG (r);
9917       mark_used (r);
9918       return r;
9919
9920     case CONST_DECL:
9921       {
9922         tree enum_type;
9923         tree v;
9924
9925         if (DECL_TEMPLATE_PARM_P (t))
9926           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
9927         /* There is no need to substitute into namespace-scope
9928            enumerators.  */
9929         if (DECL_NAMESPACE_SCOPE_P (t))
9930           return t;
9931         /* If ARGS is NULL, then T is known to be non-dependent.  */
9932         if (args == NULL_TREE)
9933           return integral_constant_value (t);
9934
9935         /* Unfortunately, we cannot just call lookup_name here.
9936            Consider:
9937
9938              template <int I> int f() {
9939              enum E { a = I };
9940              struct S { void g() { E e = a; } };
9941              };
9942
9943            When we instantiate f<7>::S::g(), say, lookup_name is not
9944            clever enough to find f<7>::a.  */
9945         enum_type
9946           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
9947                               /*entering_scope=*/0);
9948
9949         for (v = TYPE_VALUES (enum_type);
9950              v != NULL_TREE;
9951              v = TREE_CHAIN (v))
9952           if (TREE_PURPOSE (v) == DECL_NAME (t))
9953             return TREE_VALUE (v);
9954
9955           /* We didn't find the name.  That should never happen; if
9956              name-lookup found it during preliminary parsing, we
9957              should find it again here during instantiation.  */
9958         gcc_unreachable ();
9959       }
9960       return t;
9961
9962     case FIELD_DECL:
9963       if (DECL_CONTEXT (t))
9964         {
9965           tree ctx;
9966
9967           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
9968                                   /*entering_scope=*/1);
9969           if (ctx != DECL_CONTEXT (t))
9970             {
9971               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
9972               if (!r)
9973                 {
9974                   if (complain & tf_error)
9975                     error ("using invalid field %qD", t);
9976                   return error_mark_node;
9977                 }
9978               return r;
9979             }
9980         }
9981
9982       return t;
9983
9984     case VAR_DECL:
9985     case FUNCTION_DECL:
9986       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
9987           || local_variable_p (t))
9988         t = tsubst (t, args, complain, in_decl);
9989       mark_used (t);
9990       return t;
9991
9992     case BASELINK:
9993       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
9994
9995     case TEMPLATE_DECL:
9996       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
9997         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
9998                        args, complain, in_decl);
9999       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
10000         return tsubst (t, args, complain, in_decl);
10001       else if (DECL_CLASS_SCOPE_P (t)
10002                && uses_template_parms (DECL_CONTEXT (t)))
10003         {
10004           /* Template template argument like the following example need
10005              special treatment:
10006
10007                template <template <class> class TT> struct C {};
10008                template <class T> struct D {
10009                  template <class U> struct E {};
10010                  C<E> c;                                // #1
10011                };
10012                D<int> d;                                // #2
10013
10014              We are processing the template argument `E' in #1 for
10015              the template instantiation #2.  Originally, `E' is a
10016              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
10017              have to substitute this with one having context `D<int>'.  */
10018
10019           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
10020           return lookup_field (context, DECL_NAME(t), 0, false);
10021         }
10022       else
10023         /* Ordinary template template argument.  */
10024         return t;
10025
10026     case CAST_EXPR:
10027     case REINTERPRET_CAST_EXPR:
10028     case CONST_CAST_EXPR:
10029     case STATIC_CAST_EXPR:
10030     case DYNAMIC_CAST_EXPR:
10031     case NOP_EXPR:
10032       return build1
10033         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10034          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10035
10036     case SIZEOF_EXPR:
10037       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
10038         {
10039           /* We only want to compute the number of arguments.  */
10040           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
10041                                                 complain, in_decl);
10042           int len = 0;
10043
10044           if (TREE_CODE (expanded) == TREE_VEC)
10045             len = TREE_VEC_LENGTH (expanded);
10046
10047           if (expanded == error_mark_node)
10048             return error_mark_node;
10049           else if (PACK_EXPANSION_P (expanded)
10050                    || (TREE_CODE (expanded) == TREE_VEC
10051                        && len > 0
10052                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
10053             {
10054               if (TREE_CODE (expanded) == TREE_VEC)
10055                 expanded = TREE_VEC_ELT (expanded, len - 1);
10056
10057               if (TYPE_P (expanded))
10058                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
10059                                                    complain & tf_error);
10060               else
10061                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
10062                                                    complain & tf_error);
10063             }
10064           else
10065             return build_int_cst (size_type_node, len);
10066         }
10067       /* Fall through */
10068
10069     case INDIRECT_REF:
10070     case NEGATE_EXPR:
10071     case TRUTH_NOT_EXPR:
10072     case BIT_NOT_EXPR:
10073     case ADDR_EXPR:
10074     case UNARY_PLUS_EXPR:      /* Unary + */
10075     case ALIGNOF_EXPR:
10076     case ARROW_EXPR:
10077     case THROW_EXPR:
10078     case TYPEID_EXPR:
10079     case REALPART_EXPR:
10080     case IMAGPART_EXPR:
10081       return build1
10082         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10083          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10084
10085     case COMPONENT_REF:
10086       {
10087         tree object;
10088         tree name;
10089
10090         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
10091         name = TREE_OPERAND (t, 1);
10092         if (TREE_CODE (name) == BIT_NOT_EXPR)
10093           {
10094             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10095                                 complain, in_decl);
10096             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10097           }
10098         else if (TREE_CODE (name) == SCOPE_REF
10099                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
10100           {
10101             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
10102                                      complain, in_decl);
10103             name = TREE_OPERAND (name, 1);
10104             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10105                                 complain, in_decl);
10106             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10107             name = build_qualified_name (/*type=*/NULL_TREE,
10108                                          base, name,
10109                                          /*template_p=*/false);
10110           }
10111         else if (TREE_CODE (name) == BASELINK)
10112           name = tsubst_baselink (name,
10113                                   non_reference (TREE_TYPE (object)),
10114                                   args, complain,
10115                                   in_decl);
10116         else
10117           name = tsubst_copy (name, args, complain, in_decl);
10118         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
10119       }
10120
10121     case PLUS_EXPR:
10122     case MINUS_EXPR:
10123     case MULT_EXPR:
10124     case TRUNC_DIV_EXPR:
10125     case CEIL_DIV_EXPR:
10126     case FLOOR_DIV_EXPR:
10127     case ROUND_DIV_EXPR:
10128     case EXACT_DIV_EXPR:
10129     case BIT_AND_EXPR:
10130     case BIT_IOR_EXPR:
10131     case BIT_XOR_EXPR:
10132     case TRUNC_MOD_EXPR:
10133     case FLOOR_MOD_EXPR:
10134     case TRUTH_ANDIF_EXPR:
10135     case TRUTH_ORIF_EXPR:
10136     case TRUTH_AND_EXPR:
10137     case TRUTH_OR_EXPR:
10138     case RSHIFT_EXPR:
10139     case LSHIFT_EXPR:
10140     case RROTATE_EXPR:
10141     case LROTATE_EXPR:
10142     case EQ_EXPR:
10143     case NE_EXPR:
10144     case MAX_EXPR:
10145     case MIN_EXPR:
10146     case LE_EXPR:
10147     case GE_EXPR:
10148     case LT_EXPR:
10149     case GT_EXPR:
10150     case COMPOUND_EXPR:
10151     case DOTSTAR_EXPR:
10152     case MEMBER_REF:
10153     case PREDECREMENT_EXPR:
10154     case PREINCREMENT_EXPR:
10155     case POSTDECREMENT_EXPR:
10156     case POSTINCREMENT_EXPR:
10157       return build_nt
10158         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10159          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10160
10161     case SCOPE_REF:
10162       return build_qualified_name (/*type=*/NULL_TREE,
10163                                    tsubst_copy (TREE_OPERAND (t, 0),
10164                                                 args, complain, in_decl),
10165                                    tsubst_copy (TREE_OPERAND (t, 1),
10166                                                 args, complain, in_decl),
10167                                    QUALIFIED_NAME_IS_TEMPLATE (t));
10168
10169     case ARRAY_REF:
10170       return build_nt
10171         (ARRAY_REF,
10172          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10173          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10174          NULL_TREE, NULL_TREE);
10175
10176     case CALL_EXPR:
10177       {
10178         int n = VL_EXP_OPERAND_LENGTH (t);
10179         tree result = build_vl_exp (CALL_EXPR, n);
10180         int i;
10181         for (i = 0; i < n; i++)
10182           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
10183                                              complain, in_decl);
10184         return result;
10185       }
10186
10187     case COND_EXPR:
10188     case MODOP_EXPR:
10189     case PSEUDO_DTOR_EXPR:
10190       {
10191         r = build_nt
10192           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10193            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10194            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10195         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
10196         return r;
10197       }
10198
10199     case NEW_EXPR:
10200       {
10201         r = build_nt
10202         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10203          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10204          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10205         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
10206         return r;
10207       }
10208
10209     case DELETE_EXPR:
10210       {
10211         r = build_nt
10212         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10213          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10214         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
10215         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
10216         return r;
10217       }
10218
10219     case TEMPLATE_ID_EXPR:
10220       {
10221         /* Substituted template arguments */
10222         tree fn = TREE_OPERAND (t, 0);
10223         tree targs = TREE_OPERAND (t, 1);
10224
10225         fn = tsubst_copy (fn, args, complain, in_decl);
10226         if (targs)
10227           targs = tsubst_template_args (targs, args, complain, in_decl);
10228
10229         return lookup_template_function (fn, targs);
10230       }
10231
10232     case TREE_LIST:
10233       {
10234         tree purpose, value, chain;
10235
10236         if (t == void_list_node)
10237           return t;
10238
10239         purpose = TREE_PURPOSE (t);
10240         if (purpose)
10241           purpose = tsubst_copy (purpose, args, complain, in_decl);
10242         value = TREE_VALUE (t);
10243         if (value)
10244           value = tsubst_copy (value, args, complain, in_decl);
10245         chain = TREE_CHAIN (t);
10246         if (chain && chain != void_type_node)
10247           chain = tsubst_copy (chain, args, complain, in_decl);
10248         if (purpose == TREE_PURPOSE (t)
10249             && value == TREE_VALUE (t)
10250             && chain == TREE_CHAIN (t))
10251           return t;
10252         return tree_cons (purpose, value, chain);
10253       }
10254
10255     case RECORD_TYPE:
10256     case UNION_TYPE:
10257     case ENUMERAL_TYPE:
10258     case INTEGER_TYPE:
10259     case TEMPLATE_TYPE_PARM:
10260     case TEMPLATE_TEMPLATE_PARM:
10261     case BOUND_TEMPLATE_TEMPLATE_PARM:
10262     case TEMPLATE_PARM_INDEX:
10263     case POINTER_TYPE:
10264     case REFERENCE_TYPE:
10265     case OFFSET_TYPE:
10266     case FUNCTION_TYPE:
10267     case METHOD_TYPE:
10268     case ARRAY_TYPE:
10269     case TYPENAME_TYPE:
10270     case UNBOUND_CLASS_TEMPLATE:
10271     case TYPEOF_TYPE:
10272     case DECLTYPE_TYPE:
10273     case TYPE_DECL:
10274       return tsubst (t, args, complain, in_decl);
10275
10276     case IDENTIFIER_NODE:
10277       if (IDENTIFIER_TYPENAME_P (t))
10278         {
10279           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10280           return mangle_conv_op_name_for_type (new_type);
10281         }
10282       else
10283         return t;
10284
10285     case CONSTRUCTOR:
10286       /* This is handled by tsubst_copy_and_build.  */
10287       gcc_unreachable ();
10288
10289     case VA_ARG_EXPR:
10290       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
10291                                           in_decl),
10292                              tsubst (TREE_TYPE (t), args, complain, in_decl));
10293
10294     case CLEANUP_POINT_EXPR:
10295       /* We shouldn't have built any of these during initial template
10296          generation.  Instead, they should be built during instantiation
10297          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
10298       gcc_unreachable ();
10299
10300     case OFFSET_REF:
10301       mark_used (TREE_OPERAND (t, 1));
10302       return t;
10303
10304     case EXPR_PACK_EXPANSION:
10305       error ("invalid use of pack expansion expression");
10306       return error_mark_node;
10307
10308     case NONTYPE_ARGUMENT_PACK:
10309       error ("use %<...%> to expand argument pack");
10310       return error_mark_node;
10311
10312     default:
10313       return t;
10314     }
10315 }
10316
10317 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
10318
10319 static tree
10320 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
10321                     tree in_decl)
10322 {
10323   tree new_clauses = NULL, nc, oc;
10324
10325   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
10326     {
10327       nc = copy_node (oc);
10328       OMP_CLAUSE_CHAIN (nc) = new_clauses;
10329       new_clauses = nc;
10330
10331       switch (OMP_CLAUSE_CODE (nc))
10332         {
10333         case OMP_CLAUSE_LASTPRIVATE:
10334           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
10335             {
10336               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
10337               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
10338                            in_decl, /*integral_constant_expression_p=*/false);
10339               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
10340                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
10341             }
10342           /* FALLTHRU */
10343         case OMP_CLAUSE_PRIVATE:
10344         case OMP_CLAUSE_SHARED:
10345         case OMP_CLAUSE_FIRSTPRIVATE:
10346         case OMP_CLAUSE_REDUCTION:
10347         case OMP_CLAUSE_COPYIN:
10348         case OMP_CLAUSE_COPYPRIVATE:
10349         case OMP_CLAUSE_IF:
10350         case OMP_CLAUSE_NUM_THREADS:
10351         case OMP_CLAUSE_SCHEDULE:
10352         case OMP_CLAUSE_COLLAPSE:
10353           OMP_CLAUSE_OPERAND (nc, 0)
10354             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
10355                            in_decl, /*integral_constant_expression_p=*/false);
10356           break;
10357         case OMP_CLAUSE_NOWAIT:
10358         case OMP_CLAUSE_ORDERED:
10359         case OMP_CLAUSE_DEFAULT:
10360         case OMP_CLAUSE_UNTIED:
10361           break;
10362         default:
10363           gcc_unreachable ();
10364         }
10365     }
10366
10367   return finish_omp_clauses (nreverse (new_clauses));
10368 }
10369
10370 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
10371
10372 static tree
10373 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
10374                           tree in_decl)
10375 {
10376 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
10377
10378   tree purpose, value, chain;
10379
10380   if (t == NULL)
10381     return t;
10382
10383   if (TREE_CODE (t) != TREE_LIST)
10384     return tsubst_copy_and_build (t, args, complain, in_decl,
10385                                   /*function_p=*/false,
10386                                   /*integral_constant_expression_p=*/false);
10387
10388   if (t == void_list_node)
10389     return t;
10390
10391   purpose = TREE_PURPOSE (t);
10392   if (purpose)
10393     purpose = RECUR (purpose);
10394   value = TREE_VALUE (t);
10395   if (value)
10396     value = RECUR (value);
10397   chain = TREE_CHAIN (t);
10398   if (chain && chain != void_type_node)
10399     chain = RECUR (chain);
10400   return tree_cons (purpose, value, chain);
10401 #undef RECUR
10402 }
10403
10404 /* Substitute one OMP_FOR iterator.  */
10405
10406 static void
10407 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
10408                          tree condv, tree incrv, tree *clauses,
10409                          tree args, tsubst_flags_t complain, tree in_decl,
10410                          bool integral_constant_expression_p)
10411 {
10412 #define RECUR(NODE)                             \
10413   tsubst_expr ((NODE), args, complain, in_decl, \
10414                integral_constant_expression_p)
10415   tree decl, init, cond, incr, auto_node;
10416
10417   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
10418   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
10419   decl = RECUR (TREE_OPERAND (init, 0));
10420   init = TREE_OPERAND (init, 1);
10421   auto_node = type_uses_auto (TREE_TYPE (decl));
10422   if (auto_node && init)
10423     {
10424       tree init_expr = init;
10425       if (TREE_CODE (init_expr) == DECL_EXPR)
10426         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
10427       init_expr = RECUR (init_expr);
10428       TREE_TYPE (decl)
10429         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
10430     }
10431   gcc_assert (!type_dependent_expression_p (decl));
10432
10433   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
10434     {
10435       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
10436       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
10437       if (TREE_CODE (incr) == MODIFY_EXPR)
10438         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
10439                                     RECUR (TREE_OPERAND (incr, 1)),
10440                                     complain);
10441       else
10442         incr = RECUR (incr);
10443       TREE_VEC_ELT (declv, i) = decl;
10444       TREE_VEC_ELT (initv, i) = init;
10445       TREE_VEC_ELT (condv, i) = cond;
10446       TREE_VEC_ELT (incrv, i) = incr;
10447       return;
10448     }
10449
10450   if (init && TREE_CODE (init) != DECL_EXPR)
10451     {
10452       tree c;
10453       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
10454         {
10455           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
10456                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
10457               && OMP_CLAUSE_DECL (c) == decl)
10458             break;
10459           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
10460                    && OMP_CLAUSE_DECL (c) == decl)
10461             error ("iteration variable %qD should not be firstprivate", decl);
10462           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
10463                    && OMP_CLAUSE_DECL (c) == decl)
10464             error ("iteration variable %qD should not be reduction", decl);
10465         }
10466       if (c == NULL)
10467         {
10468           c = build_omp_clause (OMP_CLAUSE_PRIVATE);
10469           OMP_CLAUSE_DECL (c) = decl;
10470           c = finish_omp_clauses (c);
10471           if (c)
10472             {
10473               OMP_CLAUSE_CHAIN (c) = *clauses;
10474               *clauses = c;
10475             }
10476         }
10477     }
10478   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
10479   if (COMPARISON_CLASS_P (cond))
10480     cond = build2 (TREE_CODE (cond), boolean_type_node,
10481                    RECUR (TREE_OPERAND (cond, 0)),
10482                    RECUR (TREE_OPERAND (cond, 1)));
10483   else
10484     cond = RECUR (cond);
10485   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
10486   switch (TREE_CODE (incr))
10487     {
10488     case PREINCREMENT_EXPR:
10489     case PREDECREMENT_EXPR:
10490     case POSTINCREMENT_EXPR:
10491     case POSTDECREMENT_EXPR:
10492       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
10493                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
10494       break;
10495     case MODIFY_EXPR:
10496       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
10497           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
10498         {
10499           tree rhs = TREE_OPERAND (incr, 1);
10500           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
10501                          RECUR (TREE_OPERAND (incr, 0)),
10502                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
10503                                  RECUR (TREE_OPERAND (rhs, 0)),
10504                                  RECUR (TREE_OPERAND (rhs, 1))));
10505         }
10506       else
10507         incr = RECUR (incr);
10508       break;
10509     case MODOP_EXPR:
10510       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
10511           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
10512         {
10513           tree lhs = RECUR (TREE_OPERAND (incr, 0));
10514           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
10515                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
10516                                  TREE_TYPE (decl), lhs,
10517                                  RECUR (TREE_OPERAND (incr, 2))));
10518         }
10519       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
10520                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
10521                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
10522         {
10523           tree rhs = TREE_OPERAND (incr, 2);
10524           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
10525                          RECUR (TREE_OPERAND (incr, 0)),
10526                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
10527                                  RECUR (TREE_OPERAND (rhs, 0)),
10528                                  RECUR (TREE_OPERAND (rhs, 1))));
10529         }
10530       else
10531         incr = RECUR (incr);
10532       break;
10533     default:
10534       incr = RECUR (incr);
10535       break;
10536     }
10537
10538   TREE_VEC_ELT (declv, i) = decl;
10539   TREE_VEC_ELT (initv, i) = init;
10540   TREE_VEC_ELT (condv, i) = cond;
10541   TREE_VEC_ELT (incrv, i) = incr;
10542 #undef RECUR
10543 }
10544
10545 /* Like tsubst_copy for expressions, etc. but also does semantic
10546    processing.  */
10547
10548 static tree
10549 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
10550              bool integral_constant_expression_p)
10551 {
10552 #define RECUR(NODE)                             \
10553   tsubst_expr ((NODE), args, complain, in_decl, \
10554                integral_constant_expression_p)
10555
10556   tree stmt, tmp;
10557
10558   if (t == NULL_TREE || t == error_mark_node)
10559     return t;
10560
10561   if (EXPR_HAS_LOCATION (t))
10562     input_location = EXPR_LOCATION (t);
10563   if (STATEMENT_CODE_P (TREE_CODE (t)))
10564     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
10565
10566   switch (TREE_CODE (t))
10567     {
10568     case STATEMENT_LIST:
10569       {
10570         tree_stmt_iterator i;
10571         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
10572           RECUR (tsi_stmt (i));
10573         break;
10574       }
10575
10576     case CTOR_INITIALIZER:
10577       finish_mem_initializers (tsubst_initializer_list
10578                                (TREE_OPERAND (t, 0), args));
10579       break;
10580
10581     case RETURN_EXPR:
10582       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
10583       break;
10584
10585     case EXPR_STMT:
10586       tmp = RECUR (EXPR_STMT_EXPR (t));
10587       if (EXPR_STMT_STMT_EXPR_RESULT (t))
10588         finish_stmt_expr_expr (tmp, cur_stmt_expr);
10589       else
10590         finish_expr_stmt (tmp);
10591       break;
10592
10593     case USING_STMT:
10594       do_using_directive (RECUR (USING_STMT_NAMESPACE (t)));
10595       break;
10596
10597     case DECL_EXPR:
10598       {
10599         tree decl;
10600         tree init;
10601
10602         decl = DECL_EXPR_DECL (t);
10603         if (TREE_CODE (decl) == LABEL_DECL)
10604           finish_label_decl (DECL_NAME (decl));
10605         else if (TREE_CODE (decl) == USING_DECL)
10606           {
10607             tree scope = USING_DECL_SCOPE (decl);
10608             tree name = DECL_NAME (decl);
10609             tree decl;
10610
10611             scope = RECUR (scope);
10612             decl = lookup_qualified_name (scope, name,
10613                                           /*is_type_p=*/false,
10614                                           /*complain=*/false);
10615             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
10616               qualified_name_lookup_error (scope, name, decl, input_location);
10617             else
10618               do_local_using_decl (decl, scope, name);
10619           }
10620         else
10621           {
10622             init = DECL_INITIAL (decl);
10623             decl = tsubst (decl, args, complain, in_decl);
10624             if (decl != error_mark_node)
10625               {
10626                 /* By marking the declaration as instantiated, we avoid
10627                    trying to instantiate it.  Since instantiate_decl can't
10628                    handle local variables, and since we've already done
10629                    all that needs to be done, that's the right thing to
10630                    do.  */
10631                 if (TREE_CODE (decl) == VAR_DECL)
10632                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
10633                 if (TREE_CODE (decl) == VAR_DECL
10634                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
10635                   /* Anonymous aggregates are a special case.  */
10636                   finish_anon_union (decl);
10637                 else
10638                   {
10639                     maybe_push_decl (decl);
10640                     if (TREE_CODE (decl) == VAR_DECL
10641                         && DECL_PRETTY_FUNCTION_P (decl))
10642                       {
10643                         /* For __PRETTY_FUNCTION__ we have to adjust the
10644                            initializer.  */
10645                         const char *const name
10646                           = cxx_printable_name (current_function_decl, 2);
10647                         init = cp_fname_init (name, &TREE_TYPE (decl));
10648                       }
10649                     else
10650                       {
10651                         tree t = RECUR (init);
10652
10653                         if (init && !t)
10654                           /* If we had an initializer but it
10655                              instantiated to nothing,
10656                              value-initialize the object.  This will
10657                              only occur when the initializer was a
10658                              pack expansion where the parameter packs
10659                              used in that expansion were of length
10660                              zero.  */
10661                           init = build_value_init (TREE_TYPE (decl));
10662                         else
10663                           init = t;
10664                       }
10665
10666                     finish_decl (decl, init, NULL_TREE);
10667                   }
10668               }
10669           }
10670
10671         /* A DECL_EXPR can also be used as an expression, in the condition
10672            clause of an if/for/while construct.  */
10673         return decl;
10674       }
10675
10676     case FOR_STMT:
10677       stmt = begin_for_stmt ();
10678                           RECUR (FOR_INIT_STMT (t));
10679       finish_for_init_stmt (stmt);
10680       tmp = RECUR (FOR_COND (t));
10681       finish_for_cond (tmp, stmt);
10682       tmp = RECUR (FOR_EXPR (t));
10683       finish_for_expr (tmp, stmt);
10684       RECUR (FOR_BODY (t));
10685       finish_for_stmt (stmt);
10686       break;
10687
10688     case WHILE_STMT:
10689       stmt = begin_while_stmt ();
10690       tmp = RECUR (WHILE_COND (t));
10691       finish_while_stmt_cond (tmp, stmt);
10692       RECUR (WHILE_BODY (t));
10693       finish_while_stmt (stmt);
10694       break;
10695
10696     case DO_STMT:
10697       stmt = begin_do_stmt ();
10698       RECUR (DO_BODY (t));
10699       finish_do_body (stmt);
10700       tmp = RECUR (DO_COND (t));
10701       finish_do_stmt (tmp, stmt);
10702       break;
10703
10704     case IF_STMT:
10705       stmt = begin_if_stmt ();
10706       tmp = RECUR (IF_COND (t));
10707       finish_if_stmt_cond (tmp, stmt);
10708       RECUR (THEN_CLAUSE (t));
10709       finish_then_clause (stmt);
10710
10711       if (ELSE_CLAUSE (t))
10712         {
10713           begin_else_clause (stmt);
10714           RECUR (ELSE_CLAUSE (t));
10715           finish_else_clause (stmt);
10716         }
10717
10718       finish_if_stmt (stmt);
10719       break;
10720
10721     case BIND_EXPR:
10722       if (BIND_EXPR_BODY_BLOCK (t))
10723         stmt = begin_function_body ();
10724       else
10725         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
10726                                     ? BCS_TRY_BLOCK : 0);
10727
10728       RECUR (BIND_EXPR_BODY (t));
10729
10730       if (BIND_EXPR_BODY_BLOCK (t))
10731         finish_function_body (stmt);
10732       else
10733         finish_compound_stmt (stmt);
10734       break;
10735
10736     case BREAK_STMT:
10737       finish_break_stmt ();
10738       break;
10739
10740     case CONTINUE_STMT:
10741       finish_continue_stmt ();
10742       break;
10743
10744     case SWITCH_STMT:
10745       stmt = begin_switch_stmt ();
10746       tmp = RECUR (SWITCH_STMT_COND (t));
10747       finish_switch_cond (tmp, stmt);
10748       RECUR (SWITCH_STMT_BODY (t));
10749       finish_switch_stmt (stmt);
10750       break;
10751
10752     case CASE_LABEL_EXPR:
10753       finish_case_label (RECUR (CASE_LOW (t)),
10754                          RECUR (CASE_HIGH (t)));
10755       break;
10756
10757     case LABEL_EXPR:
10758       finish_label_stmt (DECL_NAME (LABEL_EXPR_LABEL (t)));
10759       break;
10760
10761     case GOTO_EXPR:
10762       tmp = GOTO_DESTINATION (t);
10763       if (TREE_CODE (tmp) != LABEL_DECL)
10764         /* Computed goto's must be tsubst'd into.  On the other hand,
10765            non-computed gotos must not be; the identifier in question
10766            will have no binding.  */
10767         tmp = RECUR (tmp);
10768       else
10769         tmp = DECL_NAME (tmp);
10770       finish_goto_stmt (tmp);
10771       break;
10772
10773     case ASM_EXPR:
10774       tmp = finish_asm_stmt
10775         (ASM_VOLATILE_P (t),
10776          RECUR (ASM_STRING (t)),
10777          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
10778          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
10779          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl));
10780       {
10781         tree asm_expr = tmp;
10782         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
10783           asm_expr = TREE_OPERAND (asm_expr, 0);
10784         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
10785       }
10786       break;
10787
10788     case TRY_BLOCK:
10789       if (CLEANUP_P (t))
10790         {
10791           stmt = begin_try_block ();
10792           RECUR (TRY_STMTS (t));
10793           finish_cleanup_try_block (stmt);
10794           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
10795         }
10796       else
10797         {
10798           tree compound_stmt = NULL_TREE;
10799
10800           if (FN_TRY_BLOCK_P (t))
10801             stmt = begin_function_try_block (&compound_stmt);
10802           else
10803             stmt = begin_try_block ();
10804
10805           RECUR (TRY_STMTS (t));
10806
10807           if (FN_TRY_BLOCK_P (t))
10808             finish_function_try_block (stmt);
10809           else
10810             finish_try_block (stmt);
10811
10812           RECUR (TRY_HANDLERS (t));
10813           if (FN_TRY_BLOCK_P (t))
10814             finish_function_handler_sequence (stmt, compound_stmt);
10815           else
10816             finish_handler_sequence (stmt);
10817         }
10818       break;
10819
10820     case HANDLER:
10821       {
10822         tree decl = HANDLER_PARMS (t);
10823
10824         if (decl)
10825           {
10826             decl = tsubst (decl, args, complain, in_decl);
10827             /* Prevent instantiate_decl from trying to instantiate
10828                this variable.  We've already done all that needs to be
10829                done.  */
10830             if (decl != error_mark_node)
10831               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
10832           }
10833         stmt = begin_handler ();
10834         finish_handler_parms (decl, stmt);
10835         RECUR (HANDLER_BODY (t));
10836         finish_handler (stmt);
10837       }
10838       break;
10839
10840     case TAG_DEFN:
10841       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
10842       break;
10843
10844     case STATIC_ASSERT:
10845       {
10846         tree condition = 
10847           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
10848                        args,
10849                        complain, in_decl,
10850                        /*integral_constant_expression_p=*/true);
10851         finish_static_assert (condition,
10852                               STATIC_ASSERT_MESSAGE (t),
10853                               STATIC_ASSERT_SOURCE_LOCATION (t),
10854                               /*member_p=*/false);
10855       }
10856       break;
10857
10858     case OMP_PARALLEL:
10859       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
10860                                 args, complain, in_decl);
10861       stmt = begin_omp_parallel ();
10862       RECUR (OMP_PARALLEL_BODY (t));
10863       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
10864         = OMP_PARALLEL_COMBINED (t);
10865       break;
10866
10867     case OMP_TASK:
10868       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
10869                                 args, complain, in_decl);
10870       stmt = begin_omp_task ();
10871       RECUR (OMP_TASK_BODY (t));
10872       finish_omp_task (tmp, stmt);
10873       break;
10874
10875     case OMP_FOR:
10876       {
10877         tree clauses, body, pre_body;
10878         tree declv, initv, condv, incrv;
10879         int i;
10880
10881         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
10882                                       args, complain, in_decl);
10883         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
10884         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
10885         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
10886         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
10887
10888         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
10889           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
10890                                    &clauses, args, complain, in_decl,
10891                                    integral_constant_expression_p);
10892
10893         stmt = begin_omp_structured_block ();
10894
10895         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
10896           if (TREE_VEC_ELT (initv, i) == NULL
10897               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
10898             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
10899           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
10900             {
10901               tree init = RECUR (TREE_VEC_ELT (initv, i));
10902               gcc_assert (init == TREE_VEC_ELT (declv, i));
10903               TREE_VEC_ELT (initv, i) = NULL_TREE;
10904             }
10905           else
10906             {
10907               tree decl_expr = TREE_VEC_ELT (initv, i);
10908               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
10909               gcc_assert (init != NULL);
10910               TREE_VEC_ELT (initv, i) = RECUR (init);
10911               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
10912               RECUR (decl_expr);
10913               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
10914             }
10915
10916         pre_body = push_stmt_list ();
10917         RECUR (OMP_FOR_PRE_BODY (t));
10918         pre_body = pop_stmt_list (pre_body);
10919
10920         body = push_stmt_list ();
10921         RECUR (OMP_FOR_BODY (t));
10922         body = pop_stmt_list (body);
10923
10924         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
10925                             body, pre_body, clauses);
10926
10927         add_stmt (finish_omp_structured_block (stmt));
10928       }
10929       break;
10930
10931     case OMP_SECTIONS:
10932     case OMP_SINGLE:
10933       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
10934       stmt = push_stmt_list ();
10935       RECUR (OMP_BODY (t));
10936       stmt = pop_stmt_list (stmt);
10937
10938       t = copy_node (t);
10939       OMP_BODY (t) = stmt;
10940       OMP_CLAUSES (t) = tmp;
10941       add_stmt (t);
10942       break;
10943
10944     case OMP_SECTION:
10945     case OMP_CRITICAL:
10946     case OMP_MASTER:
10947     case OMP_ORDERED:
10948       stmt = push_stmt_list ();
10949       RECUR (OMP_BODY (t));
10950       stmt = pop_stmt_list (stmt);
10951
10952       t = copy_node (t);
10953       OMP_BODY (t) = stmt;
10954       add_stmt (t);
10955       break;
10956
10957     case OMP_ATOMIC:
10958       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
10959       {
10960         tree op1 = TREE_OPERAND (t, 1);
10961         tree lhs = RECUR (TREE_OPERAND (op1, 0));
10962         tree rhs = RECUR (TREE_OPERAND (op1, 1));
10963         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
10964       }
10965       break;
10966
10967     case EXPR_PACK_EXPANSION:
10968       error ("invalid use of pack expansion expression");
10969       return error_mark_node;
10970
10971     case NONTYPE_ARGUMENT_PACK:
10972       error ("use %<...%> to expand argument pack");
10973       return error_mark_node;
10974
10975     default:
10976       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
10977
10978       return tsubst_copy_and_build (t, args, complain, in_decl,
10979                                     /*function_p=*/false,
10980                                     integral_constant_expression_p);
10981     }
10982
10983   return NULL_TREE;
10984 #undef RECUR
10985 }
10986
10987 /* T is a postfix-expression that is not being used in a function
10988    call.  Return the substituted version of T.  */
10989
10990 static tree
10991 tsubst_non_call_postfix_expression (tree t, tree args,
10992                                     tsubst_flags_t complain,
10993                                     tree in_decl)
10994 {
10995   if (TREE_CODE (t) == SCOPE_REF)
10996     t = tsubst_qualified_id (t, args, complain, in_decl,
10997                              /*done=*/false, /*address_p=*/false);
10998   else
10999     t = tsubst_copy_and_build (t, args, complain, in_decl,
11000                                /*function_p=*/false,
11001                                /*integral_constant_expression_p=*/false);
11002
11003   return t;
11004 }
11005
11006 /* Like tsubst but deals with expressions and performs semantic
11007    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
11008
11009 tree
11010 tsubst_copy_and_build (tree t,
11011                        tree args,
11012                        tsubst_flags_t complain,
11013                        tree in_decl,
11014                        bool function_p,
11015                        bool integral_constant_expression_p)
11016 {
11017 #define RECUR(NODE)                                             \
11018   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
11019                          /*function_p=*/false,                  \
11020                          integral_constant_expression_p)
11021
11022   tree op1;
11023
11024   if (t == NULL_TREE || t == error_mark_node)
11025     return t;
11026
11027   switch (TREE_CODE (t))
11028     {
11029     case USING_DECL:
11030       t = DECL_NAME (t);
11031       /* Fall through.  */
11032     case IDENTIFIER_NODE:
11033       {
11034         tree decl;
11035         cp_id_kind idk;
11036         bool non_integral_constant_expression_p;
11037         const char *error_msg;
11038
11039         if (IDENTIFIER_TYPENAME_P (t))
11040           {
11041             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11042             t = mangle_conv_op_name_for_type (new_type);
11043           }
11044
11045         /* Look up the name.  */
11046         decl = lookup_name (t);
11047
11048         /* By convention, expressions use ERROR_MARK_NODE to indicate
11049            failure, not NULL_TREE.  */
11050         if (decl == NULL_TREE)
11051           decl = error_mark_node;
11052
11053         decl = finish_id_expression (t, decl, NULL_TREE,
11054                                      &idk,
11055                                      integral_constant_expression_p,
11056                                      /*allow_non_integral_constant_expression_p=*/false,
11057                                      &non_integral_constant_expression_p,
11058                                      /*template_p=*/false,
11059                                      /*done=*/true,
11060                                      /*address_p=*/false,
11061                                      /*template_arg_p=*/false,
11062                                      &error_msg,
11063                                      input_location);
11064         if (error_msg)
11065           error (error_msg);
11066         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
11067           decl = unqualified_name_lookup_error (decl);
11068         return decl;
11069       }
11070
11071     case TEMPLATE_ID_EXPR:
11072       {
11073         tree object;
11074         tree templ = RECUR (TREE_OPERAND (t, 0));
11075         tree targs = TREE_OPERAND (t, 1);
11076
11077         if (targs)
11078           targs = tsubst_template_args (targs, args, complain, in_decl);
11079
11080         if (TREE_CODE (templ) == COMPONENT_REF)
11081           {
11082             object = TREE_OPERAND (templ, 0);
11083             templ = TREE_OPERAND (templ, 1);
11084           }
11085         else
11086           object = NULL_TREE;
11087         templ = lookup_template_function (templ, targs);
11088
11089         if (object)
11090           return build3 (COMPONENT_REF, TREE_TYPE (templ),
11091                          object, templ, NULL_TREE);
11092         else
11093           return baselink_for_fns (templ);
11094       }
11095
11096     case INDIRECT_REF:
11097       {
11098         tree r = RECUR (TREE_OPERAND (t, 0));
11099
11100         if (REFERENCE_REF_P (t))
11101           {
11102             /* A type conversion to reference type will be enclosed in
11103                such an indirect ref, but the substitution of the cast
11104                will have also added such an indirect ref.  */
11105             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
11106               r = convert_from_reference (r);
11107           }
11108         else
11109           r = build_x_indirect_ref (r, "unary *", complain);
11110         return r;
11111       }
11112
11113     case NOP_EXPR:
11114       return build_nop
11115         (tsubst (TREE_TYPE (t), args, complain, in_decl),
11116          RECUR (TREE_OPERAND (t, 0)));
11117
11118     case CAST_EXPR:
11119     case REINTERPRET_CAST_EXPR:
11120     case CONST_CAST_EXPR:
11121     case DYNAMIC_CAST_EXPR:
11122     case STATIC_CAST_EXPR:
11123       {
11124         tree type;
11125         tree op;
11126
11127         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11128         if (integral_constant_expression_p
11129             && !cast_valid_in_integral_constant_expression_p (type))
11130           {
11131             if (complain & tf_error)
11132               error ("a cast to a type other than an integral or "
11133                      "enumeration type cannot appear in a constant-expression");
11134             return error_mark_node; 
11135           }
11136
11137         op = RECUR (TREE_OPERAND (t, 0));
11138
11139         switch (TREE_CODE (t))
11140           {
11141           case CAST_EXPR:
11142             return build_functional_cast (type, op, complain);
11143           case REINTERPRET_CAST_EXPR:
11144             return build_reinterpret_cast (type, op, complain);
11145           case CONST_CAST_EXPR:
11146             return build_const_cast (type, op, complain);
11147           case DYNAMIC_CAST_EXPR:
11148             return build_dynamic_cast (type, op, complain);
11149           case STATIC_CAST_EXPR:
11150             return build_static_cast (type, op, complain);
11151           default:
11152             gcc_unreachable ();
11153           }
11154       }
11155
11156     case POSTDECREMENT_EXPR:
11157     case POSTINCREMENT_EXPR:
11158       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11159                                                 args, complain, in_decl);
11160       return build_x_unary_op (TREE_CODE (t), op1, complain);
11161
11162     case PREDECREMENT_EXPR:
11163     case PREINCREMENT_EXPR:
11164     case NEGATE_EXPR:
11165     case BIT_NOT_EXPR:
11166     case ABS_EXPR:
11167     case TRUTH_NOT_EXPR:
11168     case UNARY_PLUS_EXPR:  /* Unary + */
11169     case REALPART_EXPR:
11170     case IMAGPART_EXPR:
11171       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
11172                                complain);
11173
11174     case ADDR_EXPR:
11175       op1 = TREE_OPERAND (t, 0);
11176       if (TREE_CODE (op1) == SCOPE_REF)
11177         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
11178                                    /*done=*/true, /*address_p=*/true);
11179       else
11180         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
11181                                                   in_decl);
11182       if (TREE_CODE (op1) == LABEL_DECL)
11183         return finish_label_address_expr (DECL_NAME (op1),
11184                                           EXPR_LOCATION (op1));
11185       return build_x_unary_op (ADDR_EXPR, op1, complain);
11186
11187     case PLUS_EXPR:
11188     case MINUS_EXPR:
11189     case MULT_EXPR:
11190     case TRUNC_DIV_EXPR:
11191     case CEIL_DIV_EXPR:
11192     case FLOOR_DIV_EXPR:
11193     case ROUND_DIV_EXPR:
11194     case EXACT_DIV_EXPR:
11195     case BIT_AND_EXPR:
11196     case BIT_IOR_EXPR:
11197     case BIT_XOR_EXPR:
11198     case TRUNC_MOD_EXPR:
11199     case FLOOR_MOD_EXPR:
11200     case TRUTH_ANDIF_EXPR:
11201     case TRUTH_ORIF_EXPR:
11202     case TRUTH_AND_EXPR:
11203     case TRUTH_OR_EXPR:
11204     case RSHIFT_EXPR:
11205     case LSHIFT_EXPR:
11206     case RROTATE_EXPR:
11207     case LROTATE_EXPR:
11208     case EQ_EXPR:
11209     case NE_EXPR:
11210     case MAX_EXPR:
11211     case MIN_EXPR:
11212     case LE_EXPR:
11213     case GE_EXPR:
11214     case LT_EXPR:
11215     case GT_EXPR:
11216     case MEMBER_REF:
11217     case DOTSTAR_EXPR:
11218       return build_x_binary_op
11219         (TREE_CODE (t),
11220          RECUR (TREE_OPERAND (t, 0)),
11221          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
11222           ? ERROR_MARK
11223           : TREE_CODE (TREE_OPERAND (t, 0))),
11224          RECUR (TREE_OPERAND (t, 1)),
11225          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
11226           ? ERROR_MARK
11227           : TREE_CODE (TREE_OPERAND (t, 1))),
11228          /*overloaded_p=*/NULL,
11229          complain);
11230
11231     case SCOPE_REF:
11232       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
11233                                   /*address_p=*/false);
11234     case ARRAY_REF:
11235       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11236                                                 args, complain, in_decl);
11237       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
11238
11239     case SIZEOF_EXPR:
11240       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11241         return tsubst_copy (t, args, complain, in_decl);
11242       /* Fall through */
11243       
11244     case ALIGNOF_EXPR:
11245       op1 = TREE_OPERAND (t, 0);
11246       if (!args)
11247         {
11248           /* When there are no ARGS, we are trying to evaluate a
11249              non-dependent expression from the parser.  Trying to do
11250              the substitutions may not work.  */
11251           if (!TYPE_P (op1))
11252             op1 = TREE_TYPE (op1);
11253         }
11254       else
11255         {
11256           ++skip_evaluation;
11257           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
11258                                        /*function_p=*/false,
11259                                        /*integral_constant_expression_p=*/false);
11260           --skip_evaluation;
11261         }
11262       if (TYPE_P (op1))
11263         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
11264                                            complain & tf_error);
11265       else
11266         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
11267                                            complain & tf_error);
11268
11269     case MODOP_EXPR:
11270       {
11271         tree r = build_x_modify_expr
11272           (RECUR (TREE_OPERAND (t, 0)),
11273            TREE_CODE (TREE_OPERAND (t, 1)),
11274            RECUR (TREE_OPERAND (t, 2)),
11275            complain);
11276         /* TREE_NO_WARNING must be set if either the expression was
11277            parenthesized or it uses an operator such as >>= rather
11278            than plain assignment.  In the former case, it was already
11279            set and must be copied.  In the latter case,
11280            build_x_modify_expr sets it and it must not be reset
11281            here.  */
11282         if (TREE_NO_WARNING (t))
11283           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
11284         return r;
11285       }
11286
11287     case ARROW_EXPR:
11288       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11289                                                 args, complain, in_decl);
11290       /* Remember that there was a reference to this entity.  */
11291       if (DECL_P (op1))
11292         mark_used (op1);
11293       return build_x_arrow (op1);
11294
11295     case NEW_EXPR:
11296       {
11297         tree init = RECUR (TREE_OPERAND (t, 3));
11298
11299         if (TREE_OPERAND (t, 3) && !init)
11300           /* If there was an initializer in the original tree, but
11301              it instantiated to an empty list, then we should pass on
11302              VOID_ZERO_NODE to tell build_new that it was an empty
11303              initializer () rather than no initializer.  This can only
11304              happen when the initializer is a pack expansion whose
11305              parameter packs are of length zero.  */
11306           init = void_zero_node;
11307
11308         return build_new
11309           (RECUR (TREE_OPERAND (t, 0)),
11310            RECUR (TREE_OPERAND (t, 1)),
11311            RECUR (TREE_OPERAND (t, 2)),
11312            init,
11313            NEW_EXPR_USE_GLOBAL (t),
11314            complain);
11315       }
11316
11317     case DELETE_EXPR:
11318      return delete_sanity
11319        (RECUR (TREE_OPERAND (t, 0)),
11320         RECUR (TREE_OPERAND (t, 1)),
11321         DELETE_EXPR_USE_VEC (t),
11322         DELETE_EXPR_USE_GLOBAL (t));
11323
11324     case COMPOUND_EXPR:
11325       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
11326                                     RECUR (TREE_OPERAND (t, 1)),
11327                                     complain);
11328
11329     case CALL_EXPR:
11330       {
11331         tree function;
11332         tree call_args;
11333         bool qualified_p;
11334         bool koenig_p;
11335
11336         function = CALL_EXPR_FN (t);
11337         /* When we parsed the expression,  we determined whether or
11338            not Koenig lookup should be performed.  */
11339         koenig_p = KOENIG_LOOKUP_P (t);
11340         if (TREE_CODE (function) == SCOPE_REF)
11341           {
11342             qualified_p = true;
11343             function = tsubst_qualified_id (function, args, complain, in_decl,
11344                                             /*done=*/false,
11345                                             /*address_p=*/false);
11346           }
11347         else
11348           {
11349             if (TREE_CODE (function) == COMPONENT_REF)
11350               {
11351                 tree op = TREE_OPERAND (function, 1);
11352
11353                 qualified_p = (TREE_CODE (op) == SCOPE_REF
11354                                || (BASELINK_P (op)
11355                                    && BASELINK_QUALIFIED_P (op)));
11356               }
11357             else
11358               qualified_p = false;
11359
11360             function = tsubst_copy_and_build (function, args, complain,
11361                                               in_decl,
11362                                               !qualified_p,
11363                                               integral_constant_expression_p);
11364
11365             if (BASELINK_P (function))
11366               qualified_p = true;
11367           }
11368
11369         /* FIXME:  Rewrite this so as not to construct an arglist.  */
11370         call_args = RECUR (CALL_EXPR_ARGS (t));
11371
11372         /* We do not perform argument-dependent lookup if normal
11373            lookup finds a non-function, in accordance with the
11374            expected resolution of DR 218.  */
11375         if (koenig_p
11376             && ((is_overloaded_fn (function)
11377                  /* If lookup found a member function, the Koenig lookup is
11378                     not appropriate, even if an unqualified-name was used
11379                     to denote the function.  */
11380                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
11381                 || TREE_CODE (function) == IDENTIFIER_NODE))
11382           function = perform_koenig_lookup (function, call_args);
11383
11384         if (TREE_CODE (function) == IDENTIFIER_NODE)
11385           {
11386             unqualified_name_lookup_error (function);
11387             return error_mark_node;
11388           }
11389
11390         /* Remember that there was a reference to this entity.  */
11391         if (DECL_P (function))
11392           mark_used (function);
11393
11394         if (TREE_CODE (function) == OFFSET_REF)
11395           return build_offset_ref_call_from_tree (function, call_args);
11396         if (TREE_CODE (function) == COMPONENT_REF)
11397           {
11398             if (!BASELINK_P (TREE_OPERAND (function, 1)))
11399               return finish_call_expr (function, call_args,
11400                                        /*disallow_virtual=*/false,
11401                                        /*koenig_p=*/false,
11402                                        complain);
11403             else
11404               return (build_new_method_call
11405                       (TREE_OPERAND (function, 0),
11406                        TREE_OPERAND (function, 1),
11407                        call_args, NULL_TREE,
11408                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
11409                        /*fn_p=*/NULL,
11410                        complain));
11411           }
11412         /* Pass -1 for koenig_p so that build_new_function_call will
11413            allow hidden friends found by arg-dependent lookup at template
11414            parsing time.  */
11415         return finish_call_expr (function, call_args,
11416                                  /*disallow_virtual=*/qualified_p,
11417                                  /*koenig_p*/-1,
11418                                  complain);
11419       }
11420
11421     case COND_EXPR:
11422       return build_x_conditional_expr
11423         (RECUR (TREE_OPERAND (t, 0)),
11424          RECUR (TREE_OPERAND (t, 1)),
11425          RECUR (TREE_OPERAND (t, 2)),
11426          complain);
11427
11428     case PSEUDO_DTOR_EXPR:
11429       return finish_pseudo_destructor_expr
11430         (RECUR (TREE_OPERAND (t, 0)),
11431          RECUR (TREE_OPERAND (t, 1)),
11432          RECUR (TREE_OPERAND (t, 2)));
11433
11434     case TREE_LIST:
11435       {
11436         tree purpose, value, chain;
11437
11438         if (t == void_list_node)
11439           return t;
11440
11441         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
11442             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
11443           {
11444             /* We have pack expansions, so expand those and
11445                create a new list out of it.  */
11446             tree purposevec = NULL_TREE;
11447             tree valuevec = NULL_TREE;
11448             tree chain;
11449             int i, len = -1;
11450
11451             /* Expand the argument expressions.  */
11452             if (TREE_PURPOSE (t))
11453               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
11454                                                  complain, in_decl);
11455             if (TREE_VALUE (t))
11456               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
11457                                                complain, in_decl);
11458
11459             /* Build the rest of the list.  */
11460             chain = TREE_CHAIN (t);
11461             if (chain && chain != void_type_node)
11462               chain = RECUR (chain);
11463
11464             /* Determine the number of arguments.  */
11465             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
11466               {
11467                 len = TREE_VEC_LENGTH (purposevec);
11468                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
11469               }
11470             else if (TREE_CODE (valuevec) == TREE_VEC)
11471               len = TREE_VEC_LENGTH (valuevec);
11472             else
11473               {
11474                 /* Since we only performed a partial substitution into
11475                    the argument pack, we only return a single list
11476                    node.  */
11477                 if (purposevec == TREE_PURPOSE (t)
11478                     && valuevec == TREE_VALUE (t)
11479                     && chain == TREE_CHAIN (t))
11480                   return t;
11481
11482                 return tree_cons (purposevec, valuevec, chain);
11483               }
11484             
11485             /* Convert the argument vectors into a TREE_LIST */
11486             i = len;
11487             while (i > 0)
11488               {
11489                 /* Grab the Ith values.  */
11490                 i--;
11491                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
11492                                      : NULL_TREE;
11493                 value 
11494                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
11495                              : NULL_TREE;
11496
11497                 /* Build the list (backwards).  */
11498                 chain = tree_cons (purpose, value, chain);
11499               }
11500
11501             return chain;
11502           }
11503
11504         purpose = TREE_PURPOSE (t);
11505         if (purpose)
11506           purpose = RECUR (purpose);
11507         value = TREE_VALUE (t);
11508         if (value)
11509           value = RECUR (value);
11510         chain = TREE_CHAIN (t);
11511         if (chain && chain != void_type_node)
11512           chain = RECUR (chain);
11513         if (purpose == TREE_PURPOSE (t)
11514             && value == TREE_VALUE (t)
11515             && chain == TREE_CHAIN (t))
11516           return t;
11517         return tree_cons (purpose, value, chain);
11518       }
11519
11520     case COMPONENT_REF:
11521       {
11522         tree object;
11523         tree object_type;
11524         tree member;
11525
11526         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11527                                                      args, complain, in_decl);
11528         /* Remember that there was a reference to this entity.  */
11529         if (DECL_P (object))
11530           mark_used (object);
11531         object_type = TREE_TYPE (object);
11532
11533         member = TREE_OPERAND (t, 1);
11534         if (BASELINK_P (member))
11535           member = tsubst_baselink (member,
11536                                     non_reference (TREE_TYPE (object)),
11537                                     args, complain, in_decl);
11538         else
11539           member = tsubst_copy (member, args, complain, in_decl);
11540         if (member == error_mark_node)
11541           return error_mark_node;
11542
11543         if (object_type && !CLASS_TYPE_P (object_type))
11544           {
11545             if (SCALAR_TYPE_P (object_type))
11546               {
11547                 tree s = NULL_TREE;
11548                 tree dtor = member;
11549
11550                 if (TREE_CODE (dtor) == SCOPE_REF)
11551                   {
11552                     s = TREE_OPERAND (dtor, 0);
11553                     dtor = TREE_OPERAND (dtor, 1);
11554                   }
11555                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
11556                   {
11557                     dtor = TREE_OPERAND (dtor, 0);
11558                     if (TYPE_P (dtor))
11559                       return finish_pseudo_destructor_expr (object, s, dtor);
11560                   }
11561               }
11562           }
11563         else if (TREE_CODE (member) == SCOPE_REF
11564                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
11565           {
11566             tree tmpl;
11567             tree args;
11568
11569             /* Lookup the template functions now that we know what the
11570                scope is.  */
11571             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
11572             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
11573             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
11574                                             /*is_type_p=*/false,
11575                                             /*complain=*/false);
11576             if (BASELINK_P (member))
11577               {
11578                 BASELINK_FUNCTIONS (member)
11579                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
11580                               args);
11581                 member = (adjust_result_of_qualified_name_lookup
11582                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
11583                            object_type));
11584               }
11585             else
11586               {
11587                 qualified_name_lookup_error (object_type, tmpl, member,
11588                                              input_location);
11589                 return error_mark_node;
11590               }
11591           }
11592         else if (TREE_CODE (member) == SCOPE_REF
11593                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
11594                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
11595           {
11596             if (complain & tf_error)
11597               {
11598                 if (TYPE_P (TREE_OPERAND (member, 0)))
11599                   error ("%qT is not a class or namespace",
11600                          TREE_OPERAND (member, 0));
11601                 else
11602                   error ("%qD is not a class or namespace",
11603                          TREE_OPERAND (member, 0));
11604               }
11605             return error_mark_node;
11606           }
11607         else if (TREE_CODE (member) == FIELD_DECL)
11608           return finish_non_static_data_member (member, object, NULL_TREE);
11609
11610         return finish_class_member_access_expr (object, member,
11611                                                 /*template_p=*/false,
11612                                                 complain);
11613       }
11614
11615     case THROW_EXPR:
11616       return build_throw
11617         (RECUR (TREE_OPERAND (t, 0)));
11618
11619     case CONSTRUCTOR:
11620       {
11621         VEC(constructor_elt,gc) *n;
11622         constructor_elt *ce;
11623         unsigned HOST_WIDE_INT idx;
11624         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11625         bool process_index_p;
11626         int newlen;
11627         bool need_copy_p = false;
11628         tree r;
11629
11630         if (type == error_mark_node)
11631           return error_mark_node;
11632
11633         /* digest_init will do the wrong thing if we let it.  */
11634         if (type && TYPE_PTRMEMFUNC_P (type))
11635           return t;
11636
11637         /* We do not want to process the index of aggregate
11638            initializers as they are identifier nodes which will be
11639            looked up by digest_init.  */
11640         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
11641
11642         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
11643         newlen = VEC_length (constructor_elt, n);
11644         for (idx = 0; VEC_iterate (constructor_elt, n, idx, ce); idx++)
11645           {
11646             if (ce->index && process_index_p)
11647               ce->index = RECUR (ce->index);
11648
11649             if (PACK_EXPANSION_P (ce->value))
11650               {
11651                 /* Substitute into the pack expansion.  */
11652                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
11653                                                   in_decl);
11654
11655                 if (ce->value == error_mark_node)
11656                   ;
11657                 else if (TREE_VEC_LENGTH (ce->value) == 1)
11658                   /* Just move the argument into place.  */
11659                   ce->value = TREE_VEC_ELT (ce->value, 0);
11660                 else
11661                   {
11662                     /* Update the length of the final CONSTRUCTOR
11663                        arguments vector, and note that we will need to
11664                        copy.*/
11665                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
11666                     need_copy_p = true;
11667                   }
11668               }
11669             else
11670               ce->value = RECUR (ce->value);
11671           }
11672
11673         if (need_copy_p)
11674           {
11675             VEC(constructor_elt,gc) *old_n = n;
11676
11677             n = VEC_alloc (constructor_elt, gc, newlen);
11678             for (idx = 0; VEC_iterate (constructor_elt, old_n, idx, ce); 
11679                  idx++)
11680               {
11681                 if (TREE_CODE (ce->value) == TREE_VEC)
11682                   {
11683                     int i, len = TREE_VEC_LENGTH (ce->value);
11684                     for (i = 0; i < len; ++i)
11685                       CONSTRUCTOR_APPEND_ELT (n, 0,
11686                                               TREE_VEC_ELT (ce->value, i));
11687                   }
11688                 else
11689                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
11690               }
11691           }
11692
11693         r = build_constructor (init_list_type_node, n);
11694         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
11695
11696         if (TREE_HAS_CONSTRUCTOR (t))
11697           return finish_compound_literal (type, r);
11698
11699         return r;
11700       }
11701
11702     case TYPEID_EXPR:
11703       {
11704         tree operand_0 = RECUR (TREE_OPERAND (t, 0));
11705         if (TYPE_P (operand_0))
11706           return get_typeid (operand_0);
11707         return build_typeid (operand_0);
11708       }
11709
11710     case VAR_DECL:
11711       if (!args)
11712         return t;
11713       /* Fall through */
11714
11715     case PARM_DECL:
11716       {
11717         tree r = tsubst_copy (t, args, complain, in_decl);
11718
11719         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
11720           /* If the original type was a reference, we'll be wrapped in
11721              the appropriate INDIRECT_REF.  */
11722           r = convert_from_reference (r);
11723         return r;
11724       }
11725
11726     case VA_ARG_EXPR:
11727       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
11728                              tsubst_copy (TREE_TYPE (t), args, complain,
11729                                           in_decl));
11730
11731     case OFFSETOF_EXPR:
11732       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
11733
11734     case TRAIT_EXPR:
11735       {
11736         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
11737                                   complain, in_decl);
11738
11739         tree type2 = TRAIT_EXPR_TYPE2 (t);
11740         if (type2)
11741           type2 = tsubst_copy (type2, args, complain, in_decl);
11742         
11743         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
11744       }
11745
11746     case STMT_EXPR:
11747       {
11748         tree old_stmt_expr = cur_stmt_expr;
11749         tree stmt_expr = begin_stmt_expr ();
11750
11751         cur_stmt_expr = stmt_expr;
11752         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
11753                      integral_constant_expression_p);
11754         stmt_expr = finish_stmt_expr (stmt_expr, false);
11755         cur_stmt_expr = old_stmt_expr;
11756
11757         return stmt_expr;
11758       }
11759
11760     case CONST_DECL:
11761       t = tsubst_copy (t, args, complain, in_decl);
11762       /* As in finish_id_expression, we resolve enumeration constants
11763          to their underlying values.  */
11764       if (TREE_CODE (t) == CONST_DECL)
11765         {
11766           used_types_insert (TREE_TYPE (t));
11767           return DECL_INITIAL (t);
11768         }
11769       return t;
11770
11771     default:
11772       /* Handle Objective-C++ constructs, if appropriate.  */
11773       {
11774         tree subst
11775           = objcp_tsubst_copy_and_build (t, args, complain,
11776                                          in_decl, /*function_p=*/false);
11777         if (subst)
11778           return subst;
11779       }
11780       return tsubst_copy (t, args, complain, in_decl);
11781     }
11782
11783 #undef RECUR
11784 }
11785
11786 /* Verify that the instantiated ARGS are valid. For type arguments,
11787    make sure that the type's linkage is ok. For non-type arguments,
11788    make sure they are constants if they are integral or enumerations.
11789    Emit an error under control of COMPLAIN, and return TRUE on error.  */
11790
11791 static bool
11792 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
11793 {
11794   if (ARGUMENT_PACK_P (t))
11795     {
11796       tree vec = ARGUMENT_PACK_ARGS (t);
11797       int len = TREE_VEC_LENGTH (vec);
11798       bool result = false;
11799       int i;
11800
11801       for (i = 0; i < len; ++i)
11802         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
11803           result = true;
11804       return result;
11805     }
11806   else if (TYPE_P (t))
11807     {
11808       /* [basic.link]: A name with no linkage (notably, the name
11809          of a class or enumeration declared in a local scope)
11810          shall not be used to declare an entity with linkage.
11811          This implies that names with no linkage cannot be used as
11812          template arguments.  */
11813       tree nt = no_linkage_check (t, /*relaxed_p=*/false);
11814
11815       if (nt)
11816         {
11817           /* DR 488 makes use of a type with no linkage cause
11818              type deduction to fail.  */
11819           if (complain & tf_error)
11820             {
11821               if (TYPE_ANONYMOUS_P (nt))
11822                 error ("%qT is/uses anonymous type", t);
11823               else
11824                 error ("template argument for %qD uses local type %qT",
11825                        tmpl, t);
11826             }
11827           return true;
11828         }
11829       /* In order to avoid all sorts of complications, we do not
11830          allow variably-modified types as template arguments.  */
11831       else if (variably_modified_type_p (t, NULL_TREE))
11832         {
11833           if (complain & tf_error)
11834             error ("%qT is a variably modified type", t);
11835           return true;
11836         }
11837     }
11838   /* A non-type argument of integral or enumerated type must be a
11839      constant.  */
11840   else if (TREE_TYPE (t)
11841            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
11842            && !TREE_CONSTANT (t))
11843     {
11844       if (complain & tf_error)
11845         error ("integral expression %qE is not constant", t);
11846       return true;
11847     }
11848   return false;
11849 }
11850
11851 static bool
11852 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
11853 {
11854   int ix, len = DECL_NTPARMS (tmpl);
11855   bool result = false;
11856
11857   for (ix = 0; ix != len; ix++)
11858     {
11859       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
11860         result = true;
11861     }
11862   if (result && (complain & tf_error))
11863     error ("  trying to instantiate %qD", tmpl);
11864   return result;
11865 }
11866
11867 /* Instantiate the indicated variable or function template TMPL with
11868    the template arguments in TARG_PTR.  */
11869
11870 tree
11871 instantiate_template (tree tmpl, tree targ_ptr, tsubst_flags_t complain)
11872 {
11873   tree fndecl;
11874   tree gen_tmpl;
11875   tree spec;
11876   HOST_WIDE_INT saved_processing_template_decl;
11877
11878   if (tmpl == error_mark_node)
11879     return error_mark_node;
11880
11881   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
11882
11883   /* If this function is a clone, handle it specially.  */
11884   if (DECL_CLONED_FUNCTION_P (tmpl))
11885     {
11886       tree spec;
11887       tree clone;
11888
11889       spec = instantiate_template (DECL_CLONED_FUNCTION (tmpl), targ_ptr,
11890                                    complain);
11891       if (spec == error_mark_node)
11892         return error_mark_node;
11893
11894       /* Look for the clone.  */
11895       FOR_EACH_CLONE (clone, spec)
11896         if (DECL_NAME (clone) == DECL_NAME (tmpl))
11897           return clone;
11898       /* We should always have found the clone by now.  */
11899       gcc_unreachable ();
11900       return NULL_TREE;
11901     }
11902
11903   /* Check to see if we already have this specialization.  */
11904   spec = retrieve_specialization (tmpl, targ_ptr,
11905                                   /*class_specializations_p=*/false);
11906   if (spec != NULL_TREE)
11907     return spec;
11908
11909   gen_tmpl = most_general_template (tmpl);
11910   if (tmpl != gen_tmpl)
11911     {
11912       /* The TMPL is a partial instantiation.  To get a full set of
11913          arguments we must add the arguments used to perform the
11914          partial instantiation.  */
11915       targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
11916                                               targ_ptr);
11917
11918       /* Check to see if we already have this specialization.  */
11919       spec = retrieve_specialization (gen_tmpl, targ_ptr,
11920                                       /*class_specializations_p=*/false);
11921       if (spec != NULL_TREE)
11922         return spec;
11923     }
11924
11925   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
11926                                complain))
11927     return error_mark_node;
11928
11929   /* We are building a FUNCTION_DECL, during which the access of its
11930      parameters and return types have to be checked.  However this
11931      FUNCTION_DECL which is the desired context for access checking
11932      is not built yet.  We solve this chicken-and-egg problem by
11933      deferring all checks until we have the FUNCTION_DECL.  */
11934   push_deferring_access_checks (dk_deferred);
11935
11936   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
11937      (because, for example, we have encountered a non-dependent
11938      function call in the body of a template function and must now
11939      determine which of several overloaded functions will be called),
11940      within the instantiation itself we are not processing a
11941      template.  */  
11942   saved_processing_template_decl = processing_template_decl;
11943   processing_template_decl = 0;
11944   /* Substitute template parameters to obtain the specialization.  */
11945   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
11946                    targ_ptr, complain, gen_tmpl);
11947   processing_template_decl = saved_processing_template_decl;
11948   if (fndecl == error_mark_node)
11949     return error_mark_node;
11950
11951   /* Now we know the specialization, compute access previously
11952      deferred.  */
11953   push_access_scope (fndecl);
11954   perform_deferred_access_checks ();
11955   pop_access_scope (fndecl);
11956   pop_deferring_access_checks ();
11957
11958   /* The DECL_TI_TEMPLATE should always be the immediate parent
11959      template, not the most general template.  */
11960   DECL_TI_TEMPLATE (fndecl) = tmpl;
11961
11962   /* If we've just instantiated the main entry point for a function,
11963      instantiate all the alternate entry points as well.  We do this
11964      by cloning the instantiation of the main entry point, not by
11965      instantiating the template clones.  */
11966   if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
11967     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
11968
11969   return fndecl;
11970 }
11971
11972 /* The FN is a TEMPLATE_DECL for a function.  The ARGS are the
11973    arguments that are being used when calling it.  TARGS is a vector
11974    into which the deduced template arguments are placed.
11975
11976    Return zero for success, 2 for an incomplete match that doesn't resolve
11977    all the types, and 1 for complete failure.  An error message will be
11978    printed only for an incomplete match.
11979
11980    If FN is a conversion operator, or we are trying to produce a specific
11981    specialization, RETURN_TYPE is the return type desired.
11982
11983    The EXPLICIT_TARGS are explicit template arguments provided via a
11984    template-id.
11985
11986    The parameter STRICT is one of:
11987
11988    DEDUCE_CALL:
11989      We are deducing arguments for a function call, as in
11990      [temp.deduct.call].
11991
11992    DEDUCE_CONV:
11993      We are deducing arguments for a conversion function, as in
11994      [temp.deduct.conv].
11995
11996    DEDUCE_EXACT:
11997      We are deducing arguments when doing an explicit instantiation
11998      as in [temp.explicit], when determining an explicit specialization
11999      as in [temp.expl.spec], or when taking the address of a function
12000      template, as in [temp.deduct.funcaddr].  */
12001
12002 int
12003 fn_type_unification (tree fn,
12004                      tree explicit_targs,
12005                      tree targs,
12006                      tree args,
12007                      tree return_type,
12008                      unification_kind_t strict,
12009                      int flags)
12010 {
12011   tree parms;
12012   tree fntype;
12013   int result;
12014   bool incomplete_argument_packs_p = false;
12015
12016   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
12017
12018   fntype = TREE_TYPE (fn);
12019   if (explicit_targs)
12020     {
12021       /* [temp.deduct]
12022
12023          The specified template arguments must match the template
12024          parameters in kind (i.e., type, nontype, template), and there
12025          must not be more arguments than there are parameters;
12026          otherwise type deduction fails.
12027
12028          Nontype arguments must match the types of the corresponding
12029          nontype template parameters, or must be convertible to the
12030          types of the corresponding nontype parameters as specified in
12031          _temp.arg.nontype_, otherwise type deduction fails.
12032
12033          All references in the function type of the function template
12034          to the corresponding template parameters are replaced by the
12035          specified template argument values.  If a substitution in a
12036          template parameter or in the function type of the function
12037          template results in an invalid type, type deduction fails.  */
12038       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
12039       int i, len = TREE_VEC_LENGTH (tparms);
12040       tree converted_args;
12041       bool incomplete = false;
12042
12043       if (explicit_targs == error_mark_node)
12044         return 1;
12045
12046       converted_args
12047         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
12048                                   /*require_all_args=*/false,
12049                                   /*use_default_args=*/false));
12050       if (converted_args == error_mark_node)
12051         return 1;
12052
12053       /* Substitute the explicit args into the function type.  This is
12054          necessary so that, for instance, explicitly declared function
12055          arguments can match null pointed constants.  If we were given
12056          an incomplete set of explicit args, we must not do semantic
12057          processing during substitution as we could create partial
12058          instantiations.  */
12059       for (i = 0; i < len; i++)
12060         {
12061           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
12062           bool parameter_pack = false;
12063
12064           /* Dig out the actual parm.  */
12065           if (TREE_CODE (parm) == TYPE_DECL
12066               || TREE_CODE (parm) == TEMPLATE_DECL)
12067             {
12068               parm = TREE_TYPE (parm);
12069               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
12070             }
12071           else if (TREE_CODE (parm) == PARM_DECL)
12072             {
12073               parm = DECL_INITIAL (parm);
12074               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
12075             }
12076
12077           if (parameter_pack)
12078             {
12079               int level, idx;
12080               tree targ;
12081               template_parm_level_and_index (parm, &level, &idx);
12082
12083               /* Mark the argument pack as "incomplete". We could
12084                  still deduce more arguments during unification.  */
12085               targ = TMPL_ARG (converted_args, level, idx);
12086               if (targ)
12087                 {
12088                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
12089                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
12090                     = ARGUMENT_PACK_ARGS (targ);
12091                 }
12092
12093               /* We have some incomplete argument packs.  */
12094               incomplete_argument_packs_p = true;
12095             }
12096         }
12097
12098       if (incomplete_argument_packs_p)
12099         /* Any substitution is guaranteed to be incomplete if there
12100            are incomplete argument packs, because we can still deduce
12101            more arguments.  */
12102         incomplete = 1;
12103       else
12104         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
12105
12106       processing_template_decl += incomplete;
12107       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
12108       processing_template_decl -= incomplete;
12109
12110       if (fntype == error_mark_node)
12111         return 1;
12112
12113       /* Place the explicitly specified arguments in TARGS.  */
12114       for (i = NUM_TMPL_ARGS (converted_args); i--;)
12115         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
12116     }
12117
12118   /* Never do unification on the 'this' parameter.  */
12119   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
12120
12121   if (return_type)
12122     {
12123       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
12124       args = tree_cons (NULL_TREE, return_type, args);
12125     }
12126
12127   /* We allow incomplete unification without an error message here
12128      because the standard doesn't seem to explicitly prohibit it.  Our
12129      callers must be ready to deal with unification failures in any
12130      event.  */
12131   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
12132                                   targs, parms, args, /*subr=*/0,
12133                                   strict, flags);
12134
12135   if (result == 0 && incomplete_argument_packs_p)
12136     {
12137       int i, len = NUM_TMPL_ARGS (targs);
12138
12139       /* Clear the "incomplete" flags on all argument packs.  */
12140       for (i = 0; i < len; i++)
12141         {
12142           tree arg = TREE_VEC_ELT (targs, i);
12143           if (ARGUMENT_PACK_P (arg))
12144             {
12145               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
12146               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
12147             }
12148         }
12149     }
12150
12151   /* Now that we have bindings for all of the template arguments,
12152      ensure that the arguments deduced for the template template
12153      parameters have compatible template parameter lists.  We cannot
12154      check this property before we have deduced all template
12155      arguments, because the template parameter types of a template
12156      template parameter might depend on prior template parameters
12157      deduced after the template template parameter.  The following
12158      ill-formed example illustrates this issue:
12159
12160        template<typename T, template<T> class C> void f(C<5>, T);
12161
12162        template<int N> struct X {};
12163
12164        void g() {
12165          f(X<5>(), 5l); // error: template argument deduction fails
12166        }
12167
12168      The template parameter list of 'C' depends on the template type
12169      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
12170      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
12171      time that we deduce 'C'.  */
12172   if (result == 0
12173       && !template_template_parm_bindings_ok_p 
12174            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
12175     return 1;
12176
12177   if (result == 0)
12178     /* All is well so far.  Now, check:
12179
12180        [temp.deduct]
12181
12182        When all template arguments have been deduced, all uses of
12183        template parameters in nondeduced contexts are replaced with
12184        the corresponding deduced argument values.  If the
12185        substitution results in an invalid type, as described above,
12186        type deduction fails.  */
12187     if (tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE)
12188         == error_mark_node)
12189       return 1;
12190
12191   return result;
12192 }
12193
12194 /* Adjust types before performing type deduction, as described in
12195    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
12196    sections are symmetric.  PARM is the type of a function parameter
12197    or the return type of the conversion function.  ARG is the type of
12198    the argument passed to the call, or the type of the value
12199    initialized with the result of the conversion function.
12200    ARG_EXPR is the original argument expression, which may be null.  */
12201
12202 static int
12203 maybe_adjust_types_for_deduction (unification_kind_t strict,
12204                                   tree* parm,
12205                                   tree* arg,
12206                                   tree arg_expr)
12207 {
12208   int result = 0;
12209
12210   switch (strict)
12211     {
12212     case DEDUCE_CALL:
12213       break;
12214
12215     case DEDUCE_CONV:
12216       {
12217         /* Swap PARM and ARG throughout the remainder of this
12218            function; the handling is precisely symmetric since PARM
12219            will initialize ARG rather than vice versa.  */
12220         tree* temp = parm;
12221         parm = arg;
12222         arg = temp;
12223         break;
12224       }
12225
12226     case DEDUCE_EXACT:
12227       /* There is nothing to do in this case.  */
12228       return 0;
12229
12230     default:
12231       gcc_unreachable ();
12232     }
12233
12234   if (TREE_CODE (*parm) != REFERENCE_TYPE)
12235     {
12236       /* [temp.deduct.call]
12237
12238          If P is not a reference type:
12239
12240          --If A is an array type, the pointer type produced by the
12241          array-to-pointer standard conversion (_conv.array_) is
12242          used in place of A for type deduction; otherwise,
12243
12244          --If A is a function type, the pointer type produced by
12245          the function-to-pointer standard conversion
12246          (_conv.func_) is used in place of A for type deduction;
12247          otherwise,
12248
12249          --If A is a cv-qualified type, the top level
12250          cv-qualifiers of A's type are ignored for type
12251          deduction.  */
12252       if (TREE_CODE (*arg) == ARRAY_TYPE)
12253         *arg = build_pointer_type (TREE_TYPE (*arg));
12254       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
12255         *arg = build_pointer_type (*arg);
12256       else
12257         *arg = TYPE_MAIN_VARIANT (*arg);
12258     }
12259
12260   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
12261      of the form T&&, where T is a template parameter, and the argument
12262      is an lvalue, T is deduced as A& */
12263   if (TREE_CODE (*parm) == REFERENCE_TYPE
12264       && TYPE_REF_IS_RVALUE (*parm)
12265       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
12266       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
12267       && arg_expr && real_lvalue_p (arg_expr))
12268     *arg = build_reference_type (*arg);
12269
12270   /* [temp.deduct.call]
12271
12272      If P is a cv-qualified type, the top level cv-qualifiers
12273      of P's type are ignored for type deduction.  If P is a
12274      reference type, the type referred to by P is used for
12275      type deduction.  */
12276   *parm = TYPE_MAIN_VARIANT (*parm);
12277   if (TREE_CODE (*parm) == REFERENCE_TYPE)
12278     {
12279       *parm = TREE_TYPE (*parm);
12280       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
12281     }
12282
12283   /* DR 322. For conversion deduction, remove a reference type on parm
12284      too (which has been swapped into ARG).  */
12285   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
12286     *arg = TREE_TYPE (*arg);
12287
12288   return result;
12289 }
12290
12291 /* Most parms like fn_type_unification.
12292
12293    If SUBR is 1, we're being called recursively (to unify the
12294    arguments of a function or method parameter of a function
12295    template). */
12296
12297 static int
12298 type_unification_real (tree tparms,
12299                        tree targs,
12300                        tree xparms,
12301                        tree xargs,
12302                        int subr,
12303                        unification_kind_t strict,
12304                        int flags)
12305 {
12306   tree parm, arg, arg_expr;
12307   int i;
12308   int ntparms = TREE_VEC_LENGTH (tparms);
12309   int sub_strict;
12310   int saw_undeduced = 0;
12311   tree parms, args;
12312
12313   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
12314   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
12315   gcc_assert (!xargs || TREE_CODE (xargs) == TREE_LIST);
12316   gcc_assert (ntparms > 0);
12317
12318   switch (strict)
12319     {
12320     case DEDUCE_CALL:
12321       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
12322                     | UNIFY_ALLOW_DERIVED);
12323       break;
12324
12325     case DEDUCE_CONV:
12326       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
12327       break;
12328
12329     case DEDUCE_EXACT:
12330       sub_strict = UNIFY_ALLOW_NONE;
12331       break;
12332
12333     default:
12334       gcc_unreachable ();
12335     }
12336
12337  again:
12338   parms = xparms;
12339   args = xargs;
12340
12341   while (parms && parms != void_list_node
12342          && args && args != void_list_node)
12343     {
12344       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
12345         break;
12346
12347       parm = TREE_VALUE (parms);
12348       parms = TREE_CHAIN (parms);
12349       arg = TREE_VALUE (args);
12350       args = TREE_CHAIN (args);
12351       arg_expr = NULL;
12352
12353       if (arg == error_mark_node)
12354         return 1;
12355       if (arg == unknown_type_node)
12356         /* We can't deduce anything from this, but we might get all the
12357            template args from other function args.  */
12358         continue;
12359
12360       /* Conversions will be performed on a function argument that
12361          corresponds with a function parameter that contains only
12362          non-deducible template parameters and explicitly specified
12363          template parameters.  */
12364       if (!uses_template_parms (parm))
12365         {
12366           tree type;
12367
12368           if (!TYPE_P (arg))
12369             type = TREE_TYPE (arg);
12370           else
12371             type = arg;
12372
12373           if (same_type_p (parm, type))
12374             continue;
12375           if (strict != DEDUCE_EXACT
12376               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
12377                                   flags))
12378             continue;
12379
12380           return 1;
12381         }
12382
12383       if (!TYPE_P (arg))
12384         {
12385           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
12386           if (type_unknown_p (arg))
12387             {
12388               /* [temp.deduct.type] 
12389
12390                  A template-argument can be deduced from a pointer to
12391                  function or pointer to member function argument if
12392                  the set of overloaded functions does not contain
12393                  function templates and at most one of a set of
12394                  overloaded functions provides a unique match.  */
12395               if (resolve_overloaded_unification
12396                   (tparms, targs, parm, arg, strict, sub_strict))
12397                 continue;
12398
12399               return 1;
12400             }
12401           arg_expr = arg;
12402           arg = unlowered_expr_type (arg);
12403           if (arg == error_mark_node)
12404             return 1;
12405         }
12406
12407       {
12408         int arg_strict = sub_strict;
12409
12410         if (!subr)
12411           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
12412                                                           arg_expr);
12413
12414         if (arg == init_list_type_node && arg_expr)
12415           arg = arg_expr;
12416         if (unify (tparms, targs, parm, arg, arg_strict))
12417           return 1;
12418       }
12419     }
12420
12421
12422   if (parms 
12423       && parms != void_list_node
12424       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
12425     {
12426       /* Unify the remaining arguments with the pack expansion type.  */
12427       tree argvec;
12428       tree parmvec = make_tree_vec (1);
12429       int len = 0;
12430       tree t;
12431
12432       /* Count the number of arguments that remain.  */
12433       for (t = args; t && t != void_list_node; t = TREE_CHAIN (t))
12434         len++;
12435         
12436       /* Allocate a TREE_VEC and copy in all of the arguments */ 
12437       argvec = make_tree_vec (len);
12438       for (i = 0; args && args != void_list_node; args = TREE_CHAIN (args))
12439         {
12440           TREE_VEC_ELT (argvec, i) = TREE_VALUE (args);
12441           ++i;
12442         }
12443
12444       /* Copy the parameter into parmvec.  */
12445       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
12446       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
12447                                 /*call_args_p=*/true, /*subr=*/subr))
12448         return 1;
12449
12450       /* Advance to the end of the list of parameters.  */
12451       parms = TREE_CHAIN (parms);
12452     }
12453
12454   /* Fail if we've reached the end of the parm list, and more args
12455      are present, and the parm list isn't variadic.  */
12456   if (args && args != void_list_node && parms == void_list_node)
12457     return 1;
12458   /* Fail if parms are left and they don't have default values.  */
12459   if (parms && parms != void_list_node
12460       && TREE_PURPOSE (parms) == NULL_TREE)
12461     return 1;
12462
12463   if (!subr)
12464     for (i = 0; i < ntparms; i++)
12465       if (!TREE_VEC_ELT (targs, i))
12466         {
12467           tree tparm;
12468
12469           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
12470             continue;
12471
12472           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
12473
12474           /* If this is an undeduced nontype parameter that depends on
12475              a type parameter, try another pass; its type may have been
12476              deduced from a later argument than the one from which
12477              this parameter can be deduced.  */
12478           if (TREE_CODE (tparm) == PARM_DECL
12479               && uses_template_parms (TREE_TYPE (tparm))
12480               && !saw_undeduced++)
12481             goto again;
12482
12483           /* Core issue #226 (C++0x) [temp.deduct]:
12484
12485                If a template argument has not been deduced, its
12486                default template argument, if any, is used. 
12487
12488              When we are in C++98 mode, TREE_PURPOSE will either
12489              be NULL_TREE or ERROR_MARK_NODE, so we do not need
12490              to explicitly check cxx_dialect here.  */
12491           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
12492             {
12493               tree arg = tsubst (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)), 
12494                                  targs, tf_none, NULL_TREE);
12495               if (arg == error_mark_node)
12496                 return 1;
12497               else
12498                 {
12499                   TREE_VEC_ELT (targs, i) = arg;
12500                   continue;
12501                 }
12502             }
12503
12504           /* If the type parameter is a parameter pack, then it will
12505              be deduced to an empty parameter pack.  */
12506           if (template_parameter_pack_p (tparm))
12507             {
12508               tree arg;
12509
12510               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
12511                 {
12512                   arg = make_node (NONTYPE_ARGUMENT_PACK);
12513                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
12514                   TREE_CONSTANT (arg) = 1;
12515                 }
12516               else
12517                 arg = make_node (TYPE_ARGUMENT_PACK);
12518
12519               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
12520
12521               TREE_VEC_ELT (targs, i) = arg;
12522               continue;
12523             }
12524
12525           return 2;
12526         }
12527
12528   return 0;
12529 }
12530
12531 /* Subroutine of type_unification_real.  Args are like the variables
12532    at the call site.  ARG is an overloaded function (or template-id);
12533    we try deducing template args from each of the overloads, and if
12534    only one succeeds, we go with that.  Modifies TARGS and returns
12535    true on success.  */
12536
12537 static bool
12538 resolve_overloaded_unification (tree tparms,
12539                                 tree targs,
12540                                 tree parm,
12541                                 tree arg,
12542                                 unification_kind_t strict,
12543                                 int sub_strict)
12544 {
12545   tree tempargs = copy_node (targs);
12546   int good = 0;
12547   bool addr_p;
12548
12549   if (TREE_CODE (arg) == ADDR_EXPR)
12550     {
12551       arg = TREE_OPERAND (arg, 0);
12552       addr_p = true;
12553     }
12554   else
12555     addr_p = false;
12556
12557   if (TREE_CODE (arg) == COMPONENT_REF)
12558     /* Handle `&x' where `x' is some static or non-static member
12559        function name.  */
12560     arg = TREE_OPERAND (arg, 1);
12561
12562   if (TREE_CODE (arg) == OFFSET_REF)
12563     arg = TREE_OPERAND (arg, 1);
12564
12565   /* Strip baselink information.  */
12566   if (BASELINK_P (arg))
12567     arg = BASELINK_FUNCTIONS (arg);
12568
12569   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
12570     {
12571       /* If we got some explicit template args, we need to plug them into
12572          the affected templates before we try to unify, in case the
12573          explicit args will completely resolve the templates in question.  */
12574
12575       tree expl_subargs = TREE_OPERAND (arg, 1);
12576       arg = TREE_OPERAND (arg, 0);
12577
12578       for (; arg; arg = OVL_NEXT (arg))
12579         {
12580           tree fn = OVL_CURRENT (arg);
12581           tree subargs, elem;
12582
12583           if (TREE_CODE (fn) != TEMPLATE_DECL)
12584             continue;
12585
12586           ++processing_template_decl;
12587           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
12588                                   expl_subargs, /*check_ret=*/false);
12589           if (subargs)
12590             {
12591               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
12592               good += try_one_overload (tparms, targs, tempargs, parm,
12593                                         elem, strict, sub_strict, addr_p);
12594             }
12595           --processing_template_decl;
12596         }
12597     }
12598   else if (TREE_CODE (arg) != OVERLOAD
12599            && TREE_CODE (arg) != FUNCTION_DECL)
12600     /* If ARG is, for example, "(0, &f)" then its type will be unknown
12601        -- but the deduction does not succeed because the expression is
12602        not just the function on its own.  */
12603     return false;
12604   else
12605     for (; arg; arg = OVL_NEXT (arg))
12606       good += try_one_overload (tparms, targs, tempargs, parm,
12607                                 TREE_TYPE (OVL_CURRENT (arg)),
12608                                 strict, sub_strict, addr_p);
12609
12610   /* [temp.deduct.type] A template-argument can be deduced from a pointer
12611      to function or pointer to member function argument if the set of
12612      overloaded functions does not contain function templates and at most
12613      one of a set of overloaded functions provides a unique match.
12614
12615      So if we found multiple possibilities, we return success but don't
12616      deduce anything.  */
12617
12618   if (good == 1)
12619     {
12620       int i = TREE_VEC_LENGTH (targs);
12621       for (; i--; )
12622         if (TREE_VEC_ELT (tempargs, i))
12623           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
12624     }
12625   if (good)
12626     return true;
12627
12628   return false;
12629 }
12630
12631 /* Subroutine of resolve_overloaded_unification; does deduction for a single
12632    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
12633    different overloads deduce different arguments for a given parm.
12634    ADDR_P is true if the expression for which deduction is being
12635    performed was of the form "& fn" rather than simply "fn".
12636
12637    Returns 1 on success.  */
12638
12639 static int
12640 try_one_overload (tree tparms,
12641                   tree orig_targs,
12642                   tree targs,
12643                   tree parm,
12644                   tree arg,
12645                   unification_kind_t strict,
12646                   int sub_strict,
12647                   bool addr_p)
12648 {
12649   int nargs;
12650   tree tempargs;
12651   int i;
12652
12653   /* [temp.deduct.type] A template-argument can be deduced from a pointer
12654      to function or pointer to member function argument if the set of
12655      overloaded functions does not contain function templates and at most
12656      one of a set of overloaded functions provides a unique match.
12657
12658      So if this is a template, just return success.  */
12659
12660   if (uses_template_parms (arg))
12661     return 1;
12662
12663   if (TREE_CODE (arg) == METHOD_TYPE)
12664     arg = build_ptrmemfunc_type (build_pointer_type (arg));
12665   else if (addr_p)
12666     arg = build_pointer_type (arg);
12667
12668   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
12669
12670   /* We don't copy orig_targs for this because if we have already deduced
12671      some template args from previous args, unify would complain when we
12672      try to deduce a template parameter for the same argument, even though
12673      there isn't really a conflict.  */
12674   nargs = TREE_VEC_LENGTH (targs);
12675   tempargs = make_tree_vec (nargs);
12676
12677   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
12678     return 0;
12679
12680   /* First make sure we didn't deduce anything that conflicts with
12681      explicitly specified args.  */
12682   for (i = nargs; i--; )
12683     {
12684       tree elt = TREE_VEC_ELT (tempargs, i);
12685       tree oldelt = TREE_VEC_ELT (orig_targs, i);
12686
12687       if (!elt)
12688         /*NOP*/;
12689       else if (uses_template_parms (elt))
12690         /* Since we're unifying against ourselves, we will fill in
12691            template args used in the function parm list with our own
12692            template parms.  Discard them.  */
12693         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
12694       else if (oldelt && !template_args_equal (oldelt, elt))
12695         return 0;
12696     }
12697
12698   for (i = nargs; i--; )
12699     {
12700       tree elt = TREE_VEC_ELT (tempargs, i);
12701
12702       if (elt)
12703         TREE_VEC_ELT (targs, i) = elt;
12704     }
12705
12706   return 1;
12707 }
12708
12709 /* PARM is a template class (perhaps with unbound template
12710    parameters).  ARG is a fully instantiated type.  If ARG can be
12711    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
12712    TARGS are as for unify.  */
12713
12714 static tree
12715 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
12716 {
12717   tree copy_of_targs;
12718
12719   if (!CLASSTYPE_TEMPLATE_INFO (arg)
12720       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
12721           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
12722     return NULL_TREE;
12723
12724   /* We need to make a new template argument vector for the call to
12725      unify.  If we used TARGS, we'd clutter it up with the result of
12726      the attempted unification, even if this class didn't work out.
12727      We also don't want to commit ourselves to all the unifications
12728      we've already done, since unification is supposed to be done on
12729      an argument-by-argument basis.  In other words, consider the
12730      following pathological case:
12731
12732        template <int I, int J, int K>
12733        struct S {};
12734
12735        template <int I, int J>
12736        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
12737
12738        template <int I, int J, int K>
12739        void f(S<I, J, K>, S<I, I, I>);
12740
12741        void g() {
12742          S<0, 0, 0> s0;
12743          S<0, 1, 2> s2;
12744
12745          f(s0, s2);
12746        }
12747
12748      Now, by the time we consider the unification involving `s2', we
12749      already know that we must have `f<0, 0, 0>'.  But, even though
12750      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
12751      because there are two ways to unify base classes of S<0, 1, 2>
12752      with S<I, I, I>.  If we kept the already deduced knowledge, we
12753      would reject the possibility I=1.  */
12754   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
12755
12756   /* If unification failed, we're done.  */
12757   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
12758              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
12759     return NULL_TREE;
12760
12761   return arg;
12762 }
12763
12764 /* Given a template type PARM and a class type ARG, find the unique
12765    base type in ARG that is an instance of PARM.  We do not examine
12766    ARG itself; only its base-classes.  If there is not exactly one
12767    appropriate base class, return NULL_TREE.  PARM may be the type of
12768    a partial specialization, as well as a plain template type.  Used
12769    by unify.  */
12770
12771 static tree
12772 get_template_base (tree tparms, tree targs, tree parm, tree arg)
12773 {
12774   tree rval = NULL_TREE;
12775   tree binfo;
12776
12777   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
12778
12779   binfo = TYPE_BINFO (complete_type (arg));
12780   if (!binfo)
12781     /* The type could not be completed.  */
12782     return NULL_TREE;
12783
12784   /* Walk in inheritance graph order.  The search order is not
12785      important, and this avoids multiple walks of virtual bases.  */
12786   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
12787     {
12788       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
12789
12790       if (r)
12791         {
12792           /* If there is more than one satisfactory baseclass, then:
12793
12794                [temp.deduct.call]
12795
12796               If they yield more than one possible deduced A, the type
12797               deduction fails.
12798
12799              applies.  */
12800           if (rval && !same_type_p (r, rval))
12801             return NULL_TREE;
12802
12803           rval = r;
12804         }
12805     }
12806
12807   return rval;
12808 }
12809
12810 /* Returns the level of DECL, which declares a template parameter.  */
12811
12812 static int
12813 template_decl_level (tree decl)
12814 {
12815   switch (TREE_CODE (decl))
12816     {
12817     case TYPE_DECL:
12818     case TEMPLATE_DECL:
12819       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
12820
12821     case PARM_DECL:
12822       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
12823
12824     default:
12825       gcc_unreachable ();
12826     }
12827   return 0;
12828 }
12829
12830 /* Decide whether ARG can be unified with PARM, considering only the
12831    cv-qualifiers of each type, given STRICT as documented for unify.
12832    Returns nonzero iff the unification is OK on that basis.  */
12833
12834 static int
12835 check_cv_quals_for_unify (int strict, tree arg, tree parm)
12836 {
12837   int arg_quals = cp_type_quals (arg);
12838   int parm_quals = cp_type_quals (parm);
12839
12840   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
12841       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
12842     {
12843       /*  Although a CVR qualifier is ignored when being applied to a
12844           substituted template parameter ([8.3.2]/1 for example), that
12845           does not apply during deduction [14.8.2.4]/1, (even though
12846           that is not explicitly mentioned, [14.8.2.4]/9 indicates
12847           this).  Except when we're allowing additional CV qualifiers
12848           at the outer level [14.8.2.1]/3,1st bullet.  */
12849       if ((TREE_CODE (arg) == REFERENCE_TYPE
12850            || TREE_CODE (arg) == FUNCTION_TYPE
12851            || TREE_CODE (arg) == METHOD_TYPE)
12852           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
12853         return 0;
12854
12855       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
12856           && (parm_quals & TYPE_QUAL_RESTRICT))
12857         return 0;
12858     }
12859
12860   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
12861       && (arg_quals & parm_quals) != parm_quals)
12862     return 0;
12863
12864   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
12865       && (parm_quals & arg_quals) != arg_quals)
12866     return 0;
12867
12868   return 1;
12869 }
12870
12871 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
12872 void 
12873 template_parm_level_and_index (tree parm, int* level, int* index)
12874 {
12875   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
12876       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
12877       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
12878     {
12879       *index = TEMPLATE_TYPE_IDX (parm);
12880       *level = TEMPLATE_TYPE_LEVEL (parm);
12881     }
12882   else
12883     {
12884       *index = TEMPLATE_PARM_IDX (parm);
12885       *level = TEMPLATE_PARM_LEVEL (parm);
12886     }
12887 }
12888
12889 /* Unifies the remaining arguments in PACKED_ARGS with the pack
12890    expansion at the end of PACKED_PARMS. Returns 0 if the type
12891    deduction succeeds, 1 otherwise. STRICT is the same as in
12892    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
12893    call argument list. We'll need to adjust the arguments to make them
12894    types. SUBR tells us if this is from a recursive call to
12895    type_unification_real.  */
12896 int
12897 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
12898                       tree packed_args, int strict, bool call_args_p,
12899                       bool subr)
12900 {
12901   tree parm 
12902     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
12903   tree pattern = PACK_EXPANSION_PATTERN (parm);
12904   tree pack, packs = NULL_TREE;
12905   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
12906   int len = TREE_VEC_LENGTH (packed_args);
12907
12908   /* Determine the parameter packs we will be deducing from the
12909      pattern, and record their current deductions.  */
12910   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
12911        pack; pack = TREE_CHAIN (pack))
12912     {
12913       tree parm_pack = TREE_VALUE (pack);
12914       int idx, level;
12915
12916       /* Determine the index and level of this parameter pack.  */
12917       template_parm_level_and_index (parm_pack, &level, &idx);
12918
12919       /* Keep track of the parameter packs and their corresponding
12920          argument packs.  */
12921       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
12922       TREE_TYPE (packs) = make_tree_vec (len - start);
12923     }
12924   
12925   /* Loop through all of the arguments that have not yet been
12926      unified and unify each with the pattern.  */
12927   for (i = start; i < len; i++)
12928     {
12929       tree parm = pattern;
12930
12931       /* For each parameter pack, clear out the deduced value so that
12932          we can deduce it again.  */
12933       for (pack = packs; pack; pack = TREE_CHAIN (pack))
12934         {
12935           int idx, level;
12936           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
12937
12938           TMPL_ARG (targs, level, idx) = NULL_TREE;
12939         }
12940
12941       /* Unify the pattern with the current argument.  */
12942       {
12943         tree arg = TREE_VEC_ELT (packed_args, i);
12944         tree arg_expr = NULL_TREE;
12945         int arg_strict = strict;
12946         bool skip_arg_p = false;
12947
12948         if (call_args_p)
12949           {
12950             int sub_strict;
12951
12952             /* This mirrors what we do in type_unification_real.  */
12953             switch (strict)
12954               {
12955               case DEDUCE_CALL:
12956                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
12957                               | UNIFY_ALLOW_MORE_CV_QUAL
12958                               | UNIFY_ALLOW_DERIVED);
12959                 break;
12960                 
12961               case DEDUCE_CONV:
12962                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
12963                 break;
12964                 
12965               case DEDUCE_EXACT:
12966                 sub_strict = UNIFY_ALLOW_NONE;
12967                 break;
12968                 
12969               default:
12970                 gcc_unreachable ();
12971               }
12972
12973             if (!TYPE_P (arg))
12974               {
12975                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
12976                 if (type_unknown_p (arg))
12977                   {
12978                     /* [temp.deduct.type] A template-argument can be
12979                        deduced from a pointer to function or pointer
12980                        to member function argument if the set of
12981                        overloaded functions does not contain function
12982                        templates and at most one of a set of
12983                        overloaded functions provides a unique
12984                        match.  */
12985
12986                     if (resolve_overloaded_unification
12987                         (tparms, targs, parm, arg, strict, sub_strict)
12988                         != 0)
12989                       return 1;
12990                     skip_arg_p = true;
12991                   }
12992
12993                 if (!skip_arg_p)
12994                   {
12995                     arg_expr = arg;
12996                     arg = unlowered_expr_type (arg);
12997                     if (arg == error_mark_node)
12998                       return 1;
12999                   }
13000               }
13001       
13002             arg_strict = sub_strict;
13003
13004             if (!subr)
13005               arg_strict |= 
13006                 maybe_adjust_types_for_deduction (strict, &parm, &arg, 
13007                                                   arg_expr);
13008           }
13009
13010         if (!skip_arg_p)
13011           {
13012             if (unify (tparms, targs, parm, arg, arg_strict))
13013               return 1;
13014           }
13015       }
13016
13017       /* For each parameter pack, collect the deduced value.  */
13018       for (pack = packs; pack; pack = TREE_CHAIN (pack))
13019         {
13020           int idx, level;
13021           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13022
13023           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
13024             TMPL_ARG (targs, level, idx);
13025         }
13026     }
13027
13028   /* Verify that the results of unification with the parameter packs
13029      produce results consistent with what we've seen before, and make
13030      the deduced argument packs available.  */
13031   for (pack = packs; pack; pack = TREE_CHAIN (pack))
13032     {
13033       tree old_pack = TREE_VALUE (pack);
13034       tree new_args = TREE_TYPE (pack);
13035       int i, len = TREE_VEC_LENGTH (new_args);
13036       bool nondeduced_p = false;
13037
13038       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
13039          actually deduce anything.  */
13040       for (i = 0; i < len && !nondeduced_p; ++i)
13041         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
13042           nondeduced_p = true;
13043       if (nondeduced_p)
13044         continue;
13045
13046       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
13047         {
13048           /* Prepend the explicit arguments onto NEW_ARGS.  */
13049           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
13050           tree old_args = new_args;
13051           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
13052           int len = explicit_len + TREE_VEC_LENGTH (old_args);
13053
13054           /* Copy the explicit arguments.  */
13055           new_args = make_tree_vec (len);
13056           for (i = 0; i < explicit_len; i++)
13057             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
13058
13059           /* Copy the deduced arguments.  */
13060           for (; i < len; i++)
13061             TREE_VEC_ELT (new_args, i) =
13062               TREE_VEC_ELT (old_args, i - explicit_len);
13063         }
13064
13065       if (!old_pack)
13066         {
13067           tree result;
13068           int idx, level;
13069           
13070           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13071
13072           /* Build the deduced *_ARGUMENT_PACK.  */
13073           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
13074             {
13075               result = make_node (NONTYPE_ARGUMENT_PACK);
13076               TREE_TYPE (result) = 
13077                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
13078               TREE_CONSTANT (result) = 1;
13079             }
13080           else
13081             result = make_node (TYPE_ARGUMENT_PACK);
13082
13083           SET_ARGUMENT_PACK_ARGS (result, new_args);
13084
13085           /* Note the deduced argument packs for this parameter
13086              pack.  */
13087           TMPL_ARG (targs, level, idx) = result;
13088         }
13089       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
13090                && (ARGUMENT_PACK_ARGS (old_pack) 
13091                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
13092         {
13093           /* We only had the explicitly-provided arguments before, but
13094              now we have a complete set of arguments.  */
13095           int idx, level;
13096           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
13097           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13098
13099           /* Keep the original deduced argument pack.  */
13100           TMPL_ARG (targs, level, idx) = old_pack;
13101
13102           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
13103           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
13104           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
13105         }
13106       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
13107                                     new_args))
13108         /* Inconsistent unification of this parameter pack.  */
13109         return 1;
13110       else
13111         {
13112           int idx, level;
13113           
13114           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13115
13116           /* Keep the original deduced argument pack.  */
13117           TMPL_ARG (targs, level, idx) = old_pack;
13118         }
13119     }
13120
13121   return 0;
13122 }
13123
13124 /* Deduce the value of template parameters.  TPARMS is the (innermost)
13125    set of template parameters to a template.  TARGS is the bindings
13126    for those template parameters, as determined thus far; TARGS may
13127    include template arguments for outer levels of template parameters
13128    as well.  PARM is a parameter to a template function, or a
13129    subcomponent of that parameter; ARG is the corresponding argument.
13130    This function attempts to match PARM with ARG in a manner
13131    consistent with the existing assignments in TARGS.  If more values
13132    are deduced, then TARGS is updated.
13133
13134    Returns 0 if the type deduction succeeds, 1 otherwise.  The
13135    parameter STRICT is a bitwise or of the following flags:
13136
13137      UNIFY_ALLOW_NONE:
13138        Require an exact match between PARM and ARG.
13139      UNIFY_ALLOW_MORE_CV_QUAL:
13140        Allow the deduced ARG to be more cv-qualified (by qualification
13141        conversion) than ARG.
13142      UNIFY_ALLOW_LESS_CV_QUAL:
13143        Allow the deduced ARG to be less cv-qualified than ARG.
13144      UNIFY_ALLOW_DERIVED:
13145        Allow the deduced ARG to be a template base class of ARG,
13146        or a pointer to a template base class of the type pointed to by
13147        ARG.
13148      UNIFY_ALLOW_INTEGER:
13149        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
13150        case for more information.
13151      UNIFY_ALLOW_OUTER_LEVEL:
13152        This is the outermost level of a deduction. Used to determine validity
13153        of qualification conversions. A valid qualification conversion must
13154        have const qualified pointers leading up to the inner type which
13155        requires additional CV quals, except at the outer level, where const
13156        is not required [conv.qual]. It would be normal to set this flag in
13157        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
13158      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
13159        This is the outermost level of a deduction, and PARM can be more CV
13160        qualified at this point.
13161      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
13162        This is the outermost level of a deduction, and PARM can be less CV
13163        qualified at this point.  */
13164
13165 static int
13166 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
13167 {
13168   int idx;
13169   tree targ;
13170   tree tparm;
13171   int strict_in = strict;
13172
13173   /* I don't think this will do the right thing with respect to types.
13174      But the only case I've seen it in so far has been array bounds, where
13175      signedness is the only information lost, and I think that will be
13176      okay.  */
13177   while (TREE_CODE (parm) == NOP_EXPR)
13178     parm = TREE_OPERAND (parm, 0);
13179
13180   if (arg == error_mark_node)
13181     return 1;
13182   if (arg == unknown_type_node
13183       || arg == init_list_type_node)
13184     /* We can't deduce anything from this, but we might get all the
13185        template args from other function args.  */
13186     return 0;
13187
13188   /* If PARM uses template parameters, then we can't bail out here,
13189      even if ARG == PARM, since we won't record unifications for the
13190      template parameters.  We might need them if we're trying to
13191      figure out which of two things is more specialized.  */
13192   if (arg == parm && !uses_template_parms (parm))
13193     return 0;
13194
13195   /* Handle init lists early, so the rest of the function can assume
13196      we're dealing with a type. */
13197   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
13198     {
13199       tree elt, elttype;
13200       unsigned i;
13201
13202       if (!is_std_init_list (parm))
13203         /* We can only deduce from an initializer list argument if the
13204            parameter is std::initializer_list; otherwise this is a
13205            non-deduced context. */
13206         return 0;
13207
13208       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
13209
13210       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
13211         {
13212           int elt_strict = strict;
13213           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
13214             {
13215               tree type = TREE_TYPE (elt);
13216               /* It should only be possible to get here for a call.  */
13217               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
13218               elt_strict |= maybe_adjust_types_for_deduction
13219                 (DEDUCE_CALL, &elttype, &type, elt);
13220               elt = type;
13221             }
13222
13223           if (unify (tparms, targs, elttype, elt, elt_strict))
13224             return 1;
13225         }
13226       return 0;
13227     }
13228
13229   /* Immediately reject some pairs that won't unify because of
13230      cv-qualification mismatches.  */
13231   if (TREE_CODE (arg) == TREE_CODE (parm)
13232       && TYPE_P (arg)
13233       /* It is the elements of the array which hold the cv quals of an array
13234          type, and the elements might be template type parms. We'll check
13235          when we recurse.  */
13236       && TREE_CODE (arg) != ARRAY_TYPE
13237       /* We check the cv-qualifiers when unifying with template type
13238          parameters below.  We want to allow ARG `const T' to unify with
13239          PARM `T' for example, when computing which of two templates
13240          is more specialized, for example.  */
13241       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
13242       && !check_cv_quals_for_unify (strict_in, arg, parm))
13243     return 1;
13244
13245   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
13246       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
13247     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
13248   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
13249   strict &= ~UNIFY_ALLOW_DERIVED;
13250   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
13251   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
13252
13253   switch (TREE_CODE (parm))
13254     {
13255     case TYPENAME_TYPE:
13256     case SCOPE_REF:
13257     case UNBOUND_CLASS_TEMPLATE:
13258       /* In a type which contains a nested-name-specifier, template
13259          argument values cannot be deduced for template parameters used
13260          within the nested-name-specifier.  */
13261       return 0;
13262
13263     case TEMPLATE_TYPE_PARM:
13264     case TEMPLATE_TEMPLATE_PARM:
13265     case BOUND_TEMPLATE_TEMPLATE_PARM:
13266       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
13267       if (tparm == error_mark_node)
13268         return 1;
13269
13270       if (TEMPLATE_TYPE_LEVEL (parm)
13271           != template_decl_level (tparm))
13272         /* The PARM is not one we're trying to unify.  Just check
13273            to see if it matches ARG.  */
13274         return (TREE_CODE (arg) == TREE_CODE (parm)
13275                 && same_type_p (parm, arg)) ? 0 : 1;
13276       idx = TEMPLATE_TYPE_IDX (parm);
13277       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
13278       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
13279
13280       /* Check for mixed types and values.  */
13281       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13282            && TREE_CODE (tparm) != TYPE_DECL)
13283           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13284               && TREE_CODE (tparm) != TEMPLATE_DECL))
13285         return 1;
13286
13287       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13288         {
13289           /* ARG must be constructed from a template class or a template
13290              template parameter.  */
13291           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
13292               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
13293             return 1;
13294
13295           {
13296             tree parmvec = TYPE_TI_ARGS (parm);
13297             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
13298             tree parm_parms 
13299               = DECL_INNERMOST_TEMPLATE_PARMS
13300                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
13301             int i, len;
13302             int parm_variadic_p = 0;
13303
13304             /* The resolution to DR150 makes clear that default
13305                arguments for an N-argument may not be used to bind T
13306                to a template template parameter with fewer than N
13307                parameters.  It is not safe to permit the binding of
13308                default arguments as an extension, as that may change
13309                the meaning of a conforming program.  Consider:
13310
13311                   struct Dense { static const unsigned int dim = 1; };
13312
13313                   template <template <typename> class View,
13314                             typename Block>
13315                   void operator+(float, View<Block> const&);
13316
13317                   template <typename Block,
13318                             unsigned int Dim = Block::dim>
13319                   struct Lvalue_proxy { operator float() const; };
13320
13321                   void
13322                   test_1d (void) {
13323                     Lvalue_proxy<Dense> p;
13324                     float b;
13325                     b + p;
13326                   }
13327
13328               Here, if Lvalue_proxy is permitted to bind to View, then
13329               the global operator+ will be used; if they are not, the
13330               Lvalue_proxy will be converted to float.  */
13331             if (coerce_template_parms (parm_parms,
13332                                        argvec,
13333                                        TYPE_TI_TEMPLATE (parm),
13334                                        tf_none,
13335                                        /*require_all_args=*/true,
13336                                        /*use_default_args=*/false)
13337                 == error_mark_node)
13338               return 1;
13339
13340             /* Deduce arguments T, i from TT<T> or TT<i>.
13341                We check each element of PARMVEC and ARGVEC individually
13342                rather than the whole TREE_VEC since they can have
13343                different number of elements.  */
13344
13345             parmvec = expand_template_argument_pack (parmvec);
13346             argvec = expand_template_argument_pack (argvec);
13347
13348             len = TREE_VEC_LENGTH (parmvec);
13349
13350             /* Check if the parameters end in a pack, making them
13351                variadic.  */
13352             if (len > 0
13353                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
13354               parm_variadic_p = 1;
13355             
13356             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
13357               return 1;
13358
13359              for (i = 0; i < len - parm_variadic_p; ++i)
13360               {
13361                 if (unify (tparms, targs,
13362                            TREE_VEC_ELT (parmvec, i),
13363                            TREE_VEC_ELT (argvec, i),
13364                            UNIFY_ALLOW_NONE))
13365                   return 1;
13366               }
13367
13368             if (parm_variadic_p
13369                 && unify_pack_expansion (tparms, targs,
13370                                          parmvec, argvec,
13371                                          UNIFY_ALLOW_NONE,
13372                                          /*call_args_p=*/false,
13373                                          /*subr=*/false))
13374               return 1;
13375           }
13376           arg = TYPE_TI_TEMPLATE (arg);
13377
13378           /* Fall through to deduce template name.  */
13379         }
13380
13381       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13382           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13383         {
13384           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
13385
13386           /* Simple cases: Value already set, does match or doesn't.  */
13387           if (targ != NULL_TREE && template_args_equal (targ, arg))
13388             return 0;
13389           else if (targ)
13390             return 1;
13391         }
13392       else
13393         {
13394           /* If PARM is `const T' and ARG is only `int', we don't have
13395              a match unless we are allowing additional qualification.
13396              If ARG is `const int' and PARM is just `T' that's OK;
13397              that binds `const int' to `T'.  */
13398           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
13399                                          arg, parm))
13400             return 1;
13401
13402           /* Consider the case where ARG is `const volatile int' and
13403              PARM is `const T'.  Then, T should be `volatile int'.  */
13404           arg = cp_build_qualified_type_real
13405             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
13406           if (arg == error_mark_node)
13407             return 1;
13408
13409           /* Simple cases: Value already set, does match or doesn't.  */
13410           if (targ != NULL_TREE && same_type_p (targ, arg))
13411             return 0;
13412           else if (targ)
13413             return 1;
13414
13415           /* Make sure that ARG is not a variable-sized array.  (Note
13416              that were talking about variable-sized arrays (like
13417              `int[n]'), rather than arrays of unknown size (like
13418              `int[]').)  We'll get very confused by such a type since
13419              the bound of the array will not be computable in an
13420              instantiation.  Besides, such types are not allowed in
13421              ISO C++, so we can do as we please here.  */
13422           if (variably_modified_type_p (arg, NULL_TREE))
13423             return 1;
13424         }
13425
13426       /* If ARG is a parameter pack or an expansion, we cannot unify
13427          against it unless PARM is also a parameter pack.  */
13428       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
13429           && !template_parameter_pack_p (parm))
13430         return 1;
13431
13432       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
13433       return 0;
13434
13435     case TEMPLATE_PARM_INDEX:
13436       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
13437       if (tparm == error_mark_node)
13438         return 1;
13439
13440       if (TEMPLATE_PARM_LEVEL (parm)
13441           != template_decl_level (tparm))
13442         /* The PARM is not one we're trying to unify.  Just check
13443            to see if it matches ARG.  */
13444         return !(TREE_CODE (arg) == TREE_CODE (parm)
13445                  && cp_tree_equal (parm, arg));
13446
13447       idx = TEMPLATE_PARM_IDX (parm);
13448       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
13449
13450       if (targ)
13451         return !cp_tree_equal (targ, arg);
13452
13453       /* [temp.deduct.type] If, in the declaration of a function template
13454          with a non-type template-parameter, the non-type
13455          template-parameter is used in an expression in the function
13456          parameter-list and, if the corresponding template-argument is
13457          deduced, the template-argument type shall match the type of the
13458          template-parameter exactly, except that a template-argument
13459          deduced from an array bound may be of any integral type.
13460          The non-type parameter might use already deduced type parameters.  */
13461       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
13462       if (!TREE_TYPE (arg))
13463         /* Template-parameter dependent expression.  Just accept it for now.
13464            It will later be processed in convert_template_argument.  */
13465         ;
13466       else if (same_type_p (TREE_TYPE (arg), tparm))
13467         /* OK */;
13468       else if ((strict & UNIFY_ALLOW_INTEGER)
13469                && (TREE_CODE (tparm) == INTEGER_TYPE
13470                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
13471         /* Convert the ARG to the type of PARM; the deduced non-type
13472            template argument must exactly match the types of the
13473            corresponding parameter.  */
13474         arg = fold (build_nop (tparm, arg));
13475       else if (uses_template_parms (tparm))
13476         /* We haven't deduced the type of this parameter yet.  Try again
13477            later.  */
13478         return 0;
13479       else
13480         return 1;
13481
13482       /* If ARG is a parameter pack or an expansion, we cannot unify
13483          against it unless PARM is also a parameter pack.  */
13484       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
13485           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
13486         return 1;
13487
13488       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
13489       return 0;
13490
13491     case PTRMEM_CST:
13492      {
13493         /* A pointer-to-member constant can be unified only with
13494          another constant.  */
13495       if (TREE_CODE (arg) != PTRMEM_CST)
13496         return 1;
13497
13498       /* Just unify the class member. It would be useless (and possibly
13499          wrong, depending on the strict flags) to unify also
13500          PTRMEM_CST_CLASS, because we want to be sure that both parm and
13501          arg refer to the same variable, even if through different
13502          classes. For instance:
13503
13504          struct A { int x; };
13505          struct B : A { };
13506
13507          Unification of &A::x and &B::x must succeed.  */
13508       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
13509                     PTRMEM_CST_MEMBER (arg), strict);
13510      }
13511
13512     case POINTER_TYPE:
13513       {
13514         if (TREE_CODE (arg) != POINTER_TYPE)
13515           return 1;
13516
13517         /* [temp.deduct.call]
13518
13519            A can be another pointer or pointer to member type that can
13520            be converted to the deduced A via a qualification
13521            conversion (_conv.qual_).
13522
13523            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
13524            This will allow for additional cv-qualification of the
13525            pointed-to types if appropriate.  */
13526
13527         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
13528           /* The derived-to-base conversion only persists through one
13529              level of pointers.  */
13530           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
13531
13532         return unify (tparms, targs, TREE_TYPE (parm),
13533                       TREE_TYPE (arg), strict);
13534       }
13535
13536     case REFERENCE_TYPE:
13537       if (TREE_CODE (arg) != REFERENCE_TYPE)
13538         return 1;
13539       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
13540                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
13541
13542     case ARRAY_TYPE:
13543       if (TREE_CODE (arg) != ARRAY_TYPE)
13544         return 1;
13545       if ((TYPE_DOMAIN (parm) == NULL_TREE)
13546           != (TYPE_DOMAIN (arg) == NULL_TREE))
13547         return 1;
13548       if (TYPE_DOMAIN (parm) != NULL_TREE)
13549         {
13550           tree parm_max;
13551           tree arg_max;
13552           bool parm_cst;
13553           bool arg_cst;
13554
13555           /* Our representation of array types uses "N - 1" as the
13556              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
13557              not an integer constant.  We cannot unify arbitrarily
13558              complex expressions, so we eliminate the MINUS_EXPRs
13559              here.  */
13560           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
13561           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
13562           if (!parm_cst)
13563             {
13564               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
13565               parm_max = TREE_OPERAND (parm_max, 0);
13566             }
13567           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
13568           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
13569           if (!arg_cst)
13570             {
13571               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
13572                  trying to unify the type of a variable with the type
13573                  of a template parameter.  For example:
13574
13575                    template <unsigned int N>
13576                    void f (char (&) [N]);
13577                    int g(); 
13578                    void h(int i) {
13579                      char a[g(i)];
13580                      f(a); 
13581                    }
13582
13583                 Here, the type of the ARG will be "int [g(i)]", and
13584                 may be a SAVE_EXPR, etc.  */
13585               if (TREE_CODE (arg_max) != MINUS_EXPR)
13586                 return 1;
13587               arg_max = TREE_OPERAND (arg_max, 0);
13588             }
13589
13590           /* If only one of the bounds used a MINUS_EXPR, compensate
13591              by adding one to the other bound.  */
13592           if (parm_cst && !arg_cst)
13593             parm_max = fold_build2 (PLUS_EXPR,
13594                                     integer_type_node,
13595                                     parm_max,
13596                                     integer_one_node);
13597           else if (arg_cst && !parm_cst)
13598             arg_max = fold_build2 (PLUS_EXPR,
13599                                    integer_type_node,
13600                                    arg_max,
13601                                    integer_one_node);
13602
13603           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
13604             return 1;
13605         }
13606       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
13607                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
13608
13609     case REAL_TYPE:
13610     case COMPLEX_TYPE:
13611     case VECTOR_TYPE:
13612     case INTEGER_TYPE:
13613     case BOOLEAN_TYPE:
13614     case ENUMERAL_TYPE:
13615     case VOID_TYPE:
13616       if (TREE_CODE (arg) != TREE_CODE (parm))
13617         return 1;
13618
13619       /* We have already checked cv-qualification at the top of the
13620          function.  */
13621       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
13622         return 1;
13623
13624       /* As far as unification is concerned, this wins.  Later checks
13625          will invalidate it if necessary.  */
13626       return 0;
13627
13628       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
13629       /* Type INTEGER_CST can come from ordinary constant template args.  */
13630     case INTEGER_CST:
13631       while (TREE_CODE (arg) == NOP_EXPR)
13632         arg = TREE_OPERAND (arg, 0);
13633
13634       if (TREE_CODE (arg) != INTEGER_CST)
13635         return 1;
13636       return !tree_int_cst_equal (parm, arg);
13637
13638     case TREE_VEC:
13639       {
13640         int i;
13641         if (TREE_CODE (arg) != TREE_VEC)
13642           return 1;
13643         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
13644           return 1;
13645         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
13646           if (unify (tparms, targs,
13647                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
13648                      UNIFY_ALLOW_NONE))
13649             return 1;
13650         return 0;
13651       }
13652
13653     case RECORD_TYPE:
13654     case UNION_TYPE:
13655       if (TREE_CODE (arg) != TREE_CODE (parm))
13656         return 1;
13657
13658       if (TYPE_PTRMEMFUNC_P (parm))
13659         {
13660           if (!TYPE_PTRMEMFUNC_P (arg))
13661             return 1;
13662
13663           return unify (tparms, targs,
13664                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
13665                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
13666                         strict);
13667         }
13668
13669       if (CLASSTYPE_TEMPLATE_INFO (parm))
13670         {
13671           tree t = NULL_TREE;
13672
13673           if (strict_in & UNIFY_ALLOW_DERIVED)
13674             {
13675               /* First, we try to unify the PARM and ARG directly.  */
13676               t = try_class_unification (tparms, targs,
13677                                          parm, arg);
13678
13679               if (!t)
13680                 {
13681                   /* Fallback to the special case allowed in
13682                      [temp.deduct.call]:
13683
13684                        If P is a class, and P has the form
13685                        template-id, then A can be a derived class of
13686                        the deduced A.  Likewise, if P is a pointer to
13687                        a class of the form template-id, A can be a
13688                        pointer to a derived class pointed to by the
13689                        deduced A.  */
13690                   t = get_template_base (tparms, targs, parm, arg);
13691
13692                   if (!t)
13693                     return 1;
13694                 }
13695             }
13696           else if (CLASSTYPE_TEMPLATE_INFO (arg)
13697                    && (CLASSTYPE_TI_TEMPLATE (parm)
13698                        == CLASSTYPE_TI_TEMPLATE (arg)))
13699             /* Perhaps PARM is something like S<U> and ARG is S<int>.
13700                Then, we should unify `int' and `U'.  */
13701             t = arg;
13702           else
13703             /* There's no chance of unification succeeding.  */
13704             return 1;
13705
13706           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
13707                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
13708         }
13709       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
13710         return 1;
13711       return 0;
13712
13713     case METHOD_TYPE:
13714     case FUNCTION_TYPE:
13715       if (TREE_CODE (arg) != TREE_CODE (parm))
13716         return 1;
13717
13718       /* CV qualifications for methods can never be deduced, they must
13719          match exactly.  We need to check them explicitly here,
13720          because type_unification_real treats them as any other
13721          cv-qualified parameter.  */
13722       if (TREE_CODE (parm) == METHOD_TYPE
13723           && (!check_cv_quals_for_unify
13724               (UNIFY_ALLOW_NONE,
13725                TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
13726                TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
13727         return 1;
13728
13729       if (unify (tparms, targs, TREE_TYPE (parm),
13730                  TREE_TYPE (arg), UNIFY_ALLOW_NONE))
13731         return 1;
13732       return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
13733                                     TYPE_ARG_TYPES (arg), 1, DEDUCE_EXACT,
13734                                     LOOKUP_NORMAL);
13735
13736     case OFFSET_TYPE:
13737       /* Unify a pointer to member with a pointer to member function, which
13738          deduces the type of the member as a function type. */
13739       if (TYPE_PTRMEMFUNC_P (arg))
13740         {
13741           tree method_type;
13742           tree fntype;
13743           cp_cv_quals cv_quals;
13744
13745           /* Check top-level cv qualifiers */
13746           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
13747             return 1;
13748
13749           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
13750                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
13751             return 1;
13752
13753           /* Determine the type of the function we are unifying against. */
13754           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
13755           fntype =
13756             build_function_type (TREE_TYPE (method_type),
13757                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
13758
13759           /* Extract the cv-qualifiers of the member function from the
13760              implicit object parameter and place them on the function
13761              type to be restored later. */
13762           cv_quals =
13763             cp_type_quals(TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (method_type))));
13764           fntype = build_qualified_type (fntype, cv_quals);
13765           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
13766         }
13767
13768       if (TREE_CODE (arg) != OFFSET_TYPE)
13769         return 1;
13770       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
13771                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
13772         return 1;
13773       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
13774                     strict);
13775
13776     case CONST_DECL:
13777       if (DECL_TEMPLATE_PARM_P (parm))
13778         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
13779       if (arg != integral_constant_value (parm))
13780         return 1;
13781       return 0;
13782
13783     case FIELD_DECL:
13784     case TEMPLATE_DECL:
13785       /* Matched cases are handled by the ARG == PARM test above.  */
13786       return 1;
13787
13788     case TYPE_ARGUMENT_PACK:
13789     case NONTYPE_ARGUMENT_PACK:
13790       {
13791         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
13792         tree packed_args = ARGUMENT_PACK_ARGS (arg);
13793         int i, len = TREE_VEC_LENGTH (packed_parms);
13794         int argslen = TREE_VEC_LENGTH (packed_args);
13795         int parm_variadic_p = 0;
13796
13797         for (i = 0; i < len; ++i)
13798           {
13799             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
13800               {
13801                 if (i == len - 1)
13802                   /* We can unify against something with a trailing
13803                      parameter pack.  */
13804                   parm_variadic_p = 1;
13805                 else
13806                   /* Since there is something following the pack
13807                      expansion, we cannot unify this template argument
13808                      list.  */
13809                   return 0;
13810               }
13811           }
13812           
13813
13814         /* If we don't have enough arguments to satisfy the parameters
13815            (not counting the pack expression at the end), or we have
13816            too many arguments for a parameter list that doesn't end in
13817            a pack expression, we can't unify.  */
13818         if (argslen < (len - parm_variadic_p)
13819             || (argslen > len && !parm_variadic_p))
13820           return 1;
13821
13822         /* Unify all of the parameters that precede the (optional)
13823            pack expression.  */
13824         for (i = 0; i < len - parm_variadic_p; ++i)
13825           {
13826             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
13827                        TREE_VEC_ELT (packed_args, i), strict))
13828               return 1;
13829           }
13830
13831         if (parm_variadic_p)
13832           return unify_pack_expansion (tparms, targs, 
13833                                        packed_parms, packed_args,
13834                                        strict, /*call_args_p=*/false,
13835                                        /*subr=*/false);
13836         return 0;
13837       }
13838
13839       break;
13840
13841     case TYPEOF_TYPE:
13842     case DECLTYPE_TYPE:
13843       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
13844          nodes.  */
13845       return 0;
13846
13847     case ERROR_MARK:
13848       /* Unification fails if we hit an error node.  */
13849       return 1;
13850
13851     default:
13852       gcc_assert (EXPR_P (parm));
13853
13854       /* We must be looking at an expression.  This can happen with
13855          something like:
13856
13857            template <int I>
13858            void foo(S<I>, S<I + 2>);
13859
13860          This is a "nondeduced context":
13861
13862            [deduct.type]
13863
13864            The nondeduced contexts are:
13865
13866            --A type that is a template-id in which one or more of
13867              the template-arguments is an expression that references
13868              a template-parameter.
13869
13870          In these cases, we assume deduction succeeded, but don't
13871          actually infer any unifications.  */
13872
13873       if (!uses_template_parms (parm)
13874           && !template_args_equal (parm, arg))
13875         return 1;
13876       else
13877         return 0;
13878     }
13879 }
13880 \f
13881 /* Note that DECL can be defined in this translation unit, if
13882    required.  */
13883
13884 static void
13885 mark_definable (tree decl)
13886 {
13887   tree clone;
13888   DECL_NOT_REALLY_EXTERN (decl) = 1;
13889   FOR_EACH_CLONE (clone, decl)
13890     DECL_NOT_REALLY_EXTERN (clone) = 1;
13891 }
13892
13893 /* Called if RESULT is explicitly instantiated, or is a member of an
13894    explicitly instantiated class.  */
13895
13896 void
13897 mark_decl_instantiated (tree result, int extern_p)
13898 {
13899   SET_DECL_EXPLICIT_INSTANTIATION (result);
13900
13901   /* If this entity has already been written out, it's too late to
13902      make any modifications.  */
13903   if (TREE_ASM_WRITTEN (result))
13904     return;
13905
13906   if (TREE_CODE (result) != FUNCTION_DECL)
13907     /* The TREE_PUBLIC flag for function declarations will have been
13908        set correctly by tsubst.  */
13909     TREE_PUBLIC (result) = 1;
13910
13911   /* This might have been set by an earlier implicit instantiation.  */
13912   DECL_COMDAT (result) = 0;
13913
13914   if (extern_p)
13915     DECL_NOT_REALLY_EXTERN (result) = 0;
13916   else
13917     {
13918       mark_definable (result);
13919       /* Always make artificials weak.  */
13920       if (DECL_ARTIFICIAL (result) && flag_weak)
13921         comdat_linkage (result);
13922       /* For WIN32 we also want to put explicit instantiations in
13923          linkonce sections.  */
13924       else if (TREE_PUBLIC (result))
13925         maybe_make_one_only (result);
13926     }
13927
13928   /* If EXTERN_P, then this function will not be emitted -- unless
13929      followed by an explicit instantiation, at which point its linkage
13930      will be adjusted.  If !EXTERN_P, then this function will be
13931      emitted here.  In neither circumstance do we want
13932      import_export_decl to adjust the linkage.  */
13933   DECL_INTERFACE_KNOWN (result) = 1;
13934 }
13935
13936 /* Given two function templates PAT1 and PAT2, return:
13937
13938    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
13939    -1 if PAT2 is more specialized than PAT1.
13940    0 if neither is more specialized.
13941
13942    LEN indicates the number of parameters we should consider
13943    (defaulted parameters should not be considered).
13944
13945    The 1998 std underspecified function template partial ordering, and
13946    DR214 addresses the issue.  We take pairs of arguments, one from
13947    each of the templates, and deduce them against each other.  One of
13948    the templates will be more specialized if all the *other*
13949    template's arguments deduce against its arguments and at least one
13950    of its arguments *does* *not* deduce against the other template's
13951    corresponding argument.  Deduction is done as for class templates.
13952    The arguments used in deduction have reference and top level cv
13953    qualifiers removed.  Iff both arguments were originally reference
13954    types *and* deduction succeeds in both directions, the template
13955    with the more cv-qualified argument wins for that pairing (if
13956    neither is more cv-qualified, they both are equal).  Unlike regular
13957    deduction, after all the arguments have been deduced in this way,
13958    we do *not* verify the deduced template argument values can be
13959    substituted into non-deduced contexts, nor do we have to verify
13960    that all template arguments have been deduced.  */
13961
13962 int
13963 more_specialized_fn (tree pat1, tree pat2, int len)
13964 {
13965   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
13966   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
13967   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
13968   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
13969   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
13970   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
13971   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
13972   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
13973   int better1 = 0;
13974   int better2 = 0;
13975
13976   /* Remove the this parameter from non-static member functions.  If
13977      one is a non-static member function and the other is not a static
13978      member function, remove the first parameter from that function
13979      also.  This situation occurs for operator functions where we
13980      locate both a member function (with this pointer) and non-member
13981      operator (with explicit first operand).  */
13982   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
13983     {
13984       len--; /* LEN is the number of significant arguments for DECL1 */
13985       args1 = TREE_CHAIN (args1);
13986       if (!DECL_STATIC_FUNCTION_P (decl2))
13987         args2 = TREE_CHAIN (args2);
13988     }
13989   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
13990     {
13991       args2 = TREE_CHAIN (args2);
13992       if (!DECL_STATIC_FUNCTION_P (decl1))
13993         {
13994           len--;
13995           args1 = TREE_CHAIN (args1);
13996         }
13997     }
13998
13999   /* If only one is a conversion operator, they are unordered.  */
14000   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
14001     return 0;
14002
14003   /* Consider the return type for a conversion function */
14004   if (DECL_CONV_FN_P (decl1))
14005     {
14006       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
14007       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
14008       len++;
14009     }
14010
14011   processing_template_decl++;
14012
14013   while (len--
14014          /* Stop when an ellipsis is seen.  */
14015          && args1 != NULL_TREE && args2 != NULL_TREE)
14016     {
14017       tree arg1 = TREE_VALUE (args1);
14018       tree arg2 = TREE_VALUE (args2);
14019       int deduce1, deduce2;
14020       int quals1 = -1;
14021       int quals2 = -1;
14022
14023       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
14024           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
14025         {
14026           /* When both arguments are pack expansions, we need only
14027              unify the patterns themselves.  */
14028           arg1 = PACK_EXPANSION_PATTERN (arg1);
14029           arg2 = PACK_EXPANSION_PATTERN (arg2);
14030
14031           /* This is the last comparison we need to do.  */
14032           len = 0;
14033         }
14034
14035       if (TREE_CODE (arg1) == REFERENCE_TYPE)
14036         {
14037           arg1 = TREE_TYPE (arg1);
14038           quals1 = cp_type_quals (arg1);
14039         }
14040
14041       if (TREE_CODE (arg2) == REFERENCE_TYPE)
14042         {
14043           arg2 = TREE_TYPE (arg2);
14044           quals2 = cp_type_quals (arg2);
14045         }
14046
14047       if ((quals1 < 0) != (quals2 < 0))
14048         {
14049           /* Only of the args is a reference, see if we should apply
14050              array/function pointer decay to it.  This is not part of
14051              DR214, but is, IMHO, consistent with the deduction rules
14052              for the function call itself, and with our earlier
14053              implementation of the underspecified partial ordering
14054              rules.  (nathan).  */
14055           if (quals1 >= 0)
14056             {
14057               switch (TREE_CODE (arg1))
14058                 {
14059                 case ARRAY_TYPE:
14060                   arg1 = TREE_TYPE (arg1);
14061                   /* FALLTHROUGH. */
14062                 case FUNCTION_TYPE:
14063                   arg1 = build_pointer_type (arg1);
14064                   break;
14065
14066                 default:
14067                   break;
14068                 }
14069             }
14070           else
14071             {
14072               switch (TREE_CODE (arg2))
14073                 {
14074                 case ARRAY_TYPE:
14075                   arg2 = TREE_TYPE (arg2);
14076                   /* FALLTHROUGH. */
14077                 case FUNCTION_TYPE:
14078                   arg2 = build_pointer_type (arg2);
14079                   break;
14080
14081                 default:
14082                   break;
14083                 }
14084             }
14085         }
14086
14087       arg1 = TYPE_MAIN_VARIANT (arg1);
14088       arg2 = TYPE_MAIN_VARIANT (arg2);
14089
14090       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
14091         {
14092           int i, len2 = list_length (args2);
14093           tree parmvec = make_tree_vec (1);
14094           tree argvec = make_tree_vec (len2);
14095           tree ta = args2;
14096
14097           /* Setup the parameter vector, which contains only ARG1.  */
14098           TREE_VEC_ELT (parmvec, 0) = arg1;
14099
14100           /* Setup the argument vector, which contains the remaining
14101              arguments.  */
14102           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
14103             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
14104
14105           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
14106                                            argvec, UNIFY_ALLOW_NONE, 
14107                                            /*call_args_p=*/false, 
14108                                            /*subr=*/0);
14109
14110           /* We cannot deduce in the other direction, because ARG1 is
14111              a pack expansion but ARG2 is not.  */
14112           deduce2 = 0;
14113         }
14114       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
14115         {
14116           int i, len1 = list_length (args1);
14117           tree parmvec = make_tree_vec (1);
14118           tree argvec = make_tree_vec (len1);
14119           tree ta = args1;
14120
14121           /* Setup the parameter vector, which contains only ARG1.  */
14122           TREE_VEC_ELT (parmvec, 0) = arg2;
14123
14124           /* Setup the argument vector, which contains the remaining
14125              arguments.  */
14126           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
14127             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
14128
14129           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
14130                                            argvec, UNIFY_ALLOW_NONE, 
14131                                            /*call_args_p=*/false, 
14132                                            /*subr=*/0);
14133
14134           /* We cannot deduce in the other direction, because ARG2 is
14135              a pack expansion but ARG1 is not.*/
14136           deduce1 = 0;
14137         }
14138
14139       else
14140         {
14141           /* The normal case, where neither argument is a pack
14142              expansion.  */
14143           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
14144           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
14145         }
14146
14147       if (!deduce1)
14148         better2 = -1;
14149       if (!deduce2)
14150         better1 = -1;
14151       if (better1 < 0 && better2 < 0)
14152         /* We've failed to deduce something in either direction.
14153            These must be unordered.  */
14154         break;
14155
14156       if (deduce1 && deduce2 && quals1 >= 0 && quals2 >= 0)
14157         {
14158           /* Deduces in both directions, see if quals can
14159              disambiguate.  Pretend the worse one failed to deduce. */
14160           if ((quals1 & quals2) == quals2)
14161             deduce1 = 0;
14162           if ((quals1 & quals2) == quals1)
14163             deduce2 = 0;
14164         }
14165       if (deduce1 && !deduce2 && !better2)
14166         better2 = 1;
14167       if (deduce2 && !deduce1 && !better1)
14168         better1 = 1;
14169
14170       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
14171           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
14172         /* We have already processed all of the arguments in our
14173            handing of the pack expansion type.  */
14174         len = 0;
14175
14176       args1 = TREE_CHAIN (args1);
14177       args2 = TREE_CHAIN (args2);
14178     }
14179
14180   processing_template_decl--;
14181
14182   /* All things being equal, if the next argument is a pack expansion
14183      for one function but not for the other, prefer the
14184      non-variadic function.  */
14185   if ((better1 > 0) - (better2 > 0) == 0
14186       && args1 && TREE_VALUE (args1)
14187       && args2 && TREE_VALUE (args2))
14188     {
14189       if (TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION)
14190         return TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION ? 0 : -1;
14191       else if (TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION)
14192         return 1;
14193     }
14194
14195   return (better1 > 0) - (better2 > 0);
14196 }
14197
14198 /* Determine which of two partial specializations is more specialized.
14199
14200    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
14201    to the first partial specialization.  The TREE_VALUE is the
14202    innermost set of template parameters for the partial
14203    specialization.  PAT2 is similar, but for the second template.
14204
14205    Return 1 if the first partial specialization is more specialized;
14206    -1 if the second is more specialized; 0 if neither is more
14207    specialized.
14208
14209    See [temp.class.order] for information about determining which of
14210    two templates is more specialized.  */
14211
14212 static int
14213 more_specialized_class (tree pat1, tree pat2)
14214 {
14215   tree targs;
14216   tree tmpl1, tmpl2;
14217   int winner = 0;
14218   bool any_deductions = false;
14219
14220   tmpl1 = TREE_TYPE (pat1);
14221   tmpl2 = TREE_TYPE (pat2);
14222
14223   /* Just like what happens for functions, if we are ordering between
14224      different class template specializations, we may encounter dependent
14225      types in the arguments, and we need our dependency check functions
14226      to behave correctly.  */
14227   ++processing_template_decl;
14228   targs = get_class_bindings (TREE_VALUE (pat1),
14229                               CLASSTYPE_TI_ARGS (tmpl1),
14230                               CLASSTYPE_TI_ARGS (tmpl2));
14231   if (targs)
14232     {
14233       --winner;
14234       any_deductions = true;
14235     }
14236
14237   targs = get_class_bindings (TREE_VALUE (pat2),
14238                               CLASSTYPE_TI_ARGS (tmpl2),
14239                               CLASSTYPE_TI_ARGS (tmpl1));
14240   if (targs)
14241     {
14242       ++winner;
14243       any_deductions = true;
14244     }
14245   --processing_template_decl;
14246
14247   /* In the case of a tie where at least one of the class templates
14248      has a parameter pack at the end, the template with the most
14249      non-packed parameters wins.  */
14250   if (winner == 0
14251       && any_deductions
14252       && (template_args_variadic_p (TREE_PURPOSE (pat1))
14253           || template_args_variadic_p (TREE_PURPOSE (pat2))))
14254     {
14255       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
14256       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
14257       int len1 = TREE_VEC_LENGTH (args1);
14258       int len2 = TREE_VEC_LENGTH (args2);
14259
14260       /* We don't count the pack expansion at the end.  */
14261       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
14262         --len1;
14263       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
14264         --len2;
14265
14266       if (len1 > len2)
14267         return 1;
14268       else if (len1 < len2)
14269         return -1;
14270     }
14271
14272   return winner;
14273 }
14274
14275 /* Return the template arguments that will produce the function signature
14276    DECL from the function template FN, with the explicit template
14277    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
14278    also match.  Return NULL_TREE if no satisfactory arguments could be
14279    found.  */
14280
14281 static tree
14282 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
14283 {
14284   int ntparms = DECL_NTPARMS (fn);
14285   tree targs = make_tree_vec (ntparms);
14286   tree decl_type;
14287   tree decl_arg_types;
14288
14289   /* Substitute the explicit template arguments into the type of DECL.
14290      The call to fn_type_unification will handle substitution into the
14291      FN.  */
14292   decl_type = TREE_TYPE (decl);
14293   if (explicit_args && uses_template_parms (decl_type))
14294     {
14295       tree tmpl;
14296       tree converted_args;
14297
14298       if (DECL_TEMPLATE_INFO (decl))
14299         tmpl = DECL_TI_TEMPLATE (decl);
14300       else
14301         /* We can get here for some invalid specializations.  */
14302         return NULL_TREE;
14303
14304       converted_args
14305         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
14306                                  explicit_args, NULL_TREE,
14307                                  tf_none,
14308                                  /*require_all_args=*/false,
14309                                  /*use_default_args=*/false);
14310       if (converted_args == error_mark_node)
14311         return NULL_TREE;
14312
14313       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
14314       if (decl_type == error_mark_node)
14315         return NULL_TREE;
14316     }
14317
14318   /* Never do unification on the 'this' parameter.  */
14319   decl_arg_types = skip_artificial_parms_for (decl, 
14320                                               TYPE_ARG_TYPES (decl_type));
14321
14322   if (fn_type_unification (fn, explicit_args, targs,
14323                            decl_arg_types,
14324                            (check_rettype || DECL_CONV_FN_P (fn)
14325                             ? TREE_TYPE (decl_type) : NULL_TREE),
14326                            DEDUCE_EXACT, LOOKUP_NORMAL))
14327     return NULL_TREE;
14328
14329   return targs;
14330 }
14331
14332 /* Return the innermost template arguments that, when applied to a
14333    template specialization whose innermost template parameters are
14334    TPARMS, and whose specialization arguments are PARMS, yield the
14335    ARGS.
14336
14337    For example, suppose we have:
14338
14339      template <class T, class U> struct S {};
14340      template <class T> struct S<T*, int> {};
14341
14342    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
14343    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
14344    int}.  The resulting vector will be {double}, indicating that `T'
14345    is bound to `double'.  */
14346
14347 static tree
14348 get_class_bindings (tree tparms, tree spec_args, tree args)
14349 {
14350   int i, ntparms = TREE_VEC_LENGTH (tparms);
14351   tree deduced_args;
14352   tree innermost_deduced_args;
14353
14354   innermost_deduced_args = make_tree_vec (ntparms);
14355   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
14356     {
14357       deduced_args = copy_node (args);
14358       SET_TMPL_ARGS_LEVEL (deduced_args,
14359                            TMPL_ARGS_DEPTH (deduced_args),
14360                            innermost_deduced_args);
14361     }
14362   else
14363     deduced_args = innermost_deduced_args;
14364
14365   if (unify (tparms, deduced_args,
14366              INNERMOST_TEMPLATE_ARGS (spec_args),
14367              INNERMOST_TEMPLATE_ARGS (args),
14368              UNIFY_ALLOW_NONE))
14369     return NULL_TREE;
14370
14371   for (i =  0; i < ntparms; ++i)
14372     if (! TREE_VEC_ELT (innermost_deduced_args, i))
14373       return NULL_TREE;
14374
14375   /* Verify that nondeduced template arguments agree with the type
14376      obtained from argument deduction.
14377
14378      For example:
14379
14380        struct A { typedef int X; };
14381        template <class T, class U> struct C {};
14382        template <class T> struct C<T, typename T::X> {};
14383
14384      Then with the instantiation `C<A, int>', we can deduce that
14385      `T' is `A' but unify () does not check whether `typename T::X'
14386      is `int'.  */
14387   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
14388   if (spec_args == error_mark_node
14389       /* We only need to check the innermost arguments; the other
14390          arguments will always agree.  */
14391       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
14392                               INNERMOST_TEMPLATE_ARGS (args)))
14393     return NULL_TREE;
14394
14395   /* Now that we have bindings for all of the template arguments,
14396      ensure that the arguments deduced for the template template
14397      parameters have compatible template parameter lists.  See the use
14398      of template_template_parm_bindings_ok_p in fn_type_unification
14399      for more information.  */
14400   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
14401     return NULL_TREE;
14402
14403   return deduced_args;
14404 }
14405
14406 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
14407    Return the TREE_LIST node with the most specialized template, if
14408    any.  If there is no most specialized template, the error_mark_node
14409    is returned.
14410
14411    Note that this function does not look at, or modify, the
14412    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
14413    returned is one of the elements of INSTANTIATIONS, callers may
14414    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
14415    and retrieve it from the value returned.  */
14416
14417 tree
14418 most_specialized_instantiation (tree templates)
14419 {
14420   tree fn, champ;
14421
14422   ++processing_template_decl;
14423
14424   champ = templates;
14425   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
14426     {
14427       int fate = 0;
14428
14429       if (get_bindings (TREE_VALUE (champ),
14430                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
14431                         NULL_TREE, /*check_ret=*/false))
14432         fate--;
14433
14434       if (get_bindings (TREE_VALUE (fn),
14435                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
14436                         NULL_TREE, /*check_ret=*/false))
14437         fate++;
14438
14439       if (fate == -1)
14440         champ = fn;
14441       else if (!fate)
14442         {
14443           /* Equally specialized, move to next function.  If there
14444              is no next function, nothing's most specialized.  */
14445           fn = TREE_CHAIN (fn);
14446           champ = fn;
14447           if (!fn)
14448             break;
14449         }
14450     }
14451
14452   if (champ)
14453     /* Now verify that champ is better than everything earlier in the
14454        instantiation list.  */
14455     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
14456       if (get_bindings (TREE_VALUE (champ),
14457                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
14458                         NULL_TREE, /*check_ret=*/false)
14459           || !get_bindings (TREE_VALUE (fn),
14460                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
14461                             NULL_TREE, /*check_ret=*/false))
14462         {
14463           champ = NULL_TREE;
14464           break;
14465         }
14466
14467   processing_template_decl--;
14468
14469   if (!champ)
14470     return error_mark_node;
14471
14472   return champ;
14473 }
14474
14475 /* If DECL is a specialization of some template, return the most
14476    general such template.  Otherwise, returns NULL_TREE.
14477
14478    For example, given:
14479
14480      template <class T> struct S { template <class U> void f(U); };
14481
14482    if TMPL is `template <class U> void S<int>::f(U)' this will return
14483    the full template.  This function will not trace past partial
14484    specializations, however.  For example, given in addition:
14485
14486      template <class T> struct S<T*> { template <class U> void f(U); };
14487
14488    if TMPL is `template <class U> void S<int*>::f(U)' this will return
14489    `template <class T> template <class U> S<T*>::f(U)'.  */
14490
14491 tree
14492 most_general_template (tree decl)
14493 {
14494   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
14495      an immediate specialization.  */
14496   if (TREE_CODE (decl) == FUNCTION_DECL)
14497     {
14498       if (DECL_TEMPLATE_INFO (decl)) {
14499         decl = DECL_TI_TEMPLATE (decl);
14500
14501         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
14502            template friend.  */
14503         if (TREE_CODE (decl) != TEMPLATE_DECL)
14504           return NULL_TREE;
14505       } else
14506         return NULL_TREE;
14507     }
14508
14509   /* Look for more and more general templates.  */
14510   while (DECL_TEMPLATE_INFO (decl))
14511     {
14512       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
14513          (See cp-tree.h for details.)  */
14514       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
14515         break;
14516
14517       if (CLASS_TYPE_P (TREE_TYPE (decl))
14518           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
14519         break;
14520
14521       /* Stop if we run into an explicitly specialized class template.  */
14522       if (!DECL_NAMESPACE_SCOPE_P (decl)
14523           && DECL_CONTEXT (decl)
14524           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
14525         break;
14526
14527       decl = DECL_TI_TEMPLATE (decl);
14528     }
14529
14530   return decl;
14531 }
14532
14533 /* Return the most specialized of the class template partial
14534    specializations of TMPL which can produce TYPE, a specialization of
14535    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
14536    a _TYPE node corresponding to the partial specialization, while the
14537    TREE_PURPOSE is the set of template arguments that must be
14538    substituted into the TREE_TYPE in order to generate TYPE.
14539
14540    If the choice of partial specialization is ambiguous, a diagnostic
14541    is issued, and the error_mark_node is returned.  If there are no
14542    partial specializations of TMPL matching TYPE, then NULL_TREE is
14543    returned.  */
14544
14545 static tree
14546 most_specialized_class (tree type, tree tmpl)
14547 {
14548   tree list = NULL_TREE;
14549   tree t;
14550   tree champ;
14551   int fate;
14552   bool ambiguous_p;
14553   tree args;
14554   tree outer_args = NULL_TREE;
14555
14556   tmpl = most_general_template (tmpl);
14557   args = CLASSTYPE_TI_ARGS (type);
14558
14559   /* For determining which partial specialization to use, only the
14560      innermost args are interesting.  */
14561   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
14562     {
14563       outer_args = strip_innermost_template_args (args, 1);
14564       args = INNERMOST_TEMPLATE_ARGS (args);
14565     }
14566
14567   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
14568     {
14569       tree partial_spec_args;
14570       tree spec_args;
14571       tree parms = TREE_VALUE (t);
14572
14573       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
14574       if (outer_args)
14575         {
14576           int i;
14577
14578           ++processing_template_decl;
14579
14580           /* Discard the outer levels of args, and then substitute in the
14581              template args from the enclosing class.  */
14582           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
14583           partial_spec_args = tsubst_template_args
14584             (partial_spec_args, outer_args, tf_none, NULL_TREE);
14585
14586           /* PARMS already refers to just the innermost parms, but the
14587              template parms in partial_spec_args had their levels lowered
14588              by tsubst, so we need to do the same for the parm list.  We
14589              can't just tsubst the TREE_VEC itself, as tsubst wants to
14590              treat a TREE_VEC as an argument vector.  */
14591           parms = copy_node (parms);
14592           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
14593             TREE_VEC_ELT (parms, i) =
14594               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
14595
14596           --processing_template_decl;
14597         }
14598       spec_args = get_class_bindings (parms,
14599                                       partial_spec_args,
14600                                       args);
14601       if (spec_args)
14602         {
14603           if (outer_args)
14604             spec_args = add_to_template_args (outer_args, spec_args);
14605           list = tree_cons (spec_args, TREE_VALUE (t), list);
14606           TREE_TYPE (list) = TREE_TYPE (t);
14607         }
14608     }
14609
14610   if (! list)
14611     return NULL_TREE;
14612
14613   ambiguous_p = false;
14614   t = list;
14615   champ = t;
14616   t = TREE_CHAIN (t);
14617   for (; t; t = TREE_CHAIN (t))
14618     {
14619       fate = more_specialized_class (champ, t);
14620       if (fate == 1)
14621         ;
14622       else
14623         {
14624           if (fate == 0)
14625             {
14626               t = TREE_CHAIN (t);
14627               if (! t)
14628                 {
14629                   ambiguous_p = true;
14630                   break;
14631                 }
14632             }
14633           champ = t;
14634         }
14635     }
14636
14637   if (!ambiguous_p)
14638     for (t = list; t && t != champ; t = TREE_CHAIN (t))
14639       {
14640         fate = more_specialized_class (champ, t);
14641         if (fate != 1)
14642           {
14643             ambiguous_p = true;
14644             break;
14645           }
14646       }
14647
14648   if (ambiguous_p)
14649     {
14650       const char *str = "candidates are:";
14651       error ("ambiguous class template instantiation for %q#T", type);
14652       for (t = list; t; t = TREE_CHAIN (t))
14653         {
14654           error ("%s %+#T", str, TREE_TYPE (t));
14655           str = "               ";
14656         }
14657       return error_mark_node;
14658     }
14659
14660   return champ;
14661 }
14662
14663 /* Explicitly instantiate DECL.  */
14664
14665 void
14666 do_decl_instantiation (tree decl, tree storage)
14667 {
14668   tree result = NULL_TREE;
14669   int extern_p = 0;
14670
14671   if (!decl || decl == error_mark_node)
14672     /* An error occurred, for which grokdeclarator has already issued
14673        an appropriate message.  */
14674     return;
14675   else if (! DECL_LANG_SPECIFIC (decl))
14676     {
14677       error ("explicit instantiation of non-template %q#D", decl);
14678       return;
14679     }
14680   else if (TREE_CODE (decl) == VAR_DECL)
14681     {
14682       /* There is an asymmetry here in the way VAR_DECLs and
14683          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
14684          the latter, the DECL we get back will be marked as a
14685          template instantiation, and the appropriate
14686          DECL_TEMPLATE_INFO will be set up.  This does not happen for
14687          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
14688          should handle VAR_DECLs as it currently handles
14689          FUNCTION_DECLs.  */
14690       if (!DECL_CLASS_SCOPE_P (decl))
14691         {
14692           error ("%qD is not a static data member of a class template", decl);
14693           return;
14694         }
14695       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
14696       if (!result || TREE_CODE (result) != VAR_DECL)
14697         {
14698           error ("no matching template for %qD found", decl);
14699           return;
14700         }
14701       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
14702         {
14703           error ("type %qT for explicit instantiation %qD does not match "
14704                  "declared type %qT", TREE_TYPE (result), decl,
14705                  TREE_TYPE (decl));
14706           return;
14707         }
14708     }
14709   else if (TREE_CODE (decl) != FUNCTION_DECL)
14710     {
14711       error ("explicit instantiation of %q#D", decl);
14712       return;
14713     }
14714   else
14715     result = decl;
14716
14717   /* Check for various error cases.  Note that if the explicit
14718      instantiation is valid the RESULT will currently be marked as an
14719      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
14720      until we get here.  */
14721
14722   if (DECL_TEMPLATE_SPECIALIZATION (result))
14723     {
14724       /* DR 259 [temp.spec].
14725
14726          Both an explicit instantiation and a declaration of an explicit
14727          specialization shall not appear in a program unless the explicit
14728          instantiation follows a declaration of the explicit specialization.
14729
14730          For a given set of template parameters, if an explicit
14731          instantiation of a template appears after a declaration of an
14732          explicit specialization for that template, the explicit
14733          instantiation has no effect.  */
14734       return;
14735     }
14736   else if (DECL_EXPLICIT_INSTANTIATION (result))
14737     {
14738       /* [temp.spec]
14739
14740          No program shall explicitly instantiate any template more
14741          than once.
14742
14743          We check DECL_NOT_REALLY_EXTERN so as not to complain when
14744          the first instantiation was `extern' and the second is not,
14745          and EXTERN_P for the opposite case.  */
14746       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
14747         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
14748       /* If an "extern" explicit instantiation follows an ordinary
14749          explicit instantiation, the template is instantiated.  */
14750       if (extern_p)
14751         return;
14752     }
14753   else if (!DECL_IMPLICIT_INSTANTIATION (result))
14754     {
14755       error ("no matching template for %qD found", result);
14756       return;
14757     }
14758   else if (!DECL_TEMPLATE_INFO (result))
14759     {
14760       permerror (input_location, "explicit instantiation of non-template %q#D", result);
14761       return;
14762     }
14763
14764   if (storage == NULL_TREE)
14765     ;
14766   else if (storage == ridpointers[(int) RID_EXTERN])
14767     {
14768       if (!in_system_header && (cxx_dialect == cxx98))
14769         pedwarn (input_location, OPT_pedantic, 
14770                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
14771                  "instantiations");
14772       extern_p = 1;
14773     }
14774   else
14775     error ("storage class %qD applied to template instantiation", storage);
14776
14777   check_explicit_instantiation_namespace (result);
14778   mark_decl_instantiated (result, extern_p);
14779   if (! extern_p)
14780     instantiate_decl (result, /*defer_ok=*/1,
14781                       /*expl_inst_class_mem_p=*/false);
14782 }
14783
14784 static void
14785 mark_class_instantiated (tree t, int extern_p)
14786 {
14787   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
14788   SET_CLASSTYPE_INTERFACE_KNOWN (t);
14789   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
14790   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
14791   if (! extern_p)
14792     {
14793       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
14794       rest_of_type_compilation (t, 1);
14795     }
14796 }
14797
14798 /* Called from do_type_instantiation through binding_table_foreach to
14799    do recursive instantiation for the type bound in ENTRY.  */
14800 static void
14801 bt_instantiate_type_proc (binding_entry entry, void *data)
14802 {
14803   tree storage = *(tree *) data;
14804
14805   if (MAYBE_CLASS_TYPE_P (entry->type)
14806       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
14807     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
14808 }
14809
14810 /* Called from do_type_instantiation to instantiate a member
14811    (a member function or a static member variable) of an
14812    explicitly instantiated class template.  */
14813 static void
14814 instantiate_class_member (tree decl, int extern_p)
14815 {
14816   mark_decl_instantiated (decl, extern_p);
14817   if (! extern_p)
14818     instantiate_decl (decl, /*defer_ok=*/1,
14819                       /*expl_inst_class_mem_p=*/true);
14820 }
14821
14822 /* Perform an explicit instantiation of template class T.  STORAGE, if
14823    non-null, is the RID for extern, inline or static.  COMPLAIN is
14824    nonzero if this is called from the parser, zero if called recursively,
14825    since the standard is unclear (as detailed below).  */
14826
14827 void
14828 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
14829 {
14830   int extern_p = 0;
14831   int nomem_p = 0;
14832   int static_p = 0;
14833   int previous_instantiation_extern_p = 0;
14834
14835   if (TREE_CODE (t) == TYPE_DECL)
14836     t = TREE_TYPE (t);
14837
14838   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
14839     {
14840       error ("explicit instantiation of non-template type %qT", t);
14841       return;
14842     }
14843
14844   complete_type (t);
14845
14846   if (!COMPLETE_TYPE_P (t))
14847     {
14848       if (complain & tf_error)
14849         error ("explicit instantiation of %q#T before definition of template",
14850                t);
14851       return;
14852     }
14853
14854   if (storage != NULL_TREE)
14855     {
14856       if (!in_system_header)
14857         {
14858           if (storage == ridpointers[(int) RID_EXTERN])
14859             {
14860               if (cxx_dialect == cxx98)
14861                 pedwarn (input_location, OPT_pedantic, 
14862                          "ISO C++ 1998 forbids the use of %<extern%> on "
14863                          "explicit instantiations");
14864             }
14865           else
14866             pedwarn (input_location, OPT_pedantic, 
14867                      "ISO C++ forbids the use of %qE"
14868                      " on explicit instantiations", storage);
14869         }
14870
14871       if (storage == ridpointers[(int) RID_INLINE])
14872         nomem_p = 1;
14873       else if (storage == ridpointers[(int) RID_EXTERN])
14874         extern_p = 1;
14875       else if (storage == ridpointers[(int) RID_STATIC])
14876         static_p = 1;
14877       else
14878         {
14879           error ("storage class %qD applied to template instantiation",
14880                  storage);
14881           extern_p = 0;
14882         }
14883     }
14884
14885   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
14886     {
14887       /* DR 259 [temp.spec].
14888
14889          Both an explicit instantiation and a declaration of an explicit
14890          specialization shall not appear in a program unless the explicit
14891          instantiation follows a declaration of the explicit specialization.
14892
14893          For a given set of template parameters, if an explicit
14894          instantiation of a template appears after a declaration of an
14895          explicit specialization for that template, the explicit
14896          instantiation has no effect.  */
14897       return;
14898     }
14899   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
14900     {
14901       /* [temp.spec]
14902
14903          No program shall explicitly instantiate any template more
14904          than once.
14905
14906          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
14907          instantiation was `extern'.  If EXTERN_P then the second is.
14908          These cases are OK.  */
14909       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
14910
14911       if (!previous_instantiation_extern_p && !extern_p
14912           && (complain & tf_error))
14913         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
14914
14915       /* If we've already instantiated the template, just return now.  */
14916       if (!CLASSTYPE_INTERFACE_ONLY (t))
14917         return;
14918     }
14919
14920   check_explicit_instantiation_namespace (TYPE_NAME (t));
14921   mark_class_instantiated (t, extern_p);
14922
14923   if (nomem_p)
14924     return;
14925
14926   {
14927     tree tmp;
14928
14929     /* In contrast to implicit instantiation, where only the
14930        declarations, and not the definitions, of members are
14931        instantiated, we have here:
14932
14933          [temp.explicit]
14934
14935          The explicit instantiation of a class template specialization
14936          implies the instantiation of all of its members not
14937          previously explicitly specialized in the translation unit
14938          containing the explicit instantiation.
14939
14940        Of course, we can't instantiate member template classes, since
14941        we don't have any arguments for them.  Note that the standard
14942        is unclear on whether the instantiation of the members are
14943        *explicit* instantiations or not.  However, the most natural
14944        interpretation is that it should be an explicit instantiation.  */
14945
14946     if (! static_p)
14947       for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
14948         if (TREE_CODE (tmp) == FUNCTION_DECL
14949             && DECL_TEMPLATE_INSTANTIATION (tmp))
14950           instantiate_class_member (tmp, extern_p);
14951
14952     for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
14953       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
14954         instantiate_class_member (tmp, extern_p);
14955
14956     if (CLASSTYPE_NESTED_UTDS (t))
14957       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
14958                              bt_instantiate_type_proc, &storage);
14959   }
14960 }
14961
14962 /* Given a function DECL, which is a specialization of TMPL, modify
14963    DECL to be a re-instantiation of TMPL with the same template
14964    arguments.  TMPL should be the template into which tsubst'ing
14965    should occur for DECL, not the most general template.
14966
14967    One reason for doing this is a scenario like this:
14968
14969      template <class T>
14970      void f(const T&, int i);
14971
14972      void g() { f(3, 7); }
14973
14974      template <class T>
14975      void f(const T& t, const int i) { }
14976
14977    Note that when the template is first instantiated, with
14978    instantiate_template, the resulting DECL will have no name for the
14979    first parameter, and the wrong type for the second.  So, when we go
14980    to instantiate the DECL, we regenerate it.  */
14981
14982 static void
14983 regenerate_decl_from_template (tree decl, tree tmpl)
14984 {
14985   /* The arguments used to instantiate DECL, from the most general
14986      template.  */
14987   tree args;
14988   tree code_pattern;
14989
14990   args = DECL_TI_ARGS (decl);
14991   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
14992
14993   /* Make sure that we can see identifiers, and compute access
14994      correctly.  */
14995   push_access_scope (decl);
14996
14997   if (TREE_CODE (decl) == FUNCTION_DECL)
14998     {
14999       tree decl_parm;
15000       tree pattern_parm;
15001       tree specs;
15002       int args_depth;
15003       int parms_depth;
15004
15005       args_depth = TMPL_ARGS_DEPTH (args);
15006       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
15007       if (args_depth > parms_depth)
15008         args = get_innermost_template_args (args, parms_depth);
15009
15010       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
15011                                               args, tf_error, NULL_TREE);
15012       if (specs)
15013         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
15014                                                     specs);
15015
15016       /* Merge parameter declarations.  */
15017       decl_parm = skip_artificial_parms_for (decl,
15018                                              DECL_ARGUMENTS (decl));
15019       pattern_parm
15020         = skip_artificial_parms_for (code_pattern,
15021                                      DECL_ARGUMENTS (code_pattern));
15022       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
15023         {
15024           tree parm_type;
15025           tree attributes;
15026           
15027           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
15028             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
15029           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
15030                               NULL_TREE);
15031           parm_type = type_decays_to (parm_type);
15032           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
15033             TREE_TYPE (decl_parm) = parm_type;
15034           attributes = DECL_ATTRIBUTES (pattern_parm);
15035           if (DECL_ATTRIBUTES (decl_parm) != attributes)
15036             {
15037               DECL_ATTRIBUTES (decl_parm) = attributes;
15038               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
15039             }
15040           decl_parm = TREE_CHAIN (decl_parm);
15041           pattern_parm = TREE_CHAIN (pattern_parm);
15042         }
15043       /* Merge any parameters that match with the function parameter
15044          pack.  */
15045       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
15046         {
15047           int i, len;
15048           tree expanded_types;
15049           /* Expand the TYPE_PACK_EXPANSION that provides the types for
15050              the parameters in this function parameter pack.  */
15051           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
15052                                                  args, tf_error, NULL_TREE);
15053           len = TREE_VEC_LENGTH (expanded_types);
15054           for (i = 0; i < len; i++)
15055             {
15056               tree parm_type;
15057               tree attributes;
15058           
15059               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
15060                 /* Rename the parameter to include the index.  */
15061                 DECL_NAME (decl_parm) = 
15062                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
15063               parm_type = TREE_VEC_ELT (expanded_types, i);
15064               parm_type = type_decays_to (parm_type);
15065               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
15066                 TREE_TYPE (decl_parm) = parm_type;
15067               attributes = DECL_ATTRIBUTES (pattern_parm);
15068               if (DECL_ATTRIBUTES (decl_parm) != attributes)
15069                 {
15070                   DECL_ATTRIBUTES (decl_parm) = attributes;
15071                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
15072                 }
15073               decl_parm = TREE_CHAIN (decl_parm);
15074             }
15075         }
15076       /* Merge additional specifiers from the CODE_PATTERN.  */
15077       if (DECL_DECLARED_INLINE_P (code_pattern)
15078           && !DECL_DECLARED_INLINE_P (decl))
15079         DECL_DECLARED_INLINE_P (decl) = 1;
15080     }
15081   else if (TREE_CODE (decl) == VAR_DECL)
15082     DECL_INITIAL (decl) =
15083       tsubst_expr (DECL_INITIAL (code_pattern), args,
15084                    tf_error, DECL_TI_TEMPLATE (decl),
15085                    /*integral_constant_expression_p=*/false);
15086   else
15087     gcc_unreachable ();
15088
15089   pop_access_scope (decl);
15090 }
15091
15092 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
15093    substituted to get DECL.  */
15094
15095 tree
15096 template_for_substitution (tree decl)
15097 {
15098   tree tmpl = DECL_TI_TEMPLATE (decl);
15099
15100   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
15101      for the instantiation.  This is not always the most general
15102      template.  Consider, for example:
15103
15104         template <class T>
15105         struct S { template <class U> void f();
15106                    template <> void f<int>(); };
15107
15108      and an instantiation of S<double>::f<int>.  We want TD to be the
15109      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
15110   while (/* An instantiation cannot have a definition, so we need a
15111             more general template.  */
15112          DECL_TEMPLATE_INSTANTIATION (tmpl)
15113            /* We must also deal with friend templates.  Given:
15114
15115                 template <class T> struct S {
15116                   template <class U> friend void f() {};
15117                 };
15118
15119               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
15120               so far as the language is concerned, but that's still
15121               where we get the pattern for the instantiation from.  On
15122               other hand, if the definition comes outside the class, say:
15123
15124                 template <class T> struct S {
15125                   template <class U> friend void f();
15126                 };
15127                 template <class U> friend void f() {}
15128
15129               we don't need to look any further.  That's what the check for
15130               DECL_INITIAL is for.  */
15131           || (TREE_CODE (decl) == FUNCTION_DECL
15132               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
15133               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
15134     {
15135       /* The present template, TD, should not be a definition.  If it
15136          were a definition, we should be using it!  Note that we
15137          cannot restructure the loop to just keep going until we find
15138          a template with a definition, since that might go too far if
15139          a specialization was declared, but not defined.  */
15140       gcc_assert (TREE_CODE (decl) != VAR_DECL
15141                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
15142
15143       /* Fetch the more general template.  */
15144       tmpl = DECL_TI_TEMPLATE (tmpl);
15145     }
15146
15147   return tmpl;
15148 }
15149
15150 /* Produce the definition of D, a _DECL generated from a template.  If
15151    DEFER_OK is nonzero, then we don't have to actually do the
15152    instantiation now; we just have to do it sometime.  Normally it is
15153    an error if this is an explicit instantiation but D is undefined.
15154    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
15155    explicitly instantiated class template.  */
15156
15157 tree
15158 instantiate_decl (tree d, int defer_ok,
15159                   bool expl_inst_class_mem_p)
15160 {
15161   tree tmpl = DECL_TI_TEMPLATE (d);
15162   tree gen_args;
15163   tree args;
15164   tree td;
15165   tree code_pattern;
15166   tree spec;
15167   tree gen_tmpl;
15168   bool pattern_defined;
15169   int need_push;
15170   location_t saved_loc = input_location;
15171   bool external_p;
15172
15173   /* This function should only be used to instantiate templates for
15174      functions and static member variables.  */
15175   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
15176               || TREE_CODE (d) == VAR_DECL);
15177
15178   /* Variables are never deferred; if instantiation is required, they
15179      are instantiated right away.  That allows for better code in the
15180      case that an expression refers to the value of the variable --
15181      if the variable has a constant value the referring expression can
15182      take advantage of that fact.  */
15183   if (TREE_CODE (d) == VAR_DECL)
15184     defer_ok = 0;
15185
15186   /* Don't instantiate cloned functions.  Instead, instantiate the
15187      functions they cloned.  */
15188   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
15189     d = DECL_CLONED_FUNCTION (d);
15190
15191   if (DECL_TEMPLATE_INSTANTIATED (d))
15192     /* D has already been instantiated.  It might seem reasonable to
15193        check whether or not D is an explicit instantiation, and, if so,
15194        stop here.  But when an explicit instantiation is deferred
15195        until the end of the compilation, DECL_EXPLICIT_INSTANTIATION
15196        is set, even though we still need to do the instantiation.  */
15197     return d;
15198
15199   /* If we already have a specialization of this declaration, then
15200      there's no reason to instantiate it.  Note that
15201      retrieve_specialization gives us both instantiations and
15202      specializations, so we must explicitly check
15203      DECL_TEMPLATE_SPECIALIZATION.  */
15204   gen_tmpl = most_general_template (tmpl);
15205   gen_args = DECL_TI_ARGS (d);
15206   spec = retrieve_specialization (gen_tmpl, gen_args,
15207                                   /*class_specializations_p=*/false);
15208   if (spec != NULL_TREE && DECL_TEMPLATE_SPECIALIZATION (spec))
15209     return spec;
15210
15211   /* This needs to happen before any tsubsting.  */
15212   if (! push_tinst_level (d))
15213     return d;
15214
15215   timevar_push (TV_PARSE);
15216
15217   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
15218      for the instantiation.  */
15219   td = template_for_substitution (d);
15220   code_pattern = DECL_TEMPLATE_RESULT (td);
15221
15222   /* We should never be trying to instantiate a member of a class
15223      template or partial specialization.  */
15224   gcc_assert (d != code_pattern);
15225
15226   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
15227       || DECL_TEMPLATE_SPECIALIZATION (td))
15228     /* In the case of a friend template whose definition is provided
15229        outside the class, we may have too many arguments.  Drop the
15230        ones we don't need.  The same is true for specializations.  */
15231     args = get_innermost_template_args
15232       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
15233   else
15234     args = gen_args;
15235
15236   if (TREE_CODE (d) == FUNCTION_DECL)
15237     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
15238   else
15239     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
15240
15241   /* We may be in the middle of deferred access check.  Disable it now.  */
15242   push_deferring_access_checks (dk_no_deferred);
15243
15244   /* Unless an explicit instantiation directive has already determined
15245      the linkage of D, remember that a definition is available for
15246      this entity.  */
15247   if (pattern_defined
15248       && !DECL_INTERFACE_KNOWN (d)
15249       && !DECL_NOT_REALLY_EXTERN (d))
15250     mark_definable (d);
15251
15252   input_location = DECL_SOURCE_LOCATION (d);
15253
15254   /* If D is a member of an explicitly instantiated class template,
15255      and no definition is available, treat it like an implicit
15256      instantiation.  */
15257   if (!pattern_defined && expl_inst_class_mem_p
15258       && DECL_EXPLICIT_INSTANTIATION (d))
15259     {
15260       DECL_NOT_REALLY_EXTERN (d) = 0;
15261       DECL_INTERFACE_KNOWN (d) = 0;
15262       SET_DECL_IMPLICIT_INSTANTIATION (d);
15263     }
15264
15265   if (!defer_ok)
15266     {
15267       /* Recheck the substitutions to obtain any warning messages
15268          about ignoring cv qualifiers.  */
15269       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
15270       tree type = TREE_TYPE (gen);
15271
15272       /* Make sure that we can see identifiers, and compute access
15273          correctly.  D is already the target FUNCTION_DECL with the
15274          right context.  */
15275       push_access_scope (d);
15276
15277       if (TREE_CODE (gen) == FUNCTION_DECL)
15278         {
15279           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
15280           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
15281                                           d);
15282           /* Don't simply tsubst the function type, as that will give
15283              duplicate warnings about poor parameter qualifications.
15284              The function arguments are the same as the decl_arguments
15285              without the top level cv qualifiers.  */
15286           type = TREE_TYPE (type);
15287         }
15288       tsubst (type, gen_args, tf_warning_or_error, d);
15289
15290       pop_access_scope (d);
15291     }
15292
15293   /* Check to see whether we know that this template will be
15294      instantiated in some other file, as with "extern template"
15295      extension.  */
15296   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
15297   /* In general, we do not instantiate such templates...  */
15298   if (external_p
15299       /* ... but we instantiate inline functions so that we can inline
15300          them.  An explicit instantiation declaration prohibits implicit
15301          instantiation of non-inline functions.  With high levels of
15302          optimization, we would normally inline non-inline functions
15303          -- but we're not allowed to do that for "extern template" functions.
15304          Therefore, we check DECL_DECLARED_INLINE_P, rather than
15305          possibly_inlined_p.  And ...  */
15306       && ! (TREE_CODE (d) == FUNCTION_DECL
15307             && DECL_DECLARED_INLINE_P (d))
15308       /* ... we instantiate static data members whose values are
15309          needed in integral constant expressions.  */
15310       && ! (TREE_CODE (d) == VAR_DECL
15311             && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (d)))
15312     goto out;
15313   /* Defer all other templates, unless we have been explicitly
15314      forbidden from doing so.  */
15315   if (/* If there is no definition, we cannot instantiate the
15316          template.  */
15317       ! pattern_defined
15318       /* If it's OK to postpone instantiation, do so.  */
15319       || defer_ok
15320       /* If this is a static data member that will be defined
15321          elsewhere, we don't want to instantiate the entire data
15322          member, but we do want to instantiate the initializer so that
15323          we can substitute that elsewhere.  */
15324       || (external_p && TREE_CODE (d) == VAR_DECL))
15325     {
15326       /* The definition of the static data member is now required so
15327          we must substitute the initializer.  */
15328       if (TREE_CODE (d) == VAR_DECL
15329           && !DECL_INITIAL (d)
15330           && DECL_INITIAL (code_pattern))
15331         {
15332           tree ns;
15333           tree init;
15334
15335           ns = decl_namespace_context (d);
15336           push_nested_namespace (ns);
15337           push_nested_class (DECL_CONTEXT (d));
15338           init = tsubst_expr (DECL_INITIAL (code_pattern),
15339                               args,
15340                               tf_warning_or_error, NULL_TREE,
15341                               /*integral_constant_expression_p=*/false);
15342           cp_finish_decl (d, init, /*init_const_expr_p=*/false,
15343                           /*asmspec_tree=*/NULL_TREE,
15344                           LOOKUP_ONLYCONVERTING);
15345           pop_nested_class ();
15346           pop_nested_namespace (ns);
15347         }
15348
15349       /* We restore the source position here because it's used by
15350          add_pending_template.  */
15351       input_location = saved_loc;
15352
15353       if (at_eof && !pattern_defined
15354           && DECL_EXPLICIT_INSTANTIATION (d)
15355           && DECL_NOT_REALLY_EXTERN (d))
15356         /* [temp.explicit]
15357
15358            The definition of a non-exported function template, a
15359            non-exported member function template, or a non-exported
15360            member function or static data member of a class template
15361            shall be present in every translation unit in which it is
15362            explicitly instantiated.  */
15363         permerror (input_location,  "explicit instantiation of %qD "
15364                    "but no definition available", d);
15365
15366       /* ??? Historically, we have instantiated inline functions, even
15367          when marked as "extern template".  */
15368       if (!(external_p && TREE_CODE (d) == VAR_DECL))
15369         add_pending_template (d);
15370       goto out;
15371     }
15372   /* Tell the repository that D is available in this translation unit
15373      -- and see if it is supposed to be instantiated here.  */
15374   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
15375     {
15376       /* In a PCH file, despite the fact that the repository hasn't
15377          requested instantiation in the PCH it is still possible that
15378          an instantiation will be required in a file that includes the
15379          PCH.  */
15380       if (pch_file)
15381         add_pending_template (d);
15382       /* Instantiate inline functions so that the inliner can do its
15383          job, even though we'll not be emitting a copy of this
15384          function.  */
15385       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
15386         goto out;
15387     }
15388
15389   need_push = !cfun || !global_bindings_p ();
15390   if (need_push)
15391     push_to_top_level ();
15392
15393   /* Mark D as instantiated so that recursive calls to
15394      instantiate_decl do not try to instantiate it again.  */
15395   DECL_TEMPLATE_INSTANTIATED (d) = 1;
15396
15397   /* Regenerate the declaration in case the template has been modified
15398      by a subsequent redeclaration.  */
15399   regenerate_decl_from_template (d, td);
15400
15401   /* We already set the file and line above.  Reset them now in case
15402      they changed as a result of calling regenerate_decl_from_template.  */
15403   input_location = DECL_SOURCE_LOCATION (d);
15404
15405   if (TREE_CODE (d) == VAR_DECL)
15406     {
15407       tree init;
15408
15409       /* Clear out DECL_RTL; whatever was there before may not be right
15410          since we've reset the type of the declaration.  */
15411       SET_DECL_RTL (d, NULL_RTX);
15412       DECL_IN_AGGR_P (d) = 0;
15413
15414       /* The initializer is placed in DECL_INITIAL by
15415          regenerate_decl_from_template.  Pull it out so that
15416          finish_decl can process it.  */
15417       init = DECL_INITIAL (d);
15418       DECL_INITIAL (d) = NULL_TREE;
15419       DECL_INITIALIZED_P (d) = 0;
15420
15421       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
15422          initializer.  That function will defer actual emission until
15423          we have a chance to determine linkage.  */
15424       DECL_EXTERNAL (d) = 0;
15425
15426       /* Enter the scope of D so that access-checking works correctly.  */
15427       push_nested_class (DECL_CONTEXT (d));
15428       finish_decl (d, init, NULL_TREE);
15429       pop_nested_class ();
15430     }
15431   else if (TREE_CODE (d) == FUNCTION_DECL)
15432     {
15433       htab_t saved_local_specializations;
15434       tree subst_decl;
15435       tree tmpl_parm;
15436       tree spec_parm;
15437
15438       /* Save away the current list, in case we are instantiating one
15439          template from within the body of another.  */
15440       saved_local_specializations = local_specializations;
15441
15442       /* Set up the list of local specializations.  */
15443       local_specializations = htab_create (37,
15444                                            hash_local_specialization,
15445                                            eq_local_specializations,
15446                                            NULL);
15447
15448       /* Set up context.  */
15449       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
15450
15451       /* Create substitution entries for the parameters.  */
15452       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
15453       tmpl_parm = DECL_ARGUMENTS (subst_decl);
15454       spec_parm = DECL_ARGUMENTS (d);
15455       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
15456         {
15457           register_local_specialization (spec_parm, tmpl_parm);
15458           spec_parm = skip_artificial_parms_for (d, spec_parm);
15459           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
15460         }
15461       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
15462         {
15463           register_local_specialization (spec_parm, tmpl_parm);
15464           tmpl_parm = TREE_CHAIN (tmpl_parm);
15465           spec_parm = TREE_CHAIN (spec_parm);
15466         }
15467       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
15468         {
15469           /* Collect all of the extra "packed" parameters into an
15470              argument pack.  */
15471           tree parmvec;
15472           tree parmtypevec;
15473           tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
15474           tree argtypepack = make_node (TYPE_ARGUMENT_PACK);
15475           int i, len = 0;
15476           tree t;
15477           
15478           /* Count how many parameters remain.  */
15479           for (t = spec_parm; t; t = TREE_CHAIN (t))
15480             len++;
15481
15482           /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
15483           parmvec = make_tree_vec (len);
15484           parmtypevec = make_tree_vec (len);
15485           for(i = 0; i < len; i++, spec_parm = TREE_CHAIN (spec_parm))
15486             {
15487               TREE_VEC_ELT (parmvec, i) = spec_parm;
15488               TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
15489             }
15490
15491           /* Build the argument packs.  */
15492           SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
15493           SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
15494           TREE_TYPE (argpack) = argtypepack;
15495           
15496           /* Register the (value) argument pack as a specialization of
15497              TMPL_PARM, then move on.  */
15498           register_local_specialization (argpack, tmpl_parm);
15499           tmpl_parm = TREE_CHAIN (tmpl_parm);
15500         }
15501       gcc_assert (!spec_parm);
15502
15503       /* Substitute into the body of the function.  */
15504       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
15505                    tf_warning_or_error, tmpl,
15506                    /*integral_constant_expression_p=*/false);
15507
15508       /* Set the current input_location to the end of the function
15509          so that finish_function knows where we are.  */
15510       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
15511
15512       /* We don't need the local specializations any more.  */
15513       htab_delete (local_specializations);
15514       local_specializations = saved_local_specializations;
15515
15516       /* Finish the function.  */
15517       d = finish_function (0);
15518       expand_or_defer_fn (d);
15519     }
15520
15521   /* We're not deferring instantiation any more.  */
15522   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
15523
15524   if (need_push)
15525     pop_from_top_level ();
15526
15527 out:
15528   input_location = saved_loc;
15529   pop_deferring_access_checks ();
15530   pop_tinst_level ();
15531
15532   timevar_pop (TV_PARSE);
15533
15534   return d;
15535 }
15536
15537 /* Run through the list of templates that we wish we could
15538    instantiate, and instantiate any we can.  RETRIES is the
15539    number of times we retry pending template instantiation.  */
15540
15541 void
15542 instantiate_pending_templates (int retries)
15543 {
15544   int reconsider;
15545   location_t saved_loc = input_location;
15546
15547   /* Instantiating templates may trigger vtable generation.  This in turn
15548      may require further template instantiations.  We place a limit here
15549      to avoid infinite loop.  */
15550   if (pending_templates && retries >= max_tinst_depth)
15551     {
15552       tree decl = pending_templates->tinst->decl;
15553
15554       error ("template instantiation depth exceeds maximum of %d"
15555              " instantiating %q+D, possibly from virtual table generation"
15556              " (use -ftemplate-depth-NN to increase the maximum)",
15557              max_tinst_depth, decl);
15558       if (TREE_CODE (decl) == FUNCTION_DECL)
15559         /* Pretend that we defined it.  */
15560         DECL_INITIAL (decl) = error_mark_node;
15561       return;
15562     }
15563
15564   do
15565     {
15566       struct pending_template **t = &pending_templates;
15567       struct pending_template *last = NULL;
15568       reconsider = 0;
15569       while (*t)
15570         {
15571           tree instantiation = reopen_tinst_level ((*t)->tinst);
15572           bool complete = false;
15573
15574           if (TYPE_P (instantiation))
15575             {
15576               tree fn;
15577
15578               if (!COMPLETE_TYPE_P (instantiation))
15579                 {
15580                   instantiate_class_template (instantiation);
15581                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
15582                     for (fn = TYPE_METHODS (instantiation);
15583                          fn;
15584                          fn = TREE_CHAIN (fn))
15585                       if (! DECL_ARTIFICIAL (fn))
15586                         instantiate_decl (fn,
15587                                           /*defer_ok=*/0,
15588                                           /*expl_inst_class_mem_p=*/false);
15589                   if (COMPLETE_TYPE_P (instantiation))
15590                     reconsider = 1;
15591                 }
15592
15593               complete = COMPLETE_TYPE_P (instantiation);
15594             }
15595           else
15596             {
15597               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
15598                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
15599                 {
15600                   instantiation
15601                     = instantiate_decl (instantiation,
15602                                         /*defer_ok=*/0,
15603                                         /*expl_inst_class_mem_p=*/false);
15604                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
15605                     reconsider = 1;
15606                 }
15607
15608               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
15609                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
15610             }
15611
15612           if (complete)
15613             /* If INSTANTIATION has been instantiated, then we don't
15614                need to consider it again in the future.  */
15615             *t = (*t)->next;
15616           else
15617             {
15618               last = *t;
15619               t = &(*t)->next;
15620             }
15621           tinst_depth = 0;
15622           current_tinst_level = NULL;
15623         }
15624       last_pending_template = last;
15625     }
15626   while (reconsider);
15627
15628   input_location = saved_loc;
15629 }
15630
15631 /* Substitute ARGVEC into T, which is a list of initializers for
15632    either base class or a non-static data member.  The TREE_PURPOSEs
15633    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
15634    instantiate_decl.  */
15635
15636 static tree
15637 tsubst_initializer_list (tree t, tree argvec)
15638 {
15639   tree inits = NULL_TREE;
15640
15641   for (; t; t = TREE_CHAIN (t))
15642     {
15643       tree decl;
15644       tree init;
15645       tree expanded_bases = NULL_TREE;
15646       tree expanded_arguments = NULL_TREE;
15647       int i, len = 1;
15648
15649       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
15650         {
15651           tree expr;
15652           tree arg;
15653
15654           /* Expand the base class expansion type into separate base
15655              classes.  */
15656           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
15657                                                  tf_warning_or_error,
15658                                                  NULL_TREE);
15659           if (expanded_bases == error_mark_node)
15660             continue;
15661           
15662           /* We'll be building separate TREE_LISTs of arguments for
15663              each base.  */
15664           len = TREE_VEC_LENGTH (expanded_bases);
15665           expanded_arguments = make_tree_vec (len);
15666           for (i = 0; i < len; i++)
15667             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
15668
15669           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
15670              expand each argument in the TREE_VALUE of t.  */
15671           expr = make_node (EXPR_PACK_EXPANSION);
15672           PACK_EXPANSION_PARAMETER_PACKS (expr) =
15673             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
15674
15675           if (TREE_VALUE (t) == void_type_node)
15676             /* VOID_TYPE_NODE is used to indicate
15677                value-initialization.  */
15678             {
15679               for (i = 0; i < len; i++)
15680                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
15681             }
15682           else
15683             {
15684               /* Substitute parameter packs into each argument in the
15685                  TREE_LIST.  */
15686               in_base_initializer = 1;
15687               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
15688                 {
15689                   tree expanded_exprs;
15690
15691                   /* Expand the argument.  */
15692                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
15693                   expanded_exprs 
15694                     = tsubst_pack_expansion (expr, argvec,
15695                                              tf_warning_or_error,
15696                                              NULL_TREE);
15697                   if (expanded_exprs == error_mark_node)
15698                     continue;
15699
15700                   /* Prepend each of the expanded expressions to the
15701                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
15702                   for (i = 0; i < len; i++)
15703                     {
15704                       TREE_VEC_ELT (expanded_arguments, i) = 
15705                         tree_cons (NULL_TREE, 
15706                                    TREE_VEC_ELT (expanded_exprs, i),
15707                                    TREE_VEC_ELT (expanded_arguments, i));
15708                     }
15709                 }
15710               in_base_initializer = 0;
15711
15712               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
15713                  since we built them backwards.  */
15714               for (i = 0; i < len; i++)
15715                 {
15716                   TREE_VEC_ELT (expanded_arguments, i) = 
15717                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
15718                 }
15719             }
15720         }
15721
15722       for (i = 0; i < len; ++i)
15723         {
15724           if (expanded_bases)
15725             {
15726               decl = TREE_VEC_ELT (expanded_bases, i);
15727               decl = expand_member_init (decl);
15728               init = TREE_VEC_ELT (expanded_arguments, i);
15729             }
15730           else
15731             {
15732               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
15733                                   tf_warning_or_error, NULL_TREE);
15734
15735               decl = expand_member_init (decl);
15736               if (decl && !DECL_P (decl))
15737                 in_base_initializer = 1;
15738
15739               init = tsubst_expr (TREE_VALUE (t), argvec, 
15740                                   tf_warning_or_error, NULL_TREE,
15741                                   /*integral_constant_expression_p=*/false);
15742               in_base_initializer = 0;
15743             }
15744
15745           if (decl)
15746             {
15747               init = build_tree_list (decl, init);
15748               TREE_CHAIN (init) = inits;
15749               inits = init;
15750             }
15751         }
15752     }
15753   return inits;
15754 }
15755
15756 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
15757
15758 static void
15759 set_current_access_from_decl (tree decl)
15760 {
15761   if (TREE_PRIVATE (decl))
15762     current_access_specifier = access_private_node;
15763   else if (TREE_PROTECTED (decl))
15764     current_access_specifier = access_protected_node;
15765   else
15766     current_access_specifier = access_public_node;
15767 }
15768
15769 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
15770    is the instantiation (which should have been created with
15771    start_enum) and ARGS are the template arguments to use.  */
15772
15773 static void
15774 tsubst_enum (tree tag, tree newtag, tree args)
15775 {
15776   tree e;
15777
15778   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
15779     {
15780       tree value;
15781       tree decl;
15782
15783       decl = TREE_VALUE (e);
15784       /* Note that in a template enum, the TREE_VALUE is the
15785          CONST_DECL, not the corresponding INTEGER_CST.  */
15786       value = tsubst_expr (DECL_INITIAL (decl),
15787                            args, tf_warning_or_error, NULL_TREE,
15788                            /*integral_constant_expression_p=*/true);
15789
15790       /* Give this enumeration constant the correct access.  */
15791       set_current_access_from_decl (decl);
15792
15793       /* Actually build the enumerator itself.  */
15794       build_enumerator (DECL_NAME (decl), value, newtag);
15795     }
15796
15797   finish_enum (newtag);
15798   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
15799     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
15800 }
15801
15802 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
15803    its type -- but without substituting the innermost set of template
15804    arguments.  So, innermost set of template parameters will appear in
15805    the type.  */
15806
15807 tree
15808 get_mostly_instantiated_function_type (tree decl)
15809 {
15810   tree fn_type;
15811   tree tmpl;
15812   tree targs;
15813   tree tparms;
15814   int parm_depth;
15815
15816   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
15817   targs = DECL_TI_ARGS (decl);
15818   tparms = DECL_TEMPLATE_PARMS (tmpl);
15819   parm_depth = TMPL_PARMS_DEPTH (tparms);
15820
15821   /* There should be as many levels of arguments as there are levels
15822      of parameters.  */
15823   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
15824
15825   fn_type = TREE_TYPE (tmpl);
15826
15827   if (parm_depth == 1)
15828     /* No substitution is necessary.  */
15829     ;
15830   else
15831     {
15832       int i, save_access_control;
15833       tree partial_args;
15834
15835       /* Replace the innermost level of the TARGS with NULL_TREEs to
15836          let tsubst know not to substitute for those parameters.  */
15837       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
15838       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
15839         SET_TMPL_ARGS_LEVEL (partial_args, i,
15840                              TMPL_ARGS_LEVEL (targs, i));
15841       SET_TMPL_ARGS_LEVEL (partial_args,
15842                            TMPL_ARGS_DEPTH (targs),
15843                            make_tree_vec (DECL_NTPARMS (tmpl)));
15844
15845       /* Disable access control as this function is used only during
15846          name-mangling.  */
15847       save_access_control = flag_access_control;
15848       flag_access_control = 0;
15849
15850       ++processing_template_decl;
15851       /* Now, do the (partial) substitution to figure out the
15852          appropriate function type.  */
15853       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
15854       --processing_template_decl;
15855
15856       /* Substitute into the template parameters to obtain the real
15857          innermost set of parameters.  This step is important if the
15858          innermost set of template parameters contains value
15859          parameters whose types depend on outer template parameters.  */
15860       TREE_VEC_LENGTH (partial_args)--;
15861       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
15862
15863       flag_access_control = save_access_control;
15864     }
15865
15866   return fn_type;
15867 }
15868
15869 /* Return truthvalue if we're processing a template different from
15870    the last one involved in diagnostics.  */
15871 int
15872 problematic_instantiation_changed (void)
15873 {
15874   return last_template_error_tick != tinst_level_tick;
15875 }
15876
15877 /* Remember current template involved in diagnostics.  */
15878 void
15879 record_last_problematic_instantiation (void)
15880 {
15881   last_template_error_tick = tinst_level_tick;
15882 }
15883
15884 struct tinst_level *
15885 current_instantiation (void)
15886 {
15887   return current_tinst_level;
15888 }
15889
15890 /* [temp.param] Check that template non-type parm TYPE is of an allowable
15891    type. Return zero for ok, nonzero for disallowed. Issue error and
15892    warning messages under control of COMPLAIN.  */
15893
15894 static int
15895 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
15896 {
15897   if (INTEGRAL_TYPE_P (type))
15898     return 0;
15899   else if (POINTER_TYPE_P (type))
15900     return 0;
15901   else if (TYPE_PTR_TO_MEMBER_P (type))
15902     return 0;
15903   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
15904     return 0;
15905   else if (TREE_CODE (type) == TYPENAME_TYPE)
15906     return 0;
15907
15908   if (complain & tf_error)
15909     error ("%q#T is not a valid type for a template constant parameter", type);
15910   return 1;
15911 }
15912
15913 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
15914    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
15915
15916 static bool
15917 dependent_type_p_r (tree type)
15918 {
15919   tree scope;
15920
15921   /* [temp.dep.type]
15922
15923      A type is dependent if it is:
15924
15925      -- a template parameter. Template template parameters are types
15926         for us (since TYPE_P holds true for them) so we handle
15927         them here.  */
15928   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
15929       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
15930     return true;
15931   /* -- a qualified-id with a nested-name-specifier which contains a
15932         class-name that names a dependent type or whose unqualified-id
15933         names a dependent type.  */
15934   if (TREE_CODE (type) == TYPENAME_TYPE)
15935     return true;
15936   /* -- a cv-qualified type where the cv-unqualified type is
15937         dependent.  */
15938   type = TYPE_MAIN_VARIANT (type);
15939   /* -- a compound type constructed from any dependent type.  */
15940   if (TYPE_PTR_TO_MEMBER_P (type))
15941     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
15942             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
15943                                            (type)));
15944   else if (TREE_CODE (type) == POINTER_TYPE
15945            || TREE_CODE (type) == REFERENCE_TYPE)
15946     return dependent_type_p (TREE_TYPE (type));
15947   else if (TREE_CODE (type) == FUNCTION_TYPE
15948            || TREE_CODE (type) == METHOD_TYPE)
15949     {
15950       tree arg_type;
15951
15952       if (dependent_type_p (TREE_TYPE (type)))
15953         return true;
15954       for (arg_type = TYPE_ARG_TYPES (type);
15955            arg_type;
15956            arg_type = TREE_CHAIN (arg_type))
15957         if (dependent_type_p (TREE_VALUE (arg_type)))
15958           return true;
15959       return false;
15960     }
15961   /* -- an array type constructed from any dependent type or whose
15962         size is specified by a constant expression that is
15963         value-dependent.  */
15964   if (TREE_CODE (type) == ARRAY_TYPE)
15965     {
15966       if (TYPE_DOMAIN (type)
15967           && dependent_type_p (TYPE_DOMAIN (type)))
15968         return true;
15969       return dependent_type_p (TREE_TYPE (type));
15970     }
15971   else if (TREE_CODE (type) == INTEGER_TYPE
15972            && !TREE_CONSTANT (TYPE_MAX_VALUE (type)))
15973     {
15974       /* If this is the TYPE_DOMAIN of an array type, consider it
15975          dependent.  */
15976       return (value_dependent_expression_p (TYPE_MAX_VALUE (type))
15977               || type_dependent_expression_p (TYPE_MAX_VALUE (type)));
15978     }
15979
15980   /* -- a template-id in which either the template name is a template
15981      parameter ...  */
15982   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
15983     return true;
15984   /* ... or any of the template arguments is a dependent type or
15985         an expression that is type-dependent or value-dependent.  */
15986   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
15987            && (any_dependent_template_arguments_p
15988                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
15989     return true;
15990
15991   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
15992      argument of the `typeof' expression is not type-dependent, then
15993      it should already been have resolved.  */
15994   if (TREE_CODE (type) == TYPEOF_TYPE
15995       || TREE_CODE (type) == DECLTYPE_TYPE)
15996     return true;
15997
15998   /* A template argument pack is dependent if any of its packed
15999      arguments are.  */
16000   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
16001     {
16002       tree args = ARGUMENT_PACK_ARGS (type);
16003       int i, len = TREE_VEC_LENGTH (args);
16004       for (i = 0; i < len; ++i)
16005         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
16006           return true;
16007     }
16008
16009   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
16010      be template parameters.  */
16011   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
16012     return true;
16013
16014   /* The standard does not specifically mention types that are local
16015      to template functions or local classes, but they should be
16016      considered dependent too.  For example:
16017
16018        template <int I> void f() {
16019          enum E { a = I };
16020          S<sizeof (E)> s;
16021        }
16022
16023      The size of `E' cannot be known until the value of `I' has been
16024      determined.  Therefore, `E' must be considered dependent.  */
16025   scope = TYPE_CONTEXT (type);
16026   if (scope && TYPE_P (scope))
16027     return dependent_type_p (scope);
16028   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
16029     return type_dependent_expression_p (scope);
16030
16031   /* Other types are non-dependent.  */
16032   return false;
16033 }
16034
16035 /* Returns TRUE if TYPE is dependent, in the sense of
16036    [temp.dep.type].  */
16037
16038 bool
16039 dependent_type_p (tree type)
16040 {
16041   /* If there are no template parameters in scope, then there can't be
16042      any dependent types.  */
16043   if (!processing_template_decl)
16044     {
16045       /* If we are not processing a template, then nobody should be
16046          providing us with a dependent type.  */
16047       gcc_assert (type);
16048       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
16049       return false;
16050     }
16051
16052   /* If the type is NULL, we have not computed a type for the entity
16053      in question; in that case, the type is dependent.  */
16054   if (!type)
16055     return true;
16056
16057   /* Erroneous types can be considered non-dependent.  */
16058   if (type == error_mark_node)
16059     return false;
16060
16061   /* If we have not already computed the appropriate value for TYPE,
16062      do so now.  */
16063   if (!TYPE_DEPENDENT_P_VALID (type))
16064     {
16065       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
16066       TYPE_DEPENDENT_P_VALID (type) = 1;
16067     }
16068
16069   return TYPE_DEPENDENT_P (type);
16070 }
16071
16072 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
16073    lookup.  In other words, a dependent type that is not the current
16074    instantiation.  */
16075
16076 bool
16077 dependent_scope_p (tree scope)
16078 {
16079   return dependent_type_p (scope) && !currently_open_class (scope);
16080 }
16081
16082 /* Returns TRUE if EXPRESSION is dependent, according to CRITERION.  */
16083
16084 static bool
16085 dependent_scope_ref_p (tree expression, bool criterion (tree))
16086 {
16087   tree scope;
16088   tree name;
16089
16090   gcc_assert (TREE_CODE (expression) == SCOPE_REF);
16091
16092   if (!TYPE_P (TREE_OPERAND (expression, 0)))
16093     return true;
16094
16095   scope = TREE_OPERAND (expression, 0);
16096   name = TREE_OPERAND (expression, 1);
16097
16098   /* [temp.dep.expr]
16099
16100      An id-expression is type-dependent if it contains a
16101      nested-name-specifier that contains a class-name that names a
16102      dependent type.  */
16103   /* The suggested resolution to Core Issue 224 implies that if the
16104      qualifying type is the current class, then we must peek
16105      inside it.  */
16106   if (DECL_P (name)
16107       && currently_open_class (scope)
16108       && !criterion (name))
16109     return false;
16110   if (dependent_type_p (scope))
16111     return true;
16112
16113   return false;
16114 }
16115
16116 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
16117    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
16118    expression.  */
16119
16120 bool
16121 value_dependent_expression_p (tree expression)
16122 {
16123   if (!processing_template_decl)
16124     return false;
16125
16126   /* A name declared with a dependent type.  */
16127   if (DECL_P (expression) && type_dependent_expression_p (expression))
16128     return true;
16129
16130   switch (TREE_CODE (expression))
16131     {
16132     case IDENTIFIER_NODE:
16133       /* A name that has not been looked up -- must be dependent.  */
16134       return true;
16135
16136     case TEMPLATE_PARM_INDEX:
16137       /* A non-type template parm.  */
16138       return true;
16139
16140     case CONST_DECL:
16141       /* A non-type template parm.  */
16142       if (DECL_TEMPLATE_PARM_P (expression))
16143         return true;
16144       return value_dependent_expression_p (DECL_INITIAL (expression));
16145
16146     case VAR_DECL:
16147        /* A constant with integral or enumeration type and is initialized
16148           with an expression that is value-dependent.  */
16149       if (DECL_INITIAL (expression)
16150           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
16151           && value_dependent_expression_p (DECL_INITIAL (expression)))
16152         return true;
16153       return false;
16154
16155     case DYNAMIC_CAST_EXPR:
16156     case STATIC_CAST_EXPR:
16157     case CONST_CAST_EXPR:
16158     case REINTERPRET_CAST_EXPR:
16159     case CAST_EXPR:
16160       /* These expressions are value-dependent if the type to which
16161          the cast occurs is dependent or the expression being casted
16162          is value-dependent.  */
16163       {
16164         tree type = TREE_TYPE (expression);
16165
16166         if (dependent_type_p (type))
16167           return true;
16168
16169         /* A functional cast has a list of operands.  */
16170         expression = TREE_OPERAND (expression, 0);
16171         if (!expression)
16172           {
16173             /* If there are no operands, it must be an expression such
16174                as "int()". This should not happen for aggregate types
16175                because it would form non-constant expressions.  */
16176             gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
16177
16178             return false;
16179           }
16180
16181         if (TREE_CODE (expression) == TREE_LIST)
16182           return any_value_dependent_elements_p (expression);
16183
16184         return value_dependent_expression_p (expression);
16185       }
16186
16187     case SIZEOF_EXPR:
16188     case ALIGNOF_EXPR:
16189       /* A `sizeof' expression is value-dependent if the operand is
16190          type-dependent or is a pack expansion.  */
16191       expression = TREE_OPERAND (expression, 0);
16192       if (PACK_EXPANSION_P (expression))
16193         return true;
16194       else if (TYPE_P (expression))
16195         return dependent_type_p (expression);
16196       return type_dependent_expression_p (expression);
16197
16198     case SCOPE_REF:
16199       return dependent_scope_ref_p (expression, value_dependent_expression_p);
16200
16201     case COMPONENT_REF:
16202       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
16203               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
16204
16205     case CALL_EXPR:
16206       /* A CALL_EXPR may appear in a constant expression if it is a
16207          call to a builtin function, e.g., __builtin_constant_p.  All
16208          such calls are value-dependent.  */
16209       return true;
16210
16211     case NONTYPE_ARGUMENT_PACK:
16212       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
16213          is value-dependent.  */
16214       {
16215         tree values = ARGUMENT_PACK_ARGS (expression);
16216         int i, len = TREE_VEC_LENGTH (values);
16217         
16218         for (i = 0; i < len; ++i)
16219           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
16220             return true;
16221         
16222         return false;
16223       }
16224
16225     case TRAIT_EXPR:
16226       {
16227         tree type2 = TRAIT_EXPR_TYPE2 (expression);
16228         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
16229                 || (type2 ? dependent_type_p (type2) : false));
16230       }
16231
16232     case MODOP_EXPR:
16233       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
16234               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
16235
16236     default:
16237       /* A constant expression is value-dependent if any subexpression is
16238          value-dependent.  */
16239       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
16240         {
16241         case tcc_reference:
16242         case tcc_unary:
16243           return (value_dependent_expression_p
16244                   (TREE_OPERAND (expression, 0)));
16245
16246         case tcc_comparison:
16247         case tcc_binary:
16248           return ((value_dependent_expression_p
16249                    (TREE_OPERAND (expression, 0)))
16250                   || (value_dependent_expression_p
16251                       (TREE_OPERAND (expression, 1))));
16252
16253         case tcc_expression:
16254         case tcc_vl_exp:
16255           {
16256             int i;
16257             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
16258               /* In some cases, some of the operands may be missing.
16259                  (For example, in the case of PREDECREMENT_EXPR, the
16260                  amount to increment by may be missing.)  That doesn't
16261                  make the expression dependent.  */
16262               if (TREE_OPERAND (expression, i)
16263                   && (value_dependent_expression_p
16264                       (TREE_OPERAND (expression, i))))
16265                 return true;
16266             return false;
16267           }
16268
16269         default:
16270           break;
16271         }
16272     }
16273
16274   /* The expression is not value-dependent.  */
16275   return false;
16276 }
16277
16278 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
16279    [temp.dep.expr].  */
16280
16281 bool
16282 type_dependent_expression_p (tree expression)
16283 {
16284   if (!processing_template_decl)
16285     return false;
16286
16287   if (expression == error_mark_node)
16288     return false;
16289
16290   /* An unresolved name is always dependent.  */
16291   if (TREE_CODE (expression) == IDENTIFIER_NODE
16292       || TREE_CODE (expression) == USING_DECL)
16293     return true;
16294
16295   /* Some expression forms are never type-dependent.  */
16296   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
16297       || TREE_CODE (expression) == SIZEOF_EXPR
16298       || TREE_CODE (expression) == ALIGNOF_EXPR
16299       || TREE_CODE (expression) == TRAIT_EXPR
16300       || TREE_CODE (expression) == TYPEID_EXPR
16301       || TREE_CODE (expression) == DELETE_EXPR
16302       || TREE_CODE (expression) == VEC_DELETE_EXPR
16303       || TREE_CODE (expression) == THROW_EXPR)
16304     return false;
16305
16306   /* The types of these expressions depends only on the type to which
16307      the cast occurs.  */
16308   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
16309       || TREE_CODE (expression) == STATIC_CAST_EXPR
16310       || TREE_CODE (expression) == CONST_CAST_EXPR
16311       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
16312       || TREE_CODE (expression) == CAST_EXPR)
16313     return dependent_type_p (TREE_TYPE (expression));
16314
16315   /* The types of these expressions depends only on the type created
16316      by the expression.  */
16317   if (TREE_CODE (expression) == NEW_EXPR
16318       || TREE_CODE (expression) == VEC_NEW_EXPR)
16319     {
16320       /* For NEW_EXPR tree nodes created inside a template, either
16321          the object type itself or a TREE_LIST may appear as the
16322          operand 1.  */
16323       tree type = TREE_OPERAND (expression, 1);
16324       if (TREE_CODE (type) == TREE_LIST)
16325         /* This is an array type.  We need to check array dimensions
16326            as well.  */
16327         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
16328                || value_dependent_expression_p
16329                     (TREE_OPERAND (TREE_VALUE (type), 1));
16330       else
16331         return dependent_type_p (type);
16332     }
16333
16334   if (TREE_CODE (expression) == SCOPE_REF
16335       && dependent_scope_ref_p (expression,
16336                                 type_dependent_expression_p))
16337     return true;
16338
16339   if (TREE_CODE (expression) == FUNCTION_DECL
16340       && DECL_LANG_SPECIFIC (expression)
16341       && DECL_TEMPLATE_INFO (expression)
16342       && (any_dependent_template_arguments_p
16343           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
16344     return true;
16345
16346   if (TREE_CODE (expression) == TEMPLATE_DECL
16347       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
16348     return false;
16349
16350   if (TREE_CODE (expression) == STMT_EXPR)
16351     expression = stmt_expr_value_expr (expression);
16352
16353   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
16354     {
16355       tree elt;
16356       unsigned i;
16357
16358       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
16359         {
16360           if (type_dependent_expression_p (elt))
16361             return true;
16362         }
16363       return false;
16364     }
16365
16366   if (TREE_TYPE (expression) == unknown_type_node)
16367     {
16368       if (TREE_CODE (expression) == ADDR_EXPR)
16369         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
16370       if (TREE_CODE (expression) == COMPONENT_REF
16371           || TREE_CODE (expression) == OFFSET_REF)
16372         {
16373           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
16374             return true;
16375           expression = TREE_OPERAND (expression, 1);
16376           if (TREE_CODE (expression) == IDENTIFIER_NODE)
16377             return false;
16378         }
16379       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
16380       if (TREE_CODE (expression) == SCOPE_REF)
16381         return false;
16382
16383       if (TREE_CODE (expression) == BASELINK)
16384         expression = BASELINK_FUNCTIONS (expression);
16385
16386       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
16387         {
16388           if (any_dependent_template_arguments_p
16389               (TREE_OPERAND (expression, 1)))
16390             return true;
16391           expression = TREE_OPERAND (expression, 0);
16392         }
16393       gcc_assert (TREE_CODE (expression) == OVERLOAD
16394                   || TREE_CODE (expression) == FUNCTION_DECL);
16395
16396       while (expression)
16397         {
16398           if (type_dependent_expression_p (OVL_CURRENT (expression)))
16399             return true;
16400           expression = OVL_NEXT (expression);
16401         }
16402       return false;
16403     }
16404
16405   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
16406
16407   return (dependent_type_p (TREE_TYPE (expression)));
16408 }
16409
16410 /* Returns TRUE if ARGS (a TREE_LIST of arguments to a function call)
16411    contains a type-dependent expression.  */
16412
16413 bool
16414 any_type_dependent_arguments_p (const_tree args)
16415 {
16416   while (args)
16417     {
16418       tree arg = TREE_VALUE (args);
16419
16420       if (type_dependent_expression_p (arg))
16421         return true;
16422       args = TREE_CHAIN (args);
16423     }
16424   return false;
16425 }
16426
16427 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
16428    expressions) contains any value-dependent expressions.  */
16429
16430 bool
16431 any_value_dependent_elements_p (const_tree list)
16432 {
16433   for (; list; list = TREE_CHAIN (list))
16434     if (value_dependent_expression_p (TREE_VALUE (list)))
16435       return true;
16436
16437   return false;
16438 }
16439
16440 /* Returns TRUE if the ARG (a template argument) is dependent.  */
16441
16442 bool
16443 dependent_template_arg_p (tree arg)
16444 {
16445   if (!processing_template_decl)
16446     return false;
16447
16448   if (TREE_CODE (arg) == TEMPLATE_DECL
16449       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
16450     return dependent_template_p (arg);
16451   else if (ARGUMENT_PACK_P (arg))
16452     {
16453       tree args = ARGUMENT_PACK_ARGS (arg);
16454       int i, len = TREE_VEC_LENGTH (args);
16455       for (i = 0; i < len; ++i)
16456         {
16457           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
16458             return true;
16459         }
16460
16461       return false;
16462     }
16463   else if (TYPE_P (arg))
16464     return dependent_type_p (arg);
16465   else
16466     return (type_dependent_expression_p (arg)
16467             || value_dependent_expression_p (arg));
16468 }
16469
16470 /* Returns true if ARGS (a collection of template arguments) contains
16471    any types that require structural equality testing.  */
16472
16473 bool
16474 any_template_arguments_need_structural_equality_p (tree args)
16475 {
16476   int i;
16477   int j;
16478
16479   if (!args)
16480     return false;
16481   if (args == error_mark_node)
16482     return true;
16483
16484   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
16485     {
16486       tree level = TMPL_ARGS_LEVEL (args, i + 1);
16487       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
16488         {
16489           tree arg = TREE_VEC_ELT (level, j);
16490           tree packed_args = NULL_TREE;
16491           int k, len = 1;
16492
16493           if (ARGUMENT_PACK_P (arg))
16494             {
16495               /* Look inside the argument pack.  */
16496               packed_args = ARGUMENT_PACK_ARGS (arg);
16497               len = TREE_VEC_LENGTH (packed_args);
16498             }
16499
16500           for (k = 0; k < len; ++k)
16501             {
16502               if (packed_args)
16503                 arg = TREE_VEC_ELT (packed_args, k);
16504
16505               if (error_operand_p (arg))
16506                 return true;
16507               else if (TREE_CODE (arg) == TEMPLATE_DECL
16508                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
16509                 continue;
16510               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
16511                 return true;
16512               else if (!TYPE_P (arg) && TREE_TYPE (arg)
16513                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
16514                 return true;
16515             }
16516         }
16517     }
16518
16519   return false;
16520 }
16521
16522 /* Returns true if ARGS (a collection of template arguments) contains
16523    any dependent arguments.  */
16524
16525 bool
16526 any_dependent_template_arguments_p (const_tree args)
16527 {
16528   int i;
16529   int j;
16530
16531   if (!args)
16532     return false;
16533   if (args == error_mark_node)
16534     return true;
16535
16536   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
16537     {
16538       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
16539       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
16540         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
16541           return true;
16542     }
16543
16544   return false;
16545 }
16546
16547 /* Returns TRUE if the template TMPL is dependent.  */
16548
16549 bool
16550 dependent_template_p (tree tmpl)
16551 {
16552   if (TREE_CODE (tmpl) == OVERLOAD)
16553     {
16554       while (tmpl)
16555         {
16556           if (dependent_template_p (OVL_FUNCTION (tmpl)))
16557             return true;
16558           tmpl = OVL_CHAIN (tmpl);
16559         }
16560       return false;
16561     }
16562
16563   /* Template template parameters are dependent.  */
16564   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
16565       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
16566     return true;
16567   /* So are names that have not been looked up.  */
16568   if (TREE_CODE (tmpl) == SCOPE_REF
16569       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
16570     return true;
16571   /* So are member templates of dependent classes.  */
16572   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
16573     return dependent_type_p (DECL_CONTEXT (tmpl));
16574   return false;
16575 }
16576
16577 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
16578
16579 bool
16580 dependent_template_id_p (tree tmpl, tree args)
16581 {
16582   return (dependent_template_p (tmpl)
16583           || any_dependent_template_arguments_p (args));
16584 }
16585
16586 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
16587    is dependent.  */
16588
16589 bool
16590 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
16591 {
16592   int i;
16593
16594   if (!processing_template_decl)
16595     return false;
16596
16597   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
16598     {
16599       tree decl = TREE_VEC_ELT (declv, i);
16600       tree init = TREE_VEC_ELT (initv, i);
16601       tree cond = TREE_VEC_ELT (condv, i);
16602       tree incr = TREE_VEC_ELT (incrv, i);
16603
16604       if (type_dependent_expression_p (decl))
16605         return true;
16606
16607       if (init && type_dependent_expression_p (init))
16608         return true;
16609
16610       if (type_dependent_expression_p (cond))
16611         return true;
16612
16613       if (COMPARISON_CLASS_P (cond)
16614           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
16615               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
16616         return true;
16617
16618       if (TREE_CODE (incr) == MODOP_EXPR)
16619         {
16620           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
16621               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
16622             return true;
16623         }
16624       else if (type_dependent_expression_p (incr))
16625         return true;
16626       else if (TREE_CODE (incr) == MODIFY_EXPR)
16627         {
16628           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
16629             return true;
16630           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
16631             {
16632               tree t = TREE_OPERAND (incr, 1);
16633               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
16634                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
16635                 return true;
16636             }
16637         }
16638     }
16639
16640   return false;
16641 }
16642
16643 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
16644    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
16645    no such TYPE can be found.  Note that this function peers inside
16646    uninstantiated templates and therefore should be used only in
16647    extremely limited situations.  ONLY_CURRENT_P restricts this
16648    peering to the currently open classes hierarchy (which is required
16649    when comparing types).  */
16650
16651 tree
16652 resolve_typename_type (tree type, bool only_current_p)
16653 {
16654   tree scope;
16655   tree name;
16656   tree decl;
16657   int quals;
16658   tree pushed_scope;
16659   tree result;
16660
16661   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
16662
16663   scope = TYPE_CONTEXT (type);
16664   name = TYPE_IDENTIFIER (type);
16665
16666   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
16667      it first before we can figure out what NAME refers to.  */
16668   if (TREE_CODE (scope) == TYPENAME_TYPE)
16669     scope = resolve_typename_type (scope, only_current_p);
16670   /* If we don't know what SCOPE refers to, then we cannot resolve the
16671      TYPENAME_TYPE.  */
16672   if (TREE_CODE (scope) == TYPENAME_TYPE)
16673     return type;
16674   /* If the SCOPE is a template type parameter, we have no way of
16675      resolving the name.  */
16676   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
16677     return type;
16678   /* If the SCOPE is not the current instantiation, there's no reason
16679      to look inside it.  */
16680   if (only_current_p && !currently_open_class (scope))
16681     return type;
16682   /* If SCOPE isn't the template itself, it will not have a valid
16683      TYPE_FIELDS list.  */
16684   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
16685     /* scope is either the template itself or a compatible instantiation
16686        like X<T>, so look up the name in the original template.  */
16687     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
16688   else
16689     /* scope is a partial instantiation, so we can't do the lookup or we
16690        will lose the template arguments.  */
16691     return type;
16692   /* Enter the SCOPE so that name lookup will be resolved as if we
16693      were in the class definition.  In particular, SCOPE will no
16694      longer be considered a dependent type.  */
16695   pushed_scope = push_scope (scope);
16696   /* Look up the declaration.  */
16697   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
16698
16699   result = NULL_TREE;
16700   
16701   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
16702      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
16703   if (!decl)
16704     /*nop*/;
16705   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
16706            && TREE_CODE (decl) == TYPE_DECL)
16707     {
16708       result = TREE_TYPE (decl);
16709       if (result == error_mark_node)
16710         result = NULL_TREE;
16711     }
16712   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
16713            && DECL_CLASS_TEMPLATE_P (decl))
16714     {
16715       tree tmpl;
16716       tree args;
16717       /* Obtain the template and the arguments.  */
16718       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
16719       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
16720       /* Instantiate the template.  */
16721       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
16722                                       /*entering_scope=*/0,
16723                                       tf_error | tf_user);
16724       if (result == error_mark_node)
16725         result = NULL_TREE;
16726     }
16727   
16728   /* Leave the SCOPE.  */
16729   if (pushed_scope)
16730     pop_scope (pushed_scope);
16731
16732   /* If we failed to resolve it, return the original typename.  */
16733   if (!result)
16734     return type;
16735   
16736   /* If lookup found a typename type, resolve that too.  */
16737   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
16738     {
16739       /* Ill-formed programs can cause infinite recursion here, so we
16740          must catch that.  */
16741       TYPENAME_IS_RESOLVING_P (type) = 1;
16742       result = resolve_typename_type (result, only_current_p);
16743       TYPENAME_IS_RESOLVING_P (type) = 0;
16744     }
16745   
16746   /* Qualify the resulting type.  */
16747   quals = cp_type_quals (type);
16748   if (quals)
16749     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
16750
16751   return result;
16752 }
16753
16754 /* EXPR is an expression which is not type-dependent.  Return a proxy
16755    for EXPR that can be used to compute the types of larger
16756    expressions containing EXPR.  */
16757
16758 tree
16759 build_non_dependent_expr (tree expr)
16760 {
16761   tree inner_expr;
16762
16763   /* Preserve null pointer constants so that the type of things like
16764      "p == 0" where "p" is a pointer can be determined.  */
16765   if (null_ptr_cst_p (expr))
16766     return expr;
16767   /* Preserve OVERLOADs; the functions must be available to resolve
16768      types.  */
16769   inner_expr = expr;
16770   if (TREE_CODE (inner_expr) == STMT_EXPR)
16771     inner_expr = stmt_expr_value_expr (inner_expr);
16772   if (TREE_CODE (inner_expr) == ADDR_EXPR)
16773     inner_expr = TREE_OPERAND (inner_expr, 0);
16774   if (TREE_CODE (inner_expr) == COMPONENT_REF)
16775     inner_expr = TREE_OPERAND (inner_expr, 1);
16776   if (is_overloaded_fn (inner_expr)
16777       || TREE_CODE (inner_expr) == OFFSET_REF)
16778     return expr;
16779   /* There is no need to return a proxy for a variable.  */
16780   if (TREE_CODE (expr) == VAR_DECL)
16781     return expr;
16782   /* Preserve string constants; conversions from string constants to
16783      "char *" are allowed, even though normally a "const char *"
16784      cannot be used to initialize a "char *".  */
16785   if (TREE_CODE (expr) == STRING_CST)
16786     return expr;
16787   /* Preserve arithmetic constants, as an optimization -- there is no
16788      reason to create a new node.  */
16789   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
16790     return expr;
16791   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
16792      There is at least one place where we want to know that a
16793      particular expression is a throw-expression: when checking a ?:
16794      expression, there are special rules if the second or third
16795      argument is a throw-expression.  */
16796   if (TREE_CODE (expr) == THROW_EXPR)
16797     return expr;
16798
16799   if (TREE_CODE (expr) == COND_EXPR)
16800     return build3 (COND_EXPR,
16801                    TREE_TYPE (expr),
16802                    TREE_OPERAND (expr, 0),
16803                    (TREE_OPERAND (expr, 1)
16804                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
16805                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
16806                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
16807   if (TREE_CODE (expr) == COMPOUND_EXPR
16808       && !COMPOUND_EXPR_OVERLOADED (expr))
16809     return build2 (COMPOUND_EXPR,
16810                    TREE_TYPE (expr),
16811                    TREE_OPERAND (expr, 0),
16812                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
16813
16814   /* If the type is unknown, it can't really be non-dependent */
16815   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
16816
16817   /* Otherwise, build a NON_DEPENDENT_EXPR.
16818
16819      REFERENCE_TYPEs are not stripped for expressions in templates
16820      because doing so would play havoc with mangling.  Consider, for
16821      example:
16822
16823        template <typename T> void f<T& g>() { g(); }
16824
16825      In the body of "f", the expression for "g" will have
16826      REFERENCE_TYPE, even though the standard says that it should
16827      not.  The reason is that we must preserve the syntactic form of
16828      the expression so that mangling (say) "f<g>" inside the body of
16829      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
16830      stripped here.  */
16831   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
16832 }
16833
16834 /* ARGS is a TREE_LIST of expressions as arguments to a function call.
16835    Return a new TREE_LIST with the various arguments replaced with
16836    equivalent non-dependent expressions.  */
16837
16838 tree
16839 build_non_dependent_args (tree args)
16840 {
16841   tree a;
16842   tree new_args;
16843
16844   new_args = NULL_TREE;
16845   for (a = args; a; a = TREE_CHAIN (a))
16846     new_args = tree_cons (NULL_TREE,
16847                           build_non_dependent_expr (TREE_VALUE (a)),
16848                           new_args);
16849   return nreverse (new_args);
16850 }
16851
16852 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
16853    with a level one deeper than the actual template parms.  */
16854
16855 tree
16856 make_auto (void)
16857 {
16858   tree au;
16859
16860   /* ??? Is it worth caching this for multiple autos at the same level?  */
16861   au = cxx_make_type (TEMPLATE_TYPE_PARM);
16862   TYPE_NAME (au) = build_decl (TYPE_DECL, get_identifier ("auto"), au);
16863   TYPE_STUB_DECL (au) = TYPE_NAME (au);
16864   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
16865     (0, processing_template_decl + 1, processing_template_decl + 1,
16866      TYPE_NAME (au), NULL_TREE);
16867   TYPE_CANONICAL (au) = canonical_type_parameter (au);
16868   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
16869   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
16870
16871   return au;
16872 }
16873
16874 /* Replace auto in TYPE with std::initializer_list<auto>.  */
16875
16876 static tree
16877 listify_autos (tree type, tree auto_node)
16878 {
16879   tree std_init_list = namespace_binding
16880     (get_identifier ("initializer_list"), std_node);
16881   tree argvec;
16882   tree init_auto;
16883   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
16884     {    
16885       error ("deducing auto from brace-enclosed initializer list requires "
16886              "#include <initializer_list>");
16887       return error_mark_node;
16888     }
16889   argvec = make_tree_vec (1);
16890   TREE_VEC_ELT (argvec, 0) = auto_node;
16891   init_auto = lookup_template_class (std_init_list, argvec, NULL_TREE,
16892                                      NULL_TREE, 0, tf_warning_or_error);
16893
16894   TREE_VEC_ELT (argvec, 0) = init_auto;
16895   if (processing_template_decl)
16896     argvec = add_to_template_args (current_template_args (), argvec);
16897   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
16898 }
16899
16900 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
16901    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
16902
16903 tree
16904 do_auto_deduction (tree type, tree init, tree auto_node)
16905 {
16906   tree parms, args, tparms, targs;
16907   int val;
16908
16909   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
16910      with either a new invented type template parameter U or, if the
16911      initializer is a braced-init-list (8.5.4), with
16912      std::initializer_list<U>.  */
16913   if (BRACE_ENCLOSED_INITIALIZER_P (init))
16914     type = listify_autos (type, auto_node);
16915
16916   parms = build_tree_list (NULL_TREE, type);
16917   args = build_tree_list (NULL_TREE, init);
16918   tparms = make_tree_vec (1);
16919   targs = make_tree_vec (1);
16920   TREE_VEC_ELT (tparms, 0)
16921     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
16922   val = type_unification_real (tparms, targs, parms, args, 0,
16923                                DEDUCE_CALL, LOOKUP_NORMAL);
16924   if (val > 0)
16925     {
16926       error ("unable to deduce %qT from %qE", type, init);
16927       return error_mark_node;
16928     }
16929
16930   if (processing_template_decl)
16931     targs = add_to_template_args (current_template_args (), targs);
16932   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
16933 }
16934
16935 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
16936    result.  */
16937
16938 tree
16939 splice_late_return_type (tree type, tree late_return_type)
16940 {
16941   tree argvec;
16942
16943   if (late_return_type == NULL_TREE)
16944     return type;
16945   argvec = make_tree_vec (1);
16946   TREE_VEC_ELT (argvec, 0) = late_return_type;
16947   if (processing_template_decl)
16948     argvec = add_to_template_args (current_template_args (), argvec);
16949   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
16950 }
16951
16952 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
16953
16954 bool
16955 is_auto (const_tree type)
16956 {
16957   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
16958       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
16959     return true;
16960   else
16961     return false;
16962 }
16963
16964 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
16965    appear as a type-specifier for the declaration in question, we don't
16966    have to look through the whole type.  */
16967
16968 tree
16969 type_uses_auto (tree type)
16970 {
16971   enum tree_code code;
16972   if (is_auto (type))
16973     return type;
16974
16975   code = TREE_CODE (type);
16976
16977   if (code == POINTER_TYPE || code == REFERENCE_TYPE
16978       || code == OFFSET_TYPE || code == FUNCTION_TYPE
16979       || code == METHOD_TYPE || code == ARRAY_TYPE)
16980     return type_uses_auto (TREE_TYPE (type));
16981
16982   if (TYPE_PTRMEMFUNC_P (type))
16983     return type_uses_auto (TREE_TYPE (TREE_TYPE
16984                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
16985
16986   return NULL_TREE;
16987 }
16988
16989 #include "gt-cp-pt.h"