OSDN Git Service

dfe779146b23cf74b9bbd1d8854b01f493868cf2
[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 GTY (()) pending_template {
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 typedef struct GTY(()) spec_entry
86 {
87   tree tmpl;
88   tree args;
89   tree spec;
90 } spec_entry;
91
92 static GTY ((param_is (spec_entry)))
93   htab_t decl_specializations;
94
95 static GTY ((param_is (spec_entry)))
96   htab_t type_specializations;
97
98 /* Contains canonical template parameter types. The vector is indexed by
99    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
100    TREE_LIST, whose TREE_VALUEs contain the canonical template
101    parameters of various types and levels.  */
102 static GTY(()) VEC(tree,gc) *canonical_template_parms;
103
104 #define UNIFY_ALLOW_NONE 0
105 #define UNIFY_ALLOW_MORE_CV_QUAL 1
106 #define UNIFY_ALLOW_LESS_CV_QUAL 2
107 #define UNIFY_ALLOW_DERIVED 4
108 #define UNIFY_ALLOW_INTEGER 8
109 #define UNIFY_ALLOW_OUTER_LEVEL 16
110 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
111 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
112
113 static void push_access_scope (tree);
114 static void pop_access_scope (tree);
115 static bool resolve_overloaded_unification (tree, tree, tree, tree,
116                                             unification_kind_t, int);
117 static int try_one_overload (tree, tree, tree, tree, tree,
118                              unification_kind_t, int, bool);
119 static int unify (tree, tree, tree, tree, int);
120 static void add_pending_template (tree);
121 static int push_tinst_level (tree);
122 static void pop_tinst_level (void);
123 static tree reopen_tinst_level (struct tinst_level *);
124 static tree tsubst_initializer_list (tree, tree);
125 static tree get_class_bindings (tree, tree, tree);
126 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
127                                    bool, bool);
128 static void tsubst_enum (tree, tree, tree);
129 static tree add_to_template_args (tree, tree);
130 static tree add_outermost_template_args (tree, tree);
131 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
132 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
133                                              tree);
134 static int type_unification_real (tree, tree, tree, const tree *,
135                                   unsigned int, int, unification_kind_t, int);
136 static void note_template_header (int);
137 static tree convert_nontype_argument_function (tree, tree);
138 static tree convert_nontype_argument (tree, tree);
139 static tree convert_template_argument (tree, tree, tree,
140                                        tsubst_flags_t, int, tree);
141 static int for_each_template_parm (tree, tree_fn_t, void*,
142                                    struct pointer_set_t*, bool);
143 static tree expand_template_argument_pack (tree);
144 static tree build_template_parm_index (int, int, int, tree, tree);
145 static bool inline_needs_template_parms (tree);
146 static void push_inline_template_parms_recursive (tree, int);
147 static tree retrieve_local_specialization (tree);
148 static void register_local_specialization (tree, tree);
149 static hashval_t hash_specialization (const void *p);
150 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
151 static int mark_template_parm (tree, void *);
152 static int template_parm_this_level_p (tree, void *);
153 static tree tsubst_friend_function (tree, tree);
154 static tree tsubst_friend_class (tree, tree);
155 static int can_complete_type_without_circularity (tree);
156 static tree get_bindings (tree, tree, tree, bool);
157 static int template_decl_level (tree);
158 static int check_cv_quals_for_unify (int, tree, tree);
159 static void template_parm_level_and_index (tree, int*, int*);
160 static int unify_pack_expansion (tree, tree, tree, tree, int, bool, bool);
161 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
162 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
163 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
164 static void regenerate_decl_from_template (tree, tree);
165 static tree most_specialized_class (tree, tree);
166 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
167 static tree tsubst_arg_types (tree, tree, tsubst_flags_t, tree);
168 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
169 static bool check_specialization_scope (void);
170 static tree process_partial_specialization (tree);
171 static void set_current_access_from_decl (tree);
172 static tree get_template_base (tree, tree, tree, tree);
173 static tree try_class_unification (tree, tree, tree, tree);
174 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
175                                            tree, tree);
176 static bool template_template_parm_bindings_ok_p (tree, tree);
177 static int template_args_equal (tree, tree);
178 static void tsubst_default_arguments (tree);
179 static tree for_each_template_parm_r (tree *, int *, void *);
180 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
181 static void copy_default_args_to_explicit_spec (tree);
182 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
183 static int eq_local_specializations (const void *, const void *);
184 static bool dependent_template_arg_p (tree);
185 static bool any_template_arguments_need_structural_equality_p (tree);
186 static bool dependent_type_p_r (tree);
187 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree, bool);
188 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
189 static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
190 static tree tsubst_decl (tree, tree, tsubst_flags_t);
191 static void perform_typedefs_access_check (tree tmpl, tree targs);
192 static void append_type_to_template_for_access_check_1 (tree, tree, tree,
193                                                         location_t);
194 static hashval_t iterative_hash_template_arg (tree arg, hashval_t val);
195 static tree listify (tree);
196 static tree listify_autos (tree, tree);
197
198 /* Make the current scope suitable for access checking when we are
199    processing T.  T can be FUNCTION_DECL for instantiated function
200    template, or VAR_DECL for static member variable (need by
201    instantiate_decl).  */
202
203 static void
204 push_access_scope (tree t)
205 {
206   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
207               || TREE_CODE (t) == VAR_DECL);
208
209   if (DECL_FRIEND_CONTEXT (t))
210     push_nested_class (DECL_FRIEND_CONTEXT (t));
211   else if (DECL_CLASS_SCOPE_P (t))
212     push_nested_class (DECL_CONTEXT (t));
213   else
214     push_to_top_level ();
215
216   if (TREE_CODE (t) == FUNCTION_DECL)
217     {
218       saved_access_scope = tree_cons
219         (NULL_TREE, current_function_decl, saved_access_scope);
220       current_function_decl = t;
221     }
222 }
223
224 /* Restore the scope set up by push_access_scope.  T is the node we
225    are processing.  */
226
227 static void
228 pop_access_scope (tree t)
229 {
230   if (TREE_CODE (t) == FUNCTION_DECL)
231     {
232       current_function_decl = TREE_VALUE (saved_access_scope);
233       saved_access_scope = TREE_CHAIN (saved_access_scope);
234     }
235
236   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
237     pop_nested_class ();
238   else
239     pop_from_top_level ();
240 }
241
242 /* Do any processing required when DECL (a member template
243    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
244    to DECL, unless it is a specialization, in which case the DECL
245    itself is returned.  */
246
247 tree
248 finish_member_template_decl (tree decl)
249 {
250   if (decl == error_mark_node)
251     return error_mark_node;
252
253   gcc_assert (DECL_P (decl));
254
255   if (TREE_CODE (decl) == TYPE_DECL)
256     {
257       tree type;
258
259       type = TREE_TYPE (decl);
260       if (type == error_mark_node)
261         return error_mark_node;
262       if (MAYBE_CLASS_TYPE_P (type)
263           && CLASSTYPE_TEMPLATE_INFO (type)
264           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
265         {
266           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
267           check_member_template (tmpl);
268           return tmpl;
269         }
270       return NULL_TREE;
271     }
272   else if (TREE_CODE (decl) == FIELD_DECL)
273     error ("data member %qD cannot be a member template", decl);
274   else if (DECL_TEMPLATE_INFO (decl))
275     {
276       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
277         {
278           check_member_template (DECL_TI_TEMPLATE (decl));
279           return DECL_TI_TEMPLATE (decl);
280         }
281       else
282         return decl;
283     }
284   else
285     error ("invalid member template declaration %qD", decl);
286
287   return error_mark_node;
288 }
289
290 /* Create a template info node.  */
291
292 tree
293 build_template_info (tree template_decl, tree template_args)
294 {
295   tree result = make_node (TEMPLATE_INFO);
296   TI_TEMPLATE (result) = template_decl;
297   TI_ARGS (result) = template_args;
298   return result;
299 }
300
301 /* Return the template info node corresponding to T, whatever T is.  */
302
303 tree
304 get_template_info (const_tree t)
305 {
306   tree tinfo = NULL_TREE;
307
308   if (!t || t == error_mark_node)
309     return NULL;
310
311   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
312     tinfo = DECL_TEMPLATE_INFO (t);
313
314   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
315     t = TREE_TYPE (t);
316
317   if (TAGGED_TYPE_P (t))
318     tinfo = TYPE_TEMPLATE_INFO (t);
319
320   return tinfo;
321 }
322
323 /* Returns the template nesting level of the indicated class TYPE.
324
325    For example, in:
326      template <class T>
327      struct A
328      {
329        template <class U>
330        struct B {};
331      };
332
333    A<T>::B<U> has depth two, while A<T> has depth one.
334    Both A<T>::B<int> and A<int>::B<U> have depth one, if
335    they are instantiations, not specializations.
336
337    This function is guaranteed to return 0 if passed NULL_TREE so
338    that, for example, `template_class_depth (current_class_type)' is
339    always safe.  */
340
341 int
342 template_class_depth (tree type)
343 {
344   int depth;
345
346   for (depth = 0;
347        type && TREE_CODE (type) != NAMESPACE_DECL;
348        type = (TREE_CODE (type) == FUNCTION_DECL)
349          ? CP_DECL_CONTEXT (type) : TYPE_CONTEXT (type))
350     {
351       tree tinfo = get_template_info (type);
352
353       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
354           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
355         ++depth;
356     }
357
358   return depth;
359 }
360
361 /* Subroutine of maybe_begin_member_template_processing.
362    Returns true if processing DECL needs us to push template parms.  */
363
364 static bool
365 inline_needs_template_parms (tree decl)
366 {
367   if (! DECL_TEMPLATE_INFO (decl))
368     return false;
369
370   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
371           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
372 }
373
374 /* Subroutine of maybe_begin_member_template_processing.
375    Push the template parms in PARMS, starting from LEVELS steps into the
376    chain, and ending at the beginning, since template parms are listed
377    innermost first.  */
378
379 static void
380 push_inline_template_parms_recursive (tree parmlist, int levels)
381 {
382   tree parms = TREE_VALUE (parmlist);
383   int i;
384
385   if (levels > 1)
386     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
387
388   ++processing_template_decl;
389   current_template_parms
390     = tree_cons (size_int (processing_template_decl),
391                  parms, current_template_parms);
392   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
393
394   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
395                NULL);
396   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
397     {
398       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
399
400       if (parm == error_mark_node)
401         continue;
402
403       gcc_assert (DECL_P (parm));
404
405       switch (TREE_CODE (parm))
406         {
407         case TYPE_DECL:
408         case TEMPLATE_DECL:
409           pushdecl (parm);
410           break;
411
412         case PARM_DECL:
413           {
414             /* Make a CONST_DECL as is done in process_template_parm.
415                It is ugly that we recreate this here; the original
416                version built in process_template_parm is no longer
417                available.  */
418             tree decl = build_decl (DECL_SOURCE_LOCATION (parm),
419                                     CONST_DECL, DECL_NAME (parm),
420                                     TREE_TYPE (parm));
421             DECL_ARTIFICIAL (decl) = 1;
422             TREE_CONSTANT (decl) = 1;
423             TREE_READONLY (decl) = 1;
424             DECL_INITIAL (decl) = DECL_INITIAL (parm);
425             SET_DECL_TEMPLATE_PARM_P (decl);
426             pushdecl (decl);
427           }
428           break;
429
430         default:
431           gcc_unreachable ();
432         }
433     }
434 }
435
436 /* Restore the template parameter context for a member template or
437    a friend template defined in a class definition.  */
438
439 void
440 maybe_begin_member_template_processing (tree decl)
441 {
442   tree parms;
443   int levels = 0;
444
445   if (inline_needs_template_parms (decl))
446     {
447       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
448       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
449
450       if (DECL_TEMPLATE_SPECIALIZATION (decl))
451         {
452           --levels;
453           parms = TREE_CHAIN (parms);
454         }
455
456       push_inline_template_parms_recursive (parms, levels);
457     }
458
459   /* Remember how many levels of template parameters we pushed so that
460      we can pop them later.  */
461   VEC_safe_push (int, heap, inline_parm_levels, levels);
462 }
463
464 /* Undo the effects of maybe_begin_member_template_processing.  */
465
466 void
467 maybe_end_member_template_processing (void)
468 {
469   int i;
470   int last;
471
472   if (VEC_length (int, inline_parm_levels) == 0)
473     return;
474
475   last = VEC_pop (int, inline_parm_levels);
476   for (i = 0; i < last; ++i)
477     {
478       --processing_template_decl;
479       current_template_parms = TREE_CHAIN (current_template_parms);
480       poplevel (0, 0, 0);
481     }
482 }
483
484 /* Return a new template argument vector which contains all of ARGS,
485    but has as its innermost set of arguments the EXTRA_ARGS.  */
486
487 static tree
488 add_to_template_args (tree args, tree extra_args)
489 {
490   tree new_args;
491   int extra_depth;
492   int i;
493   int j;
494
495   extra_depth = TMPL_ARGS_DEPTH (extra_args);
496   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
497
498   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
499     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
500
501   for (j = 1; j <= extra_depth; ++j, ++i)
502     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
503
504   return new_args;
505 }
506
507 /* Like add_to_template_args, but only the outermost ARGS are added to
508    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
509    (EXTRA_ARGS) levels are added.  This function is used to combine
510    the template arguments from a partial instantiation with the
511    template arguments used to attain the full instantiation from the
512    partial instantiation.  */
513
514 static tree
515 add_outermost_template_args (tree args, tree extra_args)
516 {
517   tree new_args;
518
519   /* If there are more levels of EXTRA_ARGS than there are ARGS,
520      something very fishy is going on.  */
521   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
522
523   /* If *all* the new arguments will be the EXTRA_ARGS, just return
524      them.  */
525   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
526     return extra_args;
527
528   /* For the moment, we make ARGS look like it contains fewer levels.  */
529   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
530
531   new_args = add_to_template_args (args, extra_args);
532
533   /* Now, we restore ARGS to its full dimensions.  */
534   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
535
536   return new_args;
537 }
538
539 /* Return the N levels of innermost template arguments from the ARGS.  */
540
541 tree
542 get_innermost_template_args (tree args, int n)
543 {
544   tree new_args;
545   int extra_levels;
546   int i;
547
548   gcc_assert (n >= 0);
549
550   /* If N is 1, just return the innermost set of template arguments.  */
551   if (n == 1)
552     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
553
554   /* If we're not removing anything, just return the arguments we were
555      given.  */
556   extra_levels = TMPL_ARGS_DEPTH (args) - n;
557   gcc_assert (extra_levels >= 0);
558   if (extra_levels == 0)
559     return args;
560
561   /* Make a new set of arguments, not containing the outer arguments.  */
562   new_args = make_tree_vec (n);
563   for (i = 1; i <= n; ++i)
564     SET_TMPL_ARGS_LEVEL (new_args, i,
565                          TMPL_ARGS_LEVEL (args, i + extra_levels));
566
567   return new_args;
568 }
569
570 /* The inverse of get_innermost_template_args: Return all but the innermost
571    EXTRA_LEVELS levels of template arguments from the ARGS.  */
572
573 static tree
574 strip_innermost_template_args (tree args, int extra_levels)
575 {
576   tree new_args;
577   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
578   int i;
579
580   gcc_assert (n >= 0);
581
582   /* If N is 1, just return the outermost set of template arguments.  */
583   if (n == 1)
584     return TMPL_ARGS_LEVEL (args, 1);
585
586   /* If we're not removing anything, just return the arguments we were
587      given.  */
588   gcc_assert (extra_levels >= 0);
589   if (extra_levels == 0)
590     return args;
591
592   /* Make a new set of arguments, not containing the inner arguments.  */
593   new_args = make_tree_vec (n);
594   for (i = 1; i <= n; ++i)
595     SET_TMPL_ARGS_LEVEL (new_args, i,
596                          TMPL_ARGS_LEVEL (args, i));
597
598   return new_args;
599 }
600
601 /* We've got a template header coming up; push to a new level for storing
602    the parms.  */
603
604 void
605 begin_template_parm_list (void)
606 {
607   /* We use a non-tag-transparent scope here, which causes pushtag to
608      put tags in this scope, rather than in the enclosing class or
609      namespace scope.  This is the right thing, since we want
610      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
611      global template class, push_template_decl handles putting the
612      TEMPLATE_DECL into top-level scope.  For a nested template class,
613      e.g.:
614
615        template <class T> struct S1 {
616          template <class T> struct S2 {};
617        };
618
619      pushtag contains special code to call pushdecl_with_scope on the
620      TEMPLATE_DECL for S2.  */
621   begin_scope (sk_template_parms, NULL);
622   ++processing_template_decl;
623   ++processing_template_parmlist;
624   note_template_header (0);
625 }
626
627 /* This routine is called when a specialization is declared.  If it is
628    invalid to declare a specialization here, an error is reported and
629    false is returned, otherwise this routine will return true.  */
630
631 static bool
632 check_specialization_scope (void)
633 {
634   tree scope = current_scope ();
635
636   /* [temp.expl.spec]
637
638      An explicit specialization shall be declared in the namespace of
639      which the template is a member, or, for member templates, in the
640      namespace of which the enclosing class or enclosing class
641      template is a member.  An explicit specialization of a member
642      function, member class or static data member of a class template
643      shall be declared in the namespace of which the class template
644      is a member.  */
645   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
646     {
647       error ("explicit specialization in non-namespace scope %qD", scope);
648       return false;
649     }
650
651   /* [temp.expl.spec]
652
653      In an explicit specialization declaration for a member of a class
654      template or a member template that appears in namespace scope,
655      the member template and some of its enclosing class templates may
656      remain unspecialized, except that the declaration shall not
657      explicitly specialize a class member template if its enclosing
658      class templates are not explicitly specialized as well.  */
659   if (current_template_parms)
660     {
661       error ("enclosing class templates are not explicitly specialized");
662       return false;
663     }
664
665   return true;
666 }
667
668 /* We've just seen template <>.  */
669
670 bool
671 begin_specialization (void)
672 {
673   begin_scope (sk_template_spec, NULL);
674   note_template_header (1);
675   return check_specialization_scope ();
676 }
677
678 /* Called at then end of processing a declaration preceded by
679    template<>.  */
680
681 void
682 end_specialization (void)
683 {
684   finish_scope ();
685   reset_specialization ();
686 }
687
688 /* Any template <>'s that we have seen thus far are not referring to a
689    function specialization.  */
690
691 void
692 reset_specialization (void)
693 {
694   processing_specialization = 0;
695   template_header_count = 0;
696 }
697
698 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
699    it was of the form template <>.  */
700
701 static void
702 note_template_header (int specialization)
703 {
704   processing_specialization = specialization;
705   template_header_count++;
706 }
707
708 /* We're beginning an explicit instantiation.  */
709
710 void
711 begin_explicit_instantiation (void)
712 {
713   gcc_assert (!processing_explicit_instantiation);
714   processing_explicit_instantiation = true;
715 }
716
717
718 void
719 end_explicit_instantiation (void)
720 {
721   gcc_assert (processing_explicit_instantiation);
722   processing_explicit_instantiation = false;
723 }
724
725 /* An explicit specialization or partial specialization TMPL is being
726    declared.  Check that the namespace in which the specialization is
727    occurring is permissible.  Returns false iff it is invalid to
728    specialize TMPL in the current namespace.  */
729
730 static bool
731 check_specialization_namespace (tree tmpl)
732 {
733   tree tpl_ns = decl_namespace_context (tmpl);
734
735   /* [tmpl.expl.spec]
736
737      An explicit specialization shall be declared in the namespace of
738      which the template is a member, or, for member templates, in the
739      namespace of which the enclosing class or enclosing class
740      template is a member.  An explicit specialization of a member
741      function, member class or static data member of a class template
742      shall be declared in the namespace of which the class template is
743      a member.  */
744   if (is_associated_namespace (current_namespace, tpl_ns))
745     /* Same or super-using namespace.  */
746     return true;
747   else
748     {
749       permerror (input_location, "specialization of %qD in different namespace", tmpl);
750       permerror (input_location, "  from definition of %q+#D", tmpl);
751       return false;
752     }
753 }
754
755 /* SPEC is an explicit instantiation.  Check that it is valid to
756    perform this explicit instantiation in the current namespace.  */
757
758 static void
759 check_explicit_instantiation_namespace (tree spec)
760 {
761   tree ns;
762
763   /* DR 275: An explicit instantiation shall appear in an enclosing
764      namespace of its template.  */
765   ns = decl_namespace_context (spec);
766   if (!is_ancestor (current_namespace, ns))
767     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
768                "(which does not enclose namespace %qD)",
769                spec, current_namespace, ns);
770 }
771
772 /* The TYPE is being declared.  If it is a template type, that means it
773    is a partial specialization.  Do appropriate error-checking.  */
774
775 tree
776 maybe_process_partial_specialization (tree type)
777 {
778   tree context;
779
780   if (type == error_mark_node)
781     return error_mark_node;
782
783   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
784     {
785       error ("name of class shadows template template parameter %qD",
786              TYPE_NAME (type));
787       return error_mark_node;
788     }
789
790   context = TYPE_CONTEXT (type);
791
792   if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
793     {
794       /* This is for ordinary explicit specialization and partial
795          specialization of a template class such as:
796
797            template <> class C<int>;
798
799          or:
800
801            template <class T> class C<T*>;
802
803          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
804
805       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
806           && !COMPLETE_TYPE_P (type))
807         {
808           check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
809           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
810           if (processing_template_decl)
811             {
812               if (push_template_decl (TYPE_MAIN_DECL (type))
813                   == error_mark_node)
814                 return error_mark_node;
815             }
816         }
817       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
818         error ("specialization of %qT after instantiation", type);
819     }
820   else if (CLASS_TYPE_P (type)
821            && !CLASSTYPE_USE_TEMPLATE (type)
822            && CLASSTYPE_TEMPLATE_INFO (type)
823            && context && CLASS_TYPE_P (context)
824            && CLASSTYPE_TEMPLATE_INFO (context))
825     {
826       /* This is for an explicit specialization of member class
827          template according to [temp.expl.spec/18]:
828
829            template <> template <class U> class C<int>::D;
830
831          The context `C<int>' must be an implicit instantiation.
832          Otherwise this is just a member class template declared
833          earlier like:
834
835            template <> class C<int> { template <class U> class D; };
836            template <> template <class U> class C<int>::D;
837
838          In the first case, `C<int>::D' is a specialization of `C<T>::D'
839          while in the second case, `C<int>::D' is a primary template
840          and `C<T>::D' may not exist.  */
841
842       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
843           && !COMPLETE_TYPE_P (type))
844         {
845           tree t;
846           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
847
848           if (current_namespace
849               != decl_namespace_context (tmpl))
850             {
851               permerror (input_location, "specializing %q#T in different namespace", type);
852               permerror (input_location, "  from definition of %q+#D", tmpl);
853             }
854
855           /* Check for invalid specialization after instantiation:
856
857                template <> template <> class C<int>::D<int>;
858                template <> template <class U> class C<int>::D;  */
859
860           for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
861                t; t = TREE_CHAIN (t))
862             {
863               tree inst = TREE_VALUE (t);
864               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst))
865                 {
866                   /* We already have a full specialization of this partial
867                      instantiation.  Reassign it to the new member
868                      specialization template.  */
869                   spec_entry elt;
870                   spec_entry **slot;
871
872                   elt.tmpl = most_general_template (tmpl);
873                   elt.args = CLASSTYPE_TI_ARGS (inst);
874                   elt.spec = inst;
875
876                   htab_remove_elt (type_specializations, &elt);
877
878                   elt.tmpl = tmpl;
879                   elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
880
881                   slot = (spec_entry **)
882                     htab_find_slot (type_specializations, &elt, INSERT);
883                   *slot = GGC_NEW (spec_entry);
884                   **slot = elt;
885                 }
886               else if (COMPLETE_TYPE_P (inst) || TYPE_BEING_DEFINED (inst))
887                 /* But if we've had an implicit instantiation, that's a
888                    problem ([temp.expl.spec]/6).  */
889                 error ("specialization %qT after instantiation %qT",
890                        type, inst);
891             }
892
893           /* Mark TYPE as a specialization.  And as a result, we only
894              have one level of template argument for the innermost
895              class template.  */
896           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
897           CLASSTYPE_TI_ARGS (type)
898             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
899         }
900     }
901   else if (processing_specialization)
902     {
903       error ("explicit specialization of non-template %qT", type);
904       return error_mark_node;
905     }
906
907   return type;
908 }
909
910 /* Returns nonzero if we can optimize the retrieval of specializations
911    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
912    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
913
914 static inline bool
915 optimize_specialization_lookup_p (tree tmpl)
916 {
917   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
918           && DECL_CLASS_SCOPE_P (tmpl)
919           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
920              parameter.  */
921           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
922           /* The optimized lookup depends on the fact that the
923              template arguments for the member function template apply
924              purely to the containing class, which is not true if the
925              containing class is an explicit or partial
926              specialization.  */
927           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
928           && !DECL_MEMBER_TEMPLATE_P (tmpl)
929           && !DECL_CONV_FN_P (tmpl)
930           /* It is possible to have a template that is not a member
931              template and is not a member of a template class:
932
933              template <typename T>
934              struct S { friend A::f(); };
935
936              Here, the friend function is a template, but the context does
937              not have template information.  The optimized lookup relies
938              on having ARGS be the template arguments for both the class
939              and the function template.  */
940           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
941 }
942
943 /* Retrieve the specialization (in the sense of [temp.spec] - a
944    specialization is either an instantiation or an explicit
945    specialization) of TMPL for the given template ARGS.  If there is
946    no such specialization, return NULL_TREE.  The ARGS are a vector of
947    arguments, or a vector of vectors of arguments, in the case of
948    templates with more than one level of parameters.
949
950    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
951    then we search for a partial specialization matching ARGS.  This
952    parameter is ignored if TMPL is not a class template.  */
953
954 static tree
955 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
956 {
957   if (args == error_mark_node)
958     return NULL_TREE;
959
960   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
961
962   /* There should be as many levels of arguments as there are
963      levels of parameters.  */
964   gcc_assert (TMPL_ARGS_DEPTH (args)
965               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
966
967   if (optimize_specialization_lookup_p (tmpl))
968     {
969       tree class_template;
970       tree class_specialization;
971       VEC(tree,gc) *methods;
972       tree fns;
973       int idx;
974
975       /* The template arguments actually apply to the containing
976          class.  Find the class specialization with those
977          arguments.  */
978       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
979       class_specialization
980         = retrieve_specialization (class_template, args, 0);
981       if (!class_specialization)
982         return NULL_TREE;
983       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
984          for the specialization.  */
985       idx = class_method_index_for_fn (class_specialization, tmpl);
986       if (idx == -1)
987         return NULL_TREE;
988       /* Iterate through the methods with the indicated name, looking
989          for the one that has an instance of TMPL.  */
990       methods = CLASSTYPE_METHOD_VEC (class_specialization);
991       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
992         {
993           tree fn = OVL_CURRENT (fns);
994           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl
995               /* using-declarations can add base methods to the method vec,
996                  and we don't want those here.  */
997               && DECL_CONTEXT (fn) == class_specialization)
998             return fn;
999         }
1000       return NULL_TREE;
1001     }
1002   else
1003     {
1004       spec_entry *found;
1005       spec_entry elt;
1006       htab_t specializations;
1007
1008       elt.tmpl = tmpl;
1009       elt.args = args;
1010       elt.spec = NULL_TREE;
1011
1012       if (DECL_CLASS_TEMPLATE_P (tmpl))
1013         specializations = type_specializations;
1014       else
1015         specializations = decl_specializations;
1016
1017       if (hash == 0)
1018         hash = hash_specialization (&elt);
1019       found = (spec_entry *) htab_find_with_hash (specializations, &elt, hash);
1020       if (found)
1021         return found->spec;
1022     }
1023
1024   return NULL_TREE;
1025 }
1026
1027 /* Like retrieve_specialization, but for local declarations.  */
1028
1029 static tree
1030 retrieve_local_specialization (tree tmpl)
1031 {
1032   tree spec;
1033
1034   if (local_specializations == NULL)
1035     return NULL_TREE;
1036
1037   spec = (tree) htab_find_with_hash (local_specializations, tmpl,
1038                                      htab_hash_pointer (tmpl));
1039   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
1040 }
1041
1042 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1043
1044 int
1045 is_specialization_of (tree decl, tree tmpl)
1046 {
1047   tree t;
1048
1049   if (TREE_CODE (decl) == FUNCTION_DECL)
1050     {
1051       for (t = decl;
1052            t != NULL_TREE;
1053            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1054         if (t == tmpl)
1055           return 1;
1056     }
1057   else
1058     {
1059       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1060
1061       for (t = TREE_TYPE (decl);
1062            t != NULL_TREE;
1063            t = CLASSTYPE_USE_TEMPLATE (t)
1064              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1065         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1066           return 1;
1067     }
1068
1069   return 0;
1070 }
1071
1072 /* Returns nonzero iff DECL is a specialization of friend declaration
1073    FRIEND_DECL according to [temp.friend].  */
1074
1075 bool
1076 is_specialization_of_friend (tree decl, tree friend_decl)
1077 {
1078   bool need_template = true;
1079   int template_depth;
1080
1081   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1082               || TREE_CODE (decl) == TYPE_DECL);
1083
1084   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1085      of a template class, we want to check if DECL is a specialization
1086      if this.  */
1087   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1088       && DECL_TEMPLATE_INFO (friend_decl)
1089       && !DECL_USE_TEMPLATE (friend_decl))
1090     {
1091       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1092       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1093       need_template = false;
1094     }
1095   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1096            && !PRIMARY_TEMPLATE_P (friend_decl))
1097     need_template = false;
1098
1099   /* There is nothing to do if this is not a template friend.  */
1100   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1101     return false;
1102
1103   if (is_specialization_of (decl, friend_decl))
1104     return true;
1105
1106   /* [temp.friend/6]
1107      A member of a class template may be declared to be a friend of a
1108      non-template class.  In this case, the corresponding member of
1109      every specialization of the class template is a friend of the
1110      class granting friendship.
1111
1112      For example, given a template friend declaration
1113
1114        template <class T> friend void A<T>::f();
1115
1116      the member function below is considered a friend
1117
1118        template <> struct A<int> {
1119          void f();
1120        };
1121
1122      For this type of template friend, TEMPLATE_DEPTH below will be
1123      nonzero.  To determine if DECL is a friend of FRIEND, we first
1124      check if the enclosing class is a specialization of another.  */
1125
1126   template_depth = template_class_depth (DECL_CONTEXT (friend_decl));
1127   if (template_depth
1128       && DECL_CLASS_SCOPE_P (decl)
1129       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1130                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1131     {
1132       /* Next, we check the members themselves.  In order to handle
1133          a few tricky cases, such as when FRIEND_DECL's are
1134
1135            template <class T> friend void A<T>::g(T t);
1136            template <class T> template <T t> friend void A<T>::h();
1137
1138          and DECL's are
1139
1140            void A<int>::g(int);
1141            template <int> void A<int>::h();
1142
1143          we need to figure out ARGS, the template arguments from
1144          the context of DECL.  This is required for template substitution
1145          of `T' in the function parameter of `g' and template parameter
1146          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1147
1148       tree context = DECL_CONTEXT (decl);
1149       tree args = NULL_TREE;
1150       int current_depth = 0;
1151
1152       while (current_depth < template_depth)
1153         {
1154           if (CLASSTYPE_TEMPLATE_INFO (context))
1155             {
1156               if (current_depth == 0)
1157                 args = TYPE_TI_ARGS (context);
1158               else
1159                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1160               current_depth++;
1161             }
1162           context = TYPE_CONTEXT (context);
1163         }
1164
1165       if (TREE_CODE (decl) == FUNCTION_DECL)
1166         {
1167           bool is_template;
1168           tree friend_type;
1169           tree decl_type;
1170           tree friend_args_type;
1171           tree decl_args_type;
1172
1173           /* Make sure that both DECL and FRIEND_DECL are templates or
1174              non-templates.  */
1175           is_template = DECL_TEMPLATE_INFO (decl)
1176                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1177           if (need_template ^ is_template)
1178             return false;
1179           else if (is_template)
1180             {
1181               /* If both are templates, check template parameter list.  */
1182               tree friend_parms
1183                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1184                                          args, tf_none);
1185               if (!comp_template_parms
1186                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1187                       friend_parms))
1188                 return false;
1189
1190               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1191             }
1192           else
1193             decl_type = TREE_TYPE (decl);
1194
1195           friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1196                                               tf_none, NULL_TREE);
1197           if (friend_type == error_mark_node)
1198             return false;
1199
1200           /* Check if return types match.  */
1201           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1202             return false;
1203
1204           /* Check if function parameter types match, ignoring the
1205              `this' parameter.  */
1206           friend_args_type = TYPE_ARG_TYPES (friend_type);
1207           decl_args_type = TYPE_ARG_TYPES (decl_type);
1208           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1209             friend_args_type = TREE_CHAIN (friend_args_type);
1210           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1211             decl_args_type = TREE_CHAIN (decl_args_type);
1212
1213           return compparms (decl_args_type, friend_args_type);
1214         }
1215       else
1216         {
1217           /* DECL is a TYPE_DECL */
1218           bool is_template;
1219           tree decl_type = TREE_TYPE (decl);
1220
1221           /* Make sure that both DECL and FRIEND_DECL are templates or
1222              non-templates.  */
1223           is_template
1224             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1225               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1226
1227           if (need_template ^ is_template)
1228             return false;
1229           else if (is_template)
1230             {
1231               tree friend_parms;
1232               /* If both are templates, check the name of the two
1233                  TEMPLATE_DECL's first because is_friend didn't.  */
1234               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1235                   != DECL_NAME (friend_decl))
1236                 return false;
1237
1238               /* Now check template parameter list.  */
1239               friend_parms
1240                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1241                                          args, tf_none);
1242               return comp_template_parms
1243                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1244                  friend_parms);
1245             }
1246           else
1247             return (DECL_NAME (decl)
1248                     == DECL_NAME (friend_decl));
1249         }
1250     }
1251   return false;
1252 }
1253
1254 /* Register the specialization SPEC as a specialization of TMPL with
1255    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1256    is actually just a friend declaration.  Returns SPEC, or an
1257    equivalent prior declaration, if available.  */
1258
1259 static tree
1260 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1261                          hashval_t hash)
1262 {
1263   tree fn;
1264   spec_entry **slot = NULL;
1265   spec_entry elt;
1266
1267   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec));
1268
1269   if (TREE_CODE (spec) == FUNCTION_DECL
1270       && uses_template_parms (DECL_TI_ARGS (spec)))
1271     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1272        register it; we want the corresponding TEMPLATE_DECL instead.
1273        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1274        the more obvious `uses_template_parms (spec)' to avoid problems
1275        with default function arguments.  In particular, given
1276        something like this:
1277
1278           template <class T> void f(T t1, T t = T())
1279
1280        the default argument expression is not substituted for in an
1281        instantiation unless and until it is actually needed.  */
1282     return spec;
1283
1284   if (optimize_specialization_lookup_p (tmpl))
1285     /* We don't put these specializations in the hash table, but we might
1286        want to give an error about a mismatch.  */
1287     fn = retrieve_specialization (tmpl, args, 0);
1288   else
1289     {
1290       elt.tmpl = tmpl;
1291       elt.args = args;
1292       elt.spec = spec;
1293
1294       if (hash == 0)
1295         hash = hash_specialization (&elt);
1296
1297       slot = (spec_entry **)
1298         htab_find_slot_with_hash (decl_specializations, &elt, hash, INSERT);
1299       if (*slot)
1300         fn = (*slot)->spec;
1301       else
1302         fn = NULL_TREE;
1303     }
1304
1305   /* We can sometimes try to re-register a specialization that we've
1306      already got.  In particular, regenerate_decl_from_template calls
1307      duplicate_decls which will update the specialization list.  But,
1308      we'll still get called again here anyhow.  It's more convenient
1309      to simply allow this than to try to prevent it.  */
1310   if (fn == spec)
1311     return spec;
1312   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1313     {
1314       if (DECL_TEMPLATE_INSTANTIATION (fn))
1315         {
1316           if (DECL_ODR_USED (fn)
1317               || DECL_EXPLICIT_INSTANTIATION (fn))
1318             {
1319               error ("specialization of %qD after instantiation",
1320                      fn);
1321               return error_mark_node;
1322             }
1323           else
1324             {
1325               tree clone;
1326               /* This situation should occur only if the first
1327                  specialization is an implicit instantiation, the
1328                  second is an explicit specialization, and the
1329                  implicit instantiation has not yet been used.  That
1330                  situation can occur if we have implicitly
1331                  instantiated a member function and then specialized
1332                  it later.
1333
1334                  We can also wind up here if a friend declaration that
1335                  looked like an instantiation turns out to be a
1336                  specialization:
1337
1338                    template <class T> void foo(T);
1339                    class S { friend void foo<>(int) };
1340                    template <> void foo(int);
1341
1342                  We transform the existing DECL in place so that any
1343                  pointers to it become pointers to the updated
1344                  declaration.
1345
1346                  If there was a definition for the template, but not
1347                  for the specialization, we want this to look as if
1348                  there were no definition, and vice versa.  */
1349               DECL_INITIAL (fn) = NULL_TREE;
1350               duplicate_decls (spec, fn, is_friend);
1351               /* The call to duplicate_decls will have applied
1352                  [temp.expl.spec]:
1353
1354                    An explicit specialization of a function template
1355                    is inline only if it is explicitly declared to be,
1356                    and independently of whether its function template
1357                    is.
1358
1359                 to the primary function; now copy the inline bits to
1360                 the various clones.  */
1361               FOR_EACH_CLONE (clone, fn)
1362                 {
1363                   DECL_DECLARED_INLINE_P (clone)
1364                     = DECL_DECLARED_INLINE_P (fn);
1365                   DECL_SOURCE_LOCATION (clone)
1366                     = DECL_SOURCE_LOCATION (fn);
1367                 }
1368               check_specialization_namespace (fn);
1369
1370               return fn;
1371             }
1372         }
1373       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1374         {
1375           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1376             /* Dup decl failed, but this is a new definition. Set the
1377                line number so any errors match this new
1378                definition.  */
1379             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1380
1381           return fn;
1382         }
1383     }
1384   else if (fn)
1385     return duplicate_decls (spec, fn, is_friend);
1386
1387   /* A specialization must be declared in the same namespace as the
1388      template it is specializing.  */
1389   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1390       && !check_specialization_namespace (tmpl))
1391     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1392
1393   if (!optimize_specialization_lookup_p (tmpl))
1394     {
1395       gcc_assert (tmpl && args && spec);
1396       *slot = GGC_NEW (spec_entry);
1397       **slot = elt;
1398       if (TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1399           && PRIMARY_TEMPLATE_P (tmpl)
1400           && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1401         /* TMPL is a forward declaration of a template function; keep a list
1402            of all specializations in case we need to reassign them to a friend
1403            template later in tsubst_friend_function.  */
1404         DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1405           = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1406     }
1407
1408   return spec;
1409 }
1410
1411 /* Returns true iff two spec_entry nodes are equivalent.  Only compares the
1412    TMPL and ARGS members, ignores SPEC.  */
1413
1414 static int
1415 eq_specializations (const void *p1, const void *p2)
1416 {
1417   const spec_entry *e1 = (const spec_entry *)p1;
1418   const spec_entry *e2 = (const spec_entry *)p2;
1419
1420   return (e1->tmpl == e2->tmpl
1421           && comp_template_args (e1->args, e2->args));
1422 }
1423
1424 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1425
1426 static hashval_t
1427 hash_tmpl_and_args (tree tmpl, tree args)
1428 {
1429   hashval_t val = DECL_UID (tmpl);
1430   return iterative_hash_template_arg (args, val);
1431 }
1432
1433 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1434    ignoring SPEC.  */
1435
1436 static hashval_t
1437 hash_specialization (const void *p)
1438 {
1439   const spec_entry *e = (const spec_entry *)p;
1440   return hash_tmpl_and_args (e->tmpl, e->args);
1441 }
1442
1443 /* Recursively calculate a hash value for a template argument ARG, for use
1444    in the hash tables of template specializations.  */
1445
1446 static hashval_t
1447 iterative_hash_template_arg (tree arg, hashval_t val)
1448 {
1449   unsigned HOST_WIDE_INT i;
1450   enum tree_code code;
1451   char tclass;
1452
1453   if (arg == NULL_TREE)
1454     return iterative_hash_object (arg, val);
1455
1456   if (!TYPE_P (arg))
1457     STRIP_NOPS (arg);
1458
1459   code = TREE_CODE (arg);
1460   tclass = TREE_CODE_CLASS (code);
1461
1462   val = iterative_hash_object (code, val);
1463
1464   switch (code)
1465     {
1466     case ERROR_MARK:
1467       return val;
1468
1469     case IDENTIFIER_NODE:
1470       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1471
1472     case TREE_VEC:
1473       {
1474         int i, len = TREE_VEC_LENGTH (arg);
1475         for (i = 0; i < len; ++i)
1476           val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1477         return val;
1478       }
1479
1480     case TYPE_PACK_EXPANSION:
1481     case EXPR_PACK_EXPANSION:
1482       return iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1483
1484     case ARGUMENT_PACK_SELECT:
1485       /* We can get one of these when re-hashing a previous entry in the middle
1486          of substituting into a pack expansion.  Just look through it...  */
1487       arg = ARGUMENT_PACK_SELECT_FROM_PACK (arg);
1488       /* ...and fall through.  */
1489     case TYPE_ARGUMENT_PACK:
1490     case NONTYPE_ARGUMENT_PACK:
1491       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1492
1493     case TREE_LIST:
1494       for (; arg; arg = TREE_CHAIN (arg))
1495         val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1496       return val;
1497
1498     case OVERLOAD:
1499       for (; arg; arg = OVL_CHAIN (arg))
1500         val = iterative_hash_template_arg (OVL_FUNCTION (arg), val);
1501       return val;
1502
1503     case CONSTRUCTOR:
1504       {
1505         tree field, value;
1506         FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1507           {
1508             val = iterative_hash_template_arg (field, val);
1509             val = iterative_hash_template_arg (value, val);
1510           }
1511         return val;
1512       }
1513
1514     case PARM_DECL:
1515       if (!DECL_ARTIFICIAL (arg))
1516         val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1517       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1518
1519     case TARGET_EXPR:
1520       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1521
1522     case PTRMEM_CST:
1523       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1524       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1525
1526     case TEMPLATE_PARM_INDEX:
1527       val = iterative_hash_template_arg
1528         (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1529       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1530       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1531
1532     case TRAIT_EXPR:
1533       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1534       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1535       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1536
1537     case BASELINK:
1538       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1539                                          val);
1540       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1541                                           val);
1542
1543     case MODOP_EXPR:
1544       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1545       code = TREE_CODE (TREE_OPERAND (arg, 1));
1546       val = iterative_hash_object (code, val);
1547       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1548
1549     default:
1550       switch (tclass)
1551         {
1552         case tcc_type:
1553           if (TYPE_CANONICAL (arg))
1554             return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1555                                           val);
1556           else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1557             return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1558           /* Otherwise just compare the types during lookup.  */
1559           return val;
1560
1561         case tcc_declaration:
1562         case tcc_constant:
1563           return iterative_hash_expr (arg, val);
1564
1565         default:
1566           gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1567           {
1568             unsigned n = TREE_OPERAND_LENGTH (arg);
1569             for (i = 0; i < n; ++i)
1570               val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1571             return val;
1572           }
1573         }
1574     }
1575   gcc_unreachable ();
1576   return 0;
1577 }
1578
1579 /* Unregister the specialization SPEC as a specialization of TMPL.
1580    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1581    if the SPEC was listed as a specialization of TMPL.
1582
1583    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1584
1585 bool
1586 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1587 {
1588   spec_entry **slot;
1589   spec_entry elt;
1590
1591   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1592   elt.args = TI_ARGS (tinfo);
1593   elt.spec = NULL_TREE;
1594
1595   slot = (spec_entry **) htab_find_slot (decl_specializations, &elt, INSERT);
1596   if (*slot)
1597     {
1598       gcc_assert ((*slot)->spec == spec || (*slot)->spec == new_spec);
1599       gcc_assert (new_spec != NULL_TREE);
1600       (*slot)->spec = new_spec;
1601       return 1;
1602     }
1603
1604   return 0;
1605 }
1606
1607 /* Compare an entry in the local specializations hash table P1 (which
1608    is really a pointer to a TREE_LIST) with P2 (which is really a
1609    DECL).  */
1610
1611 static int
1612 eq_local_specializations (const void *p1, const void *p2)
1613 {
1614   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1615 }
1616
1617 /* Hash P1, an entry in the local specializations table.  */
1618
1619 static hashval_t
1620 hash_local_specialization (const void* p1)
1621 {
1622   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1623 }
1624
1625 /* Like register_specialization, but for local declarations.  We are
1626    registering SPEC, an instantiation of TMPL.  */
1627
1628 static void
1629 register_local_specialization (tree spec, tree tmpl)
1630 {
1631   void **slot;
1632
1633   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1634                                    htab_hash_pointer (tmpl), INSERT);
1635   *slot = build_tree_list (spec, tmpl);
1636 }
1637
1638 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1639    specialized class.  */
1640
1641 bool
1642 explicit_class_specialization_p (tree type)
1643 {
1644   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1645     return false;
1646   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1647 }
1648
1649 /* Print the list of candidate FNS in an error message.  */
1650
1651 void
1652 print_candidates (tree fns)
1653 {
1654   tree fn;
1655   tree f;
1656
1657   const char *str = "candidates are:";
1658
1659   if (is_overloaded_fn (fns))
1660     {
1661       for (f = fns; f; f = OVL_NEXT (f))
1662         {
1663           error ("%s %+#D", str, OVL_CURRENT (f));
1664           str = "               ";
1665         }
1666     }
1667   else for (fn = fns; fn != NULL_TREE; fn = TREE_CHAIN (fn))
1668     {
1669       for (f = TREE_VALUE (fn); f; f = OVL_NEXT (f))
1670         error ("%s %+#D", str, OVL_CURRENT (f));
1671       str = "               ";
1672     }
1673 }
1674
1675 /* Returns the template (one of the functions given by TEMPLATE_ID)
1676    which can be specialized to match the indicated DECL with the
1677    explicit template args given in TEMPLATE_ID.  The DECL may be
1678    NULL_TREE if none is available.  In that case, the functions in
1679    TEMPLATE_ID are non-members.
1680
1681    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1682    specialization of a member template.
1683
1684    The TEMPLATE_COUNT is the number of references to qualifying
1685    template classes that appeared in the name of the function. See
1686    check_explicit_specialization for a more accurate description.
1687
1688    TSK indicates what kind of template declaration (if any) is being
1689    declared.  TSK_TEMPLATE indicates that the declaration given by
1690    DECL, though a FUNCTION_DECL, has template parameters, and is
1691    therefore a template function.
1692
1693    The template args (those explicitly specified and those deduced)
1694    are output in a newly created vector *TARGS_OUT.
1695
1696    If it is impossible to determine the result, an error message is
1697    issued.  The error_mark_node is returned to indicate failure.  */
1698
1699 static tree
1700 determine_specialization (tree template_id,
1701                           tree decl,
1702                           tree* targs_out,
1703                           int need_member_template,
1704                           int template_count,
1705                           tmpl_spec_kind tsk)
1706 {
1707   tree fns;
1708   tree targs;
1709   tree explicit_targs;
1710   tree candidates = NULL_TREE;
1711   /* A TREE_LIST of templates of which DECL may be a specialization.
1712      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1713      corresponding TREE_PURPOSE is the set of template arguments that,
1714      when used to instantiate the template, would produce a function
1715      with the signature of DECL.  */
1716   tree templates = NULL_TREE;
1717   int header_count;
1718   struct cp_binding_level *b;
1719
1720   *targs_out = NULL_TREE;
1721
1722   if (template_id == error_mark_node || decl == error_mark_node)
1723     return error_mark_node;
1724
1725   fns = TREE_OPERAND (template_id, 0);
1726   explicit_targs = TREE_OPERAND (template_id, 1);
1727
1728   if (fns == error_mark_node)
1729     return error_mark_node;
1730
1731   /* Check for baselinks.  */
1732   if (BASELINK_P (fns))
1733     fns = BASELINK_FUNCTIONS (fns);
1734
1735   if (!is_overloaded_fn (fns))
1736     {
1737       error ("%qD is not a function template", fns);
1738       return error_mark_node;
1739     }
1740
1741   /* Count the number of template headers specified for this
1742      specialization.  */
1743   header_count = 0;
1744   for (b = current_binding_level;
1745        b->kind == sk_template_parms;
1746        b = b->level_chain)
1747     ++header_count;
1748
1749   for (; fns; fns = OVL_NEXT (fns))
1750     {
1751       tree fn = OVL_CURRENT (fns);
1752
1753       if (TREE_CODE (fn) == TEMPLATE_DECL)
1754         {
1755           tree decl_arg_types;
1756           tree fn_arg_types;
1757
1758           /* In case of explicit specialization, we need to check if
1759              the number of template headers appearing in the specialization
1760              is correct. This is usually done in check_explicit_specialization,
1761              but the check done there cannot be exhaustive when specializing
1762              member functions. Consider the following code:
1763
1764              template <> void A<int>::f(int);
1765              template <> template <> void A<int>::f(int);
1766
1767              Assuming that A<int> is not itself an explicit specialization
1768              already, the first line specializes "f" which is a non-template
1769              member function, whilst the second line specializes "f" which
1770              is a template member function. So both lines are syntactically
1771              correct, and check_explicit_specialization does not reject
1772              them.
1773
1774              Here, we can do better, as we are matching the specialization
1775              against the declarations. We count the number of template
1776              headers, and we check if they match TEMPLATE_COUNT + 1
1777              (TEMPLATE_COUNT is the number of qualifying template classes,
1778              plus there must be another header for the member template
1779              itself).
1780
1781              Notice that if header_count is zero, this is not a
1782              specialization but rather a template instantiation, so there
1783              is no check we can perform here.  */
1784           if (header_count && header_count != template_count + 1)
1785             continue;
1786
1787           /* Check that the number of template arguments at the
1788              innermost level for DECL is the same as for FN.  */
1789           if (current_binding_level->kind == sk_template_parms
1790               && !current_binding_level->explicit_spec_p
1791               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1792                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1793                                       (current_template_parms))))
1794             continue;
1795
1796           /* DECL might be a specialization of FN.  */
1797           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1798           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1799
1800           /* For a non-static member function, we need to make sure
1801              that the const qualification is the same.  Since
1802              get_bindings does not try to merge the "this" parameter,
1803              we must do the comparison explicitly.  */
1804           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1805               && !same_type_p (TREE_VALUE (fn_arg_types),
1806                                TREE_VALUE (decl_arg_types)))
1807             continue;
1808
1809           /* Skip the "this" parameter and, for constructors of
1810              classes with virtual bases, the VTT parameter.  A
1811              full specialization of a constructor will have a VTT
1812              parameter, but a template never will.  */ 
1813           decl_arg_types 
1814             = skip_artificial_parms_for (decl, decl_arg_types);
1815           fn_arg_types 
1816             = skip_artificial_parms_for (fn, fn_arg_types);
1817
1818           /* Check that the number of function parameters matches.
1819              For example,
1820                template <class T> void f(int i = 0);
1821                template <> void f<int>();
1822              The specialization f<int> is invalid but is not caught
1823              by get_bindings below.  */
1824           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1825             continue;
1826
1827           /* Function templates cannot be specializations; there are
1828              no partial specializations of functions.  Therefore, if
1829              the type of DECL does not match FN, there is no
1830              match.  */
1831           if (tsk == tsk_template)
1832             {
1833               if (compparms (fn_arg_types, decl_arg_types))
1834                 candidates = tree_cons (NULL_TREE, fn, candidates);
1835               continue;
1836             }
1837
1838           /* See whether this function might be a specialization of this
1839              template.  */
1840           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1841
1842           if (!targs)
1843             /* We cannot deduce template arguments that when used to
1844                specialize TMPL will produce DECL.  */
1845             continue;
1846
1847           /* Save this template, and the arguments deduced.  */
1848           templates = tree_cons (targs, fn, templates);
1849         }
1850       else if (need_member_template)
1851         /* FN is an ordinary member function, and we need a
1852            specialization of a member template.  */
1853         ;
1854       else if (TREE_CODE (fn) != FUNCTION_DECL)
1855         /* We can get IDENTIFIER_NODEs here in certain erroneous
1856            cases.  */
1857         ;
1858       else if (!DECL_FUNCTION_MEMBER_P (fn))
1859         /* This is just an ordinary non-member function.  Nothing can
1860            be a specialization of that.  */
1861         ;
1862       else if (DECL_ARTIFICIAL (fn))
1863         /* Cannot specialize functions that are created implicitly.  */
1864         ;
1865       else
1866         {
1867           tree decl_arg_types;
1868
1869           /* This is an ordinary member function.  However, since
1870              we're here, we can assume it's enclosing class is a
1871              template class.  For example,
1872
1873                template <typename T> struct S { void f(); };
1874                template <> void S<int>::f() {}
1875
1876              Here, S<int>::f is a non-template, but S<int> is a
1877              template class.  If FN has the same type as DECL, we
1878              might be in business.  */
1879
1880           if (!DECL_TEMPLATE_INFO (fn))
1881             /* Its enclosing class is an explicit specialization
1882                of a template class.  This is not a candidate.  */
1883             continue;
1884
1885           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1886                             TREE_TYPE (TREE_TYPE (fn))))
1887             /* The return types differ.  */
1888             continue;
1889
1890           /* Adjust the type of DECL in case FN is a static member.  */
1891           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1892           if (DECL_STATIC_FUNCTION_P (fn)
1893               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1894             decl_arg_types = TREE_CHAIN (decl_arg_types);
1895
1896           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1897                          decl_arg_types))
1898             /* They match!  */
1899             candidates = tree_cons (NULL_TREE, fn, candidates);
1900         }
1901     }
1902
1903   if (templates && TREE_CHAIN (templates))
1904     {
1905       /* We have:
1906
1907            [temp.expl.spec]
1908
1909            It is possible for a specialization with a given function
1910            signature to be instantiated from more than one function
1911            template.  In such cases, explicit specification of the
1912            template arguments must be used to uniquely identify the
1913            function template specialization being specialized.
1914
1915          Note that here, there's no suggestion that we're supposed to
1916          determine which of the candidate templates is most
1917          specialized.  However, we, also have:
1918
1919            [temp.func.order]
1920
1921            Partial ordering of overloaded function template
1922            declarations is used in the following contexts to select
1923            the function template to which a function template
1924            specialization refers:
1925
1926            -- when an explicit specialization refers to a function
1927               template.
1928
1929          So, we do use the partial ordering rules, at least for now.
1930          This extension can only serve to make invalid programs valid,
1931          so it's safe.  And, there is strong anecdotal evidence that
1932          the committee intended the partial ordering rules to apply;
1933          the EDG front end has that behavior, and John Spicer claims
1934          that the committee simply forgot to delete the wording in
1935          [temp.expl.spec].  */
1936       tree tmpl = most_specialized_instantiation (templates);
1937       if (tmpl != error_mark_node)
1938         {
1939           templates = tmpl;
1940           TREE_CHAIN (templates) = NULL_TREE;
1941         }
1942     }
1943
1944   if (templates == NULL_TREE && candidates == NULL_TREE)
1945     {
1946       error ("template-id %qD for %q+D does not match any template "
1947              "declaration", template_id, decl);
1948       if (header_count && header_count != template_count + 1)
1949         inform (input_location, "saw %d %<template<>%>, need %d for "
1950                 "specializing a member function template",
1951                 header_count, template_count + 1);
1952       return error_mark_node;
1953     }
1954   else if ((templates && TREE_CHAIN (templates))
1955            || (candidates && TREE_CHAIN (candidates))
1956            || (templates && candidates))
1957     {
1958       error ("ambiguous template specialization %qD for %q+D",
1959              template_id, decl);
1960       candidates = chainon (candidates, templates);
1961       print_candidates (candidates);
1962       return error_mark_node;
1963     }
1964
1965   /* We have one, and exactly one, match.  */
1966   if (candidates)
1967     {
1968       tree fn = TREE_VALUE (candidates);
1969       *targs_out = copy_node (DECL_TI_ARGS (fn));
1970       /* DECL is a re-declaration or partial instantiation of a template
1971          function.  */
1972       if (TREE_CODE (fn) == TEMPLATE_DECL)
1973         return fn;
1974       /* It was a specialization of an ordinary member function in a
1975          template class.  */
1976       return DECL_TI_TEMPLATE (fn);
1977     }
1978
1979   /* It was a specialization of a template.  */
1980   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
1981   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
1982     {
1983       *targs_out = copy_node (targs);
1984       SET_TMPL_ARGS_LEVEL (*targs_out,
1985                            TMPL_ARGS_DEPTH (*targs_out),
1986                            TREE_PURPOSE (templates));
1987     }
1988   else
1989     *targs_out = TREE_PURPOSE (templates);
1990   return TREE_VALUE (templates);
1991 }
1992
1993 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
1994    but with the default argument values filled in from those in the
1995    TMPL_TYPES.  */
1996
1997 static tree
1998 copy_default_args_to_explicit_spec_1 (tree spec_types,
1999                                       tree tmpl_types)
2000 {
2001   tree new_spec_types;
2002
2003   if (!spec_types)
2004     return NULL_TREE;
2005
2006   if (spec_types == void_list_node)
2007     return void_list_node;
2008
2009   /* Substitute into the rest of the list.  */
2010   new_spec_types =
2011     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2012                                           TREE_CHAIN (tmpl_types));
2013
2014   /* Add the default argument for this parameter.  */
2015   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2016                          TREE_VALUE (spec_types),
2017                          new_spec_types);
2018 }
2019
2020 /* DECL is an explicit specialization.  Replicate default arguments
2021    from the template it specializes.  (That way, code like:
2022
2023      template <class T> void f(T = 3);
2024      template <> void f(double);
2025      void g () { f (); }
2026
2027    works, as required.)  An alternative approach would be to look up
2028    the correct default arguments at the call-site, but this approach
2029    is consistent with how implicit instantiations are handled.  */
2030
2031 static void
2032 copy_default_args_to_explicit_spec (tree decl)
2033 {
2034   tree tmpl;
2035   tree spec_types;
2036   tree tmpl_types;
2037   tree new_spec_types;
2038   tree old_type;
2039   tree new_type;
2040   tree t;
2041   tree object_type = NULL_TREE;
2042   tree in_charge = NULL_TREE;
2043   tree vtt = NULL_TREE;
2044
2045   /* See if there's anything we need to do.  */
2046   tmpl = DECL_TI_TEMPLATE (decl);
2047   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2048   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2049     if (TREE_PURPOSE (t))
2050       break;
2051   if (!t)
2052     return;
2053
2054   old_type = TREE_TYPE (decl);
2055   spec_types = TYPE_ARG_TYPES (old_type);
2056
2057   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2058     {
2059       /* Remove the this pointer, but remember the object's type for
2060          CV quals.  */
2061       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2062       spec_types = TREE_CHAIN (spec_types);
2063       tmpl_types = TREE_CHAIN (tmpl_types);
2064
2065       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2066         {
2067           /* DECL may contain more parameters than TMPL due to the extra
2068              in-charge parameter in constructors and destructors.  */
2069           in_charge = spec_types;
2070           spec_types = TREE_CHAIN (spec_types);
2071         }
2072       if (DECL_HAS_VTT_PARM_P (decl))
2073         {
2074           vtt = spec_types;
2075           spec_types = TREE_CHAIN (spec_types);
2076         }
2077     }
2078
2079   /* Compute the merged default arguments.  */
2080   new_spec_types =
2081     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2082
2083   /* Compute the new FUNCTION_TYPE.  */
2084   if (object_type)
2085     {
2086       if (vtt)
2087         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2088                                          TREE_VALUE (vtt),
2089                                          new_spec_types);
2090
2091       if (in_charge)
2092         /* Put the in-charge parameter back.  */
2093         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2094                                          TREE_VALUE (in_charge),
2095                                          new_spec_types);
2096
2097       new_type = build_method_type_directly (object_type,
2098                                              TREE_TYPE (old_type),
2099                                              new_spec_types);
2100     }
2101   else
2102     new_type = build_function_type (TREE_TYPE (old_type),
2103                                     new_spec_types);
2104   new_type = cp_build_type_attribute_variant (new_type,
2105                                               TYPE_ATTRIBUTES (old_type));
2106   new_type = build_exception_variant (new_type,
2107                                       TYPE_RAISES_EXCEPTIONS (old_type));
2108   TREE_TYPE (decl) = new_type;
2109 }
2110
2111 /* Check to see if the function just declared, as indicated in
2112    DECLARATOR, and in DECL, is a specialization of a function
2113    template.  We may also discover that the declaration is an explicit
2114    instantiation at this point.
2115
2116    Returns DECL, or an equivalent declaration that should be used
2117    instead if all goes well.  Issues an error message if something is
2118    amiss.  Returns error_mark_node if the error is not easily
2119    recoverable.
2120
2121    FLAGS is a bitmask consisting of the following flags:
2122
2123    2: The function has a definition.
2124    4: The function is a friend.
2125
2126    The TEMPLATE_COUNT is the number of references to qualifying
2127    template classes that appeared in the name of the function.  For
2128    example, in
2129
2130      template <class T> struct S { void f(); };
2131      void S<int>::f();
2132
2133    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2134    classes are not counted in the TEMPLATE_COUNT, so that in
2135
2136      template <class T> struct S {};
2137      template <> struct S<int> { void f(); }
2138      template <> void S<int>::f();
2139
2140    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2141    invalid; there should be no template <>.)
2142
2143    If the function is a specialization, it is marked as such via
2144    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2145    is set up correctly, and it is added to the list of specializations
2146    for that template.  */
2147
2148 tree
2149 check_explicit_specialization (tree declarator,
2150                                tree decl,
2151                                int template_count,
2152                                int flags)
2153 {
2154   int have_def = flags & 2;
2155   int is_friend = flags & 4;
2156   int specialization = 0;
2157   int explicit_instantiation = 0;
2158   int member_specialization = 0;
2159   tree ctype = DECL_CLASS_CONTEXT (decl);
2160   tree dname = DECL_NAME (decl);
2161   tmpl_spec_kind tsk;
2162
2163   if (is_friend)
2164     {
2165       if (!processing_specialization)
2166         tsk = tsk_none;
2167       else
2168         tsk = tsk_excessive_parms;
2169     }
2170   else
2171     tsk = current_tmpl_spec_kind (template_count);
2172
2173   switch (tsk)
2174     {
2175     case tsk_none:
2176       if (processing_specialization)
2177         {
2178           specialization = 1;
2179           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2180         }
2181       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2182         {
2183           if (is_friend)
2184             /* This could be something like:
2185
2186                template <class T> void f(T);
2187                class S { friend void f<>(int); }  */
2188             specialization = 1;
2189           else
2190             {
2191               /* This case handles bogus declarations like template <>
2192                  template <class T> void f<int>(); */
2193
2194               error ("template-id %qD in declaration of primary template",
2195                      declarator);
2196               return decl;
2197             }
2198         }
2199       break;
2200
2201     case tsk_invalid_member_spec:
2202       /* The error has already been reported in
2203          check_specialization_scope.  */
2204       return error_mark_node;
2205
2206     case tsk_invalid_expl_inst:
2207       error ("template parameter list used in explicit instantiation");
2208
2209       /* Fall through.  */
2210
2211     case tsk_expl_inst:
2212       if (have_def)
2213         error ("definition provided for explicit instantiation");
2214
2215       explicit_instantiation = 1;
2216       break;
2217
2218     case tsk_excessive_parms:
2219     case tsk_insufficient_parms:
2220       if (tsk == tsk_excessive_parms)
2221         error ("too many template parameter lists in declaration of %qD",
2222                decl);
2223       else if (template_header_count)
2224         error("too few template parameter lists in declaration of %qD", decl);
2225       else
2226         error("explicit specialization of %qD must be introduced by "
2227               "%<template <>%>", decl);
2228
2229       /* Fall through.  */
2230     case tsk_expl_spec:
2231       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2232       if (ctype)
2233         member_specialization = 1;
2234       else
2235         specialization = 1;
2236       break;
2237
2238     case tsk_template:
2239       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2240         {
2241           /* This case handles bogus declarations like template <>
2242              template <class T> void f<int>(); */
2243
2244           if (uses_template_parms (declarator))
2245             error ("function template partial specialization %qD "
2246                    "is not allowed", declarator);
2247           else
2248             error ("template-id %qD in declaration of primary template",
2249                    declarator);
2250           return decl;
2251         }
2252
2253       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2254         /* This is a specialization of a member template, without
2255            specialization the containing class.  Something like:
2256
2257              template <class T> struct S {
2258                template <class U> void f (U);
2259              };
2260              template <> template <class U> void S<int>::f(U) {}
2261
2262            That's a specialization -- but of the entire template.  */
2263         specialization = 1;
2264       break;
2265
2266     default:
2267       gcc_unreachable ();
2268     }
2269
2270   if (specialization || member_specialization)
2271     {
2272       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2273       for (; t; t = TREE_CHAIN (t))
2274         if (TREE_PURPOSE (t))
2275           {
2276             permerror (input_location, 
2277                        "default argument specified in explicit specialization");
2278             break;
2279           }
2280     }
2281
2282   if (specialization || member_specialization || explicit_instantiation)
2283     {
2284       tree tmpl = NULL_TREE;
2285       tree targs = NULL_TREE;
2286
2287       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2288       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2289         {
2290           tree fns;
2291
2292           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2293           if (ctype)
2294             fns = dname;
2295           else
2296             {
2297               /* If there is no class context, the explicit instantiation
2298                  must be at namespace scope.  */
2299               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2300
2301               /* Find the namespace binding, using the declaration
2302                  context.  */
2303               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2304                                            false, true);
2305               if (fns == error_mark_node || !is_overloaded_fn (fns))
2306                 {
2307                   error ("%qD is not a template function", dname);
2308                   fns = error_mark_node;
2309                 }
2310               else
2311                 {
2312                   tree fn = OVL_CURRENT (fns);
2313                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2314                                                 CP_DECL_CONTEXT (fn)))
2315                     error ("%qD is not declared in %qD",
2316                            decl, current_namespace);
2317                 }
2318             }
2319
2320           declarator = lookup_template_function (fns, NULL_TREE);
2321         }
2322
2323       if (declarator == error_mark_node)
2324         return error_mark_node;
2325
2326       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2327         {
2328           if (!explicit_instantiation)
2329             /* A specialization in class scope.  This is invalid,
2330                but the error will already have been flagged by
2331                check_specialization_scope.  */
2332             return error_mark_node;
2333           else
2334             {
2335               /* It's not valid to write an explicit instantiation in
2336                  class scope, e.g.:
2337
2338                    class C { template void f(); }
2339
2340                    This case is caught by the parser.  However, on
2341                    something like:
2342
2343                    template class C { void f(); };
2344
2345                    (which is invalid) we can get here.  The error will be
2346                    issued later.  */
2347               ;
2348             }
2349
2350           return decl;
2351         }
2352       else if (ctype != NULL_TREE
2353                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2354                    IDENTIFIER_NODE))
2355         {
2356           /* Find the list of functions in ctype that have the same
2357              name as the declared function.  */
2358           tree name = TREE_OPERAND (declarator, 0);
2359           tree fns = NULL_TREE;
2360           int idx;
2361
2362           if (constructor_name_p (name, ctype))
2363             {
2364               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2365
2366               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2367                   : !CLASSTYPE_DESTRUCTORS (ctype))
2368                 {
2369                   /* From [temp.expl.spec]:
2370
2371                      If such an explicit specialization for the member
2372                      of a class template names an implicitly-declared
2373                      special member function (clause _special_), the
2374                      program is ill-formed.
2375
2376                      Similar language is found in [temp.explicit].  */
2377                   error ("specialization of implicitly-declared special member function");
2378                   return error_mark_node;
2379                 }
2380
2381               name = is_constructor ? ctor_identifier : dtor_identifier;
2382             }
2383
2384           if (!DECL_CONV_FN_P (decl))
2385             {
2386               idx = lookup_fnfields_1 (ctype, name);
2387               if (idx >= 0)
2388                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2389             }
2390           else
2391             {
2392               VEC(tree,gc) *methods;
2393               tree ovl;
2394
2395               /* For a type-conversion operator, we cannot do a
2396                  name-based lookup.  We might be looking for `operator
2397                  int' which will be a specialization of `operator T'.
2398                  So, we find *all* the conversion operators, and then
2399                  select from them.  */
2400               fns = NULL_TREE;
2401
2402               methods = CLASSTYPE_METHOD_VEC (ctype);
2403               if (methods)
2404                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2405                      VEC_iterate (tree, methods, idx, ovl);
2406                      ++idx)
2407                   {
2408                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2409                       /* There are no more conversion functions.  */
2410                       break;
2411
2412                     /* Glue all these conversion functions together
2413                        with those we already have.  */
2414                     for (; ovl; ovl = OVL_NEXT (ovl))
2415                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2416                   }
2417             }
2418
2419           if (fns == NULL_TREE)
2420             {
2421               error ("no member function %qD declared in %qT", name, ctype);
2422               return error_mark_node;
2423             }
2424           else
2425             TREE_OPERAND (declarator, 0) = fns;
2426         }
2427
2428       /* Figure out what exactly is being specialized at this point.
2429          Note that for an explicit instantiation, even one for a
2430          member function, we cannot tell apriori whether the
2431          instantiation is for a member template, or just a member
2432          function of a template class.  Even if a member template is
2433          being instantiated, the member template arguments may be
2434          elided if they can be deduced from the rest of the
2435          declaration.  */
2436       tmpl = determine_specialization (declarator, decl,
2437                                        &targs,
2438                                        member_specialization,
2439                                        template_count,
2440                                        tsk);
2441
2442       if (!tmpl || tmpl == error_mark_node)
2443         /* We couldn't figure out what this declaration was
2444            specializing.  */
2445         return error_mark_node;
2446       else
2447         {
2448           tree gen_tmpl = most_general_template (tmpl);
2449
2450           if (explicit_instantiation)
2451             {
2452               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2453                  is done by do_decl_instantiation later.  */
2454
2455               int arg_depth = TMPL_ARGS_DEPTH (targs);
2456               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2457
2458               if (arg_depth > parm_depth)
2459                 {
2460                   /* If TMPL is not the most general template (for
2461                      example, if TMPL is a friend template that is
2462                      injected into namespace scope), then there will
2463                      be too many levels of TARGS.  Remove some of them
2464                      here.  */
2465                   int i;
2466                   tree new_targs;
2467
2468                   new_targs = make_tree_vec (parm_depth);
2469                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2470                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2471                       = TREE_VEC_ELT (targs, i);
2472                   targs = new_targs;
2473                 }
2474
2475               return instantiate_template (tmpl, targs, tf_error);
2476             }
2477
2478           /* If we thought that the DECL was a member function, but it
2479              turns out to be specializing a static member function,
2480              make DECL a static member function as well.  */
2481           if (DECL_STATIC_FUNCTION_P (tmpl)
2482               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2483             revert_static_member_fn (decl);
2484
2485           /* If this is a specialization of a member template of a
2486              template class, we want to return the TEMPLATE_DECL, not
2487              the specialization of it.  */
2488           if (tsk == tsk_template)
2489             {
2490               tree result = DECL_TEMPLATE_RESULT (tmpl);
2491               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2492               DECL_INITIAL (result) = NULL_TREE;
2493               if (have_def)
2494                 {
2495                   tree parm;
2496                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2497                   DECL_SOURCE_LOCATION (result)
2498                     = DECL_SOURCE_LOCATION (decl);
2499                   /* We want to use the argument list specified in the
2500                      definition, not in the original declaration.  */
2501                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2502                   for (parm = DECL_ARGUMENTS (result); parm;
2503                        parm = TREE_CHAIN (parm))
2504                     DECL_CONTEXT (parm) = result;
2505                 }
2506               return register_specialization (tmpl, gen_tmpl, targs,
2507                                               is_friend, 0);
2508             }
2509
2510           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2511           DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
2512
2513           /* Inherit default function arguments from the template
2514              DECL is specializing.  */
2515           copy_default_args_to_explicit_spec (decl);
2516
2517           /* This specialization has the same protection as the
2518              template it specializes.  */
2519           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2520           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2521
2522           /* 7.1.1-1 [dcl.stc]
2523
2524              A storage-class-specifier shall not be specified in an
2525              explicit specialization...
2526
2527              The parser rejects these, so unless action is taken here,
2528              explicit function specializations will always appear with
2529              global linkage.
2530
2531              The action recommended by the C++ CWG in response to C++
2532              defect report 605 is to make the storage class and linkage
2533              of the explicit specialization match the templated function:
2534
2535              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2536            */
2537           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2538             {
2539               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2540               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2541
2542               /* This specialization has the same linkage and visibility as
2543                  the function template it specializes.  */
2544               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2545               if (! TREE_PUBLIC (decl))
2546                 {
2547                   DECL_INTERFACE_KNOWN (decl) = 1;
2548                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2549                 }
2550               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2551               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2552                 {
2553                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2554                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2555                 }
2556             }
2557
2558           /* If DECL is a friend declaration, declared using an
2559              unqualified name, the namespace associated with DECL may
2560              have been set incorrectly.  For example, in:
2561
2562                template <typename T> void f(T);
2563                namespace N {
2564                  struct S { friend void f<int>(int); }
2565                }
2566
2567              we will have set the DECL_CONTEXT for the friend
2568              declaration to N, rather than to the global namespace.  */
2569           if (DECL_NAMESPACE_SCOPE_P (decl))
2570             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2571
2572           if (is_friend && !have_def)
2573             /* This is not really a declaration of a specialization.
2574                It's just the name of an instantiation.  But, it's not
2575                a request for an instantiation, either.  */
2576             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2577           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2578             /* This is indeed a specialization.  In case of constructors
2579                and destructors, we need in-charge and not-in-charge
2580                versions in V3 ABI.  */
2581             clone_function_decl (decl, /*update_method_vec_p=*/0);
2582
2583           /* Register this specialization so that we can find it
2584              again.  */
2585           decl = register_specialization (decl, gen_tmpl, targs, is_friend, 0);
2586         }
2587     }
2588
2589   return decl;
2590 }
2591
2592 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2593    parameters.  These are represented in the same format used for
2594    DECL_TEMPLATE_PARMS.  */
2595
2596 int
2597 comp_template_parms (const_tree parms1, const_tree parms2)
2598 {
2599   const_tree p1;
2600   const_tree p2;
2601
2602   if (parms1 == parms2)
2603     return 1;
2604
2605   for (p1 = parms1, p2 = parms2;
2606        p1 != NULL_TREE && p2 != NULL_TREE;
2607        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2608     {
2609       tree t1 = TREE_VALUE (p1);
2610       tree t2 = TREE_VALUE (p2);
2611       int i;
2612
2613       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2614       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2615
2616       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2617         return 0;
2618
2619       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2620         {
2621           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2622           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2623
2624           /* If either of the template parameters are invalid, assume
2625              they match for the sake of error recovery. */
2626           if (parm1 == error_mark_node || parm2 == error_mark_node)
2627             return 1;
2628
2629           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2630             return 0;
2631
2632           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2633               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2634                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2635             continue;
2636           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2637             return 0;
2638         }
2639     }
2640
2641   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2642     /* One set of parameters has more parameters lists than the
2643        other.  */
2644     return 0;
2645
2646   return 1;
2647 }
2648
2649 /* Determine whether PARM is a parameter pack.  */
2650
2651 bool 
2652 template_parameter_pack_p (const_tree parm)
2653 {
2654   /* Determine if we have a non-type template parameter pack.  */
2655   if (TREE_CODE (parm) == PARM_DECL)
2656     return (DECL_TEMPLATE_PARM_P (parm) 
2657             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2658
2659   /* If this is a list of template parameters, we could get a
2660      TYPE_DECL or a TEMPLATE_DECL.  */ 
2661   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2662     parm = TREE_TYPE (parm);
2663
2664   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2665            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2666           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2667 }
2668
2669 /* Determine if T is a function parameter pack.  */
2670
2671 bool
2672 function_parameter_pack_p (const_tree t)
2673 {
2674   if (t && TREE_CODE (t) == PARM_DECL)
2675     return FUNCTION_PARAMETER_PACK_P (t);
2676   return false;
2677 }
2678
2679 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
2680    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
2681
2682 tree
2683 get_function_template_decl (const_tree primary_func_tmpl_inst)
2684 {
2685   if (! primary_func_tmpl_inst
2686       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
2687       || ! primary_template_instantiation_p (primary_func_tmpl_inst))
2688     return NULL;
2689
2690   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
2691 }
2692
2693 /* Return true iff the function parameter PARAM_DECL was expanded
2694    from the function parameter pack PACK.  */
2695
2696 bool
2697 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
2698 {
2699     if (DECL_ARTIFICIAL (param_decl)
2700         || !function_parameter_pack_p (pack))
2701       return false;
2702
2703     gcc_assert (DECL_NAME (param_decl) && DECL_NAME (pack));
2704
2705     /* The parameter pack and its pack arguments have the same
2706        DECL_PARM_INDEX.  */
2707     return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
2708 }
2709
2710 /* Determine whether ARGS describes a variadic template args list,
2711    i.e., one that is terminated by a template argument pack.  */
2712
2713 static bool 
2714 template_args_variadic_p (tree args)
2715 {
2716   int nargs;
2717   tree last_parm;
2718
2719   if (args == NULL_TREE)
2720     return false;
2721
2722   args = INNERMOST_TEMPLATE_ARGS (args);
2723   nargs = TREE_VEC_LENGTH (args);
2724
2725   if (nargs == 0)
2726     return false;
2727
2728   last_parm = TREE_VEC_ELT (args, nargs - 1);
2729
2730   return ARGUMENT_PACK_P (last_parm);
2731 }
2732
2733 /* Generate a new name for the parameter pack name NAME (an
2734    IDENTIFIER_NODE) that incorporates its */
2735
2736 static tree
2737 make_ith_pack_parameter_name (tree name, int i)
2738 {
2739   /* Munge the name to include the parameter index.  */
2740 #define NUMBUF_LEN 128
2741   char numbuf[NUMBUF_LEN];
2742   char* newname;
2743   int newname_len;
2744
2745   snprintf (numbuf, NUMBUF_LEN, "%i", i);
2746   newname_len = IDENTIFIER_LENGTH (name)
2747                 + strlen (numbuf) + 2;
2748   newname = (char*)alloca (newname_len);
2749   snprintf (newname, newname_len,
2750             "%s#%i", IDENTIFIER_POINTER (name), i);
2751   return get_identifier (newname);
2752 }
2753
2754 /* Return true if T is a primary function
2755    or class template instantiation.  */
2756
2757 bool
2758 primary_template_instantiation_p (const_tree t)
2759 {
2760   if (!t)
2761     return false;
2762
2763   if (TREE_CODE (t) == FUNCTION_DECL)
2764     return DECL_LANG_SPECIFIC (t)
2765            && DECL_TEMPLATE_INSTANTIATION (t)
2766            && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t));
2767   else if (CLASS_TYPE_P (t))
2768     return CLASSTYPE_TEMPLATE_INSTANTIATION (t)
2769            && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t));
2770   return false;
2771 }
2772
2773 /* Return true if PARM is a template template parameter.  */
2774
2775 bool
2776 template_template_parameter_p (const_tree parm)
2777 {
2778   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
2779 }
2780
2781 /* Return the template parameters of T if T is a
2782    primary template instantiation, NULL otherwise.  */
2783
2784 tree
2785 get_primary_template_innermost_parameters (const_tree t)
2786 {
2787   tree parms = NULL, template_info = NULL;
2788
2789   if ((template_info = get_template_info (t))
2790       && primary_template_instantiation_p (t))
2791     parms = INNERMOST_TEMPLATE_PARMS
2792         (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
2793
2794   return parms;
2795 }
2796
2797 /* Returns the template arguments of T if T is a template instantiation,
2798    NULL otherwise.  */
2799
2800 tree
2801 get_template_innermost_arguments (const_tree t)
2802 {
2803   tree args = NULL, template_info = NULL;
2804
2805   if ((template_info = get_template_info (t))
2806       && TI_ARGS (template_info))
2807     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
2808
2809   return args;
2810 }
2811
2812 /* Return the argument pack elements of T if T is a template argument pack,
2813    NULL otherwise.  */
2814
2815 tree
2816 get_template_argument_pack_elems (const_tree t)
2817 {
2818   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
2819       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
2820     return NULL;
2821
2822   return ARGUMENT_PACK_ARGS (t);
2823 }
2824
2825 /* Structure used to track the progress of find_parameter_packs_r.  */
2826 struct find_parameter_pack_data 
2827 {
2828   /* TREE_LIST that will contain all of the parameter packs found by
2829      the traversal.  */
2830   tree* parameter_packs;
2831
2832   /* Set of AST nodes that have been visited by the traversal.  */
2833   struct pointer_set_t *visited;
2834 };
2835
2836 /* Identifies all of the argument packs that occur in a template
2837    argument and appends them to the TREE_LIST inside DATA, which is a
2838    find_parameter_pack_data structure. This is a subroutine of
2839    make_pack_expansion and uses_parameter_packs.  */
2840 static tree
2841 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2842 {
2843   tree t = *tp;
2844   struct find_parameter_pack_data* ppd = 
2845     (struct find_parameter_pack_data*)data;
2846   bool parameter_pack_p = false;
2847
2848   /* Identify whether this is a parameter pack or not.  */
2849   switch (TREE_CODE (t))
2850     {
2851     case TEMPLATE_PARM_INDEX:
2852       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2853         parameter_pack_p = true;
2854       break;
2855
2856     case TEMPLATE_TYPE_PARM:
2857     case TEMPLATE_TEMPLATE_PARM:
2858       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2859         parameter_pack_p = true;
2860       break;
2861
2862     case PARM_DECL:
2863       if (FUNCTION_PARAMETER_PACK_P (t))
2864         {
2865           /* We don't want to walk into the type of a PARM_DECL,
2866              because we don't want to see the type parameter pack.  */
2867           *walk_subtrees = 0;
2868           parameter_pack_p = true;
2869         }
2870       break;
2871
2872     default:
2873       /* Not a parameter pack.  */
2874       break;
2875     }
2876
2877   if (parameter_pack_p)
2878     {
2879       /* Add this parameter pack to the list.  */
2880       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2881     }
2882
2883   if (TYPE_P (t))
2884     cp_walk_tree (&TYPE_CONTEXT (t), 
2885                   &find_parameter_packs_r, ppd, ppd->visited);
2886
2887   /* This switch statement will return immediately if we don't find a
2888      parameter pack.  */
2889   switch (TREE_CODE (t)) 
2890     {
2891     case TEMPLATE_PARM_INDEX:
2892       return NULL_TREE;
2893
2894     case BOUND_TEMPLATE_TEMPLATE_PARM:
2895       /* Check the template itself.  */
2896       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
2897                     &find_parameter_packs_r, ppd, ppd->visited);
2898       /* Check the template arguments.  */
2899       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
2900                     ppd->visited);
2901       *walk_subtrees = 0;
2902       return NULL_TREE;
2903
2904     case TEMPLATE_TYPE_PARM:
2905     case TEMPLATE_TEMPLATE_PARM:
2906       return NULL_TREE;
2907
2908     case PARM_DECL:
2909       return NULL_TREE;
2910
2911     case RECORD_TYPE:
2912       if (TYPE_PTRMEMFUNC_P (t))
2913         return NULL_TREE;
2914       /* Fall through.  */
2915
2916     case UNION_TYPE:
2917     case ENUMERAL_TYPE:
2918       if (TYPE_TEMPLATE_INFO (t))
2919         cp_walk_tree (&TI_ARGS (TYPE_TEMPLATE_INFO (t)),
2920                       &find_parameter_packs_r, ppd, ppd->visited);
2921
2922       *walk_subtrees = 0;
2923       return NULL_TREE;
2924
2925     case TEMPLATE_DECL:
2926       cp_walk_tree (&TREE_TYPE (t),
2927                     &find_parameter_packs_r, ppd, ppd->visited);
2928       return NULL_TREE;
2929  
2930     case TYPENAME_TYPE:
2931       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
2932                    ppd, ppd->visited);
2933       *walk_subtrees = 0;
2934       return NULL_TREE;
2935       
2936     case TYPE_PACK_EXPANSION:
2937     case EXPR_PACK_EXPANSION:
2938       *walk_subtrees = 0;
2939       return NULL_TREE;
2940
2941     case INTEGER_TYPE:
2942       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
2943                     ppd, ppd->visited);
2944       *walk_subtrees = 0;
2945       return NULL_TREE;
2946
2947     case IDENTIFIER_NODE:
2948       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
2949                     ppd->visited);
2950       *walk_subtrees = 0;
2951       return NULL_TREE;
2952
2953     default:
2954       return NULL_TREE;
2955     }
2956
2957   return NULL_TREE;
2958 }
2959
2960 /* Determines if the expression or type T uses any parameter packs.  */
2961 bool
2962 uses_parameter_packs (tree t)
2963 {
2964   tree parameter_packs = NULL_TREE;
2965   struct find_parameter_pack_data ppd;
2966   ppd.parameter_packs = &parameter_packs;
2967   ppd.visited = pointer_set_create ();
2968   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
2969   pointer_set_destroy (ppd.visited);
2970   return parameter_packs != NULL_TREE;
2971 }
2972
2973 /* Turn ARG, which may be an expression, type, or a TREE_LIST
2974    representation a base-class initializer into a parameter pack
2975    expansion. If all goes well, the resulting node will be an
2976    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
2977    respectively.  */
2978 tree 
2979 make_pack_expansion (tree arg)
2980 {
2981   tree result;
2982   tree parameter_packs = NULL_TREE;
2983   bool for_types = false;
2984   struct find_parameter_pack_data ppd;
2985
2986   if (!arg || arg == error_mark_node)
2987     return arg;
2988
2989   if (TREE_CODE (arg) == TREE_LIST)
2990     {
2991       /* The only time we will see a TREE_LIST here is for a base
2992          class initializer.  In this case, the TREE_PURPOSE will be a
2993          _TYPE node (representing the base class expansion we're
2994          initializing) and the TREE_VALUE will be a TREE_LIST
2995          containing the initialization arguments. 
2996
2997          The resulting expansion looks somewhat different from most
2998          expansions. Rather than returning just one _EXPANSION, we
2999          return a TREE_LIST whose TREE_PURPOSE is a
3000          TYPE_PACK_EXPANSION containing the bases that will be
3001          initialized.  The TREE_VALUE will be identical to the
3002          original TREE_VALUE, which is a list of arguments that will
3003          be passed to each base.  We do not introduce any new pack
3004          expansion nodes into the TREE_VALUE (although it is possible
3005          that some already exist), because the TREE_PURPOSE and
3006          TREE_VALUE all need to be expanded together with the same
3007          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3008          resulting TREE_PURPOSE will mention the parameter packs in
3009          both the bases and the arguments to the bases.  */
3010       tree purpose;
3011       tree value;
3012       tree parameter_packs = NULL_TREE;
3013
3014       /* Determine which parameter packs will be used by the base
3015          class expansion.  */
3016       ppd.visited = pointer_set_create ();
3017       ppd.parameter_packs = &parameter_packs;
3018       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
3019                     &ppd, ppd.visited);
3020
3021       if (parameter_packs == NULL_TREE)
3022         {
3023           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
3024           pointer_set_destroy (ppd.visited);
3025           return error_mark_node;
3026         }
3027
3028       if (TREE_VALUE (arg) != void_type_node)
3029         {
3030           /* Collect the sets of parameter packs used in each of the
3031              initialization arguments.  */
3032           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3033             {
3034               /* Determine which parameter packs will be expanded in this
3035                  argument.  */
3036               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
3037                             &ppd, ppd.visited);
3038             }
3039         }
3040
3041       pointer_set_destroy (ppd.visited);
3042
3043       /* Create the pack expansion type for the base type.  */
3044       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3045       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3046       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3047
3048       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3049          they will rarely be compared to anything.  */
3050       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3051
3052       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3053     }
3054
3055   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3056     for_types = true;
3057
3058   /* Build the PACK_EXPANSION_* node.  */
3059   result = for_types
3060      ? cxx_make_type (TYPE_PACK_EXPANSION)
3061      : make_node (EXPR_PACK_EXPANSION);
3062   SET_PACK_EXPANSION_PATTERN (result, arg);
3063   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3064     {
3065       /* Propagate type and const-expression information.  */
3066       TREE_TYPE (result) = TREE_TYPE (arg);
3067       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3068     }
3069   else
3070     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3071        they will rarely be compared to anything.  */
3072     SET_TYPE_STRUCTURAL_EQUALITY (result);
3073
3074   /* Determine which parameter packs will be expanded.  */
3075   ppd.parameter_packs = &parameter_packs;
3076   ppd.visited = pointer_set_create ();
3077   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3078   pointer_set_destroy (ppd.visited);
3079
3080   /* Make sure we found some parameter packs.  */
3081   if (parameter_packs == NULL_TREE)
3082     {
3083       if (TYPE_P (arg))
3084         error ("expansion pattern %<%T%> contains no argument packs", arg);
3085       else
3086         error ("expansion pattern %<%E%> contains no argument packs", arg);
3087       return error_mark_node;
3088     }
3089   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
3090
3091   return result;
3092 }
3093
3094 /* Checks T for any "bare" parameter packs, which have not yet been
3095    expanded, and issues an error if any are found. This operation can
3096    only be done on full expressions or types (e.g., an expression
3097    statement, "if" condition, etc.), because we could have expressions like:
3098
3099      foo(f(g(h(args)))...)
3100
3101    where "args" is a parameter pack. check_for_bare_parameter_packs
3102    should not be called for the subexpressions args, h(args),
3103    g(h(args)), or f(g(h(args))), because we would produce erroneous
3104    error messages. 
3105
3106    Returns TRUE and emits an error if there were bare parameter packs,
3107    returns FALSE otherwise.  */
3108 bool 
3109 check_for_bare_parameter_packs (tree t)
3110 {
3111   tree parameter_packs = NULL_TREE;
3112   struct find_parameter_pack_data ppd;
3113
3114   if (!processing_template_decl || !t || t == error_mark_node)
3115     return false;
3116
3117   if (TREE_CODE (t) == TYPE_DECL)
3118     t = TREE_TYPE (t);
3119
3120   ppd.parameter_packs = &parameter_packs;
3121   ppd.visited = pointer_set_create ();
3122   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3123   pointer_set_destroy (ppd.visited);
3124
3125   if (parameter_packs) 
3126     {
3127       error ("parameter packs not expanded with %<...%>:");
3128       while (parameter_packs)
3129         {
3130           tree pack = TREE_VALUE (parameter_packs);
3131           tree name = NULL_TREE;
3132
3133           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
3134               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
3135             name = TYPE_NAME (pack);
3136           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
3137             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
3138           else
3139             name = DECL_NAME (pack);
3140
3141           if (name)
3142             inform (input_location, "        %qD", name);
3143           else
3144             inform (input_location, "        <anonymous>");
3145
3146           parameter_packs = TREE_CHAIN (parameter_packs);
3147         }
3148
3149       return true;
3150     }
3151
3152   return false;
3153 }
3154
3155 /* Expand any parameter packs that occur in the template arguments in
3156    ARGS.  */
3157 tree
3158 expand_template_argument_pack (tree args)
3159 {
3160   tree result_args = NULL_TREE;
3161   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3162   int num_result_args = -1;
3163
3164   /* First, determine if we need to expand anything, and the number of
3165      slots we'll need.  */
3166   for (in_arg = 0; in_arg < nargs; ++in_arg)
3167     {
3168       tree arg = TREE_VEC_ELT (args, in_arg);
3169       if (arg == NULL_TREE)
3170         return args;
3171       if (ARGUMENT_PACK_P (arg))
3172         {
3173           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3174           if (num_result_args < 0)
3175             num_result_args = in_arg + num_packed;
3176           else
3177             num_result_args += num_packed;
3178         }
3179       else
3180         {
3181           if (num_result_args >= 0)
3182             num_result_args++;
3183         }
3184     }
3185
3186   /* If no expansion is necessary, we're done.  */
3187   if (num_result_args < 0)
3188     return args;
3189
3190   /* Expand arguments.  */
3191   result_args = make_tree_vec (num_result_args);
3192   for (in_arg = 0; in_arg < nargs; ++in_arg)
3193     {
3194       tree arg = TREE_VEC_ELT (args, in_arg);
3195       if (ARGUMENT_PACK_P (arg))
3196         {
3197           tree packed = ARGUMENT_PACK_ARGS (arg);
3198           int i, num_packed = TREE_VEC_LENGTH (packed);
3199           for (i = 0; i < num_packed; ++i, ++out_arg)
3200             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3201         }
3202       else
3203         {
3204           TREE_VEC_ELT (result_args, out_arg) = arg;
3205           ++out_arg;
3206         }
3207     }
3208
3209   return result_args;
3210 }
3211
3212 /* Checks if DECL shadows a template parameter.
3213
3214    [temp.local]: A template-parameter shall not be redeclared within its
3215    scope (including nested scopes).
3216
3217    Emits an error and returns TRUE if the DECL shadows a parameter,
3218    returns FALSE otherwise.  */
3219
3220 bool
3221 check_template_shadow (tree decl)
3222 {
3223   tree olddecl;
3224
3225   /* If we're not in a template, we can't possibly shadow a template
3226      parameter.  */
3227   if (!current_template_parms)
3228     return true;
3229
3230   /* Figure out what we're shadowing.  */
3231   if (TREE_CODE (decl) == OVERLOAD)
3232     decl = OVL_CURRENT (decl);
3233   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3234
3235   /* If there's no previous binding for this name, we're not shadowing
3236      anything, let alone a template parameter.  */
3237   if (!olddecl)
3238     return true;
3239
3240   /* If we're not shadowing a template parameter, we're done.  Note
3241      that OLDDECL might be an OVERLOAD (or perhaps even an
3242      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3243      node.  */
3244   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3245     return true;
3246
3247   /* We check for decl != olddecl to avoid bogus errors for using a
3248      name inside a class.  We check TPFI to avoid duplicate errors for
3249      inline member templates.  */
3250   if (decl == olddecl
3251       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
3252     return true;
3253
3254   error ("declaration of %q+#D", decl);
3255   error (" shadows template parm %q+#D", olddecl);
3256   return false;
3257 }
3258
3259 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3260    ORIG_LEVEL, DECL, and TYPE.  */
3261
3262 static tree
3263 build_template_parm_index (int index,
3264                            int level,
3265                            int orig_level,
3266                            tree decl,
3267                            tree type)
3268 {
3269   tree t = make_node (TEMPLATE_PARM_INDEX);
3270   TEMPLATE_PARM_IDX (t) = index;
3271   TEMPLATE_PARM_LEVEL (t) = level;
3272   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3273   TEMPLATE_PARM_DECL (t) = decl;
3274   TREE_TYPE (t) = type;
3275   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3276   TREE_READONLY (t) = TREE_READONLY (decl);
3277
3278   return t;
3279 }
3280
3281 /* Find the canonical type parameter for the given template type
3282    parameter.  Returns the canonical type parameter, which may be TYPE
3283    if no such parameter existed.  */
3284 static tree
3285 canonical_type_parameter (tree type)
3286 {
3287   tree list;
3288   int idx = TEMPLATE_TYPE_IDX (type);
3289   if (!canonical_template_parms)
3290     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
3291
3292   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
3293     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
3294
3295   list = VEC_index (tree, canonical_template_parms, idx);
3296   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3297     list = TREE_CHAIN (list);
3298
3299   if (list)
3300     return TREE_VALUE (list);
3301   else
3302     {
3303       VEC_replace(tree, canonical_template_parms, idx,
3304                   tree_cons (NULL_TREE, type, 
3305                              VEC_index (tree, canonical_template_parms, idx)));
3306       return type;
3307     }
3308 }
3309
3310 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3311    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3312    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3313    new one is created.  */
3314
3315 static tree
3316 reduce_template_parm_level (tree index, tree type, int levels, tree args,
3317                             tsubst_flags_t complain)
3318 {
3319   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3320       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3321           != TEMPLATE_PARM_LEVEL (index) - levels))
3322     {
3323       tree orig_decl = TEMPLATE_PARM_DECL (index);
3324       tree decl, t;
3325
3326       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3327                          TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3328       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
3329       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
3330       DECL_ARTIFICIAL (decl) = 1;
3331       SET_DECL_TEMPLATE_PARM_P (decl);
3332
3333       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
3334                                      TEMPLATE_PARM_LEVEL (index) - levels,
3335                                      TEMPLATE_PARM_ORIG_LEVEL (index),
3336                                      decl, type);
3337       TEMPLATE_PARM_DESCENDANTS (index) = t;
3338       TEMPLATE_PARM_PARAMETER_PACK (t) 
3339         = TEMPLATE_PARM_PARAMETER_PACK (index);
3340
3341         /* Template template parameters need this.  */
3342       if (TREE_CODE (decl) == TEMPLATE_DECL)
3343         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
3344           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
3345            args, complain);
3346     }
3347
3348   return TEMPLATE_PARM_DESCENDANTS (index);
3349 }
3350
3351 /* Process information from new template parameter PARM and append it to the
3352    LIST being built.  This new parameter is a non-type parameter iff
3353    IS_NON_TYPE is true. This new parameter is a parameter
3354    pack iff IS_PARAMETER_PACK is true.  The location of PARM is in 
3355    PARM_LOC.  */
3356
3357 tree
3358 process_template_parm (tree list, location_t parm_loc, tree parm, bool is_non_type, 
3359                        bool is_parameter_pack)
3360 {
3361   tree decl = 0;
3362   tree defval;
3363   tree err_parm_list;
3364   int idx = 0;
3365
3366   gcc_assert (TREE_CODE (parm) == TREE_LIST);
3367   defval = TREE_PURPOSE (parm);
3368
3369   if (list)
3370     {
3371       tree p = tree_last (list);
3372
3373       if (p && TREE_VALUE (p) != error_mark_node)
3374         {
3375           p = TREE_VALUE (p);
3376           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3377             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3378           else
3379             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3380         }
3381
3382       ++idx;
3383     }
3384   else
3385     idx = 0;
3386
3387   if (is_non_type)
3388     {
3389       parm = TREE_VALUE (parm);
3390
3391       SET_DECL_TEMPLATE_PARM_P (parm);
3392
3393       if (TREE_TYPE (parm) == error_mark_node)
3394         {
3395           err_parm_list = build_tree_list (defval, parm);
3396           TREE_VALUE (err_parm_list) = error_mark_node;
3397            return chainon (list, err_parm_list);
3398         }
3399       else
3400       {
3401         /* [temp.param]
3402
3403            The top-level cv-qualifiers on the template-parameter are
3404            ignored when determining its type.  */
3405         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3406         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3407           {
3408             err_parm_list = build_tree_list (defval, parm);
3409             TREE_VALUE (err_parm_list) = error_mark_node;
3410              return chainon (list, err_parm_list);
3411           }
3412
3413         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3414           {
3415             /* This template parameter is not a parameter pack, but it
3416                should be. Complain about "bare" parameter packs.  */
3417             check_for_bare_parameter_packs (TREE_TYPE (parm));
3418             
3419             /* Recover by calling this a parameter pack.  */
3420             is_parameter_pack = true;
3421           }
3422       }
3423
3424       /* A template parameter is not modifiable.  */
3425       TREE_CONSTANT (parm) = 1;
3426       TREE_READONLY (parm) = 1;
3427       decl = build_decl (parm_loc,
3428                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3429       TREE_CONSTANT (decl) = 1;
3430       TREE_READONLY (decl) = 1;
3431       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3432         = build_template_parm_index (idx, processing_template_decl,
3433                                      processing_template_decl,
3434                                      decl, TREE_TYPE (parm));
3435
3436       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3437         = is_parameter_pack;
3438     }
3439   else
3440     {
3441       tree t;
3442       parm = TREE_VALUE (TREE_VALUE (parm));
3443
3444       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3445         {
3446           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3447           /* This is for distinguishing between real templates and template
3448              template parameters */
3449           TREE_TYPE (parm) = t;
3450           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3451           decl = parm;
3452         }
3453       else
3454         {
3455           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3456           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3457           decl = build_decl (parm_loc,
3458                              TYPE_DECL, parm, t);
3459         }
3460
3461       TYPE_NAME (t) = decl;
3462       TYPE_STUB_DECL (t) = decl;
3463       parm = decl;
3464       TEMPLATE_TYPE_PARM_INDEX (t)
3465         = build_template_parm_index (idx, processing_template_decl,
3466                                      processing_template_decl,
3467                                      decl, TREE_TYPE (parm));
3468       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3469       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3470     }
3471   DECL_ARTIFICIAL (decl) = 1;
3472   SET_DECL_TEMPLATE_PARM_P (decl);
3473   pushdecl (decl);
3474   parm = build_tree_list (defval, parm);
3475   return chainon (list, parm);
3476 }
3477
3478 /* The end of a template parameter list has been reached.  Process the
3479    tree list into a parameter vector, converting each parameter into a more
3480    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3481    as PARM_DECLs.  */
3482
3483 tree
3484 end_template_parm_list (tree parms)
3485 {
3486   int nparms;
3487   tree parm, next;
3488   tree saved_parmlist = make_tree_vec (list_length (parms));
3489
3490   current_template_parms
3491     = tree_cons (size_int (processing_template_decl),
3492                  saved_parmlist, current_template_parms);
3493
3494   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3495     {
3496       next = TREE_CHAIN (parm);
3497       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3498       TREE_CHAIN (parm) = NULL_TREE;
3499     }
3500
3501   --processing_template_parmlist;
3502
3503   return saved_parmlist;
3504 }
3505
3506 /* end_template_decl is called after a template declaration is seen.  */
3507
3508 void
3509 end_template_decl (void)
3510 {
3511   reset_specialization ();
3512
3513   if (! processing_template_decl)
3514     return;
3515
3516   /* This matches the pushlevel in begin_template_parm_list.  */
3517   finish_scope ();
3518
3519   --processing_template_decl;
3520   current_template_parms = TREE_CHAIN (current_template_parms);
3521 }
3522
3523 /* Within the declaration of a template, return all levels of template
3524    parameters that apply.  The template parameters are represented as
3525    a TREE_VEC, in the form documented in cp-tree.h for template
3526    arguments.  */
3527
3528 static tree
3529 current_template_args (void)
3530 {
3531   tree header;
3532   tree args = NULL_TREE;
3533   int length = TMPL_PARMS_DEPTH (current_template_parms);
3534   int l = length;
3535
3536   /* If there is only one level of template parameters, we do not
3537      create a TREE_VEC of TREE_VECs.  Instead, we return a single
3538      TREE_VEC containing the arguments.  */
3539   if (length > 1)
3540     args = make_tree_vec (length);
3541
3542   for (header = current_template_parms; header; header = TREE_CHAIN (header))
3543     {
3544       tree a = copy_node (TREE_VALUE (header));
3545       int i;
3546
3547       TREE_TYPE (a) = NULL_TREE;
3548       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3549         {
3550           tree t = TREE_VEC_ELT (a, i);
3551
3552           /* T will be a list if we are called from within a
3553              begin/end_template_parm_list pair, but a vector directly
3554              if within a begin/end_member_template_processing pair.  */
3555           if (TREE_CODE (t) == TREE_LIST)
3556             {
3557               t = TREE_VALUE (t);
3558
3559               if (!error_operand_p (t))
3560                 {
3561                   if (TREE_CODE (t) == TYPE_DECL
3562                       || TREE_CODE (t) == TEMPLATE_DECL)
3563                     {
3564                       t = TREE_TYPE (t);
3565                       
3566                       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3567                         {
3568                           /* Turn this argument into a TYPE_ARGUMENT_PACK
3569                              with a single element, which expands T.  */
3570                           tree vec = make_tree_vec (1);
3571                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3572                           
3573                           t = cxx_make_type (TYPE_ARGUMENT_PACK);
3574                           SET_ARGUMENT_PACK_ARGS (t, vec);
3575                         }
3576                     }
3577                   else
3578                     {
3579                       t = DECL_INITIAL (t);
3580                       
3581                       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3582                         {
3583                           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3584                              with a single element, which expands T.  */
3585                           tree vec = make_tree_vec (1);
3586                           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3587                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3588                           
3589                           t  = make_node (NONTYPE_ARGUMENT_PACK);
3590                           SET_ARGUMENT_PACK_ARGS (t, vec);
3591                           TREE_TYPE (t) = type;
3592                         }
3593                     }
3594                   TREE_VEC_ELT (a, i) = t;
3595                 }
3596             }
3597         }
3598
3599       if (length > 1)
3600         TREE_VEC_ELT (args, --l) = a;
3601       else
3602         args = a;
3603     }
3604
3605   return args;
3606 }
3607
3608 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
3609    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
3610    a member template.  Used by push_template_decl below.  */
3611
3612 static tree
3613 build_template_decl (tree decl, tree parms, bool member_template_p)
3614 {
3615   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
3616   DECL_TEMPLATE_PARMS (tmpl) = parms;
3617   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
3618   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
3619
3620   return tmpl;
3621 }
3622
3623 struct template_parm_data
3624 {
3625   /* The level of the template parameters we are currently
3626      processing.  */
3627   int level;
3628
3629   /* The index of the specialization argument we are currently
3630      processing.  */
3631   int current_arg;
3632
3633   /* An array whose size is the number of template parameters.  The
3634      elements are nonzero if the parameter has been used in any one
3635      of the arguments processed so far.  */
3636   int* parms;
3637
3638   /* An array whose size is the number of template arguments.  The
3639      elements are nonzero if the argument makes use of template
3640      parameters of this level.  */
3641   int* arg_uses_template_parms;
3642 };
3643
3644 /* Subroutine of push_template_decl used to see if each template
3645    parameter in a partial specialization is used in the explicit
3646    argument list.  If T is of the LEVEL given in DATA (which is
3647    treated as a template_parm_data*), then DATA->PARMS is marked
3648    appropriately.  */
3649
3650 static int
3651 mark_template_parm (tree t, void* data)
3652 {
3653   int level;
3654   int idx;
3655   struct template_parm_data* tpd = (struct template_parm_data*) data;
3656
3657   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3658     {
3659       level = TEMPLATE_PARM_LEVEL (t);
3660       idx = TEMPLATE_PARM_IDX (t);
3661     }
3662   else
3663     {
3664       level = TEMPLATE_TYPE_LEVEL (t);
3665       idx = TEMPLATE_TYPE_IDX (t);
3666     }
3667
3668   if (level == tpd->level)
3669     {
3670       tpd->parms[idx] = 1;
3671       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
3672     }
3673
3674   /* Return zero so that for_each_template_parm will continue the
3675      traversal of the tree; we want to mark *every* template parm.  */
3676   return 0;
3677 }
3678
3679 /* Process the partial specialization DECL.  */
3680
3681 static tree
3682 process_partial_specialization (tree decl)
3683 {
3684   tree type = TREE_TYPE (decl);
3685   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
3686   tree specargs = CLASSTYPE_TI_ARGS (type);
3687   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
3688   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
3689   tree inner_parms;
3690   int nargs = TREE_VEC_LENGTH (inner_args);
3691   int ntparms;
3692   int  i;
3693   int did_error_intro = 0;
3694   struct template_parm_data tpd;
3695   struct template_parm_data tpd2;
3696
3697   gcc_assert (current_template_parms);
3698
3699   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3700   ntparms = TREE_VEC_LENGTH (inner_parms);
3701
3702   /* We check that each of the template parameters given in the
3703      partial specialization is used in the argument list to the
3704      specialization.  For example:
3705
3706        template <class T> struct S;
3707        template <class T> struct S<T*>;
3708
3709      The second declaration is OK because `T*' uses the template
3710      parameter T, whereas
3711
3712        template <class T> struct S<int>;
3713
3714      is no good.  Even trickier is:
3715
3716        template <class T>
3717        struct S1
3718        {
3719           template <class U>
3720           struct S2;
3721           template <class U>
3722           struct S2<T>;
3723        };
3724
3725      The S2<T> declaration is actually invalid; it is a
3726      full-specialization.  Of course,
3727
3728           template <class U>
3729           struct S2<T (*)(U)>;
3730
3731      or some such would have been OK.  */
3732   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
3733   tpd.parms = (int *) alloca (sizeof (int) * ntparms);
3734   memset (tpd.parms, 0, sizeof (int) * ntparms);
3735
3736   tpd.arg_uses_template_parms = (int *) alloca (sizeof (int) * nargs);
3737   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
3738   for (i = 0; i < nargs; ++i)
3739     {
3740       tpd.current_arg = i;
3741       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
3742                               &mark_template_parm,
3743                               &tpd,
3744                               NULL,
3745                               /*include_nondeduced_p=*/false);
3746     }
3747   for (i = 0; i < ntparms; ++i)
3748     if (tpd.parms[i] == 0)
3749       {
3750         /* One of the template parms was not used in the
3751            specialization.  */
3752         if (!did_error_intro)
3753           {
3754             error ("template parameters not used in partial specialization:");
3755             did_error_intro = 1;
3756           }
3757
3758         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
3759       }
3760
3761   /* [temp.class.spec]
3762
3763      The argument list of the specialization shall not be identical to
3764      the implicit argument list of the primary template.  */
3765   if (comp_template_args
3766       (inner_args,
3767        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
3768                                                    (maintmpl)))))
3769     error ("partial specialization %qT does not specialize any template arguments", type);
3770
3771   /* [temp.class.spec]
3772
3773      A partially specialized non-type argument expression shall not
3774      involve template parameters of the partial specialization except
3775      when the argument expression is a simple identifier.
3776
3777      The type of a template parameter corresponding to a specialized
3778      non-type argument shall not be dependent on a parameter of the
3779      specialization. 
3780
3781      Also, we verify that pack expansions only occur at the
3782      end of the argument list.  */
3783   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
3784   tpd2.parms = 0;
3785   for (i = 0; i < nargs; ++i)
3786     {
3787       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
3788       tree arg = TREE_VEC_ELT (inner_args, i);
3789       tree packed_args = NULL_TREE;
3790       int j, len = 1;
3791
3792       if (ARGUMENT_PACK_P (arg))
3793         {
3794           /* Extract the arguments from the argument pack. We'll be
3795              iterating over these in the following loop.  */
3796           packed_args = ARGUMENT_PACK_ARGS (arg);
3797           len = TREE_VEC_LENGTH (packed_args);
3798         }
3799
3800       for (j = 0; j < len; j++)
3801         {
3802           if (packed_args)
3803             /* Get the Jth argument in the parameter pack.  */
3804             arg = TREE_VEC_ELT (packed_args, j);
3805
3806           if (PACK_EXPANSION_P (arg))
3807             {
3808               /* Pack expansions must come at the end of the
3809                  argument list.  */
3810               if ((packed_args && j < len - 1)
3811                   || (!packed_args && i < nargs - 1))
3812                 {
3813                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3814                     error ("parameter pack argument %qE must be at the "
3815                            "end of the template argument list", arg);
3816                   else
3817                     error ("parameter pack argument %qT must be at the "
3818                            "end of the template argument list", arg);
3819                 }
3820             }
3821
3822           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3823             /* We only care about the pattern.  */
3824             arg = PACK_EXPANSION_PATTERN (arg);
3825
3826           if (/* These first two lines are the `non-type' bit.  */
3827               !TYPE_P (arg)
3828               && TREE_CODE (arg) != TEMPLATE_DECL
3829               /* This next line is the `argument expression is not just a
3830                  simple identifier' condition and also the `specialized
3831                  non-type argument' bit.  */
3832               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
3833             {
3834               if ((!packed_args && tpd.arg_uses_template_parms[i])
3835                   || (packed_args && uses_template_parms (arg)))
3836                 error ("template argument %qE involves template parameter(s)",
3837                        arg);
3838               else 
3839                 {
3840                   /* Look at the corresponding template parameter,
3841                      marking which template parameters its type depends
3842                      upon.  */
3843                   tree type = TREE_TYPE (parm);
3844
3845                   if (!tpd2.parms)
3846                     {
3847                       /* We haven't yet initialized TPD2.  Do so now.  */
3848                       tpd2.arg_uses_template_parms 
3849                         = (int *) alloca (sizeof (int) * nargs);
3850                       /* The number of parameters here is the number in the
3851                          main template, which, as checked in the assertion
3852                          above, is NARGS.  */
3853                       tpd2.parms = (int *) alloca (sizeof (int) * nargs);
3854                       tpd2.level = 
3855                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
3856                     }
3857
3858                   /* Mark the template parameters.  But this time, we're
3859                      looking for the template parameters of the main
3860                      template, not in the specialization.  */
3861                   tpd2.current_arg = i;
3862                   tpd2.arg_uses_template_parms[i] = 0;
3863                   memset (tpd2.parms, 0, sizeof (int) * nargs);
3864                   for_each_template_parm (type,
3865                                           &mark_template_parm,
3866                                           &tpd2,
3867                                           NULL,
3868                                           /*include_nondeduced_p=*/false);
3869
3870                   if (tpd2.arg_uses_template_parms [i])
3871                     {
3872                       /* The type depended on some template parameters.
3873                          If they are fully specialized in the
3874                          specialization, that's OK.  */
3875                       int j;
3876                       for (j = 0; j < nargs; ++j)
3877                         if (tpd2.parms[j] != 0
3878                             && tpd.arg_uses_template_parms [j])
3879                           {
3880                             error ("type %qT of template argument %qE depends "
3881                                    "on template parameter(s)", 
3882                                    type,
3883                                    arg);
3884                             break;
3885                           }
3886                     }
3887                 }
3888             }
3889         }
3890     }
3891
3892   /* We should only get here once.  */
3893   gcc_assert (!COMPLETE_TYPE_P (type));
3894
3895   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
3896     = tree_cons (specargs, inner_parms,
3897                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
3898   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
3899   return decl;
3900 }
3901
3902 /* Check that a template declaration's use of default arguments and
3903    parameter packs is not invalid.  Here, PARMS are the template
3904    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
3905    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
3906    specialization.
3907    
3908
3909    IS_FRIEND_DECL is nonzero if DECL is a friend function template
3910    declaration (but not a definition); 1 indicates a declaration, 2
3911    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
3912    emitted for extraneous default arguments.
3913
3914    Returns TRUE if there were no errors found, FALSE otherwise. */
3915
3916 bool
3917 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
3918                          int is_partial, int is_friend_decl)
3919 {
3920   const char *msg;
3921   int last_level_to_check;
3922   tree parm_level;
3923   bool no_errors = true;
3924
3925   /* [temp.param]
3926
3927      A default template-argument shall not be specified in a
3928      function template declaration or a function template definition, nor
3929      in the template-parameter-list of the definition of a member of a
3930      class template.  */
3931
3932   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
3933     /* You can't have a function template declaration in a local
3934        scope, nor you can you define a member of a class template in a
3935        local scope.  */
3936     return true;
3937
3938   if (current_class_type
3939       && !TYPE_BEING_DEFINED (current_class_type)
3940       && DECL_LANG_SPECIFIC (decl)
3941       && DECL_DECLARES_FUNCTION_P (decl)
3942       /* If this is either a friend defined in the scope of the class
3943          or a member function.  */
3944       && (DECL_FUNCTION_MEMBER_P (decl)
3945           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
3946           : DECL_FRIEND_CONTEXT (decl)
3947           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
3948           : false)
3949       /* And, if it was a member function, it really was defined in
3950          the scope of the class.  */
3951       && (!DECL_FUNCTION_MEMBER_P (decl)
3952           || DECL_INITIALIZED_IN_CLASS_P (decl)))
3953     /* We already checked these parameters when the template was
3954        declared, so there's no need to do it again now.  This function
3955        was defined in class scope, but we're processing it's body now
3956        that the class is complete.  */
3957     return true;
3958
3959   /* Core issue 226 (C++0x only): the following only applies to class
3960      templates.  */
3961   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
3962     {
3963       /* [temp.param]
3964
3965          If a template-parameter has a default template-argument, all
3966          subsequent template-parameters shall have a default
3967          template-argument supplied.  */
3968       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
3969         {
3970           tree inner_parms = TREE_VALUE (parm_level);
3971           int ntparms = TREE_VEC_LENGTH (inner_parms);
3972           int seen_def_arg_p = 0;
3973           int i;
3974
3975           for (i = 0; i < ntparms; ++i)
3976             {
3977               tree parm = TREE_VEC_ELT (inner_parms, i);
3978
3979               if (parm == error_mark_node)
3980                 continue;
3981
3982               if (TREE_PURPOSE (parm))
3983                 seen_def_arg_p = 1;
3984               else if (seen_def_arg_p
3985                        && !template_parameter_pack_p (TREE_VALUE (parm)))
3986                 {
3987                   error ("no default argument for %qD", TREE_VALUE (parm));
3988                   /* For better subsequent error-recovery, we indicate that
3989                      there should have been a default argument.  */
3990                   TREE_PURPOSE (parm) = error_mark_node;
3991                   no_errors = false;
3992                 }
3993               else if (is_primary
3994                        && !is_partial
3995                        && !is_friend_decl
3996                        /* Don't complain about an enclosing partial
3997                           specialization.  */
3998                        && parm_level == parms
3999                        && TREE_CODE (decl) == TYPE_DECL
4000                        && i < ntparms - 1
4001                        && template_parameter_pack_p (TREE_VALUE (parm)))
4002                 {
4003                   /* A primary class template can only have one
4004                      parameter pack, at the end of the template
4005                      parameter list.  */
4006
4007                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
4008                     error ("parameter pack %qE must be at the end of the"
4009                            " template parameter list", TREE_VALUE (parm));
4010                   else
4011                     error ("parameter pack %qT must be at the end of the"
4012                            " template parameter list", 
4013                            TREE_TYPE (TREE_VALUE (parm)));
4014
4015                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
4016                     = error_mark_node;
4017                   no_errors = false;
4018                 }
4019             }
4020         }
4021     }
4022
4023   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
4024       || is_partial 
4025       || !is_primary
4026       || is_friend_decl)
4027     /* For an ordinary class template, default template arguments are
4028        allowed at the innermost level, e.g.:
4029          template <class T = int>
4030          struct S {};
4031        but, in a partial specialization, they're not allowed even
4032        there, as we have in [temp.class.spec]:
4033
4034          The template parameter list of a specialization shall not
4035          contain default template argument values.
4036
4037        So, for a partial specialization, or for a function template
4038        (in C++98/C++03), we look at all of them.  */
4039     ;
4040   else
4041     /* But, for a primary class template that is not a partial
4042        specialization we look at all template parameters except the
4043        innermost ones.  */
4044     parms = TREE_CHAIN (parms);
4045
4046   /* Figure out what error message to issue.  */
4047   if (is_friend_decl == 2)
4048     msg = "default template arguments may not be used in function template friend re-declaration";
4049   else if (is_friend_decl)
4050     msg = "default template arguments may not be used in function template friend declarations";
4051   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
4052     msg = ("default template arguments may not be used in function templates "
4053            "without -std=c++0x or -std=gnu++0x");
4054   else if (is_partial)
4055     msg = "default template arguments may not be used in partial specializations";
4056   else
4057     msg = "default argument for template parameter for class enclosing %qD";
4058
4059   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
4060     /* If we're inside a class definition, there's no need to
4061        examine the parameters to the class itself.  On the one
4062        hand, they will be checked when the class is defined, and,
4063        on the other, default arguments are valid in things like:
4064          template <class T = double>
4065          struct S { template <class U> void f(U); };
4066        Here the default argument for `S' has no bearing on the
4067        declaration of `f'.  */
4068     last_level_to_check = template_class_depth (current_class_type) + 1;
4069   else
4070     /* Check everything.  */
4071     last_level_to_check = 0;
4072
4073   for (parm_level = parms;
4074        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
4075        parm_level = TREE_CHAIN (parm_level))
4076     {
4077       tree inner_parms = TREE_VALUE (parm_level);
4078       int i;
4079       int ntparms;
4080
4081       ntparms = TREE_VEC_LENGTH (inner_parms);
4082       for (i = 0; i < ntparms; ++i)
4083         {
4084           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
4085             continue;
4086
4087           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
4088             {
4089               if (msg)
4090                 {
4091                   no_errors = false;
4092                   if (is_friend_decl == 2)
4093                     return no_errors;
4094
4095                   error (msg, decl);
4096                   msg = 0;
4097                 }
4098
4099               /* Clear out the default argument so that we are not
4100                  confused later.  */
4101               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
4102             }
4103         }
4104
4105       /* At this point, if we're still interested in issuing messages,
4106          they must apply to classes surrounding the object declared.  */
4107       if (msg)
4108         msg = "default argument for template parameter for class enclosing %qD";
4109     }
4110
4111   return no_errors;
4112 }
4113
4114 /* Worker for push_template_decl_real, called via
4115    for_each_template_parm.  DATA is really an int, indicating the
4116    level of the parameters we are interested in.  If T is a template
4117    parameter of that level, return nonzero.  */
4118
4119 static int
4120 template_parm_this_level_p (tree t, void* data)
4121 {
4122   int this_level = *(int *)data;
4123   int level;
4124
4125   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4126     level = TEMPLATE_PARM_LEVEL (t);
4127   else
4128     level = TEMPLATE_TYPE_LEVEL (t);
4129   return level == this_level;
4130 }
4131
4132 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
4133    parameters given by current_template_args, or reuses a
4134    previously existing one, if appropriate.  Returns the DECL, or an
4135    equivalent one, if it is replaced via a call to duplicate_decls.
4136
4137    If IS_FRIEND is true, DECL is a friend declaration.  */
4138
4139 tree
4140 push_template_decl_real (tree decl, bool is_friend)
4141 {
4142   tree tmpl;
4143   tree args;
4144   tree info;
4145   tree ctx;
4146   int primary;
4147   int is_partial;
4148   int new_template_p = 0;
4149   /* True if the template is a member template, in the sense of
4150      [temp.mem].  */
4151   bool member_template_p = false;
4152
4153   if (decl == error_mark_node || !current_template_parms)
4154     return error_mark_node;
4155
4156   /* See if this is a partial specialization.  */
4157   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
4158                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
4159                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
4160
4161   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
4162     is_friend = true;
4163
4164   if (is_friend)
4165     /* For a friend, we want the context of the friend function, not
4166        the type of which it is a friend.  */
4167     ctx = DECL_CONTEXT (decl);
4168   else if (CP_DECL_CONTEXT (decl)
4169            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
4170     /* In the case of a virtual function, we want the class in which
4171        it is defined.  */
4172     ctx = CP_DECL_CONTEXT (decl);
4173   else
4174     /* Otherwise, if we're currently defining some class, the DECL
4175        is assumed to be a member of the class.  */
4176     ctx = current_scope ();
4177
4178   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
4179     ctx = NULL_TREE;
4180
4181   if (!DECL_CONTEXT (decl))
4182     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4183
4184   /* See if this is a primary template.  */
4185   if (is_friend && ctx)
4186     /* A friend template that specifies a class context, i.e.
4187          template <typename T> friend void A<T>::f();
4188        is not primary.  */
4189     primary = 0;
4190   else
4191     primary = template_parm_scope_p ();
4192
4193   if (primary)
4194     {
4195       if (DECL_CLASS_SCOPE_P (decl))
4196         member_template_p = true;
4197       if (TREE_CODE (decl) == TYPE_DECL
4198           && ANON_AGGRNAME_P (DECL_NAME (decl)))
4199         {
4200           error ("template class without a name");
4201           return error_mark_node;
4202         }
4203       else if (TREE_CODE (decl) == FUNCTION_DECL)
4204         {
4205           if (DECL_DESTRUCTOR_P (decl))
4206             {
4207               /* [temp.mem]
4208
4209                  A destructor shall not be a member template.  */
4210               error ("destructor %qD declared as member template", decl);
4211               return error_mark_node;
4212             }
4213           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
4214               && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
4215                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
4216                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
4217                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
4218                       == void_list_node)))
4219             {
4220               /* [basic.stc.dynamic.allocation]
4221
4222                  An allocation function can be a function
4223                  template. ... Template allocation functions shall
4224                  have two or more parameters.  */
4225               error ("invalid template declaration of %qD", decl);
4226               return error_mark_node;
4227             }
4228         }
4229       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4230                && CLASS_TYPE_P (TREE_TYPE (decl)))
4231         /* OK */;
4232       else
4233         {
4234           error ("template declaration of %q#D", decl);
4235           return error_mark_node;
4236         }
4237     }
4238
4239   /* Check to see that the rules regarding the use of default
4240      arguments are not being violated.  */
4241   check_default_tmpl_args (decl, current_template_parms,
4242                            primary, is_partial, /*is_friend_decl=*/0);
4243
4244   /* Ensure that there are no parameter packs in the type of this
4245      declaration that have not been expanded.  */
4246   if (TREE_CODE (decl) == FUNCTION_DECL)
4247     {
4248       /* Check each of the arguments individually to see if there are
4249          any bare parameter packs.  */
4250       tree type = TREE_TYPE (decl);
4251       tree arg = DECL_ARGUMENTS (decl);
4252       tree argtype = TYPE_ARG_TYPES (type);
4253
4254       while (arg && argtype)
4255         {
4256           if (!FUNCTION_PARAMETER_PACK_P (arg)
4257               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
4258             {
4259             /* This is a PARM_DECL that contains unexpanded parameter
4260                packs. We have already complained about this in the
4261                check_for_bare_parameter_packs call, so just replace
4262                these types with ERROR_MARK_NODE.  */
4263               TREE_TYPE (arg) = error_mark_node;
4264               TREE_VALUE (argtype) = error_mark_node;
4265             }
4266
4267           arg = TREE_CHAIN (arg);
4268           argtype = TREE_CHAIN (argtype);
4269         }
4270
4271       /* Check for bare parameter packs in the return type and the
4272          exception specifiers.  */
4273       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
4274         /* Errors were already issued, set return type to int
4275            as the frontend doesn't expect error_mark_node as
4276            the return type.  */
4277         TREE_TYPE (type) = integer_type_node;
4278       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
4279         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
4280     }
4281   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
4282     {
4283       TREE_TYPE (decl) = error_mark_node;
4284       return error_mark_node;
4285     }
4286
4287   if (is_partial)
4288     return process_partial_specialization (decl);
4289
4290   args = current_template_args ();
4291
4292   if (!ctx
4293       || TREE_CODE (ctx) == FUNCTION_DECL
4294       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
4295       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
4296     {
4297       if (DECL_LANG_SPECIFIC (decl)
4298           && DECL_TEMPLATE_INFO (decl)
4299           && DECL_TI_TEMPLATE (decl))
4300         tmpl = DECL_TI_TEMPLATE (decl);
4301       /* If DECL is a TYPE_DECL for a class-template, then there won't
4302          be DECL_LANG_SPECIFIC.  The information equivalent to
4303          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
4304       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4305                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
4306                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
4307         {
4308           /* Since a template declaration already existed for this
4309              class-type, we must be redeclaring it here.  Make sure
4310              that the redeclaration is valid.  */
4311           redeclare_class_template (TREE_TYPE (decl),
4312                                     current_template_parms);
4313           /* We don't need to create a new TEMPLATE_DECL; just use the
4314              one we already had.  */
4315           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
4316         }
4317       else
4318         {
4319           tmpl = build_template_decl (decl, current_template_parms,
4320                                       member_template_p);
4321           new_template_p = 1;
4322
4323           if (DECL_LANG_SPECIFIC (decl)
4324               && DECL_TEMPLATE_SPECIALIZATION (decl))
4325             {
4326               /* A specialization of a member template of a template
4327                  class.  */
4328               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4329               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
4330               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
4331             }
4332         }
4333     }
4334   else
4335     {
4336       tree a, t, current, parms;
4337       int i;
4338       tree tinfo = get_template_info (decl);
4339
4340       if (!tinfo)
4341         {
4342           error ("template definition of non-template %q#D", decl);
4343           return error_mark_node;
4344         }
4345
4346       tmpl = TI_TEMPLATE (tinfo);
4347
4348       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
4349           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
4350           && DECL_TEMPLATE_SPECIALIZATION (decl)
4351           && DECL_MEMBER_TEMPLATE_P (tmpl))
4352         {
4353           tree new_tmpl;
4354
4355           /* The declaration is a specialization of a member
4356              template, declared outside the class.  Therefore, the
4357              innermost template arguments will be NULL, so we
4358              replace them with the arguments determined by the
4359              earlier call to check_explicit_specialization.  */
4360           args = DECL_TI_ARGS (decl);
4361
4362           new_tmpl
4363             = build_template_decl (decl, current_template_parms,
4364                                    member_template_p);
4365           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4366           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4367           DECL_TI_TEMPLATE (decl) = new_tmpl;
4368           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4369           DECL_TEMPLATE_INFO (new_tmpl)
4370             = build_template_info (tmpl, args);
4371
4372           register_specialization (new_tmpl,
4373                                    most_general_template (tmpl),
4374                                    args,
4375                                    is_friend, 0);
4376           return decl;
4377         }
4378
4379       /* Make sure the template headers we got make sense.  */
4380
4381       parms = DECL_TEMPLATE_PARMS (tmpl);
4382       i = TMPL_PARMS_DEPTH (parms);
4383       if (TMPL_ARGS_DEPTH (args) != i)
4384         {
4385           error ("expected %d levels of template parms for %q#D, got %d",
4386                  i, decl, TMPL_ARGS_DEPTH (args));
4387         }
4388       else
4389         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4390           {
4391             a = TMPL_ARGS_LEVEL (args, i);
4392             t = INNERMOST_TEMPLATE_PARMS (parms);
4393
4394             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4395               {
4396                 if (current == decl)
4397                   error ("got %d template parameters for %q#D",
4398                          TREE_VEC_LENGTH (a), decl);
4399                 else
4400                   error ("got %d template parameters for %q#T",
4401                          TREE_VEC_LENGTH (a), current);
4402                 error ("  but %d required", TREE_VEC_LENGTH (t));
4403                 return error_mark_node;
4404               }
4405
4406             if (current == decl)
4407               current = ctx;
4408             else
4409               current = (TYPE_P (current)
4410                          ? TYPE_CONTEXT (current)
4411                          : DECL_CONTEXT (current));
4412           }
4413
4414       /* Check that the parms are used in the appropriate qualifying scopes
4415          in the declarator.  */
4416       if (!comp_template_args
4417           (TI_ARGS (tinfo),
4418            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4419         {
4420           error ("\
4421 template arguments to %qD do not match original template %qD",
4422                  decl, DECL_TEMPLATE_RESULT (tmpl));
4423           if (!uses_template_parms (TI_ARGS (tinfo)))
4424             inform (input_location, "use template<> for an explicit specialization");
4425           /* Avoid crash in import_export_decl.  */
4426           DECL_INTERFACE_KNOWN (decl) = 1;
4427           return error_mark_node;
4428         }
4429     }
4430
4431   DECL_TEMPLATE_RESULT (tmpl) = decl;
4432   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4433
4434   /* Push template declarations for global functions and types.  Note
4435      that we do not try to push a global template friend declared in a
4436      template class; such a thing may well depend on the template
4437      parameters of the class.  */
4438   if (new_template_p && !ctx
4439       && !(is_friend && template_class_depth (current_class_type) > 0))
4440     {
4441       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4442       if (tmpl == error_mark_node)
4443         return error_mark_node;
4444
4445       /* Hide template friend classes that haven't been declared yet.  */
4446       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4447         {
4448           DECL_ANTICIPATED (tmpl) = 1;
4449           DECL_FRIEND_P (tmpl) = 1;
4450         }
4451     }
4452
4453   if (primary)
4454     {
4455       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4456       int i;
4457
4458       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4459       if (DECL_CONV_FN_P (tmpl))
4460         {
4461           int depth = TMPL_PARMS_DEPTH (parms);
4462
4463           /* It is a conversion operator. See if the type converted to
4464              depends on innermost template operands.  */
4465
4466           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4467                                          depth))
4468             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4469         }
4470
4471       /* Give template template parms a DECL_CONTEXT of the template
4472          for which they are a parameter.  */
4473       parms = INNERMOST_TEMPLATE_PARMS (parms);
4474       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
4475         {
4476           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4477           if (TREE_CODE (parm) == TEMPLATE_DECL)
4478             DECL_CONTEXT (parm) = tmpl;
4479         }
4480     }
4481
4482   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
4483      back to its most general template.  If TMPL is a specialization,
4484      ARGS may only have the innermost set of arguments.  Add the missing
4485      argument levels if necessary.  */
4486   if (DECL_TEMPLATE_INFO (tmpl))
4487     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
4488
4489   info = build_template_info (tmpl, args);
4490
4491   if (DECL_IMPLICIT_TYPEDEF_P (decl))
4492     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
4493   else if (DECL_LANG_SPECIFIC (decl))
4494     DECL_TEMPLATE_INFO (decl) = info;
4495
4496   return DECL_TEMPLATE_RESULT (tmpl);
4497 }
4498
4499 tree
4500 push_template_decl (tree decl)
4501 {
4502   return push_template_decl_real (decl, false);
4503 }
4504
4505 /* Called when a class template TYPE is redeclared with the indicated
4506    template PARMS, e.g.:
4507
4508      template <class T> struct S;
4509      template <class T> struct S {};  */
4510
4511 bool
4512 redeclare_class_template (tree type, tree parms)
4513 {
4514   tree tmpl;
4515   tree tmpl_parms;
4516   int i;
4517
4518   if (!TYPE_TEMPLATE_INFO (type))
4519     {
4520       error ("%qT is not a template type", type);
4521       return false;
4522     }
4523
4524   tmpl = TYPE_TI_TEMPLATE (type);
4525   if (!PRIMARY_TEMPLATE_P (tmpl))
4526     /* The type is nested in some template class.  Nothing to worry
4527        about here; there are no new template parameters for the nested
4528        type.  */
4529     return true;
4530
4531   if (!parms)
4532     {
4533       error ("template specifiers not specified in declaration of %qD",
4534              tmpl);
4535       return false;
4536     }
4537
4538   parms = INNERMOST_TEMPLATE_PARMS (parms);
4539   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
4540
4541   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
4542     {
4543       error ("redeclared with %d template parameter(s)", 
4544              TREE_VEC_LENGTH (parms));
4545       inform (input_location, "previous declaration %q+D used %d template parameter(s)", 
4546              tmpl, TREE_VEC_LENGTH (tmpl_parms));
4547       return false;
4548     }
4549
4550   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
4551     {
4552       tree tmpl_parm;
4553       tree parm;
4554       tree tmpl_default;
4555       tree parm_default;
4556
4557       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
4558           || TREE_VEC_ELT (parms, i) == error_mark_node)
4559         continue;
4560
4561       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
4562       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4563       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
4564       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
4565
4566       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
4567          TEMPLATE_DECL.  */
4568       if (tmpl_parm != error_mark_node
4569           && (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
4570               || (TREE_CODE (tmpl_parm) != TYPE_DECL
4571                   && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
4572               || (TREE_CODE (tmpl_parm) != PARM_DECL
4573                   && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
4574                       != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
4575               || (TREE_CODE (tmpl_parm) == PARM_DECL
4576                   && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
4577                       != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))))))
4578         {
4579           error ("template parameter %q+#D", tmpl_parm);
4580           error ("redeclared here as %q#D", parm);
4581           return false;
4582         }
4583
4584       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
4585         {
4586           /* We have in [temp.param]:
4587
4588              A template-parameter may not be given default arguments
4589              by two different declarations in the same scope.  */
4590           error_at (input_location, "redefinition of default argument for %q#D", parm);
4591           inform (DECL_SOURCE_LOCATION (tmpl_parm),
4592                   "original definition appeared here");
4593           return false;
4594         }
4595
4596       if (parm_default != NULL_TREE)
4597         /* Update the previous template parameters (which are the ones
4598            that will really count) with the new default value.  */
4599         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
4600       else if (tmpl_default != NULL_TREE)
4601         /* Update the new parameters, too; they'll be used as the
4602            parameters for any members.  */
4603         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
4604     }
4605
4606     return true;
4607 }
4608
4609 /* Simplify EXPR if it is a non-dependent expression.  Returns the
4610    (possibly simplified) expression.  */
4611
4612 tree
4613 fold_non_dependent_expr (tree expr)
4614 {
4615   if (expr == NULL_TREE)
4616     return NULL_TREE;
4617
4618   /* If we're in a template, but EXPR isn't value dependent, simplify
4619      it.  We're supposed to treat:
4620
4621        template <typename T> void f(T[1 + 1]);
4622        template <typename T> void f(T[2]);
4623
4624      as two declarations of the same function, for example.  */
4625   if (processing_template_decl
4626       && !type_dependent_expression_p (expr)
4627       && !value_dependent_expression_p (expr))
4628     {
4629       HOST_WIDE_INT saved_processing_template_decl;
4630
4631       saved_processing_template_decl = processing_template_decl;
4632       processing_template_decl = 0;
4633       expr = tsubst_copy_and_build (expr,
4634                                     /*args=*/NULL_TREE,
4635                                     tf_error,
4636                                     /*in_decl=*/NULL_TREE,
4637                                     /*function_p=*/false,
4638                                     /*integral_constant_expression_p=*/true);
4639       processing_template_decl = saved_processing_template_decl;
4640     }
4641   return expr;
4642 }
4643
4644 /* EXPR is an expression which is used in a constant-expression context.
4645    For instance, it could be a VAR_DECL with a constant initializer.
4646    Extract the innermost constant expression.
4647
4648    This is basically a more powerful version of
4649    integral_constant_value, which can be used also in templates where
4650    initializers can maintain a syntactic rather than semantic form
4651    (even if they are non-dependent, for access-checking purposes).  */
4652
4653 static tree
4654 fold_decl_constant_value (tree expr)
4655 {
4656   tree const_expr = expr;
4657   do
4658     {
4659       expr = fold_non_dependent_expr (const_expr);
4660       const_expr = integral_constant_value (expr);
4661     }
4662   while (expr != const_expr);
4663
4664   return expr;
4665 }
4666
4667 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
4668    must be a function or a pointer-to-function type, as specified
4669    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
4670    and check that the resulting function has external linkage.  */
4671
4672 static tree
4673 convert_nontype_argument_function (tree type, tree expr)
4674 {
4675   tree fns = expr;
4676   tree fn, fn_no_ptr;
4677
4678   fn = instantiate_type (type, fns, tf_none);
4679   if (fn == error_mark_node)
4680     return error_mark_node;
4681
4682   fn_no_ptr = fn;
4683   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
4684     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
4685   if (TREE_CODE (fn_no_ptr) == BASELINK)
4686     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
4687  
4688   /* [temp.arg.nontype]/1
4689
4690      A template-argument for a non-type, non-template template-parameter
4691      shall be one of:
4692      [...]
4693      -- the address of an object or function with external linkage.  */
4694   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
4695     {
4696       error ("%qE is not a valid template argument for type %qT "
4697              "because function %qD has not external linkage",
4698              expr, type, fn_no_ptr);
4699       return NULL_TREE;
4700     }
4701
4702   return fn;
4703 }
4704
4705 /* Subroutine of convert_nontype_argument.
4706    Check if EXPR of type TYPE is a valid pointer-to-member constant.
4707    Emit an error otherwise.  */
4708
4709 static bool
4710 check_valid_ptrmem_cst_expr (tree type, tree expr)
4711 {
4712   STRIP_NOPS (expr);
4713   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
4714     return true;
4715   error ("%qE is not a valid template argument for type %qT",
4716          expr, type);
4717   error ("it must be a pointer-to-member of the form `&X::Y'");
4718   return false;
4719 }
4720
4721 /* Attempt to convert the non-type template parameter EXPR to the
4722    indicated TYPE.  If the conversion is successful, return the
4723    converted value.  If the conversion is unsuccessful, return
4724    NULL_TREE if we issued an error message, or error_mark_node if we
4725    did not.  We issue error messages for out-and-out bad template
4726    parameters, but not simply because the conversion failed, since we
4727    might be just trying to do argument deduction.  Both TYPE and EXPR
4728    must be non-dependent.
4729
4730    The conversion follows the special rules described in
4731    [temp.arg.nontype], and it is much more strict than an implicit
4732    conversion.
4733
4734    This function is called twice for each template argument (see
4735    lookup_template_class for a more accurate description of this
4736    problem). This means that we need to handle expressions which
4737    are not valid in a C++ source, but can be created from the
4738    first call (for instance, casts to perform conversions). These
4739    hacks can go away after we fix the double coercion problem.  */
4740
4741 static tree
4742 convert_nontype_argument (tree type, tree expr)
4743 {
4744   tree expr_type;
4745
4746   /* Detect immediately string literals as invalid non-type argument.
4747      This special-case is not needed for correctness (we would easily
4748      catch this later), but only to provide better diagnostic for this
4749      common user mistake. As suggested by DR 100, we do not mention
4750      linkage issues in the diagnostic as this is not the point.  */
4751   if (TREE_CODE (expr) == STRING_CST)
4752     {
4753       error ("%qE is not a valid template argument for type %qT "
4754              "because string literals can never be used in this context",
4755              expr, type);
4756       return NULL_TREE;
4757     }
4758
4759   /* If we are in a template, EXPR may be non-dependent, but still
4760      have a syntactic, rather than semantic, form.  For example, EXPR
4761      might be a SCOPE_REF, rather than the VAR_DECL to which the
4762      SCOPE_REF refers.  Preserving the qualifying scope is necessary
4763      so that access checking can be performed when the template is
4764      instantiated -- but here we need the resolved form so that we can
4765      convert the argument.  */
4766   expr = fold_non_dependent_expr (expr);
4767   if (error_operand_p (expr))
4768     return error_mark_node;
4769   expr_type = TREE_TYPE (expr);
4770
4771   /* HACK: Due to double coercion, we can get a
4772      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
4773      which is the tree that we built on the first call (see
4774      below when coercing to reference to object or to reference to
4775      function). We just strip everything and get to the arg.
4776      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
4777      for examples.  */
4778   if (TREE_CODE (expr) == NOP_EXPR)
4779     {
4780       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
4781         {
4782           /* ??? Maybe we could use convert_from_reference here, but we
4783              would need to relax its constraints because the NOP_EXPR
4784              could actually change the type to something more cv-qualified,
4785              and this is not folded by convert_from_reference.  */
4786           tree addr = TREE_OPERAND (expr, 0);
4787           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
4788           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
4789           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
4790           gcc_assert (same_type_ignoring_top_level_qualifiers_p
4791                       (TREE_TYPE (expr_type),
4792                        TREE_TYPE (TREE_TYPE (addr))));
4793
4794           expr = TREE_OPERAND (addr, 0);
4795           expr_type = TREE_TYPE (expr);
4796         }
4797
4798       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
4799          parameter is a pointer to object, through decay and
4800          qualification conversion. Let's strip everything.  */
4801       else if (TYPE_PTROBV_P (type))
4802         {
4803           STRIP_NOPS (expr);
4804           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
4805           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
4806           /* Skip the ADDR_EXPR only if it is part of the decay for
4807              an array. Otherwise, it is part of the original argument
4808              in the source code.  */
4809           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
4810             expr = TREE_OPERAND (expr, 0);
4811           expr_type = TREE_TYPE (expr);
4812         }
4813     }
4814
4815   /* [temp.arg.nontype]/5, bullet 1
4816
4817      For a non-type template-parameter of integral or enumeration type,
4818      integral promotions (_conv.prom_) and integral conversions
4819      (_conv.integral_) are applied.  */
4820   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
4821     {
4822       if (!INTEGRAL_OR_ENUMERATION_TYPE_P (expr_type))
4823         return error_mark_node;
4824
4825       expr = fold_decl_constant_value (expr);
4826       /* Notice that there are constant expressions like '4 % 0' which
4827          do not fold into integer constants.  */
4828       if (TREE_CODE (expr) != INTEGER_CST)
4829         {
4830           error ("%qE is not a valid template argument for type %qT "
4831                  "because it is a non-constant expression", expr, type);
4832           return NULL_TREE;
4833         }
4834
4835       /* At this point, an implicit conversion does what we want,
4836          because we already know that the expression is of integral
4837          type.  */
4838       expr = ocp_convert (type, expr, CONV_IMPLICIT, LOOKUP_PROTECT);
4839       if (expr == error_mark_node)
4840         return error_mark_node;
4841
4842       /* Conversion was allowed: fold it to a bare integer constant.  */
4843       expr = fold (expr);
4844     }
4845   /* [temp.arg.nontype]/5, bullet 2
4846
4847      For a non-type template-parameter of type pointer to object,
4848      qualification conversions (_conv.qual_) and the array-to-pointer
4849      conversion (_conv.array_) are applied.  */
4850   else if (TYPE_PTROBV_P (type))
4851     {
4852       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
4853
4854          A template-argument for a non-type, non-template template-parameter
4855          shall be one of: [...]
4856
4857          -- the name of a non-type template-parameter;
4858          -- the address of an object or function with external linkage, [...]
4859             expressed as "& id-expression" where the & is optional if the name
4860             refers to a function or array, or if the corresponding
4861             template-parameter is a reference.
4862
4863         Here, we do not care about functions, as they are invalid anyway
4864         for a parameter of type pointer-to-object.  */
4865
4866       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
4867         /* Non-type template parameters are OK.  */
4868         ;
4869       else if (TREE_CODE (expr) != ADDR_EXPR
4870                && TREE_CODE (expr_type) != ARRAY_TYPE)
4871         {
4872           if (TREE_CODE (expr) == VAR_DECL)
4873             {
4874               error ("%qD is not a valid template argument "
4875                      "because %qD is a variable, not the address of "
4876                      "a variable",
4877                      expr, expr);
4878               return NULL_TREE;
4879             }
4880           /* Other values, like integer constants, might be valid
4881              non-type arguments of some other type.  */
4882           return error_mark_node;
4883         }
4884       else
4885         {
4886           tree decl;
4887
4888           decl = ((TREE_CODE (expr) == ADDR_EXPR)
4889                   ? TREE_OPERAND (expr, 0) : expr);
4890           if (TREE_CODE (decl) != VAR_DECL)
4891             {
4892               error ("%qE is not a valid template argument of type %qT "
4893                      "because %qE is not a variable",
4894                      expr, type, decl);
4895               return NULL_TREE;
4896             }
4897           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
4898             {
4899               error ("%qE is not a valid template argument of type %qT "
4900                      "because %qD does not have external linkage",
4901                      expr, type, decl);
4902               return NULL_TREE;
4903             }
4904         }
4905
4906       expr = decay_conversion (expr);
4907       if (expr == error_mark_node)
4908         return error_mark_node;
4909
4910       expr = perform_qualification_conversions (type, expr);
4911       if (expr == error_mark_node)
4912         return error_mark_node;
4913     }
4914   /* [temp.arg.nontype]/5, bullet 3
4915
4916      For a non-type template-parameter of type reference to object, no
4917      conversions apply. The type referred to by the reference may be more
4918      cv-qualified than the (otherwise identical) type of the
4919      template-argument. The template-parameter is bound directly to the
4920      template-argument, which must be an lvalue.  */
4921   else if (TYPE_REF_OBJ_P (type))
4922     {
4923       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
4924                                                       expr_type))
4925         return error_mark_node;
4926
4927       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
4928         {
4929           error ("%qE is not a valid template argument for type %qT "
4930                  "because of conflicts in cv-qualification", expr, type);
4931           return NULL_TREE;
4932         }
4933
4934       if (!real_lvalue_p (expr))
4935         {
4936           error ("%qE is not a valid template argument for type %qT "
4937                  "because it is not an lvalue", expr, type);
4938           return NULL_TREE;
4939         }
4940
4941       /* [temp.arg.nontype]/1
4942
4943          A template-argument for a non-type, non-template template-parameter
4944          shall be one of: [...]
4945
4946          -- the address of an object or function with external linkage.  */
4947       if (TREE_CODE (expr) == INDIRECT_REF
4948           && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
4949         {
4950           expr = TREE_OPERAND (expr, 0);
4951           if (DECL_P (expr))
4952             {
4953               error ("%q#D is not a valid template argument for type %qT "
4954                      "because a reference variable does not have a constant "
4955                      "address", expr, type);
4956               return NULL_TREE;
4957             }
4958         }
4959
4960       if (!DECL_P (expr))
4961         {
4962           error ("%qE is not a valid template argument for type %qT "
4963                  "because it is not an object with external linkage",
4964                  expr, type);
4965           return NULL_TREE;
4966         }
4967
4968       if (!DECL_EXTERNAL_LINKAGE_P (expr))
4969         {
4970           error ("%qE is not a valid template argument for type %qT "
4971                  "because object %qD has not external linkage",
4972                  expr, type, expr);
4973           return NULL_TREE;
4974         }
4975
4976       expr = build_nop (type, build_address (expr));
4977     }
4978   /* [temp.arg.nontype]/5, bullet 4
4979
4980      For a non-type template-parameter of type pointer to function, only
4981      the function-to-pointer conversion (_conv.func_) is applied. If the
4982      template-argument represents a set of overloaded functions (or a
4983      pointer to such), the matching function is selected from the set
4984      (_over.over_).  */
4985   else if (TYPE_PTRFN_P (type))
4986     {
4987       /* If the argument is a template-id, we might not have enough
4988          context information to decay the pointer.  */
4989       if (!type_unknown_p (expr_type))
4990         {
4991           expr = decay_conversion (expr);
4992           if (expr == error_mark_node)
4993             return error_mark_node;
4994         }
4995
4996       expr = convert_nontype_argument_function (type, expr);
4997       if (!expr || expr == error_mark_node)
4998         return expr;
4999
5000       if (TREE_CODE (expr) != ADDR_EXPR)
5001         {
5002           error ("%qE is not a valid template argument for type %qT", expr, type);
5003           error ("it must be the address of a function with external linkage");
5004           return NULL_TREE;
5005         }
5006     }
5007   /* [temp.arg.nontype]/5, bullet 5
5008
5009      For a non-type template-parameter of type reference to function, no
5010      conversions apply. If the template-argument represents a set of
5011      overloaded functions, the matching function is selected from the set
5012      (_over.over_).  */
5013   else if (TYPE_REFFN_P (type))
5014     {
5015       if (TREE_CODE (expr) == ADDR_EXPR)
5016         {
5017           error ("%qE is not a valid template argument for type %qT "
5018                  "because it is a pointer", expr, type);
5019           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
5020           return NULL_TREE;
5021         }
5022
5023       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
5024       if (!expr || expr == error_mark_node)
5025         return expr;
5026
5027       expr = build_nop (type, build_address (expr));
5028     }
5029   /* [temp.arg.nontype]/5, bullet 6
5030
5031      For a non-type template-parameter of type pointer to member function,
5032      no conversions apply. If the template-argument represents a set of
5033      overloaded member functions, the matching member function is selected
5034      from the set (_over.over_).  */
5035   else if (TYPE_PTRMEMFUNC_P (type))
5036     {
5037       expr = instantiate_type (type, expr, tf_none);
5038       if (expr == error_mark_node)
5039         return error_mark_node;
5040
5041       /* [temp.arg.nontype] bullet 1 says the pointer to member
5042          expression must be a pointer-to-member constant.  */
5043       if (!check_valid_ptrmem_cst_expr (type, expr))
5044         return error_mark_node;
5045
5046       /* There is no way to disable standard conversions in
5047          resolve_address_of_overloaded_function (called by
5048          instantiate_type). It is possible that the call succeeded by
5049          converting &B::I to &D::I (where B is a base of D), so we need
5050          to reject this conversion here.
5051
5052          Actually, even if there was a way to disable standard conversions,
5053          it would still be better to reject them here so that we can
5054          provide a superior diagnostic.  */
5055       if (!same_type_p (TREE_TYPE (expr), type))
5056         {
5057           /* Make sure we are just one standard conversion off.  */
5058           gcc_assert (can_convert (type, TREE_TYPE (expr)));
5059           error ("%qE is not a valid template argument for type %qT "
5060                  "because it is of type %qT", expr, type,
5061                  TREE_TYPE (expr));
5062           inform (input_location, "standard conversions are not allowed in this context");
5063           return NULL_TREE;
5064         }
5065     }
5066   /* [temp.arg.nontype]/5, bullet 7
5067
5068      For a non-type template-parameter of type pointer to data member,
5069      qualification conversions (_conv.qual_) are applied.  */
5070   else if (TYPE_PTRMEM_P (type))
5071     {
5072       /* [temp.arg.nontype] bullet 1 says the pointer to member
5073          expression must be a pointer-to-member constant.  */
5074       if (!check_valid_ptrmem_cst_expr (type, expr))
5075         return error_mark_node;
5076
5077       expr = perform_qualification_conversions (type, expr);
5078       if (expr == error_mark_node)
5079         return expr;
5080     }
5081   /* A template non-type parameter must be one of the above.  */
5082   else
5083     gcc_unreachable ();
5084
5085   /* Sanity check: did we actually convert the argument to the
5086      right type?  */
5087   gcc_assert (same_type_p (type, TREE_TYPE (expr)));
5088   return expr;
5089 }
5090
5091 /* Subroutine of coerce_template_template_parms, which returns 1 if
5092    PARM_PARM and ARG_PARM match using the rule for the template
5093    parameters of template template parameters. Both PARM and ARG are
5094    template parameters; the rest of the arguments are the same as for
5095    coerce_template_template_parms.
5096  */
5097 static int
5098 coerce_template_template_parm (tree parm,
5099                               tree arg,
5100                               tsubst_flags_t complain,
5101                               tree in_decl,
5102                               tree outer_args)
5103 {
5104   if (arg == NULL_TREE || arg == error_mark_node
5105       || parm == NULL_TREE || parm == error_mark_node)
5106     return 0;
5107   
5108   if (TREE_CODE (arg) != TREE_CODE (parm))
5109     return 0;
5110   
5111   switch (TREE_CODE (parm))
5112     {
5113     case TEMPLATE_DECL:
5114       /* We encounter instantiations of templates like
5115          template <template <template <class> class> class TT>
5116          class C;  */
5117       {
5118         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5119         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5120         
5121         if (!coerce_template_template_parms
5122             (parmparm, argparm, complain, in_decl, outer_args))
5123           return 0;
5124       }
5125       /* Fall through.  */
5126       
5127     case TYPE_DECL:
5128       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
5129           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5130         /* Argument is a parameter pack but parameter is not.  */
5131         return 0;
5132       break;
5133       
5134     case PARM_DECL:
5135       /* The tsubst call is used to handle cases such as
5136          
5137            template <int> class C {};
5138            template <class T, template <T> class TT> class D {};
5139            D<int, C> d;
5140
5141          i.e. the parameter list of TT depends on earlier parameters.  */
5142       if (!uses_template_parms (TREE_TYPE (arg))
5143           && !same_type_p
5144                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
5145                  TREE_TYPE (arg)))
5146         return 0;
5147       
5148       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
5149           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5150         /* Argument is a parameter pack but parameter is not.  */
5151         return 0;
5152       
5153       break;
5154
5155     default:
5156       gcc_unreachable ();
5157     }
5158
5159   return 1;
5160 }
5161
5162
5163 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
5164    template template parameters.  Both PARM_PARMS and ARG_PARMS are
5165    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
5166    or PARM_DECL.
5167
5168    Consider the example:
5169      template <class T> class A;
5170      template<template <class U> class TT> class B;
5171
5172    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
5173    the parameters to A, and OUTER_ARGS contains A.  */
5174
5175 static int
5176 coerce_template_template_parms (tree parm_parms,
5177                                 tree arg_parms,
5178                                 tsubst_flags_t complain,
5179                                 tree in_decl,
5180                                 tree outer_args)
5181 {
5182   int nparms, nargs, i;
5183   tree parm, arg;
5184   int variadic_p = 0;
5185
5186   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
5187   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
5188
5189   nparms = TREE_VEC_LENGTH (parm_parms);
5190   nargs = TREE_VEC_LENGTH (arg_parms);
5191
5192   /* Determine whether we have a parameter pack at the end of the
5193      template template parameter's template parameter list.  */
5194   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
5195     {
5196       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
5197       
5198       if (parm == error_mark_node)
5199         return 0;
5200
5201       switch (TREE_CODE (parm))
5202         {
5203         case TEMPLATE_DECL:
5204         case TYPE_DECL:
5205           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5206             variadic_p = 1;
5207           break;
5208           
5209         case PARM_DECL:
5210           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5211             variadic_p = 1;
5212           break;
5213           
5214         default:
5215           gcc_unreachable ();
5216         }
5217     }
5218  
5219   if (nargs != nparms
5220       && !(variadic_p && nargs >= nparms - 1))
5221     return 0;
5222
5223   /* Check all of the template parameters except the parameter pack at
5224      the end (if any).  */
5225   for (i = 0; i < nparms - variadic_p; ++i)
5226     {
5227       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
5228           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5229         continue;
5230
5231       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5232       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5233
5234       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5235                                           outer_args))
5236         return 0;
5237
5238     }
5239
5240   if (variadic_p)
5241     {
5242       /* Check each of the template parameters in the template
5243          argument against the template parameter pack at the end of
5244          the template template parameter.  */
5245       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
5246         return 0;
5247
5248       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5249
5250       for (; i < nargs; ++i)
5251         {
5252           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5253             continue;
5254  
5255           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5256  
5257           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5258                                               outer_args))
5259             return 0;
5260         }
5261     }
5262
5263   return 1;
5264 }
5265
5266 /* Verifies that the deduced template arguments (in TARGS) for the
5267    template template parameters (in TPARMS) represent valid bindings,
5268    by comparing the template parameter list of each template argument
5269    to the template parameter list of its corresponding template
5270    template parameter, in accordance with DR150. This
5271    routine can only be called after all template arguments have been
5272    deduced. It will return TRUE if all of the template template
5273    parameter bindings are okay, FALSE otherwise.  */
5274 bool 
5275 template_template_parm_bindings_ok_p (tree tparms, tree targs)
5276 {
5277   int i, ntparms = TREE_VEC_LENGTH (tparms);
5278   bool ret = true;
5279
5280   /* We're dealing with template parms in this process.  */
5281   ++processing_template_decl;
5282
5283   targs = INNERMOST_TEMPLATE_ARGS (targs);
5284
5285   for (i = 0; i < ntparms; ++i)
5286     {
5287       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
5288       tree targ = TREE_VEC_ELT (targs, i);
5289
5290       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
5291         {
5292           tree packed_args = NULL_TREE;
5293           int idx, len = 1;
5294
5295           if (ARGUMENT_PACK_P (targ))
5296             {
5297               /* Look inside the argument pack.  */
5298               packed_args = ARGUMENT_PACK_ARGS (targ);
5299               len = TREE_VEC_LENGTH (packed_args);
5300             }
5301
5302           for (idx = 0; idx < len; ++idx)
5303             {
5304               tree targ_parms = NULL_TREE;
5305
5306               if (packed_args)
5307                 /* Extract the next argument from the argument
5308                    pack.  */
5309                 targ = TREE_VEC_ELT (packed_args, idx);
5310
5311               if (PACK_EXPANSION_P (targ))
5312                 /* Look at the pattern of the pack expansion.  */
5313                 targ = PACK_EXPANSION_PATTERN (targ);
5314
5315               /* Extract the template parameters from the template
5316                  argument.  */
5317               if (TREE_CODE (targ) == TEMPLATE_DECL)
5318                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
5319               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
5320                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
5321
5322               /* Verify that we can coerce the template template
5323                  parameters from the template argument to the template
5324                  parameter.  This requires an exact match.  */
5325               if (targ_parms
5326                   && !coerce_template_template_parms
5327                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
5328                         targ_parms,
5329                         tf_none,
5330                         tparm,
5331                         targs))
5332                 {
5333                   ret = false;
5334                   goto out;
5335                 }
5336             }
5337         }
5338     }
5339
5340  out:
5341
5342   --processing_template_decl;
5343   return ret;
5344 }
5345
5346 /* Convert the indicated template ARG as necessary to match the
5347    indicated template PARM.  Returns the converted ARG, or
5348    error_mark_node if the conversion was unsuccessful.  Error and
5349    warning messages are issued under control of COMPLAIN.  This
5350    conversion is for the Ith parameter in the parameter list.  ARGS is
5351    the full set of template arguments deduced so far.  */
5352
5353 static tree
5354 convert_template_argument (tree parm,
5355                            tree arg,
5356                            tree args,
5357                            tsubst_flags_t complain,
5358                            int i,
5359                            tree in_decl)
5360 {
5361   tree orig_arg;
5362   tree val;
5363   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
5364
5365   if (TREE_CODE (arg) == TREE_LIST
5366       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
5367     {
5368       /* The template argument was the name of some
5369          member function.  That's usually
5370          invalid, but static members are OK.  In any
5371          case, grab the underlying fields/functions
5372          and issue an error later if required.  */
5373       orig_arg = TREE_VALUE (arg);
5374       TREE_TYPE (arg) = unknown_type_node;
5375     }
5376
5377   orig_arg = arg;
5378
5379   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
5380   requires_type = (TREE_CODE (parm) == TYPE_DECL
5381                    || requires_tmpl_type);
5382
5383   /* When determining whether an argument pack expansion is a template,
5384      look at the pattern.  */
5385   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
5386     arg = PACK_EXPANSION_PATTERN (arg);
5387
5388   /* Deal with an injected-class-name used as a template template arg.  */
5389   if (requires_tmpl_type && CLASS_TYPE_P (arg))
5390     {
5391       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
5392       if (TREE_CODE (t) == TEMPLATE_DECL)
5393         {
5394           if (complain & tf_warning_or_error)
5395             pedwarn (input_location, OPT_pedantic, "injected-class-name %qD"
5396                      " used as template template argument", TYPE_NAME (arg));
5397           else if (flag_pedantic_errors)
5398             t = arg;
5399
5400           arg = t;
5401         }
5402     }
5403
5404   is_tmpl_type = 
5405     ((TREE_CODE (arg) == TEMPLATE_DECL
5406       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
5407      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5408      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
5409
5410   if (is_tmpl_type
5411       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5412           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
5413     arg = TYPE_STUB_DECL (arg);
5414
5415   is_type = TYPE_P (arg) || is_tmpl_type;
5416
5417   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
5418       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
5419     {
5420       permerror (input_location, "to refer to a type member of a template parameter, "
5421                  "use %<typename %E%>", orig_arg);
5422
5423       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
5424                                      TREE_OPERAND (arg, 1),
5425                                      typename_type,
5426                                      complain & tf_error);
5427       arg = orig_arg;
5428       is_type = 1;
5429     }
5430   if (is_type != requires_type)
5431     {
5432       if (in_decl)
5433         {
5434           if (complain & tf_error)
5435             {
5436               error ("type/value mismatch at argument %d in template "
5437                      "parameter list for %qD",
5438                      i + 1, in_decl);
5439               if (is_type)
5440                 error ("  expected a constant of type %qT, got %qT",
5441                        TREE_TYPE (parm),
5442                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
5443               else if (requires_tmpl_type)
5444                 error ("  expected a class template, got %qE", orig_arg);
5445               else
5446                 error ("  expected a type, got %qE", orig_arg);
5447             }
5448         }
5449       return error_mark_node;
5450     }
5451   if (is_tmpl_type ^ requires_tmpl_type)
5452     {
5453       if (in_decl && (complain & tf_error))
5454         {
5455           error ("type/value mismatch at argument %d in template "
5456                  "parameter list for %qD",
5457                  i + 1, in_decl);
5458           if (is_tmpl_type)
5459             error ("  expected a type, got %qT", DECL_NAME (arg));
5460           else
5461             error ("  expected a class template, got %qT", orig_arg);
5462         }
5463       return error_mark_node;
5464     }
5465
5466   if (is_type)
5467     {
5468       if (requires_tmpl_type)
5469         {
5470           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
5471             /* The number of argument required is not known yet.
5472                Just accept it for now.  */
5473             val = TREE_TYPE (arg);
5474           else
5475             {
5476               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5477               tree argparm;
5478
5479               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5480
5481               if (coerce_template_template_parms (parmparm, argparm,
5482                                                   complain, in_decl,
5483                                                   args))
5484                 {
5485                   val = arg;
5486
5487                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
5488                      TEMPLATE_DECL.  */
5489                   if (val != error_mark_node)
5490                     {
5491                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
5492                         val = TREE_TYPE (val);
5493                       if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
5494                         val = make_pack_expansion (val);
5495                     }
5496                 }
5497               else
5498                 {
5499                   if (in_decl && (complain & tf_error))
5500                     {
5501                       error ("type/value mismatch at argument %d in "
5502                              "template parameter list for %qD",
5503                              i + 1, in_decl);
5504                       error ("  expected a template of type %qD, got %qT",
5505                              parm, orig_arg);
5506                     }
5507
5508                   val = error_mark_node;
5509                 }
5510             }
5511         }
5512       else
5513         val = orig_arg;
5514       /* We only form one instance of each template specialization.
5515          Therefore, if we use a non-canonical variant (i.e., a
5516          typedef), any future messages referring to the type will use
5517          the typedef, which is confusing if those future uses do not
5518          themselves also use the typedef.  */
5519       if (TYPE_P (val))
5520         val = strip_typedefs (val);
5521     }
5522   else
5523     {
5524       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
5525
5526       if (invalid_nontype_parm_type_p (t, complain))
5527         return error_mark_node;
5528
5529       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
5530         {
5531           if (same_type_p (t, TREE_TYPE (orig_arg)))
5532             val = orig_arg;
5533           else
5534             {
5535               /* Not sure if this is reachable, but it doesn't hurt
5536                  to be robust.  */
5537               error ("type mismatch in nontype parameter pack");
5538               val = error_mark_node;
5539             }
5540         }
5541       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
5542         /* We used to call digest_init here.  However, digest_init
5543            will report errors, which we don't want when complain
5544            is zero.  More importantly, digest_init will try too
5545            hard to convert things: for example, `0' should not be
5546            converted to pointer type at this point according to
5547            the standard.  Accepting this is not merely an
5548            extension, since deciding whether or not these
5549            conversions can occur is part of determining which
5550            function template to call, or whether a given explicit
5551            argument specification is valid.  */
5552         val = convert_nontype_argument (t, orig_arg);
5553       else
5554         val = orig_arg;
5555
5556       if (val == NULL_TREE)
5557         val = error_mark_node;
5558       else if (val == error_mark_node && (complain & tf_error))
5559         error ("could not convert template argument %qE to %qT",  orig_arg, t);
5560     }
5561
5562   return val;
5563 }
5564
5565 /* Coerces the remaining template arguments in INNER_ARGS (from
5566    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
5567    Returns the coerced argument pack. PARM_IDX is the position of this
5568    parameter in the template parameter list. ARGS is the original
5569    template argument list.  */
5570 static tree
5571 coerce_template_parameter_pack (tree parms,
5572                                 int parm_idx,
5573                                 tree args,
5574                                 tree inner_args,
5575                                 int arg_idx,
5576                                 tree new_args,
5577                                 int* lost,
5578                                 tree in_decl,
5579                                 tsubst_flags_t complain)
5580 {
5581   tree parm = TREE_VEC_ELT (parms, parm_idx);
5582   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5583   tree packed_args;
5584   tree argument_pack;
5585   tree packed_types = NULL_TREE;
5586
5587   if (arg_idx > nargs)
5588     arg_idx = nargs;
5589
5590   packed_args = make_tree_vec (nargs - arg_idx);
5591
5592   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
5593       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
5594     {
5595       /* When the template parameter is a non-type template
5596          parameter pack whose type uses parameter packs, we need
5597          to look at each of the template arguments
5598          separately. Build a vector of the types for these
5599          non-type template parameters in PACKED_TYPES.  */
5600       tree expansion 
5601         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
5602       packed_types = tsubst_pack_expansion (expansion, args,
5603                                             complain, in_decl);
5604
5605       if (packed_types == error_mark_node)
5606         return error_mark_node;
5607
5608       /* Check that we have the right number of arguments.  */
5609       if (arg_idx < nargs
5610           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
5611           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
5612         {
5613           int needed_parms 
5614             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
5615           error ("wrong number of template arguments (%d, should be %d)",
5616                  nargs, needed_parms);
5617           return error_mark_node;
5618         }
5619
5620       /* If we aren't able to check the actual arguments now
5621          (because they haven't been expanded yet), we can at least
5622          verify that all of the types used for the non-type
5623          template parameter pack are, in fact, valid for non-type
5624          template parameters.  */
5625       if (arg_idx < nargs 
5626           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
5627         {
5628           int j, len = TREE_VEC_LENGTH (packed_types);
5629           for (j = 0; j < len; ++j)
5630             {
5631               tree t = TREE_VEC_ELT (packed_types, j);
5632               if (invalid_nontype_parm_type_p (t, complain))
5633                 return error_mark_node;
5634             }
5635         }
5636     }
5637
5638   /* Convert the remaining arguments, which will be a part of the
5639      parameter pack "parm".  */
5640   for (; arg_idx < nargs; ++arg_idx)
5641     {
5642       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
5643       tree actual_parm = TREE_VALUE (parm);
5644
5645       if (packed_types && !PACK_EXPANSION_P (arg))
5646         {
5647           /* When we have a vector of types (corresponding to the
5648              non-type template parameter pack that uses parameter
5649              packs in its type, as mention above), and the
5650              argument is not an expansion (which expands to a
5651              currently unknown number of arguments), clone the
5652              parm and give it the next type in PACKED_TYPES.  */
5653           actual_parm = copy_node (actual_parm);
5654           TREE_TYPE (actual_parm) = 
5655             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
5656         }
5657
5658       if (arg != error_mark_node)
5659         arg = convert_template_argument (actual_parm, 
5660                                          arg, new_args, complain, parm_idx,
5661                                          in_decl);
5662       if (arg == error_mark_node)
5663         (*lost)++;
5664       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
5665     }
5666
5667   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
5668       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
5669     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
5670   else
5671     {
5672       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
5673       TREE_TYPE (argument_pack) 
5674         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
5675       TREE_CONSTANT (argument_pack) = 1;
5676     }
5677
5678   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
5679   return argument_pack;
5680 }
5681
5682 /* Convert all template arguments to their appropriate types, and
5683    return a vector containing the innermost resulting template
5684    arguments.  If any error occurs, return error_mark_node. Error and
5685    warning messages are issued under control of COMPLAIN.
5686
5687    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
5688    for arguments not specified in ARGS.  Otherwise, if
5689    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
5690    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
5691    USE_DEFAULT_ARGS is false, then all arguments must be specified in
5692    ARGS.  */
5693
5694 static tree
5695 coerce_template_parms (tree parms,
5696                        tree args,
5697                        tree in_decl,
5698                        tsubst_flags_t complain,
5699                        bool require_all_args,
5700                        bool use_default_args)
5701 {
5702   int nparms, nargs, parm_idx, arg_idx, lost = 0;
5703   tree inner_args;
5704   tree new_args;
5705   tree new_inner_args;
5706   int saved_unevaluated_operand;
5707   int saved_inhibit_evaluation_warnings;
5708
5709   /* When used as a boolean value, indicates whether this is a
5710      variadic template parameter list. Since it's an int, we can also
5711      subtract it from nparms to get the number of non-variadic
5712      parameters.  */
5713   int variadic_p = 0;
5714
5715   nparms = TREE_VEC_LENGTH (parms);
5716
5717   /* Determine if there are any parameter packs.  */
5718   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
5719     {
5720       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
5721       if (template_parameter_pack_p (tparm))
5722         ++variadic_p;
5723     }
5724
5725   inner_args = INNERMOST_TEMPLATE_ARGS (args);
5726   /* If there are 0 or 1 parameter packs, we need to expand any argument
5727      packs so that we can deduce a parameter pack from some non-packed args
5728      followed by an argument pack, as in variadic85.C.  If there are more
5729      than that, we need to leave argument packs intact so the arguments are
5730      assigned to the right parameter packs.  This should only happen when
5731      dealing with a nested class inside a partial specialization of a class
5732      template, as in variadic92.C.  */
5733   if (variadic_p <= 1)
5734     inner_args = expand_template_argument_pack (inner_args);
5735
5736   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5737   if ((nargs > nparms && !variadic_p)
5738       || (nargs < nparms - variadic_p
5739           && require_all_args
5740           && (!use_default_args
5741               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
5742                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
5743     {
5744       if (complain & tf_error)
5745         {
5746           const char *or_more = "";
5747           if (variadic_p)
5748             {
5749               or_more = " or more";
5750               --nparms;
5751             }
5752
5753           error ("wrong number of template arguments (%d, should be %d%s)",
5754                  nargs, nparms, or_more);
5755
5756           if (in_decl)
5757             error ("provided for %q+D", in_decl);
5758         }
5759
5760       return error_mark_node;
5761     }
5762
5763   /* We need to evaluate the template arguments, even though this
5764      template-id may be nested within a "sizeof".  */
5765   saved_unevaluated_operand = cp_unevaluated_operand;
5766   cp_unevaluated_operand = 0;
5767   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
5768   c_inhibit_evaluation_warnings = 0;
5769   new_inner_args = make_tree_vec (nparms);
5770   new_args = add_outermost_template_args (args, new_inner_args);
5771   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
5772     {
5773       tree arg;
5774       tree parm;
5775
5776       /* Get the Ith template parameter.  */
5777       parm = TREE_VEC_ELT (parms, parm_idx);
5778  
5779       if (parm == error_mark_node)
5780       {
5781         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
5782         continue;
5783       }
5784
5785       /* Calculate the next argument.  */
5786       if (arg_idx < nargs)
5787         arg = TREE_VEC_ELT (inner_args, arg_idx);
5788       else
5789         arg = NULL_TREE;
5790
5791       if (template_parameter_pack_p (TREE_VALUE (parm))
5792           && !(arg && ARGUMENT_PACK_P (arg)))
5793         {
5794           /* All remaining arguments will be placed in the
5795              template parameter pack PARM.  */
5796           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
5797                                                 inner_args, arg_idx,
5798                                                 new_args, &lost,
5799                                                 in_decl, complain);
5800
5801           /* Store this argument.  */
5802           if (arg == error_mark_node)
5803             lost++;
5804           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
5805
5806           /* We are done with all of the arguments.  */
5807           arg_idx = nargs;
5808           
5809           continue;
5810         }
5811       else if (arg)
5812         {
5813           if (PACK_EXPANSION_P (arg))
5814             {
5815               if (complain & tf_error)
5816                 {
5817                   /* FIXME this restriction was removed by N2555; see
5818                      bug 35722.  */
5819                   /* If ARG is a pack expansion, but PARM is not a
5820                      template parameter pack (if it were, we would have
5821                      handled it above), we're trying to expand into a
5822                      fixed-length argument list.  */
5823                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5824                     sorry ("cannot expand %<%E%> into a fixed-length "
5825                            "argument list", arg);
5826                   else
5827                     sorry ("cannot expand %<%T%> into a fixed-length "
5828                            "argument list", arg);
5829                 }
5830               return error_mark_node;
5831             }
5832         }
5833       else if (require_all_args)
5834         /* There must be a default arg in this case.  */
5835         arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
5836                                    complain, in_decl);
5837       else
5838         break;
5839
5840       if (arg == error_mark_node)
5841         {
5842           if (complain & tf_error)
5843             error ("template argument %d is invalid", arg_idx + 1);
5844         }
5845       else if (!arg)
5846         /* This only occurs if there was an error in the template
5847            parameter list itself (which we would already have
5848            reported) that we are trying to recover from, e.g., a class
5849            template with a parameter list such as
5850            template<typename..., typename>.  */
5851         return error_mark_node;
5852       else
5853         arg = convert_template_argument (TREE_VALUE (parm),
5854                                          arg, new_args, complain, 
5855                                          parm_idx, in_decl);
5856
5857       if (arg == error_mark_node)
5858         lost++;
5859       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
5860     }
5861   cp_unevaluated_operand = saved_unevaluated_operand;
5862   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
5863
5864   if (lost)
5865     return error_mark_node;
5866
5867   return new_inner_args;
5868 }
5869
5870 /* Returns 1 if template args OT and NT are equivalent.  */
5871
5872 static int
5873 template_args_equal (tree ot, tree nt)
5874 {
5875   if (nt == ot)
5876     return 1;
5877
5878   if (TREE_CODE (nt) == TREE_VEC)
5879     /* For member templates */
5880     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
5881   else if (PACK_EXPANSION_P (ot))
5882     return PACK_EXPANSION_P (nt) 
5883       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
5884                               PACK_EXPANSION_PATTERN (nt));
5885   else if (ARGUMENT_PACK_P (ot))
5886     {
5887       int i, len;
5888       tree opack, npack;
5889
5890       if (!ARGUMENT_PACK_P (nt))
5891         return 0;
5892
5893       opack = ARGUMENT_PACK_ARGS (ot);
5894       npack = ARGUMENT_PACK_ARGS (nt);
5895       len = TREE_VEC_LENGTH (opack);
5896       if (TREE_VEC_LENGTH (npack) != len)
5897         return 0;
5898       for (i = 0; i < len; ++i)
5899         if (!template_args_equal (TREE_VEC_ELT (opack, i),
5900                                   TREE_VEC_ELT (npack, i)))
5901           return 0;
5902       return 1;
5903     }
5904   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
5905     {
5906       /* We get here probably because we are in the middle of substituting
5907          into the pattern of a pack expansion. In that case the
5908          ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
5909          interested in. So we want to use the initial pack argument for
5910          the comparison.  */
5911       ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
5912       if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
5913         nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
5914       return template_args_equal (ot, nt);
5915     }
5916   else if (TYPE_P (nt))
5917     return TYPE_P (ot) && same_type_p (ot, nt);
5918   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
5919     return 0;
5920   else
5921     return cp_tree_equal (ot, nt);
5922 }
5923
5924 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
5925    of template arguments.  Returns 0 otherwise.  */
5926
5927 int
5928 comp_template_args (tree oldargs, tree newargs)
5929 {
5930   int i;
5931
5932   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
5933     return 0;
5934
5935   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
5936     {
5937       tree nt = TREE_VEC_ELT (newargs, i);
5938       tree ot = TREE_VEC_ELT (oldargs, i);
5939
5940       if (! template_args_equal (ot, nt))
5941         return 0;
5942     }
5943   return 1;
5944 }
5945
5946 static void
5947 add_pending_template (tree d)
5948 {
5949   tree ti = (TYPE_P (d)
5950              ? CLASSTYPE_TEMPLATE_INFO (d)
5951              : DECL_TEMPLATE_INFO (d));
5952   struct pending_template *pt;
5953   int level;
5954
5955   if (TI_PENDING_TEMPLATE_FLAG (ti))
5956     return;
5957
5958   /* We are called both from instantiate_decl, where we've already had a
5959      tinst_level pushed, and instantiate_template, where we haven't.
5960      Compensate.  */
5961   level = !current_tinst_level || current_tinst_level->decl != d;
5962
5963   if (level)
5964     push_tinst_level (d);
5965
5966   pt = GGC_NEW (struct pending_template);
5967   pt->next = NULL;
5968   pt->tinst = current_tinst_level;
5969   if (last_pending_template)
5970     last_pending_template->next = pt;
5971   else
5972     pending_templates = pt;
5973
5974   last_pending_template = pt;
5975
5976   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
5977
5978   if (level)
5979     pop_tinst_level ();
5980 }
5981
5982
5983 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
5984    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
5985    documentation for TEMPLATE_ID_EXPR.  */
5986
5987 tree
5988 lookup_template_function (tree fns, tree arglist)
5989 {
5990   tree type;
5991
5992   if (fns == error_mark_node || arglist == error_mark_node)
5993     return error_mark_node;
5994
5995   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
5996   gcc_assert (fns && (is_overloaded_fn (fns)
5997                       || TREE_CODE (fns) == IDENTIFIER_NODE));
5998
5999   if (BASELINK_P (fns))
6000     {
6001       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
6002                                          unknown_type_node,
6003                                          BASELINK_FUNCTIONS (fns),
6004                                          arglist);
6005       return fns;
6006     }
6007
6008   type = TREE_TYPE (fns);
6009   if (TREE_CODE (fns) == OVERLOAD || !type)
6010     type = unknown_type_node;
6011
6012   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
6013 }
6014
6015 /* Within the scope of a template class S<T>, the name S gets bound
6016    (in build_self_reference) to a TYPE_DECL for the class, not a
6017    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
6018    or one of its enclosing classes, and that type is a template,
6019    return the associated TEMPLATE_DECL.  Otherwise, the original
6020    DECL is returned.
6021
6022    Also handle the case when DECL is a TREE_LIST of ambiguous
6023    injected-class-names from different bases.  */
6024
6025 tree
6026 maybe_get_template_decl_from_type_decl (tree decl)
6027 {
6028   if (decl == NULL_TREE)
6029     return decl;
6030
6031   /* DR 176: A lookup that finds an injected-class-name (10.2
6032      [class.member.lookup]) can result in an ambiguity in certain cases
6033      (for example, if it is found in more than one base class). If all of
6034      the injected-class-names that are found refer to specializations of
6035      the same class template, and if the name is followed by a
6036      template-argument-list, the reference refers to the class template
6037      itself and not a specialization thereof, and is not ambiguous.  */
6038   if (TREE_CODE (decl) == TREE_LIST)
6039     {
6040       tree t, tmpl = NULL_TREE;
6041       for (t = decl; t; t = TREE_CHAIN (t))
6042         {
6043           tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
6044           if (!tmpl)
6045             tmpl = elt;
6046           else if (tmpl != elt)
6047             break;
6048         }
6049       if (tmpl && t == NULL_TREE)
6050         return tmpl;
6051       else
6052         return decl;
6053     }
6054
6055   return (decl != NULL_TREE
6056           && DECL_SELF_REFERENCE_P (decl)
6057           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
6058     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
6059 }
6060
6061 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
6062    parameters, find the desired type.
6063
6064    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
6065
6066    IN_DECL, if non-NULL, is the template declaration we are trying to
6067    instantiate.
6068
6069    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
6070    the class we are looking up.
6071
6072    Issue error and warning messages under control of COMPLAIN.
6073
6074    If the template class is really a local class in a template
6075    function, then the FUNCTION_CONTEXT is the function in which it is
6076    being instantiated.
6077
6078    ??? Note that this function is currently called *twice* for each
6079    template-id: the first time from the parser, while creating the
6080    incomplete type (finish_template_type), and the second type during the
6081    real instantiation (instantiate_template_class). This is surely something
6082    that we want to avoid. It also causes some problems with argument
6083    coercion (see convert_nontype_argument for more information on this).  */
6084
6085 tree
6086 lookup_template_class (tree d1,
6087                        tree arglist,
6088                        tree in_decl,
6089                        tree context,
6090                        int entering_scope,
6091                        tsubst_flags_t complain)
6092 {
6093   tree templ = NULL_TREE, parmlist;
6094   tree t;
6095   spec_entry **slot;
6096   spec_entry *entry;
6097   spec_entry elt;
6098   hashval_t hash;
6099
6100   timevar_push (TV_NAME_LOOKUP);
6101
6102   if (TREE_CODE (d1) == IDENTIFIER_NODE)
6103     {
6104       tree value = innermost_non_namespace_value (d1);
6105       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
6106         templ = value;
6107       else
6108         {
6109           if (context)
6110             push_decl_namespace (context);
6111           templ = lookup_name (d1);
6112           templ = maybe_get_template_decl_from_type_decl (templ);
6113           if (context)
6114             pop_decl_namespace ();
6115         }
6116       if (templ)
6117         context = DECL_CONTEXT (templ);
6118     }
6119   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
6120     {
6121       tree type = TREE_TYPE (d1);
6122
6123       /* If we are declaring a constructor, say A<T>::A<T>, we will get
6124          an implicit typename for the second A.  Deal with it.  */
6125       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
6126         type = TREE_TYPE (type);
6127
6128       if (CLASSTYPE_TEMPLATE_INFO (type))
6129         {
6130           templ = CLASSTYPE_TI_TEMPLATE (type);
6131           d1 = DECL_NAME (templ);
6132         }
6133     }
6134   else if (TREE_CODE (d1) == ENUMERAL_TYPE
6135            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
6136     {
6137       templ = TYPE_TI_TEMPLATE (d1);
6138       d1 = DECL_NAME (templ);
6139     }
6140   else if (TREE_CODE (d1) == TEMPLATE_DECL
6141            && DECL_TEMPLATE_RESULT (d1)
6142            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
6143     {
6144       templ = d1;
6145       d1 = DECL_NAME (templ);
6146       context = DECL_CONTEXT (templ);
6147     }
6148
6149   /* Issue an error message if we didn't find a template.  */
6150   if (! templ)
6151     {
6152       if (complain & tf_error)
6153         error ("%qT is not a template", d1);
6154       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6155     }
6156
6157   if (TREE_CODE (templ) != TEMPLATE_DECL
6158          /* Make sure it's a user visible template, if it was named by
6159             the user.  */
6160       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
6161           && !PRIMARY_TEMPLATE_P (templ)))
6162     {
6163       if (complain & tf_error)
6164         {
6165           error ("non-template type %qT used as a template", d1);
6166           if (in_decl)
6167             error ("for template declaration %q+D", in_decl);
6168         }
6169       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6170     }
6171
6172   complain &= ~tf_user;
6173
6174   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
6175     {
6176       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
6177          template arguments */
6178
6179       tree parm;
6180       tree arglist2;
6181       tree outer;
6182
6183       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
6184
6185       /* Consider an example where a template template parameter declared as
6186
6187            template <class T, class U = std::allocator<T> > class TT
6188
6189          The template parameter level of T and U are one level larger than
6190          of TT.  To proper process the default argument of U, say when an
6191          instantiation `TT<int>' is seen, we need to build the full
6192          arguments containing {int} as the innermost level.  Outer levels,
6193          available when not appearing as default template argument, can be
6194          obtained from the arguments of the enclosing template.
6195
6196          Suppose that TT is later substituted with std::vector.  The above
6197          instantiation is `TT<int, std::allocator<T> >' with TT at
6198          level 1, and T at level 2, while the template arguments at level 1
6199          becomes {std::vector} and the inner level 2 is {int}.  */
6200
6201       outer = DECL_CONTEXT (templ);
6202       if (outer)
6203         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
6204       else if (current_template_parms)
6205         /* This is an argument of the current template, so we haven't set
6206            DECL_CONTEXT yet.  */
6207         outer = current_template_args ();
6208
6209       if (outer)
6210         arglist = add_to_template_args (outer, arglist);
6211
6212       arglist2 = coerce_template_parms (parmlist, arglist, templ,
6213                                         complain,
6214                                         /*require_all_args=*/true,
6215                                         /*use_default_args=*/true);
6216       if (arglist2 == error_mark_node
6217           || (!uses_template_parms (arglist2)
6218               && check_instantiated_args (templ, arglist2, complain)))
6219         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6220
6221       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
6222       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
6223     }
6224   else
6225     {
6226       tree template_type = TREE_TYPE (templ);
6227       tree gen_tmpl;
6228       tree type_decl;
6229       tree found = NULL_TREE;
6230       int arg_depth;
6231       int parm_depth;
6232       int is_partial_instantiation;
6233
6234       gen_tmpl = most_general_template (templ);
6235       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
6236       parm_depth = TMPL_PARMS_DEPTH (parmlist);
6237       arg_depth = TMPL_ARGS_DEPTH (arglist);
6238
6239       if (arg_depth == 1 && parm_depth > 1)
6240         {
6241           /* We've been given an incomplete set of template arguments.
6242              For example, given:
6243
6244                template <class T> struct S1 {
6245                  template <class U> struct S2 {};
6246                  template <class U> struct S2<U*> {};
6247                 };
6248
6249              we will be called with an ARGLIST of `U*', but the
6250              TEMPLATE will be `template <class T> template
6251              <class U> struct S1<T>::S2'.  We must fill in the missing
6252              arguments.  */
6253           arglist
6254             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
6255                                            arglist);
6256           arg_depth = TMPL_ARGS_DEPTH (arglist);
6257         }
6258
6259       /* Now we should have enough arguments.  */
6260       gcc_assert (parm_depth == arg_depth);
6261
6262       /* From here on, we're only interested in the most general
6263          template.  */
6264
6265       /* Calculate the BOUND_ARGS.  These will be the args that are
6266          actually tsubst'd into the definition to create the
6267          instantiation.  */
6268       if (parm_depth > 1)
6269         {
6270           /* We have multiple levels of arguments to coerce, at once.  */
6271           int i;
6272           int saved_depth = TMPL_ARGS_DEPTH (arglist);
6273
6274           tree bound_args = make_tree_vec (parm_depth);
6275
6276           for (i = saved_depth,
6277                  t = DECL_TEMPLATE_PARMS (gen_tmpl);
6278                i > 0 && t != NULL_TREE;
6279                --i, t = TREE_CHAIN (t))
6280             {
6281               tree a = coerce_template_parms (TREE_VALUE (t),
6282                                               arglist, gen_tmpl,
6283                                               complain,
6284                                               /*require_all_args=*/true,
6285                                               /*use_default_args=*/true);
6286
6287               /* Don't process further if one of the levels fails.  */
6288               if (a == error_mark_node)
6289                 {
6290                   /* Restore the ARGLIST to its full size.  */
6291                   TREE_VEC_LENGTH (arglist) = saved_depth;
6292                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6293                 }
6294
6295               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
6296
6297               /* We temporarily reduce the length of the ARGLIST so
6298                  that coerce_template_parms will see only the arguments
6299                  corresponding to the template parameters it is
6300                  examining.  */
6301               TREE_VEC_LENGTH (arglist)--;
6302             }
6303
6304           /* Restore the ARGLIST to its full size.  */
6305           TREE_VEC_LENGTH (arglist) = saved_depth;
6306
6307           arglist = bound_args;
6308         }
6309       else
6310         arglist
6311           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
6312                                    INNERMOST_TEMPLATE_ARGS (arglist),
6313                                    gen_tmpl,
6314                                    complain,
6315                                    /*require_all_args=*/true,
6316                                    /*use_default_args=*/true);
6317
6318       if (arglist == error_mark_node)
6319         /* We were unable to bind the arguments.  */
6320         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6321
6322       /* In the scope of a template class, explicit references to the
6323          template class refer to the type of the template, not any
6324          instantiation of it.  For example, in:
6325
6326            template <class T> class C { void f(C<T>); }
6327
6328          the `C<T>' is just the same as `C'.  Outside of the
6329          class, however, such a reference is an instantiation.  */
6330       if ((entering_scope
6331            || !PRIMARY_TEMPLATE_P (gen_tmpl)
6332            || currently_open_class (template_type))
6333           /* comp_template_args is expensive, check it last.  */
6334           && comp_template_args (TYPE_TI_ARGS (template_type),
6335                                  arglist))
6336         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, template_type);
6337
6338       /* If we already have this specialization, return it.  */
6339       elt.tmpl = gen_tmpl;
6340       elt.args = arglist;
6341       hash = hash_specialization (&elt);
6342       entry = (spec_entry *) htab_find_with_hash (type_specializations,
6343                                                   &elt, hash);
6344
6345       if (entry)
6346         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, entry->spec);
6347
6348       /* This type is a "partial instantiation" if any of the template
6349          arguments still involve template parameters.  Note that we set
6350          IS_PARTIAL_INSTANTIATION for partial specializations as
6351          well.  */
6352       is_partial_instantiation = uses_template_parms (arglist);
6353
6354       /* If the deduced arguments are invalid, then the binding
6355          failed.  */
6356       if (!is_partial_instantiation
6357           && check_instantiated_args (gen_tmpl,
6358                                       INNERMOST_TEMPLATE_ARGS (arglist),
6359                                       complain))
6360         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6361
6362       if (!is_partial_instantiation
6363           && !PRIMARY_TEMPLATE_P (gen_tmpl)
6364           && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
6365           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
6366         {
6367           found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
6368                                       DECL_NAME (gen_tmpl),
6369                                       /*tag_scope=*/ts_global);
6370           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
6371         }
6372
6373       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
6374                         complain, in_decl);
6375       if (!context)
6376         context = global_namespace;
6377
6378       /* Create the type.  */
6379       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
6380         {
6381           if (!is_partial_instantiation)
6382             {
6383               set_current_access_from_decl (TYPE_NAME (template_type));
6384               t = start_enum (TYPE_IDENTIFIER (template_type),
6385                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
6386                                       arglist, complain, in_decl),
6387                               SCOPED_ENUM_P (template_type));
6388             }
6389           else
6390             {
6391               /* We don't want to call start_enum for this type, since
6392                  the values for the enumeration constants may involve
6393                  template parameters.  And, no one should be interested
6394                  in the enumeration constants for such a type.  */
6395               t = cxx_make_type (ENUMERAL_TYPE);
6396               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
6397             }
6398         }
6399       else
6400         {
6401           t = make_class_type (TREE_CODE (template_type));
6402           CLASSTYPE_DECLARED_CLASS (t)
6403             = CLASSTYPE_DECLARED_CLASS (template_type);
6404           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
6405           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
6406
6407           /* A local class.  Make sure the decl gets registered properly.  */
6408           if (context == current_function_decl)
6409             pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
6410
6411           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
6412             /* This instantiation is another name for the primary
6413                template type. Set the TYPE_CANONICAL field
6414                appropriately. */
6415             TYPE_CANONICAL (t) = template_type;
6416           else if (any_template_arguments_need_structural_equality_p (arglist))
6417             /* Some of the template arguments require structural
6418                equality testing, so this template class requires
6419                structural equality testing. */
6420             SET_TYPE_STRUCTURAL_EQUALITY (t);
6421         }
6422
6423       /* If we called start_enum or pushtag above, this information
6424          will already be set up.  */
6425       if (!TYPE_NAME (t))
6426         {
6427           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
6428
6429           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
6430           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
6431           DECL_SOURCE_LOCATION (type_decl)
6432             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
6433         }
6434       else
6435         type_decl = TYPE_NAME (t);
6436
6437       TREE_PRIVATE (type_decl)
6438         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
6439       TREE_PROTECTED (type_decl)
6440         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
6441       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
6442         {
6443           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
6444           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
6445         }
6446
6447       /* Set up the template information.  We have to figure out which
6448          template is the immediate parent if this is a full
6449          instantiation.  */
6450       if (parm_depth == 1 || is_partial_instantiation
6451           || !PRIMARY_TEMPLATE_P (gen_tmpl))
6452         /* This case is easy; there are no member templates involved.  */
6453         found = gen_tmpl;
6454       else
6455         {
6456           /* This is a full instantiation of a member template.  Find
6457              the partial instantiation of which this is an instance.  */
6458
6459           /* Temporarily reduce by one the number of levels in the ARGLIST
6460              so as to avoid comparing the last set of arguments.  */
6461           TREE_VEC_LENGTH (arglist)--;
6462           found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
6463           TREE_VEC_LENGTH (arglist)++;
6464           found = CLASSTYPE_TI_TEMPLATE (found);
6465         }
6466
6467       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
6468
6469       elt.spec = t;
6470       slot = (spec_entry **) htab_find_slot_with_hash (type_specializations,
6471                                                        &elt, hash, INSERT);
6472       *slot = GGC_NEW (spec_entry);
6473       **slot = elt;
6474
6475       /* Note this use of the partial instantiation so we can check it
6476          later in maybe_process_partial_specialization.  */
6477       DECL_TEMPLATE_INSTANTIATIONS (templ)
6478         = tree_cons (arglist, t,
6479                      DECL_TEMPLATE_INSTANTIATIONS (templ));
6480
6481       if (TREE_CODE (t) == ENUMERAL_TYPE
6482           && !is_partial_instantiation)
6483         /* Now that the type has been registered on the instantiations
6484            list, we set up the enumerators.  Because the enumeration
6485            constants may involve the enumeration type itself, we make
6486            sure to register the type first, and then create the
6487            constants.  That way, doing tsubst_expr for the enumeration
6488            constants won't result in recursive calls here; we'll find
6489            the instantiation and exit above.  */
6490         tsubst_enum (template_type, t, arglist);
6491
6492       if (is_partial_instantiation)
6493         /* If the type makes use of template parameters, the
6494            code that generates debugging information will crash.  */
6495         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
6496
6497       /* Possibly limit visibility based on template args.  */
6498       TREE_PUBLIC (type_decl) = 1;
6499       determine_visibility (type_decl);
6500
6501       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
6502     }
6503   timevar_pop (TV_NAME_LOOKUP);
6504 }
6505 \f
6506 struct pair_fn_data
6507 {
6508   tree_fn_t fn;
6509   void *data;
6510   /* True when we should also visit template parameters that occur in
6511      non-deduced contexts.  */
6512   bool include_nondeduced_p;
6513   struct pointer_set_t *visited;
6514 };
6515
6516 /* Called from for_each_template_parm via walk_tree.  */
6517
6518 static tree
6519 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
6520 {
6521   tree t = *tp;
6522   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
6523   tree_fn_t fn = pfd->fn;
6524   void *data = pfd->data;
6525
6526   if (TYPE_P (t)
6527       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
6528       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
6529                                  pfd->include_nondeduced_p))
6530     return error_mark_node;
6531
6532   switch (TREE_CODE (t))
6533     {
6534     case RECORD_TYPE:
6535       if (TYPE_PTRMEMFUNC_P (t))
6536         break;
6537       /* Fall through.  */
6538
6539     case UNION_TYPE:
6540     case ENUMERAL_TYPE:
6541       if (!TYPE_TEMPLATE_INFO (t))
6542         *walk_subtrees = 0;
6543       else if (for_each_template_parm (TI_ARGS (TYPE_TEMPLATE_INFO (t)),
6544                                        fn, data, pfd->visited, 
6545                                        pfd->include_nondeduced_p))
6546         return error_mark_node;
6547       break;
6548
6549     case INTEGER_TYPE:
6550       if (for_each_template_parm (TYPE_MIN_VALUE (t),
6551                                   fn, data, pfd->visited, 
6552                                   pfd->include_nondeduced_p)
6553           || for_each_template_parm (TYPE_MAX_VALUE (t),
6554                                      fn, data, pfd->visited,
6555                                      pfd->include_nondeduced_p))
6556         return error_mark_node;
6557       break;
6558
6559     case METHOD_TYPE:
6560       /* Since we're not going to walk subtrees, we have to do this
6561          explicitly here.  */
6562       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
6563                                   pfd->visited, pfd->include_nondeduced_p))
6564         return error_mark_node;
6565       /* Fall through.  */
6566
6567     case FUNCTION_TYPE:
6568       /* Check the return type.  */
6569       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6570                                   pfd->include_nondeduced_p))
6571         return error_mark_node;
6572
6573       /* Check the parameter types.  Since default arguments are not
6574          instantiated until they are needed, the TYPE_ARG_TYPES may
6575          contain expressions that involve template parameters.  But,
6576          no-one should be looking at them yet.  And, once they're
6577          instantiated, they don't contain template parameters, so
6578          there's no point in looking at them then, either.  */
6579       {
6580         tree parm;
6581
6582         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
6583           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
6584                                       pfd->visited, pfd->include_nondeduced_p))
6585             return error_mark_node;
6586
6587         /* Since we've already handled the TYPE_ARG_TYPES, we don't
6588            want walk_tree walking into them itself.  */
6589         *walk_subtrees = 0;
6590       }
6591       break;
6592
6593     case TYPEOF_TYPE:
6594       if (pfd->include_nondeduced_p
6595           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
6596                                      pfd->visited, 
6597                                      pfd->include_nondeduced_p))
6598         return error_mark_node;
6599       break;
6600
6601     case FUNCTION_DECL:
6602     case VAR_DECL:
6603       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
6604           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
6605                                      pfd->visited, pfd->include_nondeduced_p))
6606         return error_mark_node;
6607       /* Fall through.  */
6608
6609     case PARM_DECL:
6610     case CONST_DECL:
6611       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
6612           && for_each_template_parm (DECL_INITIAL (t), fn, data,
6613                                      pfd->visited, pfd->include_nondeduced_p))
6614         return error_mark_node;
6615       if (DECL_CONTEXT (t)
6616           && pfd->include_nondeduced_p
6617           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
6618                                      pfd->visited, pfd->include_nondeduced_p))
6619         return error_mark_node;
6620       break;
6621
6622     case BOUND_TEMPLATE_TEMPLATE_PARM:
6623       /* Record template parameters such as `T' inside `TT<T>'.  */
6624       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
6625                                   pfd->include_nondeduced_p))
6626         return error_mark_node;
6627       /* Fall through.  */
6628
6629     case TEMPLATE_TEMPLATE_PARM:
6630     case TEMPLATE_TYPE_PARM:
6631     case TEMPLATE_PARM_INDEX:
6632       if (fn && (*fn)(t, data))
6633         return error_mark_node;
6634       else if (!fn)
6635         return error_mark_node;
6636       break;
6637
6638     case TEMPLATE_DECL:
6639       /* A template template parameter is encountered.  */
6640       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
6641           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6642                                      pfd->include_nondeduced_p))
6643         return error_mark_node;
6644
6645       /* Already substituted template template parameter */
6646       *walk_subtrees = 0;
6647       break;
6648
6649     case TYPENAME_TYPE:
6650       if (!fn
6651           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
6652                                      data, pfd->visited, 
6653                                      pfd->include_nondeduced_p))
6654         return error_mark_node;
6655       break;
6656
6657     case CONSTRUCTOR:
6658       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
6659           && pfd->include_nondeduced_p
6660           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
6661                                      (TREE_TYPE (t)), fn, data,
6662                                      pfd->visited, pfd->include_nondeduced_p))
6663         return error_mark_node;
6664       break;
6665
6666     case INDIRECT_REF:
6667     case COMPONENT_REF:
6668       /* If there's no type, then this thing must be some expression
6669          involving template parameters.  */
6670       if (!fn && !TREE_TYPE (t))
6671         return error_mark_node;
6672       break;
6673
6674     case MODOP_EXPR:
6675     case CAST_EXPR:
6676     case REINTERPRET_CAST_EXPR:
6677     case CONST_CAST_EXPR:
6678     case STATIC_CAST_EXPR:
6679     case DYNAMIC_CAST_EXPR:
6680     case ARROW_EXPR:
6681     case DOTSTAR_EXPR:
6682     case TYPEID_EXPR:
6683     case PSEUDO_DTOR_EXPR:
6684       if (!fn)
6685         return error_mark_node;
6686       break;
6687
6688     default:
6689       break;
6690     }
6691
6692   /* We didn't find any template parameters we liked.  */
6693   return NULL_TREE;
6694 }
6695
6696 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
6697    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
6698    call FN with the parameter and the DATA.
6699    If FN returns nonzero, the iteration is terminated, and
6700    for_each_template_parm returns 1.  Otherwise, the iteration
6701    continues.  If FN never returns a nonzero value, the value
6702    returned by for_each_template_parm is 0.  If FN is NULL, it is
6703    considered to be the function which always returns 1.
6704
6705    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
6706    parameters that occur in non-deduced contexts.  When false, only
6707    visits those template parameters that can be deduced.  */
6708
6709 static int
6710 for_each_template_parm (tree t, tree_fn_t fn, void* data,
6711                         struct pointer_set_t *visited,
6712                         bool include_nondeduced_p)
6713 {
6714   struct pair_fn_data pfd;
6715   int result;
6716
6717   /* Set up.  */
6718   pfd.fn = fn;
6719   pfd.data = data;
6720   pfd.include_nondeduced_p = include_nondeduced_p;
6721
6722   /* Walk the tree.  (Conceptually, we would like to walk without
6723      duplicates, but for_each_template_parm_r recursively calls
6724      for_each_template_parm, so we would need to reorganize a fair
6725      bit to use walk_tree_without_duplicates, so we keep our own
6726      visited list.)  */
6727   if (visited)
6728     pfd.visited = visited;
6729   else
6730     pfd.visited = pointer_set_create ();
6731   result = cp_walk_tree (&t,
6732                          for_each_template_parm_r,
6733                          &pfd,
6734                          pfd.visited) != NULL_TREE;
6735
6736   /* Clean up.  */
6737   if (!visited)
6738     {
6739       pointer_set_destroy (pfd.visited);
6740       pfd.visited = 0;
6741     }
6742
6743   return result;
6744 }
6745
6746 /* Returns true if T depends on any template parameter.  */
6747
6748 int
6749 uses_template_parms (tree t)
6750 {
6751   bool dependent_p;
6752   int saved_processing_template_decl;
6753
6754   saved_processing_template_decl = processing_template_decl;
6755   if (!saved_processing_template_decl)
6756     processing_template_decl = 1;
6757   if (TYPE_P (t))
6758     dependent_p = dependent_type_p (t);
6759   else if (TREE_CODE (t) == TREE_VEC)
6760     dependent_p = any_dependent_template_arguments_p (t);
6761   else if (TREE_CODE (t) == TREE_LIST)
6762     dependent_p = (uses_template_parms (TREE_VALUE (t))
6763                    || uses_template_parms (TREE_CHAIN (t)));
6764   else if (TREE_CODE (t) == TYPE_DECL)
6765     dependent_p = dependent_type_p (TREE_TYPE (t));
6766   else if (DECL_P (t)
6767            || EXPR_P (t)
6768            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
6769            || TREE_CODE (t) == OVERLOAD
6770            || TREE_CODE (t) == BASELINK
6771            || TREE_CODE (t) == IDENTIFIER_NODE
6772            || TREE_CODE (t) == TRAIT_EXPR
6773            || TREE_CODE (t) == CONSTRUCTOR
6774            || CONSTANT_CLASS_P (t))
6775     dependent_p = (type_dependent_expression_p (t)
6776                    || value_dependent_expression_p (t));
6777   else
6778     {
6779       gcc_assert (t == error_mark_node);
6780       dependent_p = false;
6781     }
6782
6783   processing_template_decl = saved_processing_template_decl;
6784
6785   return dependent_p;
6786 }
6787
6788 /* Returns true if T depends on any template parameter with level LEVEL.  */
6789
6790 int
6791 uses_template_parms_level (tree t, int level)
6792 {
6793   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
6794                                  /*include_nondeduced_p=*/true);
6795 }
6796
6797 static int tinst_depth;
6798 extern int max_tinst_depth;
6799 #ifdef GATHER_STATISTICS
6800 int depth_reached;
6801 #endif
6802 static int tinst_level_tick;
6803 static int last_template_error_tick;
6804
6805 /* We're starting to instantiate D; record the template instantiation context
6806    for diagnostics and to restore it later.  */
6807
6808 static int
6809 push_tinst_level (tree d)
6810 {
6811   struct tinst_level *new_level;
6812
6813   if (tinst_depth >= max_tinst_depth)
6814     {
6815       /* If the instantiation in question still has unbound template parms,
6816          we don't really care if we can't instantiate it, so just return.
6817          This happens with base instantiation for implicit `typename'.  */
6818       if (uses_template_parms (d))
6819         return 0;
6820
6821       last_template_error_tick = tinst_level_tick;
6822       error ("template instantiation depth exceeds maximum of %d (use "
6823              "-ftemplate-depth-NN to increase the maximum) instantiating %qD",
6824              max_tinst_depth, d);
6825
6826       print_instantiation_context ();
6827
6828       return 0;
6829     }
6830
6831   new_level = GGC_NEW (struct tinst_level);
6832   new_level->decl = d;
6833   new_level->locus = input_location;
6834   new_level->in_system_header_p = in_system_header;
6835   new_level->next = current_tinst_level;
6836   current_tinst_level = new_level;
6837
6838   ++tinst_depth;
6839 #ifdef GATHER_STATISTICS
6840   if (tinst_depth > depth_reached)
6841     depth_reached = tinst_depth;
6842 #endif
6843
6844   ++tinst_level_tick;
6845   return 1;
6846 }
6847
6848 /* We're done instantiating this template; return to the instantiation
6849    context.  */
6850
6851 static void
6852 pop_tinst_level (void)
6853 {
6854   /* Restore the filename and line number stashed away when we started
6855      this instantiation.  */
6856   input_location = current_tinst_level->locus;
6857   current_tinst_level = current_tinst_level->next;
6858   --tinst_depth;
6859   ++tinst_level_tick;
6860 }
6861
6862 /* We're instantiating a deferred template; restore the template
6863    instantiation context in which the instantiation was requested, which
6864    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
6865
6866 static tree
6867 reopen_tinst_level (struct tinst_level *level)
6868 {
6869   struct tinst_level *t;
6870
6871   tinst_depth = 0;
6872   for (t = level; t; t = t->next)
6873     ++tinst_depth;
6874
6875   current_tinst_level = level;
6876   pop_tinst_level ();
6877   return level->decl;
6878 }
6879
6880 /* Returns the TINST_LEVEL which gives the original instantiation
6881    context.  */
6882
6883 struct tinst_level *
6884 outermost_tinst_level (void)
6885 {
6886   struct tinst_level *level = current_tinst_level;
6887   if (level)
6888     while (level->next)
6889       level = level->next;
6890   return level;
6891 }
6892
6893 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
6894
6895 bool
6896 parameter_of_template_p (tree parm, tree templ)
6897 {
6898   tree parms;
6899   int i;
6900
6901   if (!parm || !templ)
6902     return false;
6903
6904   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
6905   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
6906
6907   parms = DECL_TEMPLATE_PARMS (templ);
6908   parms = INNERMOST_TEMPLATE_PARMS (parms);
6909
6910   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
6911     if (parm == TREE_VALUE (TREE_VEC_ELT (parms, i)))
6912       return true;
6913
6914   return false;
6915 }
6916
6917 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
6918    vector of template arguments, as for tsubst.
6919
6920    Returns an appropriate tsubst'd friend declaration.  */
6921
6922 static tree
6923 tsubst_friend_function (tree decl, tree args)
6924 {
6925   tree new_friend;
6926
6927   if (TREE_CODE (decl) == FUNCTION_DECL
6928       && DECL_TEMPLATE_INSTANTIATION (decl)
6929       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
6930     /* This was a friend declared with an explicit template
6931        argument list, e.g.:
6932
6933        friend void f<>(T);
6934
6935        to indicate that f was a template instantiation, not a new
6936        function declaration.  Now, we have to figure out what
6937        instantiation of what template.  */
6938     {
6939       tree template_id, arglist, fns;
6940       tree new_args;
6941       tree tmpl;
6942       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
6943
6944       /* Friend functions are looked up in the containing namespace scope.
6945          We must enter that scope, to avoid finding member functions of the
6946          current class with same name.  */
6947       push_nested_namespace (ns);
6948       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
6949                          tf_warning_or_error, NULL_TREE,
6950                          /*integral_constant_expression_p=*/false);
6951       pop_nested_namespace (ns);
6952       arglist = tsubst (DECL_TI_ARGS (decl), args,
6953                         tf_warning_or_error, NULL_TREE);
6954       template_id = lookup_template_function (fns, arglist);
6955
6956       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6957       tmpl = determine_specialization (template_id, new_friend,
6958                                        &new_args,
6959                                        /*need_member_template=*/0,
6960                                        TREE_VEC_LENGTH (args),
6961                                        tsk_none);
6962       return instantiate_template (tmpl, new_args, tf_error);
6963     }
6964
6965   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
6966
6967   /* The NEW_FRIEND will look like an instantiation, to the
6968      compiler, but is not an instantiation from the point of view of
6969      the language.  For example, we might have had:
6970
6971      template <class T> struct S {
6972        template <class U> friend void f(T, U);
6973      };
6974
6975      Then, in S<int>, template <class U> void f(int, U) is not an
6976      instantiation of anything.  */
6977   if (new_friend == error_mark_node)
6978     return error_mark_node;
6979
6980   DECL_USE_TEMPLATE (new_friend) = 0;
6981   if (TREE_CODE (decl) == TEMPLATE_DECL)
6982     {
6983       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
6984       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
6985         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
6986     }
6987
6988   /* The mangled name for the NEW_FRIEND is incorrect.  The function
6989      is not a template instantiation and should not be mangled like
6990      one.  Therefore, we forget the mangling here; we'll recompute it
6991      later if we need it.  */
6992   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
6993     {
6994       SET_DECL_RTL (new_friend, NULL_RTX);
6995       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
6996     }
6997
6998   if (DECL_NAMESPACE_SCOPE_P (new_friend))
6999     {
7000       tree old_decl;
7001       tree new_friend_template_info;
7002       tree new_friend_result_template_info;
7003       tree ns;
7004       int  new_friend_is_defn;
7005
7006       /* We must save some information from NEW_FRIEND before calling
7007          duplicate decls since that function will free NEW_FRIEND if
7008          possible.  */
7009       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
7010       new_friend_is_defn =
7011             (DECL_INITIAL (DECL_TEMPLATE_RESULT
7012                            (template_for_substitution (new_friend)))
7013              != NULL_TREE);
7014       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
7015         {
7016           /* This declaration is a `primary' template.  */
7017           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
7018
7019           new_friend_result_template_info
7020             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
7021         }
7022       else
7023         new_friend_result_template_info = NULL_TREE;
7024
7025       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
7026       if (new_friend_is_defn)
7027         DECL_INITIAL (new_friend) = error_mark_node;
7028
7029       /* Inside pushdecl_namespace_level, we will push into the
7030          current namespace. However, the friend function should go
7031          into the namespace of the template.  */
7032       ns = decl_namespace_context (new_friend);
7033       push_nested_namespace (ns);
7034       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
7035       pop_nested_namespace (ns);
7036
7037       if (old_decl == error_mark_node)
7038         return error_mark_node;
7039
7040       if (old_decl != new_friend)
7041         {
7042           /* This new friend declaration matched an existing
7043              declaration.  For example, given:
7044
7045                template <class T> void f(T);
7046                template <class U> class C {
7047                  template <class T> friend void f(T) {}
7048                };
7049
7050              the friend declaration actually provides the definition
7051              of `f', once C has been instantiated for some type.  So,
7052              old_decl will be the out-of-class template declaration,
7053              while new_friend is the in-class definition.
7054
7055              But, if `f' was called before this point, the
7056              instantiation of `f' will have DECL_TI_ARGS corresponding
7057              to `T' but not to `U', references to which might appear
7058              in the definition of `f'.  Previously, the most general
7059              template for an instantiation of `f' was the out-of-class
7060              version; now it is the in-class version.  Therefore, we
7061              run through all specialization of `f', adding to their
7062              DECL_TI_ARGS appropriately.  In particular, they need a
7063              new set of outer arguments, corresponding to the
7064              arguments for this class instantiation.
7065
7066              The same situation can arise with something like this:
7067
7068                friend void f(int);
7069                template <class T> class C {
7070                  friend void f(T) {}
7071                };
7072
7073              when `C<int>' is instantiated.  Now, `f(int)' is defined
7074              in the class.  */
7075
7076           if (!new_friend_is_defn)
7077             /* On the other hand, if the in-class declaration does
7078                *not* provide a definition, then we don't want to alter
7079                existing definitions.  We can just leave everything
7080                alone.  */
7081             ;
7082           else
7083             {
7084               tree new_template = TI_TEMPLATE (new_friend_template_info);
7085               tree new_args = TI_ARGS (new_friend_template_info);
7086
7087               /* Overwrite whatever template info was there before, if
7088                  any, with the new template information pertaining to
7089                  the declaration.  */
7090               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
7091
7092               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
7093                 /* We should have called reregister_specialization in
7094                    duplicate_decls.  */
7095                 gcc_assert (retrieve_specialization (new_template,
7096                                                      new_args, 0)
7097                             == old_decl);
7098               else
7099                 {
7100                   tree t;
7101
7102                   /* Indicate that the old function template is a partial
7103                      instantiation.  */
7104                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
7105                     = new_friend_result_template_info;
7106
7107                   gcc_assert (new_template
7108                               == most_general_template (new_template));
7109                   gcc_assert (new_template != old_decl);
7110
7111                   /* Reassign any specializations already in the hash table
7112                      to the new more general template, and add the
7113                      additional template args.  */
7114                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
7115                        t != NULL_TREE;
7116                        t = TREE_CHAIN (t))
7117                     {
7118                       tree spec = TREE_VALUE (t);
7119                       spec_entry elt;
7120
7121                       elt.tmpl = old_decl;
7122                       elt.args = DECL_TI_ARGS (spec);
7123                       elt.spec = NULL_TREE;
7124
7125                       htab_remove_elt (decl_specializations, &elt);
7126
7127                       DECL_TI_ARGS (spec)
7128                         = add_outermost_template_args (new_args,
7129                                                        DECL_TI_ARGS (spec));
7130
7131                       register_specialization
7132                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
7133
7134                     }
7135                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
7136                 }
7137             }
7138
7139           /* The information from NEW_FRIEND has been merged into OLD_DECL
7140              by duplicate_decls.  */
7141           new_friend = old_decl;
7142         }
7143     }
7144   else
7145     {
7146       tree context = DECL_CONTEXT (new_friend);
7147       bool dependent_p;
7148
7149       /* In the code
7150            template <class T> class C {
7151              template <class U> friend void C1<U>::f (); // case 1
7152              friend void C2<T>::f ();                    // case 2
7153            };
7154          we only need to make sure CONTEXT is a complete type for
7155          case 2.  To distinguish between the two cases, we note that
7156          CONTEXT of case 1 remains dependent type after tsubst while
7157          this isn't true for case 2.  */
7158       ++processing_template_decl;
7159       dependent_p = dependent_type_p (context);
7160       --processing_template_decl;
7161
7162       if (!dependent_p
7163           && !complete_type_or_else (context, NULL_TREE))
7164         return error_mark_node;
7165
7166       if (COMPLETE_TYPE_P (context))
7167         {
7168           /* Check to see that the declaration is really present, and,
7169              possibly obtain an improved declaration.  */
7170           tree fn = check_classfn (context,
7171                                    new_friend, NULL_TREE);
7172
7173           if (fn)
7174             new_friend = fn;
7175         }
7176     }
7177
7178   return new_friend;
7179 }
7180
7181 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
7182    template arguments, as for tsubst.
7183
7184    Returns an appropriate tsubst'd friend type or error_mark_node on
7185    failure.  */
7186
7187 static tree
7188 tsubst_friend_class (tree friend_tmpl, tree args)
7189 {
7190   tree friend_type;
7191   tree tmpl;
7192   tree context;
7193
7194   context = DECL_CONTEXT (friend_tmpl);
7195
7196   if (context)
7197     {
7198       if (TREE_CODE (context) == NAMESPACE_DECL)
7199         push_nested_namespace (context);
7200       else
7201         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
7202     }
7203
7204   /* Look for a class template declaration.  We look for hidden names
7205      because two friend declarations of the same template are the
7206      same.  For example, in:
7207
7208        struct A { 
7209          template <typename> friend class F;
7210        };
7211        template <typename> struct B { 
7212          template <typename> friend class F;
7213        };
7214
7215      both F templates are the same.  */
7216   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
7217                            /*block_p=*/true, 0, 
7218                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
7219
7220   /* But, if we don't find one, it might be because we're in a
7221      situation like this:
7222
7223        template <class T>
7224        struct S {
7225          template <class U>
7226          friend struct S;
7227        };
7228
7229      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
7230      for `S<int>', not the TEMPLATE_DECL.  */
7231   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
7232     {
7233       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
7234       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
7235     }
7236
7237   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
7238     {
7239       /* The friend template has already been declared.  Just
7240          check to see that the declarations match, and install any new
7241          default parameters.  We must tsubst the default parameters,
7242          of course.  We only need the innermost template parameters
7243          because that is all that redeclare_class_template will look
7244          at.  */
7245       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
7246           > TMPL_ARGS_DEPTH (args))
7247         {
7248           tree parms;
7249           location_t saved_input_location;
7250           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
7251                                          args, tf_warning_or_error);
7252
7253           saved_input_location = input_location;
7254           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
7255           redeclare_class_template (TREE_TYPE (tmpl), parms);
7256           input_location = saved_input_location;
7257           
7258         }
7259
7260       friend_type = TREE_TYPE (tmpl);
7261     }
7262   else
7263     {
7264       /* The friend template has not already been declared.  In this
7265          case, the instantiation of the template class will cause the
7266          injection of this template into the global scope.  */
7267       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
7268       if (tmpl == error_mark_node)
7269         return error_mark_node;
7270
7271       /* The new TMPL is not an instantiation of anything, so we
7272          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
7273          the new type because that is supposed to be the corresponding
7274          template decl, i.e., TMPL.  */
7275       DECL_USE_TEMPLATE (tmpl) = 0;
7276       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
7277       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
7278       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
7279         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
7280
7281       /* Inject this template into the global scope.  */
7282       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
7283     }
7284
7285   if (context)
7286     {
7287       if (TREE_CODE (context) == NAMESPACE_DECL)
7288         pop_nested_namespace (context);
7289       else
7290         pop_nested_class ();
7291     }
7292
7293   return friend_type;
7294 }
7295
7296 /* Returns zero if TYPE cannot be completed later due to circularity.
7297    Otherwise returns one.  */
7298
7299 static int
7300 can_complete_type_without_circularity (tree type)
7301 {
7302   if (type == NULL_TREE || type == error_mark_node)
7303     return 0;
7304   else if (COMPLETE_TYPE_P (type))
7305     return 1;
7306   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
7307     return can_complete_type_without_circularity (TREE_TYPE (type));
7308   else if (CLASS_TYPE_P (type)
7309            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
7310     return 0;
7311   else
7312     return 1;
7313 }
7314
7315 /* Apply any attributes which had to be deferred until instantiation
7316    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
7317    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
7318
7319 static void
7320 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
7321                                 tree args, tsubst_flags_t complain, tree in_decl)
7322 {
7323   tree last_dep = NULL_TREE;
7324   tree t;
7325   tree *p;
7326
7327   for (t = attributes; t; t = TREE_CHAIN (t))
7328     if (ATTR_IS_DEPENDENT (t))
7329       {
7330         last_dep = t;
7331         attributes = copy_list (attributes);
7332         break;
7333       }
7334
7335   if (DECL_P (*decl_p))
7336     {
7337       if (TREE_TYPE (*decl_p) == error_mark_node)
7338         return;
7339       p = &DECL_ATTRIBUTES (*decl_p);
7340     }
7341   else
7342     p = &TYPE_ATTRIBUTES (*decl_p);
7343
7344   if (last_dep)
7345     {
7346       tree late_attrs = NULL_TREE;
7347       tree *q = &late_attrs;
7348
7349       for (*p = attributes; *p; )
7350         {
7351           t = *p;
7352           if (ATTR_IS_DEPENDENT (t))
7353             {
7354               *p = TREE_CHAIN (t);
7355               TREE_CHAIN (t) = NULL_TREE;
7356               /* If the first attribute argument is an identifier, don't
7357                  pass it through tsubst.  Attributes like mode, format,
7358                  cleanup and several target specific attributes expect it
7359                  unmodified.  */
7360               if (TREE_VALUE (t)
7361                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
7362                   && TREE_VALUE (TREE_VALUE (t))
7363                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
7364                       == IDENTIFIER_NODE))
7365                 {
7366                   tree chain
7367                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
7368                                    in_decl,
7369                                    /*integral_constant_expression_p=*/false);
7370                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
7371                     TREE_VALUE (t)
7372                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
7373                                    chain);
7374                 }
7375               else
7376                 TREE_VALUE (t)
7377                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
7378                                  /*integral_constant_expression_p=*/false);
7379               *q = t;
7380               q = &TREE_CHAIN (t);
7381             }
7382           else
7383             p = &TREE_CHAIN (t);
7384         }
7385
7386       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
7387     }
7388 }
7389
7390 /* Perform (or defer) access check for typedefs that were referenced
7391    from within the template TMPL code.
7392    This is a subroutine of instantiate_template and instantiate_class_template.
7393    TMPL is the template to consider and TARGS is the list of arguments of
7394    that template.  */
7395
7396 static void
7397 perform_typedefs_access_check (tree tmpl, tree targs)
7398 {
7399   location_t saved_location;
7400   int i;
7401   qualified_typedef_usage_t *iter;
7402
7403   if (!tmpl
7404       || (!CLASS_TYPE_P (tmpl)
7405           && TREE_CODE (tmpl) != FUNCTION_DECL))
7406     return;
7407
7408   saved_location = input_location;
7409   for (i = 0;
7410        VEC_iterate (qualified_typedef_usage_t,
7411                     get_types_needing_access_check (tmpl),
7412                     i, iter);
7413         ++i)
7414     {
7415       tree type_decl = iter->typedef_decl;
7416       tree type_scope = iter->context;
7417
7418       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
7419         continue;
7420
7421       if (uses_template_parms (type_decl))
7422         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
7423       if (uses_template_parms (type_scope))
7424         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
7425
7426       /* Make access check error messages point to the location
7427          of the use of the typedef.  */
7428       input_location = iter->locus;
7429       perform_or_defer_access_check (TYPE_BINFO (type_scope),
7430                                      type_decl, type_decl);
7431     }
7432     input_location = saved_location;
7433 }
7434
7435 tree
7436 instantiate_class_template (tree type)
7437 {
7438   tree templ, args, pattern, t, member;
7439   tree typedecl;
7440   tree pbinfo;
7441   tree base_list;
7442   unsigned int saved_maximum_field_alignment;
7443
7444   if (type == error_mark_node)
7445     return error_mark_node;
7446
7447   if (TYPE_BEING_DEFINED (type)
7448       || COMPLETE_TYPE_P (type)
7449       || uses_template_parms (type))
7450     return type;
7451
7452   /* Figure out which template is being instantiated.  */
7453   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
7454   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7455
7456   /* Determine what specialization of the original template to
7457      instantiate.  */
7458   t = most_specialized_class (type, templ);
7459   if (t == error_mark_node)
7460     {
7461       TYPE_BEING_DEFINED (type) = 1;
7462       return error_mark_node;
7463     }
7464   else if (t)
7465     {
7466       /* This TYPE is actually an instantiation of a partial
7467          specialization.  We replace the innermost set of ARGS with
7468          the arguments appropriate for substitution.  For example,
7469          given:
7470
7471            template <class T> struct S {};
7472            template <class T> struct S<T*> {};
7473
7474          and supposing that we are instantiating S<int*>, ARGS will
7475          presently be {int*} -- but we need {int}.  */
7476       pattern = TREE_TYPE (t);
7477       args = TREE_PURPOSE (t);
7478     }
7479   else
7480     {
7481       pattern = TREE_TYPE (templ);
7482       args = CLASSTYPE_TI_ARGS (type);
7483     }
7484
7485   /* If the template we're instantiating is incomplete, then clearly
7486      there's nothing we can do.  */
7487   if (!COMPLETE_TYPE_P (pattern))
7488     return type;
7489
7490   /* If we've recursively instantiated too many templates, stop.  */
7491   if (! push_tinst_level (type))
7492     return type;
7493
7494   /* Now we're really doing the instantiation.  Mark the type as in
7495      the process of being defined.  */
7496   TYPE_BEING_DEFINED (type) = 1;
7497
7498   /* We may be in the middle of deferred access check.  Disable
7499      it now.  */
7500   push_deferring_access_checks (dk_no_deferred);
7501
7502   push_to_top_level ();
7503   /* Use #pragma pack from the template context.  */
7504   saved_maximum_field_alignment = maximum_field_alignment;
7505   maximum_field_alignment = TYPE_PRECISION (pattern);
7506
7507   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
7508
7509   /* Set the input location to the most specialized template definition.
7510      This is needed if tsubsting causes an error.  */
7511   typedecl = TYPE_MAIN_DECL (pattern);
7512   input_location = DECL_SOURCE_LOCATION (typedecl);
7513
7514   TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
7515   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
7516   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
7517   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
7518   TYPE_HAS_ASSIGN_REF (type) = TYPE_HAS_ASSIGN_REF (pattern);
7519   TYPE_HAS_CONST_ASSIGN_REF (type) = TYPE_HAS_CONST_ASSIGN_REF (pattern);
7520   TYPE_HAS_INIT_REF (type) = TYPE_HAS_INIT_REF (pattern);
7521   TYPE_HAS_CONST_INIT_REF (type) = TYPE_HAS_CONST_INIT_REF (pattern);
7522   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
7523   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
7524   TYPE_PACKED (type) = TYPE_PACKED (pattern);
7525   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
7526   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
7527   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
7528   if (ANON_AGGR_TYPE_P (pattern))
7529     SET_ANON_AGGR_TYPE_P (type);
7530   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
7531     {
7532       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
7533       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
7534     }
7535
7536   pbinfo = TYPE_BINFO (pattern);
7537
7538   /* We should never instantiate a nested class before its enclosing
7539      class; we need to look up the nested class by name before we can
7540      instantiate it, and that lookup should instantiate the enclosing
7541      class.  */
7542   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
7543               || COMPLETE_TYPE_P (TYPE_CONTEXT (type))
7544               || TYPE_BEING_DEFINED (TYPE_CONTEXT (type)));
7545
7546   base_list = NULL_TREE;
7547   if (BINFO_N_BASE_BINFOS (pbinfo))
7548     {
7549       tree pbase_binfo;
7550       tree context = TYPE_CONTEXT (type);
7551       tree pushed_scope;
7552       int i;
7553
7554       /* We must enter the scope containing the type, as that is where
7555          the accessibility of types named in dependent bases are
7556          looked up from.  */
7557       pushed_scope = push_scope (context ? context : global_namespace);
7558
7559       /* Substitute into each of the bases to determine the actual
7560          basetypes.  */
7561       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
7562         {
7563           tree base;
7564           tree access = BINFO_BASE_ACCESS (pbinfo, i);
7565           tree expanded_bases = NULL_TREE;
7566           int idx, len = 1;
7567
7568           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
7569             {
7570               expanded_bases = 
7571                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
7572                                        args, tf_error, NULL_TREE);
7573               if (expanded_bases == error_mark_node)
7574                 continue;
7575
7576               len = TREE_VEC_LENGTH (expanded_bases);
7577             }
7578
7579           for (idx = 0; idx < len; idx++)
7580             {
7581               if (expanded_bases)
7582                 /* Extract the already-expanded base class.  */
7583                 base = TREE_VEC_ELT (expanded_bases, idx);
7584               else
7585                 /* Substitute to figure out the base class.  */
7586                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
7587                                NULL_TREE);
7588
7589               if (base == error_mark_node)
7590                 continue;
7591
7592               base_list = tree_cons (access, base, base_list);
7593               if (BINFO_VIRTUAL_P (pbase_binfo))
7594                 TREE_TYPE (base_list) = integer_type_node;
7595             }
7596         }
7597
7598       /* The list is now in reverse order; correct that.  */
7599       base_list = nreverse (base_list);
7600
7601       if (pushed_scope)
7602         pop_scope (pushed_scope);
7603     }
7604   /* Now call xref_basetypes to set up all the base-class
7605      information.  */
7606   xref_basetypes (type, base_list);
7607
7608   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
7609                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
7610                                   args, tf_error, NULL_TREE);
7611
7612   /* Now that our base classes are set up, enter the scope of the
7613      class, so that name lookups into base classes, etc. will work
7614      correctly.  This is precisely analogous to what we do in
7615      begin_class_definition when defining an ordinary non-template
7616      class, except we also need to push the enclosing classes.  */
7617   push_nested_class (type);
7618
7619   /* Now members are processed in the order of declaration.  */
7620   for (member = CLASSTYPE_DECL_LIST (pattern);
7621        member; member = TREE_CHAIN (member))
7622     {
7623       tree t = TREE_VALUE (member);
7624
7625       if (TREE_PURPOSE (member))
7626         {
7627           if (TYPE_P (t))
7628             {
7629               /* Build new CLASSTYPE_NESTED_UTDS.  */
7630
7631               tree newtag;
7632               bool class_template_p;
7633
7634               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
7635                                   && TYPE_LANG_SPECIFIC (t)
7636                                   && CLASSTYPE_IS_TEMPLATE (t));
7637               /* If the member is a class template, then -- even after
7638                  substitution -- there may be dependent types in the
7639                  template argument list for the class.  We increment
7640                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
7641                  that function will assume that no types are dependent
7642                  when outside of a template.  */
7643               if (class_template_p)
7644                 ++processing_template_decl;
7645               newtag = tsubst (t, args, tf_error, NULL_TREE);
7646               if (class_template_p)
7647                 --processing_template_decl;
7648               if (newtag == error_mark_node)
7649                 continue;
7650
7651               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
7652                 {
7653                   tree name = TYPE_IDENTIFIER (t);
7654
7655                   if (class_template_p)
7656                     /* Unfortunately, lookup_template_class sets
7657                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
7658                        instantiation (i.e., for the type of a member
7659                        template class nested within a template class.)
7660                        This behavior is required for
7661                        maybe_process_partial_specialization to work
7662                        correctly, but is not accurate in this case;
7663                        the TAG is not an instantiation of anything.
7664                        (The corresponding TEMPLATE_DECL is an
7665                        instantiation, but the TYPE is not.) */
7666                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
7667
7668                   /* Now, we call pushtag to put this NEWTAG into the scope of
7669                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
7670                      pushtag calling push_template_decl.  We don't have to do
7671                      this for enums because it will already have been done in
7672                      tsubst_enum.  */
7673                   if (name)
7674                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
7675                   pushtag (name, newtag, /*tag_scope=*/ts_current);
7676                 }
7677             }
7678           else if (TREE_CODE (t) == FUNCTION_DECL
7679                    || DECL_FUNCTION_TEMPLATE_P (t))
7680             {
7681               /* Build new TYPE_METHODS.  */
7682               tree r;
7683
7684               if (TREE_CODE (t) == TEMPLATE_DECL)
7685                 ++processing_template_decl;
7686               r = tsubst (t, args, tf_error, NULL_TREE);
7687               if (TREE_CODE (t) == TEMPLATE_DECL)
7688                 --processing_template_decl;
7689               set_current_access_from_decl (r);
7690               finish_member_declaration (r);
7691             }
7692           else
7693             {
7694               /* Build new TYPE_FIELDS.  */
7695               if (TREE_CODE (t) == STATIC_ASSERT)
7696                 {
7697                   tree condition = 
7698                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
7699                                  tf_warning_or_error, NULL_TREE,
7700                                  /*integral_constant_expression_p=*/true);
7701                   finish_static_assert (condition,
7702                                         STATIC_ASSERT_MESSAGE (t), 
7703                                         STATIC_ASSERT_SOURCE_LOCATION (t),
7704                                         /*member_p=*/true);
7705                 }
7706               else if (TREE_CODE (t) != CONST_DECL)
7707                 {
7708                   tree r;
7709
7710                   /* The file and line for this declaration, to
7711                      assist in error message reporting.  Since we
7712                      called push_tinst_level above, we don't need to
7713                      restore these.  */
7714                   input_location = DECL_SOURCE_LOCATION (t);
7715
7716                   if (TREE_CODE (t) == TEMPLATE_DECL)
7717                     ++processing_template_decl;
7718                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
7719                   if (TREE_CODE (t) == TEMPLATE_DECL)
7720                     --processing_template_decl;
7721                   if (TREE_CODE (r) == VAR_DECL)
7722                     {
7723                       /* In [temp.inst]:
7724
7725                            [t]he initialization (and any associated
7726                            side-effects) of a static data member does
7727                            not occur unless the static data member is
7728                            itself used in a way that requires the
7729                            definition of the static data member to
7730                            exist.
7731
7732                          Therefore, we do not substitute into the
7733                          initialized for the static data member here.  */
7734                       finish_static_data_member_decl
7735                         (r,
7736                          /*init=*/NULL_TREE,
7737                          /*init_const_expr_p=*/false,
7738                          /*asmspec_tree=*/NULL_TREE,
7739                          /*flags=*/0);
7740                       if (DECL_INITIALIZED_IN_CLASS_P (r))
7741                         check_static_variable_definition (r, TREE_TYPE (r));
7742                     }
7743                   else if (TREE_CODE (r) == FIELD_DECL)
7744                     {
7745                       /* Determine whether R has a valid type and can be
7746                          completed later.  If R is invalid, then it is
7747                          replaced by error_mark_node so that it will not be
7748                          added to TYPE_FIELDS.  */
7749                       tree rtype = TREE_TYPE (r);
7750                       if (can_complete_type_without_circularity (rtype))
7751                         complete_type (rtype);
7752
7753                       if (!COMPLETE_TYPE_P (rtype))
7754                         {
7755                           cxx_incomplete_type_error (r, rtype);
7756                           r = error_mark_node;
7757                         }
7758                     }
7759
7760                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
7761                      such a thing will already have been added to the field
7762                      list by tsubst_enum in finish_member_declaration in the
7763                      CLASSTYPE_NESTED_UTDS case above.  */
7764                   if (!(TREE_CODE (r) == TYPE_DECL
7765                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
7766                         && DECL_ARTIFICIAL (r)))
7767                     {
7768                       set_current_access_from_decl (r);
7769                       finish_member_declaration (r);
7770                     }
7771                 }
7772             }
7773         }
7774       else
7775         {
7776           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
7777             {
7778               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
7779
7780               tree friend_type = t;
7781               bool adjust_processing_template_decl = false;
7782
7783               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7784                 {
7785                   /* template <class T> friend class C;  */
7786                   friend_type = tsubst_friend_class (friend_type, args);
7787                   adjust_processing_template_decl = true;
7788                 }
7789               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
7790                 {
7791                   /* template <class T> friend class C::D;  */
7792                   friend_type = tsubst (friend_type, args,
7793                                         tf_warning_or_error, NULL_TREE);
7794                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7795                     friend_type = TREE_TYPE (friend_type);
7796                   adjust_processing_template_decl = true;
7797                 }
7798               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
7799                 {
7800                   /* This could be either
7801
7802                        friend class T::C;
7803
7804                      when dependent_type_p is false or
7805
7806                        template <class U> friend class T::C;
7807
7808                      otherwise.  */
7809                   friend_type = tsubst (friend_type, args,
7810                                         tf_warning_or_error, NULL_TREE);
7811                   /* Bump processing_template_decl for correct
7812                      dependent_type_p calculation.  */
7813                   ++processing_template_decl;
7814                   if (dependent_type_p (friend_type))
7815                     adjust_processing_template_decl = true;
7816                   --processing_template_decl;
7817                 }
7818               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
7819                        && hidden_name_p (TYPE_NAME (friend_type)))
7820                 {
7821                   /* friend class C;
7822
7823                      where C hasn't been declared yet.  Let's lookup name
7824                      from namespace scope directly, bypassing any name that
7825                      come from dependent base class.  */
7826                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
7827
7828                   /* The call to xref_tag_from_type does injection for friend
7829                      classes.  */
7830                   push_nested_namespace (ns);
7831                   friend_type =
7832                     xref_tag_from_type (friend_type, NULL_TREE,
7833                                         /*tag_scope=*/ts_current);
7834                   pop_nested_namespace (ns);
7835                 }
7836               else if (uses_template_parms (friend_type))
7837                 /* friend class C<T>;  */
7838                 friend_type = tsubst (friend_type, args,
7839                                       tf_warning_or_error, NULL_TREE);
7840               /* Otherwise it's
7841
7842                    friend class C;
7843
7844                  where C is already declared or
7845
7846                    friend class C<int>;
7847
7848                  We don't have to do anything in these cases.  */
7849
7850               if (adjust_processing_template_decl)
7851                 /* Trick make_friend_class into realizing that the friend
7852                    we're adding is a template, not an ordinary class.  It's
7853                    important that we use make_friend_class since it will
7854                    perform some error-checking and output cross-reference
7855                    information.  */
7856                 ++processing_template_decl;
7857
7858               if (friend_type != error_mark_node)
7859                 make_friend_class (type, friend_type, /*complain=*/false);
7860
7861               if (adjust_processing_template_decl)
7862                 --processing_template_decl;
7863             }
7864           else
7865             {
7866               /* Build new DECL_FRIENDLIST.  */
7867               tree r;
7868
7869               /* The file and line for this declaration, to
7870                  assist in error message reporting.  Since we
7871                  called push_tinst_level above, we don't need to
7872                  restore these.  */
7873               input_location = DECL_SOURCE_LOCATION (t);
7874
7875               if (TREE_CODE (t) == TEMPLATE_DECL)
7876                 {
7877                   ++processing_template_decl;
7878                   push_deferring_access_checks (dk_no_check);
7879                 }
7880
7881               r = tsubst_friend_function (t, args);
7882               add_friend (type, r, /*complain=*/false);
7883               if (TREE_CODE (t) == TEMPLATE_DECL)
7884                 {
7885                   pop_deferring_access_checks ();
7886                   --processing_template_decl;
7887                 }
7888             }
7889         }
7890     }
7891
7892   /* Set the file and line number information to whatever is given for
7893      the class itself.  This puts error messages involving generated
7894      implicit functions at a predictable point, and the same point
7895      that would be used for non-template classes.  */
7896   input_location = DECL_SOURCE_LOCATION (typedecl);
7897
7898   unreverse_member_declarations (type);
7899   finish_struct_1 (type);
7900   TYPE_BEING_DEFINED (type) = 0;
7901
7902   /* Now that the class is complete, instantiate default arguments for
7903      any member functions.  We don't do this earlier because the
7904      default arguments may reference members of the class.  */
7905   if (!PRIMARY_TEMPLATE_P (templ))
7906     for (t = TYPE_METHODS (type); t; t = TREE_CHAIN (t))
7907       if (TREE_CODE (t) == FUNCTION_DECL
7908           /* Implicitly generated member functions will not have template
7909              information; they are not instantiations, but instead are
7910              created "fresh" for each instantiation.  */
7911           && DECL_TEMPLATE_INFO (t))
7912         tsubst_default_arguments (t);
7913
7914   /* Some typedefs referenced from within the template code need to be access
7915      checked at template instantiation time, i.e now. These types were
7916      added to the template at parsing time. Let's get those and perform
7917      the access checks then.  */
7918   perform_typedefs_access_check (pattern, args);
7919   perform_deferred_access_checks ();
7920   pop_nested_class ();
7921   maximum_field_alignment = saved_maximum_field_alignment;
7922   pop_from_top_level ();
7923   pop_deferring_access_checks ();
7924   pop_tinst_level ();
7925
7926   /* The vtable for a template class can be emitted in any translation
7927      unit in which the class is instantiated.  When there is no key
7928      method, however, finish_struct_1 will already have added TYPE to
7929      the keyed_classes list.  */
7930   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
7931     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
7932
7933   return type;
7934 }
7935
7936 static tree
7937 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
7938 {
7939   tree r;
7940
7941   if (!t)
7942     r = t;
7943   else if (TYPE_P (t))
7944     r = tsubst (t, args, complain, in_decl);
7945   else
7946     {
7947       r = tsubst_expr (t, args, complain, in_decl,
7948                        /*integral_constant_expression_p=*/true);
7949       r = fold_non_dependent_expr (r);
7950     }
7951   return r;
7952 }
7953
7954 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
7955    NONTYPE_ARGUMENT_PACK.  */
7956
7957 static tree
7958 make_fnparm_pack (tree spec_parm)
7959 {
7960   /* Collect all of the extra "packed" parameters into an
7961      argument pack.  */
7962   tree parmvec;
7963   tree parmtypevec;
7964   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
7965   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
7966   int i, len = list_length (spec_parm);
7967
7968   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
7969   parmvec = make_tree_vec (len);
7970   parmtypevec = make_tree_vec (len);
7971   for (i = 0; i < len; i++, spec_parm = TREE_CHAIN (spec_parm))
7972     {
7973       TREE_VEC_ELT (parmvec, i) = spec_parm;
7974       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
7975     }
7976
7977   /* Build the argument packs.  */
7978   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
7979   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
7980   TREE_TYPE (argpack) = argtypepack;
7981
7982   return argpack;
7983 }        
7984
7985 /* Substitute ARGS into T, which is an pack expansion
7986    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
7987    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
7988    (if only a partial substitution could be performed) or
7989    ERROR_MARK_NODE if there was an error.  */
7990 tree
7991 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
7992                        tree in_decl)
7993 {
7994   tree pattern;
7995   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
7996   tree first_arg_pack; int i, len = -1;
7997   tree result;
7998   int incomplete = 0;
7999   bool very_local_specializations = false;
8000
8001   gcc_assert (PACK_EXPANSION_P (t));
8002   pattern = PACK_EXPANSION_PATTERN (t);
8003
8004   /* Determine the argument packs that will instantiate the parameter
8005      packs used in the expansion expression. While we're at it,
8006      compute the number of arguments to be expanded and make sure it
8007      is consistent.  */
8008   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
8009        pack = TREE_CHAIN (pack))
8010     {
8011       tree parm_pack = TREE_VALUE (pack);
8012       tree arg_pack = NULL_TREE;
8013       tree orig_arg = NULL_TREE;
8014
8015       if (TREE_CODE (parm_pack) == PARM_DECL)
8016         {
8017           arg_pack = retrieve_local_specialization (parm_pack);
8018           if (arg_pack == NULL_TREE)
8019             {
8020               /* This can happen for a parameter name used later in a function
8021                  declaration (such as in a late-specified return type).  Just
8022                  make a dummy decl, since it's only used for its type.  */
8023               gcc_assert (cp_unevaluated_operand != 0);
8024               arg_pack = tsubst_decl (parm_pack, args, complain);
8025               arg_pack = make_fnparm_pack (arg_pack);
8026             }
8027         }
8028       else
8029         {
8030           int level, idx, levels;
8031           template_parm_level_and_index (parm_pack, &level, &idx);
8032
8033           levels = TMPL_ARGS_DEPTH (args);
8034           if (level <= levels)
8035             arg_pack = TMPL_ARG (args, level, idx);
8036         }
8037
8038       orig_arg = arg_pack;
8039       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
8040         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
8041       
8042       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
8043         /* This can only happen if we forget to expand an argument
8044            pack somewhere else. Just return an error, silently.  */
8045         {
8046           result = make_tree_vec (1);
8047           TREE_VEC_ELT (result, 0) = error_mark_node;
8048           return result;
8049         }
8050
8051       if (arg_pack
8052           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
8053           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
8054         {
8055           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
8056           tree pattern = PACK_EXPANSION_PATTERN (expansion);
8057           if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
8058               || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
8059             /* The argument pack that the parameter maps to is just an
8060                expansion of the parameter itself, such as one would
8061                find in the implicit typedef of a class inside the
8062                class itself.  Consider this parameter "unsubstituted",
8063                so that we will maintain the outer pack expansion.  */
8064             arg_pack = NULL_TREE;
8065         }
8066           
8067       if (arg_pack)
8068         {
8069           int my_len = 
8070             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
8071
8072           /* It's all-or-nothing with incomplete argument packs.  */
8073           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8074             return error_mark_node;
8075           
8076           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8077             incomplete = 1;
8078
8079           if (len < 0)
8080             {
8081               len = my_len;
8082               first_arg_pack = arg_pack;
8083             }
8084           else if (len != my_len)
8085             {
8086               if (incomplete)
8087                 /* We got explicit args for some packs but not others;
8088                    do nothing now and try again after deduction.  */
8089                 return t;
8090               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
8091                 error ("mismatched argument pack lengths while expanding "
8092                        "%<%T%>",
8093                        pattern);
8094               else
8095                 error ("mismatched argument pack lengths while expanding "
8096                        "%<%E%>",
8097                        pattern);
8098               return error_mark_node;
8099             }
8100
8101           /* Keep track of the parameter packs and their corresponding
8102              argument packs.  */
8103           packs = tree_cons (parm_pack, arg_pack, packs);
8104           TREE_TYPE (packs) = orig_arg;
8105         }
8106       else
8107         /* We can't substitute for this parameter pack.  */
8108         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
8109                                          TREE_VALUE (pack),
8110                                          unsubstituted_packs);
8111     }
8112
8113   /* We cannot expand this expansion expression, because we don't have
8114      all of the argument packs we need. Substitute into the pattern
8115      and return a PACK_EXPANSION_*. The caller will need to deal with
8116      that.  */
8117   if (unsubstituted_packs)
8118     {
8119       tree new_pat;
8120       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8121         new_pat = tsubst_expr (pattern, args, complain, in_decl,
8122                                /*integral_constant_expression_p=*/false);
8123       else
8124         new_pat = tsubst (pattern, args, complain, in_decl);
8125       return make_pack_expansion (new_pat);
8126     }
8127
8128   /* We could not find any argument packs that work.  */
8129   if (len < 0)
8130     return error_mark_node;
8131
8132   if (!local_specializations)
8133     {
8134       /* We're in a late-specified return type, so we don't have a local
8135          specializations table.  Create one for doing this expansion.  */
8136       very_local_specializations = true;
8137       local_specializations = htab_create (37,
8138                                            hash_local_specialization,
8139                                            eq_local_specializations,
8140                                            NULL);
8141     }
8142
8143   /* For each argument in each argument pack, substitute into the
8144      pattern.  */
8145   result = make_tree_vec (len + incomplete);
8146   for (i = 0; i < len + incomplete; ++i)
8147     {
8148       /* For parameter pack, change the substitution of the parameter
8149          pack to the ith argument in its argument pack, then expand
8150          the pattern.  */
8151       for (pack = packs; pack; pack = TREE_CHAIN (pack))
8152         {
8153           tree parm = TREE_PURPOSE (pack);
8154
8155           if (TREE_CODE (parm) == PARM_DECL)
8156             {
8157               /* Select the Ith argument from the pack.  */
8158               tree arg = make_node (ARGUMENT_PACK_SELECT);
8159               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
8160               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
8161               mark_used (parm);
8162               register_local_specialization (arg, parm);
8163             }
8164           else
8165             {
8166               tree value = parm;
8167               int idx, level;
8168               template_parm_level_and_index (parm, &level, &idx);
8169               
8170               if (i < len) 
8171                 {
8172                   /* Select the Ith argument from the pack. */
8173                   value = make_node (ARGUMENT_PACK_SELECT);
8174                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
8175                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
8176                 }
8177
8178               /* Update the corresponding argument.  */
8179               TMPL_ARG (args, level, idx) = value;
8180             }
8181         }
8182
8183       /* Substitute into the PATTERN with the altered arguments.  */
8184       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8185         TREE_VEC_ELT (result, i) = 
8186           tsubst_expr (pattern, args, complain, in_decl,
8187                        /*integral_constant_expression_p=*/false);
8188       else
8189         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
8190
8191       if (i == len)
8192         /* When we have incomplete argument packs, the last "expanded"
8193            result is itself a pack expansion, which allows us
8194            to deduce more arguments.  */
8195         TREE_VEC_ELT (result, i) = 
8196           make_pack_expansion (TREE_VEC_ELT (result, i));
8197
8198       if (TREE_VEC_ELT (result, i) == error_mark_node)
8199         {
8200           result = error_mark_node;
8201           break;
8202         }
8203     }
8204
8205   /* Update ARGS to restore the substitution from parameter packs to
8206      their argument packs.  */
8207   for (pack = packs; pack; pack = TREE_CHAIN (pack))
8208     {
8209       tree parm = TREE_PURPOSE (pack);
8210
8211       if (TREE_CODE (parm) == PARM_DECL)
8212         register_local_specialization (TREE_TYPE (pack), parm);
8213       else
8214         {
8215           int idx, level;
8216           template_parm_level_and_index (parm, &level, &idx);
8217           
8218           /* Update the corresponding argument.  */
8219           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
8220             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
8221               TREE_TYPE (pack);
8222           else
8223             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
8224         }
8225     }
8226
8227   if (very_local_specializations)
8228     {
8229       htab_delete (local_specializations);
8230       local_specializations = NULL;
8231     }
8232   
8233   return result;
8234 }
8235
8236 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
8237    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
8238    parameter packs; all parms generated from a function parameter pack will
8239    have the same DECL_PARM_INDEX.  */
8240
8241 tree
8242 get_pattern_parm (tree parm, tree tmpl)
8243 {
8244   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
8245   tree patparm;
8246
8247   if (DECL_ARTIFICIAL (parm))
8248     {
8249       for (patparm = DECL_ARGUMENTS (pattern);
8250            patparm; patparm = TREE_CHAIN (patparm))
8251         if (DECL_ARTIFICIAL (patparm)
8252             && DECL_NAME (parm) == DECL_NAME (patparm))
8253           break;
8254     }
8255   else
8256     {
8257       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
8258       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
8259       gcc_assert (DECL_PARM_INDEX (patparm)
8260                   == DECL_PARM_INDEX (parm));
8261     }
8262
8263   return patparm;
8264 }
8265
8266 /* Substitute ARGS into the vector or list of template arguments T.  */
8267
8268 static tree
8269 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8270 {
8271   tree orig_t = t;
8272   int len = TREE_VEC_LENGTH (t);
8273   int need_new = 0, i, expanded_len_adjust = 0, out;
8274   tree *elts = (tree *) alloca (len * sizeof (tree));
8275
8276   for (i = 0; i < len; i++)
8277     {
8278       tree orig_arg = TREE_VEC_ELT (t, i);
8279       tree new_arg;
8280
8281       if (TREE_CODE (orig_arg) == TREE_VEC)
8282         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
8283       else if (PACK_EXPANSION_P (orig_arg))
8284         {
8285           /* Substitute into an expansion expression.  */
8286           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
8287
8288           if (TREE_CODE (new_arg) == TREE_VEC)
8289             /* Add to the expanded length adjustment the number of
8290                expanded arguments. We subtract one from this
8291                measurement, because the argument pack expression
8292                itself is already counted as 1 in
8293                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
8294                the argument pack is empty.  */
8295             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
8296         }
8297       else if (ARGUMENT_PACK_P (orig_arg))
8298         {
8299           /* Substitute into each of the arguments.  */
8300           new_arg = TYPE_P (orig_arg)
8301             ? cxx_make_type (TREE_CODE (orig_arg))
8302             : make_node (TREE_CODE (orig_arg));
8303           
8304           SET_ARGUMENT_PACK_ARGS (
8305             new_arg,
8306             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
8307                                   args, complain, in_decl));
8308
8309           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
8310             new_arg = error_mark_node;
8311
8312           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
8313             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
8314                                           complain, in_decl);
8315             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
8316
8317             if (TREE_TYPE (new_arg) == error_mark_node)
8318               new_arg = error_mark_node;
8319           }
8320         }
8321       else
8322         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
8323
8324       if (new_arg == error_mark_node)
8325         return error_mark_node;
8326
8327       elts[i] = new_arg;
8328       if (new_arg != orig_arg)
8329         need_new = 1;
8330     }
8331
8332   if (!need_new)
8333     return t;
8334
8335   /* Make space for the expanded arguments coming from template
8336      argument packs.  */
8337   t = make_tree_vec (len + expanded_len_adjust);
8338   for (i = 0, out = 0; i < len; i++)
8339     {
8340       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
8341            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
8342           && TREE_CODE (elts[i]) == TREE_VEC)
8343         {
8344           int idx;
8345
8346           /* Now expand the template argument pack "in place".  */
8347           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
8348             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
8349         }
8350       else
8351         {
8352           TREE_VEC_ELT (t, out) = elts[i];
8353           out++;
8354         }
8355     }
8356
8357   return t;
8358 }
8359
8360 /* Return the result of substituting ARGS into the template parameters
8361    given by PARMS.  If there are m levels of ARGS and m + n levels of
8362    PARMS, then the result will contain n levels of PARMS.  For
8363    example, if PARMS is `template <class T> template <class U>
8364    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
8365    result will be `template <int*, double, class V>'.  */
8366
8367 static tree
8368 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
8369 {
8370   tree r = NULL_TREE;
8371   tree* new_parms;
8372
8373   /* When substituting into a template, we must set
8374      PROCESSING_TEMPLATE_DECL as the template parameters may be
8375      dependent if they are based on one-another, and the dependency
8376      predicates are short-circuit outside of templates.  */
8377   ++processing_template_decl;
8378
8379   for (new_parms = &r;
8380        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
8381        new_parms = &(TREE_CHAIN (*new_parms)),
8382          parms = TREE_CHAIN (parms))
8383     {
8384       tree new_vec =
8385         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
8386       int i;
8387
8388       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
8389         {
8390           tree tuple;
8391           tree default_value;
8392           tree parm_decl;
8393
8394           if (parms == error_mark_node)
8395             continue;
8396
8397           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
8398
8399           if (tuple == error_mark_node)
8400             continue;
8401
8402           default_value = TREE_PURPOSE (tuple);
8403           parm_decl = TREE_VALUE (tuple);
8404
8405           parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
8406           if (TREE_CODE (parm_decl) == PARM_DECL
8407               && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
8408             parm_decl = error_mark_node;
8409           default_value = tsubst_template_arg (default_value, args,
8410                                                complain, NULL_TREE);
8411
8412           tuple = build_tree_list (default_value, parm_decl);
8413           TREE_VEC_ELT (new_vec, i) = tuple;
8414         }
8415
8416       *new_parms =
8417         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
8418                              - TMPL_ARGS_DEPTH (args)),
8419                    new_vec, NULL_TREE);
8420     }
8421
8422   --processing_template_decl;
8423
8424   return r;
8425 }
8426
8427 /* Substitute the ARGS into the indicated aggregate (or enumeration)
8428    type T.  If T is not an aggregate or enumeration type, it is
8429    handled as if by tsubst.  IN_DECL is as for tsubst.  If
8430    ENTERING_SCOPE is nonzero, T is the context for a template which
8431    we are presently tsubst'ing.  Return the substituted value.  */
8432
8433 static tree
8434 tsubst_aggr_type (tree t,
8435                   tree args,
8436                   tsubst_flags_t complain,
8437                   tree in_decl,
8438                   int entering_scope)
8439 {
8440   if (t == NULL_TREE)
8441     return NULL_TREE;
8442
8443   switch (TREE_CODE (t))
8444     {
8445     case RECORD_TYPE:
8446       if (TYPE_PTRMEMFUNC_P (t))
8447         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
8448
8449       /* Else fall through.  */
8450     case ENUMERAL_TYPE:
8451     case UNION_TYPE:
8452       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
8453         {
8454           tree argvec;
8455           tree context;
8456           tree r;
8457           int saved_unevaluated_operand;
8458           int saved_inhibit_evaluation_warnings;
8459
8460           /* In "sizeof(X<I>)" we need to evaluate "I".  */
8461           saved_unevaluated_operand = cp_unevaluated_operand;
8462           cp_unevaluated_operand = 0;
8463           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
8464           c_inhibit_evaluation_warnings = 0;
8465
8466           /* First, determine the context for the type we are looking
8467              up.  */
8468           context = TYPE_CONTEXT (t);
8469           if (context)
8470             {
8471               context = tsubst_aggr_type (context, args, complain,
8472                                           in_decl, /*entering_scope=*/1);
8473               /* If context is a nested class inside a class template,
8474                  it may still need to be instantiated (c++/33959).  */
8475               if (TYPE_P (context))
8476                 context = complete_type (context);
8477             }
8478
8479           /* Then, figure out what arguments are appropriate for the
8480              type we are trying to find.  For example, given:
8481
8482                template <class T> struct S;
8483                template <class T, class U> void f(T, U) { S<U> su; }
8484
8485              and supposing that we are instantiating f<int, double>,
8486              then our ARGS will be {int, double}, but, when looking up
8487              S we only want {double}.  */
8488           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
8489                                          complain, in_decl);
8490           if (argvec == error_mark_node)
8491             r = error_mark_node;
8492           else
8493             {
8494               r = lookup_template_class (t, argvec, in_decl, context,
8495                                          entering_scope, complain);
8496               r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
8497             }
8498
8499           cp_unevaluated_operand = saved_unevaluated_operand;
8500           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
8501
8502           return r;
8503         }
8504       else
8505         /* This is not a template type, so there's nothing to do.  */
8506         return t;
8507
8508     default:
8509       return tsubst (t, args, complain, in_decl);
8510     }
8511 }
8512
8513 /* Substitute into the default argument ARG (a default argument for
8514    FN), which has the indicated TYPE.  */
8515
8516 tree
8517 tsubst_default_argument (tree fn, tree type, tree arg)
8518 {
8519   tree saved_class_ptr = NULL_TREE;
8520   tree saved_class_ref = NULL_TREE;
8521
8522   /* This default argument came from a template.  Instantiate the
8523      default argument here, not in tsubst.  In the case of
8524      something like:
8525
8526        template <class T>
8527        struct S {
8528          static T t();
8529          void f(T = t());
8530        };
8531
8532      we must be careful to do name lookup in the scope of S<T>,
8533      rather than in the current class.  */
8534   push_access_scope (fn);
8535   /* The "this" pointer is not valid in a default argument.  */
8536   if (cfun)
8537     {
8538       saved_class_ptr = current_class_ptr;
8539       cp_function_chain->x_current_class_ptr = NULL_TREE;
8540       saved_class_ref = current_class_ref;
8541       cp_function_chain->x_current_class_ref = NULL_TREE;
8542     }
8543
8544   push_deferring_access_checks(dk_no_deferred);
8545   /* The default argument expression may cause implicitly defined
8546      member functions to be synthesized, which will result in garbage
8547      collection.  We must treat this situation as if we were within
8548      the body of function so as to avoid collecting live data on the
8549      stack.  */
8550   ++function_depth;
8551   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
8552                      tf_warning_or_error, NULL_TREE,
8553                      /*integral_constant_expression_p=*/false);
8554   --function_depth;
8555   pop_deferring_access_checks();
8556
8557   /* Restore the "this" pointer.  */
8558   if (cfun)
8559     {
8560       cp_function_chain->x_current_class_ptr = saved_class_ptr;
8561       cp_function_chain->x_current_class_ref = saved_class_ref;
8562     }
8563
8564   /* Make sure the default argument is reasonable.  */
8565   arg = check_default_argument (type, arg);
8566
8567   pop_access_scope (fn);
8568
8569   return arg;
8570 }
8571
8572 /* Substitute into all the default arguments for FN.  */
8573
8574 static void
8575 tsubst_default_arguments (tree fn)
8576 {
8577   tree arg;
8578   tree tmpl_args;
8579
8580   tmpl_args = DECL_TI_ARGS (fn);
8581
8582   /* If this function is not yet instantiated, we certainly don't need
8583      its default arguments.  */
8584   if (uses_template_parms (tmpl_args))
8585     return;
8586
8587   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
8588        arg;
8589        arg = TREE_CHAIN (arg))
8590     if (TREE_PURPOSE (arg))
8591       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
8592                                                     TREE_VALUE (arg),
8593                                                     TREE_PURPOSE (arg));
8594 }
8595
8596 /* Substitute the ARGS into the T, which is a _DECL.  Return the
8597    result of the substitution.  Issue error and warning messages under
8598    control of COMPLAIN.  */
8599
8600 static tree
8601 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
8602 {
8603 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
8604   location_t saved_loc;
8605   tree r = NULL_TREE;
8606   tree in_decl = t;
8607   hashval_t hash = 0;
8608
8609   /* Set the filename and linenumber to improve error-reporting.  */
8610   saved_loc = input_location;
8611   input_location = DECL_SOURCE_LOCATION (t);
8612
8613   switch (TREE_CODE (t))
8614     {
8615     case TEMPLATE_DECL:
8616       {
8617         /* We can get here when processing a member function template,
8618            member class template, or template template parameter.  */
8619         tree decl = DECL_TEMPLATE_RESULT (t);
8620         tree spec;
8621         tree tmpl_args;
8622         tree full_args;
8623
8624         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
8625           {
8626             /* Template template parameter is treated here.  */
8627             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8628             if (new_type == error_mark_node)
8629               RETURN (error_mark_node);
8630
8631             r = copy_decl (t);
8632             TREE_CHAIN (r) = NULL_TREE;
8633             TREE_TYPE (r) = new_type;
8634             DECL_TEMPLATE_RESULT (r)
8635               = build_decl (DECL_SOURCE_LOCATION (decl),
8636                             TYPE_DECL, DECL_NAME (decl), new_type);
8637             DECL_TEMPLATE_PARMS (r)
8638               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8639                                        complain);
8640             TYPE_NAME (new_type) = r;
8641             break;
8642           }
8643
8644         /* We might already have an instance of this template.
8645            The ARGS are for the surrounding class type, so the
8646            full args contain the tsubst'd args for the context,
8647            plus the innermost args from the template decl.  */
8648         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
8649           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
8650           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
8651         /* Because this is a template, the arguments will still be
8652            dependent, even after substitution.  If
8653            PROCESSING_TEMPLATE_DECL is not set, the dependency
8654            predicates will short-circuit.  */
8655         ++processing_template_decl;
8656         full_args = tsubst_template_args (tmpl_args, args,
8657                                           complain, in_decl);
8658         --processing_template_decl;
8659         if (full_args == error_mark_node)
8660           RETURN (error_mark_node);
8661
8662         /* If this is a default template template argument,
8663            tsubst might not have changed anything.  */
8664         if (full_args == tmpl_args)
8665           RETURN (t);
8666
8667         hash = hash_tmpl_and_args (t, full_args);
8668         spec = retrieve_specialization (t, full_args, hash);
8669         if (spec != NULL_TREE)
8670           {
8671             r = spec;
8672             break;
8673           }
8674
8675         /* Make a new template decl.  It will be similar to the
8676            original, but will record the current template arguments.
8677            We also create a new function declaration, which is just
8678            like the old one, but points to this new template, rather
8679            than the old one.  */
8680         r = copy_decl (t);
8681         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
8682         TREE_CHAIN (r) = NULL_TREE;
8683
8684         DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
8685
8686         if (TREE_CODE (decl) == TYPE_DECL)
8687           {
8688             tree new_type;
8689             ++processing_template_decl;
8690             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8691             --processing_template_decl;
8692             if (new_type == error_mark_node)
8693               RETURN (error_mark_node);
8694
8695             TREE_TYPE (r) = new_type;
8696             CLASSTYPE_TI_TEMPLATE (new_type) = r;
8697             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
8698             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
8699             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
8700           }
8701         else
8702           {
8703             tree new_decl;
8704             ++processing_template_decl;
8705             new_decl = tsubst (decl, args, complain, in_decl);
8706             --processing_template_decl;
8707             if (new_decl == error_mark_node)
8708               RETURN (error_mark_node);
8709
8710             DECL_TEMPLATE_RESULT (r) = new_decl;
8711             DECL_TI_TEMPLATE (new_decl) = r;
8712             TREE_TYPE (r) = TREE_TYPE (new_decl);
8713             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
8714             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
8715           }
8716
8717         SET_DECL_IMPLICIT_INSTANTIATION (r);
8718         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
8719         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
8720
8721         /* The template parameters for this new template are all the
8722            template parameters for the old template, except the
8723            outermost level of parameters.  */
8724         DECL_TEMPLATE_PARMS (r)
8725           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8726                                    complain);
8727
8728         if (PRIMARY_TEMPLATE_P (t))
8729           DECL_PRIMARY_TEMPLATE (r) = r;
8730
8731         if (TREE_CODE (decl) != TYPE_DECL)
8732           /* Record this non-type partial instantiation.  */
8733           register_specialization (r, t,
8734                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
8735                                    false, hash);
8736       }
8737       break;
8738
8739     case FUNCTION_DECL:
8740       {
8741         tree ctx;
8742         tree argvec = NULL_TREE;
8743         tree *friends;
8744         tree gen_tmpl;
8745         tree type;
8746         int member;
8747         int args_depth;
8748         int parms_depth;
8749
8750         /* Nobody should be tsubst'ing into non-template functions.  */
8751         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
8752
8753         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
8754           {
8755             tree spec;
8756             bool dependent_p;
8757
8758             /* If T is not dependent, just return it.  We have to
8759                increment PROCESSING_TEMPLATE_DECL because
8760                value_dependent_expression_p assumes that nothing is
8761                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
8762             ++processing_template_decl;
8763             dependent_p = value_dependent_expression_p (t);
8764             --processing_template_decl;
8765             if (!dependent_p)
8766               RETURN (t);
8767
8768             /* Calculate the most general template of which R is a
8769                specialization, and the complete set of arguments used to
8770                specialize R.  */
8771             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
8772             argvec = tsubst_template_args (DECL_TI_ARGS
8773                                            (DECL_TEMPLATE_RESULT (gen_tmpl)),
8774                                            args, complain, in_decl);
8775
8776             /* Check to see if we already have this specialization.  */
8777             hash = hash_tmpl_and_args (gen_tmpl, argvec);
8778             spec = retrieve_specialization (gen_tmpl, argvec, hash);
8779
8780             if (spec)
8781               {
8782                 r = spec;
8783                 break;
8784               }
8785
8786             /* We can see more levels of arguments than parameters if
8787                there was a specialization of a member template, like
8788                this:
8789
8790                  template <class T> struct S { template <class U> void f(); }
8791                  template <> template <class U> void S<int>::f(U);
8792
8793                Here, we'll be substituting into the specialization,
8794                because that's where we can find the code we actually
8795                want to generate, but we'll have enough arguments for
8796                the most general template.
8797
8798                We also deal with the peculiar case:
8799
8800                  template <class T> struct S {
8801                    template <class U> friend void f();
8802                  };
8803                  template <class U> void f() {}
8804                  template S<int>;
8805                  template void f<double>();
8806
8807                Here, the ARGS for the instantiation of will be {int,
8808                double}.  But, we only need as many ARGS as there are
8809                levels of template parameters in CODE_PATTERN.  We are
8810                careful not to get fooled into reducing the ARGS in
8811                situations like:
8812
8813                  template <class T> struct S { template <class U> void f(U); }
8814                  template <class T> template <> void S<T>::f(int) {}
8815
8816                which we can spot because the pattern will be a
8817                specialization in this case.  */
8818             args_depth = TMPL_ARGS_DEPTH (args);
8819             parms_depth =
8820               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
8821             if (args_depth > parms_depth
8822                 && !DECL_TEMPLATE_SPECIALIZATION (t))
8823               args = get_innermost_template_args (args, parms_depth);
8824           }
8825         else
8826           {
8827             /* This special case arises when we have something like this:
8828
8829                  template <class T> struct S {
8830                    friend void f<int>(int, double);
8831                  };
8832
8833                Here, the DECL_TI_TEMPLATE for the friend declaration
8834                will be an IDENTIFIER_NODE.  We are being called from
8835                tsubst_friend_function, and we want only to create a
8836                new decl (R) with appropriate types so that we can call
8837                determine_specialization.  */
8838             gen_tmpl = NULL_TREE;
8839           }
8840
8841         if (DECL_CLASS_SCOPE_P (t))
8842           {
8843             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
8844               member = 2;
8845             else
8846               member = 1;
8847             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
8848                                     complain, t, /*entering_scope=*/1);
8849           }
8850         else
8851           {
8852             member = 0;
8853             ctx = DECL_CONTEXT (t);
8854           }
8855         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8856         if (type == error_mark_node)
8857           RETURN (error_mark_node);
8858
8859         /* We do NOT check for matching decls pushed separately at this
8860            point, as they may not represent instantiations of this
8861            template, and in any case are considered separate under the
8862            discrete model.  */
8863         r = copy_decl (t);
8864         DECL_USE_TEMPLATE (r) = 0;
8865         TREE_TYPE (r) = type;
8866         /* Clear out the mangled name and RTL for the instantiation.  */
8867         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
8868         SET_DECL_RTL (r, NULL_RTX);
8869         /* Leave DECL_INITIAL set on deleted instantiations.  */
8870         if (!DECL_DELETED_FN (r))
8871           DECL_INITIAL (r) = NULL_TREE;
8872         DECL_CONTEXT (r) = ctx;
8873
8874         if (member && DECL_CONV_FN_P (r))
8875           /* Type-conversion operator.  Reconstruct the name, in
8876              case it's the name of one of the template's parameters.  */
8877           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
8878
8879         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
8880                                      complain, t);
8881         DECL_RESULT (r) = NULL_TREE;
8882
8883         TREE_STATIC (r) = 0;
8884         TREE_PUBLIC (r) = TREE_PUBLIC (t);
8885         DECL_EXTERNAL (r) = 1;
8886         /* If this is an instantiation of a function with internal
8887            linkage, we already know what object file linkage will be
8888            assigned to the instantiation.  */
8889         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
8890         DECL_DEFER_OUTPUT (r) = 0;
8891         TREE_CHAIN (r) = NULL_TREE;
8892         DECL_PENDING_INLINE_INFO (r) = 0;
8893         DECL_PENDING_INLINE_P (r) = 0;
8894         DECL_SAVED_TREE (r) = NULL_TREE;
8895         DECL_STRUCT_FUNCTION (r) = NULL;
8896         TREE_USED (r) = 0;
8897         /* We'll re-clone as appropriate in instantiate_template.  */
8898         DECL_CLONED_FUNCTION (r) = NULL_TREE;
8899
8900         /* If we aren't complaining now, return on error before we register
8901            the specialization so that we'll complain eventually.  */
8902         if ((complain & tf_error) == 0
8903             && IDENTIFIER_OPNAME_P (DECL_NAME (r))
8904             && !grok_op_properties (r, /*complain=*/false))
8905           RETURN (error_mark_node);
8906
8907         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
8908            this in the special friend case mentioned above where
8909            GEN_TMPL is NULL.  */
8910         if (gen_tmpl)
8911           {
8912             DECL_TEMPLATE_INFO (r)
8913               = build_template_info (gen_tmpl, argvec);
8914             SET_DECL_IMPLICIT_INSTANTIATION (r);
8915             register_specialization (r, gen_tmpl, argvec, false, hash);
8916
8917             /* We're not supposed to instantiate default arguments
8918                until they are called, for a template.  But, for a
8919                declaration like:
8920
8921                  template <class T> void f ()
8922                  { extern void g(int i = T()); }
8923
8924                we should do the substitution when the template is
8925                instantiated.  We handle the member function case in
8926                instantiate_class_template since the default arguments
8927                might refer to other members of the class.  */
8928             if (!member
8929                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
8930                 && !uses_template_parms (argvec))
8931               tsubst_default_arguments (r);
8932           }
8933         else
8934           DECL_TEMPLATE_INFO (r) = NULL_TREE;
8935
8936         /* Copy the list of befriending classes.  */
8937         for (friends = &DECL_BEFRIENDING_CLASSES (r);
8938              *friends;
8939              friends = &TREE_CHAIN (*friends))
8940           {
8941             *friends = copy_node (*friends);
8942             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
8943                                             args, complain,
8944                                             in_decl);
8945           }
8946
8947         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
8948           {
8949             maybe_retrofit_in_chrg (r);
8950             if (DECL_CONSTRUCTOR_P (r))
8951               grok_ctor_properties (ctx, r);
8952             /* If this is an instantiation of a member template, clone it.
8953                If it isn't, that'll be handled by
8954                clone_constructors_and_destructors.  */
8955             if (PRIMARY_TEMPLATE_P (gen_tmpl))
8956               clone_function_decl (r, /*update_method_vec_p=*/0);
8957           }
8958         else if ((complain & tf_error) != 0
8959                  && IDENTIFIER_OPNAME_P (DECL_NAME (r))
8960                  && !grok_op_properties (r, /*complain=*/true))
8961           RETURN (error_mark_node);
8962
8963         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
8964           SET_DECL_FRIEND_CONTEXT (r,
8965                                    tsubst (DECL_FRIEND_CONTEXT (t),
8966                                             args, complain, in_decl));
8967
8968         /* Possibly limit visibility based on template args.  */
8969         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
8970         if (DECL_VISIBILITY_SPECIFIED (t))
8971           {
8972             DECL_VISIBILITY_SPECIFIED (r) = 0;
8973             DECL_ATTRIBUTES (r)
8974               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
8975           }
8976         determine_visibility (r);
8977         if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
8978             && !processing_template_decl)
8979           defaulted_late_check (r);
8980
8981         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
8982                                         args, complain, in_decl);
8983       }
8984       break;
8985
8986     case PARM_DECL:
8987       {
8988         tree type = NULL_TREE;
8989         int i, len = 1;
8990         tree expanded_types = NULL_TREE;
8991         tree prev_r = NULL_TREE;
8992         tree first_r = NULL_TREE;
8993
8994         if (FUNCTION_PARAMETER_PACK_P (t))
8995           {
8996             /* If there is a local specialization that isn't a
8997                parameter pack, it means that we're doing a "simple"
8998                substitution from inside tsubst_pack_expansion. Just
8999                return the local specialization (which will be a single
9000                parm).  */
9001             tree spec = retrieve_local_specialization (t);
9002             if (spec 
9003                 && TREE_CODE (spec) == PARM_DECL
9004                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
9005               RETURN (spec);
9006
9007             /* Expand the TYPE_PACK_EXPANSION that provides the types for
9008                the parameters in this function parameter pack.  */
9009             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
9010                                                     complain, in_decl);
9011             if (TREE_CODE (expanded_types) == TREE_VEC)
9012               {
9013                 len = TREE_VEC_LENGTH (expanded_types);
9014
9015                 /* Zero-length parameter packs are boring. Just substitute
9016                    into the chain.  */
9017                 if (len == 0)
9018                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
9019                                   TREE_CHAIN (t)));
9020               }
9021             else
9022               {
9023                 /* All we did was update the type. Make a note of that.  */
9024                 type = expanded_types;
9025                 expanded_types = NULL_TREE;
9026               }
9027           }
9028
9029         /* Loop through all of the parameter's we'll build. When T is
9030            a function parameter pack, LEN is the number of expanded
9031            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
9032         r = NULL_TREE;
9033         for (i = 0; i < len; ++i)
9034           {
9035             prev_r = r;
9036             r = copy_node (t);
9037             if (DECL_TEMPLATE_PARM_P (t))
9038               SET_DECL_TEMPLATE_PARM_P (r);
9039
9040             /* An argument of a function parameter pack is not a parameter
9041                pack.  */
9042             FUNCTION_PARAMETER_PACK_P (r) = false;
9043
9044             if (expanded_types)
9045               /* We're on the Ith parameter of the function parameter
9046                  pack.  */
9047               {
9048                 /* Get the Ith type.  */
9049                 type = TREE_VEC_ELT (expanded_types, i);
9050
9051                 if (DECL_NAME (r))
9052                   /* Rename the parameter to include the index.  */
9053                   DECL_NAME (r) =
9054                     make_ith_pack_parameter_name (DECL_NAME (r), i);
9055               }
9056             else if (!type)
9057               /* We're dealing with a normal parameter.  */
9058               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9059
9060             type = type_decays_to (type);
9061             TREE_TYPE (r) = type;
9062             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9063
9064             if (DECL_INITIAL (r))
9065               {
9066                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
9067                   DECL_INITIAL (r) = TREE_TYPE (r);
9068                 else
9069                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
9070                                              complain, in_decl);
9071               }
9072
9073             DECL_CONTEXT (r) = NULL_TREE;
9074
9075             if (!DECL_TEMPLATE_PARM_P (r))
9076               DECL_ARG_TYPE (r) = type_passed_as (type);
9077
9078             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9079                                             args, complain, in_decl);
9080
9081             /* Keep track of the first new parameter we
9082                generate. That's what will be returned to the
9083                caller.  */
9084             if (!first_r)
9085               first_r = r;
9086
9087             /* Build a proper chain of parameters when substituting
9088                into a function parameter pack.  */
9089             if (prev_r)
9090               TREE_CHAIN (prev_r) = r;
9091           }
9092
9093         if (TREE_CHAIN (t))
9094           TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args,
9095                                    complain, TREE_CHAIN (t));
9096
9097         /* FIRST_R contains the start of the chain we've built.  */
9098         r = first_r;
9099       }
9100       break;
9101
9102     case FIELD_DECL:
9103       {
9104         tree type;
9105
9106         r = copy_decl (t);
9107         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9108         if (type == error_mark_node)
9109           RETURN (error_mark_node);
9110         TREE_TYPE (r) = type;
9111         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9112
9113         /* DECL_INITIAL gives the number of bits in a bit-field.  */
9114         DECL_INITIAL (r)
9115           = tsubst_expr (DECL_INITIAL (t), args,
9116                          complain, in_decl,
9117                          /*integral_constant_expression_p=*/true);
9118         /* We don't have to set DECL_CONTEXT here; it is set by
9119            finish_member_declaration.  */
9120         TREE_CHAIN (r) = NULL_TREE;
9121         if (VOID_TYPE_P (type))
9122           error ("instantiation of %q+D as type %qT", r, type);
9123
9124         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9125                                         args, complain, in_decl);
9126       }
9127       break;
9128
9129     case USING_DECL:
9130       /* We reach here only for member using decls.  */
9131       if (DECL_DEPENDENT_P (t))
9132         {
9133           r = do_class_using_decl
9134             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
9135              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
9136           if (!r)
9137             r = error_mark_node;
9138           else
9139             {
9140               TREE_PROTECTED (r) = TREE_PROTECTED (t);
9141               TREE_PRIVATE (r) = TREE_PRIVATE (t);
9142             }
9143         }
9144       else
9145         {
9146           r = copy_node (t);
9147           TREE_CHAIN (r) = NULL_TREE;
9148         }
9149       break;
9150
9151     case TYPE_DECL:
9152     case VAR_DECL:
9153       {
9154         tree argvec = NULL_TREE;
9155         tree gen_tmpl = NULL_TREE;
9156         tree spec;
9157         tree tmpl = NULL_TREE;
9158         tree ctx;
9159         tree type = NULL_TREE;
9160         bool local_p;
9161
9162         if (TREE_CODE (t) == TYPE_DECL
9163             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
9164           {
9165             /* If this is the canonical decl, we don't have to
9166                mess with instantiations, and often we can't (for
9167                typename, template type parms and such).  Note that
9168                TYPE_NAME is not correct for the above test if
9169                we've copied the type for a typedef.  */
9170             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9171             if (type == error_mark_node)
9172               RETURN (error_mark_node);
9173             r = TYPE_NAME (type);
9174             break;
9175           }
9176
9177         /* Check to see if we already have the specialization we
9178            need.  */
9179         spec = NULL_TREE;
9180         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
9181           {
9182             /* T is a static data member or namespace-scope entity.
9183                We have to substitute into namespace-scope variables
9184                (even though such entities are never templates) because
9185                of cases like:
9186                
9187                  template <class T> void f() { extern T t; }
9188
9189                where the entity referenced is not known until
9190                instantiation time.  */
9191             local_p = false;
9192             ctx = DECL_CONTEXT (t);
9193             if (DECL_CLASS_SCOPE_P (t))
9194               {
9195                 ctx = tsubst_aggr_type (ctx, args,
9196                                         complain,
9197                                         in_decl, /*entering_scope=*/1);
9198                 /* If CTX is unchanged, then T is in fact the
9199                    specialization we want.  That situation occurs when
9200                    referencing a static data member within in its own
9201                    class.  We can use pointer equality, rather than
9202                    same_type_p, because DECL_CONTEXT is always
9203                    canonical.  */
9204                 if (ctx == DECL_CONTEXT (t))
9205                   spec = t;
9206               }
9207
9208             if (!spec)
9209               {
9210                 tmpl = DECL_TI_TEMPLATE (t);
9211                 gen_tmpl = most_general_template (tmpl);
9212                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
9213                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
9214                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
9215               }
9216           }
9217         else
9218           {
9219             /* A local variable.  */
9220             local_p = true;
9221             /* Subsequent calls to pushdecl will fill this in.  */
9222             ctx = NULL_TREE;
9223             spec = retrieve_local_specialization (t);
9224           }
9225         /* If we already have the specialization we need, there is
9226            nothing more to do.  */ 
9227         if (spec)
9228           {
9229             r = spec;
9230             break;
9231           }
9232
9233         /* Create a new node for the specialization we need.  */
9234         r = copy_decl (t);
9235         if (type == NULL_TREE)
9236           type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9237         if (TREE_CODE (r) == VAR_DECL)
9238           {
9239             /* Even if the original location is out of scope, the
9240                newly substituted one is not.  */
9241             DECL_DEAD_FOR_LOCAL (r) = 0;
9242             DECL_INITIALIZED_P (r) = 0;
9243             DECL_TEMPLATE_INSTANTIATED (r) = 0;
9244             if (type == error_mark_node)
9245               RETURN (error_mark_node);
9246             if (TREE_CODE (type) == FUNCTION_TYPE)
9247               {
9248                 /* It may seem that this case cannot occur, since:
9249
9250                      typedef void f();
9251                      void g() { f x; }
9252
9253                    declares a function, not a variable.  However:
9254       
9255                      typedef void f();
9256                      template <typename T> void g() { T t; }
9257                      template void g<f>();
9258
9259                    is an attempt to declare a variable with function
9260                    type.  */
9261                 error ("variable %qD has function type",
9262                        /* R is not yet sufficiently initialized, so we
9263                           just use its name.  */
9264                        DECL_NAME (r));
9265                 RETURN (error_mark_node);
9266               }
9267             type = complete_type (type);
9268             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
9269               = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t);
9270             type = check_var_type (DECL_NAME (r), type);
9271
9272             if (DECL_HAS_VALUE_EXPR_P (t))
9273               {
9274                 tree ve = DECL_VALUE_EXPR (t);
9275                 ve = tsubst_expr (ve, args, complain, in_decl,
9276                                   /*constant_expression_p=*/false);
9277                 SET_DECL_VALUE_EXPR (r, ve);
9278               }
9279           }
9280         else if (DECL_SELF_REFERENCE_P (t))
9281           SET_DECL_SELF_REFERENCE_P (r);
9282         TREE_TYPE (r) = type;
9283         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9284         DECL_CONTEXT (r) = ctx;
9285         /* Clear out the mangled name and RTL for the instantiation.  */
9286         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9287         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9288           SET_DECL_RTL (r, NULL_RTX);
9289         /* The initializer must not be expanded until it is required;
9290            see [temp.inst].  */
9291         DECL_INITIAL (r) = NULL_TREE;
9292         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9293           SET_DECL_RTL (r, NULL_RTX);
9294         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
9295         if (TREE_CODE (r) == VAR_DECL)
9296           {
9297             /* Possibly limit visibility based on template args.  */
9298             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
9299             if (DECL_VISIBILITY_SPECIFIED (t))
9300               {
9301                 DECL_VISIBILITY_SPECIFIED (r) = 0;
9302                 DECL_ATTRIBUTES (r)
9303                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
9304               }
9305             determine_visibility (r);
9306           }
9307         /* Preserve a typedef that names a type.  */
9308         else if (TREE_CODE (r) == TYPE_DECL
9309                  && DECL_ORIGINAL_TYPE (t)
9310                  && type != error_mark_node)
9311           {
9312             DECL_ORIGINAL_TYPE (r) = tsubst (DECL_ORIGINAL_TYPE (t),
9313                                              args, complain, in_decl);
9314             TREE_TYPE (r) = type = build_variant_type_copy (type);
9315             TYPE_NAME (type) = r;
9316           }
9317
9318         if (!local_p)
9319           {
9320             /* A static data member declaration is always marked
9321                external when it is declared in-class, even if an
9322                initializer is present.  We mimic the non-template
9323                processing here.  */
9324             DECL_EXTERNAL (r) = 1;
9325
9326             register_specialization (r, gen_tmpl, argvec, false, hash);
9327             DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
9328             SET_DECL_IMPLICIT_INSTANTIATION (r);
9329           }
9330         else if (cp_unevaluated_operand)
9331           {
9332             /* We're substituting this var in a decltype outside of its
9333                scope, such as for a lambda return type.  Don't add it to
9334                local_specializations, do perform auto deduction.  */
9335             tree auto_node = type_uses_auto (type);
9336             tree init
9337               = tsubst_expr (DECL_INITIAL (t), args, complain, in_decl,
9338                              /*constant_expression_p=*/false);
9339
9340             if (auto_node && init && describable_type (init))
9341               {
9342                 type = do_auto_deduction (type, init, auto_node);
9343                 TREE_TYPE (r) = type;
9344               }
9345           }
9346         else
9347           register_local_specialization (r, t);
9348
9349         TREE_CHAIN (r) = NULL_TREE;
9350
9351         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
9352                                         (int) ATTR_FLAG_TYPE_IN_PLACE,
9353                                         args, complain, in_decl);
9354         layout_decl (r, 0);
9355       }
9356       break;
9357
9358     default:
9359       gcc_unreachable ();
9360     }
9361 #undef RETURN
9362
9363  out:
9364   /* Restore the file and line information.  */
9365   input_location = saved_loc;
9366
9367   return r;
9368 }
9369
9370 /* Substitute into the ARG_TYPES of a function type.  */
9371
9372 static tree
9373 tsubst_arg_types (tree arg_types,
9374                   tree args,
9375                   tsubst_flags_t complain,
9376                   tree in_decl)
9377 {
9378   tree remaining_arg_types;
9379   tree type = NULL_TREE;
9380   int i = 1;
9381   tree expanded_args = NULL_TREE;
9382   tree default_arg;
9383
9384   if (!arg_types || arg_types == void_list_node)
9385     return arg_types;
9386
9387   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
9388                                           args, complain, in_decl);
9389   if (remaining_arg_types == error_mark_node)
9390     return error_mark_node;
9391
9392   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
9393     {
9394       /* For a pack expansion, perform substitution on the
9395          entire expression. Later on, we'll handle the arguments
9396          one-by-one.  */
9397       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
9398                                             args, complain, in_decl);
9399
9400       if (TREE_CODE (expanded_args) == TREE_VEC)
9401         /* So that we'll spin through the parameters, one by one.  */
9402         i = TREE_VEC_LENGTH (expanded_args);
9403       else
9404         {
9405           /* We only partially substituted into the parameter
9406              pack. Our type is TYPE_PACK_EXPANSION.  */
9407           type = expanded_args;
9408           expanded_args = NULL_TREE;
9409         }
9410     }
9411
9412   while (i > 0) {
9413     --i;
9414     
9415     if (expanded_args)
9416       type = TREE_VEC_ELT (expanded_args, i);
9417     else if (!type)
9418       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
9419
9420     if (type == error_mark_node)
9421       return error_mark_node;
9422     if (VOID_TYPE_P (type))
9423       {
9424         if (complain & tf_error)
9425           {
9426             error ("invalid parameter type %qT", type);
9427             if (in_decl)
9428               error ("in declaration %q+D", in_decl);
9429           }
9430         return error_mark_node;
9431     }
9432     
9433     /* Do array-to-pointer, function-to-pointer conversion, and ignore
9434        top-level qualifiers as required.  */
9435     type = TYPE_MAIN_VARIANT (type_decays_to (type));
9436
9437     /* We do not substitute into default arguments here.  The standard
9438        mandates that they be instantiated only when needed, which is
9439        done in build_over_call.  */
9440     default_arg = TREE_PURPOSE (arg_types);
9441
9442     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
9443       {
9444         /* We've instantiated a template before its default arguments
9445            have been parsed.  This can happen for a nested template
9446            class, and is not an error unless we require the default
9447            argument in a call of this function.  */
9448         remaining_arg_types = 
9449           tree_cons (default_arg, type, remaining_arg_types);
9450         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
9451                        remaining_arg_types);
9452       }
9453     else
9454       remaining_arg_types = 
9455         hash_tree_cons (default_arg, type, remaining_arg_types);
9456   }
9457         
9458   return remaining_arg_types;
9459 }
9460
9461 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
9462    *not* handle the exception-specification for FNTYPE, because the
9463    initial substitution of explicitly provided template parameters
9464    during argument deduction forbids substitution into the
9465    exception-specification:
9466
9467      [temp.deduct]
9468
9469      All references in the function type of the function template to  the
9470      corresponding template parameters are replaced by the specified tem-
9471      plate argument values.  If a substitution in a template parameter or
9472      in  the function type of the function template results in an invalid
9473      type, type deduction fails.  [Note: The equivalent  substitution  in
9474      exception specifications is done only when the function is instanti-
9475      ated, at which point a program is  ill-formed  if  the  substitution
9476      results in an invalid type.]  */
9477
9478 static tree
9479 tsubst_function_type (tree t,
9480                       tree args,
9481                       tsubst_flags_t complain,
9482                       tree in_decl)
9483 {
9484   tree return_type;
9485   tree arg_types;
9486   tree fntype;
9487
9488   /* The TYPE_CONTEXT is not used for function/method types.  */
9489   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
9490
9491   /* Substitute the return type.  */
9492   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9493   if (return_type == error_mark_node)
9494     return error_mark_node;
9495   /* The standard does not presently indicate that creation of a
9496      function type with an invalid return type is a deduction failure.
9497      However, that is clearly analogous to creating an array of "void"
9498      or a reference to a reference.  This is core issue #486.  */
9499   if (TREE_CODE (return_type) == ARRAY_TYPE
9500       || TREE_CODE (return_type) == FUNCTION_TYPE)
9501     {
9502       if (complain & tf_error)
9503         {
9504           if (TREE_CODE (return_type) == ARRAY_TYPE)
9505             error ("function returning an array");
9506           else
9507             error ("function returning a function");
9508         }
9509       return error_mark_node;
9510     }
9511
9512   /* Substitute the argument types.  */
9513   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
9514                                 complain, in_decl);
9515   if (arg_types == error_mark_node)
9516     return error_mark_node;
9517
9518   /* Construct a new type node and return it.  */
9519   if (TREE_CODE (t) == FUNCTION_TYPE)
9520     fntype = build_function_type (return_type, arg_types);
9521   else
9522     {
9523       tree r = TREE_TYPE (TREE_VALUE (arg_types));
9524       if (! MAYBE_CLASS_TYPE_P (r))
9525         {
9526           /* [temp.deduct]
9527
9528              Type deduction may fail for any of the following
9529              reasons:
9530
9531              -- Attempting to create "pointer to member of T" when T
9532              is not a class type.  */
9533           if (complain & tf_error)
9534             error ("creating pointer to member function of non-class type %qT",
9535                       r);
9536           return error_mark_node;
9537         }
9538
9539       fntype = build_method_type_directly (r, return_type,
9540                                            TREE_CHAIN (arg_types));
9541     }
9542   fntype = cp_build_qualified_type_real (fntype, TYPE_QUALS (t), complain);
9543   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
9544
9545   return fntype;
9546 }
9547
9548 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
9549    ARGS into that specification, and return the substituted
9550    specification.  If there is no specification, return NULL_TREE.  */
9551
9552 static tree
9553 tsubst_exception_specification (tree fntype,
9554                                 tree args,
9555                                 tsubst_flags_t complain,
9556                                 tree in_decl)
9557 {
9558   tree specs;
9559   tree new_specs;
9560
9561   specs = TYPE_RAISES_EXCEPTIONS (fntype);
9562   new_specs = NULL_TREE;
9563   if (specs)
9564     {
9565       if (! TREE_VALUE (specs))
9566         new_specs = specs;
9567       else
9568         while (specs)
9569           {
9570             tree spec;
9571             int i, len = 1;
9572             tree expanded_specs = NULL_TREE;
9573
9574             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
9575               {
9576                 /* Expand the pack expansion type.  */
9577                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
9578                                                        args, complain,
9579                                                        in_decl);
9580
9581                 if (expanded_specs == error_mark_node)
9582                   return error_mark_node;
9583                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
9584                   len = TREE_VEC_LENGTH (expanded_specs);
9585                 else
9586                   {
9587                     /* We're substituting into a member template, so
9588                        we got a TYPE_PACK_EXPANSION back.  Add that
9589                        expansion and move on.  */
9590                     gcc_assert (TREE_CODE (expanded_specs) 
9591                                 == TYPE_PACK_EXPANSION);
9592                     new_specs = add_exception_specifier (new_specs,
9593                                                          expanded_specs,
9594                                                          complain);
9595                     specs = TREE_CHAIN (specs);
9596                     continue;
9597                   }
9598               }
9599
9600             for (i = 0; i < len; ++i)
9601               {
9602                 if (expanded_specs)
9603                   spec = TREE_VEC_ELT (expanded_specs, i);
9604                 else
9605                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
9606                 if (spec == error_mark_node)
9607                   return spec;
9608                 new_specs = add_exception_specifier (new_specs, spec, 
9609                                                      complain);
9610               }
9611
9612             specs = TREE_CHAIN (specs);
9613           }
9614     }
9615   return new_specs;
9616 }
9617
9618 /* Take the tree structure T and replace template parameters used
9619    therein with the argument vector ARGS.  IN_DECL is an associated
9620    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
9621    Issue error and warning messages under control of COMPLAIN.  Note
9622    that we must be relatively non-tolerant of extensions here, in
9623    order to preserve conformance; if we allow substitutions that
9624    should not be allowed, we may allow argument deductions that should
9625    not succeed, and therefore report ambiguous overload situations
9626    where there are none.  In theory, we could allow the substitution,
9627    but indicate that it should have failed, and allow our caller to
9628    make sure that the right thing happens, but we don't try to do this
9629    yet.
9630
9631    This function is used for dealing with types, decls and the like;
9632    for expressions, use tsubst_expr or tsubst_copy.  */
9633
9634 tree
9635 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9636 {
9637   tree type, r;
9638
9639   if (t == NULL_TREE || t == error_mark_node
9640       || t == integer_type_node
9641       || t == void_type_node
9642       || t == char_type_node
9643       || t == unknown_type_node
9644       || TREE_CODE (t) == NAMESPACE_DECL)
9645     return t;
9646
9647   if (DECL_P (t))
9648     return tsubst_decl (t, args, complain);
9649
9650   if (args == NULL_TREE)
9651     return t;
9652
9653   if (TREE_CODE (t) == IDENTIFIER_NODE)
9654     type = IDENTIFIER_TYPE_VALUE (t);
9655   else
9656     type = TREE_TYPE (t);
9657
9658   gcc_assert (type != unknown_type_node);
9659
9660   /* Reuse typedefs.  We need to do this to handle dependent attributes,
9661      such as attribute aligned.  */
9662   if (TYPE_P (t)
9663       && TYPE_NAME (t)
9664       && TYPE_NAME (t) != TYPE_MAIN_DECL (t))
9665     {
9666       tree decl = TYPE_NAME (t);
9667       
9668       if (DECL_CLASS_SCOPE_P (decl)
9669           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
9670           && uses_template_parms (DECL_CONTEXT (decl)))
9671         {
9672           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
9673           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
9674           r = retrieve_specialization (tmpl, gen_args, 0);
9675         }
9676       else if (DECL_FUNCTION_SCOPE_P (decl)
9677                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
9678                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
9679         r = retrieve_local_specialization (decl);
9680       else
9681         /* The typedef is from a non-template context.  */
9682         return t;
9683
9684       if (r)
9685         {
9686           r = TREE_TYPE (r);
9687           r = cp_build_qualified_type_real
9688             (r, cp_type_quals (t) | cp_type_quals (r),
9689              complain | tf_ignore_bad_quals);
9690           return r;
9691         }
9692       /* Else we must be instantiating the typedef, so fall through.  */
9693     }
9694
9695   if (type
9696       && TREE_CODE (t) != TYPENAME_TYPE
9697       && TREE_CODE (t) != IDENTIFIER_NODE
9698       && TREE_CODE (t) != FUNCTION_TYPE
9699       && TREE_CODE (t) != METHOD_TYPE)
9700     type = tsubst (type, args, complain, in_decl);
9701   if (type == error_mark_node)
9702     return error_mark_node;
9703
9704   switch (TREE_CODE (t))
9705     {
9706     case RECORD_TYPE:
9707     case UNION_TYPE:
9708     case ENUMERAL_TYPE:
9709       return tsubst_aggr_type (t, args, complain, in_decl,
9710                                /*entering_scope=*/0);
9711
9712     case ERROR_MARK:
9713     case IDENTIFIER_NODE:
9714     case VOID_TYPE:
9715     case REAL_TYPE:
9716     case COMPLEX_TYPE:
9717     case VECTOR_TYPE:
9718     case BOOLEAN_TYPE:
9719     case INTEGER_CST:
9720     case REAL_CST:
9721     case STRING_CST:
9722       return t;
9723
9724     case INTEGER_TYPE:
9725       if (t == integer_type_node)
9726         return t;
9727
9728       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
9729           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
9730         return t;
9731
9732       {
9733         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
9734
9735         max = tsubst_expr (omax, args, complain, in_decl,
9736                            /*integral_constant_expression_p=*/false);
9737
9738         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
9739            needed.  */
9740         if (TREE_CODE (max) == NOP_EXPR
9741             && TREE_SIDE_EFFECTS (omax)
9742             && !TREE_TYPE (max))
9743           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
9744
9745         max = fold_decl_constant_value (max);
9746
9747         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
9748            with TREE_SIDE_EFFECTS that indicates this is not an integral
9749            constant expression.  */
9750         if (processing_template_decl
9751             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
9752           {
9753             gcc_assert (TREE_CODE (max) == NOP_EXPR);
9754             TREE_SIDE_EFFECTS (max) = 1;
9755           }
9756
9757         if (TREE_CODE (max) != INTEGER_CST
9758             && !at_function_scope_p ()
9759             && !TREE_SIDE_EFFECTS (max)
9760             && !value_dependent_expression_p (max))
9761           {
9762             if (complain & tf_error)
9763               error ("array bound is not an integer constant");
9764             return error_mark_node;
9765           }
9766
9767         /* [temp.deduct]
9768
9769            Type deduction may fail for any of the following
9770            reasons:
9771
9772              Attempting to create an array with a size that is
9773              zero or negative.  */
9774         if (integer_zerop (max) && !(complain & tf_error))
9775           /* We must fail if performing argument deduction (as
9776              indicated by the state of complain), so that
9777              another substitution can be found.  */
9778           return error_mark_node;
9779         else if (TREE_CODE (max) == INTEGER_CST
9780                  && INT_CST_LT (max, integer_zero_node))
9781           {
9782             if (complain & tf_error)
9783               error ("creating array with negative size (%qE)", max);
9784
9785             return error_mark_node;
9786           }
9787
9788         return compute_array_index_type (NULL_TREE, max);
9789       }
9790
9791     case TEMPLATE_TYPE_PARM:
9792     case TEMPLATE_TEMPLATE_PARM:
9793     case BOUND_TEMPLATE_TEMPLATE_PARM:
9794     case TEMPLATE_PARM_INDEX:
9795       {
9796         int idx;
9797         int level;
9798         int levels;
9799         tree arg = NULL_TREE;
9800
9801         r = NULL_TREE;
9802
9803         gcc_assert (TREE_VEC_LENGTH (args) > 0);
9804         template_parm_level_and_index (t, &level, &idx); 
9805
9806         levels = TMPL_ARGS_DEPTH (args);
9807         if (level <= levels)
9808           {
9809             arg = TMPL_ARG (args, level, idx);
9810
9811             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
9812               /* See through ARGUMENT_PACK_SELECT arguments. */
9813               arg = ARGUMENT_PACK_SELECT_ARG (arg);
9814           }
9815
9816         if (arg == error_mark_node)
9817           return error_mark_node;
9818         else if (arg != NULL_TREE)
9819           {
9820             if (ARGUMENT_PACK_P (arg))
9821               /* If ARG is an argument pack, we don't actually want to
9822                  perform a substitution here, because substitutions
9823                  for argument packs are only done
9824                  element-by-element. We can get to this point when
9825                  substituting the type of a non-type template
9826                  parameter pack, when that type actually contains
9827                  template parameter packs from an outer template, e.g.,
9828
9829                  template<typename... Types> struct A {
9830                    template<Types... Values> struct B { };
9831                  };  */
9832               return t;
9833
9834             if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
9835               {
9836                 int quals;
9837                 gcc_assert (TYPE_P (arg));
9838
9839                 /* cv-quals from the template are discarded when
9840                    substituting in a function or reference type.  */
9841                 if (TREE_CODE (arg) == FUNCTION_TYPE
9842                     || TREE_CODE (arg) == METHOD_TYPE
9843                     || TREE_CODE (arg) == REFERENCE_TYPE)
9844                   quals = cp_type_quals (arg);
9845                 else
9846                   quals = cp_type_quals (arg) | cp_type_quals (t);
9847                   
9848                 return cp_build_qualified_type_real
9849                   (arg, quals, complain | tf_ignore_bad_quals);
9850               }
9851             else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9852               {
9853                 /* We are processing a type constructed from a
9854                    template template parameter.  */
9855                 tree argvec = tsubst (TYPE_TI_ARGS (t),
9856                                       args, complain, in_decl);
9857                 if (argvec == error_mark_node)
9858                   return error_mark_node;
9859
9860                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
9861                    are resolving nested-types in the signature of a
9862                    member function templates.  Otherwise ARG is a
9863                    TEMPLATE_DECL and is the real template to be
9864                    instantiated.  */
9865                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
9866                   arg = TYPE_NAME (arg);
9867
9868                 r = lookup_template_class (arg,
9869                                            argvec, in_decl,
9870                                            DECL_CONTEXT (arg),
9871                                             /*entering_scope=*/0,
9872                                            complain);
9873                 return cp_build_qualified_type_real
9874                   (r, TYPE_QUALS (t), complain);
9875               }
9876             else
9877               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
9878               return arg;
9879           }
9880
9881         if (level == 1)
9882           /* This can happen during the attempted tsubst'ing in
9883              unify.  This means that we don't yet have any information
9884              about the template parameter in question.  */
9885           return t;
9886
9887         /* If we get here, we must have been looking at a parm for a
9888            more deeply nested template.  Make a new version of this
9889            template parameter, but with a lower level.  */
9890         switch (TREE_CODE (t))
9891           {
9892           case TEMPLATE_TYPE_PARM:
9893           case TEMPLATE_TEMPLATE_PARM:
9894           case BOUND_TEMPLATE_TEMPLATE_PARM:
9895             if (cp_type_quals (t))
9896               {
9897                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
9898                 r = cp_build_qualified_type_real
9899                   (r, cp_type_quals (t),
9900                    complain | (TREE_CODE (t) == TEMPLATE_TYPE_PARM
9901                                ? tf_ignore_bad_quals : 0));
9902               }
9903             else
9904               {
9905                 r = copy_type (t);
9906                 TEMPLATE_TYPE_PARM_INDEX (r)
9907                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
9908                                                 r, levels, args, complain);
9909                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
9910                 TYPE_MAIN_VARIANT (r) = r;
9911                 TYPE_POINTER_TO (r) = NULL_TREE;
9912                 TYPE_REFERENCE_TO (r) = NULL_TREE;
9913
9914                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
9915                   /* We have reduced the level of the template
9916                      template parameter, but not the levels of its
9917                      template parameters, so canonical_type_parameter
9918                      will not be able to find the canonical template
9919                      template parameter for this level. Thus, we
9920                      require structural equality checking to compare
9921                      TEMPLATE_TEMPLATE_PARMs. */
9922                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9923                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
9924                   SET_TYPE_STRUCTURAL_EQUALITY (r);
9925                 else
9926                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
9927
9928                 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
9929                   {
9930                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
9931                                           complain, in_decl);
9932                     if (argvec == error_mark_node)
9933                       return error_mark_node;
9934
9935                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
9936                       = build_template_info (TYPE_TI_TEMPLATE (t), argvec);
9937                   }
9938               }
9939             break;
9940
9941           case TEMPLATE_PARM_INDEX:
9942             r = reduce_template_parm_level (t, type, levels, args, complain);
9943             break;
9944
9945           default:
9946             gcc_unreachable ();
9947           }
9948
9949         return r;
9950       }
9951
9952     case TREE_LIST:
9953       {
9954         tree purpose, value, chain;
9955
9956         if (t == void_list_node)
9957           return t;
9958
9959         purpose = TREE_PURPOSE (t);
9960         if (purpose)
9961           {
9962             purpose = tsubst (purpose, args, complain, in_decl);
9963             if (purpose == error_mark_node)
9964               return error_mark_node;
9965           }
9966         value = TREE_VALUE (t);
9967         if (value)
9968           {
9969             value = tsubst (value, args, complain, in_decl);
9970             if (value == error_mark_node)
9971               return error_mark_node;
9972           }
9973         chain = TREE_CHAIN (t);
9974         if (chain && chain != void_type_node)
9975           {
9976             chain = tsubst (chain, args, complain, in_decl);
9977             if (chain == error_mark_node)
9978               return error_mark_node;
9979           }
9980         if (purpose == TREE_PURPOSE (t)
9981             && value == TREE_VALUE (t)
9982             && chain == TREE_CHAIN (t))
9983           return t;
9984         return hash_tree_cons (purpose, value, chain);
9985       }
9986
9987     case TREE_BINFO:
9988       /* We should never be tsubsting a binfo.  */
9989       gcc_unreachable ();
9990
9991     case TREE_VEC:
9992       /* A vector of template arguments.  */
9993       gcc_assert (!type);
9994       return tsubst_template_args (t, args, complain, in_decl);
9995
9996     case POINTER_TYPE:
9997     case REFERENCE_TYPE:
9998       {
9999         enum tree_code code;
10000
10001         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
10002           return t;
10003
10004         code = TREE_CODE (t);
10005
10006
10007         /* [temp.deduct]
10008
10009            Type deduction may fail for any of the following
10010            reasons:
10011
10012            -- Attempting to create a pointer to reference type.
10013            -- Attempting to create a reference to a reference type or
10014               a reference to void.
10015
10016           Core issue 106 says that creating a reference to a reference
10017           during instantiation is no longer a cause for failure. We
10018           only enforce this check in strict C++98 mode.  */
10019         if ((TREE_CODE (type) == REFERENCE_TYPE
10020              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
10021             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
10022           {
10023             static location_t last_loc;
10024
10025             /* We keep track of the last time we issued this error
10026                message to avoid spewing a ton of messages during a
10027                single bad template instantiation.  */
10028             if (complain & tf_error
10029                 && last_loc != input_location)
10030               {
10031                 if (TREE_CODE (type) == VOID_TYPE)
10032                   error ("forming reference to void");
10033                 else
10034                   error ("forming %s to reference type %qT",
10035                          (code == POINTER_TYPE) ? "pointer" : "reference",
10036                          type);
10037                 last_loc = input_location;
10038               }
10039
10040             return error_mark_node;
10041           }
10042         else if (code == POINTER_TYPE)
10043           {
10044             r = build_pointer_type (type);
10045             if (TREE_CODE (type) == METHOD_TYPE)
10046               r = build_ptrmemfunc_type (r);
10047           }
10048         else if (TREE_CODE (type) == REFERENCE_TYPE)
10049           /* In C++0x, during template argument substitution, when there is an
10050              attempt to create a reference to a reference type, reference
10051              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
10052
10053              "If a template-argument for a template-parameter T names a type
10054              that is a reference to a type A, an attempt to create the type
10055              'lvalue reference to cv T' creates the type 'lvalue reference to
10056              A,' while an attempt to create the type type rvalue reference to
10057              cv T' creates the type T"
10058           */
10059           r = cp_build_reference_type
10060               (TREE_TYPE (type),
10061                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
10062         else
10063           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
10064         r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
10065
10066         if (r != error_mark_node)
10067           /* Will this ever be needed for TYPE_..._TO values?  */
10068           layout_type (r);
10069
10070         return r;
10071       }
10072     case OFFSET_TYPE:
10073       {
10074         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
10075         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
10076           {
10077             /* [temp.deduct]
10078
10079                Type deduction may fail for any of the following
10080                reasons:
10081
10082                -- Attempting to create "pointer to member of T" when T
10083                   is not a class type.  */
10084             if (complain & tf_error)
10085               error ("creating pointer to member of non-class type %qT", r);
10086             return error_mark_node;
10087           }
10088         if (TREE_CODE (type) == REFERENCE_TYPE)
10089           {
10090             if (complain & tf_error)
10091               error ("creating pointer to member reference type %qT", type);
10092             return error_mark_node;
10093           }
10094         if (TREE_CODE (type) == VOID_TYPE)
10095           {
10096             if (complain & tf_error)
10097               error ("creating pointer to member of type void");
10098             return error_mark_node;
10099           }
10100         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
10101         if (TREE_CODE (type) == FUNCTION_TYPE)
10102           {
10103             /* The type of the implicit object parameter gets its
10104                cv-qualifiers from the FUNCTION_TYPE. */
10105             tree memptr;
10106             tree method_type = build_memfn_type (type, r, cp_type_quals (type));
10107             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
10108             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
10109                                                  complain);
10110           }
10111         else
10112           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
10113                                                TYPE_QUALS (t),
10114                                                complain);
10115       }
10116     case FUNCTION_TYPE:
10117     case METHOD_TYPE:
10118       {
10119         tree fntype;
10120         tree specs;
10121         fntype = tsubst_function_type (t, args, complain, in_decl);
10122         if (fntype == error_mark_node)
10123           return error_mark_node;
10124
10125         /* Substitute the exception specification.  */
10126         specs = tsubst_exception_specification (t, args, complain,
10127                                                 in_decl);
10128         if (specs == error_mark_node)
10129           return error_mark_node;
10130         if (specs)
10131           fntype = build_exception_variant (fntype, specs);
10132         return fntype;
10133       }
10134     case ARRAY_TYPE:
10135       {
10136         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
10137         if (domain == error_mark_node)
10138           return error_mark_node;
10139
10140         /* As an optimization, we avoid regenerating the array type if
10141            it will obviously be the same as T.  */
10142         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
10143           return t;
10144
10145         /* These checks should match the ones in grokdeclarator.
10146
10147            [temp.deduct]
10148
10149            The deduction may fail for any of the following reasons:
10150
10151            -- Attempting to create an array with an element type that
10152               is void, a function type, or a reference type, or [DR337]
10153               an abstract class type.  */
10154         if (TREE_CODE (type) == VOID_TYPE
10155             || TREE_CODE (type) == FUNCTION_TYPE
10156             || TREE_CODE (type) == REFERENCE_TYPE)
10157           {
10158             if (complain & tf_error)
10159               error ("creating array of %qT", type);
10160             return error_mark_node;
10161           }
10162         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
10163           {
10164             if (complain & tf_error)
10165               error ("creating array of %qT, which is an abstract class type",
10166                      type);
10167             return error_mark_node;
10168           }
10169
10170         r = build_cplus_array_type (type, domain);
10171
10172         if (TYPE_USER_ALIGN (t))
10173           {
10174             TYPE_ALIGN (r) = TYPE_ALIGN (t);
10175             TYPE_USER_ALIGN (r) = 1;
10176           }
10177
10178         return r;
10179       }
10180
10181     case PLUS_EXPR:
10182     case MINUS_EXPR:
10183       {
10184         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10185         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
10186
10187         if (e1 == error_mark_node || e2 == error_mark_node)
10188           return error_mark_node;
10189
10190         return fold_build2_loc (input_location,
10191                             TREE_CODE (t), TREE_TYPE (t), e1, e2);
10192       }
10193
10194     case NEGATE_EXPR:
10195     case NOP_EXPR:
10196       {
10197         tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10198         if (e == error_mark_node)
10199           return error_mark_node;
10200
10201         return fold_build1_loc (input_location, TREE_CODE (t), TREE_TYPE (t), e);
10202       }
10203
10204     case TYPENAME_TYPE:
10205       {
10206         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10207                                      in_decl, /*entering_scope=*/1);
10208         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
10209                               complain, in_decl);
10210
10211         if (ctx == error_mark_node || f == error_mark_node)
10212           return error_mark_node;
10213
10214         if (!MAYBE_CLASS_TYPE_P (ctx))
10215           {
10216             if (complain & tf_error)
10217               error ("%qT is not a class, struct, or union type", ctx);
10218             return error_mark_node;
10219           }
10220         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
10221           {
10222             /* Normally, make_typename_type does not require that the CTX
10223                have complete type in order to allow things like:
10224
10225                  template <class T> struct S { typename S<T>::X Y; };
10226
10227                But, such constructs have already been resolved by this
10228                point, so here CTX really should have complete type, unless
10229                it's a partial instantiation.  */
10230             if (!(complain & tf_no_class_instantiations))
10231               ctx = complete_type (ctx);
10232             if (!COMPLETE_TYPE_P (ctx))
10233               {
10234                 if (complain & tf_error)
10235                   cxx_incomplete_type_error (NULL_TREE, ctx);
10236                 return error_mark_node;
10237               }
10238           }
10239
10240         f = make_typename_type (ctx, f, typename_type,
10241                                 (complain & tf_error) | tf_keep_type_decl);
10242         if (f == error_mark_node)
10243           return f;
10244         if (TREE_CODE (f) == TYPE_DECL)
10245           {
10246             complain |= tf_ignore_bad_quals;
10247             f = TREE_TYPE (f);
10248           }
10249
10250         if (TREE_CODE (f) != TYPENAME_TYPE)
10251           {
10252             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
10253               error ("%qT resolves to %qT, which is not an enumeration type",
10254                      t, f);
10255             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
10256               error ("%qT resolves to %qT, which is is not a class type",
10257                      t, f);
10258           }
10259
10260         return cp_build_qualified_type_real
10261           (f, cp_type_quals (f) | cp_type_quals (t), complain);
10262       }
10263
10264     case UNBOUND_CLASS_TEMPLATE:
10265       {
10266         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10267                                      in_decl, /*entering_scope=*/1);
10268         tree name = TYPE_IDENTIFIER (t);
10269         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
10270
10271         if (ctx == error_mark_node || name == error_mark_node)
10272           return error_mark_node;
10273
10274         if (parm_list)
10275           parm_list = tsubst_template_parms (parm_list, args, complain);
10276         return make_unbound_class_template (ctx, name, parm_list, complain);
10277       }
10278
10279     case INDIRECT_REF:
10280     case ADDR_EXPR:
10281     case CALL_EXPR:
10282       gcc_unreachable ();
10283
10284     case ARRAY_REF:
10285       {
10286         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10287         tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl,
10288                                /*integral_constant_expression_p=*/false);
10289         if (e1 == error_mark_node || e2 == error_mark_node)
10290           return error_mark_node;
10291
10292         return build_nt (ARRAY_REF, e1, e2, NULL_TREE, NULL_TREE);
10293       }
10294
10295     case SCOPE_REF:
10296       {
10297         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10298         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
10299         if (e1 == error_mark_node || e2 == error_mark_node)
10300           return error_mark_node;
10301
10302         return build_qualified_name (/*type=*/NULL_TREE,
10303                                      e1, e2, QUALIFIED_NAME_IS_TEMPLATE (t));
10304       }
10305
10306     case TYPEOF_TYPE:
10307       {
10308         tree type;
10309
10310         ++cp_unevaluated_operand;
10311         ++c_inhibit_evaluation_warnings;
10312
10313         type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
10314                             complain, in_decl,
10315                             /*integral_constant_expression_p=*/false);
10316
10317         --cp_unevaluated_operand;
10318         --c_inhibit_evaluation_warnings;
10319
10320         type = finish_typeof (type);
10321         return cp_build_qualified_type_real (type,
10322                                              cp_type_quals (t)
10323                                              | cp_type_quals (type),
10324                                              complain);
10325       }
10326
10327     case DECLTYPE_TYPE:
10328       {
10329         tree type;
10330
10331         ++cp_unevaluated_operand;
10332         ++c_inhibit_evaluation_warnings;
10333
10334         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
10335                             complain, in_decl,
10336                             /*integral_constant_expression_p=*/false);
10337
10338         --cp_unevaluated_operand;
10339         --c_inhibit_evaluation_warnings;
10340
10341         if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
10342           type = lambda_capture_field_type (type);
10343         else if (DECLTYPE_FOR_LAMBDA_RETURN (t))
10344           type = lambda_return_type (type);
10345         else
10346           type = finish_decltype_type
10347             (type, DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
10348         return cp_build_qualified_type_real (type,
10349                                              cp_type_quals (t)
10350                                              | cp_type_quals (type),
10351                                              complain);
10352       }
10353
10354     case TYPE_ARGUMENT_PACK:
10355     case NONTYPE_ARGUMENT_PACK:
10356       {
10357         tree r = TYPE_P (t)
10358           ? cxx_make_type (TREE_CODE (t))
10359           : make_node (TREE_CODE (t));
10360         tree packed_out = 
10361           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
10362                                 args,
10363                                 complain,
10364                                 in_decl);
10365         SET_ARGUMENT_PACK_ARGS (r, packed_out);
10366
10367         /* For template nontype argument packs, also substitute into
10368            the type.  */
10369         if (TREE_CODE (t) == NONTYPE_ARGUMENT_PACK)
10370           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
10371
10372         return r;
10373       }
10374       break;
10375
10376     default:
10377       sorry ("use of %qs in template",
10378              tree_code_name [(int) TREE_CODE (t)]);
10379       return error_mark_node;
10380     }
10381 }
10382
10383 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
10384    type of the expression on the left-hand side of the "." or "->"
10385    operator.  */
10386
10387 static tree
10388 tsubst_baselink (tree baselink, tree object_type,
10389                  tree args, tsubst_flags_t complain, tree in_decl)
10390 {
10391     tree name;
10392     tree qualifying_scope;
10393     tree fns;
10394     tree optype;
10395     tree template_args = 0;
10396     bool template_id_p = false;
10397
10398     /* A baselink indicates a function from a base class.  Both the
10399        BASELINK_ACCESS_BINFO and the base class referenced may
10400        indicate bases of the template class, rather than the
10401        instantiated class.  In addition, lookups that were not
10402        ambiguous before may be ambiguous now.  Therefore, we perform
10403        the lookup again.  */
10404     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
10405     qualifying_scope = tsubst (qualifying_scope, args,
10406                                complain, in_decl);
10407     fns = BASELINK_FUNCTIONS (baselink);
10408     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
10409     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
10410       {
10411         template_id_p = true;
10412         template_args = TREE_OPERAND (fns, 1);
10413         fns = TREE_OPERAND (fns, 0);
10414         if (template_args)
10415           template_args = tsubst_template_args (template_args, args,
10416                                                 complain, in_decl);
10417       }
10418     name = DECL_NAME (get_first_fn (fns));
10419     if (IDENTIFIER_TYPENAME_P (name))
10420       name = mangle_conv_op_name_for_type (optype);
10421     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
10422
10423     /* If lookup found a single function, mark it as used at this
10424        point.  (If it lookup found multiple functions the one selected
10425        later by overload resolution will be marked as used at that
10426        point.)  */
10427     if (BASELINK_P (baselink))
10428       fns = BASELINK_FUNCTIONS (baselink);
10429     if (!template_id_p && !really_overloaded_fn (fns))
10430       mark_used (OVL_CURRENT (fns));
10431
10432     /* Add back the template arguments, if present.  */
10433     if (BASELINK_P (baselink) && template_id_p)
10434       BASELINK_FUNCTIONS (baselink)
10435         = build_nt (TEMPLATE_ID_EXPR,
10436                     BASELINK_FUNCTIONS (baselink),
10437                     template_args);
10438     /* Update the conversion operator type.  */
10439     BASELINK_OPTYPE (baselink) = optype;
10440
10441     if (!object_type)
10442       object_type = current_class_type;
10443     return adjust_result_of_qualified_name_lookup (baselink,
10444                                                    qualifying_scope,
10445                                                    object_type);
10446 }
10447
10448 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
10449    true if the qualified-id will be a postfix-expression in-and-of
10450    itself; false if more of the postfix-expression follows the
10451    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
10452    of "&".  */
10453
10454 static tree
10455 tsubst_qualified_id (tree qualified_id, tree args,
10456                      tsubst_flags_t complain, tree in_decl,
10457                      bool done, bool address_p)
10458 {
10459   tree expr;
10460   tree scope;
10461   tree name;
10462   bool is_template;
10463   tree template_args;
10464
10465   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
10466
10467   /* Figure out what name to look up.  */
10468   name = TREE_OPERAND (qualified_id, 1);
10469   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
10470     {
10471       is_template = true;
10472       template_args = TREE_OPERAND (name, 1);
10473       if (template_args)
10474         template_args = tsubst_template_args (template_args, args,
10475                                               complain, in_decl);
10476       name = TREE_OPERAND (name, 0);
10477     }
10478   else
10479     {
10480       is_template = false;
10481       template_args = NULL_TREE;
10482     }
10483
10484   /* Substitute into the qualifying scope.  When there are no ARGS, we
10485      are just trying to simplify a non-dependent expression.  In that
10486      case the qualifying scope may be dependent, and, in any case,
10487      substituting will not help.  */
10488   scope = TREE_OPERAND (qualified_id, 0);
10489   if (args)
10490     {
10491       scope = tsubst (scope, args, complain, in_decl);
10492       expr = tsubst_copy (name, args, complain, in_decl);
10493     }
10494   else
10495     expr = name;
10496
10497   if (dependent_type_p (scope))
10498     {
10499       tree type = NULL_TREE;
10500       if (DECL_P (expr) && !dependent_scope_p (scope))
10501         type = TREE_TYPE (expr);
10502       return build_qualified_name (type, scope, expr,
10503                                    QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
10504     }
10505
10506   if (!BASELINK_P (name) && !DECL_P (expr))
10507     {
10508       if (TREE_CODE (expr) == BIT_NOT_EXPR)
10509         {
10510           /* A BIT_NOT_EXPR is used to represent a destructor.  */
10511           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
10512             {
10513               error ("qualifying type %qT does not match destructor name ~%qT",
10514                      scope, TREE_OPERAND (expr, 0));
10515               expr = error_mark_node;
10516             }
10517           else
10518             expr = lookup_qualified_name (scope, complete_dtor_identifier,
10519                                           /*is_type_p=*/0, false);
10520         }
10521       else
10522         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
10523       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
10524                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
10525         {
10526           if (complain & tf_error)
10527             {
10528               error ("dependent-name %qE is parsed as a non-type, but "
10529                      "instantiation yields a type", qualified_id);
10530               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
10531             }
10532           return error_mark_node;
10533         }
10534     }
10535
10536   if (DECL_P (expr))
10537     {
10538       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
10539                                            scope);
10540       /* Remember that there was a reference to this entity.  */
10541       mark_used (expr);
10542     }
10543
10544   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
10545     {
10546       if (complain & tf_error)
10547         qualified_name_lookup_error (scope,
10548                                      TREE_OPERAND (qualified_id, 1),
10549                                      expr, input_location);
10550       return error_mark_node;
10551     }
10552
10553   if (is_template)
10554     expr = lookup_template_function (expr, template_args);
10555
10556   if (expr == error_mark_node && complain & tf_error)
10557     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
10558                                  expr, input_location);
10559   else if (TYPE_P (scope))
10560     {
10561       expr = (adjust_result_of_qualified_name_lookup
10562               (expr, scope, current_class_type));
10563       expr = (finish_qualified_id_expr
10564               (scope, expr, done, address_p,
10565                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
10566                /*template_arg_p=*/false));
10567     }
10568
10569   /* Expressions do not generally have reference type.  */
10570   if (TREE_CODE (expr) != SCOPE_REF
10571       /* However, if we're about to form a pointer-to-member, we just
10572          want the referenced member referenced.  */
10573       && TREE_CODE (expr) != OFFSET_REF)
10574     expr = convert_from_reference (expr);
10575
10576   return expr;
10577 }
10578
10579 /* Like tsubst, but deals with expressions.  This function just replaces
10580    template parms; to finish processing the resultant expression, use
10581    tsubst_expr.  */
10582
10583 static tree
10584 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10585 {
10586   enum tree_code code;
10587   tree r;
10588
10589   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
10590     return t;
10591
10592   code = TREE_CODE (t);
10593
10594   switch (code)
10595     {
10596     case PARM_DECL:
10597       r = retrieve_local_specialization (t);
10598
10599       if (r == NULL)
10600         {
10601           tree c;
10602           /* This can happen for a parameter name used later in a function
10603              declaration (such as in a late-specified return type).  Just
10604              make a dummy decl, since it's only used for its type.  */
10605           gcc_assert (cp_unevaluated_operand != 0);
10606           /* We copy T because want to tsubst the PARM_DECL only,
10607              not the following PARM_DECLs that are chained to T.  */
10608           c = copy_node (t);
10609           r = tsubst_decl (c, args, complain);
10610           /* Give it the template pattern as its context; its true context
10611              hasn't been instantiated yet and this is good enough for
10612              mangling.  */
10613           DECL_CONTEXT (r) = DECL_CONTEXT (t);
10614         }
10615       
10616       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
10617         r = ARGUMENT_PACK_SELECT_ARG (r);
10618       mark_used (r);
10619       return r;
10620
10621     case CONST_DECL:
10622       {
10623         tree enum_type;
10624         tree v;
10625
10626         if (DECL_TEMPLATE_PARM_P (t))
10627           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
10628         /* There is no need to substitute into namespace-scope
10629            enumerators.  */
10630         if (DECL_NAMESPACE_SCOPE_P (t))
10631           return t;
10632         /* If ARGS is NULL, then T is known to be non-dependent.  */
10633         if (args == NULL_TREE)
10634           return integral_constant_value (t);
10635
10636         /* Unfortunately, we cannot just call lookup_name here.
10637            Consider:
10638
10639              template <int I> int f() {
10640              enum E { a = I };
10641              struct S { void g() { E e = a; } };
10642              };
10643
10644            When we instantiate f<7>::S::g(), say, lookup_name is not
10645            clever enough to find f<7>::a.  */
10646         enum_type
10647           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
10648                               /*entering_scope=*/0);
10649
10650         for (v = TYPE_VALUES (enum_type);
10651              v != NULL_TREE;
10652              v = TREE_CHAIN (v))
10653           if (TREE_PURPOSE (v) == DECL_NAME (t))
10654             return TREE_VALUE (v);
10655
10656           /* We didn't find the name.  That should never happen; if
10657              name-lookup found it during preliminary parsing, we
10658              should find it again here during instantiation.  */
10659         gcc_unreachable ();
10660       }
10661       return t;
10662
10663     case FIELD_DECL:
10664       if (DECL_CONTEXT (t))
10665         {
10666           tree ctx;
10667
10668           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
10669                                   /*entering_scope=*/1);
10670           if (ctx != DECL_CONTEXT (t))
10671             {
10672               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
10673               if (!r)
10674                 {
10675                   if (complain & tf_error)
10676                     error ("using invalid field %qD", t);
10677                   return error_mark_node;
10678                 }
10679               return r;
10680             }
10681         }
10682
10683       return t;
10684
10685     case VAR_DECL:
10686     case FUNCTION_DECL:
10687       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10688           || local_variable_p (t))
10689         t = tsubst (t, args, complain, in_decl);
10690       mark_used (t);
10691       return t;
10692
10693     case BASELINK:
10694       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
10695
10696     case TEMPLATE_DECL:
10697       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10698         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
10699                        args, complain, in_decl);
10700       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
10701         return tsubst (t, args, complain, in_decl);
10702       else if (DECL_CLASS_SCOPE_P (t)
10703                && uses_template_parms (DECL_CONTEXT (t)))
10704         {
10705           /* Template template argument like the following example need
10706              special treatment:
10707
10708                template <template <class> class TT> struct C {};
10709                template <class T> struct D {
10710                  template <class U> struct E {};
10711                  C<E> c;                                // #1
10712                };
10713                D<int> d;                                // #2
10714
10715              We are processing the template argument `E' in #1 for
10716              the template instantiation #2.  Originally, `E' is a
10717              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
10718              have to substitute this with one having context `D<int>'.  */
10719
10720           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
10721           return lookup_field (context, DECL_NAME(t), 0, false);
10722         }
10723       else
10724         /* Ordinary template template argument.  */
10725         return t;
10726
10727     case CAST_EXPR:
10728     case REINTERPRET_CAST_EXPR:
10729     case CONST_CAST_EXPR:
10730     case STATIC_CAST_EXPR:
10731     case DYNAMIC_CAST_EXPR:
10732     case NOP_EXPR:
10733       return build1
10734         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10735          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10736
10737     case SIZEOF_EXPR:
10738       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
10739         {
10740           /* We only want to compute the number of arguments.  */
10741           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
10742                                                 complain, in_decl);
10743           int len = 0;
10744
10745           if (TREE_CODE (expanded) == TREE_VEC)
10746             len = TREE_VEC_LENGTH (expanded);
10747
10748           if (expanded == error_mark_node)
10749             return error_mark_node;
10750           else if (PACK_EXPANSION_P (expanded)
10751                    || (TREE_CODE (expanded) == TREE_VEC
10752                        && len > 0
10753                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
10754             {
10755               if (TREE_CODE (expanded) == TREE_VEC)
10756                 expanded = TREE_VEC_ELT (expanded, len - 1);
10757
10758               if (TYPE_P (expanded))
10759                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
10760                                                    complain & tf_error);
10761               else
10762                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
10763                                                    complain & tf_error);
10764             }
10765           else
10766             return build_int_cst (size_type_node, len);
10767         }
10768       /* Fall through */
10769
10770     case INDIRECT_REF:
10771     case NEGATE_EXPR:
10772     case TRUTH_NOT_EXPR:
10773     case BIT_NOT_EXPR:
10774     case ADDR_EXPR:
10775     case UNARY_PLUS_EXPR:      /* Unary + */
10776     case ALIGNOF_EXPR:
10777     case ARROW_EXPR:
10778     case THROW_EXPR:
10779     case TYPEID_EXPR:
10780     case REALPART_EXPR:
10781     case IMAGPART_EXPR:
10782       return build1
10783         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10784          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10785
10786     case COMPONENT_REF:
10787       {
10788         tree object;
10789         tree name;
10790
10791         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
10792         name = TREE_OPERAND (t, 1);
10793         if (TREE_CODE (name) == BIT_NOT_EXPR)
10794           {
10795             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10796                                 complain, in_decl);
10797             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10798           }
10799         else if (TREE_CODE (name) == SCOPE_REF
10800                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
10801           {
10802             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
10803                                      complain, in_decl);
10804             name = TREE_OPERAND (name, 1);
10805             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10806                                 complain, in_decl);
10807             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10808             name = build_qualified_name (/*type=*/NULL_TREE,
10809                                          base, name,
10810                                          /*template_p=*/false);
10811           }
10812         else if (TREE_CODE (name) == BASELINK)
10813           name = tsubst_baselink (name,
10814                                   non_reference (TREE_TYPE (object)),
10815                                   args, complain,
10816                                   in_decl);
10817         else
10818           name = tsubst_copy (name, args, complain, in_decl);
10819         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
10820       }
10821
10822     case PLUS_EXPR:
10823     case MINUS_EXPR:
10824     case MULT_EXPR:
10825     case TRUNC_DIV_EXPR:
10826     case CEIL_DIV_EXPR:
10827     case FLOOR_DIV_EXPR:
10828     case ROUND_DIV_EXPR:
10829     case EXACT_DIV_EXPR:
10830     case BIT_AND_EXPR:
10831     case BIT_IOR_EXPR:
10832     case BIT_XOR_EXPR:
10833     case TRUNC_MOD_EXPR:
10834     case FLOOR_MOD_EXPR:
10835     case TRUTH_ANDIF_EXPR:
10836     case TRUTH_ORIF_EXPR:
10837     case TRUTH_AND_EXPR:
10838     case TRUTH_OR_EXPR:
10839     case RSHIFT_EXPR:
10840     case LSHIFT_EXPR:
10841     case RROTATE_EXPR:
10842     case LROTATE_EXPR:
10843     case EQ_EXPR:
10844     case NE_EXPR:
10845     case MAX_EXPR:
10846     case MIN_EXPR:
10847     case LE_EXPR:
10848     case GE_EXPR:
10849     case LT_EXPR:
10850     case GT_EXPR:
10851     case COMPOUND_EXPR:
10852     case DOTSTAR_EXPR:
10853     case MEMBER_REF:
10854     case PREDECREMENT_EXPR:
10855     case PREINCREMENT_EXPR:
10856     case POSTDECREMENT_EXPR:
10857     case POSTINCREMENT_EXPR:
10858       return build_nt
10859         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10860          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10861
10862     case SCOPE_REF:
10863       return build_qualified_name (/*type=*/NULL_TREE,
10864                                    tsubst_copy (TREE_OPERAND (t, 0),
10865                                                 args, complain, in_decl),
10866                                    tsubst_copy (TREE_OPERAND (t, 1),
10867                                                 args, complain, in_decl),
10868                                    QUALIFIED_NAME_IS_TEMPLATE (t));
10869
10870     case ARRAY_REF:
10871       return build_nt
10872         (ARRAY_REF,
10873          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10874          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10875          NULL_TREE, NULL_TREE);
10876
10877     case CALL_EXPR:
10878       {
10879         int n = VL_EXP_OPERAND_LENGTH (t);
10880         tree result = build_vl_exp (CALL_EXPR, n);
10881         int i;
10882         for (i = 0; i < n; i++)
10883           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
10884                                              complain, in_decl);
10885         return result;
10886       }
10887
10888     case COND_EXPR:
10889     case MODOP_EXPR:
10890     case PSEUDO_DTOR_EXPR:
10891       {
10892         r = build_nt
10893           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10894            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10895            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10896         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
10897         return r;
10898       }
10899
10900     case NEW_EXPR:
10901       {
10902         r = build_nt
10903         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10904          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
10905          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
10906         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
10907         return r;
10908       }
10909
10910     case DELETE_EXPR:
10911       {
10912         r = build_nt
10913         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
10914          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
10915         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
10916         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
10917         return r;
10918       }
10919
10920     case TEMPLATE_ID_EXPR:
10921       {
10922         /* Substituted template arguments */
10923         tree fn = TREE_OPERAND (t, 0);
10924         tree targs = TREE_OPERAND (t, 1);
10925
10926         fn = tsubst_copy (fn, args, complain, in_decl);
10927         if (targs)
10928           targs = tsubst_template_args (targs, args, complain, in_decl);
10929
10930         return lookup_template_function (fn, targs);
10931       }
10932
10933     case TREE_LIST:
10934       {
10935         tree purpose, value, chain;
10936
10937         if (t == void_list_node)
10938           return t;
10939
10940         purpose = TREE_PURPOSE (t);
10941         if (purpose)
10942           purpose = tsubst_copy (purpose, args, complain, in_decl);
10943         value = TREE_VALUE (t);
10944         if (value)
10945           value = tsubst_copy (value, args, complain, in_decl);
10946         chain = TREE_CHAIN (t);
10947         if (chain && chain != void_type_node)
10948           chain = tsubst_copy (chain, args, complain, in_decl);
10949         if (purpose == TREE_PURPOSE (t)
10950             && value == TREE_VALUE (t)
10951             && chain == TREE_CHAIN (t))
10952           return t;
10953         return tree_cons (purpose, value, chain);
10954       }
10955
10956     case RECORD_TYPE:
10957     case UNION_TYPE:
10958     case ENUMERAL_TYPE:
10959     case INTEGER_TYPE:
10960     case TEMPLATE_TYPE_PARM:
10961     case TEMPLATE_TEMPLATE_PARM:
10962     case BOUND_TEMPLATE_TEMPLATE_PARM:
10963     case TEMPLATE_PARM_INDEX:
10964     case POINTER_TYPE:
10965     case REFERENCE_TYPE:
10966     case OFFSET_TYPE:
10967     case FUNCTION_TYPE:
10968     case METHOD_TYPE:
10969     case ARRAY_TYPE:
10970     case TYPENAME_TYPE:
10971     case UNBOUND_CLASS_TEMPLATE:
10972     case TYPEOF_TYPE:
10973     case DECLTYPE_TYPE:
10974     case TYPE_DECL:
10975       return tsubst (t, args, complain, in_decl);
10976
10977     case IDENTIFIER_NODE:
10978       if (IDENTIFIER_TYPENAME_P (t))
10979         {
10980           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10981           return mangle_conv_op_name_for_type (new_type);
10982         }
10983       else
10984         return t;
10985
10986     case CONSTRUCTOR:
10987       /* This is handled by tsubst_copy_and_build.  */
10988       gcc_unreachable ();
10989
10990     case VA_ARG_EXPR:
10991       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
10992                                           in_decl),
10993                              tsubst (TREE_TYPE (t), args, complain, in_decl));
10994
10995     case CLEANUP_POINT_EXPR:
10996       /* We shouldn't have built any of these during initial template
10997          generation.  Instead, they should be built during instantiation
10998          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
10999       gcc_unreachable ();
11000
11001     case OFFSET_REF:
11002       mark_used (TREE_OPERAND (t, 1));
11003       return t;
11004
11005     case EXPR_PACK_EXPANSION:
11006       error ("invalid use of pack expansion expression");
11007       return error_mark_node;
11008
11009     case NONTYPE_ARGUMENT_PACK:
11010       error ("use %<...%> to expand argument pack");
11011       return error_mark_node;
11012
11013     default:
11014       return t;
11015     }
11016 }
11017
11018 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
11019
11020 static tree
11021 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
11022                     tree in_decl)
11023 {
11024   tree new_clauses = NULL, nc, oc;
11025
11026   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
11027     {
11028       nc = copy_node (oc);
11029       OMP_CLAUSE_CHAIN (nc) = new_clauses;
11030       new_clauses = nc;
11031
11032       switch (OMP_CLAUSE_CODE (nc))
11033         {
11034         case OMP_CLAUSE_LASTPRIVATE:
11035           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
11036             {
11037               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
11038               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
11039                            in_decl, /*integral_constant_expression_p=*/false);
11040               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
11041                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
11042             }
11043           /* FALLTHRU */
11044         case OMP_CLAUSE_PRIVATE:
11045         case OMP_CLAUSE_SHARED:
11046         case OMP_CLAUSE_FIRSTPRIVATE:
11047         case OMP_CLAUSE_REDUCTION:
11048         case OMP_CLAUSE_COPYIN:
11049         case OMP_CLAUSE_COPYPRIVATE:
11050         case OMP_CLAUSE_IF:
11051         case OMP_CLAUSE_NUM_THREADS:
11052         case OMP_CLAUSE_SCHEDULE:
11053         case OMP_CLAUSE_COLLAPSE:
11054           OMP_CLAUSE_OPERAND (nc, 0)
11055             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
11056                            in_decl, /*integral_constant_expression_p=*/false);
11057           break;
11058         case OMP_CLAUSE_NOWAIT:
11059         case OMP_CLAUSE_ORDERED:
11060         case OMP_CLAUSE_DEFAULT:
11061         case OMP_CLAUSE_UNTIED:
11062           break;
11063         default:
11064           gcc_unreachable ();
11065         }
11066     }
11067
11068   return finish_omp_clauses (nreverse (new_clauses));
11069 }
11070
11071 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
11072
11073 static tree
11074 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
11075                           tree in_decl)
11076 {
11077 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
11078
11079   tree purpose, value, chain;
11080
11081   if (t == NULL)
11082     return t;
11083
11084   if (TREE_CODE (t) != TREE_LIST)
11085     return tsubst_copy_and_build (t, args, complain, in_decl,
11086                                   /*function_p=*/false,
11087                                   /*integral_constant_expression_p=*/false);
11088
11089   if (t == void_list_node)
11090     return t;
11091
11092   purpose = TREE_PURPOSE (t);
11093   if (purpose)
11094     purpose = RECUR (purpose);
11095   value = TREE_VALUE (t);
11096   if (value && TREE_CODE (value) != LABEL_DECL)
11097     value = RECUR (value);
11098   chain = TREE_CHAIN (t);
11099   if (chain && chain != void_type_node)
11100     chain = RECUR (chain);
11101   return tree_cons (purpose, value, chain);
11102 #undef RECUR
11103 }
11104
11105 /* Substitute one OMP_FOR iterator.  */
11106
11107 static void
11108 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
11109                          tree condv, tree incrv, tree *clauses,
11110                          tree args, tsubst_flags_t complain, tree in_decl,
11111                          bool integral_constant_expression_p)
11112 {
11113 #define RECUR(NODE)                             \
11114   tsubst_expr ((NODE), args, complain, in_decl, \
11115                integral_constant_expression_p)
11116   tree decl, init, cond, incr, auto_node;
11117
11118   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
11119   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
11120   decl = RECUR (TREE_OPERAND (init, 0));
11121   init = TREE_OPERAND (init, 1);
11122   auto_node = type_uses_auto (TREE_TYPE (decl));
11123   if (auto_node && init)
11124     {
11125       tree init_expr = init;
11126       if (TREE_CODE (init_expr) == DECL_EXPR)
11127         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
11128       init_expr = RECUR (init_expr);
11129       TREE_TYPE (decl)
11130         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
11131     }
11132   gcc_assert (!type_dependent_expression_p (decl));
11133
11134   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
11135     {
11136       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
11137       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11138       if (TREE_CODE (incr) == MODIFY_EXPR)
11139         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
11140                                     RECUR (TREE_OPERAND (incr, 1)),
11141                                     complain);
11142       else
11143         incr = RECUR (incr);
11144       TREE_VEC_ELT (declv, i) = decl;
11145       TREE_VEC_ELT (initv, i) = init;
11146       TREE_VEC_ELT (condv, i) = cond;
11147       TREE_VEC_ELT (incrv, i) = incr;
11148       return;
11149     }
11150
11151   if (init && TREE_CODE (init) != DECL_EXPR)
11152     {
11153       tree c;
11154       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
11155         {
11156           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
11157                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
11158               && OMP_CLAUSE_DECL (c) == decl)
11159             break;
11160           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
11161                    && OMP_CLAUSE_DECL (c) == decl)
11162             error ("iteration variable %qD should not be firstprivate", decl);
11163           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
11164                    && OMP_CLAUSE_DECL (c) == decl)
11165             error ("iteration variable %qD should not be reduction", decl);
11166         }
11167       if (c == NULL)
11168         {
11169           c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
11170           OMP_CLAUSE_DECL (c) = decl;
11171           c = finish_omp_clauses (c);
11172           if (c)
11173             {
11174               OMP_CLAUSE_CHAIN (c) = *clauses;
11175               *clauses = c;
11176             }
11177         }
11178     }
11179   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
11180   if (COMPARISON_CLASS_P (cond))
11181     cond = build2 (TREE_CODE (cond), boolean_type_node,
11182                    RECUR (TREE_OPERAND (cond, 0)),
11183                    RECUR (TREE_OPERAND (cond, 1)));
11184   else
11185     cond = RECUR (cond);
11186   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11187   switch (TREE_CODE (incr))
11188     {
11189     case PREINCREMENT_EXPR:
11190     case PREDECREMENT_EXPR:
11191     case POSTINCREMENT_EXPR:
11192     case POSTDECREMENT_EXPR:
11193       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
11194                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
11195       break;
11196     case MODIFY_EXPR:
11197       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11198           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11199         {
11200           tree rhs = TREE_OPERAND (incr, 1);
11201           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11202                          RECUR (TREE_OPERAND (incr, 0)),
11203                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11204                                  RECUR (TREE_OPERAND (rhs, 0)),
11205                                  RECUR (TREE_OPERAND (rhs, 1))));
11206         }
11207       else
11208         incr = RECUR (incr);
11209       break;
11210     case MODOP_EXPR:
11211       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11212           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11213         {
11214           tree lhs = RECUR (TREE_OPERAND (incr, 0));
11215           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
11216                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
11217                                  TREE_TYPE (decl), lhs,
11218                                  RECUR (TREE_OPERAND (incr, 2))));
11219         }
11220       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
11221                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
11222                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
11223         {
11224           tree rhs = TREE_OPERAND (incr, 2);
11225           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11226                          RECUR (TREE_OPERAND (incr, 0)),
11227                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11228                                  RECUR (TREE_OPERAND (rhs, 0)),
11229                                  RECUR (TREE_OPERAND (rhs, 1))));
11230         }
11231       else
11232         incr = RECUR (incr);
11233       break;
11234     default:
11235       incr = RECUR (incr);
11236       break;
11237     }
11238
11239   TREE_VEC_ELT (declv, i) = decl;
11240   TREE_VEC_ELT (initv, i) = init;
11241   TREE_VEC_ELT (condv, i) = cond;
11242   TREE_VEC_ELT (incrv, i) = incr;
11243 #undef RECUR
11244 }
11245
11246 /* Like tsubst_copy for expressions, etc. but also does semantic
11247    processing.  */
11248
11249 static tree
11250 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
11251              bool integral_constant_expression_p)
11252 {
11253 #define RECUR(NODE)                             \
11254   tsubst_expr ((NODE), args, complain, in_decl, \
11255                integral_constant_expression_p)
11256
11257   tree stmt, tmp;
11258
11259   if (t == NULL_TREE || t == error_mark_node)
11260     return t;
11261
11262   if (EXPR_HAS_LOCATION (t))
11263     input_location = EXPR_LOCATION (t);
11264   if (STATEMENT_CODE_P (TREE_CODE (t)))
11265     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
11266
11267   switch (TREE_CODE (t))
11268     {
11269     case STATEMENT_LIST:
11270       {
11271         tree_stmt_iterator i;
11272         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
11273           RECUR (tsi_stmt (i));
11274         break;
11275       }
11276
11277     case CTOR_INITIALIZER:
11278       finish_mem_initializers (tsubst_initializer_list
11279                                (TREE_OPERAND (t, 0), args));
11280       break;
11281
11282     case RETURN_EXPR:
11283       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
11284       break;
11285
11286     case EXPR_STMT:
11287       tmp = RECUR (EXPR_STMT_EXPR (t));
11288       if (EXPR_STMT_STMT_EXPR_RESULT (t))
11289         finish_stmt_expr_expr (tmp, cur_stmt_expr);
11290       else
11291         finish_expr_stmt (tmp);
11292       break;
11293
11294     case USING_STMT:
11295       do_using_directive (RECUR (USING_STMT_NAMESPACE (t)));
11296       break;
11297
11298     case DECL_EXPR:
11299       {
11300         tree decl;
11301         tree init;
11302
11303         decl = DECL_EXPR_DECL (t);
11304         if (TREE_CODE (decl) == LABEL_DECL)
11305           finish_label_decl (DECL_NAME (decl));
11306         else if (TREE_CODE (decl) == USING_DECL)
11307           {
11308             tree scope = USING_DECL_SCOPE (decl);
11309             tree name = DECL_NAME (decl);
11310             tree decl;
11311
11312             scope = RECUR (scope);
11313             decl = lookup_qualified_name (scope, name,
11314                                           /*is_type_p=*/false,
11315                                           /*complain=*/false);
11316             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
11317               qualified_name_lookup_error (scope, name, decl, input_location);
11318             else
11319               do_local_using_decl (decl, scope, name);
11320           }
11321         else
11322           {
11323             init = DECL_INITIAL (decl);
11324             decl = tsubst (decl, args, complain, in_decl);
11325             if (decl != error_mark_node)
11326               {
11327                 /* By marking the declaration as instantiated, we avoid
11328                    trying to instantiate it.  Since instantiate_decl can't
11329                    handle local variables, and since we've already done
11330                    all that needs to be done, that's the right thing to
11331                    do.  */
11332                 if (TREE_CODE (decl) == VAR_DECL)
11333                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11334                 if (TREE_CODE (decl) == VAR_DECL
11335                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
11336                   /* Anonymous aggregates are a special case.  */
11337                   finish_anon_union (decl);
11338                 else
11339                   {
11340                     maybe_push_decl (decl);
11341                     if (TREE_CODE (decl) == VAR_DECL
11342                         && DECL_PRETTY_FUNCTION_P (decl))
11343                       {
11344                         /* For __PRETTY_FUNCTION__ we have to adjust the
11345                            initializer.  */
11346                         const char *const name
11347                           = cxx_printable_name (current_function_decl, 2);
11348                         init = cp_fname_init (name, &TREE_TYPE (decl));
11349                       }
11350                     else
11351                       {
11352                         tree t = RECUR (init);
11353
11354                         if (init && !t)
11355                           /* If we had an initializer but it
11356                              instantiated to nothing,
11357                              value-initialize the object.  This will
11358                              only occur when the initializer was a
11359                              pack expansion where the parameter packs
11360                              used in that expansion were of length
11361                              zero.  */
11362                           init = build_value_init (TREE_TYPE (decl));
11363                         else
11364                           init = t;
11365                       }
11366
11367                     cp_finish_decl (decl, init, false, NULL_TREE, 0);
11368                   }
11369               }
11370           }
11371
11372         /* A DECL_EXPR can also be used as an expression, in the condition
11373            clause of an if/for/while construct.  */
11374         return decl;
11375       }
11376
11377     case FOR_STMT:
11378       stmt = begin_for_stmt ();
11379                           RECUR (FOR_INIT_STMT (t));
11380       finish_for_init_stmt (stmt);
11381       tmp = RECUR (FOR_COND (t));
11382       finish_for_cond (tmp, stmt);
11383       tmp = RECUR (FOR_EXPR (t));
11384       finish_for_expr (tmp, stmt);
11385       RECUR (FOR_BODY (t));
11386       finish_for_stmt (stmt);
11387       break;
11388
11389     case WHILE_STMT:
11390       stmt = begin_while_stmt ();
11391       tmp = RECUR (WHILE_COND (t));
11392       finish_while_stmt_cond (tmp, stmt);
11393       RECUR (WHILE_BODY (t));
11394       finish_while_stmt (stmt);
11395       break;
11396
11397     case DO_STMT:
11398       stmt = begin_do_stmt ();
11399       RECUR (DO_BODY (t));
11400       finish_do_body (stmt);
11401       tmp = RECUR (DO_COND (t));
11402       finish_do_stmt (tmp, stmt);
11403       break;
11404
11405     case IF_STMT:
11406       stmt = begin_if_stmt ();
11407       tmp = RECUR (IF_COND (t));
11408       finish_if_stmt_cond (tmp, stmt);
11409       RECUR (THEN_CLAUSE (t));
11410       finish_then_clause (stmt);
11411
11412       if (ELSE_CLAUSE (t))
11413         {
11414           begin_else_clause (stmt);
11415           RECUR (ELSE_CLAUSE (t));
11416           finish_else_clause (stmt);
11417         }
11418
11419       finish_if_stmt (stmt);
11420       break;
11421
11422     case BIND_EXPR:
11423       if (BIND_EXPR_BODY_BLOCK (t))
11424         stmt = begin_function_body ();
11425       else
11426         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
11427                                     ? BCS_TRY_BLOCK : 0);
11428
11429       RECUR (BIND_EXPR_BODY (t));
11430
11431       if (BIND_EXPR_BODY_BLOCK (t))
11432         finish_function_body (stmt);
11433       else
11434         finish_compound_stmt (stmt);
11435       break;
11436
11437     case BREAK_STMT:
11438       finish_break_stmt ();
11439       break;
11440
11441     case CONTINUE_STMT:
11442       finish_continue_stmt ();
11443       break;
11444
11445     case SWITCH_STMT:
11446       stmt = begin_switch_stmt ();
11447       tmp = RECUR (SWITCH_STMT_COND (t));
11448       finish_switch_cond (tmp, stmt);
11449       RECUR (SWITCH_STMT_BODY (t));
11450       finish_switch_stmt (stmt);
11451       break;
11452
11453     case CASE_LABEL_EXPR:
11454       finish_case_label (EXPR_LOCATION (t),
11455                          RECUR (CASE_LOW (t)),
11456                          RECUR (CASE_HIGH (t)));
11457       break;
11458
11459     case LABEL_EXPR:
11460       {
11461         tree decl = LABEL_EXPR_LABEL (t);
11462         tree label;
11463
11464         label = finish_label_stmt (DECL_NAME (decl));
11465         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
11466           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
11467       }
11468       break;
11469
11470     case GOTO_EXPR:
11471       tmp = GOTO_DESTINATION (t);
11472       if (TREE_CODE (tmp) != LABEL_DECL)
11473         /* Computed goto's must be tsubst'd into.  On the other hand,
11474            non-computed gotos must not be; the identifier in question
11475            will have no binding.  */
11476         tmp = RECUR (tmp);
11477       else
11478         tmp = DECL_NAME (tmp);
11479       finish_goto_stmt (tmp);
11480       break;
11481
11482     case ASM_EXPR:
11483       tmp = finish_asm_stmt
11484         (ASM_VOLATILE_P (t),
11485          RECUR (ASM_STRING (t)),
11486          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
11487          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
11488          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl),
11489          tsubst_copy_asm_operands (ASM_LABELS (t), args, complain, in_decl));
11490       {
11491         tree asm_expr = tmp;
11492         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
11493           asm_expr = TREE_OPERAND (asm_expr, 0);
11494         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
11495       }
11496       break;
11497
11498     case TRY_BLOCK:
11499       if (CLEANUP_P (t))
11500         {
11501           stmt = begin_try_block ();
11502           RECUR (TRY_STMTS (t));
11503           finish_cleanup_try_block (stmt);
11504           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
11505         }
11506       else
11507         {
11508           tree compound_stmt = NULL_TREE;
11509
11510           if (FN_TRY_BLOCK_P (t))
11511             stmt = begin_function_try_block (&compound_stmt);
11512           else
11513             stmt = begin_try_block ();
11514
11515           RECUR (TRY_STMTS (t));
11516
11517           if (FN_TRY_BLOCK_P (t))
11518             finish_function_try_block (stmt);
11519           else
11520             finish_try_block (stmt);
11521
11522           RECUR (TRY_HANDLERS (t));
11523           if (FN_TRY_BLOCK_P (t))
11524             finish_function_handler_sequence (stmt, compound_stmt);
11525           else
11526             finish_handler_sequence (stmt);
11527         }
11528       break;
11529
11530     case HANDLER:
11531       {
11532         tree decl = HANDLER_PARMS (t);
11533
11534         if (decl)
11535           {
11536             decl = tsubst (decl, args, complain, in_decl);
11537             /* Prevent instantiate_decl from trying to instantiate
11538                this variable.  We've already done all that needs to be
11539                done.  */
11540             if (decl != error_mark_node)
11541               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11542           }
11543         stmt = begin_handler ();
11544         finish_handler_parms (decl, stmt);
11545         RECUR (HANDLER_BODY (t));
11546         finish_handler (stmt);
11547       }
11548       break;
11549
11550     case TAG_DEFN:
11551       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
11552       break;
11553
11554     case STATIC_ASSERT:
11555       {
11556         tree condition = 
11557           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
11558                        args,
11559                        complain, in_decl,
11560                        /*integral_constant_expression_p=*/true);
11561         finish_static_assert (condition,
11562                               STATIC_ASSERT_MESSAGE (t),
11563                               STATIC_ASSERT_SOURCE_LOCATION (t),
11564                               /*member_p=*/false);
11565       }
11566       break;
11567
11568     case OMP_PARALLEL:
11569       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
11570                                 args, complain, in_decl);
11571       stmt = begin_omp_parallel ();
11572       RECUR (OMP_PARALLEL_BODY (t));
11573       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
11574         = OMP_PARALLEL_COMBINED (t);
11575       break;
11576
11577     case OMP_TASK:
11578       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
11579                                 args, complain, in_decl);
11580       stmt = begin_omp_task ();
11581       RECUR (OMP_TASK_BODY (t));
11582       finish_omp_task (tmp, stmt);
11583       break;
11584
11585     case OMP_FOR:
11586       {
11587         tree clauses, body, pre_body;
11588         tree declv, initv, condv, incrv;
11589         int i;
11590
11591         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
11592                                       args, complain, in_decl);
11593         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11594         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11595         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11596         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11597
11598         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
11599           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
11600                                    &clauses, args, complain, in_decl,
11601                                    integral_constant_expression_p);
11602
11603         stmt = begin_omp_structured_block ();
11604
11605         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
11606           if (TREE_VEC_ELT (initv, i) == NULL
11607               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
11608             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
11609           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
11610             {
11611               tree init = RECUR (TREE_VEC_ELT (initv, i));
11612               gcc_assert (init == TREE_VEC_ELT (declv, i));
11613               TREE_VEC_ELT (initv, i) = NULL_TREE;
11614             }
11615           else
11616             {
11617               tree decl_expr = TREE_VEC_ELT (initv, i);
11618               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
11619               gcc_assert (init != NULL);
11620               TREE_VEC_ELT (initv, i) = RECUR (init);
11621               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
11622               RECUR (decl_expr);
11623               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
11624             }
11625
11626         pre_body = push_stmt_list ();
11627         RECUR (OMP_FOR_PRE_BODY (t));
11628         pre_body = pop_stmt_list (pre_body);
11629
11630         body = push_stmt_list ();
11631         RECUR (OMP_FOR_BODY (t));
11632         body = pop_stmt_list (body);
11633
11634         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
11635                             body, pre_body, clauses);
11636
11637         add_stmt (finish_omp_structured_block (stmt));
11638       }
11639       break;
11640
11641     case OMP_SECTIONS:
11642     case OMP_SINGLE:
11643       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
11644       stmt = push_stmt_list ();
11645       RECUR (OMP_BODY (t));
11646       stmt = pop_stmt_list (stmt);
11647
11648       t = copy_node (t);
11649       OMP_BODY (t) = stmt;
11650       OMP_CLAUSES (t) = tmp;
11651       add_stmt (t);
11652       break;
11653
11654     case OMP_SECTION:
11655     case OMP_CRITICAL:
11656     case OMP_MASTER:
11657     case OMP_ORDERED:
11658       stmt = push_stmt_list ();
11659       RECUR (OMP_BODY (t));
11660       stmt = pop_stmt_list (stmt);
11661
11662       t = copy_node (t);
11663       OMP_BODY (t) = stmt;
11664       add_stmt (t);
11665       break;
11666
11667     case OMP_ATOMIC:
11668       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
11669       {
11670         tree op1 = TREE_OPERAND (t, 1);
11671         tree lhs = RECUR (TREE_OPERAND (op1, 0));
11672         tree rhs = RECUR (TREE_OPERAND (op1, 1));
11673         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
11674       }
11675       break;
11676
11677     case EXPR_PACK_EXPANSION:
11678       error ("invalid use of pack expansion expression");
11679       return error_mark_node;
11680
11681     case NONTYPE_ARGUMENT_PACK:
11682       error ("use %<...%> to expand argument pack");
11683       return error_mark_node;
11684
11685     default:
11686       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
11687
11688       return tsubst_copy_and_build (t, args, complain, in_decl,
11689                                     /*function_p=*/false,
11690                                     integral_constant_expression_p);
11691     }
11692
11693   return NULL_TREE;
11694 #undef RECUR
11695 }
11696
11697 /* T is a postfix-expression that is not being used in a function
11698    call.  Return the substituted version of T.  */
11699
11700 static tree
11701 tsubst_non_call_postfix_expression (tree t, tree args,
11702                                     tsubst_flags_t complain,
11703                                     tree in_decl)
11704 {
11705   if (TREE_CODE (t) == SCOPE_REF)
11706     t = tsubst_qualified_id (t, args, complain, in_decl,
11707                              /*done=*/false, /*address_p=*/false);
11708   else
11709     t = tsubst_copy_and_build (t, args, complain, in_decl,
11710                                /*function_p=*/false,
11711                                /*integral_constant_expression_p=*/false);
11712
11713   return t;
11714 }
11715
11716 /* Like tsubst but deals with expressions and performs semantic
11717    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
11718
11719 tree
11720 tsubst_copy_and_build (tree t,
11721                        tree args,
11722                        tsubst_flags_t complain,
11723                        tree in_decl,
11724                        bool function_p,
11725                        bool integral_constant_expression_p)
11726 {
11727 #define RECUR(NODE)                                             \
11728   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
11729                          /*function_p=*/false,                  \
11730                          integral_constant_expression_p)
11731
11732   tree op1;
11733
11734   if (t == NULL_TREE || t == error_mark_node)
11735     return t;
11736
11737   switch (TREE_CODE (t))
11738     {
11739     case USING_DECL:
11740       t = DECL_NAME (t);
11741       /* Fall through.  */
11742     case IDENTIFIER_NODE:
11743       {
11744         tree decl;
11745         cp_id_kind idk;
11746         bool non_integral_constant_expression_p;
11747         const char *error_msg;
11748
11749         if (IDENTIFIER_TYPENAME_P (t))
11750           {
11751             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11752             t = mangle_conv_op_name_for_type (new_type);
11753           }
11754
11755         /* Look up the name.  */
11756         decl = lookup_name (t);
11757
11758         /* By convention, expressions use ERROR_MARK_NODE to indicate
11759            failure, not NULL_TREE.  */
11760         if (decl == NULL_TREE)
11761           decl = error_mark_node;
11762
11763         decl = finish_id_expression (t, decl, NULL_TREE,
11764                                      &idk,
11765                                      integral_constant_expression_p,
11766                                      /*allow_non_integral_constant_expression_p=*/false,
11767                                      &non_integral_constant_expression_p,
11768                                      /*template_p=*/false,
11769                                      /*done=*/true,
11770                                      /*address_p=*/false,
11771                                      /*template_arg_p=*/false,
11772                                      &error_msg,
11773                                      input_location);
11774         if (error_msg)
11775           error (error_msg);
11776         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
11777           decl = unqualified_name_lookup_error (decl);
11778         return decl;
11779       }
11780
11781     case TEMPLATE_ID_EXPR:
11782       {
11783         tree object;
11784         tree templ = RECUR (TREE_OPERAND (t, 0));
11785         tree targs = TREE_OPERAND (t, 1);
11786
11787         if (targs)
11788           targs = tsubst_template_args (targs, args, complain, in_decl);
11789
11790         if (TREE_CODE (templ) == COMPONENT_REF)
11791           {
11792             object = TREE_OPERAND (templ, 0);
11793             templ = TREE_OPERAND (templ, 1);
11794           }
11795         else
11796           object = NULL_TREE;
11797         templ = lookup_template_function (templ, targs);
11798
11799         if (object)
11800           return build3 (COMPONENT_REF, TREE_TYPE (templ),
11801                          object, templ, NULL_TREE);
11802         else
11803           return baselink_for_fns (templ);
11804       }
11805
11806     case INDIRECT_REF:
11807       {
11808         tree r = RECUR (TREE_OPERAND (t, 0));
11809
11810         if (REFERENCE_REF_P (t))
11811           {
11812             /* A type conversion to reference type will be enclosed in
11813                such an indirect ref, but the substitution of the cast
11814                will have also added such an indirect ref.  */
11815             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
11816               r = convert_from_reference (r);
11817           }
11818         else
11819           r = build_x_indirect_ref (r, "unary *", complain);
11820         return r;
11821       }
11822
11823     case NOP_EXPR:
11824       return build_nop
11825         (tsubst (TREE_TYPE (t), args, complain, in_decl),
11826          RECUR (TREE_OPERAND (t, 0)));
11827
11828     case CAST_EXPR:
11829     case REINTERPRET_CAST_EXPR:
11830     case CONST_CAST_EXPR:
11831     case DYNAMIC_CAST_EXPR:
11832     case STATIC_CAST_EXPR:
11833       {
11834         tree type;
11835         tree op;
11836
11837         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11838         if (integral_constant_expression_p
11839             && !cast_valid_in_integral_constant_expression_p (type))
11840           {
11841             if (complain & tf_error)
11842               error ("a cast to a type other than an integral or "
11843                      "enumeration type cannot appear in a constant-expression");
11844             return error_mark_node; 
11845           }
11846
11847         op = RECUR (TREE_OPERAND (t, 0));
11848
11849         switch (TREE_CODE (t))
11850           {
11851           case CAST_EXPR:
11852             return build_functional_cast (type, op, complain);
11853           case REINTERPRET_CAST_EXPR:
11854             return build_reinterpret_cast (type, op, complain);
11855           case CONST_CAST_EXPR:
11856             return build_const_cast (type, op, complain);
11857           case DYNAMIC_CAST_EXPR:
11858             return build_dynamic_cast (type, op, complain);
11859           case STATIC_CAST_EXPR:
11860             return build_static_cast (type, op, complain);
11861           default:
11862             gcc_unreachable ();
11863           }
11864       }
11865
11866     case POSTDECREMENT_EXPR:
11867     case POSTINCREMENT_EXPR:
11868       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11869                                                 args, complain, in_decl);
11870       return build_x_unary_op (TREE_CODE (t), op1, complain);
11871
11872     case PREDECREMENT_EXPR:
11873     case PREINCREMENT_EXPR:
11874     case NEGATE_EXPR:
11875     case BIT_NOT_EXPR:
11876     case ABS_EXPR:
11877     case TRUTH_NOT_EXPR:
11878     case UNARY_PLUS_EXPR:  /* Unary + */
11879     case REALPART_EXPR:
11880     case IMAGPART_EXPR:
11881       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
11882                                complain);
11883
11884     case ADDR_EXPR:
11885       op1 = TREE_OPERAND (t, 0);
11886       if (TREE_CODE (op1) == SCOPE_REF)
11887         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
11888                                    /*done=*/true, /*address_p=*/true);
11889       else
11890         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
11891                                                   in_decl);
11892       if (TREE_CODE (op1) == LABEL_DECL)
11893         return finish_label_address_expr (DECL_NAME (op1),
11894                                           EXPR_LOCATION (op1));
11895       return build_x_unary_op (ADDR_EXPR, op1, complain);
11896
11897     case PLUS_EXPR:
11898     case MINUS_EXPR:
11899     case MULT_EXPR:
11900     case TRUNC_DIV_EXPR:
11901     case CEIL_DIV_EXPR:
11902     case FLOOR_DIV_EXPR:
11903     case ROUND_DIV_EXPR:
11904     case EXACT_DIV_EXPR:
11905     case BIT_AND_EXPR:
11906     case BIT_IOR_EXPR:
11907     case BIT_XOR_EXPR:
11908     case TRUNC_MOD_EXPR:
11909     case FLOOR_MOD_EXPR:
11910     case TRUTH_ANDIF_EXPR:
11911     case TRUTH_ORIF_EXPR:
11912     case TRUTH_AND_EXPR:
11913     case TRUTH_OR_EXPR:
11914     case RSHIFT_EXPR:
11915     case LSHIFT_EXPR:
11916     case RROTATE_EXPR:
11917     case LROTATE_EXPR:
11918     case EQ_EXPR:
11919     case NE_EXPR:
11920     case MAX_EXPR:
11921     case MIN_EXPR:
11922     case LE_EXPR:
11923     case GE_EXPR:
11924     case LT_EXPR:
11925     case GT_EXPR:
11926     case MEMBER_REF:
11927     case DOTSTAR_EXPR:
11928       return build_x_binary_op
11929         (TREE_CODE (t),
11930          RECUR (TREE_OPERAND (t, 0)),
11931          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
11932           ? ERROR_MARK
11933           : TREE_CODE (TREE_OPERAND (t, 0))),
11934          RECUR (TREE_OPERAND (t, 1)),
11935          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
11936           ? ERROR_MARK
11937           : TREE_CODE (TREE_OPERAND (t, 1))),
11938          /*overloaded_p=*/NULL,
11939          complain);
11940
11941     case SCOPE_REF:
11942       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
11943                                   /*address_p=*/false);
11944     case ARRAY_REF:
11945       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
11946                                                 args, complain, in_decl);
11947       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
11948
11949     case SIZEOF_EXPR:
11950       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11951         return tsubst_copy (t, args, complain, in_decl);
11952       /* Fall through */
11953       
11954     case ALIGNOF_EXPR:
11955       op1 = TREE_OPERAND (t, 0);
11956       if (!args)
11957         {
11958           /* When there are no ARGS, we are trying to evaluate a
11959              non-dependent expression from the parser.  Trying to do
11960              the substitutions may not work.  */
11961           if (!TYPE_P (op1))
11962             op1 = TREE_TYPE (op1);
11963         }
11964       else
11965         {
11966           ++cp_unevaluated_operand;
11967           ++c_inhibit_evaluation_warnings;
11968           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
11969                                        /*function_p=*/false,
11970                                        /*integral_constant_expression_p=*/false);
11971           --cp_unevaluated_operand;
11972           --c_inhibit_evaluation_warnings;
11973         }
11974       if (TYPE_P (op1))
11975         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
11976                                            complain & tf_error);
11977       else
11978         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
11979                                            complain & tf_error);
11980
11981     case MODOP_EXPR:
11982       {
11983         tree r = build_x_modify_expr
11984           (RECUR (TREE_OPERAND (t, 0)),
11985            TREE_CODE (TREE_OPERAND (t, 1)),
11986            RECUR (TREE_OPERAND (t, 2)),
11987            complain);
11988         /* TREE_NO_WARNING must be set if either the expression was
11989            parenthesized or it uses an operator such as >>= rather
11990            than plain assignment.  In the former case, it was already
11991            set and must be copied.  In the latter case,
11992            build_x_modify_expr sets it and it must not be reset
11993            here.  */
11994         if (TREE_NO_WARNING (t))
11995           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
11996         return r;
11997       }
11998
11999     case ARROW_EXPR:
12000       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12001                                                 args, complain, in_decl);
12002       /* Remember that there was a reference to this entity.  */
12003       if (DECL_P (op1))
12004         mark_used (op1);
12005       return build_x_arrow (op1);
12006
12007     case NEW_EXPR:
12008       {
12009         tree placement = RECUR (TREE_OPERAND (t, 0));
12010         tree init = RECUR (TREE_OPERAND (t, 3));
12011         VEC(tree,gc) *placement_vec;
12012         VEC(tree,gc) *init_vec;
12013         tree ret;
12014
12015         if (placement == NULL_TREE)
12016           placement_vec = NULL;
12017         else
12018           {
12019             placement_vec = make_tree_vector ();
12020             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
12021               VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
12022           }
12023
12024         /* If there was an initializer in the original tree, but it
12025            instantiated to an empty list, then we should pass a
12026            non-NULL empty vector to tell build_new that it was an
12027            empty initializer() rather than no initializer.  This can
12028            only happen when the initializer is a pack expansion whose
12029            parameter packs are of length zero.  */
12030         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
12031           init_vec = NULL;
12032         else
12033           {
12034             init_vec = make_tree_vector ();
12035             if (init == void_zero_node)
12036               gcc_assert (init_vec != NULL);
12037             else
12038               {
12039                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
12040                   VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
12041               }
12042           }
12043
12044         ret = build_new (&placement_vec,
12045                          RECUR (TREE_OPERAND (t, 1)),
12046                          RECUR (TREE_OPERAND (t, 2)),
12047                          &init_vec,
12048                          NEW_EXPR_USE_GLOBAL (t),
12049                          complain);
12050
12051         if (placement_vec != NULL)
12052           release_tree_vector (placement_vec);
12053         if (init_vec != NULL)
12054           release_tree_vector (init_vec);
12055
12056         return ret;
12057       }
12058
12059     case DELETE_EXPR:
12060      return delete_sanity
12061        (RECUR (TREE_OPERAND (t, 0)),
12062         RECUR (TREE_OPERAND (t, 1)),
12063         DELETE_EXPR_USE_VEC (t),
12064         DELETE_EXPR_USE_GLOBAL (t));
12065
12066     case COMPOUND_EXPR:
12067       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
12068                                     RECUR (TREE_OPERAND (t, 1)),
12069                                     complain);
12070
12071     case CALL_EXPR:
12072       {
12073         tree function;
12074         VEC(tree,gc) *call_args;
12075         unsigned int nargs, i;
12076         bool qualified_p;
12077         bool koenig_p;
12078         tree ret;
12079
12080         function = CALL_EXPR_FN (t);
12081         /* When we parsed the expression,  we determined whether or
12082            not Koenig lookup should be performed.  */
12083         koenig_p = KOENIG_LOOKUP_P (t);
12084         if (TREE_CODE (function) == SCOPE_REF)
12085           {
12086             qualified_p = true;
12087             function = tsubst_qualified_id (function, args, complain, in_decl,
12088                                             /*done=*/false,
12089                                             /*address_p=*/false);
12090           }
12091         else
12092           {
12093             if (TREE_CODE (function) == COMPONENT_REF)
12094               {
12095                 tree op = TREE_OPERAND (function, 1);
12096
12097                 qualified_p = (TREE_CODE (op) == SCOPE_REF
12098                                || (BASELINK_P (op)
12099                                    && BASELINK_QUALIFIED_P (op)));
12100               }
12101             else
12102               qualified_p = false;
12103
12104             function = tsubst_copy_and_build (function, args, complain,
12105                                               in_decl,
12106                                               !qualified_p,
12107                                               integral_constant_expression_p);
12108
12109             if (BASELINK_P (function))
12110               qualified_p = true;
12111           }
12112
12113         nargs = call_expr_nargs (t);
12114         call_args = make_tree_vector ();
12115         for (i = 0; i < nargs; ++i)
12116           {
12117             tree arg = CALL_EXPR_ARG (t, i);
12118
12119             if (!PACK_EXPANSION_P (arg))
12120               VEC_safe_push (tree, gc, call_args,
12121                              RECUR (CALL_EXPR_ARG (t, i)));
12122             else
12123               {
12124                 /* Expand the pack expansion and push each entry onto
12125                    CALL_ARGS.  */
12126                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
12127                 if (TREE_CODE (arg) == TREE_VEC)
12128                   {
12129                     unsigned int len, j;
12130
12131                     len = TREE_VEC_LENGTH (arg);
12132                     for (j = 0; j < len; ++j)
12133                       {
12134                         tree value = TREE_VEC_ELT (arg, j);
12135                         if (value != NULL_TREE)
12136                           value = convert_from_reference (value);
12137                         VEC_safe_push (tree, gc, call_args, value);
12138                       }
12139                   }
12140                 else
12141                   {
12142                     /* A partial substitution.  Add one entry.  */
12143                     VEC_safe_push (tree, gc, call_args, arg);
12144                   }
12145               }
12146           }
12147
12148         /* We do not perform argument-dependent lookup if normal
12149            lookup finds a non-function, in accordance with the
12150            expected resolution of DR 218.  */
12151         if (koenig_p
12152             && ((is_overloaded_fn (function)
12153                  /* If lookup found a member function, the Koenig lookup is
12154                     not appropriate, even if an unqualified-name was used
12155                     to denote the function.  */
12156                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
12157                 || TREE_CODE (function) == IDENTIFIER_NODE)
12158             /* Only do this when substitution turns a dependent call
12159                into a non-dependent call.  */
12160             && type_dependent_expression_p_push (t)
12161             && !any_type_dependent_arguments_p (call_args))
12162           function = perform_koenig_lookup (function, call_args);
12163
12164         if (TREE_CODE (function) == IDENTIFIER_NODE)
12165           {
12166             unqualified_name_lookup_error (function);
12167             release_tree_vector (call_args);
12168             return error_mark_node;
12169           }
12170
12171         /* Remember that there was a reference to this entity.  */
12172         if (DECL_P (function))
12173           mark_used (function);
12174
12175         if (TREE_CODE (function) == OFFSET_REF)
12176           ret = build_offset_ref_call_from_tree (function, &call_args);
12177         else if (TREE_CODE (function) == COMPONENT_REF)
12178           {
12179             if (!BASELINK_P (TREE_OPERAND (function, 1)))
12180               ret = finish_call_expr (function, &call_args,
12181                                        /*disallow_virtual=*/false,
12182                                        /*koenig_p=*/false,
12183                                        complain);
12184             else
12185               ret = (build_new_method_call
12186                       (TREE_OPERAND (function, 0),
12187                        TREE_OPERAND (function, 1),
12188                        &call_args, NULL_TREE,
12189                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
12190                        /*fn_p=*/NULL,
12191                        complain));
12192           }
12193         else
12194           ret = finish_call_expr (function, &call_args,
12195                                   /*disallow_virtual=*/qualified_p,
12196                                   koenig_p,
12197                                   complain);
12198
12199         release_tree_vector (call_args);
12200
12201         return ret;
12202       }
12203
12204     case COND_EXPR:
12205       return build_x_conditional_expr
12206         (RECUR (TREE_OPERAND (t, 0)),
12207          RECUR (TREE_OPERAND (t, 1)),
12208          RECUR (TREE_OPERAND (t, 2)),
12209          complain);
12210
12211     case PSEUDO_DTOR_EXPR:
12212       return finish_pseudo_destructor_expr
12213         (RECUR (TREE_OPERAND (t, 0)),
12214          RECUR (TREE_OPERAND (t, 1)),
12215          RECUR (TREE_OPERAND (t, 2)));
12216
12217     case TREE_LIST:
12218       {
12219         tree purpose, value, chain;
12220
12221         if (t == void_list_node)
12222           return t;
12223
12224         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
12225             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
12226           {
12227             /* We have pack expansions, so expand those and
12228                create a new list out of it.  */
12229             tree purposevec = NULL_TREE;
12230             tree valuevec = NULL_TREE;
12231             tree chain;
12232             int i, len = -1;
12233
12234             /* Expand the argument expressions.  */
12235             if (TREE_PURPOSE (t))
12236               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
12237                                                  complain, in_decl);
12238             if (TREE_VALUE (t))
12239               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
12240                                                complain, in_decl);
12241
12242             /* Build the rest of the list.  */
12243             chain = TREE_CHAIN (t);
12244             if (chain && chain != void_type_node)
12245               chain = RECUR (chain);
12246
12247             /* Determine the number of arguments.  */
12248             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
12249               {
12250                 len = TREE_VEC_LENGTH (purposevec);
12251                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
12252               }
12253             else if (TREE_CODE (valuevec) == TREE_VEC)
12254               len = TREE_VEC_LENGTH (valuevec);
12255             else
12256               {
12257                 /* Since we only performed a partial substitution into
12258                    the argument pack, we only return a single list
12259                    node.  */
12260                 if (purposevec == TREE_PURPOSE (t)
12261                     && valuevec == TREE_VALUE (t)
12262                     && chain == TREE_CHAIN (t))
12263                   return t;
12264
12265                 return tree_cons (purposevec, valuevec, chain);
12266               }
12267             
12268             /* Convert the argument vectors into a TREE_LIST */
12269             i = len;
12270             while (i > 0)
12271               {
12272                 /* Grab the Ith values.  */
12273                 i--;
12274                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
12275                                      : NULL_TREE;
12276                 value 
12277                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
12278                              : NULL_TREE;
12279
12280                 /* Build the list (backwards).  */
12281                 chain = tree_cons (purpose, value, chain);
12282               }
12283
12284             return chain;
12285           }
12286
12287         purpose = TREE_PURPOSE (t);
12288         if (purpose)
12289           purpose = RECUR (purpose);
12290         value = TREE_VALUE (t);
12291         if (value)
12292           value = RECUR (value);
12293         chain = TREE_CHAIN (t);
12294         if (chain && chain != void_type_node)
12295           chain = RECUR (chain);
12296         if (purpose == TREE_PURPOSE (t)
12297             && value == TREE_VALUE (t)
12298             && chain == TREE_CHAIN (t))
12299           return t;
12300         return tree_cons (purpose, value, chain);
12301       }
12302
12303     case COMPONENT_REF:
12304       {
12305         tree object;
12306         tree object_type;
12307         tree member;
12308
12309         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12310                                                      args, complain, in_decl);
12311         /* Remember that there was a reference to this entity.  */
12312         if (DECL_P (object))
12313           mark_used (object);
12314         object_type = TREE_TYPE (object);
12315
12316         member = TREE_OPERAND (t, 1);
12317         if (BASELINK_P (member))
12318           member = tsubst_baselink (member,
12319                                     non_reference (TREE_TYPE (object)),
12320                                     args, complain, in_decl);
12321         else
12322           member = tsubst_copy (member, args, complain, in_decl);
12323         if (member == error_mark_node)
12324           return error_mark_node;
12325
12326         if (object_type && !CLASS_TYPE_P (object_type))
12327           {
12328             if (SCALAR_TYPE_P (object_type))
12329               {
12330                 tree s = NULL_TREE;
12331                 tree dtor = member;
12332
12333                 if (TREE_CODE (dtor) == SCOPE_REF)
12334                   {
12335                     s = TREE_OPERAND (dtor, 0);
12336                     dtor = TREE_OPERAND (dtor, 1);
12337                   }
12338                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
12339                   {
12340                     dtor = TREE_OPERAND (dtor, 0);
12341                     if (TYPE_P (dtor))
12342                       return finish_pseudo_destructor_expr (object, s, dtor);
12343                   }
12344               }
12345           }
12346         else if (TREE_CODE (member) == SCOPE_REF
12347                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
12348           {
12349             tree tmpl;
12350             tree args;
12351
12352             /* Lookup the template functions now that we know what the
12353                scope is.  */
12354             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
12355             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
12356             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
12357                                             /*is_type_p=*/false,
12358                                             /*complain=*/false);
12359             if (BASELINK_P (member))
12360               {
12361                 BASELINK_FUNCTIONS (member)
12362                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
12363                               args);
12364                 member = (adjust_result_of_qualified_name_lookup
12365                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
12366                            object_type));
12367               }
12368             else
12369               {
12370                 qualified_name_lookup_error (object_type, tmpl, member,
12371                                              input_location);
12372                 return error_mark_node;
12373               }
12374           }
12375         else if (TREE_CODE (member) == SCOPE_REF
12376                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
12377                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
12378           {
12379             if (complain & tf_error)
12380               {
12381                 if (TYPE_P (TREE_OPERAND (member, 0)))
12382                   error ("%qT is not a class or namespace",
12383                          TREE_OPERAND (member, 0));
12384                 else
12385                   error ("%qD is not a class or namespace",
12386                          TREE_OPERAND (member, 0));
12387               }
12388             return error_mark_node;
12389           }
12390         else if (TREE_CODE (member) == FIELD_DECL)
12391           return finish_non_static_data_member (member, object, NULL_TREE);
12392
12393         return finish_class_member_access_expr (object, member,
12394                                                 /*template_p=*/false,
12395                                                 complain);
12396       }
12397
12398     case THROW_EXPR:
12399       return build_throw
12400         (RECUR (TREE_OPERAND (t, 0)));
12401
12402     case CONSTRUCTOR:
12403       {
12404         VEC(constructor_elt,gc) *n;
12405         constructor_elt *ce;
12406         unsigned HOST_WIDE_INT idx;
12407         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12408         bool process_index_p;
12409         int newlen;
12410         bool need_copy_p = false;
12411         tree r;
12412
12413         if (type == error_mark_node)
12414           return error_mark_node;
12415
12416         /* digest_init will do the wrong thing if we let it.  */
12417         if (type && TYPE_PTRMEMFUNC_P (type))
12418           return t;
12419
12420         /* We do not want to process the index of aggregate
12421            initializers as they are identifier nodes which will be
12422            looked up by digest_init.  */
12423         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
12424
12425         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
12426         newlen = VEC_length (constructor_elt, n);
12427         for (idx = 0; VEC_iterate (constructor_elt, n, idx, ce); idx++)
12428           {
12429             if (ce->index && process_index_p)
12430               ce->index = RECUR (ce->index);
12431
12432             if (PACK_EXPANSION_P (ce->value))
12433               {
12434                 /* Substitute into the pack expansion.  */
12435                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
12436                                                   in_decl);
12437
12438                 if (ce->value == error_mark_node)
12439                   ;
12440                 else if (TREE_VEC_LENGTH (ce->value) == 1)
12441                   /* Just move the argument into place.  */
12442                   ce->value = TREE_VEC_ELT (ce->value, 0);
12443                 else
12444                   {
12445                     /* Update the length of the final CONSTRUCTOR
12446                        arguments vector, and note that we will need to
12447                        copy.*/
12448                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
12449                     need_copy_p = true;
12450                   }
12451               }
12452             else
12453               ce->value = RECUR (ce->value);
12454           }
12455
12456         if (need_copy_p)
12457           {
12458             VEC(constructor_elt,gc) *old_n = n;
12459
12460             n = VEC_alloc (constructor_elt, gc, newlen);
12461             for (idx = 0; VEC_iterate (constructor_elt, old_n, idx, ce); 
12462                  idx++)
12463               {
12464                 if (TREE_CODE (ce->value) == TREE_VEC)
12465                   {
12466                     int i, len = TREE_VEC_LENGTH (ce->value);
12467                     for (i = 0; i < len; ++i)
12468                       CONSTRUCTOR_APPEND_ELT (n, 0,
12469                                               TREE_VEC_ELT (ce->value, i));
12470                   }
12471                 else
12472                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
12473               }
12474           }
12475
12476         r = build_constructor (init_list_type_node, n);
12477         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
12478
12479         if (TREE_HAS_CONSTRUCTOR (t))
12480           return finish_compound_literal (type, r);
12481
12482         return r;
12483       }
12484
12485     case TYPEID_EXPR:
12486       {
12487         tree operand_0 = RECUR (TREE_OPERAND (t, 0));
12488         if (TYPE_P (operand_0))
12489           return get_typeid (operand_0);
12490         return build_typeid (operand_0);
12491       }
12492
12493     case VAR_DECL:
12494       if (!args)
12495         return t;
12496       /* Fall through */
12497
12498     case PARM_DECL:
12499       {
12500         tree r = tsubst_copy (t, args, complain, in_decl);
12501
12502         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
12503           /* If the original type was a reference, we'll be wrapped in
12504              the appropriate INDIRECT_REF.  */
12505           r = convert_from_reference (r);
12506         return r;
12507       }
12508
12509     case VA_ARG_EXPR:
12510       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
12511                              tsubst_copy (TREE_TYPE (t), args, complain,
12512                                           in_decl));
12513
12514     case OFFSETOF_EXPR:
12515       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
12516
12517     case TRAIT_EXPR:
12518       {
12519         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
12520                                   complain, in_decl);
12521
12522         tree type2 = TRAIT_EXPR_TYPE2 (t);
12523         if (type2)
12524           type2 = tsubst_copy (type2, args, complain, in_decl);
12525         
12526         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
12527       }
12528
12529     case STMT_EXPR:
12530       {
12531         tree old_stmt_expr = cur_stmt_expr;
12532         tree stmt_expr = begin_stmt_expr ();
12533
12534         cur_stmt_expr = stmt_expr;
12535         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
12536                      integral_constant_expression_p);
12537         stmt_expr = finish_stmt_expr (stmt_expr, false);
12538         cur_stmt_expr = old_stmt_expr;
12539
12540         return stmt_expr;
12541       }
12542
12543     case CONST_DECL:
12544       t = tsubst_copy (t, args, complain, in_decl);
12545       /* As in finish_id_expression, we resolve enumeration constants
12546          to their underlying values.  */
12547       if (TREE_CODE (t) == CONST_DECL)
12548         {
12549           used_types_insert (TREE_TYPE (t));
12550           return DECL_INITIAL (t);
12551         }
12552       return t;
12553
12554     case LAMBDA_EXPR:
12555       {
12556         tree r = build_lambda_expr ();
12557
12558         tree type = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
12559         TREE_TYPE (r) = type;
12560         CLASSTYPE_LAMBDA_EXPR (type) = r;
12561
12562         LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
12563           = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
12564         LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
12565         LAMBDA_EXPR_DISCRIMINATOR (r)
12566           = (LAMBDA_EXPR_DISCRIMINATOR (t));
12567         LAMBDA_EXPR_CAPTURE_LIST (r)
12568           = RECUR (LAMBDA_EXPR_CAPTURE_LIST (t));
12569         LAMBDA_EXPR_THIS_CAPTURE (r)
12570           = RECUR (LAMBDA_EXPR_THIS_CAPTURE (t));
12571         LAMBDA_EXPR_EXTRA_SCOPE (r)
12572           = RECUR (LAMBDA_EXPR_EXTRA_SCOPE (t));
12573
12574         /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
12575         determine_visibility (TYPE_NAME (type));
12576         /* Now that we know visibility, instantiate the type so we have a
12577            declaration of the op() for later calls to lambda_function.  */
12578         complete_type (type);
12579
12580         type = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
12581         if (type)
12582           apply_lambda_return_type (r, type);
12583
12584         return build_lambda_object (r);
12585       }
12586
12587     default:
12588       /* Handle Objective-C++ constructs, if appropriate.  */
12589       {
12590         tree subst
12591           = objcp_tsubst_copy_and_build (t, args, complain,
12592                                          in_decl, /*function_p=*/false);
12593         if (subst)
12594           return subst;
12595       }
12596       return tsubst_copy (t, args, complain, in_decl);
12597     }
12598
12599 #undef RECUR
12600 }
12601
12602 /* Verify that the instantiated ARGS are valid. For type arguments,
12603    make sure that the type's linkage is ok. For non-type arguments,
12604    make sure they are constants if they are integral or enumerations.
12605    Emit an error under control of COMPLAIN, and return TRUE on error.  */
12606
12607 static bool
12608 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
12609 {
12610   if (ARGUMENT_PACK_P (t))
12611     {
12612       tree vec = ARGUMENT_PACK_ARGS (t);
12613       int len = TREE_VEC_LENGTH (vec);
12614       bool result = false;
12615       int i;
12616
12617       for (i = 0; i < len; ++i)
12618         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
12619           result = true;
12620       return result;
12621     }
12622   else if (TYPE_P (t))
12623     {
12624       /* [basic.link]: A name with no linkage (notably, the name
12625          of a class or enumeration declared in a local scope)
12626          shall not be used to declare an entity with linkage.
12627          This implies that names with no linkage cannot be used as
12628          template arguments
12629
12630          DR 757 relaxes this restriction for C++0x.  */
12631       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
12632                  : no_linkage_check (t, /*relaxed_p=*/false));
12633
12634       if (nt)
12635         {
12636           /* DR 488 makes use of a type with no linkage cause
12637              type deduction to fail.  */
12638           if (complain & tf_error)
12639             {
12640               if (TYPE_ANONYMOUS_P (nt))
12641                 error ("%qT is/uses anonymous type", t);
12642               else
12643                 error ("template argument for %qD uses local type %qT",
12644                        tmpl, t);
12645             }
12646           return true;
12647         }
12648       /* In order to avoid all sorts of complications, we do not
12649          allow variably-modified types as template arguments.  */
12650       else if (variably_modified_type_p (t, NULL_TREE))
12651         {
12652           if (complain & tf_error)
12653             error ("%qT is a variably modified type", t);
12654           return true;
12655         }
12656     }
12657   /* A non-type argument of integral or enumerated type must be a
12658      constant.  */
12659   else if (TREE_TYPE (t)
12660            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
12661            && !TREE_CONSTANT (t))
12662     {
12663       if (complain & tf_error)
12664         error ("integral expression %qE is not constant", t);
12665       return true;
12666     }
12667   return false;
12668 }
12669
12670 static bool
12671 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
12672 {
12673   int ix, len = DECL_NTPARMS (tmpl);
12674   bool result = false;
12675
12676   for (ix = 0; ix != len; ix++)
12677     {
12678       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
12679         result = true;
12680     }
12681   if (result && (complain & tf_error))
12682     error ("  trying to instantiate %qD", tmpl);
12683   return result;
12684 }
12685
12686 /* Instantiate the indicated variable or function template TMPL with
12687    the template arguments in TARG_PTR.  */
12688
12689 tree
12690 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
12691 {
12692   tree targ_ptr = orig_args;
12693   tree fndecl;
12694   tree gen_tmpl;
12695   tree spec;
12696   HOST_WIDE_INT saved_processing_template_decl;
12697
12698   if (tmpl == error_mark_node)
12699     return error_mark_node;
12700
12701   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
12702
12703   /* If this function is a clone, handle it specially.  */
12704   if (DECL_CLONED_FUNCTION_P (tmpl))
12705     {
12706       tree spec;
12707       tree clone;
12708
12709       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
12710          DECL_CLONED_FUNCTION.  */
12711       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
12712                                    targ_ptr, complain);
12713       if (spec == error_mark_node)
12714         return error_mark_node;
12715
12716       /* Look for the clone.  */
12717       FOR_EACH_CLONE (clone, spec)
12718         if (DECL_NAME (clone) == DECL_NAME (tmpl))
12719           return clone;
12720       /* We should always have found the clone by now.  */
12721       gcc_unreachable ();
12722       return NULL_TREE;
12723     }
12724
12725   /* Check to see if we already have this specialization.  */
12726   gen_tmpl = most_general_template (tmpl);
12727   if (tmpl != gen_tmpl)
12728     /* The TMPL is a partial instantiation.  To get a full set of
12729        arguments we must add the arguments used to perform the
12730        partial instantiation.  */
12731     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
12732                                             targ_ptr);
12733
12734   /* It would be nice to avoid hashing here and then again in tsubst_decl,
12735      but it doesn't seem to be on the hot path.  */
12736   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
12737
12738   gcc_assert (tmpl == gen_tmpl
12739               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
12740                   == spec)
12741               || fndecl == NULL_TREE);
12742
12743   if (spec != NULL_TREE)
12744     return spec;
12745
12746   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
12747                                complain))
12748     return error_mark_node;
12749
12750   /* We are building a FUNCTION_DECL, during which the access of its
12751      parameters and return types have to be checked.  However this
12752      FUNCTION_DECL which is the desired context for access checking
12753      is not built yet.  We solve this chicken-and-egg problem by
12754      deferring all checks until we have the FUNCTION_DECL.  */
12755   push_deferring_access_checks (dk_deferred);
12756
12757   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
12758      (because, for example, we have encountered a non-dependent
12759      function call in the body of a template function and must now
12760      determine which of several overloaded functions will be called),
12761      within the instantiation itself we are not processing a
12762      template.  */  
12763   saved_processing_template_decl = processing_template_decl;
12764   processing_template_decl = 0;
12765   /* Substitute template parameters to obtain the specialization.  */
12766   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
12767                    targ_ptr, complain, gen_tmpl);
12768   processing_template_decl = saved_processing_template_decl;
12769   if (fndecl == error_mark_node)
12770     return error_mark_node;
12771
12772   /* Now we know the specialization, compute access previously
12773      deferred.  */
12774   push_access_scope (fndecl);
12775
12776   /* Some typedefs referenced from within the template code need to be access
12777      checked at template instantiation time, i.e now. These types were
12778      added to the template at parsing time. Let's get those and perfom
12779      the acces checks then.  */
12780   perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
12781   perform_deferred_access_checks ();
12782   pop_access_scope (fndecl);
12783   pop_deferring_access_checks ();
12784
12785   /* The DECL_TI_TEMPLATE should always be the immediate parent
12786      template, not the most general template.  */
12787   DECL_TI_TEMPLATE (fndecl) = tmpl;
12788
12789   /* If we've just instantiated the main entry point for a function,
12790      instantiate all the alternate entry points as well.  We do this
12791      by cloning the instantiation of the main entry point, not by
12792      instantiating the template clones.  */
12793   if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
12794     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
12795
12796   return fndecl;
12797 }
12798
12799 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
12800    NARGS elements of the arguments that are being used when calling
12801    it.  TARGS is a vector into which the deduced template arguments
12802    are placed.
12803
12804    Return zero for success, 2 for an incomplete match that doesn't resolve
12805    all the types, and 1 for complete failure.  An error message will be
12806    printed only for an incomplete match.
12807
12808    If FN is a conversion operator, or we are trying to produce a specific
12809    specialization, RETURN_TYPE is the return type desired.
12810
12811    The EXPLICIT_TARGS are explicit template arguments provided via a
12812    template-id.
12813
12814    The parameter STRICT is one of:
12815
12816    DEDUCE_CALL:
12817      We are deducing arguments for a function call, as in
12818      [temp.deduct.call].
12819
12820    DEDUCE_CONV:
12821      We are deducing arguments for a conversion function, as in
12822      [temp.deduct.conv].
12823
12824    DEDUCE_EXACT:
12825      We are deducing arguments when doing an explicit instantiation
12826      as in [temp.explicit], when determining an explicit specialization
12827      as in [temp.expl.spec], or when taking the address of a function
12828      template, as in [temp.deduct.funcaddr].  */
12829
12830 int
12831 fn_type_unification (tree fn,
12832                      tree explicit_targs,
12833                      tree targs,
12834                      const tree *args,
12835                      unsigned int nargs,
12836                      tree return_type,
12837                      unification_kind_t strict,
12838                      int flags)
12839 {
12840   tree parms;
12841   tree fntype;
12842   int result;
12843   bool incomplete_argument_packs_p = false;
12844
12845   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
12846
12847   fntype = TREE_TYPE (fn);
12848   if (explicit_targs)
12849     {
12850       /* [temp.deduct]
12851
12852          The specified template arguments must match the template
12853          parameters in kind (i.e., type, nontype, template), and there
12854          must not be more arguments than there are parameters;
12855          otherwise type deduction fails.
12856
12857          Nontype arguments must match the types of the corresponding
12858          nontype template parameters, or must be convertible to the
12859          types of the corresponding nontype parameters as specified in
12860          _temp.arg.nontype_, otherwise type deduction fails.
12861
12862          All references in the function type of the function template
12863          to the corresponding template parameters are replaced by the
12864          specified template argument values.  If a substitution in a
12865          template parameter or in the function type of the function
12866          template results in an invalid type, type deduction fails.  */
12867       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
12868       int i, len = TREE_VEC_LENGTH (tparms);
12869       tree converted_args;
12870       bool incomplete = false;
12871
12872       if (explicit_targs == error_mark_node)
12873         return 1;
12874
12875       converted_args
12876         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
12877                                   /*require_all_args=*/false,
12878                                   /*use_default_args=*/false));
12879       if (converted_args == error_mark_node)
12880         return 1;
12881
12882       /* Substitute the explicit args into the function type.  This is
12883          necessary so that, for instance, explicitly declared function
12884          arguments can match null pointed constants.  If we were given
12885          an incomplete set of explicit args, we must not do semantic
12886          processing during substitution as we could create partial
12887          instantiations.  */
12888       for (i = 0; i < len; i++)
12889         {
12890           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
12891           bool parameter_pack = false;
12892
12893           /* Dig out the actual parm.  */
12894           if (TREE_CODE (parm) == TYPE_DECL
12895               || TREE_CODE (parm) == TEMPLATE_DECL)
12896             {
12897               parm = TREE_TYPE (parm);
12898               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
12899             }
12900           else if (TREE_CODE (parm) == PARM_DECL)
12901             {
12902               parm = DECL_INITIAL (parm);
12903               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
12904             }
12905
12906           if (parameter_pack)
12907             {
12908               int level, idx;
12909               tree targ;
12910               template_parm_level_and_index (parm, &level, &idx);
12911
12912               /* Mark the argument pack as "incomplete". We could
12913                  still deduce more arguments during unification.  */
12914               targ = TMPL_ARG (converted_args, level, idx);
12915               if (targ)
12916                 {
12917                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
12918                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
12919                     = ARGUMENT_PACK_ARGS (targ);
12920                 }
12921
12922               /* We have some incomplete argument packs.  */
12923               incomplete_argument_packs_p = true;
12924             }
12925         }
12926
12927       if (incomplete_argument_packs_p)
12928         /* Any substitution is guaranteed to be incomplete if there
12929            are incomplete argument packs, because we can still deduce
12930            more arguments.  */
12931         incomplete = 1;
12932       else
12933         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
12934
12935       processing_template_decl += incomplete;
12936       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
12937       processing_template_decl -= incomplete;
12938
12939       if (fntype == error_mark_node)
12940         return 1;
12941
12942       /* Place the explicitly specified arguments in TARGS.  */
12943       for (i = NUM_TMPL_ARGS (converted_args); i--;)
12944         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
12945     }
12946
12947   /* Never do unification on the 'this' parameter.  */
12948   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
12949
12950   if (return_type)
12951     {
12952       tree *new_args;
12953
12954       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
12955       new_args = XALLOCAVEC (tree, nargs + 1);
12956       new_args[0] = return_type;
12957       memcpy (new_args + 1, args, nargs * sizeof (tree));
12958       args = new_args;
12959       ++nargs;
12960     }
12961
12962   /* We allow incomplete unification without an error message here
12963      because the standard doesn't seem to explicitly prohibit it.  Our
12964      callers must be ready to deal with unification failures in any
12965      event.  */
12966   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
12967                                   targs, parms, args, nargs, /*subr=*/0,
12968                                   strict, flags);
12969
12970   if (result == 0 && incomplete_argument_packs_p)
12971     {
12972       int i, len = NUM_TMPL_ARGS (targs);
12973
12974       /* Clear the "incomplete" flags on all argument packs.  */
12975       for (i = 0; i < len; i++)
12976         {
12977           tree arg = TREE_VEC_ELT (targs, i);
12978           if (ARGUMENT_PACK_P (arg))
12979             {
12980               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
12981               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
12982             }
12983         }
12984     }
12985
12986   /* Now that we have bindings for all of the template arguments,
12987      ensure that the arguments deduced for the template template
12988      parameters have compatible template parameter lists.  We cannot
12989      check this property before we have deduced all template
12990      arguments, because the template parameter types of a template
12991      template parameter might depend on prior template parameters
12992      deduced after the template template parameter.  The following
12993      ill-formed example illustrates this issue:
12994
12995        template<typename T, template<T> class C> void f(C<5>, T);
12996
12997        template<int N> struct X {};
12998
12999        void g() {
13000          f(X<5>(), 5l); // error: template argument deduction fails
13001        }
13002
13003      The template parameter list of 'C' depends on the template type
13004      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
13005      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
13006      time that we deduce 'C'.  */
13007   if (result == 0
13008       && !template_template_parm_bindings_ok_p 
13009            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
13010     return 1;
13011
13012   if (result == 0)
13013     /* All is well so far.  Now, check:
13014
13015        [temp.deduct]
13016
13017        When all template arguments have been deduced, all uses of
13018        template parameters in nondeduced contexts are replaced with
13019        the corresponding deduced argument values.  If the
13020        substitution results in an invalid type, as described above,
13021        type deduction fails.  */
13022     {
13023       tree substed = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
13024       if (substed == error_mark_node)
13025         return 1;
13026
13027       /* If we're looking for an exact match, check that what we got
13028          is indeed an exact match.  It might not be if some template
13029          parameters are used in non-deduced contexts.  */
13030       if (strict == DEDUCE_EXACT)
13031         {
13032           unsigned int i;
13033
13034           tree sarg
13035             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
13036           if (return_type)
13037             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
13038           for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
13039             if (!same_type_p (args[i], TREE_VALUE (sarg)))
13040               return 1;
13041         }
13042     }
13043
13044   return result;
13045 }
13046
13047 /* Adjust types before performing type deduction, as described in
13048    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
13049    sections are symmetric.  PARM is the type of a function parameter
13050    or the return type of the conversion function.  ARG is the type of
13051    the argument passed to the call, or the type of the value
13052    initialized with the result of the conversion function.
13053    ARG_EXPR is the original argument expression, which may be null.  */
13054
13055 static int
13056 maybe_adjust_types_for_deduction (unification_kind_t strict,
13057                                   tree* parm,
13058                                   tree* arg,
13059                                   tree arg_expr)
13060 {
13061   int result = 0;
13062
13063   switch (strict)
13064     {
13065     case DEDUCE_CALL:
13066       break;
13067
13068     case DEDUCE_CONV:
13069       {
13070         /* Swap PARM and ARG throughout the remainder of this
13071            function; the handling is precisely symmetric since PARM
13072            will initialize ARG rather than vice versa.  */
13073         tree* temp = parm;
13074         parm = arg;
13075         arg = temp;
13076         break;
13077       }
13078
13079     case DEDUCE_EXACT:
13080       /* Core issue #873: Do the DR606 thing (see below) for these cases,
13081          too, but here handle it by stripping the reference from PARM
13082          rather than by adding it to ARG.  */
13083       if (TREE_CODE (*parm) == REFERENCE_TYPE
13084           && TYPE_REF_IS_RVALUE (*parm)
13085           && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13086           && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13087           && TREE_CODE (*arg) == REFERENCE_TYPE
13088           && !TYPE_REF_IS_RVALUE (*arg))
13089         *parm = TREE_TYPE (*parm);
13090       /* Nothing else to do in this case.  */
13091       return 0;
13092
13093     default:
13094       gcc_unreachable ();
13095     }
13096
13097   if (TREE_CODE (*parm) != REFERENCE_TYPE)
13098     {
13099       /* [temp.deduct.call]
13100
13101          If P is not a reference type:
13102
13103          --If A is an array type, the pointer type produced by the
13104          array-to-pointer standard conversion (_conv.array_) is
13105          used in place of A for type deduction; otherwise,
13106
13107          --If A is a function type, the pointer type produced by
13108          the function-to-pointer standard conversion
13109          (_conv.func_) is used in place of A for type deduction;
13110          otherwise,
13111
13112          --If A is a cv-qualified type, the top level
13113          cv-qualifiers of A's type are ignored for type
13114          deduction.  */
13115       if (TREE_CODE (*arg) == ARRAY_TYPE)
13116         *arg = build_pointer_type (TREE_TYPE (*arg));
13117       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
13118         *arg = build_pointer_type (*arg);
13119       else
13120         *arg = TYPE_MAIN_VARIANT (*arg);
13121     }
13122
13123   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
13124      of the form T&&, where T is a template parameter, and the argument
13125      is an lvalue, T is deduced as A& */
13126   if (TREE_CODE (*parm) == REFERENCE_TYPE
13127       && TYPE_REF_IS_RVALUE (*parm)
13128       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13129       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13130       && arg_expr && real_lvalue_p (arg_expr))
13131     *arg = build_reference_type (*arg);
13132
13133   /* [temp.deduct.call]
13134
13135      If P is a cv-qualified type, the top level cv-qualifiers
13136      of P's type are ignored for type deduction.  If P is a
13137      reference type, the type referred to by P is used for
13138      type deduction.  */
13139   *parm = TYPE_MAIN_VARIANT (*parm);
13140   if (TREE_CODE (*parm) == REFERENCE_TYPE)
13141     {
13142       *parm = TREE_TYPE (*parm);
13143       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
13144     }
13145
13146   /* DR 322. For conversion deduction, remove a reference type on parm
13147      too (which has been swapped into ARG).  */
13148   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
13149     *arg = TREE_TYPE (*arg);
13150
13151   return result;
13152 }
13153
13154 /* Most parms like fn_type_unification.
13155
13156    If SUBR is 1, we're being called recursively (to unify the
13157    arguments of a function or method parameter of a function
13158    template). */
13159
13160 static int
13161 type_unification_real (tree tparms,
13162                        tree targs,
13163                        tree xparms,
13164                        const tree *xargs,
13165                        unsigned int xnargs,
13166                        int subr,
13167                        unification_kind_t strict,
13168                        int flags)
13169 {
13170   tree parm, arg, arg_expr;
13171   int i;
13172   int ntparms = TREE_VEC_LENGTH (tparms);
13173   int sub_strict;
13174   int saw_undeduced = 0;
13175   tree parms;
13176   const tree *args;
13177   unsigned int nargs;
13178   unsigned int ia;
13179
13180   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
13181   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
13182   gcc_assert (ntparms > 0);
13183
13184   switch (strict)
13185     {
13186     case DEDUCE_CALL:
13187       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
13188                     | UNIFY_ALLOW_DERIVED);
13189       break;
13190
13191     case DEDUCE_CONV:
13192       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
13193       break;
13194
13195     case DEDUCE_EXACT:
13196       sub_strict = UNIFY_ALLOW_NONE;
13197       break;
13198
13199     default:
13200       gcc_unreachable ();
13201     }
13202
13203  again:
13204   parms = xparms;
13205   args = xargs;
13206   nargs = xnargs;
13207
13208   ia = 0;
13209   while (parms && parms != void_list_node
13210          && ia < nargs)
13211     {
13212       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13213         break;
13214
13215       parm = TREE_VALUE (parms);
13216       parms = TREE_CHAIN (parms);
13217       arg = args[ia];
13218       ++ia;
13219       arg_expr = NULL;
13220
13221       if (arg == error_mark_node)
13222         return 1;
13223       if (arg == unknown_type_node)
13224         /* We can't deduce anything from this, but we might get all the
13225            template args from other function args.  */
13226         continue;
13227
13228       /* Conversions will be performed on a function argument that
13229          corresponds with a function parameter that contains only
13230          non-deducible template parameters and explicitly specified
13231          template parameters.  */
13232       if (!uses_template_parms (parm))
13233         {
13234           tree type;
13235
13236           if (!TYPE_P (arg))
13237             type = TREE_TYPE (arg);
13238           else
13239             type = arg;
13240
13241           if (same_type_p (parm, type))
13242             continue;
13243           if (strict != DEDUCE_EXACT
13244               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
13245                                   flags))
13246             continue;
13247
13248           return 1;
13249         }
13250
13251       if (!TYPE_P (arg))
13252         {
13253           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
13254           if (type_unknown_p (arg))
13255             {
13256               /* [temp.deduct.type] 
13257
13258                  A template-argument can be deduced from a pointer to
13259                  function or pointer to member function argument if
13260                  the set of overloaded functions does not contain
13261                  function templates and at most one of a set of
13262                  overloaded functions provides a unique match.  */
13263               if (resolve_overloaded_unification
13264                   (tparms, targs, parm, arg, strict, sub_strict))
13265                 continue;
13266
13267               return 1;
13268             }
13269           arg_expr = arg;
13270           arg = unlowered_expr_type (arg);
13271           if (arg == error_mark_node)
13272             return 1;
13273         }
13274
13275       {
13276         int arg_strict = sub_strict;
13277
13278         if (!subr)
13279           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
13280                                                           arg_expr);
13281
13282         if (arg == init_list_type_node && arg_expr)
13283           arg = arg_expr;
13284         if (unify (tparms, targs, parm, arg, arg_strict))
13285           return 1;
13286       }
13287     }
13288
13289
13290   if (parms 
13291       && parms != void_list_node
13292       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13293     {
13294       /* Unify the remaining arguments with the pack expansion type.  */
13295       tree argvec;
13296       tree parmvec = make_tree_vec (1);
13297
13298       /* Allocate a TREE_VEC and copy in all of the arguments */ 
13299       argvec = make_tree_vec (nargs - ia);
13300       for (i = 0; ia < nargs; ++ia, ++i)
13301         TREE_VEC_ELT (argvec, i) = args[ia];
13302
13303       /* Copy the parameter into parmvec.  */
13304       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
13305       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
13306                                 /*call_args_p=*/true, /*subr=*/subr))
13307         return 1;
13308
13309       /* Advance to the end of the list of parameters.  */
13310       parms = TREE_CHAIN (parms);
13311     }
13312
13313   /* Fail if we've reached the end of the parm list, and more args
13314      are present, and the parm list isn't variadic.  */
13315   if (ia < nargs && parms == void_list_node)
13316     return 1;
13317   /* Fail if parms are left and they don't have default values.  */
13318   if (parms && parms != void_list_node
13319       && TREE_PURPOSE (parms) == NULL_TREE)
13320     return 1;
13321
13322   if (!subr)
13323     for (i = 0; i < ntparms; i++)
13324       if (!TREE_VEC_ELT (targs, i))
13325         {
13326           tree tparm;
13327
13328           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
13329             continue;
13330
13331           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13332
13333           /* If this is an undeduced nontype parameter that depends on
13334              a type parameter, try another pass; its type may have been
13335              deduced from a later argument than the one from which
13336              this parameter can be deduced.  */
13337           if (TREE_CODE (tparm) == PARM_DECL
13338               && uses_template_parms (TREE_TYPE (tparm))
13339               && !saw_undeduced++)
13340             goto again;
13341
13342           /* Core issue #226 (C++0x) [temp.deduct]:
13343
13344                If a template argument has not been deduced, its
13345                default template argument, if any, is used. 
13346
13347              When we are in C++98 mode, TREE_PURPOSE will either
13348              be NULL_TREE or ERROR_MARK_NODE, so we do not need
13349              to explicitly check cxx_dialect here.  */
13350           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
13351             {
13352               tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13353               tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
13354               arg = tsubst_template_arg (arg, targs, tf_none, NULL_TREE);
13355               arg = convert_template_argument (parm, arg, targs, tf_none,
13356                                                i, NULL_TREE);
13357               if (arg == error_mark_node)
13358                 return 1;
13359               else
13360                 {
13361                   TREE_VEC_ELT (targs, i) = arg;
13362                   continue;
13363                 }
13364             }
13365
13366           /* If the type parameter is a parameter pack, then it will
13367              be deduced to an empty parameter pack.  */
13368           if (template_parameter_pack_p (tparm))
13369             {
13370               tree arg;
13371
13372               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
13373                 {
13374                   arg = make_node (NONTYPE_ARGUMENT_PACK);
13375                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
13376                   TREE_CONSTANT (arg) = 1;
13377                 }
13378               else
13379                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
13380
13381               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
13382
13383               TREE_VEC_ELT (targs, i) = arg;
13384               continue;
13385             }
13386
13387           return 2;
13388         }
13389
13390   return 0;
13391 }
13392
13393 /* Subroutine of type_unification_real.  Args are like the variables
13394    at the call site.  ARG is an overloaded function (or template-id);
13395    we try deducing template args from each of the overloads, and if
13396    only one succeeds, we go with that.  Modifies TARGS and returns
13397    true on success.  */
13398
13399 static bool
13400 resolve_overloaded_unification (tree tparms,
13401                                 tree targs,
13402                                 tree parm,
13403                                 tree arg,
13404                                 unification_kind_t strict,
13405                                 int sub_strict)
13406 {
13407   tree tempargs = copy_node (targs);
13408   int good = 0;
13409   tree goodfn = NULL_TREE;
13410   bool addr_p;
13411
13412   if (TREE_CODE (arg) == ADDR_EXPR)
13413     {
13414       arg = TREE_OPERAND (arg, 0);
13415       addr_p = true;
13416     }
13417   else
13418     addr_p = false;
13419
13420   if (TREE_CODE (arg) == COMPONENT_REF)
13421     /* Handle `&x' where `x' is some static or non-static member
13422        function name.  */
13423     arg = TREE_OPERAND (arg, 1);
13424
13425   if (TREE_CODE (arg) == OFFSET_REF)
13426     arg = TREE_OPERAND (arg, 1);
13427
13428   /* Strip baselink information.  */
13429   if (BASELINK_P (arg))
13430     arg = BASELINK_FUNCTIONS (arg);
13431
13432   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
13433     {
13434       /* If we got some explicit template args, we need to plug them into
13435          the affected templates before we try to unify, in case the
13436          explicit args will completely resolve the templates in question.  */
13437
13438       tree expl_subargs = TREE_OPERAND (arg, 1);
13439       arg = TREE_OPERAND (arg, 0);
13440
13441       for (; arg; arg = OVL_NEXT (arg))
13442         {
13443           tree fn = OVL_CURRENT (arg);
13444           tree subargs, elem;
13445
13446           if (TREE_CODE (fn) != TEMPLATE_DECL)
13447             continue;
13448
13449           ++processing_template_decl;
13450           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13451                                   expl_subargs, /*check_ret=*/false);
13452           if (subargs)
13453             {
13454               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
13455               if (try_one_overload (tparms, targs, tempargs, parm,
13456                                     elem, strict, sub_strict, addr_p)
13457                   && (!goodfn || !decls_match (goodfn, elem)))
13458                 {
13459                   goodfn = elem;
13460                   ++good;
13461                 }
13462             }
13463           --processing_template_decl;
13464         }
13465     }
13466   else if (TREE_CODE (arg) != OVERLOAD
13467            && TREE_CODE (arg) != FUNCTION_DECL)
13468     /* If ARG is, for example, "(0, &f)" then its type will be unknown
13469        -- but the deduction does not succeed because the expression is
13470        not just the function on its own.  */
13471     return false;
13472   else
13473     for (; arg; arg = OVL_NEXT (arg))
13474       if (try_one_overload (tparms, targs, tempargs, parm,
13475                             TREE_TYPE (OVL_CURRENT (arg)),
13476                             strict, sub_strict, addr_p)
13477           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
13478         {
13479           goodfn = OVL_CURRENT (arg);
13480           ++good;
13481         }
13482
13483   /* [temp.deduct.type] A template-argument can be deduced from a pointer
13484      to function or pointer to member function argument if the set of
13485      overloaded functions does not contain function templates and at most
13486      one of a set of overloaded functions provides a unique match.
13487
13488      So if we found multiple possibilities, we return success but don't
13489      deduce anything.  */
13490
13491   if (good == 1)
13492     {
13493       int i = TREE_VEC_LENGTH (targs);
13494       for (; i--; )
13495         if (TREE_VEC_ELT (tempargs, i))
13496           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
13497     }
13498   if (good)
13499     return true;
13500
13501   return false;
13502 }
13503
13504 /* Core DR 115: In contexts where deduction is done and fails, or in
13505    contexts where deduction is not done, if a template argument list is
13506    specified and it, along with any default template arguments, identifies
13507    a single function template specialization, then the template-id is an
13508    lvalue for the function template specialization.  */
13509
13510 tree
13511 resolve_nondeduced_context (tree orig_expr)
13512 {
13513   tree expr, offset, baselink;
13514   bool addr;
13515
13516   if (!type_unknown_p (orig_expr))
13517     return orig_expr;
13518
13519   expr = orig_expr;
13520   addr = false;
13521   offset = NULL_TREE;
13522   baselink = NULL_TREE;
13523
13524   if (TREE_CODE (expr) == ADDR_EXPR)
13525     {
13526       expr = TREE_OPERAND (expr, 0);
13527       addr = true;
13528     }
13529   if (TREE_CODE (expr) == OFFSET_REF)
13530     {
13531       offset = expr;
13532       expr = TREE_OPERAND (expr, 1);
13533     }
13534   if (TREE_CODE (expr) == BASELINK)
13535     {
13536       baselink = expr;
13537       expr = BASELINK_FUNCTIONS (expr);
13538     }
13539
13540   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
13541     {
13542       int good = 0;
13543       tree goodfn = NULL_TREE;
13544
13545       /* If we got some explicit template args, we need to plug them into
13546          the affected templates before we try to unify, in case the
13547          explicit args will completely resolve the templates in question.  */
13548
13549       tree expl_subargs = TREE_OPERAND (expr, 1);
13550       tree arg = TREE_OPERAND (expr, 0);
13551       tree badfn = NULL_TREE;
13552       tree badargs = NULL_TREE;
13553
13554       for (; arg; arg = OVL_NEXT (arg))
13555         {
13556           tree fn = OVL_CURRENT (arg);
13557           tree subargs, elem;
13558
13559           if (TREE_CODE (fn) != TEMPLATE_DECL)
13560             continue;
13561
13562           ++processing_template_decl;
13563           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13564                                   expl_subargs, /*check_ret=*/false);
13565           if (subargs && !any_dependent_template_arguments_p (subargs))
13566             {
13567               elem = instantiate_template (fn, subargs, tf_none);
13568               if (elem == error_mark_node)
13569                 {
13570                   badfn = fn;
13571                   badargs = subargs;
13572                 }
13573               else if (elem && (!goodfn || !decls_match (goodfn, elem)))
13574                 {
13575                   goodfn = elem;
13576                   ++good;
13577                 }
13578             }
13579           --processing_template_decl;
13580         }
13581       if (good == 1)
13582         {
13583           expr = goodfn;
13584           if (baselink)
13585             expr = build_baselink (BASELINK_BINFO (baselink),
13586                                    BASELINK_ACCESS_BINFO (baselink),
13587                                    expr, BASELINK_OPTYPE (baselink));
13588           if (offset)
13589             expr = build2 (OFFSET_REF, TREE_TYPE (expr),
13590                            TREE_OPERAND (offset, 0), expr);
13591           if (addr)
13592             expr = build_address (expr);
13593           return expr;
13594         }
13595       else if (good == 0 && badargs)
13596         /* There were no good options and at least one bad one, so let the
13597            user know what the problem is.  */
13598         instantiate_template (badfn, badargs, tf_warning_or_error);
13599     }
13600   return orig_expr;
13601 }
13602
13603 /* Subroutine of resolve_overloaded_unification; does deduction for a single
13604    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
13605    different overloads deduce different arguments for a given parm.
13606    ADDR_P is true if the expression for which deduction is being
13607    performed was of the form "& fn" rather than simply "fn".
13608
13609    Returns 1 on success.  */
13610
13611 static int
13612 try_one_overload (tree tparms,
13613                   tree orig_targs,
13614                   tree targs,
13615                   tree parm,
13616                   tree arg,
13617                   unification_kind_t strict,
13618                   int sub_strict,
13619                   bool addr_p)
13620 {
13621   int nargs;
13622   tree tempargs;
13623   int i;
13624
13625   /* [temp.deduct.type] A template-argument can be deduced from a pointer
13626      to function or pointer to member function argument if the set of
13627      overloaded functions does not contain function templates and at most
13628      one of a set of overloaded functions provides a unique match.
13629
13630      So if this is a template, just return success.  */
13631
13632   if (uses_template_parms (arg))
13633     return 1;
13634
13635   if (TREE_CODE (arg) == METHOD_TYPE)
13636     arg = build_ptrmemfunc_type (build_pointer_type (arg));
13637   else if (addr_p)
13638     arg = build_pointer_type (arg);
13639
13640   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
13641
13642   /* We don't copy orig_targs for this because if we have already deduced
13643      some template args from previous args, unify would complain when we
13644      try to deduce a template parameter for the same argument, even though
13645      there isn't really a conflict.  */
13646   nargs = TREE_VEC_LENGTH (targs);
13647   tempargs = make_tree_vec (nargs);
13648
13649   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
13650     return 0;
13651
13652   /* First make sure we didn't deduce anything that conflicts with
13653      explicitly specified args.  */
13654   for (i = nargs; i--; )
13655     {
13656       tree elt = TREE_VEC_ELT (tempargs, i);
13657       tree oldelt = TREE_VEC_ELT (orig_targs, i);
13658
13659       if (!elt)
13660         /*NOP*/;
13661       else if (uses_template_parms (elt))
13662         /* Since we're unifying against ourselves, we will fill in
13663            template args used in the function parm list with our own
13664            template parms.  Discard them.  */
13665         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
13666       else if (oldelt && !template_args_equal (oldelt, elt))
13667         return 0;
13668     }
13669
13670   for (i = nargs; i--; )
13671     {
13672       tree elt = TREE_VEC_ELT (tempargs, i);
13673
13674       if (elt)
13675         TREE_VEC_ELT (targs, i) = elt;
13676     }
13677
13678   return 1;
13679 }
13680
13681 /* PARM is a template class (perhaps with unbound template
13682    parameters).  ARG is a fully instantiated type.  If ARG can be
13683    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
13684    TARGS are as for unify.  */
13685
13686 static tree
13687 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
13688 {
13689   tree copy_of_targs;
13690
13691   if (!CLASSTYPE_TEMPLATE_INFO (arg)
13692       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
13693           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
13694     return NULL_TREE;
13695
13696   /* We need to make a new template argument vector for the call to
13697      unify.  If we used TARGS, we'd clutter it up with the result of
13698      the attempted unification, even if this class didn't work out.
13699      We also don't want to commit ourselves to all the unifications
13700      we've already done, since unification is supposed to be done on
13701      an argument-by-argument basis.  In other words, consider the
13702      following pathological case:
13703
13704        template <int I, int J, int K>
13705        struct S {};
13706
13707        template <int I, int J>
13708        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
13709
13710        template <int I, int J, int K>
13711        void f(S<I, J, K>, S<I, I, I>);
13712
13713        void g() {
13714          S<0, 0, 0> s0;
13715          S<0, 1, 2> s2;
13716
13717          f(s0, s2);
13718        }
13719
13720      Now, by the time we consider the unification involving `s2', we
13721      already know that we must have `f<0, 0, 0>'.  But, even though
13722      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
13723      because there are two ways to unify base classes of S<0, 1, 2>
13724      with S<I, I, I>.  If we kept the already deduced knowledge, we
13725      would reject the possibility I=1.  */
13726   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
13727
13728   /* If unification failed, we're done.  */
13729   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
13730              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
13731     return NULL_TREE;
13732
13733   return arg;
13734 }
13735
13736 /* Given a template type PARM and a class type ARG, find the unique
13737    base type in ARG that is an instance of PARM.  We do not examine
13738    ARG itself; only its base-classes.  If there is not exactly one
13739    appropriate base class, return NULL_TREE.  PARM may be the type of
13740    a partial specialization, as well as a plain template type.  Used
13741    by unify.  */
13742
13743 static tree
13744 get_template_base (tree tparms, tree targs, tree parm, tree arg)
13745 {
13746   tree rval = NULL_TREE;
13747   tree binfo;
13748
13749   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
13750
13751   binfo = TYPE_BINFO (complete_type (arg));
13752   if (!binfo)
13753     /* The type could not be completed.  */
13754     return NULL_TREE;
13755
13756   /* Walk in inheritance graph order.  The search order is not
13757      important, and this avoids multiple walks of virtual bases.  */
13758   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
13759     {
13760       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
13761
13762       if (r)
13763         {
13764           /* If there is more than one satisfactory baseclass, then:
13765
13766                [temp.deduct.call]
13767
13768               If they yield more than one possible deduced A, the type
13769               deduction fails.
13770
13771              applies.  */
13772           if (rval && !same_type_p (r, rval))
13773             return NULL_TREE;
13774
13775           rval = r;
13776         }
13777     }
13778
13779   return rval;
13780 }
13781
13782 /* Returns the level of DECL, which declares a template parameter.  */
13783
13784 static int
13785 template_decl_level (tree decl)
13786 {
13787   switch (TREE_CODE (decl))
13788     {
13789     case TYPE_DECL:
13790     case TEMPLATE_DECL:
13791       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
13792
13793     case PARM_DECL:
13794       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
13795
13796     default:
13797       gcc_unreachable ();
13798     }
13799   return 0;
13800 }
13801
13802 /* Decide whether ARG can be unified with PARM, considering only the
13803    cv-qualifiers of each type, given STRICT as documented for unify.
13804    Returns nonzero iff the unification is OK on that basis.  */
13805
13806 static int
13807 check_cv_quals_for_unify (int strict, tree arg, tree parm)
13808 {
13809   int arg_quals = cp_type_quals (arg);
13810   int parm_quals = cp_type_quals (parm);
13811
13812   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13813       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
13814     {
13815       /*  Although a CVR qualifier is ignored when being applied to a
13816           substituted template parameter ([8.3.2]/1 for example), that
13817           does not apply during deduction [14.8.2.4]/1, (even though
13818           that is not explicitly mentioned, [14.8.2.4]/9 indicates
13819           this).  Except when we're allowing additional CV qualifiers
13820           at the outer level [14.8.2.1]/3,1st bullet.  */
13821       if ((TREE_CODE (arg) == REFERENCE_TYPE
13822            || TREE_CODE (arg) == FUNCTION_TYPE
13823            || TREE_CODE (arg) == METHOD_TYPE)
13824           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
13825         return 0;
13826
13827       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
13828           && (parm_quals & TYPE_QUAL_RESTRICT))
13829         return 0;
13830     }
13831
13832   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
13833       && (arg_quals & parm_quals) != parm_quals)
13834     return 0;
13835
13836   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
13837       && (parm_quals & arg_quals) != arg_quals)
13838     return 0;
13839
13840   return 1;
13841 }
13842
13843 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
13844 void 
13845 template_parm_level_and_index (tree parm, int* level, int* index)
13846 {
13847   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13848       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
13849       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
13850     {
13851       *index = TEMPLATE_TYPE_IDX (parm);
13852       *level = TEMPLATE_TYPE_LEVEL (parm);
13853     }
13854   else
13855     {
13856       *index = TEMPLATE_PARM_IDX (parm);
13857       *level = TEMPLATE_PARM_LEVEL (parm);
13858     }
13859 }
13860
13861 /* Unifies the remaining arguments in PACKED_ARGS with the pack
13862    expansion at the end of PACKED_PARMS. Returns 0 if the type
13863    deduction succeeds, 1 otherwise. STRICT is the same as in
13864    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
13865    call argument list. We'll need to adjust the arguments to make them
13866    types. SUBR tells us if this is from a recursive call to
13867    type_unification_real.  */
13868 int
13869 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
13870                       tree packed_args, int strict, bool call_args_p,
13871                       bool subr)
13872 {
13873   tree parm 
13874     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
13875   tree pattern = PACK_EXPANSION_PATTERN (parm);
13876   tree pack, packs = NULL_TREE;
13877   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
13878   int len = TREE_VEC_LENGTH (packed_args);
13879
13880   /* Determine the parameter packs we will be deducing from the
13881      pattern, and record their current deductions.  */
13882   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
13883        pack; pack = TREE_CHAIN (pack))
13884     {
13885       tree parm_pack = TREE_VALUE (pack);
13886       int idx, level;
13887
13888       /* Determine the index and level of this parameter pack.  */
13889       template_parm_level_and_index (parm_pack, &level, &idx);
13890
13891       /* Keep track of the parameter packs and their corresponding
13892          argument packs.  */
13893       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
13894       TREE_TYPE (packs) = make_tree_vec (len - start);
13895     }
13896   
13897   /* Loop through all of the arguments that have not yet been
13898      unified and unify each with the pattern.  */
13899   for (i = start; i < len; i++)
13900     {
13901       tree parm = pattern;
13902
13903       /* For each parameter pack, clear out the deduced value so that
13904          we can deduce it again.  */
13905       for (pack = packs; pack; pack = TREE_CHAIN (pack))
13906         {
13907           int idx, level;
13908           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13909
13910           TMPL_ARG (targs, level, idx) = NULL_TREE;
13911         }
13912
13913       /* Unify the pattern with the current argument.  */
13914       {
13915         tree arg = TREE_VEC_ELT (packed_args, i);
13916         tree arg_expr = NULL_TREE;
13917         int arg_strict = strict;
13918         bool skip_arg_p = false;
13919
13920         if (call_args_p)
13921           {
13922             int sub_strict;
13923
13924             /* This mirrors what we do in type_unification_real.  */
13925             switch (strict)
13926               {
13927               case DEDUCE_CALL:
13928                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
13929                               | UNIFY_ALLOW_MORE_CV_QUAL
13930                               | UNIFY_ALLOW_DERIVED);
13931                 break;
13932                 
13933               case DEDUCE_CONV:
13934                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
13935                 break;
13936                 
13937               case DEDUCE_EXACT:
13938                 sub_strict = UNIFY_ALLOW_NONE;
13939                 break;
13940                 
13941               default:
13942                 gcc_unreachable ();
13943               }
13944
13945             if (!TYPE_P (arg))
13946               {
13947                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
13948                 if (type_unknown_p (arg))
13949                   {
13950                     /* [temp.deduct.type] A template-argument can be
13951                        deduced from a pointer to function or pointer
13952                        to member function argument if the set of
13953                        overloaded functions does not contain function
13954                        templates and at most one of a set of
13955                        overloaded functions provides a unique
13956                        match.  */
13957
13958                     if (resolve_overloaded_unification
13959                         (tparms, targs, parm, arg,
13960                          (unification_kind_t) strict,
13961                          sub_strict)
13962                         != 0)
13963                       return 1;
13964                     skip_arg_p = true;
13965                   }
13966
13967                 if (!skip_arg_p)
13968                   {
13969                     arg_expr = arg;
13970                     arg = unlowered_expr_type (arg);
13971                     if (arg == error_mark_node)
13972                       return 1;
13973                   }
13974               }
13975       
13976             arg_strict = sub_strict;
13977
13978             if (!subr)
13979               arg_strict |= 
13980                 maybe_adjust_types_for_deduction ((unification_kind_t) strict,
13981                                                   &parm, &arg, arg_expr);
13982           }
13983
13984         if (!skip_arg_p)
13985           {
13986             if (unify (tparms, targs, parm, arg, arg_strict))
13987               return 1;
13988           }
13989       }
13990
13991       /* For each parameter pack, collect the deduced value.  */
13992       for (pack = packs; pack; pack = TREE_CHAIN (pack))
13993         {
13994           int idx, level;
13995           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
13996
13997           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
13998             TMPL_ARG (targs, level, idx);
13999         }
14000     }
14001
14002   /* Verify that the results of unification with the parameter packs
14003      produce results consistent with what we've seen before, and make
14004      the deduced argument packs available.  */
14005   for (pack = packs; pack; pack = TREE_CHAIN (pack))
14006     {
14007       tree old_pack = TREE_VALUE (pack);
14008       tree new_args = TREE_TYPE (pack);
14009       int i, len = TREE_VEC_LENGTH (new_args);
14010       bool nondeduced_p = false;
14011
14012       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
14013          actually deduce anything.  */
14014       for (i = 0; i < len && !nondeduced_p; ++i)
14015         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
14016           nondeduced_p = true;
14017       if (nondeduced_p)
14018         continue;
14019
14020       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
14021         {
14022           /* Prepend the explicit arguments onto NEW_ARGS.  */
14023           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14024           tree old_args = new_args;
14025           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
14026           int len = explicit_len + TREE_VEC_LENGTH (old_args);
14027
14028           /* Copy the explicit arguments.  */
14029           new_args = make_tree_vec (len);
14030           for (i = 0; i < explicit_len; i++)
14031             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
14032
14033           /* Copy the deduced arguments.  */
14034           for (; i < len; i++)
14035             TREE_VEC_ELT (new_args, i) =
14036               TREE_VEC_ELT (old_args, i - explicit_len);
14037         }
14038
14039       if (!old_pack)
14040         {
14041           tree result;
14042           int idx, level;
14043           
14044           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14045
14046           /* Build the deduced *_ARGUMENT_PACK.  */
14047           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
14048             {
14049               result = make_node (NONTYPE_ARGUMENT_PACK);
14050               TREE_TYPE (result) = 
14051                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
14052               TREE_CONSTANT (result) = 1;
14053             }
14054           else
14055             result = cxx_make_type (TYPE_ARGUMENT_PACK);
14056
14057           SET_ARGUMENT_PACK_ARGS (result, new_args);
14058
14059           /* Note the deduced argument packs for this parameter
14060              pack.  */
14061           TMPL_ARG (targs, level, idx) = result;
14062         }
14063       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
14064                && (ARGUMENT_PACK_ARGS (old_pack) 
14065                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
14066         {
14067           /* We only had the explicitly-provided arguments before, but
14068              now we have a complete set of arguments.  */
14069           int idx, level;
14070           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14071           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14072
14073           /* Keep the original deduced argument pack.  */
14074           TMPL_ARG (targs, level, idx) = old_pack;
14075
14076           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
14077           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
14078           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
14079         }
14080       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
14081                                     new_args))
14082         /* Inconsistent unification of this parameter pack.  */
14083         return 1;
14084       else
14085         {
14086           int idx, level;
14087           
14088           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14089
14090           /* Keep the original deduced argument pack.  */
14091           TMPL_ARG (targs, level, idx) = old_pack;
14092         }
14093     }
14094
14095   return 0;
14096 }
14097
14098 /* Deduce the value of template parameters.  TPARMS is the (innermost)
14099    set of template parameters to a template.  TARGS is the bindings
14100    for those template parameters, as determined thus far; TARGS may
14101    include template arguments for outer levels of template parameters
14102    as well.  PARM is a parameter to a template function, or a
14103    subcomponent of that parameter; ARG is the corresponding argument.
14104    This function attempts to match PARM with ARG in a manner
14105    consistent with the existing assignments in TARGS.  If more values
14106    are deduced, then TARGS is updated.
14107
14108    Returns 0 if the type deduction succeeds, 1 otherwise.  The
14109    parameter STRICT is a bitwise or of the following flags:
14110
14111      UNIFY_ALLOW_NONE:
14112        Require an exact match between PARM and ARG.
14113      UNIFY_ALLOW_MORE_CV_QUAL:
14114        Allow the deduced ARG to be more cv-qualified (by qualification
14115        conversion) than ARG.
14116      UNIFY_ALLOW_LESS_CV_QUAL:
14117        Allow the deduced ARG to be less cv-qualified than ARG.
14118      UNIFY_ALLOW_DERIVED:
14119        Allow the deduced ARG to be a template base class of ARG,
14120        or a pointer to a template base class of the type pointed to by
14121        ARG.
14122      UNIFY_ALLOW_INTEGER:
14123        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
14124        case for more information.
14125      UNIFY_ALLOW_OUTER_LEVEL:
14126        This is the outermost level of a deduction. Used to determine validity
14127        of qualification conversions. A valid qualification conversion must
14128        have const qualified pointers leading up to the inner type which
14129        requires additional CV quals, except at the outer level, where const
14130        is not required [conv.qual]. It would be normal to set this flag in
14131        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
14132      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
14133        This is the outermost level of a deduction, and PARM can be more CV
14134        qualified at this point.
14135      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
14136        This is the outermost level of a deduction, and PARM can be less CV
14137        qualified at this point.  */
14138
14139 static int
14140 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
14141 {
14142   int idx;
14143   tree targ;
14144   tree tparm;
14145   int strict_in = strict;
14146
14147   /* I don't think this will do the right thing with respect to types.
14148      But the only case I've seen it in so far has been array bounds, where
14149      signedness is the only information lost, and I think that will be
14150      okay.  */
14151   while (TREE_CODE (parm) == NOP_EXPR)
14152     parm = TREE_OPERAND (parm, 0);
14153
14154   if (arg == error_mark_node)
14155     return 1;
14156   if (arg == unknown_type_node
14157       || arg == init_list_type_node)
14158     /* We can't deduce anything from this, but we might get all the
14159        template args from other function args.  */
14160     return 0;
14161
14162   /* If PARM uses template parameters, then we can't bail out here,
14163      even if ARG == PARM, since we won't record unifications for the
14164      template parameters.  We might need them if we're trying to
14165      figure out which of two things is more specialized.  */
14166   if (arg == parm && !uses_template_parms (parm))
14167     return 0;
14168
14169   /* Handle init lists early, so the rest of the function can assume
14170      we're dealing with a type. */
14171   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
14172     {
14173       tree elt, elttype;
14174       unsigned i;
14175       tree orig_parm = parm;
14176
14177       /* Replace T with std::initializer_list<T> for deduction.  */
14178       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14179           && flag_deduce_init_list)
14180         parm = listify (parm);
14181
14182       if (!is_std_init_list (parm))
14183         /* We can only deduce from an initializer list argument if the
14184            parameter is std::initializer_list; otherwise this is a
14185            non-deduced context. */
14186         return 0;
14187
14188       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
14189
14190       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
14191         {
14192           int elt_strict = strict;
14193           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
14194             {
14195               tree type = TREE_TYPE (elt);
14196               /* It should only be possible to get here for a call.  */
14197               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
14198               elt_strict |= maybe_adjust_types_for_deduction
14199                 (DEDUCE_CALL, &elttype, &type, elt);
14200               elt = type;
14201             }
14202
14203           if (unify (tparms, targs, elttype, elt, elt_strict))
14204             return 1;
14205         }
14206
14207       /* If the std::initializer_list<T> deduction worked, replace the
14208          deduced A with std::initializer_list<A>.  */
14209       if (orig_parm != parm)
14210         {
14211           idx = TEMPLATE_TYPE_IDX (orig_parm);
14212           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14213           targ = listify (targ);
14214           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
14215         }
14216       return 0;
14217     }
14218
14219   /* Immediately reject some pairs that won't unify because of
14220      cv-qualification mismatches.  */
14221   if (TREE_CODE (arg) == TREE_CODE (parm)
14222       && TYPE_P (arg)
14223       /* It is the elements of the array which hold the cv quals of an array
14224          type, and the elements might be template type parms. We'll check
14225          when we recurse.  */
14226       && TREE_CODE (arg) != ARRAY_TYPE
14227       /* We check the cv-qualifiers when unifying with template type
14228          parameters below.  We want to allow ARG `const T' to unify with
14229          PARM `T' for example, when computing which of two templates
14230          is more specialized, for example.  */
14231       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
14232       && !check_cv_quals_for_unify (strict_in, arg, parm))
14233     return 1;
14234
14235   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
14236       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
14237     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
14238   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
14239   strict &= ~UNIFY_ALLOW_DERIVED;
14240   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
14241   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
14242
14243   switch (TREE_CODE (parm))
14244     {
14245     case TYPENAME_TYPE:
14246     case SCOPE_REF:
14247     case UNBOUND_CLASS_TEMPLATE:
14248       /* In a type which contains a nested-name-specifier, template
14249          argument values cannot be deduced for template parameters used
14250          within the nested-name-specifier.  */
14251       return 0;
14252
14253     case TEMPLATE_TYPE_PARM:
14254     case TEMPLATE_TEMPLATE_PARM:
14255     case BOUND_TEMPLATE_TEMPLATE_PARM:
14256       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14257       if (tparm == error_mark_node)
14258         return 1;
14259
14260       if (TEMPLATE_TYPE_LEVEL (parm)
14261           != template_decl_level (tparm))
14262         /* The PARM is not one we're trying to unify.  Just check
14263            to see if it matches ARG.  */
14264         return (TREE_CODE (arg) == TREE_CODE (parm)
14265                 && same_type_p (parm, arg)) ? 0 : 1;
14266       idx = TEMPLATE_TYPE_IDX (parm);
14267       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14268       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
14269
14270       /* Check for mixed types and values.  */
14271       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14272            && TREE_CODE (tparm) != TYPE_DECL)
14273           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14274               && TREE_CODE (tparm) != TEMPLATE_DECL))
14275         return 1;
14276
14277       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14278         {
14279           /* ARG must be constructed from a template class or a template
14280              template parameter.  */
14281           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
14282               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
14283             return 1;
14284
14285           {
14286             tree parmvec = TYPE_TI_ARGS (parm);
14287             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
14288             tree parm_parms 
14289               = DECL_INNERMOST_TEMPLATE_PARMS
14290                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
14291             int i, len;
14292             int parm_variadic_p = 0;
14293
14294             /* The resolution to DR150 makes clear that default
14295                arguments for an N-argument may not be used to bind T
14296                to a template template parameter with fewer than N
14297                parameters.  It is not safe to permit the binding of
14298                default arguments as an extension, as that may change
14299                the meaning of a conforming program.  Consider:
14300
14301                   struct Dense { static const unsigned int dim = 1; };
14302
14303                   template <template <typename> class View,
14304                             typename Block>
14305                   void operator+(float, View<Block> const&);
14306
14307                   template <typename Block,
14308                             unsigned int Dim = Block::dim>
14309                   struct Lvalue_proxy { operator float() const; };
14310
14311                   void
14312                   test_1d (void) {
14313                     Lvalue_proxy<Dense> p;
14314                     float b;
14315                     b + p;
14316                   }
14317
14318               Here, if Lvalue_proxy is permitted to bind to View, then
14319               the global operator+ will be used; if they are not, the
14320               Lvalue_proxy will be converted to float.  */
14321             if (coerce_template_parms (parm_parms,
14322                                        argvec,
14323                                        TYPE_TI_TEMPLATE (parm),
14324                                        tf_none,
14325                                        /*require_all_args=*/true,
14326                                        /*use_default_args=*/false)
14327                 == error_mark_node)
14328               return 1;
14329
14330             /* Deduce arguments T, i from TT<T> or TT<i>.
14331                We check each element of PARMVEC and ARGVEC individually
14332                rather than the whole TREE_VEC since they can have
14333                different number of elements.  */
14334
14335             parmvec = expand_template_argument_pack (parmvec);
14336             argvec = expand_template_argument_pack (argvec);
14337
14338             len = TREE_VEC_LENGTH (parmvec);
14339
14340             /* Check if the parameters end in a pack, making them
14341                variadic.  */
14342             if (len > 0
14343                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
14344               parm_variadic_p = 1;
14345             
14346             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
14347               return 1;
14348
14349              for (i = 0; i < len - parm_variadic_p; ++i)
14350               {
14351                 if (unify (tparms, targs,
14352                            TREE_VEC_ELT (parmvec, i),
14353                            TREE_VEC_ELT (argvec, i),
14354                            UNIFY_ALLOW_NONE))
14355                   return 1;
14356               }
14357
14358             if (parm_variadic_p
14359                 && unify_pack_expansion (tparms, targs,
14360                                          parmvec, argvec,
14361                                          UNIFY_ALLOW_NONE,
14362                                          /*call_args_p=*/false,
14363                                          /*subr=*/false))
14364               return 1;
14365           }
14366           arg = TYPE_TI_TEMPLATE (arg);
14367
14368           /* Fall through to deduce template name.  */
14369         }
14370
14371       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14372           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14373         {
14374           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
14375
14376           /* Simple cases: Value already set, does match or doesn't.  */
14377           if (targ != NULL_TREE && template_args_equal (targ, arg))
14378             return 0;
14379           else if (targ)
14380             return 1;
14381         }
14382       else
14383         {
14384           /* If PARM is `const T' and ARG is only `int', we don't have
14385              a match unless we are allowing additional qualification.
14386              If ARG is `const int' and PARM is just `T' that's OK;
14387              that binds `const int' to `T'.  */
14388           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
14389                                          arg, parm))
14390             return 1;
14391
14392           /* Consider the case where ARG is `const volatile int' and
14393              PARM is `const T'.  Then, T should be `volatile int'.  */
14394           arg = cp_build_qualified_type_real
14395             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
14396           if (arg == error_mark_node)
14397             return 1;
14398
14399           /* Simple cases: Value already set, does match or doesn't.  */
14400           if (targ != NULL_TREE && same_type_p (targ, arg))
14401             return 0;
14402           else if (targ)
14403             return 1;
14404
14405           /* Make sure that ARG is not a variable-sized array.  (Note
14406              that were talking about variable-sized arrays (like
14407              `int[n]'), rather than arrays of unknown size (like
14408              `int[]').)  We'll get very confused by such a type since
14409              the bound of the array will not be computable in an
14410              instantiation.  Besides, such types are not allowed in
14411              ISO C++, so we can do as we please here.  */
14412           if (variably_modified_type_p (arg, NULL_TREE))
14413             return 1;
14414
14415           /* Strip typedefs as in convert_template_argument.  */
14416           arg = strip_typedefs (arg);
14417         }
14418
14419       /* If ARG is a parameter pack or an expansion, we cannot unify
14420          against it unless PARM is also a parameter pack.  */
14421       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
14422           && !template_parameter_pack_p (parm))
14423         return 1;
14424
14425       /* If the argument deduction results is a METHOD_TYPE,
14426          then there is a problem.
14427          METHOD_TYPE doesn't map to any real C++ type the result of
14428          the deduction can not be of that type.  */
14429       if (TREE_CODE (arg) == METHOD_TYPE)
14430         return 1;
14431
14432       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
14433       return 0;
14434
14435     case TEMPLATE_PARM_INDEX:
14436       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14437       if (tparm == error_mark_node)
14438         return 1;
14439
14440       if (TEMPLATE_PARM_LEVEL (parm)
14441           != template_decl_level (tparm))
14442         /* The PARM is not one we're trying to unify.  Just check
14443            to see if it matches ARG.  */
14444         return !(TREE_CODE (arg) == TREE_CODE (parm)
14445                  && cp_tree_equal (parm, arg));
14446
14447       idx = TEMPLATE_PARM_IDX (parm);
14448       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14449
14450       if (targ)
14451         return !cp_tree_equal (targ, arg);
14452
14453       /* [temp.deduct.type] If, in the declaration of a function template
14454          with a non-type template-parameter, the non-type
14455          template-parameter is used in an expression in the function
14456          parameter-list and, if the corresponding template-argument is
14457          deduced, the template-argument type shall match the type of the
14458          template-parameter exactly, except that a template-argument
14459          deduced from an array bound may be of any integral type.
14460          The non-type parameter might use already deduced type parameters.  */
14461       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
14462       if (!TREE_TYPE (arg))
14463         /* Template-parameter dependent expression.  Just accept it for now.
14464            It will later be processed in convert_template_argument.  */
14465         ;
14466       else if (same_type_p (TREE_TYPE (arg), tparm))
14467         /* OK */;
14468       else if ((strict & UNIFY_ALLOW_INTEGER)
14469                && (TREE_CODE (tparm) == INTEGER_TYPE
14470                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
14471         /* Convert the ARG to the type of PARM; the deduced non-type
14472            template argument must exactly match the types of the
14473            corresponding parameter.  */
14474         arg = fold (build_nop (tparm, arg));
14475       else if (uses_template_parms (tparm))
14476         /* We haven't deduced the type of this parameter yet.  Try again
14477            later.  */
14478         return 0;
14479       else
14480         return 1;
14481
14482       /* If ARG is a parameter pack or an expansion, we cannot unify
14483          against it unless PARM is also a parameter pack.  */
14484       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
14485           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
14486         return 1;
14487
14488       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
14489       return 0;
14490
14491     case PTRMEM_CST:
14492      {
14493         /* A pointer-to-member constant can be unified only with
14494          another constant.  */
14495       if (TREE_CODE (arg) != PTRMEM_CST)
14496         return 1;
14497
14498       /* Just unify the class member. It would be useless (and possibly
14499          wrong, depending on the strict flags) to unify also
14500          PTRMEM_CST_CLASS, because we want to be sure that both parm and
14501          arg refer to the same variable, even if through different
14502          classes. For instance:
14503
14504          struct A { int x; };
14505          struct B : A { };
14506
14507          Unification of &A::x and &B::x must succeed.  */
14508       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
14509                     PTRMEM_CST_MEMBER (arg), strict);
14510      }
14511
14512     case POINTER_TYPE:
14513       {
14514         if (TREE_CODE (arg) != POINTER_TYPE)
14515           return 1;
14516
14517         /* [temp.deduct.call]
14518
14519            A can be another pointer or pointer to member type that can
14520            be converted to the deduced A via a qualification
14521            conversion (_conv.qual_).
14522
14523            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
14524            This will allow for additional cv-qualification of the
14525            pointed-to types if appropriate.  */
14526
14527         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
14528           /* The derived-to-base conversion only persists through one
14529              level of pointers.  */
14530           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
14531
14532         return unify (tparms, targs, TREE_TYPE (parm),
14533                       TREE_TYPE (arg), strict);
14534       }
14535
14536     case REFERENCE_TYPE:
14537       if (TREE_CODE (arg) != REFERENCE_TYPE)
14538         return 1;
14539       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14540                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
14541
14542     case ARRAY_TYPE:
14543       if (TREE_CODE (arg) != ARRAY_TYPE)
14544         return 1;
14545       if ((TYPE_DOMAIN (parm) == NULL_TREE)
14546           != (TYPE_DOMAIN (arg) == NULL_TREE))
14547         return 1;
14548       if (TYPE_DOMAIN (parm) != NULL_TREE)
14549         {
14550           tree parm_max;
14551           tree arg_max;
14552           bool parm_cst;
14553           bool arg_cst;
14554
14555           /* Our representation of array types uses "N - 1" as the
14556              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
14557              not an integer constant.  We cannot unify arbitrarily
14558              complex expressions, so we eliminate the MINUS_EXPRs
14559              here.  */
14560           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
14561           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
14562           if (!parm_cst)
14563             {
14564               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
14565               parm_max = TREE_OPERAND (parm_max, 0);
14566             }
14567           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
14568           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
14569           if (!arg_cst)
14570             {
14571               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
14572                  trying to unify the type of a variable with the type
14573                  of a template parameter.  For example:
14574
14575                    template <unsigned int N>
14576                    void f (char (&) [N]);
14577                    int g(); 
14578                    void h(int i) {
14579                      char a[g(i)];
14580                      f(a); 
14581                    }
14582
14583                 Here, the type of the ARG will be "int [g(i)]", and
14584                 may be a SAVE_EXPR, etc.  */
14585               if (TREE_CODE (arg_max) != MINUS_EXPR)
14586                 return 1;
14587               arg_max = TREE_OPERAND (arg_max, 0);
14588             }
14589
14590           /* If only one of the bounds used a MINUS_EXPR, compensate
14591              by adding one to the other bound.  */
14592           if (parm_cst && !arg_cst)
14593             parm_max = fold_build2_loc (input_location, PLUS_EXPR,
14594                                     integer_type_node,
14595                                     parm_max,
14596                                     integer_one_node);
14597           else if (arg_cst && !parm_cst)
14598             arg_max = fold_build2_loc (input_location, PLUS_EXPR,
14599                                    integer_type_node,
14600                                    arg_max,
14601                                    integer_one_node);
14602
14603           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
14604             return 1;
14605         }
14606       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14607                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
14608
14609     case REAL_TYPE:
14610     case COMPLEX_TYPE:
14611     case VECTOR_TYPE:
14612     case INTEGER_TYPE:
14613     case BOOLEAN_TYPE:
14614     case ENUMERAL_TYPE:
14615     case VOID_TYPE:
14616       if (TREE_CODE (arg) != TREE_CODE (parm))
14617         return 1;
14618
14619       /* We have already checked cv-qualification at the top of the
14620          function.  */
14621       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
14622         return 1;
14623
14624       /* As far as unification is concerned, this wins.  Later checks
14625          will invalidate it if necessary.  */
14626       return 0;
14627
14628       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
14629       /* Type INTEGER_CST can come from ordinary constant template args.  */
14630     case INTEGER_CST:
14631       while (TREE_CODE (arg) == NOP_EXPR)
14632         arg = TREE_OPERAND (arg, 0);
14633
14634       if (TREE_CODE (arg) != INTEGER_CST)
14635         return 1;
14636       return !tree_int_cst_equal (parm, arg);
14637
14638     case TREE_VEC:
14639       {
14640         int i;
14641         if (TREE_CODE (arg) != TREE_VEC)
14642           return 1;
14643         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
14644           return 1;
14645         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
14646           if (unify (tparms, targs,
14647                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
14648                      UNIFY_ALLOW_NONE))
14649             return 1;
14650         return 0;
14651       }
14652
14653     case RECORD_TYPE:
14654     case UNION_TYPE:
14655       if (TREE_CODE (arg) != TREE_CODE (parm))
14656         return 1;
14657
14658       if (TYPE_PTRMEMFUNC_P (parm))
14659         {
14660           if (!TYPE_PTRMEMFUNC_P (arg))
14661             return 1;
14662
14663           return unify (tparms, targs,
14664                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
14665                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
14666                         strict);
14667         }
14668
14669       if (CLASSTYPE_TEMPLATE_INFO (parm))
14670         {
14671           tree t = NULL_TREE;
14672
14673           if (strict_in & UNIFY_ALLOW_DERIVED)
14674             {
14675               /* First, we try to unify the PARM and ARG directly.  */
14676               t = try_class_unification (tparms, targs,
14677                                          parm, arg);
14678
14679               if (!t)
14680                 {
14681                   /* Fallback to the special case allowed in
14682                      [temp.deduct.call]:
14683
14684                        If P is a class, and P has the form
14685                        template-id, then A can be a derived class of
14686                        the deduced A.  Likewise, if P is a pointer to
14687                        a class of the form template-id, A can be a
14688                        pointer to a derived class pointed to by the
14689                        deduced A.  */
14690                   t = get_template_base (tparms, targs, parm, arg);
14691
14692                   if (!t)
14693                     return 1;
14694                 }
14695             }
14696           else if (CLASSTYPE_TEMPLATE_INFO (arg)
14697                    && (CLASSTYPE_TI_TEMPLATE (parm)
14698                        == CLASSTYPE_TI_TEMPLATE (arg)))
14699             /* Perhaps PARM is something like S<U> and ARG is S<int>.
14700                Then, we should unify `int' and `U'.  */
14701             t = arg;
14702           else
14703             /* There's no chance of unification succeeding.  */
14704             return 1;
14705
14706           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
14707                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
14708         }
14709       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
14710         return 1;
14711       return 0;
14712
14713     case METHOD_TYPE:
14714     case FUNCTION_TYPE:
14715       {
14716         unsigned int nargs;
14717         tree *args;
14718         tree a;
14719         unsigned int i;
14720
14721         if (TREE_CODE (arg) != TREE_CODE (parm))
14722           return 1;
14723
14724         /* CV qualifications for methods can never be deduced, they must
14725            match exactly.  We need to check them explicitly here,
14726            because type_unification_real treats them as any other
14727            cv-qualified parameter.  */
14728         if (TREE_CODE (parm) == METHOD_TYPE
14729             && (!check_cv_quals_for_unify
14730                 (UNIFY_ALLOW_NONE,
14731                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
14732                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
14733           return 1;
14734
14735         if (unify (tparms, targs, TREE_TYPE (parm),
14736                    TREE_TYPE (arg), UNIFY_ALLOW_NONE))
14737           return 1;
14738
14739         nargs = list_length (TYPE_ARG_TYPES (arg));
14740         args = XALLOCAVEC (tree, nargs);
14741         for (a = TYPE_ARG_TYPES (arg), i = 0;
14742              a != NULL_TREE && a != void_list_node;
14743              a = TREE_CHAIN (a), ++i)
14744           args[i] = TREE_VALUE (a);
14745         nargs = i;
14746
14747         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
14748                                       args, nargs, 1, DEDUCE_EXACT,
14749                                       LOOKUP_NORMAL);
14750       }
14751
14752     case OFFSET_TYPE:
14753       /* Unify a pointer to member with a pointer to member function, which
14754          deduces the type of the member as a function type. */
14755       if (TYPE_PTRMEMFUNC_P (arg))
14756         {
14757           tree method_type;
14758           tree fntype;
14759           cp_cv_quals cv_quals;
14760
14761           /* Check top-level cv qualifiers */
14762           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
14763             return 1;
14764
14765           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
14766                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
14767             return 1;
14768
14769           /* Determine the type of the function we are unifying against. */
14770           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
14771           fntype =
14772             build_function_type (TREE_TYPE (method_type),
14773                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
14774
14775           /* Extract the cv-qualifiers of the member function from the
14776              implicit object parameter and place them on the function
14777              type to be restored later. */
14778           cv_quals =
14779             cp_type_quals(TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (method_type))));
14780           fntype = build_qualified_type (fntype, cv_quals);
14781           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
14782         }
14783
14784       if (TREE_CODE (arg) != OFFSET_TYPE)
14785         return 1;
14786       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
14787                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
14788         return 1;
14789       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14790                     strict);
14791
14792     case CONST_DECL:
14793       if (DECL_TEMPLATE_PARM_P (parm))
14794         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
14795       if (arg != integral_constant_value (parm))
14796         return 1;
14797       return 0;
14798
14799     case FIELD_DECL:
14800     case TEMPLATE_DECL:
14801       /* Matched cases are handled by the ARG == PARM test above.  */
14802       return 1;
14803
14804     case TYPE_ARGUMENT_PACK:
14805     case NONTYPE_ARGUMENT_PACK:
14806       {
14807         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
14808         tree packed_args = ARGUMENT_PACK_ARGS (arg);
14809         int i, len = TREE_VEC_LENGTH (packed_parms);
14810         int argslen = TREE_VEC_LENGTH (packed_args);
14811         int parm_variadic_p = 0;
14812
14813         for (i = 0; i < len; ++i)
14814           {
14815             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
14816               {
14817                 if (i == len - 1)
14818                   /* We can unify against something with a trailing
14819                      parameter pack.  */
14820                   parm_variadic_p = 1;
14821                 else
14822                   /* Since there is something following the pack
14823                      expansion, we cannot unify this template argument
14824                      list.  */
14825                   return 0;
14826               }
14827           }
14828           
14829
14830         /* If we don't have enough arguments to satisfy the parameters
14831            (not counting the pack expression at the end), or we have
14832            too many arguments for a parameter list that doesn't end in
14833            a pack expression, we can't unify.  */
14834         if (argslen < (len - parm_variadic_p)
14835             || (argslen > len && !parm_variadic_p))
14836           return 1;
14837
14838         /* Unify all of the parameters that precede the (optional)
14839            pack expression.  */
14840         for (i = 0; i < len - parm_variadic_p; ++i)
14841           {
14842             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
14843                        TREE_VEC_ELT (packed_args, i), strict))
14844               return 1;
14845           }
14846
14847         if (parm_variadic_p)
14848           return unify_pack_expansion (tparms, targs, 
14849                                        packed_parms, packed_args,
14850                                        strict, /*call_args_p=*/false,
14851                                        /*subr=*/false);
14852         return 0;
14853       }
14854
14855       break;
14856
14857     case TYPEOF_TYPE:
14858     case DECLTYPE_TYPE:
14859       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
14860          nodes.  */
14861       return 0;
14862
14863     case ERROR_MARK:
14864       /* Unification fails if we hit an error node.  */
14865       return 1;
14866
14867     default:
14868       gcc_assert (EXPR_P (parm));
14869
14870       /* We must be looking at an expression.  This can happen with
14871          something like:
14872
14873            template <int I>
14874            void foo(S<I>, S<I + 2>);
14875
14876          This is a "nondeduced context":
14877
14878            [deduct.type]
14879
14880            The nondeduced contexts are:
14881
14882            --A type that is a template-id in which one or more of
14883              the template-arguments is an expression that references
14884              a template-parameter.
14885
14886          In these cases, we assume deduction succeeded, but don't
14887          actually infer any unifications.  */
14888
14889       if (!uses_template_parms (parm)
14890           && !template_args_equal (parm, arg))
14891         return 1;
14892       else
14893         return 0;
14894     }
14895 }
14896 \f
14897 /* Note that DECL can be defined in this translation unit, if
14898    required.  */
14899
14900 static void
14901 mark_definable (tree decl)
14902 {
14903   tree clone;
14904   DECL_NOT_REALLY_EXTERN (decl) = 1;
14905   FOR_EACH_CLONE (clone, decl)
14906     DECL_NOT_REALLY_EXTERN (clone) = 1;
14907 }
14908
14909 /* Called if RESULT is explicitly instantiated, or is a member of an
14910    explicitly instantiated class.  */
14911
14912 void
14913 mark_decl_instantiated (tree result, int extern_p)
14914 {
14915   SET_DECL_EXPLICIT_INSTANTIATION (result);
14916
14917   /* If this entity has already been written out, it's too late to
14918      make any modifications.  */
14919   if (TREE_ASM_WRITTEN (result))
14920     return;
14921
14922   if (TREE_CODE (result) != FUNCTION_DECL)
14923     /* The TREE_PUBLIC flag for function declarations will have been
14924        set correctly by tsubst.  */
14925     TREE_PUBLIC (result) = 1;
14926
14927   /* This might have been set by an earlier implicit instantiation.  */
14928   DECL_COMDAT (result) = 0;
14929
14930   if (extern_p)
14931     DECL_NOT_REALLY_EXTERN (result) = 0;
14932   else
14933     {
14934       mark_definable (result);
14935       /* Always make artificials weak.  */
14936       if (DECL_ARTIFICIAL (result) && flag_weak)
14937         comdat_linkage (result);
14938       /* For WIN32 we also want to put explicit instantiations in
14939          linkonce sections.  */
14940       else if (TREE_PUBLIC (result))
14941         maybe_make_one_only (result);
14942     }
14943
14944   /* If EXTERN_P, then this function will not be emitted -- unless
14945      followed by an explicit instantiation, at which point its linkage
14946      will be adjusted.  If !EXTERN_P, then this function will be
14947      emitted here.  In neither circumstance do we want
14948      import_export_decl to adjust the linkage.  */
14949   DECL_INTERFACE_KNOWN (result) = 1;
14950 }
14951
14952 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
14953    important template arguments.  If any are missing, we check whether
14954    they're important by using error_mark_node for substituting into any
14955    args that were used for partial ordering (the ones between ARGS and END)
14956    and seeing if it bubbles up.  */
14957
14958 static bool
14959 check_undeduced_parms (tree targs, tree args, tree end)
14960 {
14961   bool found = false;
14962   int i;
14963   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
14964     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
14965       {
14966         found = true;
14967         TREE_VEC_ELT (targs, i) = error_mark_node;
14968       }
14969   if (found)
14970     {
14971       for (; args != end; args = TREE_CHAIN (args))
14972         {
14973           tree substed = tsubst (TREE_VALUE (args), targs, tf_none, NULL_TREE);
14974           if (substed == error_mark_node)
14975             return true;
14976         }
14977     }
14978   return false;
14979 }
14980
14981 /* Given two function templates PAT1 and PAT2, return:
14982
14983    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
14984    -1 if PAT2 is more specialized than PAT1.
14985    0 if neither is more specialized.
14986
14987    LEN indicates the number of parameters we should consider
14988    (defaulted parameters should not be considered).
14989
14990    The 1998 std underspecified function template partial ordering, and
14991    DR214 addresses the issue.  We take pairs of arguments, one from
14992    each of the templates, and deduce them against each other.  One of
14993    the templates will be more specialized if all the *other*
14994    template's arguments deduce against its arguments and at least one
14995    of its arguments *does* *not* deduce against the other template's
14996    corresponding argument.  Deduction is done as for class templates.
14997    The arguments used in deduction have reference and top level cv
14998    qualifiers removed.  Iff both arguments were originally reference
14999    types *and* deduction succeeds in both directions, the template
15000    with the more cv-qualified argument wins for that pairing (if
15001    neither is more cv-qualified, they both are equal).  Unlike regular
15002    deduction, after all the arguments have been deduced in this way,
15003    we do *not* verify the deduced template argument values can be
15004    substituted into non-deduced contexts.
15005
15006    The logic can be a bit confusing here, because we look at deduce1 and
15007    targs1 to see if pat2 is at least as specialized, and vice versa; if we
15008    can find template arguments for pat1 to make arg1 look like arg2, that
15009    means that arg2 is at least as specialized as arg1.  */
15010
15011 int
15012 more_specialized_fn (tree pat1, tree pat2, int len)
15013 {
15014   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
15015   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
15016   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
15017   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
15018   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
15019   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
15020   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
15021   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
15022   tree origs1, origs2;
15023   bool lose1 = false;
15024   bool lose2 = false;
15025
15026   /* Remove the this parameter from non-static member functions.  If
15027      one is a non-static member function and the other is not a static
15028      member function, remove the first parameter from that function
15029      also.  This situation occurs for operator functions where we
15030      locate both a member function (with this pointer) and non-member
15031      operator (with explicit first operand).  */
15032   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
15033     {
15034       len--; /* LEN is the number of significant arguments for DECL1 */
15035       args1 = TREE_CHAIN (args1);
15036       if (!DECL_STATIC_FUNCTION_P (decl2))
15037         args2 = TREE_CHAIN (args2);
15038     }
15039   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
15040     {
15041       args2 = TREE_CHAIN (args2);
15042       if (!DECL_STATIC_FUNCTION_P (decl1))
15043         {
15044           len--;
15045           args1 = TREE_CHAIN (args1);
15046         }
15047     }
15048
15049   /* If only one is a conversion operator, they are unordered.  */
15050   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
15051     return 0;
15052
15053   /* Consider the return type for a conversion function */
15054   if (DECL_CONV_FN_P (decl1))
15055     {
15056       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
15057       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
15058       len++;
15059     }
15060
15061   processing_template_decl++;
15062
15063   origs1 = args1;
15064   origs2 = args2;
15065
15066   while (len--
15067          /* Stop when an ellipsis is seen.  */
15068          && args1 != NULL_TREE && args2 != NULL_TREE)
15069     {
15070       tree arg1 = TREE_VALUE (args1);
15071       tree arg2 = TREE_VALUE (args2);
15072       int deduce1, deduce2;
15073       int quals1 = -1;
15074       int quals2 = -1;
15075
15076       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15077           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15078         {
15079           /* When both arguments are pack expansions, we need only
15080              unify the patterns themselves.  */
15081           arg1 = PACK_EXPANSION_PATTERN (arg1);
15082           arg2 = PACK_EXPANSION_PATTERN (arg2);
15083
15084           /* This is the last comparison we need to do.  */
15085           len = 0;
15086         }
15087
15088       if (TREE_CODE (arg1) == REFERENCE_TYPE)
15089         {
15090           arg1 = TREE_TYPE (arg1);
15091           quals1 = cp_type_quals (arg1);
15092         }
15093
15094       if (TREE_CODE (arg2) == REFERENCE_TYPE)
15095         {
15096           arg2 = TREE_TYPE (arg2);
15097           quals2 = cp_type_quals (arg2);
15098         }
15099
15100       if ((quals1 < 0) != (quals2 < 0))
15101         {
15102           /* Only of the args is a reference, see if we should apply
15103              array/function pointer decay to it.  This is not part of
15104              DR214, but is, IMHO, consistent with the deduction rules
15105              for the function call itself, and with our earlier
15106              implementation of the underspecified partial ordering
15107              rules.  (nathan).  */
15108           if (quals1 >= 0)
15109             {
15110               switch (TREE_CODE (arg1))
15111                 {
15112                 case ARRAY_TYPE:
15113                   arg1 = TREE_TYPE (arg1);
15114                   /* FALLTHROUGH. */
15115                 case FUNCTION_TYPE:
15116                   arg1 = build_pointer_type (arg1);
15117                   break;
15118
15119                 default:
15120                   break;
15121                 }
15122             }
15123           else
15124             {
15125               switch (TREE_CODE (arg2))
15126                 {
15127                 case ARRAY_TYPE:
15128                   arg2 = TREE_TYPE (arg2);
15129                   /* FALLTHROUGH. */
15130                 case FUNCTION_TYPE:
15131                   arg2 = build_pointer_type (arg2);
15132                   break;
15133
15134                 default:
15135                   break;
15136                 }
15137             }
15138         }
15139
15140       arg1 = TYPE_MAIN_VARIANT (arg1);
15141       arg2 = TYPE_MAIN_VARIANT (arg2);
15142
15143       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
15144         {
15145           int i, len2 = list_length (args2);
15146           tree parmvec = make_tree_vec (1);
15147           tree argvec = make_tree_vec (len2);
15148           tree ta = args2;
15149
15150           /* Setup the parameter vector, which contains only ARG1.  */
15151           TREE_VEC_ELT (parmvec, 0) = arg1;
15152
15153           /* Setup the argument vector, which contains the remaining
15154              arguments.  */
15155           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
15156             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15157
15158           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
15159                                            argvec, UNIFY_ALLOW_NONE, 
15160                                            /*call_args_p=*/false, 
15161                                            /*subr=*/0);
15162
15163           /* We cannot deduce in the other direction, because ARG1 is
15164              a pack expansion but ARG2 is not.  */
15165           deduce2 = 0;
15166         }
15167       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15168         {
15169           int i, len1 = list_length (args1);
15170           tree parmvec = make_tree_vec (1);
15171           tree argvec = make_tree_vec (len1);
15172           tree ta = args1;
15173
15174           /* Setup the parameter vector, which contains only ARG1.  */
15175           TREE_VEC_ELT (parmvec, 0) = arg2;
15176
15177           /* Setup the argument vector, which contains the remaining
15178              arguments.  */
15179           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
15180             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15181
15182           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
15183                                            argvec, UNIFY_ALLOW_NONE, 
15184                                            /*call_args_p=*/false, 
15185                                            /*subr=*/0);
15186
15187           /* We cannot deduce in the other direction, because ARG2 is
15188              a pack expansion but ARG1 is not.*/
15189           deduce1 = 0;
15190         }
15191
15192       else
15193         {
15194           /* The normal case, where neither argument is a pack
15195              expansion.  */
15196           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
15197           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
15198         }
15199
15200       /* If we couldn't deduce arguments for tparms1 to make arg1 match
15201          arg2, then arg2 is not as specialized as arg1.  */
15202       if (!deduce1)
15203         lose2 = true;
15204       if (!deduce2)
15205         lose1 = true;
15206
15207       /* "If, for a given type, deduction succeeds in both directions
15208          (i.e., the types are identical after the transformations above)
15209          and if the type from the argument template is more cv-qualified
15210          than the type from the parameter template (as described above)
15211          that type is considered to be more specialized than the other. If
15212          neither type is more cv-qualified than the other then neither type
15213          is more specialized than the other."
15214
15215          We check same_type_p explicitly because deduction can also succeed
15216          in both directions when there is a nondeduced context.  */
15217       if (deduce1 && deduce2
15218           && quals1 != quals2 && quals1 >= 0 && quals2 >= 0
15219           && same_type_p (arg1, arg2))
15220         {
15221           if ((quals1 & quals2) == quals2)
15222             lose2 = true;
15223           if ((quals1 & quals2) == quals1)
15224             lose1 = true;
15225         }
15226
15227       if (lose1 && lose2)
15228         /* We've failed to deduce something in either direction.
15229            These must be unordered.  */
15230         break;
15231
15232       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15233           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15234         /* We have already processed all of the arguments in our
15235            handing of the pack expansion type.  */
15236         len = 0;
15237
15238       args1 = TREE_CHAIN (args1);
15239       args2 = TREE_CHAIN (args2);
15240     }
15241
15242   /* "In most cases, all template parameters must have values in order for
15243      deduction to succeed, but for partial ordering purposes a template
15244      parameter may remain without a value provided it is not used in the
15245      types being used for partial ordering."
15246
15247      Thus, if we are missing any of the targs1 we need to substitute into
15248      origs1, then pat2 is not as specialized as pat1.  This can happen when
15249      there is a nondeduced context.  */
15250   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
15251     lose2 = true;
15252   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
15253     lose1 = true;
15254
15255   processing_template_decl--;
15256
15257   /* All things being equal, if the next argument is a pack expansion
15258      for one function but not for the other, prefer the
15259      non-variadic function.  FIXME this is bogus; see c++/41958.  */
15260   if (lose1 == lose2
15261       && args1 && TREE_VALUE (args1)
15262       && args2 && TREE_VALUE (args2))
15263     {
15264       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
15265       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
15266     }
15267
15268   if (lose1 == lose2)
15269     return 0;
15270   else if (!lose1)
15271     return 1;
15272   else
15273     return -1;
15274 }
15275
15276 /* Determine which of two partial specializations is more specialized.
15277
15278    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
15279    to the first partial specialization.  The TREE_VALUE is the
15280    innermost set of template parameters for the partial
15281    specialization.  PAT2 is similar, but for the second template.
15282
15283    Return 1 if the first partial specialization is more specialized;
15284    -1 if the second is more specialized; 0 if neither is more
15285    specialized.
15286
15287    See [temp.class.order] for information about determining which of
15288    two templates is more specialized.  */
15289
15290 static int
15291 more_specialized_class (tree pat1, tree pat2)
15292 {
15293   tree targs;
15294   tree tmpl1, tmpl2;
15295   int winner = 0;
15296   bool any_deductions = false;
15297
15298   tmpl1 = TREE_TYPE (pat1);
15299   tmpl2 = TREE_TYPE (pat2);
15300
15301   /* Just like what happens for functions, if we are ordering between
15302      different class template specializations, we may encounter dependent
15303      types in the arguments, and we need our dependency check functions
15304      to behave correctly.  */
15305   ++processing_template_decl;
15306   targs = get_class_bindings (TREE_VALUE (pat1),
15307                               CLASSTYPE_TI_ARGS (tmpl1),
15308                               CLASSTYPE_TI_ARGS (tmpl2));
15309   if (targs)
15310     {
15311       --winner;
15312       any_deductions = true;
15313     }
15314
15315   targs = get_class_bindings (TREE_VALUE (pat2),
15316                               CLASSTYPE_TI_ARGS (tmpl2),
15317                               CLASSTYPE_TI_ARGS (tmpl1));
15318   if (targs)
15319     {
15320       ++winner;
15321       any_deductions = true;
15322     }
15323   --processing_template_decl;
15324
15325   /* In the case of a tie where at least one of the class templates
15326      has a parameter pack at the end, the template with the most
15327      non-packed parameters wins.  */
15328   if (winner == 0
15329       && any_deductions
15330       && (template_args_variadic_p (TREE_PURPOSE (pat1))
15331           || template_args_variadic_p (TREE_PURPOSE (pat2))))
15332     {
15333       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
15334       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
15335       int len1 = TREE_VEC_LENGTH (args1);
15336       int len2 = TREE_VEC_LENGTH (args2);
15337
15338       /* We don't count the pack expansion at the end.  */
15339       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
15340         --len1;
15341       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
15342         --len2;
15343
15344       if (len1 > len2)
15345         return 1;
15346       else if (len1 < len2)
15347         return -1;
15348     }
15349
15350   return winner;
15351 }
15352
15353 /* Return the template arguments that will produce the function signature
15354    DECL from the function template FN, with the explicit template
15355    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
15356    also match.  Return NULL_TREE if no satisfactory arguments could be
15357    found.  */
15358
15359 static tree
15360 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
15361 {
15362   int ntparms = DECL_NTPARMS (fn);
15363   tree targs = make_tree_vec (ntparms);
15364   tree decl_type;
15365   tree decl_arg_types;
15366   tree *args;
15367   unsigned int nargs, ix;
15368   tree arg;
15369
15370   /* Substitute the explicit template arguments into the type of DECL.
15371      The call to fn_type_unification will handle substitution into the
15372      FN.  */
15373   decl_type = TREE_TYPE (decl);
15374   if (explicit_args && uses_template_parms (decl_type))
15375     {
15376       tree tmpl;
15377       tree converted_args;
15378
15379       if (DECL_TEMPLATE_INFO (decl))
15380         tmpl = DECL_TI_TEMPLATE (decl);
15381       else
15382         /* We can get here for some invalid specializations.  */
15383         return NULL_TREE;
15384
15385       converted_args
15386         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
15387                                  explicit_args, NULL_TREE,
15388                                  tf_none,
15389                                  /*require_all_args=*/false,
15390                                  /*use_default_args=*/false);
15391       if (converted_args == error_mark_node)
15392         return NULL_TREE;
15393
15394       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
15395       if (decl_type == error_mark_node)
15396         return NULL_TREE;
15397     }
15398
15399   /* Never do unification on the 'this' parameter.  */
15400   decl_arg_types = skip_artificial_parms_for (decl, 
15401                                               TYPE_ARG_TYPES (decl_type));
15402
15403   nargs = list_length (decl_arg_types);
15404   args = XALLOCAVEC (tree, nargs);
15405   for (arg = decl_arg_types, ix = 0;
15406        arg != NULL_TREE && arg != void_list_node;
15407        arg = TREE_CHAIN (arg), ++ix)
15408     args[ix] = TREE_VALUE (arg);
15409
15410   if (fn_type_unification (fn, explicit_args, targs,
15411                            args, ix,
15412                            (check_rettype || DECL_CONV_FN_P (fn)
15413                             ? TREE_TYPE (decl_type) : NULL_TREE),
15414                            DEDUCE_EXACT, LOOKUP_NORMAL))
15415     return NULL_TREE;
15416
15417   return targs;
15418 }
15419
15420 /* Return the innermost template arguments that, when applied to a
15421    template specialization whose innermost template parameters are
15422    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
15423    ARGS.
15424
15425    For example, suppose we have:
15426
15427      template <class T, class U> struct S {};
15428      template <class T> struct S<T*, int> {};
15429
15430    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
15431    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
15432    int}.  The resulting vector will be {double}, indicating that `T'
15433    is bound to `double'.  */
15434
15435 static tree
15436 get_class_bindings (tree tparms, tree spec_args, tree args)
15437 {
15438   int i, ntparms = TREE_VEC_LENGTH (tparms);
15439   tree deduced_args;
15440   tree innermost_deduced_args;
15441
15442   innermost_deduced_args = make_tree_vec (ntparms);
15443   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
15444     {
15445       deduced_args = copy_node (args);
15446       SET_TMPL_ARGS_LEVEL (deduced_args,
15447                            TMPL_ARGS_DEPTH (deduced_args),
15448                            innermost_deduced_args);
15449     }
15450   else
15451     deduced_args = innermost_deduced_args;
15452
15453   if (unify (tparms, deduced_args,
15454              INNERMOST_TEMPLATE_ARGS (spec_args),
15455              INNERMOST_TEMPLATE_ARGS (args),
15456              UNIFY_ALLOW_NONE))
15457     return NULL_TREE;
15458
15459   for (i =  0; i < ntparms; ++i)
15460     if (! TREE_VEC_ELT (innermost_deduced_args, i))
15461       return NULL_TREE;
15462
15463   /* Verify that nondeduced template arguments agree with the type
15464      obtained from argument deduction.
15465
15466      For example:
15467
15468        struct A { typedef int X; };
15469        template <class T, class U> struct C {};
15470        template <class T> struct C<T, typename T::X> {};
15471
15472      Then with the instantiation `C<A, int>', we can deduce that
15473      `T' is `A' but unify () does not check whether `typename T::X'
15474      is `int'.  */
15475   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
15476   if (spec_args == error_mark_node
15477       /* We only need to check the innermost arguments; the other
15478          arguments will always agree.  */
15479       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
15480                               INNERMOST_TEMPLATE_ARGS (args)))
15481     return NULL_TREE;
15482
15483   /* Now that we have bindings for all of the template arguments,
15484      ensure that the arguments deduced for the template template
15485      parameters have compatible template parameter lists.  See the use
15486      of template_template_parm_bindings_ok_p in fn_type_unification
15487      for more information.  */
15488   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
15489     return NULL_TREE;
15490
15491   return deduced_args;
15492 }
15493
15494 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
15495    Return the TREE_LIST node with the most specialized template, if
15496    any.  If there is no most specialized template, the error_mark_node
15497    is returned.
15498
15499    Note that this function does not look at, or modify, the
15500    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
15501    returned is one of the elements of INSTANTIATIONS, callers may
15502    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
15503    and retrieve it from the value returned.  */
15504
15505 tree
15506 most_specialized_instantiation (tree templates)
15507 {
15508   tree fn, champ;
15509
15510   ++processing_template_decl;
15511
15512   champ = templates;
15513   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
15514     {
15515       int fate = 0;
15516
15517       if (get_bindings (TREE_VALUE (champ),
15518                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
15519                         NULL_TREE, /*check_ret=*/false))
15520         fate--;
15521
15522       if (get_bindings (TREE_VALUE (fn),
15523                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
15524                         NULL_TREE, /*check_ret=*/false))
15525         fate++;
15526
15527       if (fate == -1)
15528         champ = fn;
15529       else if (!fate)
15530         {
15531           /* Equally specialized, move to next function.  If there
15532              is no next function, nothing's most specialized.  */
15533           fn = TREE_CHAIN (fn);
15534           champ = fn;
15535           if (!fn)
15536             break;
15537         }
15538     }
15539
15540   if (champ)
15541     /* Now verify that champ is better than everything earlier in the
15542        instantiation list.  */
15543     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
15544       if (get_bindings (TREE_VALUE (champ),
15545                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
15546                         NULL_TREE, /*check_ret=*/false)
15547           || !get_bindings (TREE_VALUE (fn),
15548                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
15549                             NULL_TREE, /*check_ret=*/false))
15550         {
15551           champ = NULL_TREE;
15552           break;
15553         }
15554
15555   processing_template_decl--;
15556
15557   if (!champ)
15558     return error_mark_node;
15559
15560   return champ;
15561 }
15562
15563 /* If DECL is a specialization of some template, return the most
15564    general such template.  Otherwise, returns NULL_TREE.
15565
15566    For example, given:
15567
15568      template <class T> struct S { template <class U> void f(U); };
15569
15570    if TMPL is `template <class U> void S<int>::f(U)' this will return
15571    the full template.  This function will not trace past partial
15572    specializations, however.  For example, given in addition:
15573
15574      template <class T> struct S<T*> { template <class U> void f(U); };
15575
15576    if TMPL is `template <class U> void S<int*>::f(U)' this will return
15577    `template <class T> template <class U> S<T*>::f(U)'.  */
15578
15579 tree
15580 most_general_template (tree decl)
15581 {
15582   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
15583      an immediate specialization.  */
15584   if (TREE_CODE (decl) == FUNCTION_DECL)
15585     {
15586       if (DECL_TEMPLATE_INFO (decl)) {
15587         decl = DECL_TI_TEMPLATE (decl);
15588
15589         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
15590            template friend.  */
15591         if (TREE_CODE (decl) != TEMPLATE_DECL)
15592           return NULL_TREE;
15593       } else
15594         return NULL_TREE;
15595     }
15596
15597   /* Look for more and more general templates.  */
15598   while (DECL_TEMPLATE_INFO (decl))
15599     {
15600       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
15601          (See cp-tree.h for details.)  */
15602       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
15603         break;
15604
15605       if (CLASS_TYPE_P (TREE_TYPE (decl))
15606           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
15607         break;
15608
15609       /* Stop if we run into an explicitly specialized class template.  */
15610       if (!DECL_NAMESPACE_SCOPE_P (decl)
15611           && DECL_CONTEXT (decl)
15612           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
15613         break;
15614
15615       decl = DECL_TI_TEMPLATE (decl);
15616     }
15617
15618   return decl;
15619 }
15620
15621 /* Return the most specialized of the class template partial
15622    specializations of TMPL which can produce TYPE, a specialization of
15623    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
15624    a _TYPE node corresponding to the partial specialization, while the
15625    TREE_PURPOSE is the set of template arguments that must be
15626    substituted into the TREE_TYPE in order to generate TYPE.
15627
15628    If the choice of partial specialization is ambiguous, a diagnostic
15629    is issued, and the error_mark_node is returned.  If there are no
15630    partial specializations of TMPL matching TYPE, then NULL_TREE is
15631    returned.  */
15632
15633 static tree
15634 most_specialized_class (tree type, tree tmpl)
15635 {
15636   tree list = NULL_TREE;
15637   tree t;
15638   tree champ;
15639   int fate;
15640   bool ambiguous_p;
15641   tree args;
15642   tree outer_args = NULL_TREE;
15643
15644   tmpl = most_general_template (tmpl);
15645   args = CLASSTYPE_TI_ARGS (type);
15646
15647   /* For determining which partial specialization to use, only the
15648      innermost args are interesting.  */
15649   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
15650     {
15651       outer_args = strip_innermost_template_args (args, 1);
15652       args = INNERMOST_TEMPLATE_ARGS (args);
15653     }
15654
15655   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
15656     {
15657       tree partial_spec_args;
15658       tree spec_args;
15659       tree parms = TREE_VALUE (t);
15660
15661       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
15662       if (outer_args)
15663         {
15664           int i;
15665
15666           ++processing_template_decl;
15667
15668           /* Discard the outer levels of args, and then substitute in the
15669              template args from the enclosing class.  */
15670           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
15671           partial_spec_args = tsubst_template_args
15672             (partial_spec_args, outer_args, tf_none, NULL_TREE);
15673
15674           /* PARMS already refers to just the innermost parms, but the
15675              template parms in partial_spec_args had their levels lowered
15676              by tsubst, so we need to do the same for the parm list.  We
15677              can't just tsubst the TREE_VEC itself, as tsubst wants to
15678              treat a TREE_VEC as an argument vector.  */
15679           parms = copy_node (parms);
15680           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
15681             TREE_VEC_ELT (parms, i) =
15682               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
15683
15684           --processing_template_decl;
15685         }
15686       spec_args = get_class_bindings (parms,
15687                                       partial_spec_args,
15688                                       args);
15689       if (spec_args)
15690         {
15691           if (outer_args)
15692             spec_args = add_to_template_args (outer_args, spec_args);
15693           list = tree_cons (spec_args, TREE_VALUE (t), list);
15694           TREE_TYPE (list) = TREE_TYPE (t);
15695         }
15696     }
15697
15698   if (! list)
15699     return NULL_TREE;
15700
15701   ambiguous_p = false;
15702   t = list;
15703   champ = t;
15704   t = TREE_CHAIN (t);
15705   for (; t; t = TREE_CHAIN (t))
15706     {
15707       fate = more_specialized_class (champ, t);
15708       if (fate == 1)
15709         ;
15710       else
15711         {
15712           if (fate == 0)
15713             {
15714               t = TREE_CHAIN (t);
15715               if (! t)
15716                 {
15717                   ambiguous_p = true;
15718                   break;
15719                 }
15720             }
15721           champ = t;
15722         }
15723     }
15724
15725   if (!ambiguous_p)
15726     for (t = list; t && t != champ; t = TREE_CHAIN (t))
15727       {
15728         fate = more_specialized_class (champ, t);
15729         if (fate != 1)
15730           {
15731             ambiguous_p = true;
15732             break;
15733           }
15734       }
15735
15736   if (ambiguous_p)
15737     {
15738       const char *str = "candidates are:";
15739       error ("ambiguous class template instantiation for %q#T", type);
15740       for (t = list; t; t = TREE_CHAIN (t))
15741         {
15742           error ("%s %+#T", str, TREE_TYPE (t));
15743           str = "               ";
15744         }
15745       return error_mark_node;
15746     }
15747
15748   return champ;
15749 }
15750
15751 /* Explicitly instantiate DECL.  */
15752
15753 void
15754 do_decl_instantiation (tree decl, tree storage)
15755 {
15756   tree result = NULL_TREE;
15757   int extern_p = 0;
15758
15759   if (!decl || decl == error_mark_node)
15760     /* An error occurred, for which grokdeclarator has already issued
15761        an appropriate message.  */
15762     return;
15763   else if (! DECL_LANG_SPECIFIC (decl))
15764     {
15765       error ("explicit instantiation of non-template %q#D", decl);
15766       return;
15767     }
15768   else if (TREE_CODE (decl) == VAR_DECL)
15769     {
15770       /* There is an asymmetry here in the way VAR_DECLs and
15771          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
15772          the latter, the DECL we get back will be marked as a
15773          template instantiation, and the appropriate
15774          DECL_TEMPLATE_INFO will be set up.  This does not happen for
15775          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
15776          should handle VAR_DECLs as it currently handles
15777          FUNCTION_DECLs.  */
15778       if (!DECL_CLASS_SCOPE_P (decl))
15779         {
15780           error ("%qD is not a static data member of a class template", decl);
15781           return;
15782         }
15783       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
15784       if (!result || TREE_CODE (result) != VAR_DECL)
15785         {
15786           error ("no matching template for %qD found", decl);
15787           return;
15788         }
15789       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
15790         {
15791           error ("type %qT for explicit instantiation %qD does not match "
15792                  "declared type %qT", TREE_TYPE (result), decl,
15793                  TREE_TYPE (decl));
15794           return;
15795         }
15796     }
15797   else if (TREE_CODE (decl) != FUNCTION_DECL)
15798     {
15799       error ("explicit instantiation of %q#D", decl);
15800       return;
15801     }
15802   else
15803     result = decl;
15804
15805   /* Check for various error cases.  Note that if the explicit
15806      instantiation is valid the RESULT will currently be marked as an
15807      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
15808      until we get here.  */
15809
15810   if (DECL_TEMPLATE_SPECIALIZATION (result))
15811     {
15812       /* DR 259 [temp.spec].
15813
15814          Both an explicit instantiation and a declaration of an explicit
15815          specialization shall not appear in a program unless the explicit
15816          instantiation follows a declaration of the explicit specialization.
15817
15818          For a given set of template parameters, if an explicit
15819          instantiation of a template appears after a declaration of an
15820          explicit specialization for that template, the explicit
15821          instantiation has no effect.  */
15822       return;
15823     }
15824   else if (DECL_EXPLICIT_INSTANTIATION (result))
15825     {
15826       /* [temp.spec]
15827
15828          No program shall explicitly instantiate any template more
15829          than once.
15830
15831          We check DECL_NOT_REALLY_EXTERN so as not to complain when
15832          the first instantiation was `extern' and the second is not,
15833          and EXTERN_P for the opposite case.  */
15834       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
15835         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
15836       /* If an "extern" explicit instantiation follows an ordinary
15837          explicit instantiation, the template is instantiated.  */
15838       if (extern_p)
15839         return;
15840     }
15841   else if (!DECL_IMPLICIT_INSTANTIATION (result))
15842     {
15843       error ("no matching template for %qD found", result);
15844       return;
15845     }
15846   else if (!DECL_TEMPLATE_INFO (result))
15847     {
15848       permerror (input_location, "explicit instantiation of non-template %q#D", result);
15849       return;
15850     }
15851
15852   if (storage == NULL_TREE)
15853     ;
15854   else if (storage == ridpointers[(int) RID_EXTERN])
15855     {
15856       if (!in_system_header && (cxx_dialect == cxx98))
15857         pedwarn (input_location, OPT_pedantic, 
15858                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
15859                  "instantiations");
15860       extern_p = 1;
15861     }
15862   else
15863     error ("storage class %qD applied to template instantiation", storage);
15864
15865   check_explicit_instantiation_namespace (result);
15866   mark_decl_instantiated (result, extern_p);
15867   if (! extern_p)
15868     instantiate_decl (result, /*defer_ok=*/1,
15869                       /*expl_inst_class_mem_p=*/false);
15870 }
15871
15872 static void
15873 mark_class_instantiated (tree t, int extern_p)
15874 {
15875   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
15876   SET_CLASSTYPE_INTERFACE_KNOWN (t);
15877   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
15878   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
15879   if (! extern_p)
15880     {
15881       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
15882       rest_of_type_compilation (t, 1);
15883     }
15884 }
15885
15886 /* Called from do_type_instantiation through binding_table_foreach to
15887    do recursive instantiation for the type bound in ENTRY.  */
15888 static void
15889 bt_instantiate_type_proc (binding_entry entry, void *data)
15890 {
15891   tree storage = *(tree *) data;
15892
15893   if (MAYBE_CLASS_TYPE_P (entry->type)
15894       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
15895     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
15896 }
15897
15898 /* Called from do_type_instantiation to instantiate a member
15899    (a member function or a static member variable) of an
15900    explicitly instantiated class template.  */
15901 static void
15902 instantiate_class_member (tree decl, int extern_p)
15903 {
15904   mark_decl_instantiated (decl, extern_p);
15905   if (! extern_p)
15906     instantiate_decl (decl, /*defer_ok=*/1,
15907                       /*expl_inst_class_mem_p=*/true);
15908 }
15909
15910 /* Perform an explicit instantiation of template class T.  STORAGE, if
15911    non-null, is the RID for extern, inline or static.  COMPLAIN is
15912    nonzero if this is called from the parser, zero if called recursively,
15913    since the standard is unclear (as detailed below).  */
15914
15915 void
15916 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
15917 {
15918   int extern_p = 0;
15919   int nomem_p = 0;
15920   int static_p = 0;
15921   int previous_instantiation_extern_p = 0;
15922
15923   if (TREE_CODE (t) == TYPE_DECL)
15924     t = TREE_TYPE (t);
15925
15926   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
15927     {
15928       error ("explicit instantiation of non-template type %qT", t);
15929       return;
15930     }
15931
15932   complete_type (t);
15933
15934   if (!COMPLETE_TYPE_P (t))
15935     {
15936       if (complain & tf_error)
15937         error ("explicit instantiation of %q#T before definition of template",
15938                t);
15939       return;
15940     }
15941
15942   if (storage != NULL_TREE)
15943     {
15944       if (!in_system_header)
15945         {
15946           if (storage == ridpointers[(int) RID_EXTERN])
15947             {
15948               if (cxx_dialect == cxx98)
15949                 pedwarn (input_location, OPT_pedantic, 
15950                          "ISO C++ 1998 forbids the use of %<extern%> on "
15951                          "explicit instantiations");
15952             }
15953           else
15954             pedwarn (input_location, OPT_pedantic, 
15955                      "ISO C++ forbids the use of %qE"
15956                      " on explicit instantiations", storage);
15957         }
15958
15959       if (storage == ridpointers[(int) RID_INLINE])
15960         nomem_p = 1;
15961       else if (storage == ridpointers[(int) RID_EXTERN])
15962         extern_p = 1;
15963       else if (storage == ridpointers[(int) RID_STATIC])
15964         static_p = 1;
15965       else
15966         {
15967           error ("storage class %qD applied to template instantiation",
15968                  storage);
15969           extern_p = 0;
15970         }
15971     }
15972
15973   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
15974     {
15975       /* DR 259 [temp.spec].
15976
15977          Both an explicit instantiation and a declaration of an explicit
15978          specialization shall not appear in a program unless the explicit
15979          instantiation follows a declaration of the explicit specialization.
15980
15981          For a given set of template parameters, if an explicit
15982          instantiation of a template appears after a declaration of an
15983          explicit specialization for that template, the explicit
15984          instantiation has no effect.  */
15985       return;
15986     }
15987   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
15988     {
15989       /* [temp.spec]
15990
15991          No program shall explicitly instantiate any template more
15992          than once.
15993
15994          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
15995          instantiation was `extern'.  If EXTERN_P then the second is.
15996          These cases are OK.  */
15997       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
15998
15999       if (!previous_instantiation_extern_p && !extern_p
16000           && (complain & tf_error))
16001         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
16002
16003       /* If we've already instantiated the template, just return now.  */
16004       if (!CLASSTYPE_INTERFACE_ONLY (t))
16005         return;
16006     }
16007
16008   check_explicit_instantiation_namespace (TYPE_NAME (t));
16009   mark_class_instantiated (t, extern_p);
16010
16011   if (nomem_p)
16012     return;
16013
16014   {
16015     tree tmp;
16016
16017     /* In contrast to implicit instantiation, where only the
16018        declarations, and not the definitions, of members are
16019        instantiated, we have here:
16020
16021          [temp.explicit]
16022
16023          The explicit instantiation of a class template specialization
16024          implies the instantiation of all of its members not
16025          previously explicitly specialized in the translation unit
16026          containing the explicit instantiation.
16027
16028        Of course, we can't instantiate member template classes, since
16029        we don't have any arguments for them.  Note that the standard
16030        is unclear on whether the instantiation of the members are
16031        *explicit* instantiations or not.  However, the most natural
16032        interpretation is that it should be an explicit instantiation.  */
16033
16034     if (! static_p)
16035       for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
16036         if (TREE_CODE (tmp) == FUNCTION_DECL
16037             && DECL_TEMPLATE_INSTANTIATION (tmp))
16038           instantiate_class_member (tmp, extern_p);
16039
16040     for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
16041       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
16042         instantiate_class_member (tmp, extern_p);
16043
16044     if (CLASSTYPE_NESTED_UTDS (t))
16045       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
16046                              bt_instantiate_type_proc, &storage);
16047   }
16048 }
16049
16050 /* Given a function DECL, which is a specialization of TMPL, modify
16051    DECL to be a re-instantiation of TMPL with the same template
16052    arguments.  TMPL should be the template into which tsubst'ing
16053    should occur for DECL, not the most general template.
16054
16055    One reason for doing this is a scenario like this:
16056
16057      template <class T>
16058      void f(const T&, int i);
16059
16060      void g() { f(3, 7); }
16061
16062      template <class T>
16063      void f(const T& t, const int i) { }
16064
16065    Note that when the template is first instantiated, with
16066    instantiate_template, the resulting DECL will have no name for the
16067    first parameter, and the wrong type for the second.  So, when we go
16068    to instantiate the DECL, we regenerate it.  */
16069
16070 static void
16071 regenerate_decl_from_template (tree decl, tree tmpl)
16072 {
16073   /* The arguments used to instantiate DECL, from the most general
16074      template.  */
16075   tree args;
16076   tree code_pattern;
16077
16078   args = DECL_TI_ARGS (decl);
16079   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
16080
16081   /* Make sure that we can see identifiers, and compute access
16082      correctly.  */
16083   push_access_scope (decl);
16084
16085   if (TREE_CODE (decl) == FUNCTION_DECL)
16086     {
16087       tree decl_parm;
16088       tree pattern_parm;
16089       tree specs;
16090       int args_depth;
16091       int parms_depth;
16092
16093       args_depth = TMPL_ARGS_DEPTH (args);
16094       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
16095       if (args_depth > parms_depth)
16096         args = get_innermost_template_args (args, parms_depth);
16097
16098       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
16099                                               args, tf_error, NULL_TREE);
16100       if (specs)
16101         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
16102                                                     specs);
16103
16104       /* Merge parameter declarations.  */
16105       decl_parm = skip_artificial_parms_for (decl,
16106                                              DECL_ARGUMENTS (decl));
16107       pattern_parm
16108         = skip_artificial_parms_for (code_pattern,
16109                                      DECL_ARGUMENTS (code_pattern));
16110       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
16111         {
16112           tree parm_type;
16113           tree attributes;
16114           
16115           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16116             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
16117           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
16118                               NULL_TREE);
16119           parm_type = type_decays_to (parm_type);
16120           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16121             TREE_TYPE (decl_parm) = parm_type;
16122           attributes = DECL_ATTRIBUTES (pattern_parm);
16123           if (DECL_ATTRIBUTES (decl_parm) != attributes)
16124             {
16125               DECL_ATTRIBUTES (decl_parm) = attributes;
16126               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16127             }
16128           decl_parm = TREE_CHAIN (decl_parm);
16129           pattern_parm = TREE_CHAIN (pattern_parm);
16130         }
16131       /* Merge any parameters that match with the function parameter
16132          pack.  */
16133       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
16134         {
16135           int i, len;
16136           tree expanded_types;
16137           /* Expand the TYPE_PACK_EXPANSION that provides the types for
16138              the parameters in this function parameter pack.  */
16139           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
16140                                                  args, tf_error, NULL_TREE);
16141           len = TREE_VEC_LENGTH (expanded_types);
16142           for (i = 0; i < len; i++)
16143             {
16144               tree parm_type;
16145               tree attributes;
16146           
16147               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16148                 /* Rename the parameter to include the index.  */
16149                 DECL_NAME (decl_parm) = 
16150                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
16151               parm_type = TREE_VEC_ELT (expanded_types, i);
16152               parm_type = type_decays_to (parm_type);
16153               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16154                 TREE_TYPE (decl_parm) = parm_type;
16155               attributes = DECL_ATTRIBUTES (pattern_parm);
16156               if (DECL_ATTRIBUTES (decl_parm) != attributes)
16157                 {
16158                   DECL_ATTRIBUTES (decl_parm) = attributes;
16159                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16160                 }
16161               decl_parm = TREE_CHAIN (decl_parm);
16162             }
16163         }
16164       /* Merge additional specifiers from the CODE_PATTERN.  */
16165       if (DECL_DECLARED_INLINE_P (code_pattern)
16166           && !DECL_DECLARED_INLINE_P (decl))
16167         DECL_DECLARED_INLINE_P (decl) = 1;
16168     }
16169   else if (TREE_CODE (decl) == VAR_DECL)
16170     DECL_INITIAL (decl) =
16171       tsubst_expr (DECL_INITIAL (code_pattern), args,
16172                    tf_error, DECL_TI_TEMPLATE (decl),
16173                    /*integral_constant_expression_p=*/false);
16174   else
16175     gcc_unreachable ();
16176
16177   pop_access_scope (decl);
16178 }
16179
16180 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
16181    substituted to get DECL.  */
16182
16183 tree
16184 template_for_substitution (tree decl)
16185 {
16186   tree tmpl = DECL_TI_TEMPLATE (decl);
16187
16188   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
16189      for the instantiation.  This is not always the most general
16190      template.  Consider, for example:
16191
16192         template <class T>
16193         struct S { template <class U> void f();
16194                    template <> void f<int>(); };
16195
16196      and an instantiation of S<double>::f<int>.  We want TD to be the
16197      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
16198   while (/* An instantiation cannot have a definition, so we need a
16199             more general template.  */
16200          DECL_TEMPLATE_INSTANTIATION (tmpl)
16201            /* We must also deal with friend templates.  Given:
16202
16203                 template <class T> struct S {
16204                   template <class U> friend void f() {};
16205                 };
16206
16207               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
16208               so far as the language is concerned, but that's still
16209               where we get the pattern for the instantiation from.  On
16210               other hand, if the definition comes outside the class, say:
16211
16212                 template <class T> struct S {
16213                   template <class U> friend void f();
16214                 };
16215                 template <class U> friend void f() {}
16216
16217               we don't need to look any further.  That's what the check for
16218               DECL_INITIAL is for.  */
16219           || (TREE_CODE (decl) == FUNCTION_DECL
16220               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
16221               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
16222     {
16223       /* The present template, TD, should not be a definition.  If it
16224          were a definition, we should be using it!  Note that we
16225          cannot restructure the loop to just keep going until we find
16226          a template with a definition, since that might go too far if
16227          a specialization was declared, but not defined.  */
16228       gcc_assert (TREE_CODE (decl) != VAR_DECL
16229                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
16230
16231       /* Fetch the more general template.  */
16232       tmpl = DECL_TI_TEMPLATE (tmpl);
16233     }
16234
16235   return tmpl;
16236 }
16237
16238 /* Returns true if we need to instantiate this template instance even if we
16239    know we aren't going to emit it..  */
16240
16241 bool
16242 always_instantiate_p (tree decl)
16243 {
16244   /* We always instantiate inline functions so that we can inline them.  An
16245      explicit instantiation declaration prohibits implicit instantiation of
16246      non-inline functions.  With high levels of optimization, we would
16247      normally inline non-inline functions -- but we're not allowed to do
16248      that for "extern template" functions.  Therefore, we check
16249      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
16250   return ((TREE_CODE (decl) == FUNCTION_DECL
16251            && DECL_DECLARED_INLINE_P (decl))
16252           /* And we need to instantiate static data members so that
16253              their initializers are available in integral constant
16254              expressions.  */
16255           || (TREE_CODE (decl) == VAR_DECL
16256               && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl)));
16257 }
16258
16259 /* Produce the definition of D, a _DECL generated from a template.  If
16260    DEFER_OK is nonzero, then we don't have to actually do the
16261    instantiation now; we just have to do it sometime.  Normally it is
16262    an error if this is an explicit instantiation but D is undefined.
16263    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
16264    explicitly instantiated class template.  */
16265
16266 tree
16267 instantiate_decl (tree d, int defer_ok,
16268                   bool expl_inst_class_mem_p)
16269 {
16270   tree tmpl = DECL_TI_TEMPLATE (d);
16271   tree gen_args;
16272   tree args;
16273   tree td;
16274   tree code_pattern;
16275   tree spec;
16276   tree gen_tmpl;
16277   bool pattern_defined;
16278   int need_push;
16279   location_t saved_loc = input_location;
16280   bool external_p;
16281
16282   /* This function should only be used to instantiate templates for
16283      functions and static member variables.  */
16284   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
16285               || TREE_CODE (d) == VAR_DECL);
16286
16287   /* Variables are never deferred; if instantiation is required, they
16288      are instantiated right away.  That allows for better code in the
16289      case that an expression refers to the value of the variable --
16290      if the variable has a constant value the referring expression can
16291      take advantage of that fact.  */
16292   if (TREE_CODE (d) == VAR_DECL)
16293     defer_ok = 0;
16294
16295   /* Don't instantiate cloned functions.  Instead, instantiate the
16296      functions they cloned.  */
16297   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
16298     d = DECL_CLONED_FUNCTION (d);
16299
16300   if (DECL_TEMPLATE_INSTANTIATED (d)
16301       || DECL_TEMPLATE_SPECIALIZATION (d))
16302     /* D has already been instantiated or explicitly specialized, so
16303        there's nothing for us to do here.
16304
16305        It might seem reasonable to check whether or not D is an explicit
16306        instantiation, and, if so, stop here.  But when an explicit
16307        instantiation is deferred until the end of the compilation,
16308        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
16309        the instantiation.  */
16310     return d;
16311
16312   /* Check to see whether we know that this template will be
16313      instantiated in some other file, as with "extern template"
16314      extension.  */
16315   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
16316
16317   /* In general, we do not instantiate such templates.  */
16318   if (external_p && !always_instantiate_p (d))
16319     return d;
16320
16321   gen_tmpl = most_general_template (tmpl);
16322   gen_args = DECL_TI_ARGS (d);
16323
16324   if (tmpl != gen_tmpl)
16325     /* We should already have the extra args.  */
16326     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
16327                 == TMPL_ARGS_DEPTH (gen_args));
16328   /* And what's in the hash table should match D.  */
16329   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
16330               || spec == NULL_TREE);
16331
16332   /* This needs to happen before any tsubsting.  */
16333   if (! push_tinst_level (d))
16334     return d;
16335
16336   timevar_push (TV_PARSE);
16337
16338   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
16339      for the instantiation.  */
16340   td = template_for_substitution (d);
16341   code_pattern = DECL_TEMPLATE_RESULT (td);
16342
16343   /* We should never be trying to instantiate a member of a class
16344      template or partial specialization.  */
16345   gcc_assert (d != code_pattern);
16346
16347   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
16348       || DECL_TEMPLATE_SPECIALIZATION (td))
16349     /* In the case of a friend template whose definition is provided
16350        outside the class, we may have too many arguments.  Drop the
16351        ones we don't need.  The same is true for specializations.  */
16352     args = get_innermost_template_args
16353       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
16354   else
16355     args = gen_args;
16356
16357   if (TREE_CODE (d) == FUNCTION_DECL)
16358     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
16359   else
16360     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
16361
16362   /* We may be in the middle of deferred access check.  Disable it now.  */
16363   push_deferring_access_checks (dk_no_deferred);
16364
16365   /* Unless an explicit instantiation directive has already determined
16366      the linkage of D, remember that a definition is available for
16367      this entity.  */
16368   if (pattern_defined
16369       && !DECL_INTERFACE_KNOWN (d)
16370       && !DECL_NOT_REALLY_EXTERN (d))
16371     mark_definable (d);
16372
16373   input_location = DECL_SOURCE_LOCATION (d);
16374
16375   /* If D is a member of an explicitly instantiated class template,
16376      and no definition is available, treat it like an implicit
16377      instantiation.  */
16378   if (!pattern_defined && expl_inst_class_mem_p
16379       && DECL_EXPLICIT_INSTANTIATION (d))
16380     {
16381       DECL_NOT_REALLY_EXTERN (d) = 0;
16382       DECL_INTERFACE_KNOWN (d) = 0;
16383       SET_DECL_IMPLICIT_INSTANTIATION (d);
16384     }
16385
16386   /* Recheck the substitutions to obtain any warning messages
16387      about ignoring cv qualifiers.  Don't do this for artificial decls,
16388      as it breaks the context-sensitive substitution for lambda op(). */
16389   if (!defer_ok && !DECL_ARTIFICIAL (d))
16390     {
16391       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
16392       tree type = TREE_TYPE (gen);
16393
16394       /* Make sure that we can see identifiers, and compute access
16395          correctly.  D is already the target FUNCTION_DECL with the
16396          right context.  */
16397       push_access_scope (d);
16398
16399       if (TREE_CODE (gen) == FUNCTION_DECL)
16400         {
16401           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
16402           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
16403                                           d);
16404           /* Don't simply tsubst the function type, as that will give
16405              duplicate warnings about poor parameter qualifications.
16406              The function arguments are the same as the decl_arguments
16407              without the top level cv qualifiers.  */
16408           type = TREE_TYPE (type);
16409         }
16410       tsubst (type, gen_args, tf_warning_or_error, d);
16411
16412       pop_access_scope (d);
16413     }
16414
16415   /* Defer all other templates, unless we have been explicitly
16416      forbidden from doing so.  */
16417   if (/* If there is no definition, we cannot instantiate the
16418          template.  */
16419       ! pattern_defined
16420       /* If it's OK to postpone instantiation, do so.  */
16421       || defer_ok
16422       /* If this is a static data member that will be defined
16423          elsewhere, we don't want to instantiate the entire data
16424          member, but we do want to instantiate the initializer so that
16425          we can substitute that elsewhere.  */
16426       || (external_p && TREE_CODE (d) == VAR_DECL))
16427     {
16428       /* The definition of the static data member is now required so
16429          we must substitute the initializer.  */
16430       if (TREE_CODE (d) == VAR_DECL
16431           && !DECL_INITIAL (d)
16432           && DECL_INITIAL (code_pattern))
16433         {
16434           tree ns;
16435           tree init;
16436
16437           ns = decl_namespace_context (d);
16438           push_nested_namespace (ns);
16439           push_nested_class (DECL_CONTEXT (d));
16440           init = tsubst_expr (DECL_INITIAL (code_pattern),
16441                               args,
16442                               tf_warning_or_error, NULL_TREE,
16443                               /*integral_constant_expression_p=*/false);
16444           cp_finish_decl (d, init, /*init_const_expr_p=*/false,
16445                           /*asmspec_tree=*/NULL_TREE,
16446                           LOOKUP_ONLYCONVERTING);
16447           pop_nested_class ();
16448           pop_nested_namespace (ns);
16449         }
16450
16451       /* We restore the source position here because it's used by
16452          add_pending_template.  */
16453       input_location = saved_loc;
16454
16455       if (at_eof && !pattern_defined
16456           && DECL_EXPLICIT_INSTANTIATION (d)
16457           && DECL_NOT_REALLY_EXTERN (d))
16458         /* [temp.explicit]
16459
16460            The definition of a non-exported function template, a
16461            non-exported member function template, or a non-exported
16462            member function or static data member of a class template
16463            shall be present in every translation unit in which it is
16464            explicitly instantiated.  */
16465         permerror (input_location,  "explicit instantiation of %qD "
16466                    "but no definition available", d);
16467
16468       /* ??? Historically, we have instantiated inline functions, even
16469          when marked as "extern template".  */
16470       if (!(external_p && TREE_CODE (d) == VAR_DECL))
16471         add_pending_template (d);
16472       goto out;
16473     }
16474   /* Tell the repository that D is available in this translation unit
16475      -- and see if it is supposed to be instantiated here.  */
16476   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
16477     {
16478       /* In a PCH file, despite the fact that the repository hasn't
16479          requested instantiation in the PCH it is still possible that
16480          an instantiation will be required in a file that includes the
16481          PCH.  */
16482       if (pch_file)
16483         add_pending_template (d);
16484       /* Instantiate inline functions so that the inliner can do its
16485          job, even though we'll not be emitting a copy of this
16486          function.  */
16487       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
16488         goto out;
16489     }
16490
16491   need_push = !cfun || !global_bindings_p ();
16492   if (need_push)
16493     push_to_top_level ();
16494
16495   /* Mark D as instantiated so that recursive calls to
16496      instantiate_decl do not try to instantiate it again.  */
16497   DECL_TEMPLATE_INSTANTIATED (d) = 1;
16498
16499   /* Regenerate the declaration in case the template has been modified
16500      by a subsequent redeclaration.  */
16501   regenerate_decl_from_template (d, td);
16502
16503   /* We already set the file and line above.  Reset them now in case
16504      they changed as a result of calling regenerate_decl_from_template.  */
16505   input_location = DECL_SOURCE_LOCATION (d);
16506
16507   if (TREE_CODE (d) == VAR_DECL)
16508     {
16509       tree init;
16510
16511       /* Clear out DECL_RTL; whatever was there before may not be right
16512          since we've reset the type of the declaration.  */
16513       SET_DECL_RTL (d, NULL_RTX);
16514       DECL_IN_AGGR_P (d) = 0;
16515
16516       /* The initializer is placed in DECL_INITIAL by
16517          regenerate_decl_from_template.  Pull it out so that
16518          cp_finish_decl can process it.  */
16519       init = DECL_INITIAL (d);
16520       DECL_INITIAL (d) = NULL_TREE;
16521       DECL_INITIALIZED_P (d) = 0;
16522
16523       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
16524          initializer.  That function will defer actual emission until
16525          we have a chance to determine linkage.  */
16526       DECL_EXTERNAL (d) = 0;
16527
16528       /* Enter the scope of D so that access-checking works correctly.  */
16529       push_nested_class (DECL_CONTEXT (d));
16530       cp_finish_decl (d, init, false, NULL_TREE, 0);
16531       pop_nested_class ();
16532     }
16533   else if (TREE_CODE (d) == FUNCTION_DECL)
16534     {
16535       htab_t saved_local_specializations;
16536       tree subst_decl;
16537       tree tmpl_parm;
16538       tree spec_parm;
16539
16540       /* Save away the current list, in case we are instantiating one
16541          template from within the body of another.  */
16542       saved_local_specializations = local_specializations;
16543
16544       /* Set up the list of local specializations.  */
16545       local_specializations = htab_create (37,
16546                                            hash_local_specialization,
16547                                            eq_local_specializations,
16548                                            NULL);
16549
16550       /* Set up context.  */
16551       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
16552
16553       /* Create substitution entries for the parameters.  */
16554       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
16555       tmpl_parm = DECL_ARGUMENTS (subst_decl);
16556       spec_parm = DECL_ARGUMENTS (d);
16557       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
16558         {
16559           register_local_specialization (spec_parm, tmpl_parm);
16560           spec_parm = skip_artificial_parms_for (d, spec_parm);
16561           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
16562         }
16563       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
16564         {
16565           register_local_specialization (spec_parm, tmpl_parm);
16566           tmpl_parm = TREE_CHAIN (tmpl_parm);
16567           spec_parm = TREE_CHAIN (spec_parm);
16568         }
16569       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
16570         {
16571           /* Register the (value) argument pack as a specialization of
16572              TMPL_PARM, then move on.  */
16573           tree argpack = make_fnparm_pack (spec_parm);
16574           register_local_specialization (argpack, tmpl_parm);
16575           tmpl_parm = TREE_CHAIN (tmpl_parm);
16576           spec_parm = NULL_TREE;
16577         }
16578       gcc_assert (!spec_parm);
16579
16580       /* Substitute into the body of the function.  */
16581       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
16582                    tf_warning_or_error, tmpl,
16583                    /*integral_constant_expression_p=*/false);
16584
16585       /* Set the current input_location to the end of the function
16586          so that finish_function knows where we are.  */
16587       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
16588
16589       /* We don't need the local specializations any more.  */
16590       htab_delete (local_specializations);
16591       local_specializations = saved_local_specializations;
16592
16593       /* Finish the function.  */
16594       d = finish_function (0);
16595       expand_or_defer_fn (d);
16596     }
16597
16598   /* We're not deferring instantiation any more.  */
16599   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
16600
16601   if (need_push)
16602     pop_from_top_level ();
16603
16604 out:
16605   input_location = saved_loc;
16606   pop_deferring_access_checks ();
16607   pop_tinst_level ();
16608
16609   timevar_pop (TV_PARSE);
16610
16611   return d;
16612 }
16613
16614 /* Run through the list of templates that we wish we could
16615    instantiate, and instantiate any we can.  RETRIES is the
16616    number of times we retry pending template instantiation.  */
16617
16618 void
16619 instantiate_pending_templates (int retries)
16620 {
16621   int reconsider;
16622   location_t saved_loc = input_location;
16623
16624   /* Instantiating templates may trigger vtable generation.  This in turn
16625      may require further template instantiations.  We place a limit here
16626      to avoid infinite loop.  */
16627   if (pending_templates && retries >= max_tinst_depth)
16628     {
16629       tree decl = pending_templates->tinst->decl;
16630
16631       error ("template instantiation depth exceeds maximum of %d"
16632              " instantiating %q+D, possibly from virtual table generation"
16633              " (use -ftemplate-depth-NN to increase the maximum)",
16634              max_tinst_depth, decl);
16635       if (TREE_CODE (decl) == FUNCTION_DECL)
16636         /* Pretend that we defined it.  */
16637         DECL_INITIAL (decl) = error_mark_node;
16638       return;
16639     }
16640
16641   do
16642     {
16643       struct pending_template **t = &pending_templates;
16644       struct pending_template *last = NULL;
16645       reconsider = 0;
16646       while (*t)
16647         {
16648           tree instantiation = reopen_tinst_level ((*t)->tinst);
16649           bool complete = false;
16650
16651           if (TYPE_P (instantiation))
16652             {
16653               tree fn;
16654
16655               if (!COMPLETE_TYPE_P (instantiation))
16656                 {
16657                   instantiate_class_template (instantiation);
16658                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
16659                     for (fn = TYPE_METHODS (instantiation);
16660                          fn;
16661                          fn = TREE_CHAIN (fn))
16662                       if (! DECL_ARTIFICIAL (fn))
16663                         instantiate_decl (fn,
16664                                           /*defer_ok=*/0,
16665                                           /*expl_inst_class_mem_p=*/false);
16666                   if (COMPLETE_TYPE_P (instantiation))
16667                     reconsider = 1;
16668                 }
16669
16670               complete = COMPLETE_TYPE_P (instantiation);
16671             }
16672           else
16673             {
16674               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
16675                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
16676                 {
16677                   instantiation
16678                     = instantiate_decl (instantiation,
16679                                         /*defer_ok=*/0,
16680                                         /*expl_inst_class_mem_p=*/false);
16681                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
16682                     reconsider = 1;
16683                 }
16684
16685               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
16686                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
16687             }
16688
16689           if (complete)
16690             /* If INSTANTIATION has been instantiated, then we don't
16691                need to consider it again in the future.  */
16692             *t = (*t)->next;
16693           else
16694             {
16695               last = *t;
16696               t = &(*t)->next;
16697             }
16698           tinst_depth = 0;
16699           current_tinst_level = NULL;
16700         }
16701       last_pending_template = last;
16702     }
16703   while (reconsider);
16704
16705   input_location = saved_loc;
16706 }
16707
16708 /* Substitute ARGVEC into T, which is a list of initializers for
16709    either base class or a non-static data member.  The TREE_PURPOSEs
16710    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
16711    instantiate_decl.  */
16712
16713 static tree
16714 tsubst_initializer_list (tree t, tree argvec)
16715 {
16716   tree inits = NULL_TREE;
16717
16718   for (; t; t = TREE_CHAIN (t))
16719     {
16720       tree decl;
16721       tree init;
16722       tree expanded_bases = NULL_TREE;
16723       tree expanded_arguments = NULL_TREE;
16724       int i, len = 1;
16725
16726       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
16727         {
16728           tree expr;
16729           tree arg;
16730
16731           /* Expand the base class expansion type into separate base
16732              classes.  */
16733           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
16734                                                  tf_warning_or_error,
16735                                                  NULL_TREE);
16736           if (expanded_bases == error_mark_node)
16737             continue;
16738           
16739           /* We'll be building separate TREE_LISTs of arguments for
16740              each base.  */
16741           len = TREE_VEC_LENGTH (expanded_bases);
16742           expanded_arguments = make_tree_vec (len);
16743           for (i = 0; i < len; i++)
16744             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
16745
16746           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
16747              expand each argument in the TREE_VALUE of t.  */
16748           expr = make_node (EXPR_PACK_EXPANSION);
16749           PACK_EXPANSION_PARAMETER_PACKS (expr) =
16750             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
16751
16752           if (TREE_VALUE (t) == void_type_node)
16753             /* VOID_TYPE_NODE is used to indicate
16754                value-initialization.  */
16755             {
16756               for (i = 0; i < len; i++)
16757                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
16758             }
16759           else
16760             {
16761               /* Substitute parameter packs into each argument in the
16762                  TREE_LIST.  */
16763               in_base_initializer = 1;
16764               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
16765                 {
16766                   tree expanded_exprs;
16767
16768                   /* Expand the argument.  */
16769                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
16770                   expanded_exprs 
16771                     = tsubst_pack_expansion (expr, argvec,
16772                                              tf_warning_or_error,
16773                                              NULL_TREE);
16774                   if (expanded_exprs == error_mark_node)
16775                     continue;
16776
16777                   /* Prepend each of the expanded expressions to the
16778                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
16779                   for (i = 0; i < len; i++)
16780                     {
16781                       TREE_VEC_ELT (expanded_arguments, i) = 
16782                         tree_cons (NULL_TREE, 
16783                                    TREE_VEC_ELT (expanded_exprs, i),
16784                                    TREE_VEC_ELT (expanded_arguments, i));
16785                     }
16786                 }
16787               in_base_initializer = 0;
16788
16789               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
16790                  since we built them backwards.  */
16791               for (i = 0; i < len; i++)
16792                 {
16793                   TREE_VEC_ELT (expanded_arguments, i) = 
16794                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
16795                 }
16796             }
16797         }
16798
16799       for (i = 0; i < len; ++i)
16800         {
16801           if (expanded_bases)
16802             {
16803               decl = TREE_VEC_ELT (expanded_bases, i);
16804               decl = expand_member_init (decl);
16805               init = TREE_VEC_ELT (expanded_arguments, i);
16806             }
16807           else
16808             {
16809               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
16810                                   tf_warning_or_error, NULL_TREE);
16811
16812               decl = expand_member_init (decl);
16813               if (decl && !DECL_P (decl))
16814                 in_base_initializer = 1;
16815
16816               init = tsubst_expr (TREE_VALUE (t), argvec, 
16817                                   tf_warning_or_error, NULL_TREE,
16818                                   /*integral_constant_expression_p=*/false);
16819               in_base_initializer = 0;
16820             }
16821
16822           if (decl)
16823             {
16824               init = build_tree_list (decl, init);
16825               TREE_CHAIN (init) = inits;
16826               inits = init;
16827             }
16828         }
16829     }
16830   return inits;
16831 }
16832
16833 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
16834
16835 static void
16836 set_current_access_from_decl (tree decl)
16837 {
16838   if (TREE_PRIVATE (decl))
16839     current_access_specifier = access_private_node;
16840   else if (TREE_PROTECTED (decl))
16841     current_access_specifier = access_protected_node;
16842   else
16843     current_access_specifier = access_public_node;
16844 }
16845
16846 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
16847    is the instantiation (which should have been created with
16848    start_enum) and ARGS are the template arguments to use.  */
16849
16850 static void
16851 tsubst_enum (tree tag, tree newtag, tree args)
16852 {
16853   tree e;
16854
16855   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
16856     {
16857       tree value;
16858       tree decl;
16859
16860       decl = TREE_VALUE (e);
16861       /* Note that in a template enum, the TREE_VALUE is the
16862          CONST_DECL, not the corresponding INTEGER_CST.  */
16863       value = tsubst_expr (DECL_INITIAL (decl),
16864                            args, tf_warning_or_error, NULL_TREE,
16865                            /*integral_constant_expression_p=*/true);
16866
16867       /* Give this enumeration constant the correct access.  */
16868       set_current_access_from_decl (decl);
16869
16870       /* Actually build the enumerator itself.  */
16871       build_enumerator (DECL_NAME (decl), value, newtag);
16872     }
16873
16874   finish_enum (newtag);
16875   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
16876     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
16877 }
16878
16879 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
16880    its type -- but without substituting the innermost set of template
16881    arguments.  So, innermost set of template parameters will appear in
16882    the type.  */
16883
16884 tree
16885 get_mostly_instantiated_function_type (tree decl)
16886 {
16887   tree fn_type;
16888   tree tmpl;
16889   tree targs;
16890   tree tparms;
16891   int parm_depth;
16892
16893   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
16894   targs = DECL_TI_ARGS (decl);
16895   tparms = DECL_TEMPLATE_PARMS (tmpl);
16896   parm_depth = TMPL_PARMS_DEPTH (tparms);
16897
16898   /* There should be as many levels of arguments as there are levels
16899      of parameters.  */
16900   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
16901
16902   fn_type = TREE_TYPE (tmpl);
16903
16904   if (parm_depth == 1)
16905     /* No substitution is necessary.  */
16906     ;
16907   else
16908     {
16909       int i, save_access_control;
16910       tree partial_args;
16911
16912       /* Replace the innermost level of the TARGS with NULL_TREEs to
16913          let tsubst know not to substitute for those parameters.  */
16914       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
16915       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
16916         SET_TMPL_ARGS_LEVEL (partial_args, i,
16917                              TMPL_ARGS_LEVEL (targs, i));
16918       SET_TMPL_ARGS_LEVEL (partial_args,
16919                            TMPL_ARGS_DEPTH (targs),
16920                            make_tree_vec (DECL_NTPARMS (tmpl)));
16921
16922       /* Disable access control as this function is used only during
16923          name-mangling.  */
16924       save_access_control = flag_access_control;
16925       flag_access_control = 0;
16926
16927       ++processing_template_decl;
16928       /* Now, do the (partial) substitution to figure out the
16929          appropriate function type.  */
16930       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
16931       --processing_template_decl;
16932
16933       /* Substitute into the template parameters to obtain the real
16934          innermost set of parameters.  This step is important if the
16935          innermost set of template parameters contains value
16936          parameters whose types depend on outer template parameters.  */
16937       TREE_VEC_LENGTH (partial_args)--;
16938       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
16939
16940       flag_access_control = save_access_control;
16941     }
16942
16943   return fn_type;
16944 }
16945
16946 /* Return truthvalue if we're processing a template different from
16947    the last one involved in diagnostics.  */
16948 int
16949 problematic_instantiation_changed (void)
16950 {
16951   return last_template_error_tick != tinst_level_tick;
16952 }
16953
16954 /* Remember current template involved in diagnostics.  */
16955 void
16956 record_last_problematic_instantiation (void)
16957 {
16958   last_template_error_tick = tinst_level_tick;
16959 }
16960
16961 struct tinst_level *
16962 current_instantiation (void)
16963 {
16964   return current_tinst_level;
16965 }
16966
16967 /* [temp.param] Check that template non-type parm TYPE is of an allowable
16968    type. Return zero for ok, nonzero for disallowed. Issue error and
16969    warning messages under control of COMPLAIN.  */
16970
16971 static int
16972 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
16973 {
16974   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
16975     return 0;
16976   else if (POINTER_TYPE_P (type))
16977     return 0;
16978   else if (TYPE_PTR_TO_MEMBER_P (type))
16979     return 0;
16980   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
16981     return 0;
16982   else if (TREE_CODE (type) == TYPENAME_TYPE)
16983     return 0;
16984
16985   if (complain & tf_error)
16986     error ("%q#T is not a valid type for a template constant parameter", type);
16987   return 1;
16988 }
16989
16990 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
16991    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
16992
16993 static bool
16994 dependent_type_p_r (tree type)
16995 {
16996   tree scope;
16997
16998   /* [temp.dep.type]
16999
17000      A type is dependent if it is:
17001
17002      -- a template parameter. Template template parameters are types
17003         for us (since TYPE_P holds true for them) so we handle
17004         them here.  */
17005   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
17006       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
17007     return true;
17008   /* -- a qualified-id with a nested-name-specifier which contains a
17009         class-name that names a dependent type or whose unqualified-id
17010         names a dependent type.  */
17011   if (TREE_CODE (type) == TYPENAME_TYPE)
17012     return true;
17013   /* -- a cv-qualified type where the cv-unqualified type is
17014         dependent.  */
17015   type = TYPE_MAIN_VARIANT (type);
17016   /* -- a compound type constructed from any dependent type.  */
17017   if (TYPE_PTR_TO_MEMBER_P (type))
17018     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
17019             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
17020                                            (type)));
17021   else if (TREE_CODE (type) == POINTER_TYPE
17022            || TREE_CODE (type) == REFERENCE_TYPE)
17023     return dependent_type_p (TREE_TYPE (type));
17024   else if (TREE_CODE (type) == FUNCTION_TYPE
17025            || TREE_CODE (type) == METHOD_TYPE)
17026     {
17027       tree arg_type;
17028
17029       if (dependent_type_p (TREE_TYPE (type)))
17030         return true;
17031       for (arg_type = TYPE_ARG_TYPES (type);
17032            arg_type;
17033            arg_type = TREE_CHAIN (arg_type))
17034         if (dependent_type_p (TREE_VALUE (arg_type)))
17035           return true;
17036       return false;
17037     }
17038   /* -- an array type constructed from any dependent type or whose
17039         size is specified by a constant expression that is
17040         value-dependent.  */
17041   if (TREE_CODE (type) == ARRAY_TYPE)
17042     {
17043       if (TYPE_DOMAIN (type)
17044           && dependent_type_p (TYPE_DOMAIN (type)))
17045         return true;
17046       return dependent_type_p (TREE_TYPE (type));
17047     }
17048   else if (TREE_CODE (type) == INTEGER_TYPE
17049            && !TREE_CONSTANT (TYPE_MAX_VALUE (type)))
17050     {
17051       /* If this is the TYPE_DOMAIN of an array type, consider it
17052          dependent.  We already checked for value-dependence in
17053          compute_array_index_type.  */
17054       return type_dependent_expression_p (TYPE_MAX_VALUE (type));
17055     }
17056
17057   /* -- a template-id in which either the template name is a template
17058      parameter ...  */
17059   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
17060     return true;
17061   /* ... or any of the template arguments is a dependent type or
17062         an expression that is type-dependent or value-dependent.  */
17063   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
17064            && (any_dependent_template_arguments_p
17065                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
17066     return true;
17067
17068   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
17069      argument of the `typeof' expression is not type-dependent, then
17070      it should already been have resolved.  */
17071   if (TREE_CODE (type) == TYPEOF_TYPE
17072       || TREE_CODE (type) == DECLTYPE_TYPE)
17073     return true;
17074
17075   /* A template argument pack is dependent if any of its packed
17076      arguments are.  */
17077   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
17078     {
17079       tree args = ARGUMENT_PACK_ARGS (type);
17080       int i, len = TREE_VEC_LENGTH (args);
17081       for (i = 0; i < len; ++i)
17082         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
17083           return true;
17084     }
17085
17086   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
17087      be template parameters.  */
17088   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
17089     return true;
17090
17091   /* The standard does not specifically mention types that are local
17092      to template functions or local classes, but they should be
17093      considered dependent too.  For example:
17094
17095        template <int I> void f() {
17096          enum E { a = I };
17097          S<sizeof (E)> s;
17098        }
17099
17100      The size of `E' cannot be known until the value of `I' has been
17101      determined.  Therefore, `E' must be considered dependent.  */
17102   scope = TYPE_CONTEXT (type);
17103   if (scope && TYPE_P (scope))
17104     return dependent_type_p (scope);
17105   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
17106     return type_dependent_expression_p (scope);
17107
17108   /* Other types are non-dependent.  */
17109   return false;
17110 }
17111
17112 /* Returns TRUE if TYPE is dependent, in the sense of
17113    [temp.dep.type].  */
17114
17115 bool
17116 dependent_type_p (tree type)
17117 {
17118   /* If there are no template parameters in scope, then there can't be
17119      any dependent types.  */
17120   if (!processing_template_decl)
17121     {
17122       /* If we are not processing a template, then nobody should be
17123          providing us with a dependent type.  */
17124       gcc_assert (type);
17125       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
17126       return false;
17127     }
17128
17129   /* If the type is NULL, we have not computed a type for the entity
17130      in question; in that case, the type is dependent.  */
17131   if (!type)
17132     return true;
17133
17134   /* Erroneous types can be considered non-dependent.  */
17135   if (type == error_mark_node)
17136     return false;
17137
17138   /* If we have not already computed the appropriate value for TYPE,
17139      do so now.  */
17140   if (!TYPE_DEPENDENT_P_VALID (type))
17141     {
17142       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
17143       TYPE_DEPENDENT_P_VALID (type) = 1;
17144     }
17145
17146   return TYPE_DEPENDENT_P (type);
17147 }
17148
17149 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
17150    lookup.  In other words, a dependent type that is not the current
17151    instantiation.  */
17152
17153 bool
17154 dependent_scope_p (tree scope)
17155 {
17156   return (scope && TYPE_P (scope) && dependent_type_p (scope)
17157           && !currently_open_class (scope));
17158 }
17159
17160 /* Returns TRUE if EXPRESSION is dependent, according to CRITERION.  */
17161
17162 static bool
17163 dependent_scope_ref_p (tree expression, bool criterion (tree))
17164 {
17165   tree scope;
17166   tree name;
17167
17168   gcc_assert (TREE_CODE (expression) == SCOPE_REF);
17169
17170   if (!TYPE_P (TREE_OPERAND (expression, 0)))
17171     return true;
17172
17173   scope = TREE_OPERAND (expression, 0);
17174   name = TREE_OPERAND (expression, 1);
17175
17176   /* [temp.dep.expr]
17177
17178      An id-expression is type-dependent if it contains a
17179      nested-name-specifier that contains a class-name that names a
17180      dependent type.  */
17181   /* The suggested resolution to Core Issue 224 implies that if the
17182      qualifying type is the current class, then we must peek
17183      inside it.  */
17184   if (DECL_P (name)
17185       && currently_open_class (scope)
17186       && !criterion (name))
17187     return false;
17188   if (dependent_type_p (scope))
17189     return true;
17190
17191   return false;
17192 }
17193
17194 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
17195    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
17196    expression.  */
17197
17198 bool
17199 value_dependent_expression_p (tree expression)
17200 {
17201   if (!processing_template_decl)
17202     return false;
17203
17204   /* A name declared with a dependent type.  */
17205   if (DECL_P (expression) && type_dependent_expression_p (expression))
17206     return true;
17207
17208   switch (TREE_CODE (expression))
17209     {
17210     case IDENTIFIER_NODE:
17211       /* A name that has not been looked up -- must be dependent.  */
17212       return true;
17213
17214     case TEMPLATE_PARM_INDEX:
17215       /* A non-type template parm.  */
17216       return true;
17217
17218     case CONST_DECL:
17219       /* A non-type template parm.  */
17220       if (DECL_TEMPLATE_PARM_P (expression))
17221         return true;
17222       return value_dependent_expression_p (DECL_INITIAL (expression));
17223
17224     case VAR_DECL:
17225        /* A constant with integral or enumeration type and is initialized
17226           with an expression that is value-dependent.  */
17227       if (DECL_INITIAL (expression)
17228           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
17229           && value_dependent_expression_p (DECL_INITIAL (expression)))
17230         return true;
17231       return false;
17232
17233     case DYNAMIC_CAST_EXPR:
17234     case STATIC_CAST_EXPR:
17235     case CONST_CAST_EXPR:
17236     case REINTERPRET_CAST_EXPR:
17237     case CAST_EXPR:
17238       /* These expressions are value-dependent if the type to which
17239          the cast occurs is dependent or the expression being casted
17240          is value-dependent.  */
17241       {
17242         tree type = TREE_TYPE (expression);
17243
17244         if (dependent_type_p (type))
17245           return true;
17246
17247         /* A functional cast has a list of operands.  */
17248         expression = TREE_OPERAND (expression, 0);
17249         if (!expression)
17250           {
17251             /* If there are no operands, it must be an expression such
17252                as "int()". This should not happen for aggregate types
17253                because it would form non-constant expressions.  */
17254             gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
17255
17256             return false;
17257           }
17258
17259         if (TREE_CODE (expression) == TREE_LIST)
17260           return any_value_dependent_elements_p (expression);
17261
17262         return value_dependent_expression_p (expression);
17263       }
17264
17265     case SIZEOF_EXPR:
17266     case ALIGNOF_EXPR:
17267       /* A `sizeof' expression is value-dependent if the operand is
17268          type-dependent or is a pack expansion.  */
17269       expression = TREE_OPERAND (expression, 0);
17270       if (PACK_EXPANSION_P (expression))
17271         return true;
17272       else if (TYPE_P (expression))
17273         return dependent_type_p (expression);
17274       return type_dependent_expression_p (expression);
17275
17276     case SCOPE_REF:
17277       return dependent_scope_ref_p (expression, value_dependent_expression_p);
17278
17279     case COMPONENT_REF:
17280       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
17281               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
17282
17283     case CALL_EXPR:
17284       /* A CALL_EXPR may appear in a constant expression if it is a
17285          call to a builtin function, e.g., __builtin_constant_p.  All
17286          such calls are value-dependent.  */
17287       return true;
17288
17289     case NONTYPE_ARGUMENT_PACK:
17290       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
17291          is value-dependent.  */
17292       {
17293         tree values = ARGUMENT_PACK_ARGS (expression);
17294         int i, len = TREE_VEC_LENGTH (values);
17295         
17296         for (i = 0; i < len; ++i)
17297           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
17298             return true;
17299         
17300         return false;
17301       }
17302
17303     case TRAIT_EXPR:
17304       {
17305         tree type2 = TRAIT_EXPR_TYPE2 (expression);
17306         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
17307                 || (type2 ? dependent_type_p (type2) : false));
17308       }
17309
17310     case MODOP_EXPR:
17311       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
17312               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
17313
17314     default:
17315       /* A constant expression is value-dependent if any subexpression is
17316          value-dependent.  */
17317       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
17318         {
17319         case tcc_reference:
17320         case tcc_unary:
17321           return (value_dependent_expression_p
17322                   (TREE_OPERAND (expression, 0)));
17323
17324         case tcc_comparison:
17325         case tcc_binary:
17326           return ((value_dependent_expression_p
17327                    (TREE_OPERAND (expression, 0)))
17328                   || (value_dependent_expression_p
17329                       (TREE_OPERAND (expression, 1))));
17330
17331         case tcc_expression:
17332         case tcc_vl_exp:
17333           {
17334             int i;
17335             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
17336               /* In some cases, some of the operands may be missing.
17337                  (For example, in the case of PREDECREMENT_EXPR, the
17338                  amount to increment by may be missing.)  That doesn't
17339                  make the expression dependent.  */
17340               if (TREE_OPERAND (expression, i)
17341                   && (value_dependent_expression_p
17342                       (TREE_OPERAND (expression, i))))
17343                 return true;
17344             return false;
17345           }
17346
17347         default:
17348           break;
17349         }
17350     }
17351
17352   /* The expression is not value-dependent.  */
17353   return false;
17354 }
17355
17356 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
17357    [temp.dep.expr].  */
17358
17359 bool
17360 type_dependent_expression_p (tree expression)
17361 {
17362   if (!processing_template_decl)
17363     return false;
17364
17365   if (expression == error_mark_node)
17366     return false;
17367
17368   /* An unresolved name is always dependent.  */
17369   if (TREE_CODE (expression) == IDENTIFIER_NODE
17370       || TREE_CODE (expression) == USING_DECL)
17371     return true;
17372
17373   /* Some expression forms are never type-dependent.  */
17374   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
17375       || TREE_CODE (expression) == SIZEOF_EXPR
17376       || TREE_CODE (expression) == ALIGNOF_EXPR
17377       || TREE_CODE (expression) == TRAIT_EXPR
17378       || TREE_CODE (expression) == TYPEID_EXPR
17379       || TREE_CODE (expression) == DELETE_EXPR
17380       || TREE_CODE (expression) == VEC_DELETE_EXPR
17381       || TREE_CODE (expression) == THROW_EXPR)
17382     return false;
17383
17384   /* The types of these expressions depends only on the type to which
17385      the cast occurs.  */
17386   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
17387       || TREE_CODE (expression) == STATIC_CAST_EXPR
17388       || TREE_CODE (expression) == CONST_CAST_EXPR
17389       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
17390       || TREE_CODE (expression) == CAST_EXPR)
17391     return dependent_type_p (TREE_TYPE (expression));
17392
17393   /* The types of these expressions depends only on the type created
17394      by the expression.  */
17395   if (TREE_CODE (expression) == NEW_EXPR
17396       || TREE_CODE (expression) == VEC_NEW_EXPR)
17397     {
17398       /* For NEW_EXPR tree nodes created inside a template, either
17399          the object type itself or a TREE_LIST may appear as the
17400          operand 1.  */
17401       tree type = TREE_OPERAND (expression, 1);
17402       if (TREE_CODE (type) == TREE_LIST)
17403         /* This is an array type.  We need to check array dimensions
17404            as well.  */
17405         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
17406                || value_dependent_expression_p
17407                     (TREE_OPERAND (TREE_VALUE (type), 1));
17408       else
17409         return dependent_type_p (type);
17410     }
17411
17412   if (TREE_CODE (expression) == SCOPE_REF
17413       && dependent_scope_ref_p (expression,
17414                                 type_dependent_expression_p))
17415     return true;
17416
17417   if (TREE_CODE (expression) == FUNCTION_DECL
17418       && DECL_LANG_SPECIFIC (expression)
17419       && DECL_TEMPLATE_INFO (expression)
17420       && (any_dependent_template_arguments_p
17421           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
17422     return true;
17423
17424   if (TREE_CODE (expression) == TEMPLATE_DECL
17425       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
17426     return false;
17427
17428   if (TREE_CODE (expression) == STMT_EXPR)
17429     expression = stmt_expr_value_expr (expression);
17430
17431   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
17432     {
17433       tree elt;
17434       unsigned i;
17435
17436       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
17437         {
17438           if (type_dependent_expression_p (elt))
17439             return true;
17440         }
17441       return false;
17442     }
17443
17444   if (TREE_TYPE (expression) == unknown_type_node)
17445     {
17446       if (TREE_CODE (expression) == ADDR_EXPR)
17447         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
17448       if (TREE_CODE (expression) == COMPONENT_REF
17449           || TREE_CODE (expression) == OFFSET_REF)
17450         {
17451           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
17452             return true;
17453           expression = TREE_OPERAND (expression, 1);
17454           if (TREE_CODE (expression) == IDENTIFIER_NODE)
17455             return false;
17456         }
17457       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
17458       if (TREE_CODE (expression) == SCOPE_REF)
17459         return false;
17460
17461       if (TREE_CODE (expression) == BASELINK)
17462         expression = BASELINK_FUNCTIONS (expression);
17463
17464       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
17465         {
17466           if (any_dependent_template_arguments_p
17467               (TREE_OPERAND (expression, 1)))
17468             return true;
17469           expression = TREE_OPERAND (expression, 0);
17470         }
17471       gcc_assert (TREE_CODE (expression) == OVERLOAD
17472                   || TREE_CODE (expression) == FUNCTION_DECL);
17473
17474       while (expression)
17475         {
17476           if (type_dependent_expression_p (OVL_CURRENT (expression)))
17477             return true;
17478           expression = OVL_NEXT (expression);
17479         }
17480       return false;
17481     }
17482
17483   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
17484
17485   return (dependent_type_p (TREE_TYPE (expression)));
17486 }
17487
17488 /* Like type_dependent_expression_p, but it also works while not processing
17489    a template definition, i.e. during substitution or mangling.  */
17490
17491 bool
17492 type_dependent_expression_p_push (tree expr)
17493 {
17494   bool b;
17495   ++processing_template_decl;
17496   b = type_dependent_expression_p (expr);
17497   --processing_template_decl;
17498   return b;
17499 }
17500
17501 /* Returns TRUE if ARGS contains a type-dependent expression.  */
17502
17503 bool
17504 any_type_dependent_arguments_p (const VEC(tree,gc) *args)
17505 {
17506   unsigned int i;
17507   tree arg;
17508
17509   for (i = 0; VEC_iterate (tree, args, i, arg); ++i)
17510     {
17511       if (type_dependent_expression_p (arg))
17512         return true;
17513     }
17514   return false;
17515 }
17516
17517 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
17518    expressions) contains any value-dependent expressions.  */
17519
17520 bool
17521 any_value_dependent_elements_p (const_tree list)
17522 {
17523   for (; list; list = TREE_CHAIN (list))
17524     if (value_dependent_expression_p (TREE_VALUE (list)))
17525       return true;
17526
17527   return false;
17528 }
17529
17530 /* Returns TRUE if the ARG (a template argument) is dependent.  */
17531
17532 bool
17533 dependent_template_arg_p (tree arg)
17534 {
17535   if (!processing_template_decl)
17536     return false;
17537
17538   if (TREE_CODE (arg) == TEMPLATE_DECL
17539       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
17540     return dependent_template_p (arg);
17541   else if (ARGUMENT_PACK_P (arg))
17542     {
17543       tree args = ARGUMENT_PACK_ARGS (arg);
17544       int i, len = TREE_VEC_LENGTH (args);
17545       for (i = 0; i < len; ++i)
17546         {
17547           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
17548             return true;
17549         }
17550
17551       return false;
17552     }
17553   else if (TYPE_P (arg))
17554     return dependent_type_p (arg);
17555   else
17556     return (type_dependent_expression_p (arg)
17557             || value_dependent_expression_p (arg));
17558 }
17559
17560 /* Returns true if ARGS (a collection of template arguments) contains
17561    any types that require structural equality testing.  */
17562
17563 bool
17564 any_template_arguments_need_structural_equality_p (tree args)
17565 {
17566   int i;
17567   int j;
17568
17569   if (!args)
17570     return false;
17571   if (args == error_mark_node)
17572     return true;
17573
17574   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
17575     {
17576       tree level = TMPL_ARGS_LEVEL (args, i + 1);
17577       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
17578         {
17579           tree arg = TREE_VEC_ELT (level, j);
17580           tree packed_args = NULL_TREE;
17581           int k, len = 1;
17582
17583           if (ARGUMENT_PACK_P (arg))
17584             {
17585               /* Look inside the argument pack.  */
17586               packed_args = ARGUMENT_PACK_ARGS (arg);
17587               len = TREE_VEC_LENGTH (packed_args);
17588             }
17589
17590           for (k = 0; k < len; ++k)
17591             {
17592               if (packed_args)
17593                 arg = TREE_VEC_ELT (packed_args, k);
17594
17595               if (error_operand_p (arg))
17596                 return true;
17597               else if (TREE_CODE (arg) == TEMPLATE_DECL
17598                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
17599                 continue;
17600               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
17601                 return true;
17602               else if (!TYPE_P (arg) && TREE_TYPE (arg)
17603                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
17604                 return true;
17605             }
17606         }
17607     }
17608
17609   return false;
17610 }
17611
17612 /* Returns true if ARGS (a collection of template arguments) contains
17613    any dependent arguments.  */
17614
17615 bool
17616 any_dependent_template_arguments_p (const_tree args)
17617 {
17618   int i;
17619   int j;
17620
17621   if (!args)
17622     return false;
17623   if (args == error_mark_node)
17624     return true;
17625
17626   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
17627     {
17628       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
17629       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
17630         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
17631           return true;
17632     }
17633
17634   return false;
17635 }
17636
17637 /* Returns TRUE if the template TMPL is dependent.  */
17638
17639 bool
17640 dependent_template_p (tree tmpl)
17641 {
17642   if (TREE_CODE (tmpl) == OVERLOAD)
17643     {
17644       while (tmpl)
17645         {
17646           if (dependent_template_p (OVL_FUNCTION (tmpl)))
17647             return true;
17648           tmpl = OVL_CHAIN (tmpl);
17649         }
17650       return false;
17651     }
17652
17653   /* Template template parameters are dependent.  */
17654   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
17655       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
17656     return true;
17657   /* So are names that have not been looked up.  */
17658   if (TREE_CODE (tmpl) == SCOPE_REF
17659       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
17660     return true;
17661   /* So are member templates of dependent classes.  */
17662   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
17663     return dependent_type_p (DECL_CONTEXT (tmpl));
17664   return false;
17665 }
17666
17667 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
17668
17669 bool
17670 dependent_template_id_p (tree tmpl, tree args)
17671 {
17672   return (dependent_template_p (tmpl)
17673           || any_dependent_template_arguments_p (args));
17674 }
17675
17676 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
17677    is dependent.  */
17678
17679 bool
17680 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
17681 {
17682   int i;
17683
17684   if (!processing_template_decl)
17685     return false;
17686
17687   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
17688     {
17689       tree decl = TREE_VEC_ELT (declv, i);
17690       tree init = TREE_VEC_ELT (initv, i);
17691       tree cond = TREE_VEC_ELT (condv, i);
17692       tree incr = TREE_VEC_ELT (incrv, i);
17693
17694       if (type_dependent_expression_p (decl))
17695         return true;
17696
17697       if (init && type_dependent_expression_p (init))
17698         return true;
17699
17700       if (type_dependent_expression_p (cond))
17701         return true;
17702
17703       if (COMPARISON_CLASS_P (cond)
17704           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
17705               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
17706         return true;
17707
17708       if (TREE_CODE (incr) == MODOP_EXPR)
17709         {
17710           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
17711               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
17712             return true;
17713         }
17714       else if (type_dependent_expression_p (incr))
17715         return true;
17716       else if (TREE_CODE (incr) == MODIFY_EXPR)
17717         {
17718           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
17719             return true;
17720           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
17721             {
17722               tree t = TREE_OPERAND (incr, 1);
17723               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
17724                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
17725                 return true;
17726             }
17727         }
17728     }
17729
17730   return false;
17731 }
17732
17733 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
17734    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
17735    no such TYPE can be found.  Note that this function peers inside
17736    uninstantiated templates and therefore should be used only in
17737    extremely limited situations.  ONLY_CURRENT_P restricts this
17738    peering to the currently open classes hierarchy (which is required
17739    when comparing types).  */
17740
17741 tree
17742 resolve_typename_type (tree type, bool only_current_p)
17743 {
17744   tree scope;
17745   tree name;
17746   tree decl;
17747   int quals;
17748   tree pushed_scope;
17749   tree result;
17750
17751   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
17752
17753   scope = TYPE_CONTEXT (type);
17754   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
17755      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
17756      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
17757      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
17758      identifier  of the TYPENAME_TYPE anymore.
17759      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
17760      TYPENAME_TYPE instead, we avoid messing up with a possible
17761      typedef variant case.  */
17762   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
17763
17764   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
17765      it first before we can figure out what NAME refers to.  */
17766   if (TREE_CODE (scope) == TYPENAME_TYPE)
17767     scope = resolve_typename_type (scope, only_current_p);
17768   /* If we don't know what SCOPE refers to, then we cannot resolve the
17769      TYPENAME_TYPE.  */
17770   if (TREE_CODE (scope) == TYPENAME_TYPE)
17771     return type;
17772   /* If the SCOPE is a template type parameter, we have no way of
17773      resolving the name.  */
17774   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
17775     return type;
17776   /* If the SCOPE is not the current instantiation, there's no reason
17777      to look inside it.  */
17778   if (only_current_p && !currently_open_class (scope))
17779     return type;
17780   /* If this is a typedef, we don't want to look inside (c++/11987).  */
17781   if (typedef_variant_p (type))
17782     return type;
17783   /* If SCOPE isn't the template itself, it will not have a valid
17784      TYPE_FIELDS list.  */
17785   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
17786     /* scope is either the template itself or a compatible instantiation
17787        like X<T>, so look up the name in the original template.  */
17788     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
17789   else
17790     /* scope is a partial instantiation, so we can't do the lookup or we
17791        will lose the template arguments.  */
17792     return type;
17793   /* Enter the SCOPE so that name lookup will be resolved as if we
17794      were in the class definition.  In particular, SCOPE will no
17795      longer be considered a dependent type.  */
17796   pushed_scope = push_scope (scope);
17797   /* Look up the declaration.  */
17798   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
17799
17800   result = NULL_TREE;
17801   
17802   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
17803      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
17804   if (!decl)
17805     /*nop*/;
17806   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
17807            && TREE_CODE (decl) == TYPE_DECL)
17808     {
17809       result = TREE_TYPE (decl);
17810       if (result == error_mark_node)
17811         result = NULL_TREE;
17812     }
17813   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
17814            && DECL_CLASS_TEMPLATE_P (decl))
17815     {
17816       tree tmpl;
17817       tree args;
17818       /* Obtain the template and the arguments.  */
17819       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
17820       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
17821       /* Instantiate the template.  */
17822       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
17823                                       /*entering_scope=*/0,
17824                                       tf_error | tf_user);
17825       if (result == error_mark_node)
17826         result = NULL_TREE;
17827     }
17828   
17829   /* Leave the SCOPE.  */
17830   if (pushed_scope)
17831     pop_scope (pushed_scope);
17832
17833   /* If we failed to resolve it, return the original typename.  */
17834   if (!result)
17835     return type;
17836   
17837   /* If lookup found a typename type, resolve that too.  */
17838   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
17839     {
17840       /* Ill-formed programs can cause infinite recursion here, so we
17841          must catch that.  */
17842       TYPENAME_IS_RESOLVING_P (type) = 1;
17843       result = resolve_typename_type (result, only_current_p);
17844       TYPENAME_IS_RESOLVING_P (type) = 0;
17845     }
17846   
17847   /* Qualify the resulting type.  */
17848   quals = cp_type_quals (type);
17849   if (quals)
17850     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
17851
17852   return result;
17853 }
17854
17855 /* EXPR is an expression which is not type-dependent.  Return a proxy
17856    for EXPR that can be used to compute the types of larger
17857    expressions containing EXPR.  */
17858
17859 tree
17860 build_non_dependent_expr (tree expr)
17861 {
17862   tree inner_expr;
17863
17864   /* Preserve null pointer constants so that the type of things like
17865      "p == 0" where "p" is a pointer can be determined.  */
17866   if (null_ptr_cst_p (expr))
17867     return expr;
17868   /* Preserve OVERLOADs; the functions must be available to resolve
17869      types.  */
17870   inner_expr = expr;
17871   if (TREE_CODE (inner_expr) == STMT_EXPR)
17872     inner_expr = stmt_expr_value_expr (inner_expr);
17873   if (TREE_CODE (inner_expr) == ADDR_EXPR)
17874     inner_expr = TREE_OPERAND (inner_expr, 0);
17875   if (TREE_CODE (inner_expr) == COMPONENT_REF)
17876     inner_expr = TREE_OPERAND (inner_expr, 1);
17877   if (is_overloaded_fn (inner_expr)
17878       || TREE_CODE (inner_expr) == OFFSET_REF)
17879     return expr;
17880   /* There is no need to return a proxy for a variable.  */
17881   if (TREE_CODE (expr) == VAR_DECL)
17882     return expr;
17883   /* Preserve string constants; conversions from string constants to
17884      "char *" are allowed, even though normally a "const char *"
17885      cannot be used to initialize a "char *".  */
17886   if (TREE_CODE (expr) == STRING_CST)
17887     return expr;
17888   /* Preserve arithmetic constants, as an optimization -- there is no
17889      reason to create a new node.  */
17890   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
17891     return expr;
17892   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
17893      There is at least one place where we want to know that a
17894      particular expression is a throw-expression: when checking a ?:
17895      expression, there are special rules if the second or third
17896      argument is a throw-expression.  */
17897   if (TREE_CODE (expr) == THROW_EXPR)
17898     return expr;
17899
17900   if (TREE_CODE (expr) == COND_EXPR)
17901     return build3 (COND_EXPR,
17902                    TREE_TYPE (expr),
17903                    TREE_OPERAND (expr, 0),
17904                    (TREE_OPERAND (expr, 1)
17905                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
17906                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
17907                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
17908   if (TREE_CODE (expr) == COMPOUND_EXPR
17909       && !COMPOUND_EXPR_OVERLOADED (expr))
17910     return build2 (COMPOUND_EXPR,
17911                    TREE_TYPE (expr),
17912                    TREE_OPERAND (expr, 0),
17913                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
17914
17915   /* If the type is unknown, it can't really be non-dependent */
17916   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
17917
17918   /* Otherwise, build a NON_DEPENDENT_EXPR.
17919
17920      REFERENCE_TYPEs are not stripped for expressions in templates
17921      because doing so would play havoc with mangling.  Consider, for
17922      example:
17923
17924        template <typename T> void f<T& g>() { g(); }
17925
17926      In the body of "f", the expression for "g" will have
17927      REFERENCE_TYPE, even though the standard says that it should
17928      not.  The reason is that we must preserve the syntactic form of
17929      the expression so that mangling (say) "f<g>" inside the body of
17930      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
17931      stripped here.  */
17932   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
17933 }
17934
17935 /* ARGS is a vector of expressions as arguments to a function call.
17936    Replace the arguments with equivalent non-dependent expressions.
17937    This modifies ARGS in place.  */
17938
17939 void
17940 make_args_non_dependent (VEC(tree,gc) *args)
17941 {
17942   unsigned int ix;
17943   tree arg;
17944
17945   for (ix = 0; VEC_iterate (tree, args, ix, arg); ++ix)
17946     {
17947       tree newarg = build_non_dependent_expr (arg);
17948       if (newarg != arg)
17949         VEC_replace (tree, args, ix, newarg);
17950     }
17951 }
17952
17953 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
17954    with a level one deeper than the actual template parms.  */
17955
17956 tree
17957 make_auto (void)
17958 {
17959   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
17960   TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
17961                                TYPE_DECL, get_identifier ("auto"), au);
17962   TYPE_STUB_DECL (au) = TYPE_NAME (au);
17963   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
17964     (0, processing_template_decl + 1, processing_template_decl + 1,
17965      TYPE_NAME (au), NULL_TREE);
17966   TYPE_CANONICAL (au) = canonical_type_parameter (au);
17967   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
17968   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
17969
17970   return au;
17971 }
17972
17973 /* Given type ARG, return std::initializer_list<ARG>.  */
17974
17975 static tree
17976 listify (tree arg)
17977 {
17978   tree std_init_list = namespace_binding
17979     (get_identifier ("initializer_list"), std_node);
17980   tree argvec;
17981   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
17982     {    
17983       error ("deducing from brace-enclosed initializer list requires "
17984              "#include <initializer_list>");
17985       return error_mark_node;
17986     }
17987   argvec = make_tree_vec (1);
17988   TREE_VEC_ELT (argvec, 0) = arg;
17989   return lookup_template_class (std_init_list, argvec, NULL_TREE,
17990                                 NULL_TREE, 0, tf_warning_or_error);
17991 }
17992
17993 /* Replace auto in TYPE with std::initializer_list<auto>.  */
17994
17995 static tree
17996 listify_autos (tree type, tree auto_node)
17997 {
17998   tree init_auto = listify (auto_node);
17999   tree argvec = make_tree_vec (1);
18000   TREE_VEC_ELT (argvec, 0) = init_auto;
18001   if (processing_template_decl)
18002     argvec = add_to_template_args (current_template_args (), argvec);
18003   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
18004 }
18005
18006 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
18007    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
18008
18009 tree
18010 do_auto_deduction (tree type, tree init, tree auto_node)
18011 {
18012   tree parms, tparms, targs;
18013   tree args[1];
18014   int val;
18015
18016   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
18017      with either a new invented type template parameter U or, if the
18018      initializer is a braced-init-list (8.5.4), with
18019      std::initializer_list<U>.  */
18020   if (BRACE_ENCLOSED_INITIALIZER_P (init))
18021     type = listify_autos (type, auto_node);
18022
18023   parms = build_tree_list (NULL_TREE, type);
18024   args[0] = init;
18025   tparms = make_tree_vec (1);
18026   targs = make_tree_vec (1);
18027   TREE_VEC_ELT (tparms, 0)
18028     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
18029   val = type_unification_real (tparms, targs, parms, args, 1, 0,
18030                                DEDUCE_CALL, LOOKUP_NORMAL);
18031   if (val > 0)
18032     {
18033       error ("unable to deduce %qT from %qE", type, init);
18034       return error_mark_node;
18035     }
18036
18037   /* If the list of declarators contains more than one declarator, the type
18038      of each declared variable is determined as described above. If the
18039      type deduced for the template parameter U is not the same in each
18040      deduction, the program is ill-formed.  */
18041   if (TREE_TYPE (auto_node)
18042       && !same_type_p (TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0)))
18043     {
18044       error ("inconsistent deduction for %qT: %qT and then %qT",
18045              auto_node, TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0));
18046       return error_mark_node;
18047     }
18048   TREE_TYPE (auto_node) = TREE_VEC_ELT (targs, 0);
18049
18050   if (processing_template_decl)
18051     targs = add_to_template_args (current_template_args (), targs);
18052   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
18053 }
18054
18055 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
18056    result.  */
18057
18058 tree
18059 splice_late_return_type (tree type, tree late_return_type)
18060 {
18061   tree argvec;
18062
18063   if (late_return_type == NULL_TREE)
18064     return type;
18065   argvec = make_tree_vec (1);
18066   TREE_VEC_ELT (argvec, 0) = late_return_type;
18067   if (processing_template_decl)
18068     argvec = add_to_template_args (current_template_args (), argvec);
18069   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
18070 }
18071
18072 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
18073
18074 bool
18075 is_auto (const_tree type)
18076 {
18077   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
18078       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
18079     return true;
18080   else
18081     return false;
18082 }
18083
18084 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
18085    appear as a type-specifier for the declaration in question, we don't
18086    have to look through the whole type.  */
18087
18088 tree
18089 type_uses_auto (tree type)
18090 {
18091   enum tree_code code;
18092   if (is_auto (type))
18093     return type;
18094
18095   code = TREE_CODE (type);
18096
18097   if (code == POINTER_TYPE || code == REFERENCE_TYPE
18098       || code == OFFSET_TYPE || code == FUNCTION_TYPE
18099       || code == METHOD_TYPE || code == ARRAY_TYPE)
18100     return type_uses_auto (TREE_TYPE (type));
18101
18102   if (TYPE_PTRMEMFUNC_P (type))
18103     return type_uses_auto (TREE_TYPE (TREE_TYPE
18104                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
18105
18106   return NULL_TREE;
18107 }
18108
18109 /* For a given template T, return the vector of typedefs referenced
18110    in T for which access check is needed at T instantiation time.
18111    T is either  a FUNCTION_DECL or a RECORD_TYPE.
18112    Those typedefs were added to T by the function
18113    append_type_to_template_for_access_check.  */
18114
18115 VEC(qualified_typedef_usage_t,gc)*
18116 get_types_needing_access_check (tree t)
18117 {
18118   tree ti;
18119   VEC(qualified_typedef_usage_t,gc) *result = NULL;
18120
18121   if (!t || t == error_mark_node)
18122     return NULL;
18123
18124   if (!(ti = get_template_info (t)))
18125     return NULL;
18126
18127   if (CLASS_TYPE_P (t)
18128       || TREE_CODE (t) == FUNCTION_DECL)
18129     {
18130       if (!TI_TEMPLATE (ti))
18131         return NULL;
18132
18133       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
18134     }
18135
18136   return result;
18137 }
18138
18139 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
18140    tied to T. That list of typedefs will be access checked at
18141    T instantiation time.
18142    T is either a FUNCTION_DECL or a RECORD_TYPE.
18143    TYPE_DECL is a TYPE_DECL node representing a typedef.
18144    SCOPE is the scope through which TYPE_DECL is accessed.
18145    LOCATION is the location of the usage point of TYPE_DECL.
18146
18147    This function is a subroutine of
18148    append_type_to_template_for_access_check.  */
18149
18150 static void
18151 append_type_to_template_for_access_check_1 (tree t,
18152                                             tree type_decl,
18153                                             tree scope,
18154                                             location_t location)
18155 {
18156   qualified_typedef_usage_t typedef_usage;
18157   tree ti;
18158
18159   if (!t || t == error_mark_node)
18160     return;
18161
18162   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
18163                || CLASS_TYPE_P (t))
18164               && type_decl
18165               && TREE_CODE (type_decl) == TYPE_DECL
18166               && scope);
18167
18168   if (!(ti = get_template_info (t)))
18169     return;
18170
18171   gcc_assert (TI_TEMPLATE (ti));
18172
18173   typedef_usage.typedef_decl = type_decl;
18174   typedef_usage.context = scope;
18175   typedef_usage.locus = location;
18176
18177   VEC_safe_push (qualified_typedef_usage_t, gc,
18178                  TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti),
18179                  &typedef_usage);
18180 }
18181
18182 /* Append TYPE_DECL to the template TEMPL.
18183    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
18184    At TEMPL instanciation time, TYPE_DECL will be checked to see
18185    if it can be accessed through SCOPE.
18186    LOCATION is the location of the usage point of TYPE_DECL.
18187
18188    e.g. consider the following code snippet:
18189
18190      class C
18191      {
18192        typedef int myint;
18193      };
18194
18195      template<class U> struct S
18196      {
18197        C::myint mi; // <-- usage point of the typedef C::myint
18198      };
18199
18200      S<char> s;
18201
18202    At S<char> instantiation time, we need to check the access of C::myint
18203    In other words, we need to check the access of the myint typedef through
18204    the C scope. For that purpose, this function will add the myint typedef
18205    and the scope C through which its being accessed to a list of typedefs
18206    tied to the template S. That list will be walked at template instantiation
18207    time and access check performed on each typedefs it contains.
18208    Note that this particular code snippet should yield an error because
18209    myint is private to C.  */
18210
18211 void
18212 append_type_to_template_for_access_check (tree templ,
18213                                           tree type_decl,
18214                                           tree scope,
18215                                           location_t location)
18216 {
18217   qualified_typedef_usage_t *iter;
18218   int i;
18219
18220   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
18221
18222   /* Make sure we don't append the type to the template twice.  */
18223   for (i = 0;
18224        VEC_iterate (qualified_typedef_usage_t,
18225                     get_types_needing_access_check (templ),
18226                     i, iter);
18227        ++i)
18228     if (iter->typedef_decl == type_decl && scope == iter->context)
18229       return;
18230
18231   append_type_to_template_for_access_check_1 (templ, type_decl,
18232                                               scope, location);
18233 }
18234
18235 /* Set up the hash tables for template instantiations.  */
18236
18237 void
18238 init_template_processing (void)
18239 {
18240   decl_specializations = htab_create_ggc (37,
18241                                           hash_specialization,
18242                                           eq_specializations,
18243                                           ggc_free);
18244   type_specializations = htab_create_ggc (37,
18245                                           hash_specialization,
18246                                           eq_specializations,
18247                                           ggc_free);
18248 }
18249
18250 #include "gt-cp-pt.h"