OSDN Git Service

PR c++/38392
[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 "intl.h"
36 #include "pointer-set.h"
37 #include "flags.h"
38 #include "c-common.h"
39 #include "cp-tree.h"
40 #include "cp-objcp-common.h"
41 #include "tree-inline.h"
42 #include "decl.h"
43 #include "output.h"
44 #include "except.h"
45 #include "toplev.h"
46 #include "rtl.h"
47 #include "timevar.h"
48 #include "tree-iterator.h"
49 #include "vecprim.h"
50
51 /* The type of functions taking a tree, and some additional data, and
52    returning an int.  */
53 typedef int (*tree_fn_t) (tree, void*);
54
55 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
56    instantiations have been deferred, either because their definitions
57    were not yet available, or because we were putting off doing the work.  */
58 struct GTY (()) pending_template {
59   struct pending_template *next;
60   struct tinst_level *tinst;
61 };
62
63 static GTY(()) struct pending_template *pending_templates;
64 static GTY(()) struct pending_template *last_pending_template;
65
66 int processing_template_parmlist;
67 static int template_header_count;
68
69 static GTY(()) tree saved_trees;
70 static VEC(int,heap) *inline_parm_levels;
71
72 static GTY(()) struct tinst_level *current_tinst_level;
73
74 static GTY(()) tree saved_access_scope;
75
76 /* Live only within one (recursive) call to tsubst_expr.  We use
77    this to pass the statement expression node from the STMT_EXPR
78    to the EXPR_STMT that is its result.  */
79 static tree cur_stmt_expr;
80
81 /* A map from local variable declarations in the body of the template
82    presently being instantiated to the corresponding instantiated
83    local variables.  */
84 static htab_t local_specializations;
85
86 typedef struct GTY(()) spec_entry
87 {
88   tree tmpl;
89   tree args;
90   tree spec;
91 } spec_entry;
92
93 static GTY ((param_is (spec_entry)))
94   htab_t decl_specializations;
95
96 static GTY ((param_is (spec_entry)))
97   htab_t type_specializations;
98
99 /* Contains canonical template parameter types. The vector is indexed by
100    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
101    TREE_LIST, whose TREE_VALUEs contain the canonical template
102    parameters of various types and levels.  */
103 static GTY(()) VEC(tree,gc) *canonical_template_parms;
104
105 #define UNIFY_ALLOW_NONE 0
106 #define UNIFY_ALLOW_MORE_CV_QUAL 1
107 #define UNIFY_ALLOW_LESS_CV_QUAL 2
108 #define UNIFY_ALLOW_DERIVED 4
109 #define UNIFY_ALLOW_INTEGER 8
110 #define UNIFY_ALLOW_OUTER_LEVEL 16
111 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
112 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
113
114 static void push_access_scope (tree);
115 static void pop_access_scope (tree);
116 static bool resolve_overloaded_unification (tree, tree, tree, tree,
117                                             unification_kind_t, int);
118 static int try_one_overload (tree, tree, tree, tree, tree,
119                              unification_kind_t, int, bool);
120 static int unify (tree, tree, tree, tree, int);
121 static void add_pending_template (tree);
122 static tree reopen_tinst_level (struct tinst_level *);
123 static tree tsubst_initializer_list (tree, tree);
124 static tree get_class_bindings (tree, tree, tree);
125 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
126                                    bool, bool);
127 static void tsubst_enum (tree, tree, tree);
128 static tree add_to_template_args (tree, tree);
129 static tree add_outermost_template_args (tree, tree);
130 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
131 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
132                                              tree);
133 static int type_unification_real (tree, tree, tree, const tree *,
134                                   unsigned int, int, unification_kind_t, int);
135 static void note_template_header (int);
136 static tree convert_nontype_argument_function (tree, tree);
137 static tree convert_nontype_argument (tree, tree);
138 static tree convert_template_argument (tree, tree, tree,
139                                        tsubst_flags_t, int, tree);
140 static int for_each_template_parm (tree, tree_fn_t, void*,
141                                    struct pointer_set_t*, bool);
142 static tree expand_template_argument_pack (tree);
143 static tree build_template_parm_index (int, int, int, tree, tree);
144 static bool inline_needs_template_parms (tree);
145 static void push_inline_template_parms_recursive (tree, int);
146 static tree retrieve_local_specialization (tree);
147 static void register_local_specialization (tree, tree);
148 static hashval_t hash_specialization (const void *p);
149 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
150 static int mark_template_parm (tree, void *);
151 static int template_parm_this_level_p (tree, void *);
152 static tree tsubst_friend_function (tree, tree);
153 static tree tsubst_friend_class (tree, tree);
154 static int can_complete_type_without_circularity (tree);
155 static tree get_bindings (tree, tree, tree, bool);
156 static int template_decl_level (tree);
157 static int check_cv_quals_for_unify (int, tree, tree);
158 static void template_parm_level_and_index (tree, int*, int*);
159 static int unify_pack_expansion (tree, tree, tree, tree, int, bool, bool);
160 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
161 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
162 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
163 static void regenerate_decl_from_template (tree, tree);
164 static tree most_specialized_class (tree, tree);
165 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
166 static tree tsubst_arg_types (tree, tree, tsubst_flags_t, tree);
167 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
168 static bool check_specialization_scope (void);
169 static tree process_partial_specialization (tree);
170 static void set_current_access_from_decl (tree);
171 static tree get_template_base (tree, tree, tree, tree);
172 static tree try_class_unification (tree, tree, tree, tree);
173 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
174                                            tree, tree);
175 static bool template_template_parm_bindings_ok_p (tree, tree);
176 static int template_args_equal (tree, tree);
177 static void tsubst_default_arguments (tree);
178 static tree for_each_template_parm_r (tree *, int *, void *);
179 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
180 static void copy_default_args_to_explicit_spec (tree);
181 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
182 static int eq_local_specializations (const void *, const void *);
183 static bool dependent_template_arg_p (tree);
184 static bool any_template_arguments_need_structural_equality_p (tree);
185 static bool dependent_type_p_r (tree);
186 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree, bool);
187 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
188 static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
189 static tree tsubst_decl (tree, tree, tsubst_flags_t);
190 static void perform_typedefs_access_check (tree tmpl, tree targs);
191 static void append_type_to_template_for_access_check_1 (tree, tree, tree,
192                                                         location_t);
193 static hashval_t iterative_hash_template_arg (tree arg, hashval_t val);
194 static tree listify (tree);
195 static tree listify_autos (tree, tree);
196
197 /* Make the current scope suitable for access checking when we are
198    processing T.  T can be FUNCTION_DECL for instantiated function
199    template, or VAR_DECL for static member variable (need by
200    instantiate_decl).  */
201
202 static void
203 push_access_scope (tree t)
204 {
205   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
206               || TREE_CODE (t) == VAR_DECL);
207
208   if (DECL_FRIEND_CONTEXT (t))
209     push_nested_class (DECL_FRIEND_CONTEXT (t));
210   else if (DECL_CLASS_SCOPE_P (t))
211     push_nested_class (DECL_CONTEXT (t));
212   else
213     push_to_top_level ();
214
215   if (TREE_CODE (t) == FUNCTION_DECL)
216     {
217       saved_access_scope = tree_cons
218         (NULL_TREE, current_function_decl, saved_access_scope);
219       current_function_decl = t;
220     }
221 }
222
223 /* Restore the scope set up by push_access_scope.  T is the node we
224    are processing.  */
225
226 static void
227 pop_access_scope (tree t)
228 {
229   if (TREE_CODE (t) == FUNCTION_DECL)
230     {
231       current_function_decl = TREE_VALUE (saved_access_scope);
232       saved_access_scope = TREE_CHAIN (saved_access_scope);
233     }
234
235   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
236     pop_nested_class ();
237   else
238     pop_from_top_level ();
239 }
240
241 /* Do any processing required when DECL (a member template
242    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
243    to DECL, unless it is a specialization, in which case the DECL
244    itself is returned.  */
245
246 tree
247 finish_member_template_decl (tree decl)
248 {
249   if (decl == error_mark_node)
250     return error_mark_node;
251
252   gcc_assert (DECL_P (decl));
253
254   if (TREE_CODE (decl) == TYPE_DECL)
255     {
256       tree type;
257
258       type = TREE_TYPE (decl);
259       if (type == error_mark_node)
260         return error_mark_node;
261       if (MAYBE_CLASS_TYPE_P (type)
262           && CLASSTYPE_TEMPLATE_INFO (type)
263           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
264         {
265           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
266           check_member_template (tmpl);
267           return tmpl;
268         }
269       return NULL_TREE;
270     }
271   else if (TREE_CODE (decl) == FIELD_DECL)
272     error ("data member %qD cannot be a member template", decl);
273   else if (DECL_TEMPLATE_INFO (decl))
274     {
275       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
276         {
277           check_member_template (DECL_TI_TEMPLATE (decl));
278           return DECL_TI_TEMPLATE (decl);
279         }
280       else
281         return decl;
282     }
283   else
284     error ("invalid member template declaration %qD", decl);
285
286   return error_mark_node;
287 }
288
289 /* Create a template info node.  */
290
291 tree
292 build_template_info (tree template_decl, tree template_args)
293 {
294   tree result = make_node (TEMPLATE_INFO);
295   TI_TEMPLATE (result) = template_decl;
296   TI_ARGS (result) = template_args;
297   return result;
298 }
299
300 /* Return the template info node corresponding to T, whatever T is.  */
301
302 tree
303 get_template_info (const_tree t)
304 {
305   tree tinfo = NULL_TREE;
306
307   if (!t || t == error_mark_node)
308     return NULL;
309
310   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
311     tinfo = DECL_TEMPLATE_INFO (t);
312
313   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
314     t = TREE_TYPE (t);
315
316   if (TAGGED_TYPE_P (t))
317     tinfo = TYPE_TEMPLATE_INFO (t);
318   else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
319     tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
320
321   return tinfo;
322 }
323
324 /* Returns the template nesting level of the indicated class TYPE.
325
326    For example, in:
327      template <class T>
328      struct A
329      {
330        template <class U>
331        struct B {};
332      };
333
334    A<T>::B<U> has depth two, while A<T> has depth one.
335    Both A<T>::B<int> and A<int>::B<U> have depth one, if
336    they are instantiations, not specializations.
337
338    This function is guaranteed to return 0 if passed NULL_TREE so
339    that, for example, `template_class_depth (current_class_type)' is
340    always safe.  */
341
342 int
343 template_class_depth (tree type)
344 {
345   int depth;
346
347   for (depth = 0;
348        type && TREE_CODE (type) != NAMESPACE_DECL;
349        type = (TREE_CODE (type) == FUNCTION_DECL)
350          ? CP_DECL_CONTEXT (type) : TYPE_CONTEXT (type))
351     {
352       tree tinfo = get_template_info (type);
353
354       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
355           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
356         ++depth;
357     }
358
359   return depth;
360 }
361
362 /* Subroutine of maybe_begin_member_template_processing.
363    Returns true if processing DECL needs us to push template parms.  */
364
365 static bool
366 inline_needs_template_parms (tree decl)
367 {
368   if (! DECL_TEMPLATE_INFO (decl))
369     return false;
370
371   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
372           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
373 }
374
375 /* Subroutine of maybe_begin_member_template_processing.
376    Push the template parms in PARMS, starting from LEVELS steps into the
377    chain, and ending at the beginning, since template parms are listed
378    innermost first.  */
379
380 static void
381 push_inline_template_parms_recursive (tree parmlist, int levels)
382 {
383   tree parms = TREE_VALUE (parmlist);
384   int i;
385
386   if (levels > 1)
387     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
388
389   ++processing_template_decl;
390   current_template_parms
391     = tree_cons (size_int (processing_template_decl),
392                  parms, current_template_parms);
393   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
394
395   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
396                NULL);
397   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
398     {
399       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
400
401       if (parm == error_mark_node)
402         continue;
403
404       gcc_assert (DECL_P (parm));
405
406       switch (TREE_CODE (parm))
407         {
408         case TYPE_DECL:
409         case TEMPLATE_DECL:
410           pushdecl (parm);
411           break;
412
413         case PARM_DECL:
414           {
415             /* Make a CONST_DECL as is done in process_template_parm.
416                It is ugly that we recreate this here; the original
417                version built in process_template_parm is no longer
418                available.  */
419             tree decl = build_decl (DECL_SOURCE_LOCATION (parm),
420                                     CONST_DECL, DECL_NAME (parm),
421                                     TREE_TYPE (parm));
422             DECL_ARTIFICIAL (decl) = 1;
423             TREE_CONSTANT (decl) = 1;
424             TREE_READONLY (decl) = 1;
425             DECL_INITIAL (decl) = DECL_INITIAL (parm);
426             SET_DECL_TEMPLATE_PARM_P (decl);
427             pushdecl (decl);
428           }
429           break;
430
431         default:
432           gcc_unreachable ();
433         }
434     }
435 }
436
437 /* Restore the template parameter context for a member template or
438    a friend template defined in a class definition.  */
439
440 void
441 maybe_begin_member_template_processing (tree decl)
442 {
443   tree parms;
444   int levels = 0;
445
446   if (inline_needs_template_parms (decl))
447     {
448       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
449       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
450
451       if (DECL_TEMPLATE_SPECIALIZATION (decl))
452         {
453           --levels;
454           parms = TREE_CHAIN (parms);
455         }
456
457       push_inline_template_parms_recursive (parms, levels);
458     }
459
460   /* Remember how many levels of template parameters we pushed so that
461      we can pop them later.  */
462   VEC_safe_push (int, heap, inline_parm_levels, levels);
463 }
464
465 /* Undo the effects of maybe_begin_member_template_processing.  */
466
467 void
468 maybe_end_member_template_processing (void)
469 {
470   int i;
471   int last;
472
473   if (VEC_length (int, inline_parm_levels) == 0)
474     return;
475
476   last = VEC_pop (int, inline_parm_levels);
477   for (i = 0; i < last; ++i)
478     {
479       --processing_template_decl;
480       current_template_parms = TREE_CHAIN (current_template_parms);
481       poplevel (0, 0, 0);
482     }
483 }
484
485 /* Return a new template argument vector which contains all of ARGS,
486    but has as its innermost set of arguments the EXTRA_ARGS.  */
487
488 static tree
489 add_to_template_args (tree args, tree extra_args)
490 {
491   tree new_args;
492   int extra_depth;
493   int i;
494   int j;
495
496   if (args == NULL_TREE)
497     return extra_args;
498
499   extra_depth = TMPL_ARGS_DEPTH (extra_args);
500   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
501
502   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
503     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
504
505   for (j = 1; j <= extra_depth; ++j, ++i)
506     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
507
508   return new_args;
509 }
510
511 /* Like add_to_template_args, but only the outermost ARGS are added to
512    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
513    (EXTRA_ARGS) levels are added.  This function is used to combine
514    the template arguments from a partial instantiation with the
515    template arguments used to attain the full instantiation from the
516    partial instantiation.  */
517
518 static tree
519 add_outermost_template_args (tree args, tree extra_args)
520 {
521   tree new_args;
522
523   /* If there are more levels of EXTRA_ARGS than there are ARGS,
524      something very fishy is going on.  */
525   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
526
527   /* If *all* the new arguments will be the EXTRA_ARGS, just return
528      them.  */
529   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
530     return extra_args;
531
532   /* For the moment, we make ARGS look like it contains fewer levels.  */
533   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
534
535   new_args = add_to_template_args (args, extra_args);
536
537   /* Now, we restore ARGS to its full dimensions.  */
538   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
539
540   return new_args;
541 }
542
543 /* Return the N levels of innermost template arguments from the ARGS.  */
544
545 tree
546 get_innermost_template_args (tree args, int n)
547 {
548   tree new_args;
549   int extra_levels;
550   int i;
551
552   gcc_assert (n >= 0);
553
554   /* If N is 1, just return the innermost set of template arguments.  */
555   if (n == 1)
556     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
557
558   /* If we're not removing anything, just return the arguments we were
559      given.  */
560   extra_levels = TMPL_ARGS_DEPTH (args) - n;
561   gcc_assert (extra_levels >= 0);
562   if (extra_levels == 0)
563     return args;
564
565   /* Make a new set of arguments, not containing the outer arguments.  */
566   new_args = make_tree_vec (n);
567   for (i = 1; i <= n; ++i)
568     SET_TMPL_ARGS_LEVEL (new_args, i,
569                          TMPL_ARGS_LEVEL (args, i + extra_levels));
570
571   return new_args;
572 }
573
574 /* The inverse of get_innermost_template_args: Return all but the innermost
575    EXTRA_LEVELS levels of template arguments from the ARGS.  */
576
577 static tree
578 strip_innermost_template_args (tree args, int extra_levels)
579 {
580   tree new_args;
581   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
582   int i;
583
584   gcc_assert (n >= 0);
585
586   /* If N is 1, just return the outermost set of template arguments.  */
587   if (n == 1)
588     return TMPL_ARGS_LEVEL (args, 1);
589
590   /* If we're not removing anything, just return the arguments we were
591      given.  */
592   gcc_assert (extra_levels >= 0);
593   if (extra_levels == 0)
594     return args;
595
596   /* Make a new set of arguments, not containing the inner arguments.  */
597   new_args = make_tree_vec (n);
598   for (i = 1; i <= n; ++i)
599     SET_TMPL_ARGS_LEVEL (new_args, i,
600                          TMPL_ARGS_LEVEL (args, i));
601
602   return new_args;
603 }
604
605 /* We've got a template header coming up; push to a new level for storing
606    the parms.  */
607
608 void
609 begin_template_parm_list (void)
610 {
611   /* We use a non-tag-transparent scope here, which causes pushtag to
612      put tags in this scope, rather than in the enclosing class or
613      namespace scope.  This is the right thing, since we want
614      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
615      global template class, push_template_decl handles putting the
616      TEMPLATE_DECL into top-level scope.  For a nested template class,
617      e.g.:
618
619        template <class T> struct S1 {
620          template <class T> struct S2 {};
621        };
622
623      pushtag contains special code to call pushdecl_with_scope on the
624      TEMPLATE_DECL for S2.  */
625   begin_scope (sk_template_parms, NULL);
626   ++processing_template_decl;
627   ++processing_template_parmlist;
628   note_template_header (0);
629 }
630
631 /* This routine is called when a specialization is declared.  If it is
632    invalid to declare a specialization here, an error is reported and
633    false is returned, otherwise this routine will return true.  */
634
635 static bool
636 check_specialization_scope (void)
637 {
638   tree scope = current_scope ();
639
640   /* [temp.expl.spec]
641
642      An explicit specialization shall be declared in the namespace of
643      which the template is a member, or, for member templates, in the
644      namespace of which the enclosing class or enclosing class
645      template is a member.  An explicit specialization of a member
646      function, member class or static data member of a class template
647      shall be declared in the namespace of which the class template
648      is a member.  */
649   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
650     {
651       error ("explicit specialization in non-namespace scope %qD", scope);
652       return false;
653     }
654
655   /* [temp.expl.spec]
656
657      In an explicit specialization declaration for a member of a class
658      template or a member template that appears in namespace scope,
659      the member template and some of its enclosing class templates may
660      remain unspecialized, except that the declaration shall not
661      explicitly specialize a class member template if its enclosing
662      class templates are not explicitly specialized as well.  */
663   if (current_template_parms)
664     {
665       error ("enclosing class templates are not explicitly specialized");
666       return false;
667     }
668
669   return true;
670 }
671
672 /* We've just seen template <>.  */
673
674 bool
675 begin_specialization (void)
676 {
677   begin_scope (sk_template_spec, NULL);
678   note_template_header (1);
679   return check_specialization_scope ();
680 }
681
682 /* Called at then end of processing a declaration preceded by
683    template<>.  */
684
685 void
686 end_specialization (void)
687 {
688   finish_scope ();
689   reset_specialization ();
690 }
691
692 /* Any template <>'s that we have seen thus far are not referring to a
693    function specialization.  */
694
695 void
696 reset_specialization (void)
697 {
698   processing_specialization = 0;
699   template_header_count = 0;
700 }
701
702 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
703    it was of the form template <>.  */
704
705 static void
706 note_template_header (int specialization)
707 {
708   processing_specialization = specialization;
709   template_header_count++;
710 }
711
712 /* We're beginning an explicit instantiation.  */
713
714 void
715 begin_explicit_instantiation (void)
716 {
717   gcc_assert (!processing_explicit_instantiation);
718   processing_explicit_instantiation = true;
719 }
720
721
722 void
723 end_explicit_instantiation (void)
724 {
725   gcc_assert (processing_explicit_instantiation);
726   processing_explicit_instantiation = false;
727 }
728
729 /* An explicit specialization or partial specialization TMPL is being
730    declared.  Check that the namespace in which the specialization is
731    occurring is permissible.  Returns false iff it is invalid to
732    specialize TMPL in the current namespace.  */
733
734 static bool
735 check_specialization_namespace (tree tmpl)
736 {
737   tree tpl_ns = decl_namespace_context (tmpl);
738
739   /* [tmpl.expl.spec]
740
741      An explicit specialization shall be declared in the namespace of
742      which the template is a member, or, for member templates, in the
743      namespace of which the enclosing class or enclosing class
744      template is a member.  An explicit specialization of a member
745      function, member class or static data member of a class template
746      shall be declared in the namespace of which the class template is
747      a member.  */
748   if (current_scope() != DECL_CONTEXT (tmpl)
749       && !at_namespace_scope_p ())
750     {
751       error ("specialization of %qD must appear at namespace scope", tmpl);
752       return false;
753     }
754   if (is_associated_namespace (current_namespace, tpl_ns))
755     /* Same or super-using namespace.  */
756     return true;
757   else
758     {
759       permerror (input_location, "specialization of %qD in different namespace", tmpl);
760       permerror (input_location, "  from definition of %q+#D", tmpl);
761       return false;
762     }
763 }
764
765 /* SPEC is an explicit instantiation.  Check that it is valid to
766    perform this explicit instantiation in the current namespace.  */
767
768 static void
769 check_explicit_instantiation_namespace (tree spec)
770 {
771   tree ns;
772
773   /* DR 275: An explicit instantiation shall appear in an enclosing
774      namespace of its template.  */
775   ns = decl_namespace_context (spec);
776   if (!is_ancestor (current_namespace, ns))
777     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
778                "(which does not enclose namespace %qD)",
779                spec, current_namespace, ns);
780 }
781
782 /* The TYPE is being declared.  If it is a template type, that means it
783    is a partial specialization.  Do appropriate error-checking.  */
784
785 tree
786 maybe_process_partial_specialization (tree type)
787 {
788   tree context;
789
790   if (type == error_mark_node)
791     return error_mark_node;
792
793   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
794     {
795       error ("name of class shadows template template parameter %qD",
796              TYPE_NAME (type));
797       return error_mark_node;
798     }
799
800   context = TYPE_CONTEXT (type);
801
802   if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
803     {
804       /* This is for ordinary explicit specialization and partial
805          specialization of a template class such as:
806
807            template <> class C<int>;
808
809          or:
810
811            template <class T> class C<T*>;
812
813          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
814
815       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
816           && !COMPLETE_TYPE_P (type))
817         {
818           check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
819           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
820           if (processing_template_decl)
821             {
822               if (push_template_decl (TYPE_MAIN_DECL (type))
823                   == error_mark_node)
824                 return error_mark_node;
825             }
826         }
827       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
828         error ("specialization of %qT after instantiation", type);
829     }
830   else if (CLASS_TYPE_P (type)
831            && !CLASSTYPE_USE_TEMPLATE (type)
832            && CLASSTYPE_TEMPLATE_INFO (type)
833            && context && CLASS_TYPE_P (context)
834            && CLASSTYPE_TEMPLATE_INFO (context))
835     {
836       /* This is for an explicit specialization of member class
837          template according to [temp.expl.spec/18]:
838
839            template <> template <class U> class C<int>::D;
840
841          The context `C<int>' must be an implicit instantiation.
842          Otherwise this is just a member class template declared
843          earlier like:
844
845            template <> class C<int> { template <class U> class D; };
846            template <> template <class U> class C<int>::D;
847
848          In the first case, `C<int>::D' is a specialization of `C<T>::D'
849          while in the second case, `C<int>::D' is a primary template
850          and `C<T>::D' may not exist.  */
851
852       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
853           && !COMPLETE_TYPE_P (type))
854         {
855           tree t;
856           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
857
858           if (current_namespace
859               != decl_namespace_context (tmpl))
860             {
861               permerror (input_location, "specializing %q#T in different namespace", type);
862               permerror (input_location, "  from definition of %q+#D", tmpl);
863             }
864
865           /* Check for invalid specialization after instantiation:
866
867                template <> template <> class C<int>::D<int>;
868                template <> template <class U> class C<int>::D;  */
869
870           for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
871                t; t = TREE_CHAIN (t))
872             {
873               tree inst = TREE_VALUE (t);
874               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst))
875                 {
876                   /* We already have a full specialization of this partial
877                      instantiation.  Reassign it to the new member
878                      specialization template.  */
879                   spec_entry elt;
880                   spec_entry **slot;
881
882                   elt.tmpl = most_general_template (tmpl);
883                   elt.args = CLASSTYPE_TI_ARGS (inst);
884                   elt.spec = inst;
885
886                   htab_remove_elt (type_specializations, &elt);
887
888                   elt.tmpl = tmpl;
889                   elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
890
891                   slot = (spec_entry **)
892                     htab_find_slot (type_specializations, &elt, INSERT);
893                   *slot = GGC_NEW (spec_entry);
894                   **slot = elt;
895                 }
896               else if (COMPLETE_TYPE_P (inst) || TYPE_BEING_DEFINED (inst))
897                 /* But if we've had an implicit instantiation, that's a
898                    problem ([temp.expl.spec]/6).  */
899                 error ("specialization %qT after instantiation %qT",
900                        type, inst);
901             }
902
903           /* Mark TYPE as a specialization.  And as a result, we only
904              have one level of template argument for the innermost
905              class template.  */
906           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
907           CLASSTYPE_TI_ARGS (type)
908             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
909         }
910     }
911   else if (processing_specialization)
912     {
913       error ("explicit specialization of non-template %qT", type);
914       return error_mark_node;
915     }
916
917   return type;
918 }
919
920 /* Returns nonzero if we can optimize the retrieval of specializations
921    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
922    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
923
924 static inline bool
925 optimize_specialization_lookup_p (tree tmpl)
926 {
927   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
928           && DECL_CLASS_SCOPE_P (tmpl)
929           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
930              parameter.  */
931           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
932           /* The optimized lookup depends on the fact that the
933              template arguments for the member function template apply
934              purely to the containing class, which is not true if the
935              containing class is an explicit or partial
936              specialization.  */
937           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
938           && !DECL_MEMBER_TEMPLATE_P (tmpl)
939           && !DECL_CONV_FN_P (tmpl)
940           /* It is possible to have a template that is not a member
941              template and is not a member of a template class:
942
943              template <typename T>
944              struct S { friend A::f(); };
945
946              Here, the friend function is a template, but the context does
947              not have template information.  The optimized lookup relies
948              on having ARGS be the template arguments for both the class
949              and the function template.  */
950           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
951 }
952
953 /* Retrieve the specialization (in the sense of [temp.spec] - a
954    specialization is either an instantiation or an explicit
955    specialization) of TMPL for the given template ARGS.  If there is
956    no such specialization, return NULL_TREE.  The ARGS are a vector of
957    arguments, or a vector of vectors of arguments, in the case of
958    templates with more than one level of parameters.
959
960    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
961    then we search for a partial specialization matching ARGS.  This
962    parameter is ignored if TMPL is not a class template.  */
963
964 static tree
965 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
966 {
967   if (args == error_mark_node)
968     return NULL_TREE;
969
970   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
971
972   /* There should be as many levels of arguments as there are
973      levels of parameters.  */
974   gcc_assert (TMPL_ARGS_DEPTH (args)
975               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
976
977   if (optimize_specialization_lookup_p (tmpl))
978     {
979       tree class_template;
980       tree class_specialization;
981       VEC(tree,gc) *methods;
982       tree fns;
983       int idx;
984
985       /* The template arguments actually apply to the containing
986          class.  Find the class specialization with those
987          arguments.  */
988       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
989       class_specialization
990         = retrieve_specialization (class_template, args, 0);
991       if (!class_specialization)
992         return NULL_TREE;
993       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
994          for the specialization.  */
995       idx = class_method_index_for_fn (class_specialization, tmpl);
996       if (idx == -1)
997         return NULL_TREE;
998       /* Iterate through the methods with the indicated name, looking
999          for the one that has an instance of TMPL.  */
1000       methods = CLASSTYPE_METHOD_VEC (class_specialization);
1001       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
1002         {
1003           tree fn = OVL_CURRENT (fns);
1004           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl
1005               /* using-declarations can add base methods to the method vec,
1006                  and we don't want those here.  */
1007               && DECL_CONTEXT (fn) == class_specialization)
1008             return fn;
1009         }
1010       return NULL_TREE;
1011     }
1012   else
1013     {
1014       spec_entry *found;
1015       spec_entry elt;
1016       htab_t specializations;
1017
1018       elt.tmpl = tmpl;
1019       elt.args = args;
1020       elt.spec = NULL_TREE;
1021
1022       if (DECL_CLASS_TEMPLATE_P (tmpl))
1023         specializations = type_specializations;
1024       else
1025         specializations = decl_specializations;
1026
1027       if (hash == 0)
1028         hash = hash_specialization (&elt);
1029       found = (spec_entry *) htab_find_with_hash (specializations, &elt, hash);
1030       if (found)
1031         return found->spec;
1032     }
1033
1034   return NULL_TREE;
1035 }
1036
1037 /* Like retrieve_specialization, but for local declarations.  */
1038
1039 static tree
1040 retrieve_local_specialization (tree tmpl)
1041 {
1042   tree spec;
1043
1044   if (local_specializations == NULL)
1045     return NULL_TREE;
1046
1047   spec = (tree) htab_find_with_hash (local_specializations, tmpl,
1048                                      htab_hash_pointer (tmpl));
1049   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
1050 }
1051
1052 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1053
1054 int
1055 is_specialization_of (tree decl, tree tmpl)
1056 {
1057   tree t;
1058
1059   if (TREE_CODE (decl) == FUNCTION_DECL)
1060     {
1061       for (t = decl;
1062            t != NULL_TREE;
1063            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1064         if (t == tmpl)
1065           return 1;
1066     }
1067   else
1068     {
1069       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1070
1071       for (t = TREE_TYPE (decl);
1072            t != NULL_TREE;
1073            t = CLASSTYPE_USE_TEMPLATE (t)
1074              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1075         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1076           return 1;
1077     }
1078
1079   return 0;
1080 }
1081
1082 /* Returns nonzero iff DECL is a specialization of friend declaration
1083    FRIEND_DECL according to [temp.friend].  */
1084
1085 bool
1086 is_specialization_of_friend (tree decl, tree friend_decl)
1087 {
1088   bool need_template = true;
1089   int template_depth;
1090
1091   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1092               || TREE_CODE (decl) == TYPE_DECL);
1093
1094   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1095      of a template class, we want to check if DECL is a specialization
1096      if this.  */
1097   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1098       && DECL_TEMPLATE_INFO (friend_decl)
1099       && !DECL_USE_TEMPLATE (friend_decl))
1100     {
1101       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1102       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1103       need_template = false;
1104     }
1105   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1106            && !PRIMARY_TEMPLATE_P (friend_decl))
1107     need_template = false;
1108
1109   /* There is nothing to do if this is not a template friend.  */
1110   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1111     return false;
1112
1113   if (is_specialization_of (decl, friend_decl))
1114     return true;
1115
1116   /* [temp.friend/6]
1117      A member of a class template may be declared to be a friend of a
1118      non-template class.  In this case, the corresponding member of
1119      every specialization of the class template is a friend of the
1120      class granting friendship.
1121
1122      For example, given a template friend declaration
1123
1124        template <class T> friend void A<T>::f();
1125
1126      the member function below is considered a friend
1127
1128        template <> struct A<int> {
1129          void f();
1130        };
1131
1132      For this type of template friend, TEMPLATE_DEPTH below will be
1133      nonzero.  To determine if DECL is a friend of FRIEND, we first
1134      check if the enclosing class is a specialization of another.  */
1135
1136   template_depth = template_class_depth (DECL_CONTEXT (friend_decl));
1137   if (template_depth
1138       && DECL_CLASS_SCOPE_P (decl)
1139       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1140                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1141     {
1142       /* Next, we check the members themselves.  In order to handle
1143          a few tricky cases, such as when FRIEND_DECL's are
1144
1145            template <class T> friend void A<T>::g(T t);
1146            template <class T> template <T t> friend void A<T>::h();
1147
1148          and DECL's are
1149
1150            void A<int>::g(int);
1151            template <int> void A<int>::h();
1152
1153          we need to figure out ARGS, the template arguments from
1154          the context of DECL.  This is required for template substitution
1155          of `T' in the function parameter of `g' and template parameter
1156          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1157
1158       tree context = DECL_CONTEXT (decl);
1159       tree args = NULL_TREE;
1160       int current_depth = 0;
1161
1162       while (current_depth < template_depth)
1163         {
1164           if (CLASSTYPE_TEMPLATE_INFO (context))
1165             {
1166               if (current_depth == 0)
1167                 args = TYPE_TI_ARGS (context);
1168               else
1169                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1170               current_depth++;
1171             }
1172           context = TYPE_CONTEXT (context);
1173         }
1174
1175       if (TREE_CODE (decl) == FUNCTION_DECL)
1176         {
1177           bool is_template;
1178           tree friend_type;
1179           tree decl_type;
1180           tree friend_args_type;
1181           tree decl_args_type;
1182
1183           /* Make sure that both DECL and FRIEND_DECL are templates or
1184              non-templates.  */
1185           is_template = DECL_TEMPLATE_INFO (decl)
1186                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1187           if (need_template ^ is_template)
1188             return false;
1189           else if (is_template)
1190             {
1191               /* If both are templates, check template parameter list.  */
1192               tree friend_parms
1193                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1194                                          args, tf_none);
1195               if (!comp_template_parms
1196                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1197                       friend_parms))
1198                 return false;
1199
1200               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1201             }
1202           else
1203             decl_type = TREE_TYPE (decl);
1204
1205           friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1206                                               tf_none, NULL_TREE);
1207           if (friend_type == error_mark_node)
1208             return false;
1209
1210           /* Check if return types match.  */
1211           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1212             return false;
1213
1214           /* Check if function parameter types match, ignoring the
1215              `this' parameter.  */
1216           friend_args_type = TYPE_ARG_TYPES (friend_type);
1217           decl_args_type = TYPE_ARG_TYPES (decl_type);
1218           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1219             friend_args_type = TREE_CHAIN (friend_args_type);
1220           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1221             decl_args_type = TREE_CHAIN (decl_args_type);
1222
1223           return compparms (decl_args_type, friend_args_type);
1224         }
1225       else
1226         {
1227           /* DECL is a TYPE_DECL */
1228           bool is_template;
1229           tree decl_type = TREE_TYPE (decl);
1230
1231           /* Make sure that both DECL and FRIEND_DECL are templates or
1232              non-templates.  */
1233           is_template
1234             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1235               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1236
1237           if (need_template ^ is_template)
1238             return false;
1239           else if (is_template)
1240             {
1241               tree friend_parms;
1242               /* If both are templates, check the name of the two
1243                  TEMPLATE_DECL's first because is_friend didn't.  */
1244               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1245                   != DECL_NAME (friend_decl))
1246                 return false;
1247
1248               /* Now check template parameter list.  */
1249               friend_parms
1250                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1251                                          args, tf_none);
1252               return comp_template_parms
1253                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1254                  friend_parms);
1255             }
1256           else
1257             return (DECL_NAME (decl)
1258                     == DECL_NAME (friend_decl));
1259         }
1260     }
1261   return false;
1262 }
1263
1264 /* Register the specialization SPEC as a specialization of TMPL with
1265    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1266    is actually just a friend declaration.  Returns SPEC, or an
1267    equivalent prior declaration, if available.  */
1268
1269 static tree
1270 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1271                          hashval_t hash)
1272 {
1273   tree fn;
1274   spec_entry **slot = NULL;
1275   spec_entry elt;
1276
1277   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec));
1278
1279   if (TREE_CODE (spec) == FUNCTION_DECL
1280       && uses_template_parms (DECL_TI_ARGS (spec)))
1281     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1282        register it; we want the corresponding TEMPLATE_DECL instead.
1283        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1284        the more obvious `uses_template_parms (spec)' to avoid problems
1285        with default function arguments.  In particular, given
1286        something like this:
1287
1288           template <class T> void f(T t1, T t = T())
1289
1290        the default argument expression is not substituted for in an
1291        instantiation unless and until it is actually needed.  */
1292     return spec;
1293
1294   if (optimize_specialization_lookup_p (tmpl))
1295     /* We don't put these specializations in the hash table, but we might
1296        want to give an error about a mismatch.  */
1297     fn = retrieve_specialization (tmpl, args, 0);
1298   else
1299     {
1300       elt.tmpl = tmpl;
1301       elt.args = args;
1302       elt.spec = spec;
1303
1304       if (hash == 0)
1305         hash = hash_specialization (&elt);
1306
1307       slot = (spec_entry **)
1308         htab_find_slot_with_hash (decl_specializations, &elt, hash, INSERT);
1309       if (*slot)
1310         fn = (*slot)->spec;
1311       else
1312         fn = NULL_TREE;
1313     }
1314
1315   /* We can sometimes try to re-register a specialization that we've
1316      already got.  In particular, regenerate_decl_from_template calls
1317      duplicate_decls which will update the specialization list.  But,
1318      we'll still get called again here anyhow.  It's more convenient
1319      to simply allow this than to try to prevent it.  */
1320   if (fn == spec)
1321     return spec;
1322   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1323     {
1324       if (DECL_TEMPLATE_INSTANTIATION (fn))
1325         {
1326           if (DECL_ODR_USED (fn)
1327               || DECL_EXPLICIT_INSTANTIATION (fn))
1328             {
1329               error ("specialization of %qD after instantiation",
1330                      fn);
1331               return error_mark_node;
1332             }
1333           else
1334             {
1335               tree clone;
1336               /* This situation should occur only if the first
1337                  specialization is an implicit instantiation, the
1338                  second is an explicit specialization, and the
1339                  implicit instantiation has not yet been used.  That
1340                  situation can occur if we have implicitly
1341                  instantiated a member function and then specialized
1342                  it later.
1343
1344                  We can also wind up here if a friend declaration that
1345                  looked like an instantiation turns out to be a
1346                  specialization:
1347
1348                    template <class T> void foo(T);
1349                    class S { friend void foo<>(int) };
1350                    template <> void foo(int);
1351
1352                  We transform the existing DECL in place so that any
1353                  pointers to it become pointers to the updated
1354                  declaration.
1355
1356                  If there was a definition for the template, but not
1357                  for the specialization, we want this to look as if
1358                  there were no definition, and vice versa.  */
1359               DECL_INITIAL (fn) = NULL_TREE;
1360               duplicate_decls (spec, fn, is_friend);
1361               /* The call to duplicate_decls will have applied
1362                  [temp.expl.spec]:
1363
1364                    An explicit specialization of a function template
1365                    is inline only if it is explicitly declared to be,
1366                    and independently of whether its function template
1367                    is.
1368
1369                 to the primary function; now copy the inline bits to
1370                 the various clones.  */
1371               FOR_EACH_CLONE (clone, fn)
1372                 {
1373                   DECL_DECLARED_INLINE_P (clone)
1374                     = DECL_DECLARED_INLINE_P (fn);
1375                   DECL_SOURCE_LOCATION (clone)
1376                     = DECL_SOURCE_LOCATION (fn);
1377                 }
1378               check_specialization_namespace (fn);
1379
1380               return fn;
1381             }
1382         }
1383       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1384         {
1385           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1386             /* Dup decl failed, but this is a new definition. Set the
1387                line number so any errors match this new
1388                definition.  */
1389             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1390
1391           return fn;
1392         }
1393     }
1394   else if (fn)
1395     return duplicate_decls (spec, fn, is_friend);
1396
1397   /* A specialization must be declared in the same namespace as the
1398      template it is specializing.  */
1399   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1400       && !check_specialization_namespace (tmpl))
1401     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1402
1403   if (!optimize_specialization_lookup_p (tmpl))
1404     {
1405       gcc_assert (tmpl && args && spec);
1406       *slot = GGC_NEW (spec_entry);
1407       **slot = elt;
1408       if (TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1409           && PRIMARY_TEMPLATE_P (tmpl)
1410           && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1411         /* TMPL is a forward declaration of a template function; keep a list
1412            of all specializations in case we need to reassign them to a friend
1413            template later in tsubst_friend_function.  */
1414         DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1415           = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1416     }
1417
1418   return spec;
1419 }
1420
1421 /* Returns true iff two spec_entry nodes are equivalent.  Only compares the
1422    TMPL and ARGS members, ignores SPEC.  */
1423
1424 static int
1425 eq_specializations (const void *p1, const void *p2)
1426 {
1427   const spec_entry *e1 = (const spec_entry *)p1;
1428   const spec_entry *e2 = (const spec_entry *)p2;
1429
1430   return (e1->tmpl == e2->tmpl
1431           && comp_template_args (e1->args, e2->args));
1432 }
1433
1434 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1435
1436 static hashval_t
1437 hash_tmpl_and_args (tree tmpl, tree args)
1438 {
1439   hashval_t val = DECL_UID (tmpl);
1440   return iterative_hash_template_arg (args, val);
1441 }
1442
1443 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1444    ignoring SPEC.  */
1445
1446 static hashval_t
1447 hash_specialization (const void *p)
1448 {
1449   const spec_entry *e = (const spec_entry *)p;
1450   return hash_tmpl_and_args (e->tmpl, e->args);
1451 }
1452
1453 /* Recursively calculate a hash value for a template argument ARG, for use
1454    in the hash tables of template specializations.  */
1455
1456 static hashval_t
1457 iterative_hash_template_arg (tree arg, hashval_t val)
1458 {
1459   unsigned HOST_WIDE_INT i;
1460   enum tree_code code;
1461   char tclass;
1462
1463   if (arg == NULL_TREE)
1464     return iterative_hash_object (arg, val);
1465
1466   if (!TYPE_P (arg))
1467     STRIP_NOPS (arg);
1468
1469   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
1470     /* We can get one of these when re-hashing a previous entry in the middle
1471        of substituting into a pack expansion.  Just look through it.  */
1472     arg = ARGUMENT_PACK_SELECT_FROM_PACK (arg);
1473
1474   code = TREE_CODE (arg);
1475   tclass = TREE_CODE_CLASS (code);
1476
1477   val = iterative_hash_object (code, val);
1478
1479   switch (code)
1480     {
1481     case ERROR_MARK:
1482       return val;
1483
1484     case IDENTIFIER_NODE:
1485       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1486
1487     case TREE_VEC:
1488       {
1489         int i, len = TREE_VEC_LENGTH (arg);
1490         for (i = 0; i < len; ++i)
1491           val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1492         return val;
1493       }
1494
1495     case TYPE_PACK_EXPANSION:
1496     case EXPR_PACK_EXPANSION:
1497       return iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1498
1499     case TYPE_ARGUMENT_PACK:
1500     case NONTYPE_ARGUMENT_PACK:
1501       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1502
1503     case TREE_LIST:
1504       for (; arg; arg = TREE_CHAIN (arg))
1505         val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1506       return val;
1507
1508     case OVERLOAD:
1509       for (; arg; arg = OVL_CHAIN (arg))
1510         val = iterative_hash_template_arg (OVL_FUNCTION (arg), val);
1511       return val;
1512
1513     case CONSTRUCTOR:
1514       {
1515         tree field, value;
1516         FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1517           {
1518             val = iterative_hash_template_arg (field, val);
1519             val = iterative_hash_template_arg (value, val);
1520           }
1521         return val;
1522       }
1523
1524     case PARM_DECL:
1525       if (!DECL_ARTIFICIAL (arg))
1526         val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1527       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1528
1529     case TARGET_EXPR:
1530       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1531
1532     case PTRMEM_CST:
1533       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1534       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1535
1536     case TEMPLATE_PARM_INDEX:
1537       val = iterative_hash_template_arg
1538         (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1539       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1540       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1541
1542     case TRAIT_EXPR:
1543       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1544       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1545       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1546
1547     case BASELINK:
1548       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1549                                          val);
1550       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1551                                           val);
1552
1553     case MODOP_EXPR:
1554       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1555       code = TREE_CODE (TREE_OPERAND (arg, 1));
1556       val = iterative_hash_object (code, val);
1557       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1558
1559     case ARRAY_TYPE:
1560       /* layout_type sets structural equality for arrays of
1561          incomplete type, so we can't rely on the canonical type
1562          for hashing.  */
1563       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1564       return iterative_hash_template_arg (TYPE_DOMAIN (arg), val);
1565
1566     default:
1567       switch (tclass)
1568         {
1569         case tcc_type:
1570           if (TYPE_CANONICAL (arg))
1571             return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1572                                           val);
1573           else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1574             return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1575           /* Otherwise just compare the types during lookup.  */
1576           return val;
1577
1578         case tcc_declaration:
1579         case tcc_constant:
1580           return iterative_hash_expr (arg, val);
1581
1582         default:
1583           gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1584           {
1585             unsigned n = TREE_OPERAND_LENGTH (arg);
1586             for (i = 0; i < n; ++i)
1587               val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1588             return val;
1589           }
1590         }
1591     }
1592   gcc_unreachable ();
1593   return 0;
1594 }
1595
1596 /* Unregister the specialization SPEC as a specialization of TMPL.
1597    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1598    if the SPEC was listed as a specialization of TMPL.
1599
1600    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1601
1602 bool
1603 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1604 {
1605   spec_entry **slot;
1606   spec_entry elt;
1607
1608   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1609   elt.args = TI_ARGS (tinfo);
1610   elt.spec = NULL_TREE;
1611
1612   slot = (spec_entry **) htab_find_slot (decl_specializations, &elt, INSERT);
1613   if (*slot)
1614     {
1615       gcc_assert ((*slot)->spec == spec || (*slot)->spec == new_spec);
1616       gcc_assert (new_spec != NULL_TREE);
1617       (*slot)->spec = new_spec;
1618       return 1;
1619     }
1620
1621   return 0;
1622 }
1623
1624 /* Compare an entry in the local specializations hash table P1 (which
1625    is really a pointer to a TREE_LIST) with P2 (which is really a
1626    DECL).  */
1627
1628 static int
1629 eq_local_specializations (const void *p1, const void *p2)
1630 {
1631   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1632 }
1633
1634 /* Hash P1, an entry in the local specializations table.  */
1635
1636 static hashval_t
1637 hash_local_specialization (const void* p1)
1638 {
1639   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1640 }
1641
1642 /* Like register_specialization, but for local declarations.  We are
1643    registering SPEC, an instantiation of TMPL.  */
1644
1645 static void
1646 register_local_specialization (tree spec, tree tmpl)
1647 {
1648   void **slot;
1649
1650   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1651                                    htab_hash_pointer (tmpl), INSERT);
1652   *slot = build_tree_list (spec, tmpl);
1653 }
1654
1655 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1656    specialized class.  */
1657
1658 bool
1659 explicit_class_specialization_p (tree type)
1660 {
1661   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1662     return false;
1663   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1664 }
1665
1666 /* Print the list of functions at FNS, going through all the overloads
1667    for each element of the list.  Alternatively, FNS can not be a
1668    TREE_LIST, in which case it will be printed together with all the
1669    overloads.
1670
1671    MORE and *STR should respectively be FALSE and NULL when the function
1672    is called from the outside.  They are used internally on recursive
1673    calls.  print_candidates manages the two parameters and leaves NULL
1674    in *STR when it ends.  */
1675
1676 static void
1677 print_candidates_1 (tree fns, bool more, const char **str)
1678 {
1679   tree fn, fn2;
1680   char *spaces = NULL;
1681
1682   for (fn = fns; fn; fn = OVL_NEXT (fn))
1683     if (TREE_CODE (fn) == TREE_LIST)
1684       {
1685         gcc_assert (!OVL_NEXT (fn) && !is_overloaded_fn (fn));
1686         for (fn2 = fn; fn2 != NULL_TREE; fn2 = TREE_CHAIN (fn2))
1687           print_candidates_1 (TREE_VALUE (fn2),
1688                               TREE_CHAIN (fn2) || more, str);
1689       }
1690     else
1691       {
1692         if (!*str)
1693           {
1694             /* Pick the prefix string.  */
1695             if (!more && !OVL_NEXT (fns))
1696               {
1697                 error ("candidate is: %+#D", OVL_CURRENT (fn));
1698                 continue;
1699               }
1700
1701             *str = _("candidates are:");
1702             spaces = get_spaces (*str);
1703           }
1704         error ("%s %+#D", *str, OVL_CURRENT (fn));
1705         *str = spaces ? spaces : *str;
1706       }
1707
1708   if (!more)
1709     {
1710       free (spaces);
1711       *str = NULL;
1712     }
1713 }
1714
1715 /* Print the list of candidate FNS in an error message.  */
1716
1717 void
1718 print_candidates (tree fns)
1719 {
1720   const char *str = NULL;
1721   print_candidates_1 (fns, false, &str);
1722   gcc_assert (str == NULL);
1723 }
1724
1725 /* Returns the template (one of the functions given by TEMPLATE_ID)
1726    which can be specialized to match the indicated DECL with the
1727    explicit template args given in TEMPLATE_ID.  The DECL may be
1728    NULL_TREE if none is available.  In that case, the functions in
1729    TEMPLATE_ID are non-members.
1730
1731    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1732    specialization of a member template.
1733
1734    The TEMPLATE_COUNT is the number of references to qualifying
1735    template classes that appeared in the name of the function. See
1736    check_explicit_specialization for a more accurate description.
1737
1738    TSK indicates what kind of template declaration (if any) is being
1739    declared.  TSK_TEMPLATE indicates that the declaration given by
1740    DECL, though a FUNCTION_DECL, has template parameters, and is
1741    therefore a template function.
1742
1743    The template args (those explicitly specified and those deduced)
1744    are output in a newly created vector *TARGS_OUT.
1745
1746    If it is impossible to determine the result, an error message is
1747    issued.  The error_mark_node is returned to indicate failure.  */
1748
1749 static tree
1750 determine_specialization (tree template_id,
1751                           tree decl,
1752                           tree* targs_out,
1753                           int need_member_template,
1754                           int template_count,
1755                           tmpl_spec_kind tsk)
1756 {
1757   tree fns;
1758   tree targs;
1759   tree explicit_targs;
1760   tree candidates = NULL_TREE;
1761   /* A TREE_LIST of templates of which DECL may be a specialization.
1762      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1763      corresponding TREE_PURPOSE is the set of template arguments that,
1764      when used to instantiate the template, would produce a function
1765      with the signature of DECL.  */
1766   tree templates = NULL_TREE;
1767   int header_count;
1768   struct cp_binding_level *b;
1769
1770   *targs_out = NULL_TREE;
1771
1772   if (template_id == error_mark_node || decl == error_mark_node)
1773     return error_mark_node;
1774
1775   fns = TREE_OPERAND (template_id, 0);
1776   explicit_targs = TREE_OPERAND (template_id, 1);
1777
1778   if (fns == error_mark_node)
1779     return error_mark_node;
1780
1781   /* Check for baselinks.  */
1782   if (BASELINK_P (fns))
1783     fns = BASELINK_FUNCTIONS (fns);
1784
1785   if (!is_overloaded_fn (fns))
1786     {
1787       error ("%qD is not a function template", fns);
1788       return error_mark_node;
1789     }
1790
1791   /* Count the number of template headers specified for this
1792      specialization.  */
1793   header_count = 0;
1794   for (b = current_binding_level;
1795        b->kind == sk_template_parms;
1796        b = b->level_chain)
1797     ++header_count;
1798
1799   for (; fns; fns = OVL_NEXT (fns))
1800     {
1801       tree fn = OVL_CURRENT (fns);
1802
1803       if (TREE_CODE (fn) == TEMPLATE_DECL)
1804         {
1805           tree decl_arg_types;
1806           tree fn_arg_types;
1807
1808           /* In case of explicit specialization, we need to check if
1809              the number of template headers appearing in the specialization
1810              is correct. This is usually done in check_explicit_specialization,
1811              but the check done there cannot be exhaustive when specializing
1812              member functions. Consider the following code:
1813
1814              template <> void A<int>::f(int);
1815              template <> template <> void A<int>::f(int);
1816
1817              Assuming that A<int> is not itself an explicit specialization
1818              already, the first line specializes "f" which is a non-template
1819              member function, whilst the second line specializes "f" which
1820              is a template member function. So both lines are syntactically
1821              correct, and check_explicit_specialization does not reject
1822              them.
1823
1824              Here, we can do better, as we are matching the specialization
1825              against the declarations. We count the number of template
1826              headers, and we check if they match TEMPLATE_COUNT + 1
1827              (TEMPLATE_COUNT is the number of qualifying template classes,
1828              plus there must be another header for the member template
1829              itself).
1830
1831              Notice that if header_count is zero, this is not a
1832              specialization but rather a template instantiation, so there
1833              is no check we can perform here.  */
1834           if (header_count && header_count != template_count + 1)
1835             continue;
1836
1837           /* Check that the number of template arguments at the
1838              innermost level for DECL is the same as for FN.  */
1839           if (current_binding_level->kind == sk_template_parms
1840               && !current_binding_level->explicit_spec_p
1841               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1842                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1843                                       (current_template_parms))))
1844             continue;
1845
1846           /* DECL might be a specialization of FN.  */
1847           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1848           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1849
1850           /* For a non-static member function, we need to make sure
1851              that the const qualification is the same.  Since
1852              get_bindings does not try to merge the "this" parameter,
1853              we must do the comparison explicitly.  */
1854           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1855               && !same_type_p (TREE_VALUE (fn_arg_types),
1856                                TREE_VALUE (decl_arg_types)))
1857             continue;
1858
1859           /* Skip the "this" parameter and, for constructors of
1860              classes with virtual bases, the VTT parameter.  A
1861              full specialization of a constructor will have a VTT
1862              parameter, but a template never will.  */ 
1863           decl_arg_types 
1864             = skip_artificial_parms_for (decl, decl_arg_types);
1865           fn_arg_types 
1866             = skip_artificial_parms_for (fn, fn_arg_types);
1867
1868           /* Check that the number of function parameters matches.
1869              For example,
1870                template <class T> void f(int i = 0);
1871                template <> void f<int>();
1872              The specialization f<int> is invalid but is not caught
1873              by get_bindings below.  */
1874           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1875             continue;
1876
1877           /* Function templates cannot be specializations; there are
1878              no partial specializations of functions.  Therefore, if
1879              the type of DECL does not match FN, there is no
1880              match.  */
1881           if (tsk == tsk_template)
1882             {
1883               if (compparms (fn_arg_types, decl_arg_types))
1884                 candidates = tree_cons (NULL_TREE, fn, candidates);
1885               continue;
1886             }
1887
1888           /* See whether this function might be a specialization of this
1889              template.  */
1890           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1891
1892           if (!targs)
1893             /* We cannot deduce template arguments that when used to
1894                specialize TMPL will produce DECL.  */
1895             continue;
1896
1897           /* Save this template, and the arguments deduced.  */
1898           templates = tree_cons (targs, fn, templates);
1899         }
1900       else if (need_member_template)
1901         /* FN is an ordinary member function, and we need a
1902            specialization of a member template.  */
1903         ;
1904       else if (TREE_CODE (fn) != FUNCTION_DECL)
1905         /* We can get IDENTIFIER_NODEs here in certain erroneous
1906            cases.  */
1907         ;
1908       else if (!DECL_FUNCTION_MEMBER_P (fn))
1909         /* This is just an ordinary non-member function.  Nothing can
1910            be a specialization of that.  */
1911         ;
1912       else if (DECL_ARTIFICIAL (fn))
1913         /* Cannot specialize functions that are created implicitly.  */
1914         ;
1915       else
1916         {
1917           tree decl_arg_types;
1918
1919           /* This is an ordinary member function.  However, since
1920              we're here, we can assume it's enclosing class is a
1921              template class.  For example,
1922
1923                template <typename T> struct S { void f(); };
1924                template <> void S<int>::f() {}
1925
1926              Here, S<int>::f is a non-template, but S<int> is a
1927              template class.  If FN has the same type as DECL, we
1928              might be in business.  */
1929
1930           if (!DECL_TEMPLATE_INFO (fn))
1931             /* Its enclosing class is an explicit specialization
1932                of a template class.  This is not a candidate.  */
1933             continue;
1934
1935           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1936                             TREE_TYPE (TREE_TYPE (fn))))
1937             /* The return types differ.  */
1938             continue;
1939
1940           /* Adjust the type of DECL in case FN is a static member.  */
1941           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1942           if (DECL_STATIC_FUNCTION_P (fn)
1943               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1944             decl_arg_types = TREE_CHAIN (decl_arg_types);
1945
1946           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1947                          decl_arg_types))
1948             /* They match!  */
1949             candidates = tree_cons (NULL_TREE, fn, candidates);
1950         }
1951     }
1952
1953   if (templates && TREE_CHAIN (templates))
1954     {
1955       /* We have:
1956
1957            [temp.expl.spec]
1958
1959            It is possible for a specialization with a given function
1960            signature to be instantiated from more than one function
1961            template.  In such cases, explicit specification of the
1962            template arguments must be used to uniquely identify the
1963            function template specialization being specialized.
1964
1965          Note that here, there's no suggestion that we're supposed to
1966          determine which of the candidate templates is most
1967          specialized.  However, we, also have:
1968
1969            [temp.func.order]
1970
1971            Partial ordering of overloaded function template
1972            declarations is used in the following contexts to select
1973            the function template to which a function template
1974            specialization refers:
1975
1976            -- when an explicit specialization refers to a function
1977               template.
1978
1979          So, we do use the partial ordering rules, at least for now.
1980          This extension can only serve to make invalid programs valid,
1981          so it's safe.  And, there is strong anecdotal evidence that
1982          the committee intended the partial ordering rules to apply;
1983          the EDG front end has that behavior, and John Spicer claims
1984          that the committee simply forgot to delete the wording in
1985          [temp.expl.spec].  */
1986       tree tmpl = most_specialized_instantiation (templates);
1987       if (tmpl != error_mark_node)
1988         {
1989           templates = tmpl;
1990           TREE_CHAIN (templates) = NULL_TREE;
1991         }
1992     }
1993
1994   if (templates == NULL_TREE && candidates == NULL_TREE)
1995     {
1996       error ("template-id %qD for %q+D does not match any template "
1997              "declaration", template_id, decl);
1998       if (header_count && header_count != template_count + 1)
1999         inform (input_location, "saw %d %<template<>%>, need %d for "
2000                 "specializing a member function template",
2001                 header_count, template_count + 1);
2002       return error_mark_node;
2003     }
2004   else if ((templates && TREE_CHAIN (templates))
2005            || (candidates && TREE_CHAIN (candidates))
2006            || (templates && candidates))
2007     {
2008       error ("ambiguous template specialization %qD for %q+D",
2009              template_id, decl);
2010       candidates = chainon (candidates, templates);
2011       print_candidates (candidates);
2012       return error_mark_node;
2013     }
2014
2015   /* We have one, and exactly one, match.  */
2016   if (candidates)
2017     {
2018       tree fn = TREE_VALUE (candidates);
2019       *targs_out = copy_node (DECL_TI_ARGS (fn));
2020       /* DECL is a re-declaration or partial instantiation of a template
2021          function.  */
2022       if (TREE_CODE (fn) == TEMPLATE_DECL)
2023         return fn;
2024       /* It was a specialization of an ordinary member function in a
2025          template class.  */
2026       return DECL_TI_TEMPLATE (fn);
2027     }
2028
2029   /* It was a specialization of a template.  */
2030   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2031   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2032     {
2033       *targs_out = copy_node (targs);
2034       SET_TMPL_ARGS_LEVEL (*targs_out,
2035                            TMPL_ARGS_DEPTH (*targs_out),
2036                            TREE_PURPOSE (templates));
2037     }
2038   else
2039     *targs_out = TREE_PURPOSE (templates);
2040   return TREE_VALUE (templates);
2041 }
2042
2043 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2044    but with the default argument values filled in from those in the
2045    TMPL_TYPES.  */
2046
2047 static tree
2048 copy_default_args_to_explicit_spec_1 (tree spec_types,
2049                                       tree tmpl_types)
2050 {
2051   tree new_spec_types;
2052
2053   if (!spec_types)
2054     return NULL_TREE;
2055
2056   if (spec_types == void_list_node)
2057     return void_list_node;
2058
2059   /* Substitute into the rest of the list.  */
2060   new_spec_types =
2061     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2062                                           TREE_CHAIN (tmpl_types));
2063
2064   /* Add the default argument for this parameter.  */
2065   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2066                          TREE_VALUE (spec_types),
2067                          new_spec_types);
2068 }
2069
2070 /* DECL is an explicit specialization.  Replicate default arguments
2071    from the template it specializes.  (That way, code like:
2072
2073      template <class T> void f(T = 3);
2074      template <> void f(double);
2075      void g () { f (); }
2076
2077    works, as required.)  An alternative approach would be to look up
2078    the correct default arguments at the call-site, but this approach
2079    is consistent with how implicit instantiations are handled.  */
2080
2081 static void
2082 copy_default_args_to_explicit_spec (tree decl)
2083 {
2084   tree tmpl;
2085   tree spec_types;
2086   tree tmpl_types;
2087   tree new_spec_types;
2088   tree old_type;
2089   tree new_type;
2090   tree t;
2091   tree object_type = NULL_TREE;
2092   tree in_charge = NULL_TREE;
2093   tree vtt = NULL_TREE;
2094
2095   /* See if there's anything we need to do.  */
2096   tmpl = DECL_TI_TEMPLATE (decl);
2097   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2098   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2099     if (TREE_PURPOSE (t))
2100       break;
2101   if (!t)
2102     return;
2103
2104   old_type = TREE_TYPE (decl);
2105   spec_types = TYPE_ARG_TYPES (old_type);
2106
2107   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2108     {
2109       /* Remove the this pointer, but remember the object's type for
2110          CV quals.  */
2111       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2112       spec_types = TREE_CHAIN (spec_types);
2113       tmpl_types = TREE_CHAIN (tmpl_types);
2114
2115       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2116         {
2117           /* DECL may contain more parameters than TMPL due to the extra
2118              in-charge parameter in constructors and destructors.  */
2119           in_charge = spec_types;
2120           spec_types = TREE_CHAIN (spec_types);
2121         }
2122       if (DECL_HAS_VTT_PARM_P (decl))
2123         {
2124           vtt = spec_types;
2125           spec_types = TREE_CHAIN (spec_types);
2126         }
2127     }
2128
2129   /* Compute the merged default arguments.  */
2130   new_spec_types =
2131     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2132
2133   /* Compute the new FUNCTION_TYPE.  */
2134   if (object_type)
2135     {
2136       if (vtt)
2137         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2138                                          TREE_VALUE (vtt),
2139                                          new_spec_types);
2140
2141       if (in_charge)
2142         /* Put the in-charge parameter back.  */
2143         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2144                                          TREE_VALUE (in_charge),
2145                                          new_spec_types);
2146
2147       new_type = build_method_type_directly (object_type,
2148                                              TREE_TYPE (old_type),
2149                                              new_spec_types);
2150     }
2151   else
2152     new_type = build_function_type (TREE_TYPE (old_type),
2153                                     new_spec_types);
2154   new_type = cp_build_type_attribute_variant (new_type,
2155                                               TYPE_ATTRIBUTES (old_type));
2156   new_type = build_exception_variant (new_type,
2157                                       TYPE_RAISES_EXCEPTIONS (old_type));
2158   TREE_TYPE (decl) = new_type;
2159 }
2160
2161 /* Check to see if the function just declared, as indicated in
2162    DECLARATOR, and in DECL, is a specialization of a function
2163    template.  We may also discover that the declaration is an explicit
2164    instantiation at this point.
2165
2166    Returns DECL, or an equivalent declaration that should be used
2167    instead if all goes well.  Issues an error message if something is
2168    amiss.  Returns error_mark_node if the error is not easily
2169    recoverable.
2170
2171    FLAGS is a bitmask consisting of the following flags:
2172
2173    2: The function has a definition.
2174    4: The function is a friend.
2175
2176    The TEMPLATE_COUNT is the number of references to qualifying
2177    template classes that appeared in the name of the function.  For
2178    example, in
2179
2180      template <class T> struct S { void f(); };
2181      void S<int>::f();
2182
2183    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2184    classes are not counted in the TEMPLATE_COUNT, so that in
2185
2186      template <class T> struct S {};
2187      template <> struct S<int> { void f(); }
2188      template <> void S<int>::f();
2189
2190    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2191    invalid; there should be no template <>.)
2192
2193    If the function is a specialization, it is marked as such via
2194    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2195    is set up correctly, and it is added to the list of specializations
2196    for that template.  */
2197
2198 tree
2199 check_explicit_specialization (tree declarator,
2200                                tree decl,
2201                                int template_count,
2202                                int flags)
2203 {
2204   int have_def = flags & 2;
2205   int is_friend = flags & 4;
2206   int specialization = 0;
2207   int explicit_instantiation = 0;
2208   int member_specialization = 0;
2209   tree ctype = DECL_CLASS_CONTEXT (decl);
2210   tree dname = DECL_NAME (decl);
2211   tmpl_spec_kind tsk;
2212
2213   if (is_friend)
2214     {
2215       if (!processing_specialization)
2216         tsk = tsk_none;
2217       else
2218         tsk = tsk_excessive_parms;
2219     }
2220   else
2221     tsk = current_tmpl_spec_kind (template_count);
2222
2223   switch (tsk)
2224     {
2225     case tsk_none:
2226       if (processing_specialization)
2227         {
2228           specialization = 1;
2229           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2230         }
2231       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2232         {
2233           if (is_friend)
2234             /* This could be something like:
2235
2236                template <class T> void f(T);
2237                class S { friend void f<>(int); }  */
2238             specialization = 1;
2239           else
2240             {
2241               /* This case handles bogus declarations like template <>
2242                  template <class T> void f<int>(); */
2243
2244               error ("template-id %qD in declaration of primary template",
2245                      declarator);
2246               return decl;
2247             }
2248         }
2249       break;
2250
2251     case tsk_invalid_member_spec:
2252       /* The error has already been reported in
2253          check_specialization_scope.  */
2254       return error_mark_node;
2255
2256     case tsk_invalid_expl_inst:
2257       error ("template parameter list used in explicit instantiation");
2258
2259       /* Fall through.  */
2260
2261     case tsk_expl_inst:
2262       if (have_def)
2263         error ("definition provided for explicit instantiation");
2264
2265       explicit_instantiation = 1;
2266       break;
2267
2268     case tsk_excessive_parms:
2269     case tsk_insufficient_parms:
2270       if (tsk == tsk_excessive_parms)
2271         error ("too many template parameter lists in declaration of %qD",
2272                decl);
2273       else if (template_header_count)
2274         error("too few template parameter lists in declaration of %qD", decl);
2275       else
2276         error("explicit specialization of %qD must be introduced by "
2277               "%<template <>%>", decl);
2278
2279       /* Fall through.  */
2280     case tsk_expl_spec:
2281       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2282       if (ctype)
2283         member_specialization = 1;
2284       else
2285         specialization = 1;
2286       break;
2287
2288     case tsk_template:
2289       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2290         {
2291           /* This case handles bogus declarations like template <>
2292              template <class T> void f<int>(); */
2293
2294           if (uses_template_parms (declarator))
2295             error ("function template partial specialization %qD "
2296                    "is not allowed", declarator);
2297           else
2298             error ("template-id %qD in declaration of primary template",
2299                    declarator);
2300           return decl;
2301         }
2302
2303       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2304         /* This is a specialization of a member template, without
2305            specialization the containing class.  Something like:
2306
2307              template <class T> struct S {
2308                template <class U> void f (U);
2309              };
2310              template <> template <class U> void S<int>::f(U) {}
2311
2312            That's a specialization -- but of the entire template.  */
2313         specialization = 1;
2314       break;
2315
2316     default:
2317       gcc_unreachable ();
2318     }
2319
2320   if (specialization || member_specialization)
2321     {
2322       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2323       for (; t; t = TREE_CHAIN (t))
2324         if (TREE_PURPOSE (t))
2325           {
2326             permerror (input_location, 
2327                        "default argument specified in explicit specialization");
2328             break;
2329           }
2330     }
2331
2332   if (specialization || member_specialization || explicit_instantiation)
2333     {
2334       tree tmpl = NULL_TREE;
2335       tree targs = NULL_TREE;
2336
2337       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2338       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2339         {
2340           tree fns;
2341
2342           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2343           if (ctype)
2344             fns = dname;
2345           else
2346             {
2347               /* If there is no class context, the explicit instantiation
2348                  must be at namespace scope.  */
2349               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2350
2351               /* Find the namespace binding, using the declaration
2352                  context.  */
2353               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2354                                            false, true);
2355               if (fns == error_mark_node || !is_overloaded_fn (fns))
2356                 {
2357                   error ("%qD is not a template function", dname);
2358                   fns = error_mark_node;
2359                 }
2360               else
2361                 {
2362                   tree fn = OVL_CURRENT (fns);
2363                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2364                                                 CP_DECL_CONTEXT (fn)))
2365                     error ("%qD is not declared in %qD",
2366                            decl, current_namespace);
2367                 }
2368             }
2369
2370           declarator = lookup_template_function (fns, NULL_TREE);
2371         }
2372
2373       if (declarator == error_mark_node)
2374         return error_mark_node;
2375
2376       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2377         {
2378           if (!explicit_instantiation)
2379             /* A specialization in class scope.  This is invalid,
2380                but the error will already have been flagged by
2381                check_specialization_scope.  */
2382             return error_mark_node;
2383           else
2384             {
2385               /* It's not valid to write an explicit instantiation in
2386                  class scope, e.g.:
2387
2388                    class C { template void f(); }
2389
2390                    This case is caught by the parser.  However, on
2391                    something like:
2392
2393                    template class C { void f(); };
2394
2395                    (which is invalid) we can get here.  The error will be
2396                    issued later.  */
2397               ;
2398             }
2399
2400           return decl;
2401         }
2402       else if (ctype != NULL_TREE
2403                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2404                    IDENTIFIER_NODE))
2405         {
2406           /* Find the list of functions in ctype that have the same
2407              name as the declared function.  */
2408           tree name = TREE_OPERAND (declarator, 0);
2409           tree fns = NULL_TREE;
2410           int idx;
2411
2412           if (constructor_name_p (name, ctype))
2413             {
2414               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2415
2416               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2417                   : !CLASSTYPE_DESTRUCTORS (ctype))
2418                 {
2419                   /* From [temp.expl.spec]:
2420
2421                      If such an explicit specialization for the member
2422                      of a class template names an implicitly-declared
2423                      special member function (clause _special_), the
2424                      program is ill-formed.
2425
2426                      Similar language is found in [temp.explicit].  */
2427                   error ("specialization of implicitly-declared special member function");
2428                   return error_mark_node;
2429                 }
2430
2431               name = is_constructor ? ctor_identifier : dtor_identifier;
2432             }
2433
2434           if (!DECL_CONV_FN_P (decl))
2435             {
2436               idx = lookup_fnfields_1 (ctype, name);
2437               if (idx >= 0)
2438                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2439             }
2440           else
2441             {
2442               VEC(tree,gc) *methods;
2443               tree ovl;
2444
2445               /* For a type-conversion operator, we cannot do a
2446                  name-based lookup.  We might be looking for `operator
2447                  int' which will be a specialization of `operator T'.
2448                  So, we find *all* the conversion operators, and then
2449                  select from them.  */
2450               fns = NULL_TREE;
2451
2452               methods = CLASSTYPE_METHOD_VEC (ctype);
2453               if (methods)
2454                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2455                      VEC_iterate (tree, methods, idx, ovl);
2456                      ++idx)
2457                   {
2458                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2459                       /* There are no more conversion functions.  */
2460                       break;
2461
2462                     /* Glue all these conversion functions together
2463                        with those we already have.  */
2464                     for (; ovl; ovl = OVL_NEXT (ovl))
2465                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2466                   }
2467             }
2468
2469           if (fns == NULL_TREE)
2470             {
2471               error ("no member function %qD declared in %qT", name, ctype);
2472               return error_mark_node;
2473             }
2474           else
2475             TREE_OPERAND (declarator, 0) = fns;
2476         }
2477
2478       /* Figure out what exactly is being specialized at this point.
2479          Note that for an explicit instantiation, even one for a
2480          member function, we cannot tell apriori whether the
2481          instantiation is for a member template, or just a member
2482          function of a template class.  Even if a member template is
2483          being instantiated, the member template arguments may be
2484          elided if they can be deduced from the rest of the
2485          declaration.  */
2486       tmpl = determine_specialization (declarator, decl,
2487                                        &targs,
2488                                        member_specialization,
2489                                        template_count,
2490                                        tsk);
2491
2492       if (!tmpl || tmpl == error_mark_node)
2493         /* We couldn't figure out what this declaration was
2494            specializing.  */
2495         return error_mark_node;
2496       else
2497         {
2498           tree gen_tmpl = most_general_template (tmpl);
2499
2500           if (explicit_instantiation)
2501             {
2502               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2503                  is done by do_decl_instantiation later.  */
2504
2505               int arg_depth = TMPL_ARGS_DEPTH (targs);
2506               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2507
2508               if (arg_depth > parm_depth)
2509                 {
2510                   /* If TMPL is not the most general template (for
2511                      example, if TMPL is a friend template that is
2512                      injected into namespace scope), then there will
2513                      be too many levels of TARGS.  Remove some of them
2514                      here.  */
2515                   int i;
2516                   tree new_targs;
2517
2518                   new_targs = make_tree_vec (parm_depth);
2519                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2520                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2521                       = TREE_VEC_ELT (targs, i);
2522                   targs = new_targs;
2523                 }
2524
2525               return instantiate_template (tmpl, targs, tf_error);
2526             }
2527
2528           /* If we thought that the DECL was a member function, but it
2529              turns out to be specializing a static member function,
2530              make DECL a static member function as well.  */
2531           if (DECL_STATIC_FUNCTION_P (tmpl)
2532               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2533             revert_static_member_fn (decl);
2534
2535           /* If this is a specialization of a member template of a
2536              template class, we want to return the TEMPLATE_DECL, not
2537              the specialization of it.  */
2538           if (tsk == tsk_template)
2539             {
2540               tree result = DECL_TEMPLATE_RESULT (tmpl);
2541               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2542               DECL_INITIAL (result) = NULL_TREE;
2543               if (have_def)
2544                 {
2545                   tree parm;
2546                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2547                   DECL_SOURCE_LOCATION (result)
2548                     = DECL_SOURCE_LOCATION (decl);
2549                   /* We want to use the argument list specified in the
2550                      definition, not in the original declaration.  */
2551                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2552                   for (parm = DECL_ARGUMENTS (result); parm;
2553                        parm = TREE_CHAIN (parm))
2554                     DECL_CONTEXT (parm) = result;
2555                 }
2556               return register_specialization (tmpl, gen_tmpl, targs,
2557                                               is_friend, 0);
2558             }
2559
2560           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2561           DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
2562
2563           /* Inherit default function arguments from the template
2564              DECL is specializing.  */
2565           copy_default_args_to_explicit_spec (decl);
2566
2567           /* This specialization has the same protection as the
2568              template it specializes.  */
2569           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2570           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2571
2572           /* 7.1.1-1 [dcl.stc]
2573
2574              A storage-class-specifier shall not be specified in an
2575              explicit specialization...
2576
2577              The parser rejects these, so unless action is taken here,
2578              explicit function specializations will always appear with
2579              global linkage.
2580
2581              The action recommended by the C++ CWG in response to C++
2582              defect report 605 is to make the storage class and linkage
2583              of the explicit specialization match the templated function:
2584
2585              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2586            */
2587           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2588             {
2589               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2590               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2591
2592               /* This specialization has the same linkage and visibility as
2593                  the function template it specializes.  */
2594               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2595               if (! TREE_PUBLIC (decl))
2596                 {
2597                   DECL_INTERFACE_KNOWN (decl) = 1;
2598                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2599                 }
2600               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2601               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2602                 {
2603                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2604                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2605                 }
2606             }
2607
2608           /* If DECL is a friend declaration, declared using an
2609              unqualified name, the namespace associated with DECL may
2610              have been set incorrectly.  For example, in:
2611
2612                template <typename T> void f(T);
2613                namespace N {
2614                  struct S { friend void f<int>(int); }
2615                }
2616
2617              we will have set the DECL_CONTEXT for the friend
2618              declaration to N, rather than to the global namespace.  */
2619           if (DECL_NAMESPACE_SCOPE_P (decl))
2620             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2621
2622           if (is_friend && !have_def)
2623             /* This is not really a declaration of a specialization.
2624                It's just the name of an instantiation.  But, it's not
2625                a request for an instantiation, either.  */
2626             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2627           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2628             /* This is indeed a specialization.  In case of constructors
2629                and destructors, we need in-charge and not-in-charge
2630                versions in V3 ABI.  */
2631             clone_function_decl (decl, /*update_method_vec_p=*/0);
2632
2633           /* Register this specialization so that we can find it
2634              again.  */
2635           decl = register_specialization (decl, gen_tmpl, targs, is_friend, 0);
2636         }
2637     }
2638
2639   return decl;
2640 }
2641
2642 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2643    parameters.  These are represented in the same format used for
2644    DECL_TEMPLATE_PARMS.  */
2645
2646 int
2647 comp_template_parms (const_tree parms1, const_tree parms2)
2648 {
2649   const_tree p1;
2650   const_tree p2;
2651
2652   if (parms1 == parms2)
2653     return 1;
2654
2655   for (p1 = parms1, p2 = parms2;
2656        p1 != NULL_TREE && p2 != NULL_TREE;
2657        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2658     {
2659       tree t1 = TREE_VALUE (p1);
2660       tree t2 = TREE_VALUE (p2);
2661       int i;
2662
2663       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2664       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2665
2666       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2667         return 0;
2668
2669       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2670         {
2671           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2672           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2673
2674           /* If either of the template parameters are invalid, assume
2675              they match for the sake of error recovery. */
2676           if (parm1 == error_mark_node || parm2 == error_mark_node)
2677             return 1;
2678
2679           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2680             return 0;
2681
2682           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2683               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2684                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2685             continue;
2686           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2687             return 0;
2688         }
2689     }
2690
2691   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2692     /* One set of parameters has more parameters lists than the
2693        other.  */
2694     return 0;
2695
2696   return 1;
2697 }
2698
2699 /* Determine whether PARM is a parameter pack.  */
2700
2701 bool 
2702 template_parameter_pack_p (const_tree parm)
2703 {
2704   /* Determine if we have a non-type template parameter pack.  */
2705   if (TREE_CODE (parm) == PARM_DECL)
2706     return (DECL_TEMPLATE_PARM_P (parm) 
2707             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2708
2709   /* If this is a list of template parameters, we could get a
2710      TYPE_DECL or a TEMPLATE_DECL.  */ 
2711   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2712     parm = TREE_TYPE (parm);
2713
2714   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2715            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2716           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2717 }
2718
2719 /* Determine if T is a function parameter pack.  */
2720
2721 bool
2722 function_parameter_pack_p (const_tree t)
2723 {
2724   if (t && TREE_CODE (t) == PARM_DECL)
2725     return FUNCTION_PARAMETER_PACK_P (t);
2726   return false;
2727 }
2728
2729 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
2730    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
2731
2732 tree
2733 get_function_template_decl (const_tree primary_func_tmpl_inst)
2734 {
2735   if (! primary_func_tmpl_inst
2736       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
2737       || ! primary_template_instantiation_p (primary_func_tmpl_inst))
2738     return NULL;
2739
2740   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
2741 }
2742
2743 /* Return true iff the function parameter PARAM_DECL was expanded
2744    from the function parameter pack PACK.  */
2745
2746 bool
2747 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
2748 {
2749   if (DECL_ARTIFICIAL (param_decl)
2750       || !function_parameter_pack_p (pack))
2751     return false;
2752
2753   /* The parameter pack and its pack arguments have the same
2754      DECL_PARM_INDEX.  */
2755   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
2756 }
2757
2758 /* Determine whether ARGS describes a variadic template args list,
2759    i.e., one that is terminated by a template argument pack.  */
2760
2761 static bool 
2762 template_args_variadic_p (tree args)
2763 {
2764   int nargs;
2765   tree last_parm;
2766
2767   if (args == NULL_TREE)
2768     return false;
2769
2770   args = INNERMOST_TEMPLATE_ARGS (args);
2771   nargs = TREE_VEC_LENGTH (args);
2772
2773   if (nargs == 0)
2774     return false;
2775
2776   last_parm = TREE_VEC_ELT (args, nargs - 1);
2777
2778   return ARGUMENT_PACK_P (last_parm);
2779 }
2780
2781 /* Generate a new name for the parameter pack name NAME (an
2782    IDENTIFIER_NODE) that incorporates its */
2783
2784 static tree
2785 make_ith_pack_parameter_name (tree name, int i)
2786 {
2787   /* Munge the name to include the parameter index.  */
2788 #define NUMBUF_LEN 128
2789   char numbuf[NUMBUF_LEN];
2790   char* newname;
2791   int newname_len;
2792
2793   snprintf (numbuf, NUMBUF_LEN, "%i", i);
2794   newname_len = IDENTIFIER_LENGTH (name)
2795                 + strlen (numbuf) + 2;
2796   newname = (char*)alloca (newname_len);
2797   snprintf (newname, newname_len,
2798             "%s#%i", IDENTIFIER_POINTER (name), i);
2799   return get_identifier (newname);
2800 }
2801
2802 /* Return true if T is a primary function
2803    or class template instantiation.  */
2804
2805 bool
2806 primary_template_instantiation_p (const_tree t)
2807 {
2808   if (!t)
2809     return false;
2810
2811   if (TREE_CODE (t) == FUNCTION_DECL)
2812     return DECL_LANG_SPECIFIC (t)
2813            && DECL_TEMPLATE_INSTANTIATION (t)
2814            && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t));
2815   else if (CLASS_TYPE_P (t))
2816     return CLASSTYPE_TEMPLATE_INSTANTIATION (t)
2817            && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t));
2818   return false;
2819 }
2820
2821 /* Return true if PARM is a template template parameter.  */
2822
2823 bool
2824 template_template_parameter_p (const_tree parm)
2825 {
2826   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
2827 }
2828
2829 /* Return the template parameters of T if T is a
2830    primary template instantiation, NULL otherwise.  */
2831
2832 tree
2833 get_primary_template_innermost_parameters (const_tree t)
2834 {
2835   tree parms = NULL, template_info = NULL;
2836
2837   if ((template_info = get_template_info (t))
2838       && primary_template_instantiation_p (t))
2839     parms = INNERMOST_TEMPLATE_PARMS
2840         (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
2841
2842   return parms;
2843 }
2844
2845 /* Return the template parameters of the LEVELth level from the full list
2846    of template parameters PARMS.  */
2847
2848 tree
2849 get_template_parms_at_level (tree parms, int level)
2850 {
2851   tree p;
2852   if (!parms
2853       || TREE_CODE (parms) != TREE_LIST
2854       || level > TMPL_PARMS_DEPTH (parms))
2855     return NULL_TREE;
2856
2857   for (p = parms; p; p = TREE_CHAIN (p))
2858     if (TMPL_PARMS_DEPTH (p) == level)
2859       return p;
2860
2861   return NULL_TREE;
2862 }
2863
2864 /* Returns the template arguments of T if T is a template instantiation,
2865    NULL otherwise.  */
2866
2867 tree
2868 get_template_innermost_arguments (const_tree t)
2869 {
2870   tree args = NULL, template_info = NULL;
2871
2872   if ((template_info = get_template_info (t))
2873       && TI_ARGS (template_info))
2874     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
2875
2876   return args;
2877 }
2878
2879 /* Return the argument pack elements of T if T is a template argument pack,
2880    NULL otherwise.  */
2881
2882 tree
2883 get_template_argument_pack_elems (const_tree t)
2884 {
2885   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
2886       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
2887     return NULL;
2888
2889   return ARGUMENT_PACK_ARGS (t);
2890 }
2891
2892 /* Structure used to track the progress of find_parameter_packs_r.  */
2893 struct find_parameter_pack_data 
2894 {
2895   /* TREE_LIST that will contain all of the parameter packs found by
2896      the traversal.  */
2897   tree* parameter_packs;
2898
2899   /* Set of AST nodes that have been visited by the traversal.  */
2900   struct pointer_set_t *visited;
2901 };
2902
2903 /* Identifies all of the argument packs that occur in a template
2904    argument and appends them to the TREE_LIST inside DATA, which is a
2905    find_parameter_pack_data structure. This is a subroutine of
2906    make_pack_expansion and uses_parameter_packs.  */
2907 static tree
2908 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2909 {
2910   tree t = *tp;
2911   struct find_parameter_pack_data* ppd = 
2912     (struct find_parameter_pack_data*)data;
2913   bool parameter_pack_p = false;
2914
2915   /* Identify whether this is a parameter pack or not.  */
2916   switch (TREE_CODE (t))
2917     {
2918     case TEMPLATE_PARM_INDEX:
2919       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2920         parameter_pack_p = true;
2921       break;
2922
2923     case TEMPLATE_TYPE_PARM:
2924     case TEMPLATE_TEMPLATE_PARM:
2925       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2926         parameter_pack_p = true;
2927       break;
2928
2929     case PARM_DECL:
2930       if (FUNCTION_PARAMETER_PACK_P (t))
2931         {
2932           /* We don't want to walk into the type of a PARM_DECL,
2933              because we don't want to see the type parameter pack.  */
2934           *walk_subtrees = 0;
2935           parameter_pack_p = true;
2936         }
2937       break;
2938
2939     default:
2940       /* Not a parameter pack.  */
2941       break;
2942     }
2943
2944   if (parameter_pack_p)
2945     {
2946       /* Add this parameter pack to the list.  */
2947       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2948     }
2949
2950   if (TYPE_P (t))
2951     cp_walk_tree (&TYPE_CONTEXT (t), 
2952                   &find_parameter_packs_r, ppd, ppd->visited);
2953
2954   /* This switch statement will return immediately if we don't find a
2955      parameter pack.  */
2956   switch (TREE_CODE (t)) 
2957     {
2958     case TEMPLATE_PARM_INDEX:
2959       return NULL_TREE;
2960
2961     case BOUND_TEMPLATE_TEMPLATE_PARM:
2962       /* Check the template itself.  */
2963       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
2964                     &find_parameter_packs_r, ppd, ppd->visited);
2965       /* Check the template arguments.  */
2966       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
2967                     ppd->visited);
2968       *walk_subtrees = 0;
2969       return NULL_TREE;
2970
2971     case TEMPLATE_TYPE_PARM:
2972     case TEMPLATE_TEMPLATE_PARM:
2973       return NULL_TREE;
2974
2975     case PARM_DECL:
2976       return NULL_TREE;
2977
2978     case RECORD_TYPE:
2979       if (TYPE_PTRMEMFUNC_P (t))
2980         return NULL_TREE;
2981       /* Fall through.  */
2982
2983     case UNION_TYPE:
2984     case ENUMERAL_TYPE:
2985       if (TYPE_TEMPLATE_INFO (t))
2986         cp_walk_tree (&TI_ARGS (TYPE_TEMPLATE_INFO (t)),
2987                       &find_parameter_packs_r, ppd, ppd->visited);
2988
2989       *walk_subtrees = 0;
2990       return NULL_TREE;
2991
2992     case TEMPLATE_DECL:
2993       cp_walk_tree (&TREE_TYPE (t),
2994                     &find_parameter_packs_r, ppd, ppd->visited);
2995       return NULL_TREE;
2996  
2997     case TYPENAME_TYPE:
2998       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
2999                    ppd, ppd->visited);
3000       *walk_subtrees = 0;
3001       return NULL_TREE;
3002       
3003     case TYPE_PACK_EXPANSION:
3004     case EXPR_PACK_EXPANSION:
3005       *walk_subtrees = 0;
3006       return NULL_TREE;
3007
3008     case INTEGER_TYPE:
3009       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
3010                     ppd, ppd->visited);
3011       *walk_subtrees = 0;
3012       return NULL_TREE;
3013
3014     case IDENTIFIER_NODE:
3015       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
3016                     ppd->visited);
3017       *walk_subtrees = 0;
3018       return NULL_TREE;
3019
3020     default:
3021       return NULL_TREE;
3022     }
3023
3024   return NULL_TREE;
3025 }
3026
3027 /* Determines if the expression or type T uses any parameter packs.  */
3028 bool
3029 uses_parameter_packs (tree t)
3030 {
3031   tree parameter_packs = NULL_TREE;
3032   struct find_parameter_pack_data ppd;
3033   ppd.parameter_packs = &parameter_packs;
3034   ppd.visited = pointer_set_create ();
3035   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3036   pointer_set_destroy (ppd.visited);
3037   return parameter_packs != NULL_TREE;
3038 }
3039
3040 /* Turn ARG, which may be an expression, type, or a TREE_LIST
3041    representation a base-class initializer into a parameter pack
3042    expansion. If all goes well, the resulting node will be an
3043    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
3044    respectively.  */
3045 tree 
3046 make_pack_expansion (tree arg)
3047 {
3048   tree result;
3049   tree parameter_packs = NULL_TREE;
3050   bool for_types = false;
3051   struct find_parameter_pack_data ppd;
3052
3053   if (!arg || arg == error_mark_node)
3054     return arg;
3055
3056   if (TREE_CODE (arg) == TREE_LIST)
3057     {
3058       /* The only time we will see a TREE_LIST here is for a base
3059          class initializer.  In this case, the TREE_PURPOSE will be a
3060          _TYPE node (representing the base class expansion we're
3061          initializing) and the TREE_VALUE will be a TREE_LIST
3062          containing the initialization arguments. 
3063
3064          The resulting expansion looks somewhat different from most
3065          expansions. Rather than returning just one _EXPANSION, we
3066          return a TREE_LIST whose TREE_PURPOSE is a
3067          TYPE_PACK_EXPANSION containing the bases that will be
3068          initialized.  The TREE_VALUE will be identical to the
3069          original TREE_VALUE, which is a list of arguments that will
3070          be passed to each base.  We do not introduce any new pack
3071          expansion nodes into the TREE_VALUE (although it is possible
3072          that some already exist), because the TREE_PURPOSE and
3073          TREE_VALUE all need to be expanded together with the same
3074          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3075          resulting TREE_PURPOSE will mention the parameter packs in
3076          both the bases and the arguments to the bases.  */
3077       tree purpose;
3078       tree value;
3079       tree parameter_packs = NULL_TREE;
3080
3081       /* Determine which parameter packs will be used by the base
3082          class expansion.  */
3083       ppd.visited = pointer_set_create ();
3084       ppd.parameter_packs = &parameter_packs;
3085       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
3086                     &ppd, ppd.visited);
3087
3088       if (parameter_packs == NULL_TREE)
3089         {
3090           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
3091           pointer_set_destroy (ppd.visited);
3092           return error_mark_node;
3093         }
3094
3095       if (TREE_VALUE (arg) != void_type_node)
3096         {
3097           /* Collect the sets of parameter packs used in each of the
3098              initialization arguments.  */
3099           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3100             {
3101               /* Determine which parameter packs will be expanded in this
3102                  argument.  */
3103               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
3104                             &ppd, ppd.visited);
3105             }
3106         }
3107
3108       pointer_set_destroy (ppd.visited);
3109
3110       /* Create the pack expansion type for the base type.  */
3111       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3112       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3113       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3114
3115       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3116          they will rarely be compared to anything.  */
3117       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3118
3119       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3120     }
3121
3122   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3123     for_types = true;
3124
3125   /* Build the PACK_EXPANSION_* node.  */
3126   result = for_types
3127      ? cxx_make_type (TYPE_PACK_EXPANSION)
3128      : make_node (EXPR_PACK_EXPANSION);
3129   SET_PACK_EXPANSION_PATTERN (result, arg);
3130   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3131     {
3132       /* Propagate type and const-expression information.  */
3133       TREE_TYPE (result) = TREE_TYPE (arg);
3134       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3135     }
3136   else
3137     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3138        they will rarely be compared to anything.  */
3139     SET_TYPE_STRUCTURAL_EQUALITY (result);
3140
3141   /* Determine which parameter packs will be expanded.  */
3142   ppd.parameter_packs = &parameter_packs;
3143   ppd.visited = pointer_set_create ();
3144   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3145   pointer_set_destroy (ppd.visited);
3146
3147   /* Make sure we found some parameter packs.  */
3148   if (parameter_packs == NULL_TREE)
3149     {
3150       if (TYPE_P (arg))
3151         error ("expansion pattern %<%T%> contains no argument packs", arg);
3152       else
3153         error ("expansion pattern %<%E%> contains no argument packs", arg);
3154       return error_mark_node;
3155     }
3156   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
3157
3158   return result;
3159 }
3160
3161 /* Checks T for any "bare" parameter packs, which have not yet been
3162    expanded, and issues an error if any are found. This operation can
3163    only be done on full expressions or types (e.g., an expression
3164    statement, "if" condition, etc.), because we could have expressions like:
3165
3166      foo(f(g(h(args)))...)
3167
3168    where "args" is a parameter pack. check_for_bare_parameter_packs
3169    should not be called for the subexpressions args, h(args),
3170    g(h(args)), or f(g(h(args))), because we would produce erroneous
3171    error messages. 
3172
3173    Returns TRUE and emits an error if there were bare parameter packs,
3174    returns FALSE otherwise.  */
3175 bool 
3176 check_for_bare_parameter_packs (tree t)
3177 {
3178   tree parameter_packs = NULL_TREE;
3179   struct find_parameter_pack_data ppd;
3180
3181   if (!processing_template_decl || !t || t == error_mark_node)
3182     return false;
3183
3184   if (TREE_CODE (t) == TYPE_DECL)
3185     t = TREE_TYPE (t);
3186
3187   ppd.parameter_packs = &parameter_packs;
3188   ppd.visited = pointer_set_create ();
3189   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3190   pointer_set_destroy (ppd.visited);
3191
3192   if (parameter_packs) 
3193     {
3194       error ("parameter packs not expanded with %<...%>:");
3195       while (parameter_packs)
3196         {
3197           tree pack = TREE_VALUE (parameter_packs);
3198           tree name = NULL_TREE;
3199
3200           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
3201               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
3202             name = TYPE_NAME (pack);
3203           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
3204             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
3205           else
3206             name = DECL_NAME (pack);
3207
3208           if (name)
3209             inform (input_location, "        %qD", name);
3210           else
3211             inform (input_location, "        <anonymous>");
3212
3213           parameter_packs = TREE_CHAIN (parameter_packs);
3214         }
3215
3216       return true;
3217     }
3218
3219   return false;
3220 }
3221
3222 /* Expand any parameter packs that occur in the template arguments in
3223    ARGS.  */
3224 tree
3225 expand_template_argument_pack (tree args)
3226 {
3227   tree result_args = NULL_TREE;
3228   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3229   int num_result_args = -1;
3230   int non_default_args_count = -1;
3231
3232   /* First, determine if we need to expand anything, and the number of
3233      slots we'll need.  */
3234   for (in_arg = 0; in_arg < nargs; ++in_arg)
3235     {
3236       tree arg = TREE_VEC_ELT (args, in_arg);
3237       if (arg == NULL_TREE)
3238         return args;
3239       if (ARGUMENT_PACK_P (arg))
3240         {
3241           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3242           if (num_result_args < 0)
3243             num_result_args = in_arg + num_packed;
3244           else
3245             num_result_args += num_packed;
3246         }
3247       else
3248         {
3249           if (num_result_args >= 0)
3250             num_result_args++;
3251         }
3252     }
3253
3254   /* If no expansion is necessary, we're done.  */
3255   if (num_result_args < 0)
3256     return args;
3257
3258   /* Expand arguments.  */
3259   result_args = make_tree_vec (num_result_args);
3260   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
3261     non_default_args_count =
3262       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
3263   for (in_arg = 0; in_arg < nargs; ++in_arg)
3264     {
3265       tree arg = TREE_VEC_ELT (args, in_arg);
3266       if (ARGUMENT_PACK_P (arg))
3267         {
3268           tree packed = ARGUMENT_PACK_ARGS (arg);
3269           int i, num_packed = TREE_VEC_LENGTH (packed);
3270           for (i = 0; i < num_packed; ++i, ++out_arg)
3271             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3272           if (non_default_args_count > 0)
3273             non_default_args_count += num_packed;
3274         }
3275       else
3276         {
3277           TREE_VEC_ELT (result_args, out_arg) = arg;
3278           ++out_arg;
3279         }
3280     }
3281   if (non_default_args_count >= 0)
3282     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
3283   return result_args;
3284 }
3285
3286 /* Checks if DECL shadows a template parameter.
3287
3288    [temp.local]: A template-parameter shall not be redeclared within its
3289    scope (including nested scopes).
3290
3291    Emits an error and returns TRUE if the DECL shadows a parameter,
3292    returns FALSE otherwise.  */
3293
3294 bool
3295 check_template_shadow (tree decl)
3296 {
3297   tree olddecl;
3298
3299   /* If we're not in a template, we can't possibly shadow a template
3300      parameter.  */
3301   if (!current_template_parms)
3302     return true;
3303
3304   /* Figure out what we're shadowing.  */
3305   if (TREE_CODE (decl) == OVERLOAD)
3306     decl = OVL_CURRENT (decl);
3307   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3308
3309   /* If there's no previous binding for this name, we're not shadowing
3310      anything, let alone a template parameter.  */
3311   if (!olddecl)
3312     return true;
3313
3314   /* If we're not shadowing a template parameter, we're done.  Note
3315      that OLDDECL might be an OVERLOAD (or perhaps even an
3316      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3317      node.  */
3318   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3319     return true;
3320
3321   /* We check for decl != olddecl to avoid bogus errors for using a
3322      name inside a class.  We check TPFI to avoid duplicate errors for
3323      inline member templates.  */
3324   if (decl == olddecl
3325       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
3326     return true;
3327
3328   error ("declaration of %q+#D", decl);
3329   error (" shadows template parm %q+#D", olddecl);
3330   return false;
3331 }
3332
3333 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3334    ORIG_LEVEL, DECL, and TYPE.  */
3335
3336 static tree
3337 build_template_parm_index (int index,
3338                            int level,
3339                            int orig_level,
3340                            tree decl,
3341                            tree type)
3342 {
3343   tree t = make_node (TEMPLATE_PARM_INDEX);
3344   TEMPLATE_PARM_IDX (t) = index;
3345   TEMPLATE_PARM_LEVEL (t) = level;
3346   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3347   TEMPLATE_PARM_DECL (t) = decl;
3348   TREE_TYPE (t) = type;
3349   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3350   TREE_READONLY (t) = TREE_READONLY (decl);
3351
3352   return t;
3353 }
3354
3355 /* Find the canonical type parameter for the given template type
3356    parameter.  Returns the canonical type parameter, which may be TYPE
3357    if no such parameter existed.  */
3358 static tree
3359 canonical_type_parameter (tree type)
3360 {
3361   tree list;
3362   int idx = TEMPLATE_TYPE_IDX (type);
3363   if (!canonical_template_parms)
3364     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
3365
3366   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
3367     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
3368
3369   list = VEC_index (tree, canonical_template_parms, idx);
3370   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3371     list = TREE_CHAIN (list);
3372
3373   if (list)
3374     return TREE_VALUE (list);
3375   else
3376     {
3377       VEC_replace(tree, canonical_template_parms, idx,
3378                   tree_cons (NULL_TREE, type, 
3379                              VEC_index (tree, canonical_template_parms, idx)));
3380       return type;
3381     }
3382 }
3383
3384 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3385    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3386    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3387    new one is created.  */
3388
3389 static tree
3390 reduce_template_parm_level (tree index, tree type, int levels, tree args,
3391                             tsubst_flags_t complain)
3392 {
3393   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3394       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3395           != TEMPLATE_PARM_LEVEL (index) - levels)
3396       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
3397     {
3398       tree orig_decl = TEMPLATE_PARM_DECL (index);
3399       tree decl, t;
3400
3401       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3402                          TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3403       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
3404       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
3405       DECL_ARTIFICIAL (decl) = 1;
3406       SET_DECL_TEMPLATE_PARM_P (decl);
3407
3408       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
3409                                      TEMPLATE_PARM_LEVEL (index) - levels,
3410                                      TEMPLATE_PARM_ORIG_LEVEL (index),
3411                                      decl, type);
3412       TEMPLATE_PARM_DESCENDANTS (index) = t;
3413       TEMPLATE_PARM_PARAMETER_PACK (t) 
3414         = TEMPLATE_PARM_PARAMETER_PACK (index);
3415
3416         /* Template template parameters need this.  */
3417       if (TREE_CODE (decl) == TEMPLATE_DECL)
3418         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
3419           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
3420            args, complain);
3421     }
3422
3423   return TEMPLATE_PARM_DESCENDANTS (index);
3424 }
3425
3426 /* Process information from new template parameter PARM and append it to the
3427    LIST being built.  This new parameter is a non-type parameter iff
3428    IS_NON_TYPE is true. This new parameter is a parameter
3429    pack iff IS_PARAMETER_PACK is true.  The location of PARM is in 
3430    PARM_LOC.  */
3431
3432 tree
3433 process_template_parm (tree list, location_t parm_loc, tree parm, bool is_non_type, 
3434                        bool is_parameter_pack)
3435 {
3436   tree decl = 0;
3437   tree defval;
3438   tree err_parm_list;
3439   int idx = 0;
3440
3441   gcc_assert (TREE_CODE (parm) == TREE_LIST);
3442   defval = TREE_PURPOSE (parm);
3443
3444   if (list)
3445     {
3446       tree p = tree_last (list);
3447
3448       if (p && TREE_VALUE (p) != error_mark_node)
3449         {
3450           p = TREE_VALUE (p);
3451           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3452             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3453           else
3454             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3455         }
3456
3457       ++idx;
3458     }
3459   else
3460     idx = 0;
3461
3462   if (is_non_type)
3463     {
3464       parm = TREE_VALUE (parm);
3465
3466       SET_DECL_TEMPLATE_PARM_P (parm);
3467
3468       if (TREE_TYPE (parm) == error_mark_node)
3469         {
3470           err_parm_list = build_tree_list (defval, parm);
3471           TREE_VALUE (err_parm_list) = error_mark_node;
3472            return chainon (list, err_parm_list);
3473         }
3474       else
3475       {
3476         /* [temp.param]
3477
3478            The top-level cv-qualifiers on the template-parameter are
3479            ignored when determining its type.  */
3480         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3481         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3482           {
3483             err_parm_list = build_tree_list (defval, parm);
3484             TREE_VALUE (err_parm_list) = error_mark_node;
3485              return chainon (list, err_parm_list);
3486           }
3487
3488         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3489           {
3490             /* This template parameter is not a parameter pack, but it
3491                should be. Complain about "bare" parameter packs.  */
3492             check_for_bare_parameter_packs (TREE_TYPE (parm));
3493             
3494             /* Recover by calling this a parameter pack.  */
3495             is_parameter_pack = true;
3496           }
3497       }
3498
3499       /* A template parameter is not modifiable.  */
3500       TREE_CONSTANT (parm) = 1;
3501       TREE_READONLY (parm) = 1;
3502       decl = build_decl (parm_loc,
3503                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3504       TREE_CONSTANT (decl) = 1;
3505       TREE_READONLY (decl) = 1;
3506       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3507         = build_template_parm_index (idx, processing_template_decl,
3508                                      processing_template_decl,
3509                                      decl, TREE_TYPE (parm));
3510
3511       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3512         = is_parameter_pack;
3513     }
3514   else
3515     {
3516       tree t;
3517       parm = TREE_VALUE (TREE_VALUE (parm));
3518
3519       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3520         {
3521           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3522           /* This is for distinguishing between real templates and template
3523              template parameters */
3524           TREE_TYPE (parm) = t;
3525           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3526           decl = parm;
3527         }
3528       else
3529         {
3530           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3531           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3532           decl = build_decl (parm_loc,
3533                              TYPE_DECL, parm, t);
3534         }
3535
3536       TYPE_NAME (t) = decl;
3537       TYPE_STUB_DECL (t) = decl;
3538       parm = decl;
3539       TEMPLATE_TYPE_PARM_INDEX (t)
3540         = build_template_parm_index (idx, processing_template_decl,
3541                                      processing_template_decl,
3542                                      decl, TREE_TYPE (parm));
3543       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3544       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3545     }
3546   DECL_ARTIFICIAL (decl) = 1;
3547   SET_DECL_TEMPLATE_PARM_P (decl);
3548   pushdecl (decl);
3549   parm = build_tree_list (defval, parm);
3550   return chainon (list, parm);
3551 }
3552
3553 /* The end of a template parameter list has been reached.  Process the
3554    tree list into a parameter vector, converting each parameter into a more
3555    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3556    as PARM_DECLs.  */
3557
3558 tree
3559 end_template_parm_list (tree parms)
3560 {
3561   int nparms;
3562   tree parm, next;
3563   tree saved_parmlist = make_tree_vec (list_length (parms));
3564
3565   current_template_parms
3566     = tree_cons (size_int (processing_template_decl),
3567                  saved_parmlist, current_template_parms);
3568
3569   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3570     {
3571       next = TREE_CHAIN (parm);
3572       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3573       TREE_CHAIN (parm) = NULL_TREE;
3574       if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL)
3575         TEMPLATE_TYPE_PARM_SIBLING_PARMS (TREE_TYPE (TREE_VALUE (parm))) =
3576               current_template_parms;
3577     }
3578
3579   --processing_template_parmlist;
3580
3581   return saved_parmlist;
3582 }
3583
3584 /* end_template_decl is called after a template declaration is seen.  */
3585
3586 void
3587 end_template_decl (void)
3588 {
3589   reset_specialization ();
3590
3591   if (! processing_template_decl)
3592     return;
3593
3594   /* This matches the pushlevel in begin_template_parm_list.  */
3595   finish_scope ();
3596
3597   --processing_template_decl;
3598   current_template_parms = TREE_CHAIN (current_template_parms);
3599 }
3600
3601 /* Within the declaration of a template, return all levels of template
3602    parameters that apply.  The template parameters are represented as
3603    a TREE_VEC, in the form documented in cp-tree.h for template
3604    arguments.  */
3605
3606 static tree
3607 current_template_args (void)
3608 {
3609   tree header;
3610   tree args = NULL_TREE;
3611   int length = TMPL_PARMS_DEPTH (current_template_parms);
3612   int l = length;
3613
3614   /* If there is only one level of template parameters, we do not
3615      create a TREE_VEC of TREE_VECs.  Instead, we return a single
3616      TREE_VEC containing the arguments.  */
3617   if (length > 1)
3618     args = make_tree_vec (length);
3619
3620   for (header = current_template_parms; header; header = TREE_CHAIN (header))
3621     {
3622       tree a = copy_node (TREE_VALUE (header));
3623       int i;
3624
3625       TREE_TYPE (a) = NULL_TREE;
3626       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3627         {
3628           tree t = TREE_VEC_ELT (a, i);
3629
3630           /* T will be a list if we are called from within a
3631              begin/end_template_parm_list pair, but a vector directly
3632              if within a begin/end_member_template_processing pair.  */
3633           if (TREE_CODE (t) == TREE_LIST)
3634             {
3635               t = TREE_VALUE (t);
3636
3637               if (!error_operand_p (t))
3638                 {
3639                   if (TREE_CODE (t) == TYPE_DECL
3640                       || TREE_CODE (t) == TEMPLATE_DECL)
3641                     {
3642                       t = TREE_TYPE (t);
3643                       
3644                       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3645                         {
3646                           /* Turn this argument into a TYPE_ARGUMENT_PACK
3647                              with a single element, which expands T.  */
3648                           tree vec = make_tree_vec (1);
3649 #ifdef ENABLE_CHECKING
3650                           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3651                                 (vec, TREE_VEC_LENGTH (vec));
3652 #endif
3653                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3654                           
3655                           t = cxx_make_type (TYPE_ARGUMENT_PACK);
3656                           SET_ARGUMENT_PACK_ARGS (t, vec);
3657                         }
3658                     }
3659                   else
3660                     {
3661                       t = DECL_INITIAL (t);
3662                       
3663                       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3664                         {
3665                           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3666                              with a single element, which expands T.  */
3667                           tree vec = make_tree_vec (1);
3668                           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3669 #ifdef ENABLE_CHECKING
3670                           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3671                                 (vec, TREE_VEC_LENGTH (vec));
3672 #endif
3673                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3674                           
3675                           t  = make_node (NONTYPE_ARGUMENT_PACK);
3676                           SET_ARGUMENT_PACK_ARGS (t, vec);
3677                           TREE_TYPE (t) = type;
3678                         }
3679                     }
3680                   TREE_VEC_ELT (a, i) = t;
3681                 }
3682             }
3683         }
3684
3685 #ifdef ENABLE_CHECKING
3686       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
3687 #endif
3688
3689       if (length > 1)
3690         TREE_VEC_ELT (args, --l) = a;
3691       else
3692         args = a;
3693     }
3694
3695   return args;
3696 }
3697
3698 /* Update the declared TYPE by doing any lookups which were thought to be
3699    dependent, but are not now that we know the SCOPE of the declarator.  */
3700
3701 tree
3702 maybe_update_decl_type (tree orig_type, tree scope)
3703 {
3704   tree type = orig_type;
3705
3706   if (type == NULL_TREE)
3707     return type;
3708
3709   if (TREE_CODE (orig_type) == TYPE_DECL)
3710     type = TREE_TYPE (type);
3711
3712   if (scope && TYPE_P (scope) && dependent_type_p (scope)
3713       && dependent_type_p (type)
3714       /* Don't bother building up the args in this case.  */
3715       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
3716     {
3717       /* tsubst in the args corresponding to the template parameters,
3718          including auto if present.  Most things will be unchanged, but
3719          make_typename_type and tsubst_qualified_id will resolve
3720          TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
3721       tree args = current_template_args ();
3722       tree auto_node = type_uses_auto (type);
3723       tree pushed;
3724       if (auto_node)
3725         {
3726           tree auto_vec = make_tree_vec (1);
3727           TREE_VEC_ELT (auto_vec, 0) = auto_node;
3728           args = add_to_template_args (args, auto_vec);
3729         }
3730       pushed = push_scope (scope);
3731       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
3732       if (pushed)
3733         pop_scope (scope);
3734     }
3735
3736   if (type == error_mark_node)
3737     return orig_type;
3738
3739   if (TREE_CODE (orig_type) == TYPE_DECL)
3740     {
3741       if (same_type_p (type, TREE_TYPE (orig_type)))
3742         type = orig_type;
3743       else
3744         type = TYPE_NAME (type);
3745     }
3746   return type;
3747 }
3748
3749 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
3750    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
3751    a member template.  Used by push_template_decl below.  */
3752
3753 static tree
3754 build_template_decl (tree decl, tree parms, bool member_template_p)
3755 {
3756   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
3757   DECL_TEMPLATE_PARMS (tmpl) = parms;
3758   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
3759   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
3760
3761   return tmpl;
3762 }
3763
3764 struct template_parm_data
3765 {
3766   /* The level of the template parameters we are currently
3767      processing.  */
3768   int level;
3769
3770   /* The index of the specialization argument we are currently
3771      processing.  */
3772   int current_arg;
3773
3774   /* An array whose size is the number of template parameters.  The
3775      elements are nonzero if the parameter has been used in any one
3776      of the arguments processed so far.  */
3777   int* parms;
3778
3779   /* An array whose size is the number of template arguments.  The
3780      elements are nonzero if the argument makes use of template
3781      parameters of this level.  */
3782   int* arg_uses_template_parms;
3783 };
3784
3785 /* Subroutine of push_template_decl used to see if each template
3786    parameter in a partial specialization is used in the explicit
3787    argument list.  If T is of the LEVEL given in DATA (which is
3788    treated as a template_parm_data*), then DATA->PARMS is marked
3789    appropriately.  */
3790
3791 static int
3792 mark_template_parm (tree t, void* data)
3793 {
3794   int level;
3795   int idx;
3796   struct template_parm_data* tpd = (struct template_parm_data*) data;
3797
3798   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3799     {
3800       level = TEMPLATE_PARM_LEVEL (t);
3801       idx = TEMPLATE_PARM_IDX (t);
3802     }
3803   else
3804     {
3805       level = TEMPLATE_TYPE_LEVEL (t);
3806       idx = TEMPLATE_TYPE_IDX (t);
3807     }
3808
3809   if (level == tpd->level)
3810     {
3811       tpd->parms[idx] = 1;
3812       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
3813     }
3814
3815   /* Return zero so that for_each_template_parm will continue the
3816      traversal of the tree; we want to mark *every* template parm.  */
3817   return 0;
3818 }
3819
3820 /* Process the partial specialization DECL.  */
3821
3822 static tree
3823 process_partial_specialization (tree decl)
3824 {
3825   tree type = TREE_TYPE (decl);
3826   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
3827   tree specargs = CLASSTYPE_TI_ARGS (type);
3828   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
3829   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
3830   tree inner_parms;
3831   int nargs = TREE_VEC_LENGTH (inner_args);
3832   int ntparms;
3833   int  i;
3834   int did_error_intro = 0;
3835   struct template_parm_data tpd;
3836   struct template_parm_data tpd2;
3837
3838   gcc_assert (current_template_parms);
3839
3840   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3841   ntparms = TREE_VEC_LENGTH (inner_parms);
3842
3843   /* We check that each of the template parameters given in the
3844      partial specialization is used in the argument list to the
3845      specialization.  For example:
3846
3847        template <class T> struct S;
3848        template <class T> struct S<T*>;
3849
3850      The second declaration is OK because `T*' uses the template
3851      parameter T, whereas
3852
3853        template <class T> struct S<int>;
3854
3855      is no good.  Even trickier is:
3856
3857        template <class T>
3858        struct S1
3859        {
3860           template <class U>
3861           struct S2;
3862           template <class U>
3863           struct S2<T>;
3864        };
3865
3866      The S2<T> declaration is actually invalid; it is a
3867      full-specialization.  Of course,
3868
3869           template <class U>
3870           struct S2<T (*)(U)>;
3871
3872      or some such would have been OK.  */
3873   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
3874   tpd.parms = (int *) alloca (sizeof (int) * ntparms);
3875   memset (tpd.parms, 0, sizeof (int) * ntparms);
3876
3877   tpd.arg_uses_template_parms = (int *) alloca (sizeof (int) * nargs);
3878   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
3879   for (i = 0; i < nargs; ++i)
3880     {
3881       tpd.current_arg = i;
3882       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
3883                               &mark_template_parm,
3884                               &tpd,
3885                               NULL,
3886                               /*include_nondeduced_p=*/false);
3887     }
3888   for (i = 0; i < ntparms; ++i)
3889     if (tpd.parms[i] == 0)
3890       {
3891         /* One of the template parms was not used in the
3892            specialization.  */
3893         if (!did_error_intro)
3894           {
3895             error ("template parameters not used in partial specialization:");
3896             did_error_intro = 1;
3897           }
3898
3899         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
3900       }
3901
3902   /* [temp.class.spec]
3903
3904      The argument list of the specialization shall not be identical to
3905      the implicit argument list of the primary template.  */
3906   if (comp_template_args
3907       (inner_args,
3908        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
3909                                                    (maintmpl)))))
3910     error ("partial specialization %qT does not specialize any template arguments", type);
3911
3912   /* [temp.class.spec]
3913
3914      A partially specialized non-type argument expression shall not
3915      involve template parameters of the partial specialization except
3916      when the argument expression is a simple identifier.
3917
3918      The type of a template parameter corresponding to a specialized
3919      non-type argument shall not be dependent on a parameter of the
3920      specialization. 
3921
3922      Also, we verify that pack expansions only occur at the
3923      end of the argument list.  */
3924   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
3925   tpd2.parms = 0;
3926   for (i = 0; i < nargs; ++i)
3927     {
3928       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
3929       tree arg = TREE_VEC_ELT (inner_args, i);
3930       tree packed_args = NULL_TREE;
3931       int j, len = 1;
3932
3933       if (ARGUMENT_PACK_P (arg))
3934         {
3935           /* Extract the arguments from the argument pack. We'll be
3936              iterating over these in the following loop.  */
3937           packed_args = ARGUMENT_PACK_ARGS (arg);
3938           len = TREE_VEC_LENGTH (packed_args);
3939         }
3940
3941       for (j = 0; j < len; j++)
3942         {
3943           if (packed_args)
3944             /* Get the Jth argument in the parameter pack.  */
3945             arg = TREE_VEC_ELT (packed_args, j);
3946
3947           if (PACK_EXPANSION_P (arg))
3948             {
3949               /* Pack expansions must come at the end of the
3950                  argument list.  */
3951               if ((packed_args && j < len - 1)
3952                   || (!packed_args && i < nargs - 1))
3953                 {
3954                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3955                     error ("parameter pack argument %qE must be at the "
3956                            "end of the template argument list", arg);
3957                   else
3958                     error ("parameter pack argument %qT must be at the "
3959                            "end of the template argument list", arg);
3960                 }
3961             }
3962
3963           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3964             /* We only care about the pattern.  */
3965             arg = PACK_EXPANSION_PATTERN (arg);
3966
3967           if (/* These first two lines are the `non-type' bit.  */
3968               !TYPE_P (arg)
3969               && TREE_CODE (arg) != TEMPLATE_DECL
3970               /* This next line is the `argument expression is not just a
3971                  simple identifier' condition and also the `specialized
3972                  non-type argument' bit.  */
3973               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
3974             {
3975               if ((!packed_args && tpd.arg_uses_template_parms[i])
3976                   || (packed_args && uses_template_parms (arg)))
3977                 error ("template argument %qE involves template parameter(s)",
3978                        arg);
3979               else 
3980                 {
3981                   /* Look at the corresponding template parameter,
3982                      marking which template parameters its type depends
3983                      upon.  */
3984                   tree type = TREE_TYPE (parm);
3985
3986                   if (!tpd2.parms)
3987                     {
3988                       /* We haven't yet initialized TPD2.  Do so now.  */
3989                       tpd2.arg_uses_template_parms 
3990                         = (int *) alloca (sizeof (int) * nargs);
3991                       /* The number of parameters here is the number in the
3992                          main template, which, as checked in the assertion
3993                          above, is NARGS.  */
3994                       tpd2.parms = (int *) alloca (sizeof (int) * nargs);
3995                       tpd2.level = 
3996                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
3997                     }
3998
3999                   /* Mark the template parameters.  But this time, we're
4000                      looking for the template parameters of the main
4001                      template, not in the specialization.  */
4002                   tpd2.current_arg = i;
4003                   tpd2.arg_uses_template_parms[i] = 0;
4004                   memset (tpd2.parms, 0, sizeof (int) * nargs);
4005                   for_each_template_parm (type,
4006                                           &mark_template_parm,
4007                                           &tpd2,
4008                                           NULL,
4009                                           /*include_nondeduced_p=*/false);
4010
4011                   if (tpd2.arg_uses_template_parms [i])
4012                     {
4013                       /* The type depended on some template parameters.
4014                          If they are fully specialized in the
4015                          specialization, that's OK.  */
4016                       int j;
4017                       int count = 0;
4018                       for (j = 0; j < nargs; ++j)
4019                         if (tpd2.parms[j] != 0
4020                             && tpd.arg_uses_template_parms [j])
4021                           ++count;
4022                       if (count != 0)
4023                         error_n (input_location, count,
4024                                  "type %qT of template argument %qE depends "
4025                                  "on a template parameter",
4026                                  "type %qT of template argument %qE depends "
4027                                  "on template parameters",
4028                                  type,
4029                                  arg);
4030                     }
4031                 }
4032             }
4033         }
4034     }
4035
4036   /* We should only get here once.  */
4037   gcc_assert (!COMPLETE_TYPE_P (type));
4038
4039   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
4040     = tree_cons (specargs, inner_parms,
4041                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
4042   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
4043   return decl;
4044 }
4045
4046 /* Check that a template declaration's use of default arguments and
4047    parameter packs is not invalid.  Here, PARMS are the template
4048    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
4049    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
4050    specialization.
4051    
4052
4053    IS_FRIEND_DECL is nonzero if DECL is a friend function template
4054    declaration (but not a definition); 1 indicates a declaration, 2
4055    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
4056    emitted for extraneous default arguments.
4057
4058    Returns TRUE if there were no errors found, FALSE otherwise. */
4059
4060 bool
4061 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
4062                          int is_partial, int is_friend_decl)
4063 {
4064   const char *msg;
4065   int last_level_to_check;
4066   tree parm_level;
4067   bool no_errors = true;
4068
4069   /* [temp.param]
4070
4071      A default template-argument shall not be specified in a
4072      function template declaration or a function template definition, nor
4073      in the template-parameter-list of the definition of a member of a
4074      class template.  */
4075
4076   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
4077     /* You can't have a function template declaration in a local
4078        scope, nor you can you define a member of a class template in a
4079        local scope.  */
4080     return true;
4081
4082   if (current_class_type
4083       && !TYPE_BEING_DEFINED (current_class_type)
4084       && DECL_LANG_SPECIFIC (decl)
4085       && DECL_DECLARES_FUNCTION_P (decl)
4086       /* If this is either a friend defined in the scope of the class
4087          or a member function.  */
4088       && (DECL_FUNCTION_MEMBER_P (decl)
4089           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
4090           : DECL_FRIEND_CONTEXT (decl)
4091           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
4092           : false)
4093       /* And, if it was a member function, it really was defined in
4094          the scope of the class.  */
4095       && (!DECL_FUNCTION_MEMBER_P (decl)
4096           || DECL_INITIALIZED_IN_CLASS_P (decl)))
4097     /* We already checked these parameters when the template was
4098        declared, so there's no need to do it again now.  This function
4099        was defined in class scope, but we're processing it's body now
4100        that the class is complete.  */
4101     return true;
4102
4103   /* Core issue 226 (C++0x only): the following only applies to class
4104      templates.  */
4105   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
4106     {
4107       /* [temp.param]
4108
4109          If a template-parameter has a default template-argument, all
4110          subsequent template-parameters shall have a default
4111          template-argument supplied.  */
4112       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
4113         {
4114           tree inner_parms = TREE_VALUE (parm_level);
4115           int ntparms = TREE_VEC_LENGTH (inner_parms);
4116           int seen_def_arg_p = 0;
4117           int i;
4118
4119           for (i = 0; i < ntparms; ++i)
4120             {
4121               tree parm = TREE_VEC_ELT (inner_parms, i);
4122
4123               if (parm == error_mark_node)
4124                 continue;
4125
4126               if (TREE_PURPOSE (parm))
4127                 seen_def_arg_p = 1;
4128               else if (seen_def_arg_p
4129                        && !template_parameter_pack_p (TREE_VALUE (parm)))
4130                 {
4131                   error ("no default argument for %qD", TREE_VALUE (parm));
4132                   /* For better subsequent error-recovery, we indicate that
4133                      there should have been a default argument.  */
4134                   TREE_PURPOSE (parm) = error_mark_node;
4135                   no_errors = false;
4136                 }
4137               else if (is_primary
4138                        && !is_partial
4139                        && !is_friend_decl
4140                        /* Don't complain about an enclosing partial
4141                           specialization.  */
4142                        && parm_level == parms
4143                        && TREE_CODE (decl) == TYPE_DECL
4144                        && i < ntparms - 1
4145                        && template_parameter_pack_p (TREE_VALUE (parm)))
4146                 {
4147                   /* A primary class template can only have one
4148                      parameter pack, at the end of the template
4149                      parameter list.  */
4150
4151                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
4152                     error ("parameter pack %qE must be at the end of the"
4153                            " template parameter list", TREE_VALUE (parm));
4154                   else
4155                     error ("parameter pack %qT must be at the end of the"
4156                            " template parameter list", 
4157                            TREE_TYPE (TREE_VALUE (parm)));
4158
4159                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
4160                     = error_mark_node;
4161                   no_errors = false;
4162                 }
4163             }
4164         }
4165     }
4166
4167   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
4168       || is_partial 
4169       || !is_primary
4170       || is_friend_decl)
4171     /* For an ordinary class template, default template arguments are
4172        allowed at the innermost level, e.g.:
4173          template <class T = int>
4174          struct S {};
4175        but, in a partial specialization, they're not allowed even
4176        there, as we have in [temp.class.spec]:
4177
4178          The template parameter list of a specialization shall not
4179          contain default template argument values.
4180
4181        So, for a partial specialization, or for a function template
4182        (in C++98/C++03), we look at all of them.  */
4183     ;
4184   else
4185     /* But, for a primary class template that is not a partial
4186        specialization we look at all template parameters except the
4187        innermost ones.  */
4188     parms = TREE_CHAIN (parms);
4189
4190   /* Figure out what error message to issue.  */
4191   if (is_friend_decl == 2)
4192     msg = G_("default template arguments may not be used in function template "
4193              "friend re-declaration");
4194   else if (is_friend_decl)
4195     msg = G_("default template arguments may not be used in function template "
4196              "friend declarations");
4197   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
4198     msg = G_("default template arguments may not be used in function templates "
4199              "without -std=c++0x or -std=gnu++0x");
4200   else if (is_partial)
4201     msg = G_("default template arguments may not be used in "
4202              "partial specializations");
4203   else
4204     msg = G_("default argument for template parameter for class enclosing %qD");
4205
4206   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
4207     /* If we're inside a class definition, there's no need to
4208        examine the parameters to the class itself.  On the one
4209        hand, they will be checked when the class is defined, and,
4210        on the other, default arguments are valid in things like:
4211          template <class T = double>
4212          struct S { template <class U> void f(U); };
4213        Here the default argument for `S' has no bearing on the
4214        declaration of `f'.  */
4215     last_level_to_check = template_class_depth (current_class_type) + 1;
4216   else
4217     /* Check everything.  */
4218     last_level_to_check = 0;
4219
4220   for (parm_level = parms;
4221        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
4222        parm_level = TREE_CHAIN (parm_level))
4223     {
4224       tree inner_parms = TREE_VALUE (parm_level);
4225       int i;
4226       int ntparms;
4227
4228       ntparms = TREE_VEC_LENGTH (inner_parms);
4229       for (i = 0; i < ntparms; ++i)
4230         {
4231           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
4232             continue;
4233
4234           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
4235             {
4236               if (msg)
4237                 {
4238                   no_errors = false;
4239                   if (is_friend_decl == 2)
4240                     return no_errors;
4241
4242                   error (msg, decl);
4243                   msg = 0;
4244                 }
4245
4246               /* Clear out the default argument so that we are not
4247                  confused later.  */
4248               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
4249             }
4250         }
4251
4252       /* At this point, if we're still interested in issuing messages,
4253          they must apply to classes surrounding the object declared.  */
4254       if (msg)
4255         msg = G_("default argument for template parameter for class "
4256                  "enclosing %qD");
4257     }
4258
4259   return no_errors;
4260 }
4261
4262 /* Worker for push_template_decl_real, called via
4263    for_each_template_parm.  DATA is really an int, indicating the
4264    level of the parameters we are interested in.  If T is a template
4265    parameter of that level, return nonzero.  */
4266
4267 static int
4268 template_parm_this_level_p (tree t, void* data)
4269 {
4270   int this_level = *(int *)data;
4271   int level;
4272
4273   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4274     level = TEMPLATE_PARM_LEVEL (t);
4275   else
4276     level = TEMPLATE_TYPE_LEVEL (t);
4277   return level == this_level;
4278 }
4279
4280 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
4281    parameters given by current_template_args, or reuses a
4282    previously existing one, if appropriate.  Returns the DECL, or an
4283    equivalent one, if it is replaced via a call to duplicate_decls.
4284
4285    If IS_FRIEND is true, DECL is a friend declaration.  */
4286
4287 tree
4288 push_template_decl_real (tree decl, bool is_friend)
4289 {
4290   tree tmpl;
4291   tree args;
4292   tree info;
4293   tree ctx;
4294   int primary;
4295   int is_partial;
4296   int new_template_p = 0;
4297   /* True if the template is a member template, in the sense of
4298      [temp.mem].  */
4299   bool member_template_p = false;
4300
4301   if (decl == error_mark_node || !current_template_parms)
4302     return error_mark_node;
4303
4304   /* See if this is a partial specialization.  */
4305   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
4306                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
4307                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
4308
4309   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
4310     is_friend = true;
4311
4312   if (is_friend)
4313     /* For a friend, we want the context of the friend function, not
4314        the type of which it is a friend.  */
4315     ctx = DECL_CONTEXT (decl);
4316   else if (CP_DECL_CONTEXT (decl)
4317            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
4318     /* In the case of a virtual function, we want the class in which
4319        it is defined.  */
4320     ctx = CP_DECL_CONTEXT (decl);
4321   else
4322     /* Otherwise, if we're currently defining some class, the DECL
4323        is assumed to be a member of the class.  */
4324     ctx = current_scope ();
4325
4326   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
4327     ctx = NULL_TREE;
4328
4329   if (!DECL_CONTEXT (decl))
4330     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4331
4332   /* See if this is a primary template.  */
4333   if (is_friend && ctx)
4334     /* A friend template that specifies a class context, i.e.
4335          template <typename T> friend void A<T>::f();
4336        is not primary.  */
4337     primary = 0;
4338   else
4339     primary = template_parm_scope_p ();
4340
4341   if (primary)
4342     {
4343       if (DECL_CLASS_SCOPE_P (decl))
4344         member_template_p = true;
4345       if (TREE_CODE (decl) == TYPE_DECL
4346           && ANON_AGGRNAME_P (DECL_NAME (decl)))
4347         {
4348           error ("template class without a name");
4349           return error_mark_node;
4350         }
4351       else if (TREE_CODE (decl) == FUNCTION_DECL)
4352         {
4353           if (DECL_DESTRUCTOR_P (decl))
4354             {
4355               /* [temp.mem]
4356
4357                  A destructor shall not be a member template.  */
4358               error ("destructor %qD declared as member template", decl);
4359               return error_mark_node;
4360             }
4361           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
4362               && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
4363                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
4364                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
4365                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
4366                       == void_list_node)))
4367             {
4368               /* [basic.stc.dynamic.allocation]
4369
4370                  An allocation function can be a function
4371                  template. ... Template allocation functions shall
4372                  have two or more parameters.  */
4373               error ("invalid template declaration of %qD", decl);
4374               return error_mark_node;
4375             }
4376         }
4377       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4378                && CLASS_TYPE_P (TREE_TYPE (decl)))
4379         /* OK */;
4380       else
4381         {
4382           error ("template declaration of %q#D", decl);
4383           return error_mark_node;
4384         }
4385     }
4386
4387   /* Check to see that the rules regarding the use of default
4388      arguments are not being violated.  */
4389   check_default_tmpl_args (decl, current_template_parms,
4390                            primary, is_partial, /*is_friend_decl=*/0);
4391
4392   /* Ensure that there are no parameter packs in the type of this
4393      declaration that have not been expanded.  */
4394   if (TREE_CODE (decl) == FUNCTION_DECL)
4395     {
4396       /* Check each of the arguments individually to see if there are
4397          any bare parameter packs.  */
4398       tree type = TREE_TYPE (decl);
4399       tree arg = DECL_ARGUMENTS (decl);
4400       tree argtype = TYPE_ARG_TYPES (type);
4401
4402       while (arg && argtype)
4403         {
4404           if (!FUNCTION_PARAMETER_PACK_P (arg)
4405               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
4406             {
4407             /* This is a PARM_DECL that contains unexpanded parameter
4408                packs. We have already complained about this in the
4409                check_for_bare_parameter_packs call, so just replace
4410                these types with ERROR_MARK_NODE.  */
4411               TREE_TYPE (arg) = error_mark_node;
4412               TREE_VALUE (argtype) = error_mark_node;
4413             }
4414
4415           arg = TREE_CHAIN (arg);
4416           argtype = TREE_CHAIN (argtype);
4417         }
4418
4419       /* Check for bare parameter packs in the return type and the
4420          exception specifiers.  */
4421       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
4422         /* Errors were already issued, set return type to int
4423            as the frontend doesn't expect error_mark_node as
4424            the return type.  */
4425         TREE_TYPE (type) = integer_type_node;
4426       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
4427         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
4428     }
4429   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
4430     {
4431       TREE_TYPE (decl) = error_mark_node;
4432       return error_mark_node;
4433     }
4434
4435   if (is_partial)
4436     return process_partial_specialization (decl);
4437
4438   args = current_template_args ();
4439
4440   if (!ctx
4441       || TREE_CODE (ctx) == FUNCTION_DECL
4442       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
4443       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
4444     {
4445       if (DECL_LANG_SPECIFIC (decl)
4446           && DECL_TEMPLATE_INFO (decl)
4447           && DECL_TI_TEMPLATE (decl))
4448         tmpl = DECL_TI_TEMPLATE (decl);
4449       /* If DECL is a TYPE_DECL for a class-template, then there won't
4450          be DECL_LANG_SPECIFIC.  The information equivalent to
4451          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
4452       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4453                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
4454                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
4455         {
4456           /* Since a template declaration already existed for this
4457              class-type, we must be redeclaring it here.  Make sure
4458              that the redeclaration is valid.  */
4459           redeclare_class_template (TREE_TYPE (decl),
4460                                     current_template_parms);
4461           /* We don't need to create a new TEMPLATE_DECL; just use the
4462              one we already had.  */
4463           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
4464         }
4465       else
4466         {
4467           tmpl = build_template_decl (decl, current_template_parms,
4468                                       member_template_p);
4469           new_template_p = 1;
4470
4471           if (DECL_LANG_SPECIFIC (decl)
4472               && DECL_TEMPLATE_SPECIALIZATION (decl))
4473             {
4474               /* A specialization of a member template of a template
4475                  class.  */
4476               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4477               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
4478               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
4479             }
4480         }
4481     }
4482   else
4483     {
4484       tree a, t, current, parms;
4485       int i;
4486       tree tinfo = get_template_info (decl);
4487
4488       if (!tinfo)
4489         {
4490           error ("template definition of non-template %q#D", decl);
4491           return error_mark_node;
4492         }
4493
4494       tmpl = TI_TEMPLATE (tinfo);
4495
4496       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
4497           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
4498           && DECL_TEMPLATE_SPECIALIZATION (decl)
4499           && DECL_MEMBER_TEMPLATE_P (tmpl))
4500         {
4501           tree new_tmpl;
4502
4503           /* The declaration is a specialization of a member
4504              template, declared outside the class.  Therefore, the
4505              innermost template arguments will be NULL, so we
4506              replace them with the arguments determined by the
4507              earlier call to check_explicit_specialization.  */
4508           args = DECL_TI_ARGS (decl);
4509
4510           new_tmpl
4511             = build_template_decl (decl, current_template_parms,
4512                                    member_template_p);
4513           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4514           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4515           DECL_TI_TEMPLATE (decl) = new_tmpl;
4516           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4517           DECL_TEMPLATE_INFO (new_tmpl)
4518             = build_template_info (tmpl, args);
4519
4520           register_specialization (new_tmpl,
4521                                    most_general_template (tmpl),
4522                                    args,
4523                                    is_friend, 0);
4524           return decl;
4525         }
4526
4527       /* Make sure the template headers we got make sense.  */
4528
4529       parms = DECL_TEMPLATE_PARMS (tmpl);
4530       i = TMPL_PARMS_DEPTH (parms);
4531       if (TMPL_ARGS_DEPTH (args) != i)
4532         {
4533           error ("expected %d levels of template parms for %q#D, got %d",
4534                  i, decl, TMPL_ARGS_DEPTH (args));
4535         }
4536       else
4537         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4538           {
4539             a = TMPL_ARGS_LEVEL (args, i);
4540             t = INNERMOST_TEMPLATE_PARMS (parms);
4541
4542             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4543               {
4544                 if (current == decl)
4545                   error ("got %d template parameters for %q#D",
4546                          TREE_VEC_LENGTH (a), decl);
4547                 else
4548                   error ("got %d template parameters for %q#T",
4549                          TREE_VEC_LENGTH (a), current);
4550                 error ("  but %d required", TREE_VEC_LENGTH (t));
4551                 return error_mark_node;
4552               }
4553
4554             if (current == decl)
4555               current = ctx;
4556             else if (current == NULL_TREE)
4557               /* Can happen in erroneous input.  */
4558               break;
4559             else
4560               current = (TYPE_P (current)
4561                          ? TYPE_CONTEXT (current)
4562                          : DECL_CONTEXT (current));
4563           }
4564
4565       /* Check that the parms are used in the appropriate qualifying scopes
4566          in the declarator.  */
4567       if (!comp_template_args
4568           (TI_ARGS (tinfo),
4569            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4570         {
4571           error ("\
4572 template arguments to %qD do not match original template %qD",
4573                  decl, DECL_TEMPLATE_RESULT (tmpl));
4574           if (!uses_template_parms (TI_ARGS (tinfo)))
4575             inform (input_location, "use template<> for an explicit specialization");
4576           /* Avoid crash in import_export_decl.  */
4577           DECL_INTERFACE_KNOWN (decl) = 1;
4578           return error_mark_node;
4579         }
4580     }
4581
4582   DECL_TEMPLATE_RESULT (tmpl) = decl;
4583   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4584
4585   /* Push template declarations for global functions and types.  Note
4586      that we do not try to push a global template friend declared in a
4587      template class; such a thing may well depend on the template
4588      parameters of the class.  */
4589   if (new_template_p && !ctx
4590       && !(is_friend && template_class_depth (current_class_type) > 0))
4591     {
4592       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4593       if (tmpl == error_mark_node)
4594         return error_mark_node;
4595
4596       /* Hide template friend classes that haven't been declared yet.  */
4597       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4598         {
4599           DECL_ANTICIPATED (tmpl) = 1;
4600           DECL_FRIEND_P (tmpl) = 1;
4601         }
4602     }
4603
4604   if (primary)
4605     {
4606       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4607       int i;
4608
4609       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4610       if (DECL_CONV_FN_P (tmpl))
4611         {
4612           int depth = TMPL_PARMS_DEPTH (parms);
4613
4614           /* It is a conversion operator. See if the type converted to
4615              depends on innermost template operands.  */
4616
4617           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4618                                          depth))
4619             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4620         }
4621
4622       /* Give template template parms a DECL_CONTEXT of the template
4623          for which they are a parameter.  */
4624       parms = INNERMOST_TEMPLATE_PARMS (parms);
4625       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
4626         {
4627           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4628           if (TREE_CODE (parm) == TEMPLATE_DECL)
4629             DECL_CONTEXT (parm) = tmpl;
4630         }
4631     }
4632
4633   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
4634      back to its most general template.  If TMPL is a specialization,
4635      ARGS may only have the innermost set of arguments.  Add the missing
4636      argument levels if necessary.  */
4637   if (DECL_TEMPLATE_INFO (tmpl))
4638     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
4639
4640   info = build_template_info (tmpl, args);
4641
4642   if (DECL_IMPLICIT_TYPEDEF_P (decl))
4643     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
4644   else if (DECL_LANG_SPECIFIC (decl))
4645     DECL_TEMPLATE_INFO (decl) = info;
4646
4647   return DECL_TEMPLATE_RESULT (tmpl);
4648 }
4649
4650 tree
4651 push_template_decl (tree decl)
4652 {
4653   return push_template_decl_real (decl, false);
4654 }
4655
4656 /* Called when a class template TYPE is redeclared with the indicated
4657    template PARMS, e.g.:
4658
4659      template <class T> struct S;
4660      template <class T> struct S {};  */
4661
4662 bool
4663 redeclare_class_template (tree type, tree parms)
4664 {
4665   tree tmpl;
4666   tree tmpl_parms;
4667   int i;
4668
4669   if (!TYPE_TEMPLATE_INFO (type))
4670     {
4671       error ("%qT is not a template type", type);
4672       return false;
4673     }
4674
4675   tmpl = TYPE_TI_TEMPLATE (type);
4676   if (!PRIMARY_TEMPLATE_P (tmpl))
4677     /* The type is nested in some template class.  Nothing to worry
4678        about here; there are no new template parameters for the nested
4679        type.  */
4680     return true;
4681
4682   if (!parms)
4683     {
4684       error ("template specifiers not specified in declaration of %qD",
4685              tmpl);
4686       return false;
4687     }
4688
4689   parms = INNERMOST_TEMPLATE_PARMS (parms);
4690   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
4691
4692   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
4693     {
4694       error_n (input_location, TREE_VEC_LENGTH (parms),
4695                "redeclared with %d template parameter",
4696                "redeclared with %d template parameters",
4697                TREE_VEC_LENGTH (parms));
4698       inform_n (input_location, TREE_VEC_LENGTH (tmpl_parms),
4699                 "previous declaration %q+D used %d template parameter",
4700                 "previous declaration %q+D used %d template parameters",
4701                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
4702       return false;
4703     }
4704
4705   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
4706     {
4707       tree tmpl_parm;
4708       tree parm;
4709       tree tmpl_default;
4710       tree parm_default;
4711
4712       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
4713           || TREE_VEC_ELT (parms, i) == error_mark_node)
4714         continue;
4715
4716       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
4717       if (tmpl_parm == error_mark_node)
4718         return false;
4719
4720       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4721       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
4722       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
4723
4724       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
4725          TEMPLATE_DECL.  */
4726       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
4727           || (TREE_CODE (tmpl_parm) != TYPE_DECL
4728               && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
4729           || (TREE_CODE (tmpl_parm) != PARM_DECL
4730               && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
4731                   != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
4732           || (TREE_CODE (tmpl_parm) == PARM_DECL
4733               && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
4734                   != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
4735         {
4736           error ("template parameter %q+#D", tmpl_parm);
4737           error ("redeclared here as %q#D", parm);
4738           return false;
4739         }
4740
4741       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
4742         {
4743           /* We have in [temp.param]:
4744
4745              A template-parameter may not be given default arguments
4746              by two different declarations in the same scope.  */
4747           error_at (input_location, "redefinition of default argument for %q#D", parm);
4748           inform (DECL_SOURCE_LOCATION (tmpl_parm),
4749                   "original definition appeared here");
4750           return false;
4751         }
4752
4753       if (parm_default != NULL_TREE)
4754         /* Update the previous template parameters (which are the ones
4755            that will really count) with the new default value.  */
4756         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
4757       else if (tmpl_default != NULL_TREE)
4758         /* Update the new parameters, too; they'll be used as the
4759            parameters for any members.  */
4760         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
4761     }
4762
4763     return true;
4764 }
4765
4766 /* Simplify EXPR if it is a non-dependent expression.  Returns the
4767    (possibly simplified) expression.  */
4768
4769 tree
4770 fold_non_dependent_expr (tree expr)
4771 {
4772   if (expr == NULL_TREE)
4773     return NULL_TREE;
4774
4775   /* If we're in a template, but EXPR isn't value dependent, simplify
4776      it.  We're supposed to treat:
4777
4778        template <typename T> void f(T[1 + 1]);
4779        template <typename T> void f(T[2]);
4780
4781      as two declarations of the same function, for example.  */
4782   if (processing_template_decl
4783       && !type_dependent_expression_p (expr)
4784       && !value_dependent_expression_p (expr))
4785     {
4786       HOST_WIDE_INT saved_processing_template_decl;
4787
4788       saved_processing_template_decl = processing_template_decl;
4789       processing_template_decl = 0;
4790       expr = tsubst_copy_and_build (expr,
4791                                     /*args=*/NULL_TREE,
4792                                     tf_error,
4793                                     /*in_decl=*/NULL_TREE,
4794                                     /*function_p=*/false,
4795                                     /*integral_constant_expression_p=*/true);
4796       processing_template_decl = saved_processing_template_decl;
4797     }
4798   return expr;
4799 }
4800
4801 /* EXPR is an expression which is used in a constant-expression context.
4802    For instance, it could be a VAR_DECL with a constant initializer.
4803    Extract the innermost constant expression.
4804
4805    This is basically a more powerful version of
4806    integral_constant_value, which can be used also in templates where
4807    initializers can maintain a syntactic rather than semantic form
4808    (even if they are non-dependent, for access-checking purposes).  */
4809
4810 static tree
4811 fold_decl_constant_value (tree expr)
4812 {
4813   tree const_expr = expr;
4814   do
4815     {
4816       expr = fold_non_dependent_expr (const_expr);
4817       const_expr = integral_constant_value (expr);
4818     }
4819   while (expr != const_expr);
4820
4821   return expr;
4822 }
4823
4824 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
4825    must be a function or a pointer-to-function type, as specified
4826    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
4827    and check that the resulting function has external linkage.  */
4828
4829 static tree
4830 convert_nontype_argument_function (tree type, tree expr)
4831 {
4832   tree fns = expr;
4833   tree fn, fn_no_ptr;
4834
4835   fn = instantiate_type (type, fns, tf_none);
4836   if (fn == error_mark_node)
4837     return error_mark_node;
4838
4839   fn_no_ptr = fn;
4840   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
4841     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
4842   if (TREE_CODE (fn_no_ptr) == BASELINK)
4843     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
4844  
4845   /* [temp.arg.nontype]/1
4846
4847      A template-argument for a non-type, non-template template-parameter
4848      shall be one of:
4849      [...]
4850      -- the address of an object or function with external linkage.  */
4851   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
4852     {
4853       error ("%qE is not a valid template argument for type %qT "
4854              "because function %qD has not external linkage",
4855              expr, type, fn_no_ptr);
4856       return NULL_TREE;
4857     }
4858
4859   return fn;
4860 }
4861
4862 /* Subroutine of convert_nontype_argument.
4863    Check if EXPR of type TYPE is a valid pointer-to-member constant.
4864    Emit an error otherwise.  */
4865
4866 static bool
4867 check_valid_ptrmem_cst_expr (tree type, tree expr)
4868 {
4869   STRIP_NOPS (expr);
4870   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
4871     return true;
4872   error ("%qE is not a valid template argument for type %qT",
4873          expr, type);
4874   error ("it must be a pointer-to-member of the form `&X::Y'");
4875   return false;
4876 }
4877
4878 /* Attempt to convert the non-type template parameter EXPR to the
4879    indicated TYPE.  If the conversion is successful, return the
4880    converted value.  If the conversion is unsuccessful, return
4881    NULL_TREE if we issued an error message, or error_mark_node if we
4882    did not.  We issue error messages for out-and-out bad template
4883    parameters, but not simply because the conversion failed, since we
4884    might be just trying to do argument deduction.  Both TYPE and EXPR
4885    must be non-dependent.
4886
4887    The conversion follows the special rules described in
4888    [temp.arg.nontype], and it is much more strict than an implicit
4889    conversion.
4890
4891    This function is called twice for each template argument (see
4892    lookup_template_class for a more accurate description of this
4893    problem). This means that we need to handle expressions which
4894    are not valid in a C++ source, but can be created from the
4895    first call (for instance, casts to perform conversions). These
4896    hacks can go away after we fix the double coercion problem.  */
4897
4898 static tree
4899 convert_nontype_argument (tree type, tree expr)
4900 {
4901   tree expr_type;
4902
4903   /* Detect immediately string literals as invalid non-type argument.
4904      This special-case is not needed for correctness (we would easily
4905      catch this later), but only to provide better diagnostic for this
4906      common user mistake. As suggested by DR 100, we do not mention
4907      linkage issues in the diagnostic as this is not the point.  */
4908   if (TREE_CODE (expr) == STRING_CST)
4909     {
4910       error ("%qE is not a valid template argument for type %qT "
4911              "because string literals can never be used in this context",
4912              expr, type);
4913       return NULL_TREE;
4914     }
4915
4916   /* If we are in a template, EXPR may be non-dependent, but still
4917      have a syntactic, rather than semantic, form.  For example, EXPR
4918      might be a SCOPE_REF, rather than the VAR_DECL to which the
4919      SCOPE_REF refers.  Preserving the qualifying scope is necessary
4920      so that access checking can be performed when the template is
4921      instantiated -- but here we need the resolved form so that we can
4922      convert the argument.  */
4923   expr = fold_non_dependent_expr (expr);
4924   if (error_operand_p (expr))
4925     return error_mark_node;
4926   expr_type = TREE_TYPE (expr);
4927
4928   /* HACK: Due to double coercion, we can get a
4929      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
4930      which is the tree that we built on the first call (see
4931      below when coercing to reference to object or to reference to
4932      function). We just strip everything and get to the arg.
4933      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
4934      for examples.  */
4935   if (TREE_CODE (expr) == NOP_EXPR)
4936     {
4937       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
4938         {
4939           /* ??? Maybe we could use convert_from_reference here, but we
4940              would need to relax its constraints because the NOP_EXPR
4941              could actually change the type to something more cv-qualified,
4942              and this is not folded by convert_from_reference.  */
4943           tree addr = TREE_OPERAND (expr, 0);
4944           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
4945           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
4946           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
4947           gcc_assert (same_type_ignoring_top_level_qualifiers_p
4948                       (TREE_TYPE (expr_type),
4949                        TREE_TYPE (TREE_TYPE (addr))));
4950
4951           expr = TREE_OPERAND (addr, 0);
4952           expr_type = TREE_TYPE (expr);
4953         }
4954
4955       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
4956          parameter is a pointer to object, through decay and
4957          qualification conversion. Let's strip everything.  */
4958       else if (TYPE_PTROBV_P (type))
4959         {
4960           STRIP_NOPS (expr);
4961           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
4962           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
4963           /* Skip the ADDR_EXPR only if it is part of the decay for
4964              an array. Otherwise, it is part of the original argument
4965              in the source code.  */
4966           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
4967             expr = TREE_OPERAND (expr, 0);
4968           expr_type = TREE_TYPE (expr);
4969         }
4970     }
4971
4972   /* [temp.arg.nontype]/5, bullet 1
4973
4974      For a non-type template-parameter of integral or enumeration type,
4975      integral promotions (_conv.prom_) and integral conversions
4976      (_conv.integral_) are applied.  */
4977   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
4978     {
4979       if (!INTEGRAL_OR_ENUMERATION_TYPE_P (expr_type))
4980         return error_mark_node;
4981
4982       expr = fold_decl_constant_value (expr);
4983       /* Notice that there are constant expressions like '4 % 0' which
4984          do not fold into integer constants.  */
4985       if (TREE_CODE (expr) != INTEGER_CST)
4986         {
4987           error ("%qE is not a valid template argument for type %qT "
4988                  "because it is a non-constant expression", expr, type);
4989           return NULL_TREE;
4990         }
4991
4992       /* At this point, an implicit conversion does what we want,
4993          because we already know that the expression is of integral
4994          type.  */
4995       expr = ocp_convert (type, expr, CONV_IMPLICIT, LOOKUP_PROTECT);
4996       if (expr == error_mark_node)
4997         return error_mark_node;
4998
4999       /* Conversion was allowed: fold it to a bare integer constant.  */
5000       expr = fold (expr);
5001     }
5002   /* [temp.arg.nontype]/5, bullet 2
5003
5004      For a non-type template-parameter of type pointer to object,
5005      qualification conversions (_conv.qual_) and the array-to-pointer
5006      conversion (_conv.array_) are applied.  */
5007   else if (TYPE_PTROBV_P (type))
5008     {
5009       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
5010
5011          A template-argument for a non-type, non-template template-parameter
5012          shall be one of: [...]
5013
5014          -- the name of a non-type template-parameter;
5015          -- the address of an object or function with external linkage, [...]
5016             expressed as "& id-expression" where the & is optional if the name
5017             refers to a function or array, or if the corresponding
5018             template-parameter is a reference.
5019
5020         Here, we do not care about functions, as they are invalid anyway
5021         for a parameter of type pointer-to-object.  */
5022
5023       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
5024         /* Non-type template parameters are OK.  */
5025         ;
5026       else if (TREE_CODE (expr) != ADDR_EXPR
5027                && TREE_CODE (expr_type) != ARRAY_TYPE)
5028         {
5029           if (TREE_CODE (expr) == VAR_DECL)
5030             {
5031               error ("%qD is not a valid template argument "
5032                      "because %qD is a variable, not the address of "
5033                      "a variable",
5034                      expr, expr);
5035               return NULL_TREE;
5036             }
5037           /* Other values, like integer constants, might be valid
5038              non-type arguments of some other type.  */
5039           return error_mark_node;
5040         }
5041       else
5042         {
5043           tree decl;
5044
5045           decl = ((TREE_CODE (expr) == ADDR_EXPR)
5046                   ? TREE_OPERAND (expr, 0) : expr);
5047           if (TREE_CODE (decl) != VAR_DECL)
5048             {
5049               error ("%qE is not a valid template argument of type %qT "
5050                      "because %qE is not a variable",
5051                      expr, type, decl);
5052               return NULL_TREE;
5053             }
5054           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
5055             {
5056               error ("%qE is not a valid template argument of type %qT "
5057                      "because %qD does not have external linkage",
5058                      expr, type, decl);
5059               return NULL_TREE;
5060             }
5061         }
5062
5063       expr = decay_conversion (expr);
5064       if (expr == error_mark_node)
5065         return error_mark_node;
5066
5067       expr = perform_qualification_conversions (type, expr);
5068       if (expr == error_mark_node)
5069         return error_mark_node;
5070     }
5071   /* [temp.arg.nontype]/5, bullet 3
5072
5073      For a non-type template-parameter of type reference to object, no
5074      conversions apply. The type referred to by the reference may be more
5075      cv-qualified than the (otherwise identical) type of the
5076      template-argument. The template-parameter is bound directly to the
5077      template-argument, which must be an lvalue.  */
5078   else if (TYPE_REF_OBJ_P (type))
5079     {
5080       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
5081                                                       expr_type))
5082         return error_mark_node;
5083
5084       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
5085         {
5086           error ("%qE is not a valid template argument for type %qT "
5087                  "because of conflicts in cv-qualification", expr, type);
5088           return NULL_TREE;
5089         }
5090
5091       if (!real_lvalue_p (expr))
5092         {
5093           error ("%qE is not a valid template argument for type %qT "
5094                  "because it is not an lvalue", expr, type);
5095           return NULL_TREE;
5096         }
5097
5098       /* [temp.arg.nontype]/1
5099
5100          A template-argument for a non-type, non-template template-parameter
5101          shall be one of: [...]
5102
5103          -- the address of an object or function with external linkage.  */
5104       if (TREE_CODE (expr) == INDIRECT_REF
5105           && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
5106         {
5107           expr = TREE_OPERAND (expr, 0);
5108           if (DECL_P (expr))
5109             {
5110               error ("%q#D is not a valid template argument for type %qT "
5111                      "because a reference variable does not have a constant "
5112                      "address", expr, type);
5113               return NULL_TREE;
5114             }
5115         }
5116
5117       if (!DECL_P (expr))
5118         {
5119           error ("%qE is not a valid template argument for type %qT "
5120                  "because it is not an object with external linkage",
5121                  expr, type);
5122           return NULL_TREE;
5123         }
5124
5125       if (!DECL_EXTERNAL_LINKAGE_P (expr))
5126         {
5127           error ("%qE is not a valid template argument for type %qT "
5128                  "because object %qD has not external linkage",
5129                  expr, type, expr);
5130           return NULL_TREE;
5131         }
5132
5133       expr = build_nop (type, build_address (expr));
5134     }
5135   /* [temp.arg.nontype]/5, bullet 4
5136
5137      For a non-type template-parameter of type pointer to function, only
5138      the function-to-pointer conversion (_conv.func_) is applied. If the
5139      template-argument represents a set of overloaded functions (or a
5140      pointer to such), the matching function is selected from the set
5141      (_over.over_).  */
5142   else if (TYPE_PTRFN_P (type))
5143     {
5144       /* If the argument is a template-id, we might not have enough
5145          context information to decay the pointer.  */
5146       if (!type_unknown_p (expr_type))
5147         {
5148           expr = decay_conversion (expr);
5149           if (expr == error_mark_node)
5150             return error_mark_node;
5151         }
5152
5153       expr = convert_nontype_argument_function (type, expr);
5154       if (!expr || expr == error_mark_node)
5155         return expr;
5156
5157       if (TREE_CODE (expr) != ADDR_EXPR)
5158         {
5159           error ("%qE is not a valid template argument for type %qT", expr, type);
5160           error ("it must be the address of a function with external linkage");
5161           return NULL_TREE;
5162         }
5163     }
5164   /* [temp.arg.nontype]/5, bullet 5
5165
5166      For a non-type template-parameter of type reference to function, no
5167      conversions apply. If the template-argument represents a set of
5168      overloaded functions, the matching function is selected from the set
5169      (_over.over_).  */
5170   else if (TYPE_REFFN_P (type))
5171     {
5172       if (TREE_CODE (expr) == ADDR_EXPR)
5173         {
5174           error ("%qE is not a valid template argument for type %qT "
5175                  "because it is a pointer", expr, type);
5176           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
5177           return NULL_TREE;
5178         }
5179
5180       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
5181       if (!expr || expr == error_mark_node)
5182         return expr;
5183
5184       expr = build_nop (type, build_address (expr));
5185     }
5186   /* [temp.arg.nontype]/5, bullet 6
5187
5188      For a non-type template-parameter of type pointer to member function,
5189      no conversions apply. If the template-argument represents a set of
5190      overloaded member functions, the matching member function is selected
5191      from the set (_over.over_).  */
5192   else if (TYPE_PTRMEMFUNC_P (type))
5193     {
5194       expr = instantiate_type (type, expr, tf_none);
5195       if (expr == error_mark_node)
5196         return error_mark_node;
5197
5198       /* [temp.arg.nontype] bullet 1 says the pointer to member
5199          expression must be a pointer-to-member constant.  */
5200       if (!check_valid_ptrmem_cst_expr (type, expr))
5201         return error_mark_node;
5202
5203       /* There is no way to disable standard conversions in
5204          resolve_address_of_overloaded_function (called by
5205          instantiate_type). It is possible that the call succeeded by
5206          converting &B::I to &D::I (where B is a base of D), so we need
5207          to reject this conversion here.
5208
5209          Actually, even if there was a way to disable standard conversions,
5210          it would still be better to reject them here so that we can
5211          provide a superior diagnostic.  */
5212       if (!same_type_p (TREE_TYPE (expr), type))
5213         {
5214           error ("%qE is not a valid template argument for type %qT "
5215                  "because it is of type %qT", expr, type,
5216                  TREE_TYPE (expr));
5217           /* If we are just one standard conversion off, explain.  */
5218           if (can_convert (type, TREE_TYPE (expr)))
5219             inform (input_location,
5220                     "standard conversions are not allowed in this context");
5221           return NULL_TREE;
5222         }
5223     }
5224   /* [temp.arg.nontype]/5, bullet 7
5225
5226      For a non-type template-parameter of type pointer to data member,
5227      qualification conversions (_conv.qual_) are applied.  */
5228   else if (TYPE_PTRMEM_P (type))
5229     {
5230       /* [temp.arg.nontype] bullet 1 says the pointer to member
5231          expression must be a pointer-to-member constant.  */
5232       if (!check_valid_ptrmem_cst_expr (type, expr))
5233         return error_mark_node;
5234
5235       expr = perform_qualification_conversions (type, expr);
5236       if (expr == error_mark_node)
5237         return expr;
5238     }
5239   /* A template non-type parameter must be one of the above.  */
5240   else
5241     gcc_unreachable ();
5242
5243   /* Sanity check: did we actually convert the argument to the
5244      right type?  */
5245   gcc_assert (same_type_p (type, TREE_TYPE (expr)));
5246   return expr;
5247 }
5248
5249 /* Subroutine of coerce_template_template_parms, which returns 1 if
5250    PARM_PARM and ARG_PARM match using the rule for the template
5251    parameters of template template parameters. Both PARM and ARG are
5252    template parameters; the rest of the arguments are the same as for
5253    coerce_template_template_parms.
5254  */
5255 static int
5256 coerce_template_template_parm (tree parm,
5257                               tree arg,
5258                               tsubst_flags_t complain,
5259                               tree in_decl,
5260                               tree outer_args)
5261 {
5262   if (arg == NULL_TREE || arg == error_mark_node
5263       || parm == NULL_TREE || parm == error_mark_node)
5264     return 0;
5265   
5266   if (TREE_CODE (arg) != TREE_CODE (parm))
5267     return 0;
5268   
5269   switch (TREE_CODE (parm))
5270     {
5271     case TEMPLATE_DECL:
5272       /* We encounter instantiations of templates like
5273          template <template <template <class> class> class TT>
5274          class C;  */
5275       {
5276         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5277         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5278         
5279         if (!coerce_template_template_parms
5280             (parmparm, argparm, complain, in_decl, outer_args))
5281           return 0;
5282       }
5283       /* Fall through.  */
5284       
5285     case TYPE_DECL:
5286       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
5287           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5288         /* Argument is a parameter pack but parameter is not.  */
5289         return 0;
5290       break;
5291       
5292     case PARM_DECL:
5293       /* The tsubst call is used to handle cases such as
5294          
5295            template <int> class C {};
5296            template <class T, template <T> class TT> class D {};
5297            D<int, C> d;
5298
5299          i.e. the parameter list of TT depends on earlier parameters.  */
5300       if (!uses_template_parms (TREE_TYPE (arg))
5301           && !same_type_p
5302                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
5303                  TREE_TYPE (arg)))
5304         return 0;
5305       
5306       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
5307           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5308         /* Argument is a parameter pack but parameter is not.  */
5309         return 0;
5310       
5311       break;
5312
5313     default:
5314       gcc_unreachable ();
5315     }
5316
5317   return 1;
5318 }
5319
5320
5321 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
5322    template template parameters.  Both PARM_PARMS and ARG_PARMS are
5323    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
5324    or PARM_DECL.
5325
5326    Consider the example:
5327      template <class T> class A;
5328      template<template <class U> class TT> class B;
5329
5330    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
5331    the parameters to A, and OUTER_ARGS contains A.  */
5332
5333 static int
5334 coerce_template_template_parms (tree parm_parms,
5335                                 tree arg_parms,
5336                                 tsubst_flags_t complain,
5337                                 tree in_decl,
5338                                 tree outer_args)
5339 {
5340   int nparms, nargs, i;
5341   tree parm, arg;
5342   int variadic_p = 0;
5343
5344   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
5345   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
5346
5347   nparms = TREE_VEC_LENGTH (parm_parms);
5348   nargs = TREE_VEC_LENGTH (arg_parms);
5349
5350   /* Determine whether we have a parameter pack at the end of the
5351      template template parameter's template parameter list.  */
5352   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
5353     {
5354       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
5355       
5356       if (parm == error_mark_node)
5357         return 0;
5358
5359       switch (TREE_CODE (parm))
5360         {
5361         case TEMPLATE_DECL:
5362         case TYPE_DECL:
5363           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5364             variadic_p = 1;
5365           break;
5366           
5367         case PARM_DECL:
5368           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5369             variadic_p = 1;
5370           break;
5371           
5372         default:
5373           gcc_unreachable ();
5374         }
5375     }
5376  
5377   if (nargs != nparms
5378       && !(variadic_p && nargs >= nparms - 1))
5379     return 0;
5380
5381   /* Check all of the template parameters except the parameter pack at
5382      the end (if any).  */
5383   for (i = 0; i < nparms - variadic_p; ++i)
5384     {
5385       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
5386           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5387         continue;
5388
5389       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5390       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5391
5392       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5393                                           outer_args))
5394         return 0;
5395
5396     }
5397
5398   if (variadic_p)
5399     {
5400       /* Check each of the template parameters in the template
5401          argument against the template parameter pack at the end of
5402          the template template parameter.  */
5403       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
5404         return 0;
5405
5406       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5407
5408       for (; i < nargs; ++i)
5409         {
5410           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5411             continue;
5412  
5413           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5414  
5415           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5416                                               outer_args))
5417             return 0;
5418         }
5419     }
5420
5421   return 1;
5422 }
5423
5424 /* Verifies that the deduced template arguments (in TARGS) for the
5425    template template parameters (in TPARMS) represent valid bindings,
5426    by comparing the template parameter list of each template argument
5427    to the template parameter list of its corresponding template
5428    template parameter, in accordance with DR150. This
5429    routine can only be called after all template arguments have been
5430    deduced. It will return TRUE if all of the template template
5431    parameter bindings are okay, FALSE otherwise.  */
5432 bool 
5433 template_template_parm_bindings_ok_p (tree tparms, tree targs)
5434 {
5435   int i, ntparms = TREE_VEC_LENGTH (tparms);
5436   bool ret = true;
5437
5438   /* We're dealing with template parms in this process.  */
5439   ++processing_template_decl;
5440
5441   targs = INNERMOST_TEMPLATE_ARGS (targs);
5442
5443   for (i = 0; i < ntparms; ++i)
5444     {
5445       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
5446       tree targ = TREE_VEC_ELT (targs, i);
5447
5448       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
5449         {
5450           tree packed_args = NULL_TREE;
5451           int idx, len = 1;
5452
5453           if (ARGUMENT_PACK_P (targ))
5454             {
5455               /* Look inside the argument pack.  */
5456               packed_args = ARGUMENT_PACK_ARGS (targ);
5457               len = TREE_VEC_LENGTH (packed_args);
5458             }
5459
5460           for (idx = 0; idx < len; ++idx)
5461             {
5462               tree targ_parms = NULL_TREE;
5463
5464               if (packed_args)
5465                 /* Extract the next argument from the argument
5466                    pack.  */
5467                 targ = TREE_VEC_ELT (packed_args, idx);
5468
5469               if (PACK_EXPANSION_P (targ))
5470                 /* Look at the pattern of the pack expansion.  */
5471                 targ = PACK_EXPANSION_PATTERN (targ);
5472
5473               /* Extract the template parameters from the template
5474                  argument.  */
5475               if (TREE_CODE (targ) == TEMPLATE_DECL)
5476                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
5477               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
5478                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
5479
5480               /* Verify that we can coerce the template template
5481                  parameters from the template argument to the template
5482                  parameter.  This requires an exact match.  */
5483               if (targ_parms
5484                   && !coerce_template_template_parms
5485                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
5486                         targ_parms,
5487                         tf_none,
5488                         tparm,
5489                         targs))
5490                 {
5491                   ret = false;
5492                   goto out;
5493                 }
5494             }
5495         }
5496     }
5497
5498  out:
5499
5500   --processing_template_decl;
5501   return ret;
5502 }
5503
5504 /* Convert the indicated template ARG as necessary to match the
5505    indicated template PARM.  Returns the converted ARG, or
5506    error_mark_node if the conversion was unsuccessful.  Error and
5507    warning messages are issued under control of COMPLAIN.  This
5508    conversion is for the Ith parameter in the parameter list.  ARGS is
5509    the full set of template arguments deduced so far.  */
5510
5511 static tree
5512 convert_template_argument (tree parm,
5513                            tree arg,
5514                            tree args,
5515                            tsubst_flags_t complain,
5516                            int i,
5517                            tree in_decl)
5518 {
5519   tree orig_arg;
5520   tree val;
5521   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
5522
5523   if (TREE_CODE (arg) == TREE_LIST
5524       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
5525     {
5526       /* The template argument was the name of some
5527          member function.  That's usually
5528          invalid, but static members are OK.  In any
5529          case, grab the underlying fields/functions
5530          and issue an error later if required.  */
5531       orig_arg = TREE_VALUE (arg);
5532       TREE_TYPE (arg) = unknown_type_node;
5533     }
5534
5535   orig_arg = arg;
5536
5537   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
5538   requires_type = (TREE_CODE (parm) == TYPE_DECL
5539                    || requires_tmpl_type);
5540
5541   /* When determining whether an argument pack expansion is a template,
5542      look at the pattern.  */
5543   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
5544     arg = PACK_EXPANSION_PATTERN (arg);
5545
5546   /* Deal with an injected-class-name used as a template template arg.  */
5547   if (requires_tmpl_type && CLASS_TYPE_P (arg))
5548     {
5549       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
5550       if (TREE_CODE (t) == TEMPLATE_DECL)
5551         {
5552           if (complain & tf_warning_or_error)
5553             pedwarn (input_location, OPT_pedantic, "injected-class-name %qD"
5554                      " used as template template argument", TYPE_NAME (arg));
5555           else if (flag_pedantic_errors)
5556             t = arg;
5557
5558           arg = t;
5559         }
5560     }
5561
5562   is_tmpl_type = 
5563     ((TREE_CODE (arg) == TEMPLATE_DECL
5564       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
5565      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5566      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
5567
5568   if (is_tmpl_type
5569       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5570           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
5571     arg = TYPE_STUB_DECL (arg);
5572
5573   is_type = TYPE_P (arg) || is_tmpl_type;
5574
5575   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
5576       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
5577     {
5578       permerror (input_location, "to refer to a type member of a template parameter, "
5579                  "use %<typename %E%>", orig_arg);
5580
5581       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
5582                                      TREE_OPERAND (arg, 1),
5583                                      typename_type,
5584                                      complain & tf_error);
5585       arg = orig_arg;
5586       is_type = 1;
5587     }
5588   if (is_type != requires_type)
5589     {
5590       if (in_decl)
5591         {
5592           if (complain & tf_error)
5593             {
5594               error ("type/value mismatch at argument %d in template "
5595                      "parameter list for %qD",
5596                      i + 1, in_decl);
5597               if (is_type)
5598                 error ("  expected a constant of type %qT, got %qT",
5599                        TREE_TYPE (parm),
5600                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
5601               else if (requires_tmpl_type)
5602                 error ("  expected a class template, got %qE", orig_arg);
5603               else
5604                 error ("  expected a type, got %qE", orig_arg);
5605             }
5606         }
5607       return error_mark_node;
5608     }
5609   if (is_tmpl_type ^ requires_tmpl_type)
5610     {
5611       if (in_decl && (complain & tf_error))
5612         {
5613           error ("type/value mismatch at argument %d in template "
5614                  "parameter list for %qD",
5615                  i + 1, in_decl);
5616           if (is_tmpl_type)
5617             error ("  expected a type, got %qT", DECL_NAME (arg));
5618           else
5619             error ("  expected a class template, got %qT", orig_arg);
5620         }
5621       return error_mark_node;
5622     }
5623
5624   if (is_type)
5625     {
5626       if (requires_tmpl_type)
5627         {
5628           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
5629             /* The number of argument required is not known yet.
5630                Just accept it for now.  */
5631             val = TREE_TYPE (arg);
5632           else
5633             {
5634               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5635               tree argparm;
5636
5637               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5638
5639               if (coerce_template_template_parms (parmparm, argparm,
5640                                                   complain, in_decl,
5641                                                   args))
5642                 {
5643                   val = arg;
5644
5645                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
5646                      TEMPLATE_DECL.  */
5647                   if (val != error_mark_node)
5648                     {
5649                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
5650                         val = TREE_TYPE (val);
5651                       if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
5652                         val = make_pack_expansion (val);
5653                     }
5654                 }
5655               else
5656                 {
5657                   if (in_decl && (complain & tf_error))
5658                     {
5659                       error ("type/value mismatch at argument %d in "
5660                              "template parameter list for %qD",
5661                              i + 1, in_decl);
5662                       error ("  expected a template of type %qD, got %qT",
5663                              parm, orig_arg);
5664                     }
5665
5666                   val = error_mark_node;
5667                 }
5668             }
5669         }
5670       else
5671         val = orig_arg;
5672       /* We only form one instance of each template specialization.
5673          Therefore, if we use a non-canonical variant (i.e., a
5674          typedef), any future messages referring to the type will use
5675          the typedef, which is confusing if those future uses do not
5676          themselves also use the typedef.  */
5677       if (TYPE_P (val))
5678         val = strip_typedefs (val);
5679     }
5680   else
5681     {
5682       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
5683
5684       if (invalid_nontype_parm_type_p (t, complain))
5685         return error_mark_node;
5686
5687       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
5688         {
5689           if (same_type_p (t, TREE_TYPE (orig_arg)))
5690             val = orig_arg;
5691           else
5692             {
5693               /* Not sure if this is reachable, but it doesn't hurt
5694                  to be robust.  */
5695               error ("type mismatch in nontype parameter pack");
5696               val = error_mark_node;
5697             }
5698         }
5699       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
5700         /* We used to call digest_init here.  However, digest_init
5701            will report errors, which we don't want when complain
5702            is zero.  More importantly, digest_init will try too
5703            hard to convert things: for example, `0' should not be
5704            converted to pointer type at this point according to
5705            the standard.  Accepting this is not merely an
5706            extension, since deciding whether or not these
5707            conversions can occur is part of determining which
5708            function template to call, or whether a given explicit
5709            argument specification is valid.  */
5710         val = convert_nontype_argument (t, orig_arg);
5711       else
5712         val = orig_arg;
5713
5714       if (val == NULL_TREE)
5715         val = error_mark_node;
5716       else if (val == error_mark_node && (complain & tf_error))
5717         error ("could not convert template argument %qE to %qT",  orig_arg, t);
5718
5719       if (TREE_CODE (val) == SCOPE_REF)
5720         {
5721           /* Strip typedefs from the SCOPE_REF.  */
5722           tree type = strip_typedefs (TREE_TYPE (val));
5723           tree scope = strip_typedefs (TREE_OPERAND (val, 0));
5724           val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
5725                                       QUALIFIED_NAME_IS_TEMPLATE (val));
5726         }
5727     }
5728
5729   return val;
5730 }
5731
5732 /* Coerces the remaining template arguments in INNER_ARGS (from
5733    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
5734    Returns the coerced argument pack. PARM_IDX is the position of this
5735    parameter in the template parameter list. ARGS is the original
5736    template argument list.  */
5737 static tree
5738 coerce_template_parameter_pack (tree parms,
5739                                 int parm_idx,
5740                                 tree args,
5741                                 tree inner_args,
5742                                 int arg_idx,
5743                                 tree new_args,
5744                                 int* lost,
5745                                 tree in_decl,
5746                                 tsubst_flags_t complain)
5747 {
5748   tree parm = TREE_VEC_ELT (parms, parm_idx);
5749   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5750   tree packed_args;
5751   tree argument_pack;
5752   tree packed_types = NULL_TREE;
5753
5754   if (arg_idx > nargs)
5755     arg_idx = nargs;
5756
5757   packed_args = make_tree_vec (nargs - arg_idx);
5758
5759   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
5760       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
5761     {
5762       /* When the template parameter is a non-type template
5763          parameter pack whose type uses parameter packs, we need
5764          to look at each of the template arguments
5765          separately. Build a vector of the types for these
5766          non-type template parameters in PACKED_TYPES.  */
5767       tree expansion 
5768         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
5769       packed_types = tsubst_pack_expansion (expansion, args,
5770                                             complain, in_decl);
5771
5772       if (packed_types == error_mark_node)
5773         return error_mark_node;
5774
5775       /* Check that we have the right number of arguments.  */
5776       if (arg_idx < nargs
5777           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
5778           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
5779         {
5780           int needed_parms 
5781             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
5782           error ("wrong number of template arguments (%d, should be %d)",
5783                  nargs, needed_parms);
5784           return error_mark_node;
5785         }
5786
5787       /* If we aren't able to check the actual arguments now
5788          (because they haven't been expanded yet), we can at least
5789          verify that all of the types used for the non-type
5790          template parameter pack are, in fact, valid for non-type
5791          template parameters.  */
5792       if (arg_idx < nargs 
5793           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
5794         {
5795           int j, len = TREE_VEC_LENGTH (packed_types);
5796           for (j = 0; j < len; ++j)
5797             {
5798               tree t = TREE_VEC_ELT (packed_types, j);
5799               if (invalid_nontype_parm_type_p (t, complain))
5800                 return error_mark_node;
5801             }
5802         }
5803     }
5804
5805   /* Convert the remaining arguments, which will be a part of the
5806      parameter pack "parm".  */
5807   for (; arg_idx < nargs; ++arg_idx)
5808     {
5809       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
5810       tree actual_parm = TREE_VALUE (parm);
5811
5812       if (packed_types && !PACK_EXPANSION_P (arg))
5813         {
5814           /* When we have a vector of types (corresponding to the
5815              non-type template parameter pack that uses parameter
5816              packs in its type, as mention above), and the
5817              argument is not an expansion (which expands to a
5818              currently unknown number of arguments), clone the
5819              parm and give it the next type in PACKED_TYPES.  */
5820           actual_parm = copy_node (actual_parm);
5821           TREE_TYPE (actual_parm) = 
5822             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
5823         }
5824
5825       if (arg != error_mark_node)
5826         arg = convert_template_argument (actual_parm, 
5827                                          arg, new_args, complain, parm_idx,
5828                                          in_decl);
5829       if (arg == error_mark_node)
5830         (*lost)++;
5831       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
5832     }
5833
5834   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
5835       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
5836     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
5837   else
5838     {
5839       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
5840       TREE_TYPE (argument_pack) 
5841         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
5842       TREE_CONSTANT (argument_pack) = 1;
5843     }
5844
5845   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
5846 #ifdef ENABLE_CHECKING
5847   SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
5848                                        TREE_VEC_LENGTH (packed_args));
5849 #endif
5850   return argument_pack;
5851 }
5852
5853 /* Convert all template arguments to their appropriate types, and
5854    return a vector containing the innermost resulting template
5855    arguments.  If any error occurs, return error_mark_node. Error and
5856    warning messages are issued under control of COMPLAIN.
5857
5858    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
5859    for arguments not specified in ARGS.  Otherwise, if
5860    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
5861    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
5862    USE_DEFAULT_ARGS is false, then all arguments must be specified in
5863    ARGS.  */
5864
5865 static tree
5866 coerce_template_parms (tree parms,
5867                        tree args,
5868                        tree in_decl,
5869                        tsubst_flags_t complain,
5870                        bool require_all_args,
5871                        bool use_default_args)
5872 {
5873   int nparms, nargs, parm_idx, arg_idx, lost = 0;
5874   tree inner_args;
5875   tree new_args;
5876   tree new_inner_args;
5877   int saved_unevaluated_operand;
5878   int saved_inhibit_evaluation_warnings;
5879
5880   /* When used as a boolean value, indicates whether this is a
5881      variadic template parameter list. Since it's an int, we can also
5882      subtract it from nparms to get the number of non-variadic
5883      parameters.  */
5884   int variadic_p = 0;
5885
5886   nparms = TREE_VEC_LENGTH (parms);
5887
5888   /* Determine if there are any parameter packs.  */
5889   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
5890     {
5891       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
5892       if (template_parameter_pack_p (tparm))
5893         ++variadic_p;
5894     }
5895
5896   inner_args = INNERMOST_TEMPLATE_ARGS (args);
5897   /* If there are 0 or 1 parameter packs, we need to expand any argument
5898      packs so that we can deduce a parameter pack from some non-packed args
5899      followed by an argument pack, as in variadic85.C.  If there are more
5900      than that, we need to leave argument packs intact so the arguments are
5901      assigned to the right parameter packs.  This should only happen when
5902      dealing with a nested class inside a partial specialization of a class
5903      template, as in variadic92.C.  */
5904   if (variadic_p <= 1)
5905     inner_args = expand_template_argument_pack (inner_args);
5906
5907   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5908   if ((nargs > nparms && !variadic_p)
5909       || (nargs < nparms - variadic_p
5910           && require_all_args
5911           && (!use_default_args
5912               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
5913                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
5914     {
5915       if (complain & tf_error)
5916         {
5917           const char *or_more = "";
5918           if (variadic_p)
5919             {
5920               or_more = " or more";
5921               --nparms;
5922             }
5923
5924           error ("wrong number of template arguments (%d, should be %d%s)",
5925                  nargs, nparms, or_more);
5926
5927           if (in_decl)
5928             error ("provided for %q+D", in_decl);
5929         }
5930
5931       return error_mark_node;
5932     }
5933
5934   /* We need to evaluate the template arguments, even though this
5935      template-id may be nested within a "sizeof".  */
5936   saved_unevaluated_operand = cp_unevaluated_operand;
5937   cp_unevaluated_operand = 0;
5938   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
5939   c_inhibit_evaluation_warnings = 0;
5940   new_inner_args = make_tree_vec (nparms);
5941   new_args = add_outermost_template_args (args, new_inner_args);
5942   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
5943     {
5944       tree arg;
5945       tree parm;
5946
5947       /* Get the Ith template parameter.  */
5948       parm = TREE_VEC_ELT (parms, parm_idx);
5949  
5950       if (parm == error_mark_node)
5951       {
5952         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
5953         continue;
5954       }
5955
5956       /* Calculate the next argument.  */
5957       if (arg_idx < nargs)
5958         arg = TREE_VEC_ELT (inner_args, arg_idx);
5959       else
5960         arg = NULL_TREE;
5961
5962       if (template_parameter_pack_p (TREE_VALUE (parm))
5963           && !(arg && ARGUMENT_PACK_P (arg)))
5964         {
5965           /* All remaining arguments will be placed in the
5966              template parameter pack PARM.  */
5967           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
5968                                                 inner_args, arg_idx,
5969                                                 new_args, &lost,
5970                                                 in_decl, complain);
5971
5972           /* Store this argument.  */
5973           if (arg == error_mark_node)
5974             lost++;
5975           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
5976
5977           /* We are done with all of the arguments.  */
5978           arg_idx = nargs;
5979           
5980           continue;
5981         }
5982       else if (arg)
5983         {
5984           if (PACK_EXPANSION_P (arg))
5985             {
5986               if (complain & tf_error)
5987                 {
5988                   /* FIXME this restriction was removed by N2555; see
5989                      bug 35722.  */
5990                   /* If ARG is a pack expansion, but PARM is not a
5991                      template parameter pack (if it were, we would have
5992                      handled it above), we're trying to expand into a
5993                      fixed-length argument list.  */
5994                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5995                     sorry ("cannot expand %<%E%> into a fixed-length "
5996                            "argument list", arg);
5997                   else
5998                     sorry ("cannot expand %<%T%> into a fixed-length "
5999                            "argument list", arg);
6000                 }
6001               return error_mark_node;
6002             }
6003         }
6004       else if (require_all_args)
6005         {
6006           /* There must be a default arg in this case.  */
6007           arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
6008                                      complain, in_decl);
6009           /* The position of the first default template argument,
6010              is also the number of non-defaulted arguments in NEW_INNER_ARGS.
6011              Record that.  */
6012           if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6013             SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args, arg_idx);
6014         }
6015       else
6016         break;
6017
6018       if (arg == error_mark_node)
6019         {
6020           if (complain & tf_error)
6021             error ("template argument %d is invalid", arg_idx + 1);
6022         }
6023       else if (!arg)
6024         /* This only occurs if there was an error in the template
6025            parameter list itself (which we would already have
6026            reported) that we are trying to recover from, e.g., a class
6027            template with a parameter list such as
6028            template<typename..., typename>.  */
6029         return error_mark_node;
6030       else
6031         arg = convert_template_argument (TREE_VALUE (parm),
6032                                          arg, new_args, complain, 
6033                                          parm_idx, in_decl);
6034
6035       if (arg == error_mark_node)
6036         lost++;
6037       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
6038     }
6039   cp_unevaluated_operand = saved_unevaluated_operand;
6040   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
6041
6042   if (lost)
6043     return error_mark_node;
6044
6045 #ifdef ENABLE_CHECKING
6046   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6047     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
6048                                          TREE_VEC_LENGTH (new_inner_args));
6049 #endif
6050
6051   return new_inner_args;
6052 }
6053
6054 /* Returns 1 if template args OT and NT are equivalent.  */
6055
6056 static int
6057 template_args_equal (tree ot, tree nt)
6058 {
6059   if (nt == ot)
6060     return 1;
6061
6062   if (TREE_CODE (nt) == TREE_VEC)
6063     /* For member templates */
6064     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
6065   else if (PACK_EXPANSION_P (ot))
6066     return PACK_EXPANSION_P (nt) 
6067       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
6068                               PACK_EXPANSION_PATTERN (nt));
6069   else if (ARGUMENT_PACK_P (ot))
6070     {
6071       int i, len;
6072       tree opack, npack;
6073
6074       if (!ARGUMENT_PACK_P (nt))
6075         return 0;
6076
6077       opack = ARGUMENT_PACK_ARGS (ot);
6078       npack = ARGUMENT_PACK_ARGS (nt);
6079       len = TREE_VEC_LENGTH (opack);
6080       if (TREE_VEC_LENGTH (npack) != len)
6081         return 0;
6082       for (i = 0; i < len; ++i)
6083         if (!template_args_equal (TREE_VEC_ELT (opack, i),
6084                                   TREE_VEC_ELT (npack, i)))
6085           return 0;
6086       return 1;
6087     }
6088   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
6089     {
6090       /* We get here probably because we are in the middle of substituting
6091          into the pattern of a pack expansion. In that case the
6092          ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
6093          interested in. So we want to use the initial pack argument for
6094          the comparison.  */
6095       ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
6096       if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
6097         nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
6098       return template_args_equal (ot, nt);
6099     }
6100   else if (TYPE_P (nt))
6101     return TYPE_P (ot) && same_type_p (ot, nt);
6102   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
6103     return 0;
6104   else
6105     return cp_tree_equal (ot, nt);
6106 }
6107
6108 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
6109    of template arguments.  Returns 0 otherwise.  */
6110
6111 int
6112 comp_template_args (tree oldargs, tree newargs)
6113 {
6114   int i;
6115
6116   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
6117     return 0;
6118
6119   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
6120     {
6121       tree nt = TREE_VEC_ELT (newargs, i);
6122       tree ot = TREE_VEC_ELT (oldargs, i);
6123
6124       if (! template_args_equal (ot, nt))
6125         return 0;
6126     }
6127   return 1;
6128 }
6129
6130 static void
6131 add_pending_template (tree d)
6132 {
6133   tree ti = (TYPE_P (d)
6134              ? CLASSTYPE_TEMPLATE_INFO (d)
6135              : DECL_TEMPLATE_INFO (d));
6136   struct pending_template *pt;
6137   int level;
6138
6139   if (TI_PENDING_TEMPLATE_FLAG (ti))
6140     return;
6141
6142   /* We are called both from instantiate_decl, where we've already had a
6143      tinst_level pushed, and instantiate_template, where we haven't.
6144      Compensate.  */
6145   level = !current_tinst_level || current_tinst_level->decl != d;
6146
6147   if (level)
6148     push_tinst_level (d);
6149
6150   pt = GGC_NEW (struct pending_template);
6151   pt->next = NULL;
6152   pt->tinst = current_tinst_level;
6153   if (last_pending_template)
6154     last_pending_template->next = pt;
6155   else
6156     pending_templates = pt;
6157
6158   last_pending_template = pt;
6159
6160   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
6161
6162   if (level)
6163     pop_tinst_level ();
6164 }
6165
6166
6167 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
6168    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
6169    documentation for TEMPLATE_ID_EXPR.  */
6170
6171 tree
6172 lookup_template_function (tree fns, tree arglist)
6173 {
6174   tree type;
6175
6176   if (fns == error_mark_node || arglist == error_mark_node)
6177     return error_mark_node;
6178
6179   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
6180   gcc_assert (fns && (is_overloaded_fn (fns)
6181                       || TREE_CODE (fns) == IDENTIFIER_NODE));
6182
6183   if (BASELINK_P (fns))
6184     {
6185       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
6186                                          unknown_type_node,
6187                                          BASELINK_FUNCTIONS (fns),
6188                                          arglist);
6189       return fns;
6190     }
6191
6192   type = TREE_TYPE (fns);
6193   if (TREE_CODE (fns) == OVERLOAD || !type)
6194     type = unknown_type_node;
6195
6196   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
6197 }
6198
6199 /* Within the scope of a template class S<T>, the name S gets bound
6200    (in build_self_reference) to a TYPE_DECL for the class, not a
6201    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
6202    or one of its enclosing classes, and that type is a template,
6203    return the associated TEMPLATE_DECL.  Otherwise, the original
6204    DECL is returned.
6205
6206    Also handle the case when DECL is a TREE_LIST of ambiguous
6207    injected-class-names from different bases.  */
6208
6209 tree
6210 maybe_get_template_decl_from_type_decl (tree decl)
6211 {
6212   if (decl == NULL_TREE)
6213     return decl;
6214
6215   /* DR 176: A lookup that finds an injected-class-name (10.2
6216      [class.member.lookup]) can result in an ambiguity in certain cases
6217      (for example, if it is found in more than one base class). If all of
6218      the injected-class-names that are found refer to specializations of
6219      the same class template, and if the name is followed by a
6220      template-argument-list, the reference refers to the class template
6221      itself and not a specialization thereof, and is not ambiguous.  */
6222   if (TREE_CODE (decl) == TREE_LIST)
6223     {
6224       tree t, tmpl = NULL_TREE;
6225       for (t = decl; t; t = TREE_CHAIN (t))
6226         {
6227           tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
6228           if (!tmpl)
6229             tmpl = elt;
6230           else if (tmpl != elt)
6231             break;
6232         }
6233       if (tmpl && t == NULL_TREE)
6234         return tmpl;
6235       else
6236         return decl;
6237     }
6238
6239   return (decl != NULL_TREE
6240           && DECL_SELF_REFERENCE_P (decl)
6241           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
6242     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
6243 }
6244
6245 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
6246    parameters, find the desired type.
6247
6248    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
6249
6250    IN_DECL, if non-NULL, is the template declaration we are trying to
6251    instantiate.
6252
6253    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
6254    the class we are looking up.
6255
6256    Issue error and warning messages under control of COMPLAIN.
6257
6258    If the template class is really a local class in a template
6259    function, then the FUNCTION_CONTEXT is the function in which it is
6260    being instantiated.
6261
6262    ??? Note that this function is currently called *twice* for each
6263    template-id: the first time from the parser, while creating the
6264    incomplete type (finish_template_type), and the second type during the
6265    real instantiation (instantiate_template_class). This is surely something
6266    that we want to avoid. It also causes some problems with argument
6267    coercion (see convert_nontype_argument for more information on this).  */
6268
6269 tree
6270 lookup_template_class (tree d1,
6271                        tree arglist,
6272                        tree in_decl,
6273                        tree context,
6274                        int entering_scope,
6275                        tsubst_flags_t complain)
6276 {
6277   tree templ = NULL_TREE, parmlist;
6278   tree t;
6279   spec_entry **slot;
6280   spec_entry *entry;
6281   spec_entry elt;
6282   hashval_t hash;
6283
6284   timevar_push (TV_NAME_LOOKUP);
6285
6286   if (TREE_CODE (d1) == IDENTIFIER_NODE)
6287     {
6288       tree value = innermost_non_namespace_value (d1);
6289       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
6290         templ = value;
6291       else
6292         {
6293           if (context)
6294             push_decl_namespace (context);
6295           templ = lookup_name (d1);
6296           templ = maybe_get_template_decl_from_type_decl (templ);
6297           if (context)
6298             pop_decl_namespace ();
6299         }
6300       if (templ)
6301         context = DECL_CONTEXT (templ);
6302     }
6303   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
6304     {
6305       tree type = TREE_TYPE (d1);
6306
6307       /* If we are declaring a constructor, say A<T>::A<T>, we will get
6308          an implicit typename for the second A.  Deal with it.  */
6309       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
6310         type = TREE_TYPE (type);
6311
6312       if (CLASSTYPE_TEMPLATE_INFO (type))
6313         {
6314           templ = CLASSTYPE_TI_TEMPLATE (type);
6315           d1 = DECL_NAME (templ);
6316         }
6317     }
6318   else if (TREE_CODE (d1) == ENUMERAL_TYPE
6319            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
6320     {
6321       templ = TYPE_TI_TEMPLATE (d1);
6322       d1 = DECL_NAME (templ);
6323     }
6324   else if (TREE_CODE (d1) == TEMPLATE_DECL
6325            && DECL_TEMPLATE_RESULT (d1)
6326            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
6327     {
6328       templ = d1;
6329       d1 = DECL_NAME (templ);
6330       context = DECL_CONTEXT (templ);
6331     }
6332
6333   /* Issue an error message if we didn't find a template.  */
6334   if (! templ)
6335     {
6336       if (complain & tf_error)
6337         error ("%qT is not a template", d1);
6338       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6339     }
6340
6341   if (TREE_CODE (templ) != TEMPLATE_DECL
6342          /* Make sure it's a user visible template, if it was named by
6343             the user.  */
6344       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
6345           && !PRIMARY_TEMPLATE_P (templ)))
6346     {
6347       if (complain & tf_error)
6348         {
6349           error ("non-template type %qT used as a template", d1);
6350           if (in_decl)
6351             error ("for template declaration %q+D", in_decl);
6352         }
6353       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6354     }
6355
6356   complain &= ~tf_user;
6357
6358   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
6359     {
6360       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
6361          template arguments */
6362
6363       tree parm;
6364       tree arglist2;
6365       tree outer;
6366
6367       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
6368
6369       /* Consider an example where a template template parameter declared as
6370
6371            template <class T, class U = std::allocator<T> > class TT
6372
6373          The template parameter level of T and U are one level larger than
6374          of TT.  To proper process the default argument of U, say when an
6375          instantiation `TT<int>' is seen, we need to build the full
6376          arguments containing {int} as the innermost level.  Outer levels,
6377          available when not appearing as default template argument, can be
6378          obtained from the arguments of the enclosing template.
6379
6380          Suppose that TT is later substituted with std::vector.  The above
6381          instantiation is `TT<int, std::allocator<T> >' with TT at
6382          level 1, and T at level 2, while the template arguments at level 1
6383          becomes {std::vector} and the inner level 2 is {int}.  */
6384
6385       outer = DECL_CONTEXT (templ);
6386       if (outer)
6387         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
6388       else if (current_template_parms)
6389         /* This is an argument of the current template, so we haven't set
6390            DECL_CONTEXT yet.  */
6391         outer = current_template_args ();
6392
6393       if (outer)
6394         arglist = add_to_template_args (outer, arglist);
6395
6396       arglist2 = coerce_template_parms (parmlist, arglist, templ,
6397                                         complain,
6398                                         /*require_all_args=*/true,
6399                                         /*use_default_args=*/true);
6400       if (arglist2 == error_mark_node
6401           || (!uses_template_parms (arglist2)
6402               && check_instantiated_args (templ, arglist2, complain)))
6403         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6404
6405       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
6406       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
6407     }
6408   else
6409     {
6410       tree template_type = TREE_TYPE (templ);
6411       tree gen_tmpl;
6412       tree type_decl;
6413       tree found = NULL_TREE;
6414       int arg_depth;
6415       int parm_depth;
6416       int is_dependent_type;
6417       int use_partial_inst_tmpl = false;
6418
6419       gen_tmpl = most_general_template (templ);
6420       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
6421       parm_depth = TMPL_PARMS_DEPTH (parmlist);
6422       arg_depth = TMPL_ARGS_DEPTH (arglist);
6423
6424       if (arg_depth == 1 && parm_depth > 1)
6425         {
6426           /* We've been given an incomplete set of template arguments.
6427              For example, given:
6428
6429                template <class T> struct S1 {
6430                  template <class U> struct S2 {};
6431                  template <class U> struct S2<U*> {};
6432                 };
6433
6434              we will be called with an ARGLIST of `U*', but the
6435              TEMPLATE will be `template <class T> template
6436              <class U> struct S1<T>::S2'.  We must fill in the missing
6437              arguments.  */
6438           arglist
6439             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
6440                                            arglist);
6441           arg_depth = TMPL_ARGS_DEPTH (arglist);
6442         }
6443
6444       /* Now we should have enough arguments.  */
6445       gcc_assert (parm_depth == arg_depth);
6446
6447       /* From here on, we're only interested in the most general
6448          template.  */
6449
6450       /* Calculate the BOUND_ARGS.  These will be the args that are
6451          actually tsubst'd into the definition to create the
6452          instantiation.  */
6453       if (parm_depth > 1)
6454         {
6455           /* We have multiple levels of arguments to coerce, at once.  */
6456           int i;
6457           int saved_depth = TMPL_ARGS_DEPTH (arglist);
6458
6459           tree bound_args = make_tree_vec (parm_depth);
6460
6461           for (i = saved_depth,
6462                  t = DECL_TEMPLATE_PARMS (gen_tmpl);
6463                i > 0 && t != NULL_TREE;
6464                --i, t = TREE_CHAIN (t))
6465             {
6466               tree a = coerce_template_parms (TREE_VALUE (t),
6467                                               arglist, gen_tmpl,
6468                                               complain,
6469                                               /*require_all_args=*/true,
6470                                               /*use_default_args=*/true);
6471
6472               /* Don't process further if one of the levels fails.  */
6473               if (a == error_mark_node)
6474                 {
6475                   /* Restore the ARGLIST to its full size.  */
6476                   TREE_VEC_LENGTH (arglist) = saved_depth;
6477                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6478                 }
6479
6480               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
6481
6482               /* We temporarily reduce the length of the ARGLIST so
6483                  that coerce_template_parms will see only the arguments
6484                  corresponding to the template parameters it is
6485                  examining.  */
6486               TREE_VEC_LENGTH (arglist)--;
6487             }
6488
6489           /* Restore the ARGLIST to its full size.  */
6490           TREE_VEC_LENGTH (arglist) = saved_depth;
6491
6492           arglist = bound_args;
6493         }
6494       else
6495         arglist
6496           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
6497                                    INNERMOST_TEMPLATE_ARGS (arglist),
6498                                    gen_tmpl,
6499                                    complain,
6500                                    /*require_all_args=*/true,
6501                                    /*use_default_args=*/true);
6502
6503       if (arglist == error_mark_node)
6504         /* We were unable to bind the arguments.  */
6505         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6506
6507       /* In the scope of a template class, explicit references to the
6508          template class refer to the type of the template, not any
6509          instantiation of it.  For example, in:
6510
6511            template <class T> class C { void f(C<T>); }
6512
6513          the `C<T>' is just the same as `C'.  Outside of the
6514          class, however, such a reference is an instantiation.  */
6515       if ((entering_scope
6516            || !PRIMARY_TEMPLATE_P (gen_tmpl)
6517            || currently_open_class (template_type))
6518           /* comp_template_args is expensive, check it last.  */
6519           && comp_template_args (TYPE_TI_ARGS (template_type),
6520                                  arglist))
6521         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, template_type);
6522
6523       /* If we already have this specialization, return it.  */
6524       elt.tmpl = gen_tmpl;
6525       elt.args = arglist;
6526       hash = hash_specialization (&elt);
6527       entry = (spec_entry *) htab_find_with_hash (type_specializations,
6528                                                   &elt, hash);
6529
6530       if (entry)
6531         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, entry->spec);
6532
6533       is_dependent_type = uses_template_parms (arglist);
6534
6535       /* If the deduced arguments are invalid, then the binding
6536          failed.  */
6537       if (!is_dependent_type
6538           && check_instantiated_args (gen_tmpl,
6539                                       INNERMOST_TEMPLATE_ARGS (arglist),
6540                                       complain))
6541         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6542
6543       if (!is_dependent_type
6544           && !PRIMARY_TEMPLATE_P (gen_tmpl)
6545           && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
6546           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
6547         {
6548           found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
6549                                       DECL_NAME (gen_tmpl),
6550                                       /*tag_scope=*/ts_global);
6551           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
6552         }
6553
6554       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
6555                         complain, in_decl);
6556       if (!context)
6557         context = global_namespace;
6558
6559       /* Create the type.  */
6560       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
6561         {
6562           if (!is_dependent_type)
6563             {
6564               set_current_access_from_decl (TYPE_NAME (template_type));
6565               t = start_enum (TYPE_IDENTIFIER (template_type),
6566                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
6567                                       arglist, complain, in_decl),
6568                               SCOPED_ENUM_P (template_type));
6569             }
6570           else
6571             {
6572               /* We don't want to call start_enum for this type, since
6573                  the values for the enumeration constants may involve
6574                  template parameters.  And, no one should be interested
6575                  in the enumeration constants for such a type.  */
6576               t = cxx_make_type (ENUMERAL_TYPE);
6577               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
6578             }
6579         }
6580       else
6581         {
6582           t = make_class_type (TREE_CODE (template_type));
6583           CLASSTYPE_DECLARED_CLASS (t)
6584             = CLASSTYPE_DECLARED_CLASS (template_type);
6585           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
6586           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
6587
6588           /* A local class.  Make sure the decl gets registered properly.  */
6589           if (context == current_function_decl)
6590             pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
6591
6592           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
6593             /* This instantiation is another name for the primary
6594                template type. Set the TYPE_CANONICAL field
6595                appropriately. */
6596             TYPE_CANONICAL (t) = template_type;
6597           else if (any_template_arguments_need_structural_equality_p (arglist))
6598             /* Some of the template arguments require structural
6599                equality testing, so this template class requires
6600                structural equality testing. */
6601             SET_TYPE_STRUCTURAL_EQUALITY (t);
6602         }
6603
6604       /* If we called start_enum or pushtag above, this information
6605          will already be set up.  */
6606       if (!TYPE_NAME (t))
6607         {
6608           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
6609
6610           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
6611           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
6612           DECL_SOURCE_LOCATION (type_decl)
6613             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
6614         }
6615       else
6616         type_decl = TYPE_NAME (t);
6617
6618       TREE_PRIVATE (type_decl)
6619         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
6620       TREE_PROTECTED (type_decl)
6621         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
6622       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
6623         {
6624           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
6625           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
6626         }
6627
6628       /* Let's consider the explicit specialization of a member
6629          of a class template specialization that is implicitely instantiated,
6630          e.g.:
6631              template<class T>
6632              struct S
6633              {
6634                template<class U> struct M {}; //#0
6635              };
6636
6637              template<>
6638              template<>
6639              struct S<int>::M<char> //#1
6640              {
6641                int i;
6642              };
6643         [temp.expl.spec]/4 says this is valid.
6644
6645         In this case, when we write:
6646         S<int>::M<char> m;
6647
6648         M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
6649         the one of #0.
6650
6651         When we encounter #1, we want to store the partial instantiation
6652         of M (template<class T> S<int>::M<T>) in it's CLASSTYPE_TI_TEMPLATE.
6653
6654         For all cases other than this "explicit specialization of member of a
6655         class template", we just want to store the most general template into
6656         the CLASSTYPE_TI_TEMPLATE of M.
6657
6658         This case of "explicit specialization of member of a class template"
6659         only happens when:
6660         1/ the enclosing class is an instantiation of, and therefore not
6661         the same as, the context of the most general template, and
6662         2/ we aren't looking at the partial instantiation itself, i.e.
6663         the innermost arguments are not the same as the innermost parms of
6664         the most general template.
6665
6666         So it's only when 1/ and 2/ happens that we want to use the partial
6667         instantiation of the member template in lieu of its most general
6668         template.  */
6669
6670       if (PRIMARY_TEMPLATE_P (gen_tmpl)
6671           && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
6672           /* the enclosing class must be an instantiation...  */
6673           && CLASS_TYPE_P (context)
6674           && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
6675         {
6676           tree partial_inst_args;
6677           TREE_VEC_LENGTH (arglist)--;
6678           ++processing_template_decl;
6679           partial_inst_args =
6680             tsubst (INNERMOST_TEMPLATE_ARGS
6681                         (CLASSTYPE_TI_ARGS (TREE_TYPE (gen_tmpl))),
6682                     arglist, complain, NULL_TREE);
6683           --processing_template_decl;
6684           TREE_VEC_LENGTH (arglist)++;
6685           use_partial_inst_tmpl =
6686             /*...and we must not be looking at the partial instantiation
6687              itself. */
6688             !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
6689                                  partial_inst_args);
6690         }
6691
6692       if (!use_partial_inst_tmpl)
6693         /* This case is easy; there are no member templates involved.  */
6694         found = gen_tmpl;
6695       else
6696         {
6697           /* This is a full instantiation of a member template.  Find
6698              the partial instantiation of which this is an instance.  */
6699
6700           /* Temporarily reduce by one the number of levels in the ARGLIST
6701              so as to avoid comparing the last set of arguments.  */
6702           TREE_VEC_LENGTH (arglist)--;
6703           found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
6704           TREE_VEC_LENGTH (arglist)++;
6705           found = CLASSTYPE_TI_TEMPLATE (found);
6706         }
6707
6708       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
6709
6710       elt.spec = t;
6711       slot = (spec_entry **) htab_find_slot_with_hash (type_specializations,
6712                                                        &elt, hash, INSERT);
6713       *slot = GGC_NEW (spec_entry);
6714       **slot = elt;
6715
6716       /* Note this use of the partial instantiation so we can check it
6717          later in maybe_process_partial_specialization.  */
6718       DECL_TEMPLATE_INSTANTIATIONS (templ)
6719         = tree_cons (arglist, t,
6720                      DECL_TEMPLATE_INSTANTIATIONS (templ));
6721
6722       if (TREE_CODE (t) == ENUMERAL_TYPE && !is_dependent_type)
6723         /* Now that the type has been registered on the instantiations
6724            list, we set up the enumerators.  Because the enumeration
6725            constants may involve the enumeration type itself, we make
6726            sure to register the type first, and then create the
6727            constants.  That way, doing tsubst_expr for the enumeration
6728            constants won't result in recursive calls here; we'll find
6729            the instantiation and exit above.  */
6730         tsubst_enum (template_type, t, arglist);
6731
6732       if (is_dependent_type)
6733         /* If the type makes use of template parameters, the
6734            code that generates debugging information will crash.  */
6735         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
6736
6737       /* Possibly limit visibility based on template args.  */
6738       TREE_PUBLIC (type_decl) = 1;
6739       determine_visibility (type_decl);
6740
6741       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
6742     }
6743   timevar_pop (TV_NAME_LOOKUP);
6744 }
6745 \f
6746 struct pair_fn_data
6747 {
6748   tree_fn_t fn;
6749   void *data;
6750   /* True when we should also visit template parameters that occur in
6751      non-deduced contexts.  */
6752   bool include_nondeduced_p;
6753   struct pointer_set_t *visited;
6754 };
6755
6756 /* Called from for_each_template_parm via walk_tree.  */
6757
6758 static tree
6759 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
6760 {
6761   tree t = *tp;
6762   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
6763   tree_fn_t fn = pfd->fn;
6764   void *data = pfd->data;
6765
6766   if (TYPE_P (t)
6767       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
6768       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
6769                                  pfd->include_nondeduced_p))
6770     return error_mark_node;
6771
6772   switch (TREE_CODE (t))
6773     {
6774     case RECORD_TYPE:
6775       if (TYPE_PTRMEMFUNC_P (t))
6776         break;
6777       /* Fall through.  */
6778
6779     case UNION_TYPE:
6780     case ENUMERAL_TYPE:
6781       if (!TYPE_TEMPLATE_INFO (t))
6782         *walk_subtrees = 0;
6783       else if (for_each_template_parm (TI_ARGS (TYPE_TEMPLATE_INFO (t)),
6784                                        fn, data, pfd->visited, 
6785                                        pfd->include_nondeduced_p))
6786         return error_mark_node;
6787       break;
6788
6789     case INTEGER_TYPE:
6790       if (for_each_template_parm (TYPE_MIN_VALUE (t),
6791                                   fn, data, pfd->visited, 
6792                                   pfd->include_nondeduced_p)
6793           || for_each_template_parm (TYPE_MAX_VALUE (t),
6794                                      fn, data, pfd->visited,
6795                                      pfd->include_nondeduced_p))
6796         return error_mark_node;
6797       break;
6798
6799     case METHOD_TYPE:
6800       /* Since we're not going to walk subtrees, we have to do this
6801          explicitly here.  */
6802       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
6803                                   pfd->visited, pfd->include_nondeduced_p))
6804         return error_mark_node;
6805       /* Fall through.  */
6806
6807     case FUNCTION_TYPE:
6808       /* Check the return type.  */
6809       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6810                                   pfd->include_nondeduced_p))
6811         return error_mark_node;
6812
6813       /* Check the parameter types.  Since default arguments are not
6814          instantiated until they are needed, the TYPE_ARG_TYPES may
6815          contain expressions that involve template parameters.  But,
6816          no-one should be looking at them yet.  And, once they're
6817          instantiated, they don't contain template parameters, so
6818          there's no point in looking at them then, either.  */
6819       {
6820         tree parm;
6821
6822         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
6823           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
6824                                       pfd->visited, pfd->include_nondeduced_p))
6825             return error_mark_node;
6826
6827         /* Since we've already handled the TYPE_ARG_TYPES, we don't
6828            want walk_tree walking into them itself.  */
6829         *walk_subtrees = 0;
6830       }
6831       break;
6832
6833     case TYPEOF_TYPE:
6834       if (pfd->include_nondeduced_p
6835           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
6836                                      pfd->visited, 
6837                                      pfd->include_nondeduced_p))
6838         return error_mark_node;
6839       break;
6840
6841     case FUNCTION_DECL:
6842     case VAR_DECL:
6843       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
6844           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
6845                                      pfd->visited, pfd->include_nondeduced_p))
6846         return error_mark_node;
6847       /* Fall through.  */
6848
6849     case PARM_DECL:
6850     case CONST_DECL:
6851       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
6852           && for_each_template_parm (DECL_INITIAL (t), fn, data,
6853                                      pfd->visited, pfd->include_nondeduced_p))
6854         return error_mark_node;
6855       if (DECL_CONTEXT (t)
6856           && pfd->include_nondeduced_p
6857           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
6858                                      pfd->visited, pfd->include_nondeduced_p))
6859         return error_mark_node;
6860       break;
6861
6862     case BOUND_TEMPLATE_TEMPLATE_PARM:
6863       /* Record template parameters such as `T' inside `TT<T>'.  */
6864       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
6865                                   pfd->include_nondeduced_p))
6866         return error_mark_node;
6867       /* Fall through.  */
6868
6869     case TEMPLATE_TEMPLATE_PARM:
6870     case TEMPLATE_TYPE_PARM:
6871     case TEMPLATE_PARM_INDEX:
6872       if (fn && (*fn)(t, data))
6873         return error_mark_node;
6874       else if (!fn)
6875         return error_mark_node;
6876       break;
6877
6878     case TEMPLATE_DECL:
6879       /* A template template parameter is encountered.  */
6880       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
6881           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6882                                      pfd->include_nondeduced_p))
6883         return error_mark_node;
6884
6885       /* Already substituted template template parameter */
6886       *walk_subtrees = 0;
6887       break;
6888
6889     case TYPENAME_TYPE:
6890       if (!fn
6891           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
6892                                      data, pfd->visited, 
6893                                      pfd->include_nondeduced_p))
6894         return error_mark_node;
6895       break;
6896
6897     case CONSTRUCTOR:
6898       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
6899           && pfd->include_nondeduced_p
6900           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
6901                                      (TREE_TYPE (t)), fn, data,
6902                                      pfd->visited, pfd->include_nondeduced_p))
6903         return error_mark_node;
6904       break;
6905
6906     case INDIRECT_REF:
6907     case COMPONENT_REF:
6908       /* If there's no type, then this thing must be some expression
6909          involving template parameters.  */
6910       if (!fn && !TREE_TYPE (t))
6911         return error_mark_node;
6912       break;
6913
6914     case MODOP_EXPR:
6915     case CAST_EXPR:
6916     case REINTERPRET_CAST_EXPR:
6917     case CONST_CAST_EXPR:
6918     case STATIC_CAST_EXPR:
6919     case DYNAMIC_CAST_EXPR:
6920     case ARROW_EXPR:
6921     case DOTSTAR_EXPR:
6922     case TYPEID_EXPR:
6923     case PSEUDO_DTOR_EXPR:
6924       if (!fn)
6925         return error_mark_node;
6926       break;
6927
6928     default:
6929       break;
6930     }
6931
6932   /* We didn't find any template parameters we liked.  */
6933   return NULL_TREE;
6934 }
6935
6936 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
6937    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
6938    call FN with the parameter and the DATA.
6939    If FN returns nonzero, the iteration is terminated, and
6940    for_each_template_parm returns 1.  Otherwise, the iteration
6941    continues.  If FN never returns a nonzero value, the value
6942    returned by for_each_template_parm is 0.  If FN is NULL, it is
6943    considered to be the function which always returns 1.
6944
6945    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
6946    parameters that occur in non-deduced contexts.  When false, only
6947    visits those template parameters that can be deduced.  */
6948
6949 static int
6950 for_each_template_parm (tree t, tree_fn_t fn, void* data,
6951                         struct pointer_set_t *visited,
6952                         bool include_nondeduced_p)
6953 {
6954   struct pair_fn_data pfd;
6955   int result;
6956
6957   /* Set up.  */
6958   pfd.fn = fn;
6959   pfd.data = data;
6960   pfd.include_nondeduced_p = include_nondeduced_p;
6961
6962   /* Walk the tree.  (Conceptually, we would like to walk without
6963      duplicates, but for_each_template_parm_r recursively calls
6964      for_each_template_parm, so we would need to reorganize a fair
6965      bit to use walk_tree_without_duplicates, so we keep our own
6966      visited list.)  */
6967   if (visited)
6968     pfd.visited = visited;
6969   else
6970     pfd.visited = pointer_set_create ();
6971   result = cp_walk_tree (&t,
6972                          for_each_template_parm_r,
6973                          &pfd,
6974                          pfd.visited) != NULL_TREE;
6975
6976   /* Clean up.  */
6977   if (!visited)
6978     {
6979       pointer_set_destroy (pfd.visited);
6980       pfd.visited = 0;
6981     }
6982
6983   return result;
6984 }
6985
6986 /* Returns true if T depends on any template parameter.  */
6987
6988 int
6989 uses_template_parms (tree t)
6990 {
6991   bool dependent_p;
6992   int saved_processing_template_decl;
6993
6994   saved_processing_template_decl = processing_template_decl;
6995   if (!saved_processing_template_decl)
6996     processing_template_decl = 1;
6997   if (TYPE_P (t))
6998     dependent_p = dependent_type_p (t);
6999   else if (TREE_CODE (t) == TREE_VEC)
7000     dependent_p = any_dependent_template_arguments_p (t);
7001   else if (TREE_CODE (t) == TREE_LIST)
7002     dependent_p = (uses_template_parms (TREE_VALUE (t))
7003                    || uses_template_parms (TREE_CHAIN (t)));
7004   else if (TREE_CODE (t) == TYPE_DECL)
7005     dependent_p = dependent_type_p (TREE_TYPE (t));
7006   else if (DECL_P (t)
7007            || EXPR_P (t)
7008            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
7009            || TREE_CODE (t) == OVERLOAD
7010            || TREE_CODE (t) == BASELINK
7011            || TREE_CODE (t) == IDENTIFIER_NODE
7012            || TREE_CODE (t) == TRAIT_EXPR
7013            || TREE_CODE (t) == CONSTRUCTOR
7014            || CONSTANT_CLASS_P (t))
7015     dependent_p = (type_dependent_expression_p (t)
7016                    || value_dependent_expression_p (t));
7017   else
7018     {
7019       gcc_assert (t == error_mark_node);
7020       dependent_p = false;
7021     }
7022
7023   processing_template_decl = saved_processing_template_decl;
7024
7025   return dependent_p;
7026 }
7027
7028 /* Returns true if T depends on any template parameter with level LEVEL.  */
7029
7030 int
7031 uses_template_parms_level (tree t, int level)
7032 {
7033   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
7034                                  /*include_nondeduced_p=*/true);
7035 }
7036
7037 static int tinst_depth;
7038 extern int max_tinst_depth;
7039 #ifdef GATHER_STATISTICS
7040 int depth_reached;
7041 #endif
7042 static int tinst_level_tick;
7043 static int last_template_error_tick;
7044
7045 /* We're starting to instantiate D; record the template instantiation context
7046    for diagnostics and to restore it later.  */
7047
7048 int
7049 push_tinst_level (tree d)
7050 {
7051   struct tinst_level *new_level;
7052
7053   if (tinst_depth >= max_tinst_depth)
7054     {
7055       /* If the instantiation in question still has unbound template parms,
7056          we don't really care if we can't instantiate it, so just return.
7057          This happens with base instantiation for implicit `typename'.  */
7058       if (uses_template_parms (d))
7059         return 0;
7060
7061       last_template_error_tick = tinst_level_tick;
7062       error ("template instantiation depth exceeds maximum of %d (use "
7063              "-ftemplate-depth= to increase the maximum) instantiating %qD",
7064              max_tinst_depth, d);
7065
7066       print_instantiation_context ();
7067
7068       return 0;
7069     }
7070
7071   new_level = GGC_NEW (struct tinst_level);
7072   new_level->decl = d;
7073   new_level->locus = input_location;
7074   new_level->in_system_header_p = in_system_header;
7075   new_level->next = current_tinst_level;
7076   current_tinst_level = new_level;
7077
7078   ++tinst_depth;
7079 #ifdef GATHER_STATISTICS
7080   if (tinst_depth > depth_reached)
7081     depth_reached = tinst_depth;
7082 #endif
7083
7084   ++tinst_level_tick;
7085   return 1;
7086 }
7087
7088 /* We're done instantiating this template; return to the instantiation
7089    context.  */
7090
7091 void
7092 pop_tinst_level (void)
7093 {
7094   /* Restore the filename and line number stashed away when we started
7095      this instantiation.  */
7096   input_location = current_tinst_level->locus;
7097   current_tinst_level = current_tinst_level->next;
7098   --tinst_depth;
7099   ++tinst_level_tick;
7100 }
7101
7102 /* We're instantiating a deferred template; restore the template
7103    instantiation context in which the instantiation was requested, which
7104    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
7105
7106 static tree
7107 reopen_tinst_level (struct tinst_level *level)
7108 {
7109   struct tinst_level *t;
7110
7111   tinst_depth = 0;
7112   for (t = level; t; t = t->next)
7113     ++tinst_depth;
7114
7115   current_tinst_level = level;
7116   pop_tinst_level ();
7117   return level->decl;
7118 }
7119
7120 /* Returns the TINST_LEVEL which gives the original instantiation
7121    context.  */
7122
7123 struct tinst_level *
7124 outermost_tinst_level (void)
7125 {
7126   struct tinst_level *level = current_tinst_level;
7127   if (level)
7128     while (level->next)
7129       level = level->next;
7130   return level;
7131 }
7132
7133 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
7134
7135 bool
7136 parameter_of_template_p (tree parm, tree templ)
7137 {
7138   tree parms;
7139   int i;
7140
7141   if (!parm || !templ)
7142     return false;
7143
7144   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
7145   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7146
7147   parms = DECL_TEMPLATE_PARMS (templ);
7148   parms = INNERMOST_TEMPLATE_PARMS (parms);
7149
7150   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
7151     if (parm == TREE_VALUE (TREE_VEC_ELT (parms, i)))
7152       return true;
7153
7154   return false;
7155 }
7156
7157 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
7158    vector of template arguments, as for tsubst.
7159
7160    Returns an appropriate tsubst'd friend declaration.  */
7161
7162 static tree
7163 tsubst_friend_function (tree decl, tree args)
7164 {
7165   tree new_friend;
7166
7167   if (TREE_CODE (decl) == FUNCTION_DECL
7168       && DECL_TEMPLATE_INSTANTIATION (decl)
7169       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
7170     /* This was a friend declared with an explicit template
7171        argument list, e.g.:
7172
7173        friend void f<>(T);
7174
7175        to indicate that f was a template instantiation, not a new
7176        function declaration.  Now, we have to figure out what
7177        instantiation of what template.  */
7178     {
7179       tree template_id, arglist, fns;
7180       tree new_args;
7181       tree tmpl;
7182       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
7183
7184       /* Friend functions are looked up in the containing namespace scope.
7185          We must enter that scope, to avoid finding member functions of the
7186          current class with same name.  */
7187       push_nested_namespace (ns);
7188       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
7189                          tf_warning_or_error, NULL_TREE,
7190                          /*integral_constant_expression_p=*/false);
7191       pop_nested_namespace (ns);
7192       arglist = tsubst (DECL_TI_ARGS (decl), args,
7193                         tf_warning_or_error, NULL_TREE);
7194       template_id = lookup_template_function (fns, arglist);
7195
7196       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7197       tmpl = determine_specialization (template_id, new_friend,
7198                                        &new_args,
7199                                        /*need_member_template=*/0,
7200                                        TREE_VEC_LENGTH (args),
7201                                        tsk_none);
7202       return instantiate_template (tmpl, new_args, tf_error);
7203     }
7204
7205   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7206
7207   /* The NEW_FRIEND will look like an instantiation, to the
7208      compiler, but is not an instantiation from the point of view of
7209      the language.  For example, we might have had:
7210
7211      template <class T> struct S {
7212        template <class U> friend void f(T, U);
7213      };
7214
7215      Then, in S<int>, template <class U> void f(int, U) is not an
7216      instantiation of anything.  */
7217   if (new_friend == error_mark_node)
7218     return error_mark_node;
7219
7220   DECL_USE_TEMPLATE (new_friend) = 0;
7221   if (TREE_CODE (decl) == TEMPLATE_DECL)
7222     {
7223       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
7224       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
7225         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
7226     }
7227
7228   /* The mangled name for the NEW_FRIEND is incorrect.  The function
7229      is not a template instantiation and should not be mangled like
7230      one.  Therefore, we forget the mangling here; we'll recompute it
7231      later if we need it.  */
7232   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
7233     {
7234       SET_DECL_RTL (new_friend, NULL_RTX);
7235       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
7236     }
7237
7238   if (DECL_NAMESPACE_SCOPE_P (new_friend))
7239     {
7240       tree old_decl;
7241       tree new_friend_template_info;
7242       tree new_friend_result_template_info;
7243       tree ns;
7244       int  new_friend_is_defn;
7245
7246       /* We must save some information from NEW_FRIEND before calling
7247          duplicate decls since that function will free NEW_FRIEND if
7248          possible.  */
7249       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
7250       new_friend_is_defn =
7251             (DECL_INITIAL (DECL_TEMPLATE_RESULT
7252                            (template_for_substitution (new_friend)))
7253              != NULL_TREE);
7254       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
7255         {
7256           /* This declaration is a `primary' template.  */
7257           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
7258
7259           new_friend_result_template_info
7260             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
7261         }
7262       else
7263         new_friend_result_template_info = NULL_TREE;
7264
7265       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
7266       if (new_friend_is_defn)
7267         DECL_INITIAL (new_friend) = error_mark_node;
7268
7269       /* Inside pushdecl_namespace_level, we will push into the
7270          current namespace. However, the friend function should go
7271          into the namespace of the template.  */
7272       ns = decl_namespace_context (new_friend);
7273       push_nested_namespace (ns);
7274       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
7275       pop_nested_namespace (ns);
7276
7277       if (old_decl == error_mark_node)
7278         return error_mark_node;
7279
7280       if (old_decl != new_friend)
7281         {
7282           /* This new friend declaration matched an existing
7283              declaration.  For example, given:
7284
7285                template <class T> void f(T);
7286                template <class U> class C {
7287                  template <class T> friend void f(T) {}
7288                };
7289
7290              the friend declaration actually provides the definition
7291              of `f', once C has been instantiated for some type.  So,
7292              old_decl will be the out-of-class template declaration,
7293              while new_friend is the in-class definition.
7294
7295              But, if `f' was called before this point, the
7296              instantiation of `f' will have DECL_TI_ARGS corresponding
7297              to `T' but not to `U', references to which might appear
7298              in the definition of `f'.  Previously, the most general
7299              template for an instantiation of `f' was the out-of-class
7300              version; now it is the in-class version.  Therefore, we
7301              run through all specialization of `f', adding to their
7302              DECL_TI_ARGS appropriately.  In particular, they need a
7303              new set of outer arguments, corresponding to the
7304              arguments for this class instantiation.
7305
7306              The same situation can arise with something like this:
7307
7308                friend void f(int);
7309                template <class T> class C {
7310                  friend void f(T) {}
7311                };
7312
7313              when `C<int>' is instantiated.  Now, `f(int)' is defined
7314              in the class.  */
7315
7316           if (!new_friend_is_defn)
7317             /* On the other hand, if the in-class declaration does
7318                *not* provide a definition, then we don't want to alter
7319                existing definitions.  We can just leave everything
7320                alone.  */
7321             ;
7322           else
7323             {
7324               tree new_template = TI_TEMPLATE (new_friend_template_info);
7325               tree new_args = TI_ARGS (new_friend_template_info);
7326
7327               /* Overwrite whatever template info was there before, if
7328                  any, with the new template information pertaining to
7329                  the declaration.  */
7330               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
7331
7332               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
7333                 {
7334                   /* We should have called reregister_specialization in
7335                      duplicate_decls.  */
7336                   gcc_assert (retrieve_specialization (new_template,
7337                                                        new_args, 0)
7338                               == old_decl);
7339
7340                   /* Instantiate it if the global has already been used.  */
7341                   if (DECL_ODR_USED (old_decl))
7342                     instantiate_decl (old_decl, /*defer_ok=*/true,
7343                                       /*expl_inst_class_mem_p=*/false);
7344                 }
7345               else
7346                 {
7347                   tree t;
7348
7349                   /* Indicate that the old function template is a partial
7350                      instantiation.  */
7351                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
7352                     = new_friend_result_template_info;
7353
7354                   gcc_assert (new_template
7355                               == most_general_template (new_template));
7356                   gcc_assert (new_template != old_decl);
7357
7358                   /* Reassign any specializations already in the hash table
7359                      to the new more general template, and add the
7360                      additional template args.  */
7361                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
7362                        t != NULL_TREE;
7363                        t = TREE_CHAIN (t))
7364                     {
7365                       tree spec = TREE_VALUE (t);
7366                       spec_entry elt;
7367
7368                       elt.tmpl = old_decl;
7369                       elt.args = DECL_TI_ARGS (spec);
7370                       elt.spec = NULL_TREE;
7371
7372                       htab_remove_elt (decl_specializations, &elt);
7373
7374                       DECL_TI_ARGS (spec)
7375                         = add_outermost_template_args (new_args,
7376                                                        DECL_TI_ARGS (spec));
7377
7378                       register_specialization
7379                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
7380
7381                     }
7382                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
7383                 }
7384             }
7385
7386           /* The information from NEW_FRIEND has been merged into OLD_DECL
7387              by duplicate_decls.  */
7388           new_friend = old_decl;
7389         }
7390     }
7391   else
7392     {
7393       tree context = DECL_CONTEXT (new_friend);
7394       bool dependent_p;
7395
7396       /* In the code
7397            template <class T> class C {
7398              template <class U> friend void C1<U>::f (); // case 1
7399              friend void C2<T>::f ();                    // case 2
7400            };
7401          we only need to make sure CONTEXT is a complete type for
7402          case 2.  To distinguish between the two cases, we note that
7403          CONTEXT of case 1 remains dependent type after tsubst while
7404          this isn't true for case 2.  */
7405       ++processing_template_decl;
7406       dependent_p = dependent_type_p (context);
7407       --processing_template_decl;
7408
7409       if (!dependent_p
7410           && !complete_type_or_else (context, NULL_TREE))
7411         return error_mark_node;
7412
7413       if (COMPLETE_TYPE_P (context))
7414         {
7415           /* Check to see that the declaration is really present, and,
7416              possibly obtain an improved declaration.  */
7417           tree fn = check_classfn (context,
7418                                    new_friend, NULL_TREE);
7419
7420           if (fn)
7421             new_friend = fn;
7422         }
7423     }
7424
7425   return new_friend;
7426 }
7427
7428 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
7429    template arguments, as for tsubst.
7430
7431    Returns an appropriate tsubst'd friend type or error_mark_node on
7432    failure.  */
7433
7434 static tree
7435 tsubst_friend_class (tree friend_tmpl, tree args)
7436 {
7437   tree friend_type;
7438   tree tmpl;
7439   tree context;
7440
7441   context = DECL_CONTEXT (friend_tmpl);
7442
7443   if (context)
7444     {
7445       if (TREE_CODE (context) == NAMESPACE_DECL)
7446         push_nested_namespace (context);
7447       else
7448         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
7449     }
7450
7451   /* Look for a class template declaration.  We look for hidden names
7452      because two friend declarations of the same template are the
7453      same.  For example, in:
7454
7455        struct A { 
7456          template <typename> friend class F;
7457        };
7458        template <typename> struct B { 
7459          template <typename> friend class F;
7460        };
7461
7462      both F templates are the same.  */
7463   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
7464                            /*block_p=*/true, 0, 
7465                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
7466
7467   /* But, if we don't find one, it might be because we're in a
7468      situation like this:
7469
7470        template <class T>
7471        struct S {
7472          template <class U>
7473          friend struct S;
7474        };
7475
7476      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
7477      for `S<int>', not the TEMPLATE_DECL.  */
7478   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
7479     {
7480       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
7481       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
7482     }
7483
7484   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
7485     {
7486       /* The friend template has already been declared.  Just
7487          check to see that the declarations match, and install any new
7488          default parameters.  We must tsubst the default parameters,
7489          of course.  We only need the innermost template parameters
7490          because that is all that redeclare_class_template will look
7491          at.  */
7492       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
7493           > TMPL_ARGS_DEPTH (args))
7494         {
7495           tree parms;
7496           location_t saved_input_location;
7497           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
7498                                          args, tf_warning_or_error);
7499
7500           saved_input_location = input_location;
7501           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
7502           redeclare_class_template (TREE_TYPE (tmpl), parms);
7503           input_location = saved_input_location;
7504           
7505         }
7506
7507       friend_type = TREE_TYPE (tmpl);
7508     }
7509   else
7510     {
7511       /* The friend template has not already been declared.  In this
7512          case, the instantiation of the template class will cause the
7513          injection of this template into the global scope.  */
7514       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
7515       if (tmpl == error_mark_node)
7516         return error_mark_node;
7517
7518       /* The new TMPL is not an instantiation of anything, so we
7519          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
7520          the new type because that is supposed to be the corresponding
7521          template decl, i.e., TMPL.  */
7522       DECL_USE_TEMPLATE (tmpl) = 0;
7523       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
7524       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
7525       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
7526         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
7527
7528       /* Inject this template into the global scope.  */
7529       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
7530     }
7531
7532   if (context)
7533     {
7534       if (TREE_CODE (context) == NAMESPACE_DECL)
7535         pop_nested_namespace (context);
7536       else
7537         pop_nested_class ();
7538     }
7539
7540   return friend_type;
7541 }
7542
7543 /* Returns zero if TYPE cannot be completed later due to circularity.
7544    Otherwise returns one.  */
7545
7546 static int
7547 can_complete_type_without_circularity (tree type)
7548 {
7549   if (type == NULL_TREE || type == error_mark_node)
7550     return 0;
7551   else if (COMPLETE_TYPE_P (type))
7552     return 1;
7553   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
7554     return can_complete_type_without_circularity (TREE_TYPE (type));
7555   else if (CLASS_TYPE_P (type)
7556            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
7557     return 0;
7558   else
7559     return 1;
7560 }
7561
7562 /* Apply any attributes which had to be deferred until instantiation
7563    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
7564    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
7565
7566 static void
7567 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
7568                                 tree args, tsubst_flags_t complain, tree in_decl)
7569 {
7570   tree last_dep = NULL_TREE;
7571   tree t;
7572   tree *p;
7573
7574   for (t = attributes; t; t = TREE_CHAIN (t))
7575     if (ATTR_IS_DEPENDENT (t))
7576       {
7577         last_dep = t;
7578         attributes = copy_list (attributes);
7579         break;
7580       }
7581
7582   if (DECL_P (*decl_p))
7583     {
7584       if (TREE_TYPE (*decl_p) == error_mark_node)
7585         return;
7586       p = &DECL_ATTRIBUTES (*decl_p);
7587     }
7588   else
7589     p = &TYPE_ATTRIBUTES (*decl_p);
7590
7591   if (last_dep)
7592     {
7593       tree late_attrs = NULL_TREE;
7594       tree *q = &late_attrs;
7595
7596       for (*p = attributes; *p; )
7597         {
7598           t = *p;
7599           if (ATTR_IS_DEPENDENT (t))
7600             {
7601               *p = TREE_CHAIN (t);
7602               TREE_CHAIN (t) = NULL_TREE;
7603               /* If the first attribute argument is an identifier, don't
7604                  pass it through tsubst.  Attributes like mode, format,
7605                  cleanup and several target specific attributes expect it
7606                  unmodified.  */
7607               if (TREE_VALUE (t)
7608                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
7609                   && TREE_VALUE (TREE_VALUE (t))
7610                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
7611                       == IDENTIFIER_NODE))
7612                 {
7613                   tree chain
7614                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
7615                                    in_decl,
7616                                    /*integral_constant_expression_p=*/false);
7617                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
7618                     TREE_VALUE (t)
7619                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
7620                                    chain);
7621                 }
7622               else
7623                 TREE_VALUE (t)
7624                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
7625                                  /*integral_constant_expression_p=*/false);
7626               *q = t;
7627               q = &TREE_CHAIN (t);
7628             }
7629           else
7630             p = &TREE_CHAIN (t);
7631         }
7632
7633       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
7634     }
7635 }
7636
7637 /* Perform (or defer) access check for typedefs that were referenced
7638    from within the template TMPL code.
7639    This is a subroutine of instantiate_template and instantiate_class_template.
7640    TMPL is the template to consider and TARGS is the list of arguments of
7641    that template.  */
7642
7643 static void
7644 perform_typedefs_access_check (tree tmpl, tree targs)
7645 {
7646   location_t saved_location;
7647   int i;
7648   qualified_typedef_usage_t *iter;
7649
7650   if (!tmpl
7651       || (!CLASS_TYPE_P (tmpl)
7652           && TREE_CODE (tmpl) != FUNCTION_DECL))
7653     return;
7654
7655   saved_location = input_location;
7656   for (i = 0;
7657        VEC_iterate (qualified_typedef_usage_t,
7658                     get_types_needing_access_check (tmpl),
7659                     i, iter);
7660         ++i)
7661     {
7662       tree type_decl = iter->typedef_decl;
7663       tree type_scope = iter->context;
7664
7665       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
7666         continue;
7667
7668       if (uses_template_parms (type_decl))
7669         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
7670       if (uses_template_parms (type_scope))
7671         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
7672
7673       /* Make access check error messages point to the location
7674          of the use of the typedef.  */
7675       input_location = iter->locus;
7676       perform_or_defer_access_check (TYPE_BINFO (type_scope),
7677                                      type_decl, type_decl);
7678     }
7679     input_location = saved_location;
7680 }
7681
7682 tree
7683 instantiate_class_template (tree type)
7684 {
7685   tree templ, args, pattern, t, member;
7686   tree typedecl;
7687   tree pbinfo;
7688   tree base_list;
7689   unsigned int saved_maximum_field_alignment;
7690
7691   if (type == error_mark_node)
7692     return error_mark_node;
7693
7694   if (TYPE_BEING_DEFINED (type)
7695       || COMPLETE_TYPE_P (type)
7696       || uses_template_parms (type))
7697     return type;
7698
7699   /* Figure out which template is being instantiated.  */
7700   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
7701   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7702
7703   /* Determine what specialization of the original template to
7704      instantiate.  */
7705   t = most_specialized_class (type, templ);
7706   if (t == error_mark_node)
7707     {
7708       TYPE_BEING_DEFINED (type) = 1;
7709       return error_mark_node;
7710     }
7711   else if (t)
7712     {
7713       /* This TYPE is actually an instantiation of a partial
7714          specialization.  We replace the innermost set of ARGS with
7715          the arguments appropriate for substitution.  For example,
7716          given:
7717
7718            template <class T> struct S {};
7719            template <class T> struct S<T*> {};
7720
7721          and supposing that we are instantiating S<int*>, ARGS will
7722          presently be {int*} -- but we need {int}.  */
7723       pattern = TREE_TYPE (t);
7724       args = TREE_PURPOSE (t);
7725     }
7726   else
7727     {
7728       pattern = TREE_TYPE (templ);
7729       args = CLASSTYPE_TI_ARGS (type);
7730     }
7731
7732   /* If the template we're instantiating is incomplete, then clearly
7733      there's nothing we can do.  */
7734   if (!COMPLETE_TYPE_P (pattern))
7735     return type;
7736
7737   /* If we've recursively instantiated too many templates, stop.  */
7738   if (! push_tinst_level (type))
7739     return type;
7740
7741   /* Now we're really doing the instantiation.  Mark the type as in
7742      the process of being defined.  */
7743   TYPE_BEING_DEFINED (type) = 1;
7744
7745   /* We may be in the middle of deferred access check.  Disable
7746      it now.  */
7747   push_deferring_access_checks (dk_no_deferred);
7748
7749   push_to_top_level ();
7750   /* Use #pragma pack from the template context.  */
7751   saved_maximum_field_alignment = maximum_field_alignment;
7752   maximum_field_alignment = TYPE_PRECISION (pattern);
7753
7754   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
7755
7756   /* Set the input location to the most specialized template definition.
7757      This is needed if tsubsting causes an error.  */
7758   typedecl = TYPE_MAIN_DECL (pattern);
7759   input_location = DECL_SOURCE_LOCATION (typedecl);
7760
7761   TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
7762   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
7763   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
7764   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
7765   TYPE_HAS_ASSIGN_REF (type) = TYPE_HAS_ASSIGN_REF (pattern);
7766   TYPE_HAS_CONST_ASSIGN_REF (type) = TYPE_HAS_CONST_ASSIGN_REF (pattern);
7767   TYPE_HAS_INIT_REF (type) = TYPE_HAS_INIT_REF (pattern);
7768   TYPE_HAS_CONST_INIT_REF (type) = TYPE_HAS_CONST_INIT_REF (pattern);
7769   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
7770   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
7771   TYPE_PACKED (type) = TYPE_PACKED (pattern);
7772   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
7773   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
7774   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
7775   if (ANON_AGGR_TYPE_P (pattern))
7776     SET_ANON_AGGR_TYPE_P (type);
7777   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
7778     {
7779       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
7780       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
7781     }
7782
7783   pbinfo = TYPE_BINFO (pattern);
7784
7785   /* We should never instantiate a nested class before its enclosing
7786      class; we need to look up the nested class by name before we can
7787      instantiate it, and that lookup should instantiate the enclosing
7788      class.  */
7789   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
7790               || COMPLETE_TYPE_P (TYPE_CONTEXT (type))
7791               || TYPE_BEING_DEFINED (TYPE_CONTEXT (type)));
7792
7793   base_list = NULL_TREE;
7794   if (BINFO_N_BASE_BINFOS (pbinfo))
7795     {
7796       tree pbase_binfo;
7797       tree context = TYPE_CONTEXT (type);
7798       tree pushed_scope;
7799       int i;
7800
7801       /* We must enter the scope containing the type, as that is where
7802          the accessibility of types named in dependent bases are
7803          looked up from.  */
7804       pushed_scope = push_scope (context ? context : global_namespace);
7805
7806       /* Substitute into each of the bases to determine the actual
7807          basetypes.  */
7808       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
7809         {
7810           tree base;
7811           tree access = BINFO_BASE_ACCESS (pbinfo, i);
7812           tree expanded_bases = NULL_TREE;
7813           int idx, len = 1;
7814
7815           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
7816             {
7817               expanded_bases = 
7818                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
7819                                        args, tf_error, NULL_TREE);
7820               if (expanded_bases == error_mark_node)
7821                 continue;
7822
7823               len = TREE_VEC_LENGTH (expanded_bases);
7824             }
7825
7826           for (idx = 0; idx < len; idx++)
7827             {
7828               if (expanded_bases)
7829                 /* Extract the already-expanded base class.  */
7830                 base = TREE_VEC_ELT (expanded_bases, idx);
7831               else
7832                 /* Substitute to figure out the base class.  */
7833                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
7834                                NULL_TREE);
7835
7836               if (base == error_mark_node)
7837                 continue;
7838
7839               base_list = tree_cons (access, base, base_list);
7840               if (BINFO_VIRTUAL_P (pbase_binfo))
7841                 TREE_TYPE (base_list) = integer_type_node;
7842             }
7843         }
7844
7845       /* The list is now in reverse order; correct that.  */
7846       base_list = nreverse (base_list);
7847
7848       if (pushed_scope)
7849         pop_scope (pushed_scope);
7850     }
7851   /* Now call xref_basetypes to set up all the base-class
7852      information.  */
7853   xref_basetypes (type, base_list);
7854
7855   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
7856                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
7857                                   args, tf_error, NULL_TREE);
7858
7859   /* Now that our base classes are set up, enter the scope of the
7860      class, so that name lookups into base classes, etc. will work
7861      correctly.  This is precisely analogous to what we do in
7862      begin_class_definition when defining an ordinary non-template
7863      class, except we also need to push the enclosing classes.  */
7864   push_nested_class (type);
7865
7866   /* Now members are processed in the order of declaration.  */
7867   for (member = CLASSTYPE_DECL_LIST (pattern);
7868        member; member = TREE_CHAIN (member))
7869     {
7870       tree t = TREE_VALUE (member);
7871
7872       if (TREE_PURPOSE (member))
7873         {
7874           if (TYPE_P (t))
7875             {
7876               /* Build new CLASSTYPE_NESTED_UTDS.  */
7877
7878               tree newtag;
7879               bool class_template_p;
7880
7881               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
7882                                   && TYPE_LANG_SPECIFIC (t)
7883                                   && CLASSTYPE_IS_TEMPLATE (t));
7884               /* If the member is a class template, then -- even after
7885                  substitution -- there may be dependent types in the
7886                  template argument list for the class.  We increment
7887                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
7888                  that function will assume that no types are dependent
7889                  when outside of a template.  */
7890               if (class_template_p)
7891                 ++processing_template_decl;
7892               newtag = tsubst (t, args, tf_error, NULL_TREE);
7893               if (class_template_p)
7894                 --processing_template_decl;
7895               if (newtag == error_mark_node)
7896                 continue;
7897
7898               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
7899                 {
7900                   tree name = TYPE_IDENTIFIER (t);
7901
7902                   if (class_template_p)
7903                     /* Unfortunately, lookup_template_class sets
7904                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
7905                        instantiation (i.e., for the type of a member
7906                        template class nested within a template class.)
7907                        This behavior is required for
7908                        maybe_process_partial_specialization to work
7909                        correctly, but is not accurate in this case;
7910                        the TAG is not an instantiation of anything.
7911                        (The corresponding TEMPLATE_DECL is an
7912                        instantiation, but the TYPE is not.) */
7913                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
7914
7915                   /* Now, we call pushtag to put this NEWTAG into the scope of
7916                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
7917                      pushtag calling push_template_decl.  We don't have to do
7918                      this for enums because it will already have been done in
7919                      tsubst_enum.  */
7920                   if (name)
7921                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
7922                   pushtag (name, newtag, /*tag_scope=*/ts_current);
7923                 }
7924             }
7925           else if (TREE_CODE (t) == FUNCTION_DECL
7926                    || DECL_FUNCTION_TEMPLATE_P (t))
7927             {
7928               /* Build new TYPE_METHODS.  */
7929               tree r;
7930
7931               if (TREE_CODE (t) == TEMPLATE_DECL)
7932                 ++processing_template_decl;
7933               r = tsubst (t, args, tf_error, NULL_TREE);
7934               if (TREE_CODE (t) == TEMPLATE_DECL)
7935                 --processing_template_decl;
7936               set_current_access_from_decl (r);
7937               finish_member_declaration (r);
7938             }
7939           else
7940             {
7941               /* Build new TYPE_FIELDS.  */
7942               if (TREE_CODE (t) == STATIC_ASSERT)
7943                 {
7944                   tree condition = 
7945                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
7946                                  tf_warning_or_error, NULL_TREE,
7947                                  /*integral_constant_expression_p=*/true);
7948                   finish_static_assert (condition,
7949                                         STATIC_ASSERT_MESSAGE (t), 
7950                                         STATIC_ASSERT_SOURCE_LOCATION (t),
7951                                         /*member_p=*/true);
7952                 }
7953               else if (TREE_CODE (t) != CONST_DECL)
7954                 {
7955                   tree r;
7956
7957                   /* The file and line for this declaration, to
7958                      assist in error message reporting.  Since we
7959                      called push_tinst_level above, we don't need to
7960                      restore these.  */
7961                   input_location = DECL_SOURCE_LOCATION (t);
7962
7963                   if (TREE_CODE (t) == TEMPLATE_DECL)
7964                     ++processing_template_decl;
7965                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
7966                   if (TREE_CODE (t) == TEMPLATE_DECL)
7967                     --processing_template_decl;
7968                   if (TREE_CODE (r) == VAR_DECL)
7969                     {
7970                       /* In [temp.inst]:
7971
7972                            [t]he initialization (and any associated
7973                            side-effects) of a static data member does
7974                            not occur unless the static data member is
7975                            itself used in a way that requires the
7976                            definition of the static data member to
7977                            exist.
7978
7979                          Therefore, we do not substitute into the
7980                          initialized for the static data member here.  */
7981                       finish_static_data_member_decl
7982                         (r,
7983                          /*init=*/NULL_TREE,
7984                          /*init_const_expr_p=*/false,
7985                          /*asmspec_tree=*/NULL_TREE,
7986                          /*flags=*/0);
7987                       if (DECL_INITIALIZED_IN_CLASS_P (r))
7988                         check_static_variable_definition (r, TREE_TYPE (r));
7989                     }
7990                   else if (TREE_CODE (r) == FIELD_DECL)
7991                     {
7992                       /* Determine whether R has a valid type and can be
7993                          completed later.  If R is invalid, then it is
7994                          replaced by error_mark_node so that it will not be
7995                          added to TYPE_FIELDS.  */
7996                       tree rtype = TREE_TYPE (r);
7997                       if (can_complete_type_without_circularity (rtype))
7998                         complete_type (rtype);
7999
8000                       if (!COMPLETE_TYPE_P (rtype))
8001                         {
8002                           cxx_incomplete_type_error (r, rtype);
8003                           r = error_mark_node;
8004                         }
8005                     }
8006
8007                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
8008                      such a thing will already have been added to the field
8009                      list by tsubst_enum in finish_member_declaration in the
8010                      CLASSTYPE_NESTED_UTDS case above.  */
8011                   if (!(TREE_CODE (r) == TYPE_DECL
8012                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
8013                         && DECL_ARTIFICIAL (r)))
8014                     {
8015                       set_current_access_from_decl (r);
8016                       finish_member_declaration (r);
8017                     }
8018                 }
8019             }
8020         }
8021       else
8022         {
8023           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
8024             {
8025               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
8026
8027               tree friend_type = t;
8028               bool adjust_processing_template_decl = false;
8029
8030               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8031                 {
8032                   /* template <class T> friend class C;  */
8033                   friend_type = tsubst_friend_class (friend_type, args);
8034                   adjust_processing_template_decl = true;
8035                 }
8036               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
8037                 {
8038                   /* template <class T> friend class C::D;  */
8039                   friend_type = tsubst (friend_type, args,
8040                                         tf_warning_or_error, NULL_TREE);
8041                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8042                     friend_type = TREE_TYPE (friend_type);
8043                   adjust_processing_template_decl = true;
8044                 }
8045               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
8046                 {
8047                   /* This could be either
8048
8049                        friend class T::C;
8050
8051                      when dependent_type_p is false or
8052
8053                        template <class U> friend class T::C;
8054
8055                      otherwise.  */
8056                   friend_type = tsubst (friend_type, args,
8057                                         tf_warning_or_error, NULL_TREE);
8058                   /* Bump processing_template_decl for correct
8059                      dependent_type_p calculation.  */
8060                   ++processing_template_decl;
8061                   if (dependent_type_p (friend_type))
8062                     adjust_processing_template_decl = true;
8063                   --processing_template_decl;
8064                 }
8065               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
8066                        && hidden_name_p (TYPE_NAME (friend_type)))
8067                 {
8068                   /* friend class C;
8069
8070                      where C hasn't been declared yet.  Let's lookup name
8071                      from namespace scope directly, bypassing any name that
8072                      come from dependent base class.  */
8073                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
8074
8075                   /* The call to xref_tag_from_type does injection for friend
8076                      classes.  */
8077                   push_nested_namespace (ns);
8078                   friend_type =
8079                     xref_tag_from_type (friend_type, NULL_TREE,
8080                                         /*tag_scope=*/ts_current);
8081                   pop_nested_namespace (ns);
8082                 }
8083               else if (uses_template_parms (friend_type))
8084                 /* friend class C<T>;  */
8085                 friend_type = tsubst (friend_type, args,
8086                                       tf_warning_or_error, NULL_TREE);
8087               /* Otherwise it's
8088
8089                    friend class C;
8090
8091                  where C is already declared or
8092
8093                    friend class C<int>;
8094
8095                  We don't have to do anything in these cases.  */
8096
8097               if (adjust_processing_template_decl)
8098                 /* Trick make_friend_class into realizing that the friend
8099                    we're adding is a template, not an ordinary class.  It's
8100                    important that we use make_friend_class since it will
8101                    perform some error-checking and output cross-reference
8102                    information.  */
8103                 ++processing_template_decl;
8104
8105               if (friend_type != error_mark_node)
8106                 make_friend_class (type, friend_type, /*complain=*/false);
8107
8108               if (adjust_processing_template_decl)
8109                 --processing_template_decl;
8110             }
8111           else
8112             {
8113               /* Build new DECL_FRIENDLIST.  */
8114               tree r;
8115
8116               /* The file and line for this declaration, to
8117                  assist in error message reporting.  Since we
8118                  called push_tinst_level above, we don't need to
8119                  restore these.  */
8120               input_location = DECL_SOURCE_LOCATION (t);
8121
8122               if (TREE_CODE (t) == TEMPLATE_DECL)
8123                 {
8124                   ++processing_template_decl;
8125                   push_deferring_access_checks (dk_no_check);
8126                 }
8127
8128               r = tsubst_friend_function (t, args);
8129               add_friend (type, r, /*complain=*/false);
8130               if (TREE_CODE (t) == TEMPLATE_DECL)
8131                 {
8132                   pop_deferring_access_checks ();
8133                   --processing_template_decl;
8134                 }
8135             }
8136         }
8137     }
8138
8139   /* Set the file and line number information to whatever is given for
8140      the class itself.  This puts error messages involving generated
8141      implicit functions at a predictable point, and the same point
8142      that would be used for non-template classes.  */
8143   input_location = DECL_SOURCE_LOCATION (typedecl);
8144
8145   unreverse_member_declarations (type);
8146   finish_struct_1 (type);
8147   TYPE_BEING_DEFINED (type) = 0;
8148
8149   /* Now that the class is complete, instantiate default arguments for
8150      any member functions.  We don't do this earlier because the
8151      default arguments may reference members of the class.  */
8152   if (!PRIMARY_TEMPLATE_P (templ))
8153     for (t = TYPE_METHODS (type); t; t = TREE_CHAIN (t))
8154       if (TREE_CODE (t) == FUNCTION_DECL
8155           /* Implicitly generated member functions will not have template
8156              information; they are not instantiations, but instead are
8157              created "fresh" for each instantiation.  */
8158           && DECL_TEMPLATE_INFO (t))
8159         tsubst_default_arguments (t);
8160
8161   /* Some typedefs referenced from within the template code need to be access
8162      checked at template instantiation time, i.e now. These types were
8163      added to the template at parsing time. Let's get those and perform
8164      the access checks then.  */
8165   perform_typedefs_access_check (pattern, args);
8166   perform_deferred_access_checks ();
8167   pop_nested_class ();
8168   maximum_field_alignment = saved_maximum_field_alignment;
8169   pop_from_top_level ();
8170   pop_deferring_access_checks ();
8171   pop_tinst_level ();
8172
8173   /* The vtable for a template class can be emitted in any translation
8174      unit in which the class is instantiated.  When there is no key
8175      method, however, finish_struct_1 will already have added TYPE to
8176      the keyed_classes list.  */
8177   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
8178     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
8179
8180   return type;
8181 }
8182
8183 static tree
8184 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8185 {
8186   tree r;
8187
8188   if (!t)
8189     r = t;
8190   else if (TYPE_P (t))
8191     r = tsubst (t, args, complain, in_decl);
8192   else
8193     {
8194       r = tsubst_expr (t, args, complain, in_decl,
8195                        /*integral_constant_expression_p=*/true);
8196       r = fold_non_dependent_expr (r);
8197     }
8198   return r;
8199 }
8200
8201 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
8202    NONTYPE_ARGUMENT_PACK.  */
8203
8204 static tree
8205 make_fnparm_pack (tree spec_parm)
8206 {
8207   /* Collect all of the extra "packed" parameters into an
8208      argument pack.  */
8209   tree parmvec;
8210   tree parmtypevec;
8211   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
8212   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
8213   int i, len = list_length (spec_parm);
8214
8215   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
8216   parmvec = make_tree_vec (len);
8217   parmtypevec = make_tree_vec (len);
8218   for (i = 0; i < len; i++, spec_parm = TREE_CHAIN (spec_parm))
8219     {
8220       TREE_VEC_ELT (parmvec, i) = spec_parm;
8221       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
8222     }
8223
8224   /* Build the argument packs.  */
8225   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
8226   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
8227   TREE_TYPE (argpack) = argtypepack;
8228
8229   return argpack;
8230 }        
8231
8232 /* Substitute ARGS into T, which is an pack expansion
8233    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
8234    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
8235    (if only a partial substitution could be performed) or
8236    ERROR_MARK_NODE if there was an error.  */
8237 tree
8238 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
8239                        tree in_decl)
8240 {
8241   tree pattern;
8242   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
8243   int i, len = -1;
8244   tree result;
8245   int incomplete = 0;
8246   bool very_local_specializations = false;
8247
8248   gcc_assert (PACK_EXPANSION_P (t));
8249   pattern = PACK_EXPANSION_PATTERN (t);
8250
8251   /* Determine the argument packs that will instantiate the parameter
8252      packs used in the expansion expression. While we're at it,
8253      compute the number of arguments to be expanded and make sure it
8254      is consistent.  */
8255   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
8256        pack = TREE_CHAIN (pack))
8257     {
8258       tree parm_pack = TREE_VALUE (pack);
8259       tree arg_pack = NULL_TREE;
8260       tree orig_arg = NULL_TREE;
8261
8262       if (TREE_CODE (parm_pack) == PARM_DECL)
8263         {
8264           arg_pack = retrieve_local_specialization (parm_pack);
8265           if (arg_pack == NULL_TREE)
8266             {
8267               /* This can happen for a parameter name used later in a function
8268                  declaration (such as in a late-specified return type).  Just
8269                  make a dummy decl, since it's only used for its type.  */
8270               gcc_assert (cp_unevaluated_operand != 0);
8271               arg_pack = tsubst_decl (parm_pack, args, complain);
8272               arg_pack = make_fnparm_pack (arg_pack);
8273             }
8274         }
8275       else
8276         {
8277           int level, idx, levels;
8278           template_parm_level_and_index (parm_pack, &level, &idx);
8279
8280           levels = TMPL_ARGS_DEPTH (args);
8281           if (level <= levels)
8282             arg_pack = TMPL_ARG (args, level, idx);
8283         }
8284
8285       orig_arg = arg_pack;
8286       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
8287         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
8288       
8289       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
8290         /* This can only happen if we forget to expand an argument
8291            pack somewhere else. Just return an error, silently.  */
8292         {
8293           result = make_tree_vec (1);
8294           TREE_VEC_ELT (result, 0) = error_mark_node;
8295           return result;
8296         }
8297
8298       if (arg_pack
8299           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
8300           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
8301         {
8302           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
8303           tree pattern = PACK_EXPANSION_PATTERN (expansion);
8304           if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
8305               || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
8306             /* The argument pack that the parameter maps to is just an
8307                expansion of the parameter itself, such as one would
8308                find in the implicit typedef of a class inside the
8309                class itself.  Consider this parameter "unsubstituted",
8310                so that we will maintain the outer pack expansion.  */
8311             arg_pack = NULL_TREE;
8312         }
8313           
8314       if (arg_pack)
8315         {
8316           int my_len = 
8317             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
8318
8319           /* It's all-or-nothing with incomplete argument packs.  */
8320           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8321             return error_mark_node;
8322           
8323           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8324             incomplete = 1;
8325
8326           if (len < 0)
8327             len = my_len;
8328           else if (len != my_len)
8329             {
8330               if (incomplete)
8331                 /* We got explicit args for some packs but not others;
8332                    do nothing now and try again after deduction.  */
8333                 return t;
8334               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
8335                 error ("mismatched argument pack lengths while expanding "
8336                        "%<%T%>",
8337                        pattern);
8338               else
8339                 error ("mismatched argument pack lengths while expanding "
8340                        "%<%E%>",
8341                        pattern);
8342               return error_mark_node;
8343             }
8344
8345           /* Keep track of the parameter packs and their corresponding
8346              argument packs.  */
8347           packs = tree_cons (parm_pack, arg_pack, packs);
8348           TREE_TYPE (packs) = orig_arg;
8349         }
8350       else
8351         /* We can't substitute for this parameter pack.  */
8352         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
8353                                          TREE_VALUE (pack),
8354                                          unsubstituted_packs);
8355     }
8356
8357   /* We cannot expand this expansion expression, because we don't have
8358      all of the argument packs we need. Substitute into the pattern
8359      and return a PACK_EXPANSION_*. The caller will need to deal with
8360      that.  */
8361   if (unsubstituted_packs)
8362     {
8363       tree new_pat;
8364       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8365         new_pat = tsubst_expr (pattern, args, complain, in_decl,
8366                                /*integral_constant_expression_p=*/false);
8367       else
8368         new_pat = tsubst (pattern, args, complain, in_decl);
8369       return make_pack_expansion (new_pat);
8370     }
8371
8372   /* We could not find any argument packs that work.  */
8373   if (len < 0)
8374     return error_mark_node;
8375
8376   if (!local_specializations)
8377     {
8378       /* We're in a late-specified return type, so we don't have a local
8379          specializations table.  Create one for doing this expansion.  */
8380       very_local_specializations = true;
8381       local_specializations = htab_create (37,
8382                                            hash_local_specialization,
8383                                            eq_local_specializations,
8384                                            NULL);
8385     }
8386
8387   /* For each argument in each argument pack, substitute into the
8388      pattern.  */
8389   result = make_tree_vec (len + incomplete);
8390   for (i = 0; i < len + incomplete; ++i)
8391     {
8392       /* For parameter pack, change the substitution of the parameter
8393          pack to the ith argument in its argument pack, then expand
8394          the pattern.  */
8395       for (pack = packs; pack; pack = TREE_CHAIN (pack))
8396         {
8397           tree parm = TREE_PURPOSE (pack);
8398
8399           if (TREE_CODE (parm) == PARM_DECL)
8400             {
8401               /* Select the Ith argument from the pack.  */
8402               tree arg = make_node (ARGUMENT_PACK_SELECT);
8403               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
8404               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
8405               mark_used (parm);
8406               register_local_specialization (arg, parm);
8407             }
8408           else
8409             {
8410               tree value = parm;
8411               int idx, level;
8412               template_parm_level_and_index (parm, &level, &idx);
8413               
8414               if (i < len) 
8415                 {
8416                   /* Select the Ith argument from the pack. */
8417                   value = make_node (ARGUMENT_PACK_SELECT);
8418                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
8419                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
8420                 }
8421
8422               /* Update the corresponding argument.  */
8423               TMPL_ARG (args, level, idx) = value;
8424             }
8425         }
8426
8427       /* Substitute into the PATTERN with the altered arguments.  */
8428       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8429         TREE_VEC_ELT (result, i) = 
8430           tsubst_expr (pattern, args, complain, in_decl,
8431                        /*integral_constant_expression_p=*/false);
8432       else
8433         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
8434
8435       if (i == len)
8436         /* When we have incomplete argument packs, the last "expanded"
8437            result is itself a pack expansion, which allows us
8438            to deduce more arguments.  */
8439         TREE_VEC_ELT (result, i) = 
8440           make_pack_expansion (TREE_VEC_ELT (result, i));
8441
8442       if (TREE_VEC_ELT (result, i) == error_mark_node)
8443         {
8444           result = error_mark_node;
8445           break;
8446         }
8447     }
8448
8449   /* Update ARGS to restore the substitution from parameter packs to
8450      their argument packs.  */
8451   for (pack = packs; pack; pack = TREE_CHAIN (pack))
8452     {
8453       tree parm = TREE_PURPOSE (pack);
8454
8455       if (TREE_CODE (parm) == PARM_DECL)
8456         register_local_specialization (TREE_TYPE (pack), parm);
8457       else
8458         {
8459           int idx, level;
8460           template_parm_level_and_index (parm, &level, &idx);
8461           
8462           /* Update the corresponding argument.  */
8463           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
8464             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
8465               TREE_TYPE (pack);
8466           else
8467             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
8468         }
8469     }
8470
8471   if (very_local_specializations)
8472     {
8473       htab_delete (local_specializations);
8474       local_specializations = NULL;
8475     }
8476   
8477   return result;
8478 }
8479
8480 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
8481    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
8482    parameter packs; all parms generated from a function parameter pack will
8483    have the same DECL_PARM_INDEX.  */
8484
8485 tree
8486 get_pattern_parm (tree parm, tree tmpl)
8487 {
8488   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
8489   tree patparm;
8490
8491   if (DECL_ARTIFICIAL (parm))
8492     {
8493       for (patparm = DECL_ARGUMENTS (pattern);
8494            patparm; patparm = TREE_CHAIN (patparm))
8495         if (DECL_ARTIFICIAL (patparm)
8496             && DECL_NAME (parm) == DECL_NAME (patparm))
8497           break;
8498     }
8499   else
8500     {
8501       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
8502       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
8503       gcc_assert (DECL_PARM_INDEX (patparm)
8504                   == DECL_PARM_INDEX (parm));
8505     }
8506
8507   return patparm;
8508 }
8509
8510 /* Substitute ARGS into the vector or list of template arguments T.  */
8511
8512 static tree
8513 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8514 {
8515   tree orig_t = t;
8516   int len = TREE_VEC_LENGTH (t);
8517   int need_new = 0, i, expanded_len_adjust = 0, out;
8518   tree *elts = (tree *) alloca (len * sizeof (tree));
8519
8520   for (i = 0; i < len; i++)
8521     {
8522       tree orig_arg = TREE_VEC_ELT (t, i);
8523       tree new_arg;
8524
8525       if (TREE_CODE (orig_arg) == TREE_VEC)
8526         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
8527       else if (PACK_EXPANSION_P (orig_arg))
8528         {
8529           /* Substitute into an expansion expression.  */
8530           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
8531
8532           if (TREE_CODE (new_arg) == TREE_VEC)
8533             /* Add to the expanded length adjustment the number of
8534                expanded arguments. We subtract one from this
8535                measurement, because the argument pack expression
8536                itself is already counted as 1 in
8537                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
8538                the argument pack is empty.  */
8539             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
8540         }
8541       else if (ARGUMENT_PACK_P (orig_arg))
8542         {
8543           /* Substitute into each of the arguments.  */
8544           new_arg = TYPE_P (orig_arg)
8545             ? cxx_make_type (TREE_CODE (orig_arg))
8546             : make_node (TREE_CODE (orig_arg));
8547           
8548           SET_ARGUMENT_PACK_ARGS (
8549             new_arg,
8550             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
8551                                   args, complain, in_decl));
8552
8553           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
8554             new_arg = error_mark_node;
8555
8556           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
8557             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
8558                                           complain, in_decl);
8559             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
8560
8561             if (TREE_TYPE (new_arg) == error_mark_node)
8562               new_arg = error_mark_node;
8563           }
8564         }
8565       else
8566         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
8567
8568       if (new_arg == error_mark_node)
8569         return error_mark_node;
8570
8571       elts[i] = new_arg;
8572       if (new_arg != orig_arg)
8573         need_new = 1;
8574     }
8575
8576   if (!need_new)
8577     return t;
8578
8579   /* Make space for the expanded arguments coming from template
8580      argument packs.  */
8581   t = make_tree_vec (len + expanded_len_adjust);
8582   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
8583      arguments for a member template.
8584      In that case each TREE_VEC in ORIG_T represents a level of template
8585      arguments, and ORIG_T won't carry any non defaulted argument count.
8586      It will rather be the nested TREE_VECs that will carry one.
8587      In other words, ORIG_T carries a non defaulted argument count only
8588      if it doesn't contain any nested TREE_VEC.  */
8589   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
8590     {
8591       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
8592       count += expanded_len_adjust;
8593       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
8594     }
8595   for (i = 0, out = 0; i < len; i++)
8596     {
8597       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
8598            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
8599           && TREE_CODE (elts[i]) == TREE_VEC)
8600         {
8601           int idx;
8602
8603           /* Now expand the template argument pack "in place".  */
8604           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
8605             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
8606         }
8607       else
8608         {
8609           TREE_VEC_ELT (t, out) = elts[i];
8610           out++;
8611         }
8612     }
8613
8614   return t;
8615 }
8616
8617 /* Return the result of substituting ARGS into the template parameters
8618    given by PARMS.  If there are m levels of ARGS and m + n levels of
8619    PARMS, then the result will contain n levels of PARMS.  For
8620    example, if PARMS is `template <class T> template <class U>
8621    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
8622    result will be `template <int*, double, class V>'.  */
8623
8624 static tree
8625 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
8626 {
8627   tree r = NULL_TREE;
8628   tree* new_parms;
8629
8630   /* When substituting into a template, we must set
8631      PROCESSING_TEMPLATE_DECL as the template parameters may be
8632      dependent if they are based on one-another, and the dependency
8633      predicates are short-circuit outside of templates.  */
8634   ++processing_template_decl;
8635
8636   for (new_parms = &r;
8637        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
8638        new_parms = &(TREE_CHAIN (*new_parms)),
8639          parms = TREE_CHAIN (parms))
8640     {
8641       tree new_vec =
8642         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
8643       int i;
8644
8645       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
8646         {
8647           tree tuple;
8648           tree default_value;
8649           tree parm_decl;
8650
8651           if (parms == error_mark_node)
8652             continue;
8653
8654           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
8655
8656           if (tuple == error_mark_node)
8657             continue;
8658
8659           default_value = TREE_PURPOSE (tuple);
8660           parm_decl = TREE_VALUE (tuple);
8661
8662           parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
8663           if (TREE_CODE (parm_decl) == PARM_DECL
8664               && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
8665             parm_decl = error_mark_node;
8666           default_value = tsubst_template_arg (default_value, args,
8667                                                complain, NULL_TREE);
8668
8669           tuple = build_tree_list (default_value, parm_decl);
8670           TREE_VEC_ELT (new_vec, i) = tuple;
8671         }
8672
8673       *new_parms =
8674         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
8675                              - TMPL_ARGS_DEPTH (args)),
8676                    new_vec, NULL_TREE);
8677     }
8678
8679   --processing_template_decl;
8680
8681   return r;
8682 }
8683
8684 /* Substitute the ARGS into the indicated aggregate (or enumeration)
8685    type T.  If T is not an aggregate or enumeration type, it is
8686    handled as if by tsubst.  IN_DECL is as for tsubst.  If
8687    ENTERING_SCOPE is nonzero, T is the context for a template which
8688    we are presently tsubst'ing.  Return the substituted value.  */
8689
8690 static tree
8691 tsubst_aggr_type (tree t,
8692                   tree args,
8693                   tsubst_flags_t complain,
8694                   tree in_decl,
8695                   int entering_scope)
8696 {
8697   if (t == NULL_TREE)
8698     return NULL_TREE;
8699
8700   switch (TREE_CODE (t))
8701     {
8702     case RECORD_TYPE:
8703       if (TYPE_PTRMEMFUNC_P (t))
8704         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
8705
8706       /* Else fall through.  */
8707     case ENUMERAL_TYPE:
8708     case UNION_TYPE:
8709       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
8710         {
8711           tree argvec;
8712           tree context;
8713           tree r;
8714           int saved_unevaluated_operand;
8715           int saved_inhibit_evaluation_warnings;
8716
8717           /* In "sizeof(X<I>)" we need to evaluate "I".  */
8718           saved_unevaluated_operand = cp_unevaluated_operand;
8719           cp_unevaluated_operand = 0;
8720           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
8721           c_inhibit_evaluation_warnings = 0;
8722
8723           /* First, determine the context for the type we are looking
8724              up.  */
8725           context = TYPE_CONTEXT (t);
8726           if (context)
8727             {
8728               context = tsubst_aggr_type (context, args, complain,
8729                                           in_decl, /*entering_scope=*/1);
8730               /* If context is a nested class inside a class template,
8731                  it may still need to be instantiated (c++/33959).  */
8732               if (TYPE_P (context))
8733                 context = complete_type (context);
8734             }
8735
8736           /* Then, figure out what arguments are appropriate for the
8737              type we are trying to find.  For example, given:
8738
8739                template <class T> struct S;
8740                template <class T, class U> void f(T, U) { S<U> su; }
8741
8742              and supposing that we are instantiating f<int, double>,
8743              then our ARGS will be {int, double}, but, when looking up
8744              S we only want {double}.  */
8745           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
8746                                          complain, in_decl);
8747           if (argvec == error_mark_node)
8748             r = error_mark_node;
8749           else
8750             {
8751               r = lookup_template_class (t, argvec, in_decl, context,
8752                                          entering_scope, complain);
8753               r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
8754             }
8755
8756           cp_unevaluated_operand = saved_unevaluated_operand;
8757           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
8758
8759           return r;
8760         }
8761       else
8762         /* This is not a template type, so there's nothing to do.  */
8763         return t;
8764
8765     default:
8766       return tsubst (t, args, complain, in_decl);
8767     }
8768 }
8769
8770 /* Substitute into the default argument ARG (a default argument for
8771    FN), which has the indicated TYPE.  */
8772
8773 tree
8774 tsubst_default_argument (tree fn, tree type, tree arg)
8775 {
8776   tree saved_class_ptr = NULL_TREE;
8777   tree saved_class_ref = NULL_TREE;
8778
8779   /* This default argument came from a template.  Instantiate the
8780      default argument here, not in tsubst.  In the case of
8781      something like:
8782
8783        template <class T>
8784        struct S {
8785          static T t();
8786          void f(T = t());
8787        };
8788
8789      we must be careful to do name lookup in the scope of S<T>,
8790      rather than in the current class.  */
8791   push_access_scope (fn);
8792   /* The "this" pointer is not valid in a default argument.  */
8793   if (cfun)
8794     {
8795       saved_class_ptr = current_class_ptr;
8796       cp_function_chain->x_current_class_ptr = NULL_TREE;
8797       saved_class_ref = current_class_ref;
8798       cp_function_chain->x_current_class_ref = NULL_TREE;
8799     }
8800
8801   push_deferring_access_checks(dk_no_deferred);
8802   /* The default argument expression may cause implicitly defined
8803      member functions to be synthesized, which will result in garbage
8804      collection.  We must treat this situation as if we were within
8805      the body of function so as to avoid collecting live data on the
8806      stack.  */
8807   ++function_depth;
8808   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
8809                      tf_warning_or_error, NULL_TREE,
8810                      /*integral_constant_expression_p=*/false);
8811   --function_depth;
8812   pop_deferring_access_checks();
8813
8814   /* Restore the "this" pointer.  */
8815   if (cfun)
8816     {
8817       cp_function_chain->x_current_class_ptr = saved_class_ptr;
8818       cp_function_chain->x_current_class_ref = saved_class_ref;
8819     }
8820
8821   /* Make sure the default argument is reasonable.  */
8822   arg = check_default_argument (type, arg);
8823
8824   pop_access_scope (fn);
8825
8826   return arg;
8827 }
8828
8829 /* Substitute into all the default arguments for FN.  */
8830
8831 static void
8832 tsubst_default_arguments (tree fn)
8833 {
8834   tree arg;
8835   tree tmpl_args;
8836
8837   tmpl_args = DECL_TI_ARGS (fn);
8838
8839   /* If this function is not yet instantiated, we certainly don't need
8840      its default arguments.  */
8841   if (uses_template_parms (tmpl_args))
8842     return;
8843
8844   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
8845        arg;
8846        arg = TREE_CHAIN (arg))
8847     if (TREE_PURPOSE (arg))
8848       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
8849                                                     TREE_VALUE (arg),
8850                                                     TREE_PURPOSE (arg));
8851 }
8852
8853 /* Substitute the ARGS into the T, which is a _DECL.  Return the
8854    result of the substitution.  Issue error and warning messages under
8855    control of COMPLAIN.  */
8856
8857 static tree
8858 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
8859 {
8860 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
8861   location_t saved_loc;
8862   tree r = NULL_TREE;
8863   tree in_decl = t;
8864   hashval_t hash = 0;
8865
8866   /* Set the filename and linenumber to improve error-reporting.  */
8867   saved_loc = input_location;
8868   input_location = DECL_SOURCE_LOCATION (t);
8869
8870   switch (TREE_CODE (t))
8871     {
8872     case TEMPLATE_DECL:
8873       {
8874         /* We can get here when processing a member function template,
8875            member class template, or template template parameter.  */
8876         tree decl = DECL_TEMPLATE_RESULT (t);
8877         tree spec;
8878         tree tmpl_args;
8879         tree full_args;
8880
8881         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
8882           {
8883             /* Template template parameter is treated here.  */
8884             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8885             if (new_type == error_mark_node)
8886               RETURN (error_mark_node);
8887
8888             r = copy_decl (t);
8889             TREE_CHAIN (r) = NULL_TREE;
8890             TREE_TYPE (r) = new_type;
8891             DECL_TEMPLATE_RESULT (r)
8892               = build_decl (DECL_SOURCE_LOCATION (decl),
8893                             TYPE_DECL, DECL_NAME (decl), new_type);
8894             DECL_TEMPLATE_PARMS (r)
8895               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8896                                        complain);
8897             TYPE_NAME (new_type) = r;
8898             break;
8899           }
8900
8901         /* We might already have an instance of this template.
8902            The ARGS are for the surrounding class type, so the
8903            full args contain the tsubst'd args for the context,
8904            plus the innermost args from the template decl.  */
8905         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
8906           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
8907           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
8908         /* Because this is a template, the arguments will still be
8909            dependent, even after substitution.  If
8910            PROCESSING_TEMPLATE_DECL is not set, the dependency
8911            predicates will short-circuit.  */
8912         ++processing_template_decl;
8913         full_args = tsubst_template_args (tmpl_args, args,
8914                                           complain, in_decl);
8915         --processing_template_decl;
8916         if (full_args == error_mark_node)
8917           RETURN (error_mark_node);
8918
8919         /* If this is a default template template argument,
8920            tsubst might not have changed anything.  */
8921         if (full_args == tmpl_args)
8922           RETURN (t);
8923
8924         hash = hash_tmpl_and_args (t, full_args);
8925         spec = retrieve_specialization (t, full_args, hash);
8926         if (spec != NULL_TREE)
8927           {
8928             r = spec;
8929             break;
8930           }
8931
8932         /* Make a new template decl.  It will be similar to the
8933            original, but will record the current template arguments.
8934            We also create a new function declaration, which is just
8935            like the old one, but points to this new template, rather
8936            than the old one.  */
8937         r = copy_decl (t);
8938         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
8939         TREE_CHAIN (r) = NULL_TREE;
8940
8941         DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
8942
8943         if (TREE_CODE (decl) == TYPE_DECL)
8944           {
8945             tree new_type;
8946             ++processing_template_decl;
8947             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8948             --processing_template_decl;
8949             if (new_type == error_mark_node)
8950               RETURN (error_mark_node);
8951
8952             TREE_TYPE (r) = new_type;
8953             CLASSTYPE_TI_TEMPLATE (new_type) = r;
8954             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
8955             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
8956             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
8957           }
8958         else
8959           {
8960             tree new_decl;
8961             ++processing_template_decl;
8962             new_decl = tsubst (decl, args, complain, in_decl);
8963             --processing_template_decl;
8964             if (new_decl == error_mark_node)
8965               RETURN (error_mark_node);
8966
8967             DECL_TEMPLATE_RESULT (r) = new_decl;
8968             DECL_TI_TEMPLATE (new_decl) = r;
8969             TREE_TYPE (r) = TREE_TYPE (new_decl);
8970             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
8971             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
8972           }
8973
8974         SET_DECL_IMPLICIT_INSTANTIATION (r);
8975         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
8976         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
8977
8978         /* The template parameters for this new template are all the
8979            template parameters for the old template, except the
8980            outermost level of parameters.  */
8981         DECL_TEMPLATE_PARMS (r)
8982           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8983                                    complain);
8984
8985         if (PRIMARY_TEMPLATE_P (t))
8986           DECL_PRIMARY_TEMPLATE (r) = r;
8987
8988         if (TREE_CODE (decl) != TYPE_DECL)
8989           /* Record this non-type partial instantiation.  */
8990           register_specialization (r, t,
8991                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
8992                                    false, hash);
8993       }
8994       break;
8995
8996     case FUNCTION_DECL:
8997       {
8998         tree ctx;
8999         tree argvec = NULL_TREE;
9000         tree *friends;
9001         tree gen_tmpl;
9002         tree type;
9003         int member;
9004         int args_depth;
9005         int parms_depth;
9006
9007         /* Nobody should be tsubst'ing into non-template functions.  */
9008         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
9009
9010         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
9011           {
9012             tree spec;
9013             bool dependent_p;
9014
9015             /* If T is not dependent, just return it.  We have to
9016                increment PROCESSING_TEMPLATE_DECL because
9017                value_dependent_expression_p assumes that nothing is
9018                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
9019             ++processing_template_decl;
9020             dependent_p = value_dependent_expression_p (t);
9021             --processing_template_decl;
9022             if (!dependent_p)
9023               RETURN (t);
9024
9025             /* Calculate the most general template of which R is a
9026                specialization, and the complete set of arguments used to
9027                specialize R.  */
9028             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
9029             argvec = tsubst_template_args (DECL_TI_ARGS
9030                                           (DECL_TEMPLATE_RESULT
9031                                                  (DECL_TI_TEMPLATE (t))),
9032                                            args, complain, in_decl);
9033
9034             /* Check to see if we already have this specialization.  */
9035             hash = hash_tmpl_and_args (gen_tmpl, argvec);
9036             spec = retrieve_specialization (gen_tmpl, argvec, hash);
9037
9038             if (spec)
9039               {
9040                 r = spec;
9041                 break;
9042               }
9043
9044             /* We can see more levels of arguments than parameters if
9045                there was a specialization of a member template, like
9046                this:
9047
9048                  template <class T> struct S { template <class U> void f(); }
9049                  template <> template <class U> void S<int>::f(U);
9050
9051                Here, we'll be substituting into the specialization,
9052                because that's where we can find the code we actually
9053                want to generate, but we'll have enough arguments for
9054                the most general template.
9055
9056                We also deal with the peculiar case:
9057
9058                  template <class T> struct S {
9059                    template <class U> friend void f();
9060                  };
9061                  template <class U> void f() {}
9062                  template S<int>;
9063                  template void f<double>();
9064
9065                Here, the ARGS for the instantiation of will be {int,
9066                double}.  But, we only need as many ARGS as there are
9067                levels of template parameters in CODE_PATTERN.  We are
9068                careful not to get fooled into reducing the ARGS in
9069                situations like:
9070
9071                  template <class T> struct S { template <class U> void f(U); }
9072                  template <class T> template <> void S<T>::f(int) {}
9073
9074                which we can spot because the pattern will be a
9075                specialization in this case.  */
9076             args_depth = TMPL_ARGS_DEPTH (args);
9077             parms_depth =
9078               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
9079             if (args_depth > parms_depth
9080                 && !DECL_TEMPLATE_SPECIALIZATION (t))
9081               args = get_innermost_template_args (args, parms_depth);
9082           }
9083         else
9084           {
9085             /* This special case arises when we have something like this:
9086
9087                  template <class T> struct S {
9088                    friend void f<int>(int, double);
9089                  };
9090
9091                Here, the DECL_TI_TEMPLATE for the friend declaration
9092                will be an IDENTIFIER_NODE.  We are being called from
9093                tsubst_friend_function, and we want only to create a
9094                new decl (R) with appropriate types so that we can call
9095                determine_specialization.  */
9096             gen_tmpl = NULL_TREE;
9097           }
9098
9099         if (DECL_CLASS_SCOPE_P (t))
9100           {
9101             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
9102               member = 2;
9103             else
9104               member = 1;
9105             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
9106                                     complain, t, /*entering_scope=*/1);
9107           }
9108         else
9109           {
9110             member = 0;
9111             ctx = DECL_CONTEXT (t);
9112           }
9113         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9114         if (type == error_mark_node)
9115           RETURN (error_mark_node);
9116
9117         /* We do NOT check for matching decls pushed separately at this
9118            point, as they may not represent instantiations of this
9119            template, and in any case are considered separate under the
9120            discrete model.  */
9121         r = copy_decl (t);
9122         DECL_USE_TEMPLATE (r) = 0;
9123         TREE_TYPE (r) = type;
9124         /* Clear out the mangled name and RTL for the instantiation.  */
9125         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9126         SET_DECL_RTL (r, NULL_RTX);
9127         /* Leave DECL_INITIAL set on deleted instantiations.  */
9128         if (!DECL_DELETED_FN (r))
9129           DECL_INITIAL (r) = NULL_TREE;
9130         DECL_CONTEXT (r) = ctx;
9131
9132         if (member && DECL_CONV_FN_P (r))
9133           /* Type-conversion operator.  Reconstruct the name, in
9134              case it's the name of one of the template's parameters.  */
9135           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
9136
9137         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
9138                                      complain, t);
9139         DECL_RESULT (r) = NULL_TREE;
9140
9141         TREE_STATIC (r) = 0;
9142         TREE_PUBLIC (r) = TREE_PUBLIC (t);
9143         DECL_EXTERNAL (r) = 1;
9144         /* If this is an instantiation of a function with internal
9145            linkage, we already know what object file linkage will be
9146            assigned to the instantiation.  */
9147         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
9148         DECL_DEFER_OUTPUT (r) = 0;
9149         TREE_CHAIN (r) = NULL_TREE;
9150         DECL_PENDING_INLINE_INFO (r) = 0;
9151         DECL_PENDING_INLINE_P (r) = 0;
9152         DECL_SAVED_TREE (r) = NULL_TREE;
9153         DECL_STRUCT_FUNCTION (r) = NULL;
9154         TREE_USED (r) = 0;
9155         /* We'll re-clone as appropriate in instantiate_template.  */
9156         DECL_CLONED_FUNCTION (r) = NULL_TREE;
9157
9158         /* If we aren't complaining now, return on error before we register
9159            the specialization so that we'll complain eventually.  */
9160         if ((complain & tf_error) == 0
9161             && IDENTIFIER_OPNAME_P (DECL_NAME (r))
9162             && !grok_op_properties (r, /*complain=*/false))
9163           RETURN (error_mark_node);
9164
9165         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
9166            this in the special friend case mentioned above where
9167            GEN_TMPL is NULL.  */
9168         if (gen_tmpl)
9169           {
9170             DECL_TEMPLATE_INFO (r)
9171               = build_template_info (gen_tmpl, argvec);
9172             SET_DECL_IMPLICIT_INSTANTIATION (r);
9173             register_specialization (r, gen_tmpl, argvec, false, hash);
9174
9175             /* We're not supposed to instantiate default arguments
9176                until they are called, for a template.  But, for a
9177                declaration like:
9178
9179                  template <class T> void f ()
9180                  { extern void g(int i = T()); }
9181
9182                we should do the substitution when the template is
9183                instantiated.  We handle the member function case in
9184                instantiate_class_template since the default arguments
9185                might refer to other members of the class.  */
9186             if (!member
9187                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
9188                 && !uses_template_parms (argvec))
9189               tsubst_default_arguments (r);
9190           }
9191         else
9192           DECL_TEMPLATE_INFO (r) = NULL_TREE;
9193
9194         /* Copy the list of befriending classes.  */
9195         for (friends = &DECL_BEFRIENDING_CLASSES (r);
9196              *friends;
9197              friends = &TREE_CHAIN (*friends))
9198           {
9199             *friends = copy_node (*friends);
9200             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
9201                                             args, complain,
9202                                             in_decl);
9203           }
9204
9205         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
9206           {
9207             maybe_retrofit_in_chrg (r);
9208             if (DECL_CONSTRUCTOR_P (r))
9209               grok_ctor_properties (ctx, r);
9210             /* If this is an instantiation of a member template, clone it.
9211                If it isn't, that'll be handled by
9212                clone_constructors_and_destructors.  */
9213             if (PRIMARY_TEMPLATE_P (gen_tmpl))
9214               clone_function_decl (r, /*update_method_vec_p=*/0);
9215           }
9216         else if ((complain & tf_error) != 0
9217                  && IDENTIFIER_OPNAME_P (DECL_NAME (r))
9218                  && !grok_op_properties (r, /*complain=*/true))
9219           RETURN (error_mark_node);
9220
9221         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
9222           SET_DECL_FRIEND_CONTEXT (r,
9223                                    tsubst (DECL_FRIEND_CONTEXT (t),
9224                                             args, complain, in_decl));
9225
9226         /* Possibly limit visibility based on template args.  */
9227         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
9228         if (DECL_VISIBILITY_SPECIFIED (t))
9229           {
9230             DECL_VISIBILITY_SPECIFIED (r) = 0;
9231             DECL_ATTRIBUTES (r)
9232               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
9233           }
9234         determine_visibility (r);
9235         if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
9236             && !processing_template_decl)
9237           defaulted_late_check (r);
9238
9239         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9240                                         args, complain, in_decl);
9241       }
9242       break;
9243
9244     case PARM_DECL:
9245       {
9246         tree type = NULL_TREE;
9247         int i, len = 1;
9248         tree expanded_types = NULL_TREE;
9249         tree prev_r = NULL_TREE;
9250         tree first_r = NULL_TREE;
9251
9252         if (FUNCTION_PARAMETER_PACK_P (t))
9253           {
9254             /* If there is a local specialization that isn't a
9255                parameter pack, it means that we're doing a "simple"
9256                substitution from inside tsubst_pack_expansion. Just
9257                return the local specialization (which will be a single
9258                parm).  */
9259             tree spec = retrieve_local_specialization (t);
9260             if (spec 
9261                 && TREE_CODE (spec) == PARM_DECL
9262                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
9263               RETURN (spec);
9264
9265             /* Expand the TYPE_PACK_EXPANSION that provides the types for
9266                the parameters in this function parameter pack.  */
9267             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
9268                                                     complain, in_decl);
9269             if (TREE_CODE (expanded_types) == TREE_VEC)
9270               {
9271                 len = TREE_VEC_LENGTH (expanded_types);
9272
9273                 /* Zero-length parameter packs are boring. Just substitute
9274                    into the chain.  */
9275                 if (len == 0)
9276                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
9277                                   TREE_CHAIN (t)));
9278               }
9279             else
9280               {
9281                 /* All we did was update the type. Make a note of that.  */
9282                 type = expanded_types;
9283                 expanded_types = NULL_TREE;
9284               }
9285           }
9286
9287         /* Loop through all of the parameter's we'll build. When T is
9288            a function parameter pack, LEN is the number of expanded
9289            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
9290         r = NULL_TREE;
9291         for (i = 0; i < len; ++i)
9292           {
9293             prev_r = r;
9294             r = copy_node (t);
9295             if (DECL_TEMPLATE_PARM_P (t))
9296               SET_DECL_TEMPLATE_PARM_P (r);
9297
9298             /* An argument of a function parameter pack is not a parameter
9299                pack.  */
9300             FUNCTION_PARAMETER_PACK_P (r) = false;
9301
9302             if (expanded_types)
9303               /* We're on the Ith parameter of the function parameter
9304                  pack.  */
9305               {
9306                 /* Get the Ith type.  */
9307                 type = TREE_VEC_ELT (expanded_types, i);
9308
9309                 if (DECL_NAME (r))
9310                   /* Rename the parameter to include the index.  */
9311                   DECL_NAME (r) =
9312                     make_ith_pack_parameter_name (DECL_NAME (r), i);
9313               }
9314             else if (!type)
9315               /* We're dealing with a normal parameter.  */
9316               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9317
9318             type = type_decays_to (type);
9319             TREE_TYPE (r) = type;
9320             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9321
9322             if (DECL_INITIAL (r))
9323               {
9324                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
9325                   DECL_INITIAL (r) = TREE_TYPE (r);
9326                 else
9327                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
9328                                              complain, in_decl);
9329               }
9330
9331             DECL_CONTEXT (r) = NULL_TREE;
9332
9333             if (!DECL_TEMPLATE_PARM_P (r))
9334               DECL_ARG_TYPE (r) = type_passed_as (type);
9335
9336             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9337                                             args, complain, in_decl);
9338
9339             /* Keep track of the first new parameter we
9340                generate. That's what will be returned to the
9341                caller.  */
9342             if (!first_r)
9343               first_r = r;
9344
9345             /* Build a proper chain of parameters when substituting
9346                into a function parameter pack.  */
9347             if (prev_r)
9348               TREE_CHAIN (prev_r) = r;
9349           }
9350
9351         if (TREE_CHAIN (t))
9352           TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args,
9353                                    complain, TREE_CHAIN (t));
9354
9355         /* FIRST_R contains the start of the chain we've built.  */
9356         r = first_r;
9357       }
9358       break;
9359
9360     case FIELD_DECL:
9361       {
9362         tree type;
9363
9364         r = copy_decl (t);
9365         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9366         if (type == error_mark_node)
9367           RETURN (error_mark_node);
9368         TREE_TYPE (r) = type;
9369         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9370
9371         /* DECL_INITIAL gives the number of bits in a bit-field.  */
9372         DECL_INITIAL (r)
9373           = tsubst_expr (DECL_INITIAL (t), args,
9374                          complain, in_decl,
9375                          /*integral_constant_expression_p=*/true);
9376         /* We don't have to set DECL_CONTEXT here; it is set by
9377            finish_member_declaration.  */
9378         TREE_CHAIN (r) = NULL_TREE;
9379         if (VOID_TYPE_P (type))
9380           error ("instantiation of %q+D as type %qT", r, type);
9381
9382         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9383                                         args, complain, in_decl);
9384       }
9385       break;
9386
9387     case USING_DECL:
9388       /* We reach here only for member using decls.  */
9389       if (DECL_DEPENDENT_P (t))
9390         {
9391           r = do_class_using_decl
9392             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
9393              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
9394           if (!r)
9395             r = error_mark_node;
9396           else
9397             {
9398               TREE_PROTECTED (r) = TREE_PROTECTED (t);
9399               TREE_PRIVATE (r) = TREE_PRIVATE (t);
9400             }
9401         }
9402       else
9403         {
9404           r = copy_node (t);
9405           TREE_CHAIN (r) = NULL_TREE;
9406         }
9407       break;
9408
9409     case TYPE_DECL:
9410     case VAR_DECL:
9411       {
9412         tree argvec = NULL_TREE;
9413         tree gen_tmpl = NULL_TREE;
9414         tree spec;
9415         tree tmpl = NULL_TREE;
9416         tree ctx;
9417         tree type = NULL_TREE;
9418         bool local_p;
9419
9420         if (TREE_CODE (t) == TYPE_DECL
9421             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
9422           {
9423             /* If this is the canonical decl, we don't have to
9424                mess with instantiations, and often we can't (for
9425                typename, template type parms and such).  Note that
9426                TYPE_NAME is not correct for the above test if
9427                we've copied the type for a typedef.  */
9428             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9429             if (type == error_mark_node)
9430               RETURN (error_mark_node);
9431             r = TYPE_NAME (type);
9432             break;
9433           }
9434
9435         /* Check to see if we already have the specialization we
9436            need.  */
9437         spec = NULL_TREE;
9438         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
9439           {
9440             /* T is a static data member or namespace-scope entity.
9441                We have to substitute into namespace-scope variables
9442                (even though such entities are never templates) because
9443                of cases like:
9444                
9445                  template <class T> void f() { extern T t; }
9446
9447                where the entity referenced is not known until
9448                instantiation time.  */
9449             local_p = false;
9450             ctx = DECL_CONTEXT (t);
9451             if (DECL_CLASS_SCOPE_P (t))
9452               {
9453                 ctx = tsubst_aggr_type (ctx, args,
9454                                         complain,
9455                                         in_decl, /*entering_scope=*/1);
9456                 /* If CTX is unchanged, then T is in fact the
9457                    specialization we want.  That situation occurs when
9458                    referencing a static data member within in its own
9459                    class.  We can use pointer equality, rather than
9460                    same_type_p, because DECL_CONTEXT is always
9461                    canonical.  */
9462                 if (ctx == DECL_CONTEXT (t))
9463                   spec = t;
9464               }
9465
9466             if (!spec)
9467               {
9468                 tmpl = DECL_TI_TEMPLATE (t);
9469                 gen_tmpl = most_general_template (tmpl);
9470                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
9471                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
9472                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
9473               }
9474           }
9475         else
9476           {
9477             /* A local variable.  */
9478             local_p = true;
9479             /* Subsequent calls to pushdecl will fill this in.  */
9480             ctx = NULL_TREE;
9481             spec = retrieve_local_specialization (t);
9482           }
9483         /* If we already have the specialization we need, there is
9484            nothing more to do.  */ 
9485         if (spec)
9486           {
9487             r = spec;
9488             break;
9489           }
9490
9491         /* Create a new node for the specialization we need.  */
9492         r = copy_decl (t);
9493         if (type == NULL_TREE)
9494           {
9495             if (is_typedef_decl (t))
9496               type = DECL_ORIGINAL_TYPE (t);
9497             else
9498               type = TREE_TYPE (t);
9499             type = tsubst (type, args, complain, in_decl);
9500           }
9501         if (TREE_CODE (r) == VAR_DECL)
9502           {
9503             /* Even if the original location is out of scope, the
9504                newly substituted one is not.  */
9505             DECL_DEAD_FOR_LOCAL (r) = 0;
9506             DECL_INITIALIZED_P (r) = 0;
9507             DECL_TEMPLATE_INSTANTIATED (r) = 0;
9508             if (type == error_mark_node)
9509               RETURN (error_mark_node);
9510             if (TREE_CODE (type) == FUNCTION_TYPE)
9511               {
9512                 /* It may seem that this case cannot occur, since:
9513
9514                      typedef void f();
9515                      void g() { f x; }
9516
9517                    declares a function, not a variable.  However:
9518       
9519                      typedef void f();
9520                      template <typename T> void g() { T t; }
9521                      template void g<f>();
9522
9523                    is an attempt to declare a variable with function
9524                    type.  */
9525                 error ("variable %qD has function type",
9526                        /* R is not yet sufficiently initialized, so we
9527                           just use its name.  */
9528                        DECL_NAME (r));
9529                 RETURN (error_mark_node);
9530               }
9531             type = complete_type (type);
9532             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
9533               = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t);
9534             type = check_var_type (DECL_NAME (r), type);
9535
9536             if (DECL_HAS_VALUE_EXPR_P (t))
9537               {
9538                 tree ve = DECL_VALUE_EXPR (t);
9539                 ve = tsubst_expr (ve, args, complain, in_decl,
9540                                   /*constant_expression_p=*/false);
9541                 SET_DECL_VALUE_EXPR (r, ve);
9542               }
9543           }
9544         else if (DECL_SELF_REFERENCE_P (t))
9545           SET_DECL_SELF_REFERENCE_P (r);
9546         TREE_TYPE (r) = type;
9547         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9548         DECL_CONTEXT (r) = ctx;
9549         /* Clear out the mangled name and RTL for the instantiation.  */
9550         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9551         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9552           SET_DECL_RTL (r, NULL_RTX);
9553         /* The initializer must not be expanded until it is required;
9554            see [temp.inst].  */
9555         DECL_INITIAL (r) = NULL_TREE;
9556         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9557           SET_DECL_RTL (r, NULL_RTX);
9558         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
9559         if (TREE_CODE (r) == VAR_DECL)
9560           {
9561             /* Possibly limit visibility based on template args.  */
9562             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
9563             if (DECL_VISIBILITY_SPECIFIED (t))
9564               {
9565                 DECL_VISIBILITY_SPECIFIED (r) = 0;
9566                 DECL_ATTRIBUTES (r)
9567                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
9568               }
9569             determine_visibility (r);
9570           }
9571
9572         if (!local_p)
9573           {
9574             /* A static data member declaration is always marked
9575                external when it is declared in-class, even if an
9576                initializer is present.  We mimic the non-template
9577                processing here.  */
9578             DECL_EXTERNAL (r) = 1;
9579
9580             register_specialization (r, gen_tmpl, argvec, false, hash);
9581             DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
9582             SET_DECL_IMPLICIT_INSTANTIATION (r);
9583           }
9584         else if (cp_unevaluated_operand)
9585           {
9586             /* We're substituting this var in a decltype outside of its
9587                scope, such as for a lambda return type.  Don't add it to
9588                local_specializations, do perform auto deduction.  */
9589             tree auto_node = type_uses_auto (type);
9590             tree init
9591               = tsubst_expr (DECL_INITIAL (t), args, complain, in_decl,
9592                              /*constant_expression_p=*/false);
9593
9594             if (auto_node && init && describable_type (init))
9595               {
9596                 type = do_auto_deduction (type, init, auto_node);
9597                 TREE_TYPE (r) = type;
9598               }
9599           }
9600         else
9601           register_local_specialization (r, t);
9602
9603         TREE_CHAIN (r) = NULL_TREE;
9604
9605         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
9606                                         /*flags=*/0,
9607                                         args, complain, in_decl);
9608
9609         /* Preserve a typedef that names a type.  */
9610         if (is_typedef_decl (r))
9611           {
9612             DECL_ORIGINAL_TYPE (r) = NULL_TREE;
9613             set_underlying_type (r);
9614           }
9615
9616         layout_decl (r, 0);
9617       }
9618       break;
9619
9620     default:
9621       gcc_unreachable ();
9622     }
9623 #undef RETURN
9624
9625  out:
9626   /* Restore the file and line information.  */
9627   input_location = saved_loc;
9628
9629   return r;
9630 }
9631
9632 /* Substitute into the ARG_TYPES of a function type.  */
9633
9634 static tree
9635 tsubst_arg_types (tree arg_types,
9636                   tree args,
9637                   tsubst_flags_t complain,
9638                   tree in_decl)
9639 {
9640   tree remaining_arg_types;
9641   tree type = NULL_TREE;
9642   int i = 1;
9643   tree expanded_args = NULL_TREE;
9644   tree default_arg;
9645
9646   if (!arg_types || arg_types == void_list_node)
9647     return arg_types;
9648
9649   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
9650                                           args, complain, in_decl);
9651   if (remaining_arg_types == error_mark_node)
9652     return error_mark_node;
9653
9654   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
9655     {
9656       /* For a pack expansion, perform substitution on the
9657          entire expression. Later on, we'll handle the arguments
9658          one-by-one.  */
9659       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
9660                                             args, complain, in_decl);
9661
9662       if (TREE_CODE (expanded_args) == TREE_VEC)
9663         /* So that we'll spin through the parameters, one by one.  */
9664         i = TREE_VEC_LENGTH (expanded_args);
9665       else
9666         {
9667           /* We only partially substituted into the parameter
9668              pack. Our type is TYPE_PACK_EXPANSION.  */
9669           type = expanded_args;
9670           expanded_args = NULL_TREE;
9671         }
9672     }
9673
9674   while (i > 0) {
9675     --i;
9676     
9677     if (expanded_args)
9678       type = TREE_VEC_ELT (expanded_args, i);
9679     else if (!type)
9680       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
9681
9682     if (type == error_mark_node)
9683       return error_mark_node;
9684     if (VOID_TYPE_P (type))
9685       {
9686         if (complain & tf_error)
9687           {
9688             error ("invalid parameter type %qT", type);
9689             if (in_decl)
9690               error ("in declaration %q+D", in_decl);
9691           }
9692         return error_mark_node;
9693     }
9694     
9695     /* Do array-to-pointer, function-to-pointer conversion, and ignore
9696        top-level qualifiers as required.  */
9697     type = TYPE_MAIN_VARIANT (type_decays_to (type));
9698
9699     /* We do not substitute into default arguments here.  The standard
9700        mandates that they be instantiated only when needed, which is
9701        done in build_over_call.  */
9702     default_arg = TREE_PURPOSE (arg_types);
9703
9704     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
9705       {
9706         /* We've instantiated a template before its default arguments
9707            have been parsed.  This can happen for a nested template
9708            class, and is not an error unless we require the default
9709            argument in a call of this function.  */
9710         remaining_arg_types = 
9711           tree_cons (default_arg, type, remaining_arg_types);
9712         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
9713                        remaining_arg_types);
9714       }
9715     else
9716       remaining_arg_types = 
9717         hash_tree_cons (default_arg, type, remaining_arg_types);
9718   }
9719         
9720   return remaining_arg_types;
9721 }
9722
9723 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
9724    *not* handle the exception-specification for FNTYPE, because the
9725    initial substitution of explicitly provided template parameters
9726    during argument deduction forbids substitution into the
9727    exception-specification:
9728
9729      [temp.deduct]
9730
9731      All references in the function type of the function template to  the
9732      corresponding template parameters are replaced by the specified tem-
9733      plate argument values.  If a substitution in a template parameter or
9734      in  the function type of the function template results in an invalid
9735      type, type deduction fails.  [Note: The equivalent  substitution  in
9736      exception specifications is done only when the function is instanti-
9737      ated, at which point a program is  ill-formed  if  the  substitution
9738      results in an invalid type.]  */
9739
9740 static tree
9741 tsubst_function_type (tree t,
9742                       tree args,
9743                       tsubst_flags_t complain,
9744                       tree in_decl)
9745 {
9746   tree return_type;
9747   tree arg_types;
9748   tree fntype;
9749
9750   /* The TYPE_CONTEXT is not used for function/method types.  */
9751   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
9752
9753   /* Substitute the return type.  */
9754   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9755   if (return_type == error_mark_node)
9756     return error_mark_node;
9757   /* The standard does not presently indicate that creation of a
9758      function type with an invalid return type is a deduction failure.
9759      However, that is clearly analogous to creating an array of "void"
9760      or a reference to a reference.  This is core issue #486.  */
9761   if (TREE_CODE (return_type) == ARRAY_TYPE
9762       || TREE_CODE (return_type) == FUNCTION_TYPE)
9763     {
9764       if (complain & tf_error)
9765         {
9766           if (TREE_CODE (return_type) == ARRAY_TYPE)
9767             error ("function returning an array");
9768           else
9769             error ("function returning a function");
9770         }
9771       return error_mark_node;
9772     }
9773
9774   /* Substitute the argument types.  */
9775   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
9776                                 complain, in_decl);
9777   if (arg_types == error_mark_node)
9778     return error_mark_node;
9779
9780   /* Construct a new type node and return it.  */
9781   if (TREE_CODE (t) == FUNCTION_TYPE)
9782     fntype = build_function_type (return_type, arg_types);
9783   else
9784     {
9785       tree r = TREE_TYPE (TREE_VALUE (arg_types));
9786       if (! MAYBE_CLASS_TYPE_P (r))
9787         {
9788           /* [temp.deduct]
9789
9790              Type deduction may fail for any of the following
9791              reasons:
9792
9793              -- Attempting to create "pointer to member of T" when T
9794              is not a class type.  */
9795           if (complain & tf_error)
9796             error ("creating pointer to member function of non-class type %qT",
9797                       r);
9798           return error_mark_node;
9799         }
9800
9801       fntype = build_method_type_directly (r, return_type,
9802                                            TREE_CHAIN (arg_types));
9803     }
9804   fntype = cp_build_qualified_type_real (fntype, TYPE_QUALS (t), complain);
9805   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
9806
9807   return fntype;
9808 }
9809
9810 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
9811    ARGS into that specification, and return the substituted
9812    specification.  If there is no specification, return NULL_TREE.  */
9813
9814 static tree
9815 tsubst_exception_specification (tree fntype,
9816                                 tree args,
9817                                 tsubst_flags_t complain,
9818                                 tree in_decl)
9819 {
9820   tree specs;
9821   tree new_specs;
9822
9823   specs = TYPE_RAISES_EXCEPTIONS (fntype);
9824   new_specs = NULL_TREE;
9825   if (specs)
9826     {
9827       if (! TREE_VALUE (specs))
9828         new_specs = specs;
9829       else
9830         while (specs)
9831           {
9832             tree spec;
9833             int i, len = 1;
9834             tree expanded_specs = NULL_TREE;
9835
9836             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
9837               {
9838                 /* Expand the pack expansion type.  */
9839                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
9840                                                        args, complain,
9841                                                        in_decl);
9842
9843                 if (expanded_specs == error_mark_node)
9844                   return error_mark_node;
9845                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
9846                   len = TREE_VEC_LENGTH (expanded_specs);
9847                 else
9848                   {
9849                     /* We're substituting into a member template, so
9850                        we got a TYPE_PACK_EXPANSION back.  Add that
9851                        expansion and move on.  */
9852                     gcc_assert (TREE_CODE (expanded_specs) 
9853                                 == TYPE_PACK_EXPANSION);
9854                     new_specs = add_exception_specifier (new_specs,
9855                                                          expanded_specs,
9856                                                          complain);
9857                     specs = TREE_CHAIN (specs);
9858                     continue;
9859                   }
9860               }
9861
9862             for (i = 0; i < len; ++i)
9863               {
9864                 if (expanded_specs)
9865                   spec = TREE_VEC_ELT (expanded_specs, i);
9866                 else
9867                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
9868                 if (spec == error_mark_node)
9869                   return spec;
9870                 new_specs = add_exception_specifier (new_specs, spec, 
9871                                                      complain);
9872               }
9873
9874             specs = TREE_CHAIN (specs);
9875           }
9876     }
9877   return new_specs;
9878 }
9879
9880 /* Take the tree structure T and replace template parameters used
9881    therein with the argument vector ARGS.  IN_DECL is an associated
9882    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
9883    Issue error and warning messages under control of COMPLAIN.  Note
9884    that we must be relatively non-tolerant of extensions here, in
9885    order to preserve conformance; if we allow substitutions that
9886    should not be allowed, we may allow argument deductions that should
9887    not succeed, and therefore report ambiguous overload situations
9888    where there are none.  In theory, we could allow the substitution,
9889    but indicate that it should have failed, and allow our caller to
9890    make sure that the right thing happens, but we don't try to do this
9891    yet.
9892
9893    This function is used for dealing with types, decls and the like;
9894    for expressions, use tsubst_expr or tsubst_copy.  */
9895
9896 tree
9897 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9898 {
9899   tree type, r;
9900
9901   if (t == NULL_TREE || t == error_mark_node
9902       || t == integer_type_node
9903       || t == void_type_node
9904       || t == char_type_node
9905       || t == unknown_type_node
9906       || TREE_CODE (t) == NAMESPACE_DECL)
9907     return t;
9908
9909   if (DECL_P (t))
9910     return tsubst_decl (t, args, complain);
9911
9912   if (args == NULL_TREE)
9913     return t;
9914
9915   if (TREE_CODE (t) == IDENTIFIER_NODE)
9916     type = IDENTIFIER_TYPE_VALUE (t);
9917   else
9918     type = TREE_TYPE (t);
9919
9920   gcc_assert (type != unknown_type_node);
9921
9922   /* Reuse typedefs.  We need to do this to handle dependent attributes,
9923      such as attribute aligned.  */
9924   if (TYPE_P (t)
9925       && TYPE_NAME (t)
9926       && TYPE_NAME (t) != TYPE_MAIN_DECL (t))
9927     {
9928       tree decl = TYPE_NAME (t);
9929       
9930       if (DECL_CLASS_SCOPE_P (decl)
9931           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
9932           && uses_template_parms (DECL_CONTEXT (decl)))
9933         {
9934           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
9935           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
9936           r = retrieve_specialization (tmpl, gen_args, 0);
9937         }
9938       else if (DECL_FUNCTION_SCOPE_P (decl)
9939                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
9940                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
9941         r = retrieve_local_specialization (decl);
9942       else
9943         /* The typedef is from a non-template context.  */
9944         return t;
9945
9946       if (r)
9947         {
9948           r = TREE_TYPE (r);
9949           r = cp_build_qualified_type_real
9950             (r, cp_type_quals (t) | cp_type_quals (r),
9951              complain | tf_ignore_bad_quals);
9952           return r;
9953         }
9954       /* Else we must be instantiating the typedef, so fall through.  */
9955     }
9956
9957   if (type
9958       && TREE_CODE (t) != TYPENAME_TYPE
9959       && TREE_CODE (t) != TEMPLATE_TYPE_PARM
9960       && TREE_CODE (t) != IDENTIFIER_NODE
9961       && TREE_CODE (t) != FUNCTION_TYPE
9962       && TREE_CODE (t) != METHOD_TYPE)
9963     type = tsubst (type, args, complain, in_decl);
9964   if (type == error_mark_node)
9965     return error_mark_node;
9966
9967   switch (TREE_CODE (t))
9968     {
9969     case RECORD_TYPE:
9970     case UNION_TYPE:
9971     case ENUMERAL_TYPE:
9972       return tsubst_aggr_type (t, args, complain, in_decl,
9973                                /*entering_scope=*/0);
9974
9975     case ERROR_MARK:
9976     case IDENTIFIER_NODE:
9977     case VOID_TYPE:
9978     case REAL_TYPE:
9979     case COMPLEX_TYPE:
9980     case VECTOR_TYPE:
9981     case BOOLEAN_TYPE:
9982     case INTEGER_CST:
9983     case REAL_CST:
9984     case STRING_CST:
9985       return t;
9986
9987     case INTEGER_TYPE:
9988       if (t == integer_type_node)
9989         return t;
9990
9991       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
9992           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
9993         return t;
9994
9995       {
9996         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
9997
9998         max = tsubst_expr (omax, args, complain, in_decl,
9999                            /*integral_constant_expression_p=*/false);
10000
10001         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
10002            needed.  */
10003         if (TREE_CODE (max) == NOP_EXPR
10004             && TREE_SIDE_EFFECTS (omax)
10005             && !TREE_TYPE (max))
10006           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
10007
10008         max = fold_decl_constant_value (max);
10009
10010         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
10011            with TREE_SIDE_EFFECTS that indicates this is not an integral
10012            constant expression.  */
10013         if (processing_template_decl
10014             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
10015           {
10016             gcc_assert (TREE_CODE (max) == NOP_EXPR);
10017             TREE_SIDE_EFFECTS (max) = 1;
10018           }
10019
10020         if (TREE_CODE (max) != INTEGER_CST
10021             && !at_function_scope_p ()
10022             && !TREE_SIDE_EFFECTS (max)
10023             && !value_dependent_expression_p (max))
10024           {
10025             if (complain & tf_error)
10026               error ("array bound is not an integer constant");
10027             return error_mark_node;
10028           }
10029
10030         /* [temp.deduct]
10031
10032            Type deduction may fail for any of the following
10033            reasons:
10034
10035              Attempting to create an array with a size that is
10036              zero or negative.  */
10037         if (integer_zerop (max) && !(complain & tf_error))
10038           /* We must fail if performing argument deduction (as
10039              indicated by the state of complain), so that
10040              another substitution can be found.  */
10041           return error_mark_node;
10042         else if (TREE_CODE (max) == INTEGER_CST
10043                  && INT_CST_LT (max, integer_zero_node))
10044           {
10045             if (complain & tf_error)
10046               error ("creating array with negative size (%qE)", max);
10047
10048             return error_mark_node;
10049           }
10050
10051         return compute_array_index_type (NULL_TREE, max);
10052       }
10053
10054     case TEMPLATE_TYPE_PARM:
10055     case TEMPLATE_TEMPLATE_PARM:
10056     case BOUND_TEMPLATE_TEMPLATE_PARM:
10057     case TEMPLATE_PARM_INDEX:
10058       {
10059         int idx;
10060         int level;
10061         int levels;
10062         tree arg = NULL_TREE;
10063
10064         r = NULL_TREE;
10065
10066         gcc_assert (TREE_VEC_LENGTH (args) > 0);
10067         template_parm_level_and_index (t, &level, &idx); 
10068
10069         levels = TMPL_ARGS_DEPTH (args);
10070         if (level <= levels)
10071           {
10072             arg = TMPL_ARG (args, level, idx);
10073
10074             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
10075               /* See through ARGUMENT_PACK_SELECT arguments. */
10076               arg = ARGUMENT_PACK_SELECT_ARG (arg);
10077           }
10078
10079         if (arg == error_mark_node)
10080           return error_mark_node;
10081         else if (arg != NULL_TREE)
10082           {
10083             if (ARGUMENT_PACK_P (arg))
10084               /* If ARG is an argument pack, we don't actually want to
10085                  perform a substitution here, because substitutions
10086                  for argument packs are only done
10087                  element-by-element. We can get to this point when
10088                  substituting the type of a non-type template
10089                  parameter pack, when that type actually contains
10090                  template parameter packs from an outer template, e.g.,
10091
10092                  template<typename... Types> struct A {
10093                    template<Types... Values> struct B { };
10094                  };  */
10095               return t;
10096
10097             if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
10098               {
10099                 int quals;
10100                 gcc_assert (TYPE_P (arg));
10101
10102                 /* cv-quals from the template are discarded when
10103                    substituting in a function or reference type.  */
10104                 if (TREE_CODE (arg) == FUNCTION_TYPE
10105                     || TREE_CODE (arg) == METHOD_TYPE
10106                     || TREE_CODE (arg) == REFERENCE_TYPE)
10107                   quals = cp_type_quals (arg);
10108                 else
10109                   quals = cp_type_quals (arg) | cp_type_quals (t);
10110                   
10111                 return cp_build_qualified_type_real
10112                   (arg, quals, complain | tf_ignore_bad_quals);
10113               }
10114             else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
10115               {
10116                 /* We are processing a type constructed from a
10117                    template template parameter.  */
10118                 tree argvec = tsubst (TYPE_TI_ARGS (t),
10119                                       args, complain, in_decl);
10120                 if (argvec == error_mark_node)
10121                   return error_mark_node;
10122
10123                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
10124                    are resolving nested-types in the signature of a
10125                    member function templates.  Otherwise ARG is a
10126                    TEMPLATE_DECL and is the real template to be
10127                    instantiated.  */
10128                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
10129                   arg = TYPE_NAME (arg);
10130
10131                 r = lookup_template_class (arg,
10132                                            argvec, in_decl,
10133                                            DECL_CONTEXT (arg),
10134                                             /*entering_scope=*/0,
10135                                            complain);
10136                 return cp_build_qualified_type_real
10137                   (r, TYPE_QUALS (t), complain);
10138               }
10139             else
10140               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
10141               return arg;
10142           }
10143
10144         if (level == 1)
10145           /* This can happen during the attempted tsubst'ing in
10146              unify.  This means that we don't yet have any information
10147              about the template parameter in question.  */
10148           return t;
10149
10150         /* If we get here, we must have been looking at a parm for a
10151            more deeply nested template.  Make a new version of this
10152            template parameter, but with a lower level.  */
10153         switch (TREE_CODE (t))
10154           {
10155           case TEMPLATE_TYPE_PARM:
10156           case TEMPLATE_TEMPLATE_PARM:
10157           case BOUND_TEMPLATE_TEMPLATE_PARM:
10158             if (cp_type_quals (t))
10159               {
10160                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
10161                 r = cp_build_qualified_type_real
10162                   (r, cp_type_quals (t),
10163                    complain | (TREE_CODE (t) == TEMPLATE_TYPE_PARM
10164                                ? tf_ignore_bad_quals : 0));
10165               }
10166             else
10167               {
10168                 r = copy_type (t);
10169                 TEMPLATE_TYPE_PARM_INDEX (r)
10170                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
10171                                                 r, levels, args, complain);
10172                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
10173                 TYPE_MAIN_VARIANT (r) = r;
10174                 TYPE_POINTER_TO (r) = NULL_TREE;
10175                 TYPE_REFERENCE_TO (r) = NULL_TREE;
10176
10177                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
10178                   /* We have reduced the level of the template
10179                      template parameter, but not the levels of its
10180                      template parameters, so canonical_type_parameter
10181                      will not be able to find the canonical template
10182                      template parameter for this level. Thus, we
10183                      require structural equality checking to compare
10184                      TEMPLATE_TEMPLATE_PARMs. */
10185                   SET_TYPE_STRUCTURAL_EQUALITY (r);
10186                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
10187                   SET_TYPE_STRUCTURAL_EQUALITY (r);
10188                 else
10189                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
10190
10191                 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
10192                   {
10193                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
10194                                           complain, in_decl);
10195                     if (argvec == error_mark_node)
10196                       return error_mark_node;
10197
10198                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
10199                       = build_template_info (TYPE_TI_TEMPLATE (t), argvec);
10200                   }
10201               }
10202             break;
10203
10204           case TEMPLATE_PARM_INDEX:
10205             r = reduce_template_parm_level (t, type, levels, args, complain);
10206             break;
10207
10208           default:
10209             gcc_unreachable ();
10210           }
10211
10212         return r;
10213       }
10214
10215     case TREE_LIST:
10216       {
10217         tree purpose, value, chain;
10218
10219         if (t == void_list_node)
10220           return t;
10221
10222         purpose = TREE_PURPOSE (t);
10223         if (purpose)
10224           {
10225             purpose = tsubst (purpose, args, complain, in_decl);
10226             if (purpose == error_mark_node)
10227               return error_mark_node;
10228           }
10229         value = TREE_VALUE (t);
10230         if (value)
10231           {
10232             value = tsubst (value, args, complain, in_decl);
10233             if (value == error_mark_node)
10234               return error_mark_node;
10235           }
10236         chain = TREE_CHAIN (t);
10237         if (chain && chain != void_type_node)
10238           {
10239             chain = tsubst (chain, args, complain, in_decl);
10240             if (chain == error_mark_node)
10241               return error_mark_node;
10242           }
10243         if (purpose == TREE_PURPOSE (t)
10244             && value == TREE_VALUE (t)
10245             && chain == TREE_CHAIN (t))
10246           return t;
10247         return hash_tree_cons (purpose, value, chain);
10248       }
10249
10250     case TREE_BINFO:
10251       /* We should never be tsubsting a binfo.  */
10252       gcc_unreachable ();
10253
10254     case TREE_VEC:
10255       /* A vector of template arguments.  */
10256       gcc_assert (!type);
10257       return tsubst_template_args (t, args, complain, in_decl);
10258
10259     case POINTER_TYPE:
10260     case REFERENCE_TYPE:
10261       {
10262         enum tree_code code;
10263
10264         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
10265           return t;
10266
10267         code = TREE_CODE (t);
10268
10269
10270         /* [temp.deduct]
10271
10272            Type deduction may fail for any of the following
10273            reasons:
10274
10275            -- Attempting to create a pointer to reference type.
10276            -- Attempting to create a reference to a reference type or
10277               a reference to void.
10278
10279           Core issue 106 says that creating a reference to a reference
10280           during instantiation is no longer a cause for failure. We
10281           only enforce this check in strict C++98 mode.  */
10282         if ((TREE_CODE (type) == REFERENCE_TYPE
10283              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
10284             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
10285           {
10286             static location_t last_loc;
10287
10288             /* We keep track of the last time we issued this error
10289                message to avoid spewing a ton of messages during a
10290                single bad template instantiation.  */
10291             if (complain & tf_error
10292                 && last_loc != input_location)
10293               {
10294                 if (TREE_CODE (type) == VOID_TYPE)
10295                   error ("forming reference to void");
10296                else if (code == POINTER_TYPE)
10297                  error ("forming pointer to reference type %qT", type);
10298                else
10299                   error ("forming reference to reference type %qT", type);
10300                 last_loc = input_location;
10301               }
10302
10303             return error_mark_node;
10304           }
10305         else if (code == POINTER_TYPE)
10306           {
10307             r = build_pointer_type (type);
10308             if (TREE_CODE (type) == METHOD_TYPE)
10309               r = build_ptrmemfunc_type (r);
10310           }
10311         else if (TREE_CODE (type) == REFERENCE_TYPE)
10312           /* In C++0x, during template argument substitution, when there is an
10313              attempt to create a reference to a reference type, reference
10314              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
10315
10316              "If a template-argument for a template-parameter T names a type
10317              that is a reference to a type A, an attempt to create the type
10318              'lvalue reference to cv T' creates the type 'lvalue reference to
10319              A,' while an attempt to create the type type rvalue reference to
10320              cv T' creates the type T"
10321           */
10322           r = cp_build_reference_type
10323               (TREE_TYPE (type),
10324                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
10325         else
10326           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
10327         r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
10328
10329         if (r != error_mark_node)
10330           /* Will this ever be needed for TYPE_..._TO values?  */
10331           layout_type (r);
10332
10333         return r;
10334       }
10335     case OFFSET_TYPE:
10336       {
10337         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
10338         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
10339           {
10340             /* [temp.deduct]
10341
10342                Type deduction may fail for any of the following
10343                reasons:
10344
10345                -- Attempting to create "pointer to member of T" when T
10346                   is not a class type.  */
10347             if (complain & tf_error)
10348               error ("creating pointer to member of non-class type %qT", r);
10349             return error_mark_node;
10350           }
10351         if (TREE_CODE (type) == REFERENCE_TYPE)
10352           {
10353             if (complain & tf_error)
10354               error ("creating pointer to member reference type %qT", type);
10355             return error_mark_node;
10356           }
10357         if (TREE_CODE (type) == VOID_TYPE)
10358           {
10359             if (complain & tf_error)
10360               error ("creating pointer to member of type void");
10361             return error_mark_node;
10362           }
10363         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
10364         if (TREE_CODE (type) == FUNCTION_TYPE)
10365           {
10366             /* The type of the implicit object parameter gets its
10367                cv-qualifiers from the FUNCTION_TYPE. */
10368             tree memptr;
10369             tree method_type = build_memfn_type (type, r, cp_type_quals (type));
10370             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
10371             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
10372                                                  complain);
10373           }
10374         else
10375           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
10376                                                TYPE_QUALS (t),
10377                                                complain);
10378       }
10379     case FUNCTION_TYPE:
10380     case METHOD_TYPE:
10381       {
10382         tree fntype;
10383         tree specs;
10384         fntype = tsubst_function_type (t, args, complain, in_decl);
10385         if (fntype == error_mark_node)
10386           return error_mark_node;
10387
10388         /* Substitute the exception specification.  */
10389         specs = tsubst_exception_specification (t, args, complain,
10390                                                 in_decl);
10391         if (specs == error_mark_node)
10392           return error_mark_node;
10393         if (specs)
10394           fntype = build_exception_variant (fntype, specs);
10395         return fntype;
10396       }
10397     case ARRAY_TYPE:
10398       {
10399         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
10400         if (domain == error_mark_node)
10401           return error_mark_node;
10402
10403         /* As an optimization, we avoid regenerating the array type if
10404            it will obviously be the same as T.  */
10405         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
10406           return t;
10407
10408         /* These checks should match the ones in grokdeclarator.
10409
10410            [temp.deduct]
10411
10412            The deduction may fail for any of the following reasons:
10413
10414            -- Attempting to create an array with an element type that
10415               is void, a function type, or a reference type, or [DR337]
10416               an abstract class type.  */
10417         if (TREE_CODE (type) == VOID_TYPE
10418             || TREE_CODE (type) == FUNCTION_TYPE
10419             || TREE_CODE (type) == REFERENCE_TYPE)
10420           {
10421             if (complain & tf_error)
10422               error ("creating array of %qT", type);
10423             return error_mark_node;
10424           }
10425         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
10426           {
10427             if (complain & tf_error)
10428               error ("creating array of %qT, which is an abstract class type",
10429                      type);
10430             return error_mark_node;
10431           }
10432
10433         r = build_cplus_array_type (type, domain);
10434
10435         if (TYPE_USER_ALIGN (t))
10436           {
10437             TYPE_ALIGN (r) = TYPE_ALIGN (t);
10438             TYPE_USER_ALIGN (r) = 1;
10439           }
10440
10441         return r;
10442       }
10443
10444     case PLUS_EXPR:
10445     case MINUS_EXPR:
10446       {
10447         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10448         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
10449
10450         if (e1 == error_mark_node || e2 == error_mark_node)
10451           return error_mark_node;
10452
10453         return fold_build2_loc (input_location,
10454                             TREE_CODE (t), TREE_TYPE (t), e1, e2);
10455       }
10456
10457     case NEGATE_EXPR:
10458     case NOP_EXPR:
10459       {
10460         tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10461         if (e == error_mark_node)
10462           return error_mark_node;
10463
10464         return fold_build1_loc (input_location, TREE_CODE (t), TREE_TYPE (t), e);
10465       }
10466
10467     case TYPENAME_TYPE:
10468       {
10469         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10470                                      in_decl, /*entering_scope=*/1);
10471         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
10472                               complain, in_decl);
10473
10474         if (ctx == error_mark_node || f == error_mark_node)
10475           return error_mark_node;
10476
10477         if (!MAYBE_CLASS_TYPE_P (ctx))
10478           {
10479             if (complain & tf_error)
10480               error ("%qT is not a class, struct, or union type", ctx);
10481             return error_mark_node;
10482           }
10483         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
10484           {
10485             /* Normally, make_typename_type does not require that the CTX
10486                have complete type in order to allow things like:
10487
10488                  template <class T> struct S { typename S<T>::X Y; };
10489
10490                But, such constructs have already been resolved by this
10491                point, so here CTX really should have complete type, unless
10492                it's a partial instantiation.  */
10493             if (!(complain & tf_no_class_instantiations))
10494               ctx = complete_type (ctx);
10495             if (!COMPLETE_TYPE_P (ctx))
10496               {
10497                 if (complain & tf_error)
10498                   cxx_incomplete_type_error (NULL_TREE, ctx);
10499                 return error_mark_node;
10500               }
10501           }
10502
10503         f = make_typename_type (ctx, f, typename_type,
10504                                 (complain & tf_error) | tf_keep_type_decl);
10505         if (f == error_mark_node)
10506           return f;
10507         if (TREE_CODE (f) == TYPE_DECL)
10508           {
10509             complain |= tf_ignore_bad_quals;
10510             f = TREE_TYPE (f);
10511           }
10512
10513         if (TREE_CODE (f) != TYPENAME_TYPE)
10514           {
10515             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
10516               error ("%qT resolves to %qT, which is not an enumeration type",
10517                      t, f);
10518             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
10519               error ("%qT resolves to %qT, which is is not a class type",
10520                      t, f);
10521           }
10522
10523         return cp_build_qualified_type_real
10524           (f, cp_type_quals (f) | cp_type_quals (t), complain);
10525       }
10526
10527     case UNBOUND_CLASS_TEMPLATE:
10528       {
10529         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10530                                      in_decl, /*entering_scope=*/1);
10531         tree name = TYPE_IDENTIFIER (t);
10532         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
10533
10534         if (ctx == error_mark_node || name == error_mark_node)
10535           return error_mark_node;
10536
10537         if (parm_list)
10538           parm_list = tsubst_template_parms (parm_list, args, complain);
10539         return make_unbound_class_template (ctx, name, parm_list, complain);
10540       }
10541
10542     case INDIRECT_REF:
10543     case ADDR_EXPR:
10544     case CALL_EXPR:
10545       gcc_unreachable ();
10546
10547     case ARRAY_REF:
10548       {
10549         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10550         tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl,
10551                                /*integral_constant_expression_p=*/false);
10552         if (e1 == error_mark_node || e2 == error_mark_node)
10553           return error_mark_node;
10554
10555         return build_nt (ARRAY_REF, e1, e2, NULL_TREE, NULL_TREE);
10556       }
10557
10558     case SCOPE_REF:
10559       {
10560         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10561         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
10562         if (e1 == error_mark_node || e2 == error_mark_node)
10563           return error_mark_node;
10564
10565         return build_qualified_name (/*type=*/NULL_TREE,
10566                                      e1, e2, QUALIFIED_NAME_IS_TEMPLATE (t));
10567       }
10568
10569     case TYPEOF_TYPE:
10570       {
10571         tree type;
10572
10573         ++cp_unevaluated_operand;
10574         ++c_inhibit_evaluation_warnings;
10575
10576         type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
10577                             complain, in_decl,
10578                             /*integral_constant_expression_p=*/false);
10579
10580         --cp_unevaluated_operand;
10581         --c_inhibit_evaluation_warnings;
10582
10583         type = finish_typeof (type);
10584         return cp_build_qualified_type_real (type,
10585                                              cp_type_quals (t)
10586                                              | cp_type_quals (type),
10587                                              complain);
10588       }
10589
10590     case DECLTYPE_TYPE:
10591       {
10592         tree type;
10593
10594         ++cp_unevaluated_operand;
10595         ++c_inhibit_evaluation_warnings;
10596
10597         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
10598                             complain, in_decl,
10599                             /*integral_constant_expression_p=*/false);
10600
10601         --cp_unevaluated_operand;
10602         --c_inhibit_evaluation_warnings;
10603
10604         if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
10605           type = lambda_capture_field_type (type);
10606         else if (DECLTYPE_FOR_LAMBDA_RETURN (t))
10607           type = lambda_return_type (type);
10608         else
10609           type = finish_decltype_type
10610             (type, DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
10611         return cp_build_qualified_type_real (type,
10612                                              cp_type_quals (t)
10613                                              | cp_type_quals (type),
10614                                              complain);
10615       }
10616
10617     case TYPE_ARGUMENT_PACK:
10618     case NONTYPE_ARGUMENT_PACK:
10619       {
10620         tree r = TYPE_P (t)
10621           ? cxx_make_type (TREE_CODE (t))
10622           : make_node (TREE_CODE (t));
10623         tree packed_out = 
10624           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
10625                                 args,
10626                                 complain,
10627                                 in_decl);
10628         SET_ARGUMENT_PACK_ARGS (r, packed_out);
10629
10630         /* For template nontype argument packs, also substitute into
10631            the type.  */
10632         if (TREE_CODE (t) == NONTYPE_ARGUMENT_PACK)
10633           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
10634
10635         return r;
10636       }
10637       break;
10638
10639     default:
10640       sorry ("use of %qs in template",
10641              tree_code_name [(int) TREE_CODE (t)]);
10642       return error_mark_node;
10643     }
10644 }
10645
10646 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
10647    type of the expression on the left-hand side of the "." or "->"
10648    operator.  */
10649
10650 static tree
10651 tsubst_baselink (tree baselink, tree object_type,
10652                  tree args, tsubst_flags_t complain, tree in_decl)
10653 {
10654     tree name;
10655     tree qualifying_scope;
10656     tree fns;
10657     tree optype;
10658     tree template_args = 0;
10659     bool template_id_p = false;
10660
10661     /* A baselink indicates a function from a base class.  Both the
10662        BASELINK_ACCESS_BINFO and the base class referenced may
10663        indicate bases of the template class, rather than the
10664        instantiated class.  In addition, lookups that were not
10665        ambiguous before may be ambiguous now.  Therefore, we perform
10666        the lookup again.  */
10667     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
10668     qualifying_scope = tsubst (qualifying_scope, args,
10669                                complain, in_decl);
10670     fns = BASELINK_FUNCTIONS (baselink);
10671     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
10672     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
10673       {
10674         template_id_p = true;
10675         template_args = TREE_OPERAND (fns, 1);
10676         fns = TREE_OPERAND (fns, 0);
10677         if (template_args)
10678           template_args = tsubst_template_args (template_args, args,
10679                                                 complain, in_decl);
10680       }
10681     name = DECL_NAME (get_first_fn (fns));
10682     if (IDENTIFIER_TYPENAME_P (name))
10683       name = mangle_conv_op_name_for_type (optype);
10684     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
10685
10686     /* If lookup found a single function, mark it as used at this
10687        point.  (If it lookup found multiple functions the one selected
10688        later by overload resolution will be marked as used at that
10689        point.)  */
10690     if (BASELINK_P (baselink))
10691       fns = BASELINK_FUNCTIONS (baselink);
10692     if (!template_id_p && !really_overloaded_fn (fns))
10693       mark_used (OVL_CURRENT (fns));
10694
10695     /* Add back the template arguments, if present.  */
10696     if (BASELINK_P (baselink) && template_id_p)
10697       BASELINK_FUNCTIONS (baselink)
10698         = build_nt (TEMPLATE_ID_EXPR,
10699                     BASELINK_FUNCTIONS (baselink),
10700                     template_args);
10701     /* Update the conversion operator type.  */
10702     BASELINK_OPTYPE (baselink) = optype;
10703
10704     if (!object_type)
10705       object_type = current_class_type;
10706     return adjust_result_of_qualified_name_lookup (baselink,
10707                                                    qualifying_scope,
10708                                                    object_type);
10709 }
10710
10711 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
10712    true if the qualified-id will be a postfix-expression in-and-of
10713    itself; false if more of the postfix-expression follows the
10714    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
10715    of "&".  */
10716
10717 static tree
10718 tsubst_qualified_id (tree qualified_id, tree args,
10719                      tsubst_flags_t complain, tree in_decl,
10720                      bool done, bool address_p)
10721 {
10722   tree expr;
10723   tree scope;
10724   tree name;
10725   bool is_template;
10726   tree template_args;
10727
10728   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
10729
10730   /* Figure out what name to look up.  */
10731   name = TREE_OPERAND (qualified_id, 1);
10732   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
10733     {
10734       is_template = true;
10735       template_args = TREE_OPERAND (name, 1);
10736       if (template_args)
10737         template_args = tsubst_template_args (template_args, args,
10738                                               complain, in_decl);
10739       name = TREE_OPERAND (name, 0);
10740     }
10741   else
10742     {
10743       is_template = false;
10744       template_args = NULL_TREE;
10745     }
10746
10747   /* Substitute into the qualifying scope.  When there are no ARGS, we
10748      are just trying to simplify a non-dependent expression.  In that
10749      case the qualifying scope may be dependent, and, in any case,
10750      substituting will not help.  */
10751   scope = TREE_OPERAND (qualified_id, 0);
10752   if (args)
10753     {
10754       scope = tsubst (scope, args, complain, in_decl);
10755       expr = tsubst_copy (name, args, complain, in_decl);
10756     }
10757   else
10758     expr = name;
10759
10760   if (dependent_scope_p (scope))
10761     return build_qualified_name (NULL_TREE, scope, expr,
10762                                  QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
10763
10764   if (!BASELINK_P (name) && !DECL_P (expr))
10765     {
10766       if (TREE_CODE (expr) == BIT_NOT_EXPR)
10767         {
10768           /* A BIT_NOT_EXPR is used to represent a destructor.  */
10769           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
10770             {
10771               error ("qualifying type %qT does not match destructor name ~%qT",
10772                      scope, TREE_OPERAND (expr, 0));
10773               expr = error_mark_node;
10774             }
10775           else
10776             expr = lookup_qualified_name (scope, complete_dtor_identifier,
10777                                           /*is_type_p=*/0, false);
10778         }
10779       else
10780         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
10781       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
10782                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
10783         {
10784           if (complain & tf_error)
10785             {
10786               error ("dependent-name %qE is parsed as a non-type, but "
10787                      "instantiation yields a type", qualified_id);
10788               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
10789             }
10790           return error_mark_node;
10791         }
10792     }
10793
10794   if (DECL_P (expr))
10795     {
10796       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
10797                                            scope);
10798       /* Remember that there was a reference to this entity.  */
10799       mark_used (expr);
10800     }
10801
10802   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
10803     {
10804       if (complain & tf_error)
10805         qualified_name_lookup_error (scope,
10806                                      TREE_OPERAND (qualified_id, 1),
10807                                      expr, input_location);
10808       return error_mark_node;
10809     }
10810
10811   if (is_template)
10812     expr = lookup_template_function (expr, template_args);
10813
10814   if (expr == error_mark_node && complain & tf_error)
10815     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
10816                                  expr, input_location);
10817   else if (TYPE_P (scope))
10818     {
10819       expr = (adjust_result_of_qualified_name_lookup
10820               (expr, scope, current_class_type));
10821       expr = (finish_qualified_id_expr
10822               (scope, expr, done, address_p,
10823                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
10824                /*template_arg_p=*/false));
10825     }
10826
10827   /* Expressions do not generally have reference type.  */
10828   if (TREE_CODE (expr) != SCOPE_REF
10829       /* However, if we're about to form a pointer-to-member, we just
10830          want the referenced member referenced.  */
10831       && TREE_CODE (expr) != OFFSET_REF)
10832     expr = convert_from_reference (expr);
10833
10834   return expr;
10835 }
10836
10837 /* Like tsubst, but deals with expressions.  This function just replaces
10838    template parms; to finish processing the resultant expression, use
10839    tsubst_expr.  */
10840
10841 static tree
10842 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10843 {
10844   enum tree_code code;
10845   tree r;
10846
10847   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
10848     return t;
10849
10850   code = TREE_CODE (t);
10851
10852   switch (code)
10853     {
10854     case PARM_DECL:
10855       r = retrieve_local_specialization (t);
10856
10857       if (r == NULL)
10858         {
10859           tree c;
10860           /* This can happen for a parameter name used later in a function
10861              declaration (such as in a late-specified return type).  Just
10862              make a dummy decl, since it's only used for its type.  */
10863           gcc_assert (cp_unevaluated_operand != 0);
10864           /* We copy T because want to tsubst the PARM_DECL only,
10865              not the following PARM_DECLs that are chained to T.  */
10866           c = copy_node (t);
10867           r = tsubst_decl (c, args, complain);
10868           /* Give it the template pattern as its context; its true context
10869              hasn't been instantiated yet and this is good enough for
10870              mangling.  */
10871           DECL_CONTEXT (r) = DECL_CONTEXT (t);
10872         }
10873       
10874       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
10875         r = ARGUMENT_PACK_SELECT_ARG (r);
10876       mark_used (r);
10877       return r;
10878
10879     case CONST_DECL:
10880       {
10881         tree enum_type;
10882         tree v;
10883
10884         if (DECL_TEMPLATE_PARM_P (t))
10885           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
10886         /* There is no need to substitute into namespace-scope
10887            enumerators.  */
10888         if (DECL_NAMESPACE_SCOPE_P (t))
10889           return t;
10890         /* If ARGS is NULL, then T is known to be non-dependent.  */
10891         if (args == NULL_TREE)
10892           return integral_constant_value (t);
10893
10894         /* Unfortunately, we cannot just call lookup_name here.
10895            Consider:
10896
10897              template <int I> int f() {
10898              enum E { a = I };
10899              struct S { void g() { E e = a; } };
10900              };
10901
10902            When we instantiate f<7>::S::g(), say, lookup_name is not
10903            clever enough to find f<7>::a.  */
10904         enum_type
10905           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
10906                               /*entering_scope=*/0);
10907
10908         for (v = TYPE_VALUES (enum_type);
10909              v != NULL_TREE;
10910              v = TREE_CHAIN (v))
10911           if (TREE_PURPOSE (v) == DECL_NAME (t))
10912             return TREE_VALUE (v);
10913
10914           /* We didn't find the name.  That should never happen; if
10915              name-lookup found it during preliminary parsing, we
10916              should find it again here during instantiation.  */
10917         gcc_unreachable ();
10918       }
10919       return t;
10920
10921     case FIELD_DECL:
10922       if (DECL_CONTEXT (t))
10923         {
10924           tree ctx;
10925
10926           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
10927                                   /*entering_scope=*/1);
10928           if (ctx != DECL_CONTEXT (t))
10929             {
10930               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
10931               if (!r)
10932                 {
10933                   if (complain & tf_error)
10934                     error ("using invalid field %qD", t);
10935                   return error_mark_node;
10936                 }
10937               return r;
10938             }
10939         }
10940
10941       return t;
10942
10943     case VAR_DECL:
10944     case FUNCTION_DECL:
10945       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10946           || local_variable_p (t))
10947         t = tsubst (t, args, complain, in_decl);
10948       mark_used (t);
10949       return t;
10950
10951     case BASELINK:
10952       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
10953
10954     case TEMPLATE_DECL:
10955       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10956         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
10957                        args, complain, in_decl);
10958       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
10959         return tsubst (t, args, complain, in_decl);
10960       else if (DECL_CLASS_SCOPE_P (t)
10961                && uses_template_parms (DECL_CONTEXT (t)))
10962         {
10963           /* Template template argument like the following example need
10964              special treatment:
10965
10966                template <template <class> class TT> struct C {};
10967                template <class T> struct D {
10968                  template <class U> struct E {};
10969                  C<E> c;                                // #1
10970                };
10971                D<int> d;                                // #2
10972
10973              We are processing the template argument `E' in #1 for
10974              the template instantiation #2.  Originally, `E' is a
10975              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
10976              have to substitute this with one having context `D<int>'.  */
10977
10978           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
10979           return lookup_field (context, DECL_NAME(t), 0, false);
10980         }
10981       else
10982         /* Ordinary template template argument.  */
10983         return t;
10984
10985     case CAST_EXPR:
10986     case REINTERPRET_CAST_EXPR:
10987     case CONST_CAST_EXPR:
10988     case STATIC_CAST_EXPR:
10989     case DYNAMIC_CAST_EXPR:
10990     case NOP_EXPR:
10991       return build1
10992         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10993          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10994
10995     case SIZEOF_EXPR:
10996       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
10997         {
10998           /* We only want to compute the number of arguments.  */
10999           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
11000                                                 complain, in_decl);
11001           int len = 0;
11002
11003           if (TREE_CODE (expanded) == TREE_VEC)
11004             len = TREE_VEC_LENGTH (expanded);
11005
11006           if (expanded == error_mark_node)
11007             return error_mark_node;
11008           else if (PACK_EXPANSION_P (expanded)
11009                    || (TREE_CODE (expanded) == TREE_VEC
11010                        && len > 0
11011                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
11012             {
11013               if (TREE_CODE (expanded) == TREE_VEC)
11014                 expanded = TREE_VEC_ELT (expanded, len - 1);
11015
11016               if (TYPE_P (expanded))
11017                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
11018                                                    complain & tf_error);
11019               else
11020                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
11021                                                    complain & tf_error);
11022             }
11023           else
11024             return build_int_cst (size_type_node, len);
11025         }
11026       /* Fall through */
11027
11028     case INDIRECT_REF:
11029     case NEGATE_EXPR:
11030     case TRUTH_NOT_EXPR:
11031     case BIT_NOT_EXPR:
11032     case ADDR_EXPR:
11033     case UNARY_PLUS_EXPR:      /* Unary + */
11034     case ALIGNOF_EXPR:
11035     case ARROW_EXPR:
11036     case THROW_EXPR:
11037     case TYPEID_EXPR:
11038     case REALPART_EXPR:
11039     case IMAGPART_EXPR:
11040       return build1
11041         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11042          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11043
11044     case COMPONENT_REF:
11045       {
11046         tree object;
11047         tree name;
11048
11049         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
11050         name = TREE_OPERAND (t, 1);
11051         if (TREE_CODE (name) == BIT_NOT_EXPR)
11052           {
11053             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11054                                 complain, in_decl);
11055             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11056           }
11057         else if (TREE_CODE (name) == SCOPE_REF
11058                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
11059           {
11060             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
11061                                      complain, in_decl);
11062             name = TREE_OPERAND (name, 1);
11063             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11064                                 complain, in_decl);
11065             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11066             name = build_qualified_name (/*type=*/NULL_TREE,
11067                                          base, name,
11068                                          /*template_p=*/false);
11069           }
11070         else if (TREE_CODE (name) == BASELINK)
11071           name = tsubst_baselink (name,
11072                                   non_reference (TREE_TYPE (object)),
11073                                   args, complain,
11074                                   in_decl);
11075         else
11076           name = tsubst_copy (name, args, complain, in_decl);
11077         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
11078       }
11079
11080     case PLUS_EXPR:
11081     case MINUS_EXPR:
11082     case MULT_EXPR:
11083     case TRUNC_DIV_EXPR:
11084     case CEIL_DIV_EXPR:
11085     case FLOOR_DIV_EXPR:
11086     case ROUND_DIV_EXPR:
11087     case EXACT_DIV_EXPR:
11088     case BIT_AND_EXPR:
11089     case BIT_IOR_EXPR:
11090     case BIT_XOR_EXPR:
11091     case TRUNC_MOD_EXPR:
11092     case FLOOR_MOD_EXPR:
11093     case TRUTH_ANDIF_EXPR:
11094     case TRUTH_ORIF_EXPR:
11095     case TRUTH_AND_EXPR:
11096     case TRUTH_OR_EXPR:
11097     case RSHIFT_EXPR:
11098     case LSHIFT_EXPR:
11099     case RROTATE_EXPR:
11100     case LROTATE_EXPR:
11101     case EQ_EXPR:
11102     case NE_EXPR:
11103     case MAX_EXPR:
11104     case MIN_EXPR:
11105     case LE_EXPR:
11106     case GE_EXPR:
11107     case LT_EXPR:
11108     case GT_EXPR:
11109     case COMPOUND_EXPR:
11110     case DOTSTAR_EXPR:
11111     case MEMBER_REF:
11112     case PREDECREMENT_EXPR:
11113     case PREINCREMENT_EXPR:
11114     case POSTDECREMENT_EXPR:
11115     case POSTINCREMENT_EXPR:
11116       return build_nt
11117         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11118          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11119
11120     case SCOPE_REF:
11121       return build_qualified_name (/*type=*/NULL_TREE,
11122                                    tsubst_copy (TREE_OPERAND (t, 0),
11123                                                 args, complain, in_decl),
11124                                    tsubst_copy (TREE_OPERAND (t, 1),
11125                                                 args, complain, in_decl),
11126                                    QUALIFIED_NAME_IS_TEMPLATE (t));
11127
11128     case ARRAY_REF:
11129       return build_nt
11130         (ARRAY_REF,
11131          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11132          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11133          NULL_TREE, NULL_TREE);
11134
11135     case CALL_EXPR:
11136       {
11137         int n = VL_EXP_OPERAND_LENGTH (t);
11138         tree result = build_vl_exp (CALL_EXPR, n);
11139         int i;
11140         for (i = 0; i < n; i++)
11141           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
11142                                              complain, in_decl);
11143         return result;
11144       }
11145
11146     case COND_EXPR:
11147     case MODOP_EXPR:
11148     case PSEUDO_DTOR_EXPR:
11149       {
11150         r = build_nt
11151           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11152            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11153            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
11154         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
11155         return r;
11156       }
11157
11158     case NEW_EXPR:
11159       {
11160         r = build_nt
11161         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11162          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11163          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
11164         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
11165         return r;
11166       }
11167
11168     case DELETE_EXPR:
11169       {
11170         r = build_nt
11171         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11172          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11173         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
11174         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
11175         return r;
11176       }
11177
11178     case TEMPLATE_ID_EXPR:
11179       {
11180         /* Substituted template arguments */
11181         tree fn = TREE_OPERAND (t, 0);
11182         tree targs = TREE_OPERAND (t, 1);
11183
11184         fn = tsubst_copy (fn, args, complain, in_decl);
11185         if (targs)
11186           targs = tsubst_template_args (targs, args, complain, in_decl);
11187
11188         return lookup_template_function (fn, targs);
11189       }
11190
11191     case TREE_LIST:
11192       {
11193         tree purpose, value, chain;
11194
11195         if (t == void_list_node)
11196           return t;
11197
11198         purpose = TREE_PURPOSE (t);
11199         if (purpose)
11200           purpose = tsubst_copy (purpose, args, complain, in_decl);
11201         value = TREE_VALUE (t);
11202         if (value)
11203           value = tsubst_copy (value, args, complain, in_decl);
11204         chain = TREE_CHAIN (t);
11205         if (chain && chain != void_type_node)
11206           chain = tsubst_copy (chain, args, complain, in_decl);
11207         if (purpose == TREE_PURPOSE (t)
11208             && value == TREE_VALUE (t)
11209             && chain == TREE_CHAIN (t))
11210           return t;
11211         return tree_cons (purpose, value, chain);
11212       }
11213
11214     case RECORD_TYPE:
11215     case UNION_TYPE:
11216     case ENUMERAL_TYPE:
11217     case INTEGER_TYPE:
11218     case TEMPLATE_TYPE_PARM:
11219     case TEMPLATE_TEMPLATE_PARM:
11220     case BOUND_TEMPLATE_TEMPLATE_PARM:
11221     case TEMPLATE_PARM_INDEX:
11222     case POINTER_TYPE:
11223     case REFERENCE_TYPE:
11224     case OFFSET_TYPE:
11225     case FUNCTION_TYPE:
11226     case METHOD_TYPE:
11227     case ARRAY_TYPE:
11228     case TYPENAME_TYPE:
11229     case UNBOUND_CLASS_TEMPLATE:
11230     case TYPEOF_TYPE:
11231     case DECLTYPE_TYPE:
11232     case TYPE_DECL:
11233       return tsubst (t, args, complain, in_decl);
11234
11235     case IDENTIFIER_NODE:
11236       if (IDENTIFIER_TYPENAME_P (t))
11237         {
11238           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11239           return mangle_conv_op_name_for_type (new_type);
11240         }
11241       else
11242         return t;
11243
11244     case CONSTRUCTOR:
11245       /* This is handled by tsubst_copy_and_build.  */
11246       gcc_unreachable ();
11247
11248     case VA_ARG_EXPR:
11249       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
11250                                           in_decl),
11251                              tsubst (TREE_TYPE (t), args, complain, in_decl));
11252
11253     case CLEANUP_POINT_EXPR:
11254       /* We shouldn't have built any of these during initial template
11255          generation.  Instead, they should be built during instantiation
11256          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
11257       gcc_unreachable ();
11258
11259     case OFFSET_REF:
11260       mark_used (TREE_OPERAND (t, 1));
11261       return t;
11262
11263     case EXPR_PACK_EXPANSION:
11264       error ("invalid use of pack expansion expression");
11265       return error_mark_node;
11266
11267     case NONTYPE_ARGUMENT_PACK:
11268       error ("use %<...%> to expand argument pack");
11269       return error_mark_node;
11270
11271     default:
11272       return t;
11273     }
11274 }
11275
11276 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
11277
11278 static tree
11279 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
11280                     tree in_decl)
11281 {
11282   tree new_clauses = NULL, nc, oc;
11283
11284   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
11285     {
11286       nc = copy_node (oc);
11287       OMP_CLAUSE_CHAIN (nc) = new_clauses;
11288       new_clauses = nc;
11289
11290       switch (OMP_CLAUSE_CODE (nc))
11291         {
11292         case OMP_CLAUSE_LASTPRIVATE:
11293           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
11294             {
11295               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
11296               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
11297                            in_decl, /*integral_constant_expression_p=*/false);
11298               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
11299                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
11300             }
11301           /* FALLTHRU */
11302         case OMP_CLAUSE_PRIVATE:
11303         case OMP_CLAUSE_SHARED:
11304         case OMP_CLAUSE_FIRSTPRIVATE:
11305         case OMP_CLAUSE_REDUCTION:
11306         case OMP_CLAUSE_COPYIN:
11307         case OMP_CLAUSE_COPYPRIVATE:
11308         case OMP_CLAUSE_IF:
11309         case OMP_CLAUSE_NUM_THREADS:
11310         case OMP_CLAUSE_SCHEDULE:
11311         case OMP_CLAUSE_COLLAPSE:
11312           OMP_CLAUSE_OPERAND (nc, 0)
11313             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
11314                            in_decl, /*integral_constant_expression_p=*/false);
11315           break;
11316         case OMP_CLAUSE_NOWAIT:
11317         case OMP_CLAUSE_ORDERED:
11318         case OMP_CLAUSE_DEFAULT:
11319         case OMP_CLAUSE_UNTIED:
11320           break;
11321         default:
11322           gcc_unreachable ();
11323         }
11324     }
11325
11326   return finish_omp_clauses (nreverse (new_clauses));
11327 }
11328
11329 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
11330
11331 static tree
11332 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
11333                           tree in_decl)
11334 {
11335 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
11336
11337   tree purpose, value, chain;
11338
11339   if (t == NULL)
11340     return t;
11341
11342   if (TREE_CODE (t) != TREE_LIST)
11343     return tsubst_copy_and_build (t, args, complain, in_decl,
11344                                   /*function_p=*/false,
11345                                   /*integral_constant_expression_p=*/false);
11346
11347   if (t == void_list_node)
11348     return t;
11349
11350   purpose = TREE_PURPOSE (t);
11351   if (purpose)
11352     purpose = RECUR (purpose);
11353   value = TREE_VALUE (t);
11354   if (value && TREE_CODE (value) != LABEL_DECL)
11355     value = RECUR (value);
11356   chain = TREE_CHAIN (t);
11357   if (chain && chain != void_type_node)
11358     chain = RECUR (chain);
11359   return tree_cons (purpose, value, chain);
11360 #undef RECUR
11361 }
11362
11363 /* Substitute one OMP_FOR iterator.  */
11364
11365 static void
11366 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
11367                          tree condv, tree incrv, tree *clauses,
11368                          tree args, tsubst_flags_t complain, tree in_decl,
11369                          bool integral_constant_expression_p)
11370 {
11371 #define RECUR(NODE)                             \
11372   tsubst_expr ((NODE), args, complain, in_decl, \
11373                integral_constant_expression_p)
11374   tree decl, init, cond, incr, auto_node;
11375
11376   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
11377   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
11378   decl = RECUR (TREE_OPERAND (init, 0));
11379   init = TREE_OPERAND (init, 1);
11380   auto_node = type_uses_auto (TREE_TYPE (decl));
11381   if (auto_node && init)
11382     {
11383       tree init_expr = init;
11384       if (TREE_CODE (init_expr) == DECL_EXPR)
11385         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
11386       init_expr = RECUR (init_expr);
11387       TREE_TYPE (decl)
11388         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
11389     }
11390   gcc_assert (!type_dependent_expression_p (decl));
11391
11392   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
11393     {
11394       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
11395       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11396       if (TREE_CODE (incr) == MODIFY_EXPR)
11397         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
11398                                     RECUR (TREE_OPERAND (incr, 1)),
11399                                     complain);
11400       else
11401         incr = RECUR (incr);
11402       TREE_VEC_ELT (declv, i) = decl;
11403       TREE_VEC_ELT (initv, i) = init;
11404       TREE_VEC_ELT (condv, i) = cond;
11405       TREE_VEC_ELT (incrv, i) = incr;
11406       return;
11407     }
11408
11409   if (init && TREE_CODE (init) != DECL_EXPR)
11410     {
11411       tree c;
11412       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
11413         {
11414           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
11415                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
11416               && OMP_CLAUSE_DECL (c) == decl)
11417             break;
11418           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
11419                    && OMP_CLAUSE_DECL (c) == decl)
11420             error ("iteration variable %qD should not be firstprivate", decl);
11421           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
11422                    && OMP_CLAUSE_DECL (c) == decl)
11423             error ("iteration variable %qD should not be reduction", decl);
11424         }
11425       if (c == NULL)
11426         {
11427           c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
11428           OMP_CLAUSE_DECL (c) = decl;
11429           c = finish_omp_clauses (c);
11430           if (c)
11431             {
11432               OMP_CLAUSE_CHAIN (c) = *clauses;
11433               *clauses = c;
11434             }
11435         }
11436     }
11437   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
11438   if (COMPARISON_CLASS_P (cond))
11439     cond = build2 (TREE_CODE (cond), boolean_type_node,
11440                    RECUR (TREE_OPERAND (cond, 0)),
11441                    RECUR (TREE_OPERAND (cond, 1)));
11442   else
11443     cond = RECUR (cond);
11444   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11445   switch (TREE_CODE (incr))
11446     {
11447     case PREINCREMENT_EXPR:
11448     case PREDECREMENT_EXPR:
11449     case POSTINCREMENT_EXPR:
11450     case POSTDECREMENT_EXPR:
11451       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
11452                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
11453       break;
11454     case MODIFY_EXPR:
11455       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11456           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11457         {
11458           tree rhs = TREE_OPERAND (incr, 1);
11459           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11460                          RECUR (TREE_OPERAND (incr, 0)),
11461                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11462                                  RECUR (TREE_OPERAND (rhs, 0)),
11463                                  RECUR (TREE_OPERAND (rhs, 1))));
11464         }
11465       else
11466         incr = RECUR (incr);
11467       break;
11468     case MODOP_EXPR:
11469       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11470           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11471         {
11472           tree lhs = RECUR (TREE_OPERAND (incr, 0));
11473           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
11474                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
11475                                  TREE_TYPE (decl), lhs,
11476                                  RECUR (TREE_OPERAND (incr, 2))));
11477         }
11478       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
11479                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
11480                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
11481         {
11482           tree rhs = TREE_OPERAND (incr, 2);
11483           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11484                          RECUR (TREE_OPERAND (incr, 0)),
11485                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11486                                  RECUR (TREE_OPERAND (rhs, 0)),
11487                                  RECUR (TREE_OPERAND (rhs, 1))));
11488         }
11489       else
11490         incr = RECUR (incr);
11491       break;
11492     default:
11493       incr = RECUR (incr);
11494       break;
11495     }
11496
11497   TREE_VEC_ELT (declv, i) = decl;
11498   TREE_VEC_ELT (initv, i) = init;
11499   TREE_VEC_ELT (condv, i) = cond;
11500   TREE_VEC_ELT (incrv, i) = incr;
11501 #undef RECUR
11502 }
11503
11504 /* Like tsubst_copy for expressions, etc. but also does semantic
11505    processing.  */
11506
11507 static tree
11508 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
11509              bool integral_constant_expression_p)
11510 {
11511 #define RECUR(NODE)                             \
11512   tsubst_expr ((NODE), args, complain, in_decl, \
11513                integral_constant_expression_p)
11514
11515   tree stmt, tmp;
11516
11517   if (t == NULL_TREE || t == error_mark_node)
11518     return t;
11519
11520   if (EXPR_HAS_LOCATION (t))
11521     input_location = EXPR_LOCATION (t);
11522   if (STATEMENT_CODE_P (TREE_CODE (t)))
11523     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
11524
11525   switch (TREE_CODE (t))
11526     {
11527     case STATEMENT_LIST:
11528       {
11529         tree_stmt_iterator i;
11530         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
11531           RECUR (tsi_stmt (i));
11532         break;
11533       }
11534
11535     case CTOR_INITIALIZER:
11536       finish_mem_initializers (tsubst_initializer_list
11537                                (TREE_OPERAND (t, 0), args));
11538       break;
11539
11540     case RETURN_EXPR:
11541       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
11542       break;
11543
11544     case EXPR_STMT:
11545       tmp = RECUR (EXPR_STMT_EXPR (t));
11546       if (EXPR_STMT_STMT_EXPR_RESULT (t))
11547         finish_stmt_expr_expr (tmp, cur_stmt_expr);
11548       else
11549         finish_expr_stmt (tmp);
11550       break;
11551
11552     case USING_STMT:
11553       do_using_directive (RECUR (USING_STMT_NAMESPACE (t)));
11554       break;
11555
11556     case DECL_EXPR:
11557       {
11558         tree decl;
11559         tree init;
11560
11561         decl = DECL_EXPR_DECL (t);
11562         if (TREE_CODE (decl) == LABEL_DECL)
11563           finish_label_decl (DECL_NAME (decl));
11564         else if (TREE_CODE (decl) == USING_DECL)
11565           {
11566             tree scope = USING_DECL_SCOPE (decl);
11567             tree name = DECL_NAME (decl);
11568             tree decl;
11569
11570             scope = RECUR (scope);
11571             decl = lookup_qualified_name (scope, name,
11572                                           /*is_type_p=*/false,
11573                                           /*complain=*/false);
11574             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
11575               qualified_name_lookup_error (scope, name, decl, input_location);
11576             else
11577               do_local_using_decl (decl, scope, name);
11578           }
11579         else
11580           {
11581             init = DECL_INITIAL (decl);
11582             decl = tsubst (decl, args, complain, in_decl);
11583             if (decl != error_mark_node)
11584               {
11585                 /* By marking the declaration as instantiated, we avoid
11586                    trying to instantiate it.  Since instantiate_decl can't
11587                    handle local variables, and since we've already done
11588                    all that needs to be done, that's the right thing to
11589                    do.  */
11590                 if (TREE_CODE (decl) == VAR_DECL)
11591                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11592                 if (TREE_CODE (decl) == VAR_DECL
11593                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
11594                   /* Anonymous aggregates are a special case.  */
11595                   finish_anon_union (decl);
11596                 else
11597                   {
11598                     maybe_push_decl (decl);
11599                     if (TREE_CODE (decl) == VAR_DECL
11600                         && DECL_PRETTY_FUNCTION_P (decl))
11601                       {
11602                         /* For __PRETTY_FUNCTION__ we have to adjust the
11603                            initializer.  */
11604                         const char *const name
11605                           = cxx_printable_name (current_function_decl, 2);
11606                         init = cp_fname_init (name, &TREE_TYPE (decl));
11607                       }
11608                     else
11609                       {
11610                         tree t = RECUR (init);
11611
11612                         if (init && !t)
11613                           /* If we had an initializer but it
11614                              instantiated to nothing,
11615                              value-initialize the object.  This will
11616                              only occur when the initializer was a
11617                              pack expansion where the parameter packs
11618                              used in that expansion were of length
11619                              zero.  */
11620                           init = build_value_init (TREE_TYPE (decl));
11621                         else
11622                           init = t;
11623                       }
11624
11625                     cp_finish_decl (decl, init, false, NULL_TREE, 0);
11626                   }
11627               }
11628           }
11629
11630         /* A DECL_EXPR can also be used as an expression, in the condition
11631            clause of an if/for/while construct.  */
11632         return decl;
11633       }
11634
11635     case FOR_STMT:
11636       stmt = begin_for_stmt ();
11637                           RECUR (FOR_INIT_STMT (t));
11638       finish_for_init_stmt (stmt);
11639       tmp = RECUR (FOR_COND (t));
11640       finish_for_cond (tmp, stmt);
11641       tmp = RECUR (FOR_EXPR (t));
11642       finish_for_expr (tmp, stmt);
11643       RECUR (FOR_BODY (t));
11644       finish_for_stmt (stmt);
11645       break;
11646
11647     case WHILE_STMT:
11648       stmt = begin_while_stmt ();
11649       tmp = RECUR (WHILE_COND (t));
11650       finish_while_stmt_cond (tmp, stmt);
11651       RECUR (WHILE_BODY (t));
11652       finish_while_stmt (stmt);
11653       break;
11654
11655     case DO_STMT:
11656       stmt = begin_do_stmt ();
11657       RECUR (DO_BODY (t));
11658       finish_do_body (stmt);
11659       tmp = RECUR (DO_COND (t));
11660       finish_do_stmt (tmp, stmt);
11661       break;
11662
11663     case IF_STMT:
11664       stmt = begin_if_stmt ();
11665       tmp = RECUR (IF_COND (t));
11666       finish_if_stmt_cond (tmp, stmt);
11667       RECUR (THEN_CLAUSE (t));
11668       finish_then_clause (stmt);
11669
11670       if (ELSE_CLAUSE (t))
11671         {
11672           begin_else_clause (stmt);
11673           RECUR (ELSE_CLAUSE (t));
11674           finish_else_clause (stmt);
11675         }
11676
11677       finish_if_stmt (stmt);
11678       break;
11679
11680     case BIND_EXPR:
11681       if (BIND_EXPR_BODY_BLOCK (t))
11682         stmt = begin_function_body ();
11683       else
11684         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
11685                                     ? BCS_TRY_BLOCK : 0);
11686
11687       RECUR (BIND_EXPR_BODY (t));
11688
11689       if (BIND_EXPR_BODY_BLOCK (t))
11690         finish_function_body (stmt);
11691       else
11692         finish_compound_stmt (stmt);
11693       break;
11694
11695     case BREAK_STMT:
11696       finish_break_stmt ();
11697       break;
11698
11699     case CONTINUE_STMT:
11700       finish_continue_stmt ();
11701       break;
11702
11703     case SWITCH_STMT:
11704       stmt = begin_switch_stmt ();
11705       tmp = RECUR (SWITCH_STMT_COND (t));
11706       finish_switch_cond (tmp, stmt);
11707       RECUR (SWITCH_STMT_BODY (t));
11708       finish_switch_stmt (stmt);
11709       break;
11710
11711     case CASE_LABEL_EXPR:
11712       finish_case_label (EXPR_LOCATION (t),
11713                          RECUR (CASE_LOW (t)),
11714                          RECUR (CASE_HIGH (t)));
11715       break;
11716
11717     case LABEL_EXPR:
11718       {
11719         tree decl = LABEL_EXPR_LABEL (t);
11720         tree label;
11721
11722         label = finish_label_stmt (DECL_NAME (decl));
11723         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
11724           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
11725       }
11726       break;
11727
11728     case GOTO_EXPR:
11729       tmp = GOTO_DESTINATION (t);
11730       if (TREE_CODE (tmp) != LABEL_DECL)
11731         /* Computed goto's must be tsubst'd into.  On the other hand,
11732            non-computed gotos must not be; the identifier in question
11733            will have no binding.  */
11734         tmp = RECUR (tmp);
11735       else
11736         tmp = DECL_NAME (tmp);
11737       finish_goto_stmt (tmp);
11738       break;
11739
11740     case ASM_EXPR:
11741       tmp = finish_asm_stmt
11742         (ASM_VOLATILE_P (t),
11743          RECUR (ASM_STRING (t)),
11744          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
11745          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
11746          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl),
11747          tsubst_copy_asm_operands (ASM_LABELS (t), args, complain, in_decl));
11748       {
11749         tree asm_expr = tmp;
11750         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
11751           asm_expr = TREE_OPERAND (asm_expr, 0);
11752         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
11753       }
11754       break;
11755
11756     case TRY_BLOCK:
11757       if (CLEANUP_P (t))
11758         {
11759           stmt = begin_try_block ();
11760           RECUR (TRY_STMTS (t));
11761           finish_cleanup_try_block (stmt);
11762           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
11763         }
11764       else
11765         {
11766           tree compound_stmt = NULL_TREE;
11767
11768           if (FN_TRY_BLOCK_P (t))
11769             stmt = begin_function_try_block (&compound_stmt);
11770           else
11771             stmt = begin_try_block ();
11772
11773           RECUR (TRY_STMTS (t));
11774
11775           if (FN_TRY_BLOCK_P (t))
11776             finish_function_try_block (stmt);
11777           else
11778             finish_try_block (stmt);
11779
11780           RECUR (TRY_HANDLERS (t));
11781           if (FN_TRY_BLOCK_P (t))
11782             finish_function_handler_sequence (stmt, compound_stmt);
11783           else
11784             finish_handler_sequence (stmt);
11785         }
11786       break;
11787
11788     case HANDLER:
11789       {
11790         tree decl = HANDLER_PARMS (t);
11791
11792         if (decl)
11793           {
11794             decl = tsubst (decl, args, complain, in_decl);
11795             /* Prevent instantiate_decl from trying to instantiate
11796                this variable.  We've already done all that needs to be
11797                done.  */
11798             if (decl != error_mark_node)
11799               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11800           }
11801         stmt = begin_handler ();
11802         finish_handler_parms (decl, stmt);
11803         RECUR (HANDLER_BODY (t));
11804         finish_handler (stmt);
11805       }
11806       break;
11807
11808     case TAG_DEFN:
11809       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
11810       break;
11811
11812     case STATIC_ASSERT:
11813       {
11814         tree condition = 
11815           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
11816                        args,
11817                        complain, in_decl,
11818                        /*integral_constant_expression_p=*/true);
11819         finish_static_assert (condition,
11820                               STATIC_ASSERT_MESSAGE (t),
11821                               STATIC_ASSERT_SOURCE_LOCATION (t),
11822                               /*member_p=*/false);
11823       }
11824       break;
11825
11826     case OMP_PARALLEL:
11827       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
11828                                 args, complain, in_decl);
11829       stmt = begin_omp_parallel ();
11830       RECUR (OMP_PARALLEL_BODY (t));
11831       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
11832         = OMP_PARALLEL_COMBINED (t);
11833       break;
11834
11835     case OMP_TASK:
11836       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
11837                                 args, complain, in_decl);
11838       stmt = begin_omp_task ();
11839       RECUR (OMP_TASK_BODY (t));
11840       finish_omp_task (tmp, stmt);
11841       break;
11842
11843     case OMP_FOR:
11844       {
11845         tree clauses, body, pre_body;
11846         tree declv, initv, condv, incrv;
11847         int i;
11848
11849         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
11850                                       args, complain, in_decl);
11851         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11852         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11853         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11854         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11855
11856         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
11857           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
11858                                    &clauses, args, complain, in_decl,
11859                                    integral_constant_expression_p);
11860
11861         stmt = begin_omp_structured_block ();
11862
11863         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
11864           if (TREE_VEC_ELT (initv, i) == NULL
11865               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
11866             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
11867           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
11868             {
11869               tree init = RECUR (TREE_VEC_ELT (initv, i));
11870               gcc_assert (init == TREE_VEC_ELT (declv, i));
11871               TREE_VEC_ELT (initv, i) = NULL_TREE;
11872             }
11873           else
11874             {
11875               tree decl_expr = TREE_VEC_ELT (initv, i);
11876               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
11877               gcc_assert (init != NULL);
11878               TREE_VEC_ELT (initv, i) = RECUR (init);
11879               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
11880               RECUR (decl_expr);
11881               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
11882             }
11883
11884         pre_body = push_stmt_list ();
11885         RECUR (OMP_FOR_PRE_BODY (t));
11886         pre_body = pop_stmt_list (pre_body);
11887
11888         body = push_stmt_list ();
11889         RECUR (OMP_FOR_BODY (t));
11890         body = pop_stmt_list (body);
11891
11892         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
11893                             body, pre_body, clauses);
11894
11895         add_stmt (finish_omp_structured_block (stmt));
11896       }
11897       break;
11898
11899     case OMP_SECTIONS:
11900     case OMP_SINGLE:
11901       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
11902       stmt = push_stmt_list ();
11903       RECUR (OMP_BODY (t));
11904       stmt = pop_stmt_list (stmt);
11905
11906       t = copy_node (t);
11907       OMP_BODY (t) = stmt;
11908       OMP_CLAUSES (t) = tmp;
11909       add_stmt (t);
11910       break;
11911
11912     case OMP_SECTION:
11913     case OMP_CRITICAL:
11914     case OMP_MASTER:
11915     case OMP_ORDERED:
11916       stmt = push_stmt_list ();
11917       RECUR (OMP_BODY (t));
11918       stmt = pop_stmt_list (stmt);
11919
11920       t = copy_node (t);
11921       OMP_BODY (t) = stmt;
11922       add_stmt (t);
11923       break;
11924
11925     case OMP_ATOMIC:
11926       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
11927       {
11928         tree op1 = TREE_OPERAND (t, 1);
11929         tree lhs = RECUR (TREE_OPERAND (op1, 0));
11930         tree rhs = RECUR (TREE_OPERAND (op1, 1));
11931         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
11932       }
11933       break;
11934
11935     case EXPR_PACK_EXPANSION:
11936       error ("invalid use of pack expansion expression");
11937       return error_mark_node;
11938
11939     case NONTYPE_ARGUMENT_PACK:
11940       error ("use %<...%> to expand argument pack");
11941       return error_mark_node;
11942
11943     default:
11944       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
11945
11946       return tsubst_copy_and_build (t, args, complain, in_decl,
11947                                     /*function_p=*/false,
11948                                     integral_constant_expression_p);
11949     }
11950
11951   return NULL_TREE;
11952 #undef RECUR
11953 }
11954
11955 /* T is a postfix-expression that is not being used in a function
11956    call.  Return the substituted version of T.  */
11957
11958 static tree
11959 tsubst_non_call_postfix_expression (tree t, tree args,
11960                                     tsubst_flags_t complain,
11961                                     tree in_decl)
11962 {
11963   if (TREE_CODE (t) == SCOPE_REF)
11964     t = tsubst_qualified_id (t, args, complain, in_decl,
11965                              /*done=*/false, /*address_p=*/false);
11966   else
11967     t = tsubst_copy_and_build (t, args, complain, in_decl,
11968                                /*function_p=*/false,
11969                                /*integral_constant_expression_p=*/false);
11970
11971   return t;
11972 }
11973
11974 /* Like tsubst but deals with expressions and performs semantic
11975    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
11976
11977 tree
11978 tsubst_copy_and_build (tree t,
11979                        tree args,
11980                        tsubst_flags_t complain,
11981                        tree in_decl,
11982                        bool function_p,
11983                        bool integral_constant_expression_p)
11984 {
11985 #define RECUR(NODE)                                             \
11986   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
11987                          /*function_p=*/false,                  \
11988                          integral_constant_expression_p)
11989
11990   tree op1;
11991
11992   if (t == NULL_TREE || t == error_mark_node)
11993     return t;
11994
11995   switch (TREE_CODE (t))
11996     {
11997     case USING_DECL:
11998       t = DECL_NAME (t);
11999       /* Fall through.  */
12000     case IDENTIFIER_NODE:
12001       {
12002         tree decl;
12003         cp_id_kind idk;
12004         bool non_integral_constant_expression_p;
12005         const char *error_msg;
12006
12007         if (IDENTIFIER_TYPENAME_P (t))
12008           {
12009             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12010             t = mangle_conv_op_name_for_type (new_type);
12011           }
12012
12013         /* Look up the name.  */
12014         decl = lookup_name (t);
12015
12016         /* By convention, expressions use ERROR_MARK_NODE to indicate
12017            failure, not NULL_TREE.  */
12018         if (decl == NULL_TREE)
12019           decl = error_mark_node;
12020
12021         decl = finish_id_expression (t, decl, NULL_TREE,
12022                                      &idk,
12023                                      integral_constant_expression_p,
12024                                      /*allow_non_integral_constant_expression_p=*/false,
12025                                      &non_integral_constant_expression_p,
12026                                      /*template_p=*/false,
12027                                      /*done=*/true,
12028                                      /*address_p=*/false,
12029                                      /*template_arg_p=*/false,
12030                                      &error_msg,
12031                                      input_location);
12032         if (error_msg)
12033           error (error_msg);
12034         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
12035           decl = unqualified_name_lookup_error (decl);
12036         return decl;
12037       }
12038
12039     case TEMPLATE_ID_EXPR:
12040       {
12041         tree object;
12042         tree templ = RECUR (TREE_OPERAND (t, 0));
12043         tree targs = TREE_OPERAND (t, 1);
12044
12045         if (targs)
12046           targs = tsubst_template_args (targs, args, complain, in_decl);
12047
12048         if (TREE_CODE (templ) == COMPONENT_REF)
12049           {
12050             object = TREE_OPERAND (templ, 0);
12051             templ = TREE_OPERAND (templ, 1);
12052           }
12053         else
12054           object = NULL_TREE;
12055         templ = lookup_template_function (templ, targs);
12056
12057         if (object)
12058           return build3 (COMPONENT_REF, TREE_TYPE (templ),
12059                          object, templ, NULL_TREE);
12060         else
12061           return baselink_for_fns (templ);
12062       }
12063
12064     case INDIRECT_REF:
12065       {
12066         tree r = RECUR (TREE_OPERAND (t, 0));
12067
12068         if (REFERENCE_REF_P (t))
12069           {
12070             /* A type conversion to reference type will be enclosed in
12071                such an indirect ref, but the substitution of the cast
12072                will have also added such an indirect ref.  */
12073             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
12074               r = convert_from_reference (r);
12075           }
12076         else
12077           r = build_x_indirect_ref (r, RO_UNARY_STAR, complain);
12078         return r;
12079       }
12080
12081     case NOP_EXPR:
12082       return build_nop
12083         (tsubst (TREE_TYPE (t), args, complain, in_decl),
12084          RECUR (TREE_OPERAND (t, 0)));
12085
12086     case CAST_EXPR:
12087     case REINTERPRET_CAST_EXPR:
12088     case CONST_CAST_EXPR:
12089     case DYNAMIC_CAST_EXPR:
12090     case STATIC_CAST_EXPR:
12091       {
12092         tree type;
12093         tree op;
12094
12095         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12096         if (integral_constant_expression_p
12097             && !cast_valid_in_integral_constant_expression_p (type))
12098           {
12099             if (complain & tf_error)
12100               error ("a cast to a type other than an integral or "
12101                      "enumeration type cannot appear in a constant-expression");
12102             return error_mark_node; 
12103           }
12104
12105         op = RECUR (TREE_OPERAND (t, 0));
12106
12107         switch (TREE_CODE (t))
12108           {
12109           case CAST_EXPR:
12110             return build_functional_cast (type, op, complain);
12111           case REINTERPRET_CAST_EXPR:
12112             return build_reinterpret_cast (type, op, complain);
12113           case CONST_CAST_EXPR:
12114             return build_const_cast (type, op, complain);
12115           case DYNAMIC_CAST_EXPR:
12116             return build_dynamic_cast (type, op, complain);
12117           case STATIC_CAST_EXPR:
12118             return build_static_cast (type, op, complain);
12119           default:
12120             gcc_unreachable ();
12121           }
12122       }
12123
12124     case POSTDECREMENT_EXPR:
12125     case POSTINCREMENT_EXPR:
12126       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12127                                                 args, complain, in_decl);
12128       return build_x_unary_op (TREE_CODE (t), op1, complain);
12129
12130     case PREDECREMENT_EXPR:
12131     case PREINCREMENT_EXPR:
12132     case NEGATE_EXPR:
12133     case BIT_NOT_EXPR:
12134     case ABS_EXPR:
12135     case TRUTH_NOT_EXPR:
12136     case UNARY_PLUS_EXPR:  /* Unary + */
12137     case REALPART_EXPR:
12138     case IMAGPART_EXPR:
12139       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
12140                                complain);
12141
12142     case ADDR_EXPR:
12143       op1 = TREE_OPERAND (t, 0);
12144       if (TREE_CODE (op1) == SCOPE_REF)
12145         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
12146                                    /*done=*/true, /*address_p=*/true);
12147       else
12148         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
12149                                                   in_decl);
12150       if (TREE_CODE (op1) == LABEL_DECL)
12151         return finish_label_address_expr (DECL_NAME (op1),
12152                                           EXPR_LOCATION (op1));
12153       return build_x_unary_op (ADDR_EXPR, op1, complain);
12154
12155     case PLUS_EXPR:
12156     case MINUS_EXPR:
12157     case MULT_EXPR:
12158     case TRUNC_DIV_EXPR:
12159     case CEIL_DIV_EXPR:
12160     case FLOOR_DIV_EXPR:
12161     case ROUND_DIV_EXPR:
12162     case EXACT_DIV_EXPR:
12163     case BIT_AND_EXPR:
12164     case BIT_IOR_EXPR:
12165     case BIT_XOR_EXPR:
12166     case TRUNC_MOD_EXPR:
12167     case FLOOR_MOD_EXPR:
12168     case TRUTH_ANDIF_EXPR:
12169     case TRUTH_ORIF_EXPR:
12170     case TRUTH_AND_EXPR:
12171     case TRUTH_OR_EXPR:
12172     case RSHIFT_EXPR:
12173     case LSHIFT_EXPR:
12174     case RROTATE_EXPR:
12175     case LROTATE_EXPR:
12176     case EQ_EXPR:
12177     case NE_EXPR:
12178     case MAX_EXPR:
12179     case MIN_EXPR:
12180     case LE_EXPR:
12181     case GE_EXPR:
12182     case LT_EXPR:
12183     case GT_EXPR:
12184     case MEMBER_REF:
12185     case DOTSTAR_EXPR:
12186       return build_x_binary_op
12187         (TREE_CODE (t),
12188          RECUR (TREE_OPERAND (t, 0)),
12189          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
12190           ? ERROR_MARK
12191           : TREE_CODE (TREE_OPERAND (t, 0))),
12192          RECUR (TREE_OPERAND (t, 1)),
12193          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
12194           ? ERROR_MARK
12195           : TREE_CODE (TREE_OPERAND (t, 1))),
12196          /*overloaded_p=*/NULL,
12197          complain);
12198
12199     case SCOPE_REF:
12200       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
12201                                   /*address_p=*/false);
12202     case ARRAY_REF:
12203       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12204                                                 args, complain, in_decl);
12205       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
12206
12207     case SIZEOF_EXPR:
12208       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
12209         return tsubst_copy (t, args, complain, in_decl);
12210       /* Fall through */
12211       
12212     case ALIGNOF_EXPR:
12213       op1 = TREE_OPERAND (t, 0);
12214       if (!args)
12215         {
12216           /* When there are no ARGS, we are trying to evaluate a
12217              non-dependent expression from the parser.  Trying to do
12218              the substitutions may not work.  */
12219           if (!TYPE_P (op1))
12220             op1 = TREE_TYPE (op1);
12221         }
12222       else
12223         {
12224           ++cp_unevaluated_operand;
12225           ++c_inhibit_evaluation_warnings;
12226           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
12227                                        /*function_p=*/false,
12228                                        /*integral_constant_expression_p=*/false);
12229           --cp_unevaluated_operand;
12230           --c_inhibit_evaluation_warnings;
12231         }
12232       if (TYPE_P (op1))
12233         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
12234                                            complain & tf_error);
12235       else
12236         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
12237                                            complain & tf_error);
12238
12239     case MODOP_EXPR:
12240       {
12241         tree r = build_x_modify_expr
12242           (RECUR (TREE_OPERAND (t, 0)),
12243            TREE_CODE (TREE_OPERAND (t, 1)),
12244            RECUR (TREE_OPERAND (t, 2)),
12245            complain);
12246         /* TREE_NO_WARNING must be set if either the expression was
12247            parenthesized or it uses an operator such as >>= rather
12248            than plain assignment.  In the former case, it was already
12249            set and must be copied.  In the latter case,
12250            build_x_modify_expr sets it and it must not be reset
12251            here.  */
12252         if (TREE_NO_WARNING (t))
12253           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
12254         return r;
12255       }
12256
12257     case ARROW_EXPR:
12258       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12259                                                 args, complain, in_decl);
12260       /* Remember that there was a reference to this entity.  */
12261       if (DECL_P (op1))
12262         mark_used (op1);
12263       return build_x_arrow (op1);
12264
12265     case NEW_EXPR:
12266       {
12267         tree placement = RECUR (TREE_OPERAND (t, 0));
12268         tree init = RECUR (TREE_OPERAND (t, 3));
12269         VEC(tree,gc) *placement_vec;
12270         VEC(tree,gc) *init_vec;
12271         tree ret;
12272
12273         if (placement == NULL_TREE)
12274           placement_vec = NULL;
12275         else
12276           {
12277             placement_vec = make_tree_vector ();
12278             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
12279               VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
12280           }
12281
12282         /* If there was an initializer in the original tree, but it
12283            instantiated to an empty list, then we should pass a
12284            non-NULL empty vector to tell build_new that it was an
12285            empty initializer() rather than no initializer.  This can
12286            only happen when the initializer is a pack expansion whose
12287            parameter packs are of length zero.  */
12288         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
12289           init_vec = NULL;
12290         else
12291           {
12292             init_vec = make_tree_vector ();
12293             if (init == void_zero_node)
12294               gcc_assert (init_vec != NULL);
12295             else
12296               {
12297                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
12298                   VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
12299               }
12300           }
12301
12302         ret = build_new (&placement_vec,
12303                          RECUR (TREE_OPERAND (t, 1)),
12304                          RECUR (TREE_OPERAND (t, 2)),
12305                          &init_vec,
12306                          NEW_EXPR_USE_GLOBAL (t),
12307                          complain);
12308
12309         if (placement_vec != NULL)
12310           release_tree_vector (placement_vec);
12311         if (init_vec != NULL)
12312           release_tree_vector (init_vec);
12313
12314         return ret;
12315       }
12316
12317     case DELETE_EXPR:
12318      return delete_sanity
12319        (RECUR (TREE_OPERAND (t, 0)),
12320         RECUR (TREE_OPERAND (t, 1)),
12321         DELETE_EXPR_USE_VEC (t),
12322         DELETE_EXPR_USE_GLOBAL (t));
12323
12324     case COMPOUND_EXPR:
12325       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
12326                                     RECUR (TREE_OPERAND (t, 1)),
12327                                     complain);
12328
12329     case CALL_EXPR:
12330       {
12331         tree function;
12332         VEC(tree,gc) *call_args;
12333         unsigned int nargs, i;
12334         bool qualified_p;
12335         bool koenig_p;
12336         tree ret;
12337
12338         function = CALL_EXPR_FN (t);
12339         /* When we parsed the expression,  we determined whether or
12340            not Koenig lookup should be performed.  */
12341         koenig_p = KOENIG_LOOKUP_P (t);
12342         if (TREE_CODE (function) == SCOPE_REF)
12343           {
12344             qualified_p = true;
12345             function = tsubst_qualified_id (function, args, complain, in_decl,
12346                                             /*done=*/false,
12347                                             /*address_p=*/false);
12348           }
12349         else
12350           {
12351             if (TREE_CODE (function) == COMPONENT_REF)
12352               {
12353                 tree op = TREE_OPERAND (function, 1);
12354
12355                 qualified_p = (TREE_CODE (op) == SCOPE_REF
12356                                || (BASELINK_P (op)
12357                                    && BASELINK_QUALIFIED_P (op)));
12358               }
12359             else
12360               qualified_p = false;
12361
12362             function = tsubst_copy_and_build (function, args, complain,
12363                                               in_decl,
12364                                               !qualified_p,
12365                                               integral_constant_expression_p);
12366
12367             if (BASELINK_P (function))
12368               qualified_p = true;
12369           }
12370
12371         nargs = call_expr_nargs (t);
12372         call_args = make_tree_vector ();
12373         for (i = 0; i < nargs; ++i)
12374           {
12375             tree arg = CALL_EXPR_ARG (t, i);
12376
12377             if (!PACK_EXPANSION_P (arg))
12378               VEC_safe_push (tree, gc, call_args,
12379                              RECUR (CALL_EXPR_ARG (t, i)));
12380             else
12381               {
12382                 /* Expand the pack expansion and push each entry onto
12383                    CALL_ARGS.  */
12384                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
12385                 if (TREE_CODE (arg) == TREE_VEC)
12386                   {
12387                     unsigned int len, j;
12388
12389                     len = TREE_VEC_LENGTH (arg);
12390                     for (j = 0; j < len; ++j)
12391                       {
12392                         tree value = TREE_VEC_ELT (arg, j);
12393                         if (value != NULL_TREE)
12394                           value = convert_from_reference (value);
12395                         VEC_safe_push (tree, gc, call_args, value);
12396                       }
12397                   }
12398                 else
12399                   {
12400                     /* A partial substitution.  Add one entry.  */
12401                     VEC_safe_push (tree, gc, call_args, arg);
12402                   }
12403               }
12404           }
12405
12406         /* We do not perform argument-dependent lookup if normal
12407            lookup finds a non-function, in accordance with the
12408            expected resolution of DR 218.  */
12409         if (koenig_p
12410             && ((is_overloaded_fn (function)
12411                  /* If lookup found a member function, the Koenig lookup is
12412                     not appropriate, even if an unqualified-name was used
12413                     to denote the function.  */
12414                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
12415                 || TREE_CODE (function) == IDENTIFIER_NODE)
12416             /* Only do this when substitution turns a dependent call
12417                into a non-dependent call.  */
12418             && type_dependent_expression_p_push (t)
12419             && !any_type_dependent_arguments_p (call_args))
12420           function = perform_koenig_lookup (function, call_args);
12421
12422         if (TREE_CODE (function) == IDENTIFIER_NODE)
12423           {
12424             unqualified_name_lookup_error (function);
12425             release_tree_vector (call_args);
12426             return error_mark_node;
12427           }
12428
12429         /* Remember that there was a reference to this entity.  */
12430         if (DECL_P (function))
12431           mark_used (function);
12432
12433         if (TREE_CODE (function) == OFFSET_REF)
12434           ret = build_offset_ref_call_from_tree (function, &call_args);
12435         else if (TREE_CODE (function) == COMPONENT_REF)
12436           {
12437             if (!BASELINK_P (TREE_OPERAND (function, 1)))
12438               ret = finish_call_expr (function, &call_args,
12439                                        /*disallow_virtual=*/false,
12440                                        /*koenig_p=*/false,
12441                                        complain);
12442             else
12443               ret = (build_new_method_call
12444                       (TREE_OPERAND (function, 0),
12445                        TREE_OPERAND (function, 1),
12446                        &call_args, NULL_TREE,
12447                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
12448                        /*fn_p=*/NULL,
12449                        complain));
12450           }
12451         else
12452           ret = finish_call_expr (function, &call_args,
12453                                   /*disallow_virtual=*/qualified_p,
12454                                   koenig_p,
12455                                   complain);
12456
12457         release_tree_vector (call_args);
12458
12459         return ret;
12460       }
12461
12462     case COND_EXPR:
12463       return build_x_conditional_expr
12464         (RECUR (TREE_OPERAND (t, 0)),
12465          RECUR (TREE_OPERAND (t, 1)),
12466          RECUR (TREE_OPERAND (t, 2)),
12467          complain);
12468
12469     case PSEUDO_DTOR_EXPR:
12470       return finish_pseudo_destructor_expr
12471         (RECUR (TREE_OPERAND (t, 0)),
12472          RECUR (TREE_OPERAND (t, 1)),
12473          RECUR (TREE_OPERAND (t, 2)));
12474
12475     case TREE_LIST:
12476       {
12477         tree purpose, value, chain;
12478
12479         if (t == void_list_node)
12480           return t;
12481
12482         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
12483             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
12484           {
12485             /* We have pack expansions, so expand those and
12486                create a new list out of it.  */
12487             tree purposevec = NULL_TREE;
12488             tree valuevec = NULL_TREE;
12489             tree chain;
12490             int i, len = -1;
12491
12492             /* Expand the argument expressions.  */
12493             if (TREE_PURPOSE (t))
12494               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
12495                                                  complain, in_decl);
12496             if (TREE_VALUE (t))
12497               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
12498                                                complain, in_decl);
12499
12500             /* Build the rest of the list.  */
12501             chain = TREE_CHAIN (t);
12502             if (chain && chain != void_type_node)
12503               chain = RECUR (chain);
12504
12505             /* Determine the number of arguments.  */
12506             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
12507               {
12508                 len = TREE_VEC_LENGTH (purposevec);
12509                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
12510               }
12511             else if (TREE_CODE (valuevec) == TREE_VEC)
12512               len = TREE_VEC_LENGTH (valuevec);
12513             else
12514               {
12515                 /* Since we only performed a partial substitution into
12516                    the argument pack, we only return a single list
12517                    node.  */
12518                 if (purposevec == TREE_PURPOSE (t)
12519                     && valuevec == TREE_VALUE (t)
12520                     && chain == TREE_CHAIN (t))
12521                   return t;
12522
12523                 return tree_cons (purposevec, valuevec, chain);
12524               }
12525             
12526             /* Convert the argument vectors into a TREE_LIST */
12527             i = len;
12528             while (i > 0)
12529               {
12530                 /* Grab the Ith values.  */
12531                 i--;
12532                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
12533                                      : NULL_TREE;
12534                 value 
12535                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
12536                              : NULL_TREE;
12537
12538                 /* Build the list (backwards).  */
12539                 chain = tree_cons (purpose, value, chain);
12540               }
12541
12542             return chain;
12543           }
12544
12545         purpose = TREE_PURPOSE (t);
12546         if (purpose)
12547           purpose = RECUR (purpose);
12548         value = TREE_VALUE (t);
12549         if (value)
12550           value = RECUR (value);
12551         chain = TREE_CHAIN (t);
12552         if (chain && chain != void_type_node)
12553           chain = RECUR (chain);
12554         if (purpose == TREE_PURPOSE (t)
12555             && value == TREE_VALUE (t)
12556             && chain == TREE_CHAIN (t))
12557           return t;
12558         return tree_cons (purpose, value, chain);
12559       }
12560
12561     case COMPONENT_REF:
12562       {
12563         tree object;
12564         tree object_type;
12565         tree member;
12566
12567         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12568                                                      args, complain, in_decl);
12569         /* Remember that there was a reference to this entity.  */
12570         if (DECL_P (object))
12571           mark_used (object);
12572         object_type = TREE_TYPE (object);
12573
12574         member = TREE_OPERAND (t, 1);
12575         if (BASELINK_P (member))
12576           member = tsubst_baselink (member,
12577                                     non_reference (TREE_TYPE (object)),
12578                                     args, complain, in_decl);
12579         else
12580           member = tsubst_copy (member, args, complain, in_decl);
12581         if (member == error_mark_node)
12582           return error_mark_node;
12583
12584         if (object_type && !CLASS_TYPE_P (object_type))
12585           {
12586             if (SCALAR_TYPE_P (object_type))
12587               {
12588                 tree s = NULL_TREE;
12589                 tree dtor = member;
12590
12591                 if (TREE_CODE (dtor) == SCOPE_REF)
12592                   {
12593                     s = TREE_OPERAND (dtor, 0);
12594                     dtor = TREE_OPERAND (dtor, 1);
12595                   }
12596                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
12597                   {
12598                     dtor = TREE_OPERAND (dtor, 0);
12599                     if (TYPE_P (dtor))
12600                       return finish_pseudo_destructor_expr (object, s, dtor);
12601                   }
12602               }
12603           }
12604         else if (TREE_CODE (member) == SCOPE_REF
12605                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
12606           {
12607             tree tmpl;
12608             tree args;
12609
12610             /* Lookup the template functions now that we know what the
12611                scope is.  */
12612             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
12613             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
12614             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
12615                                             /*is_type_p=*/false,
12616                                             /*complain=*/false);
12617             if (BASELINK_P (member))
12618               {
12619                 BASELINK_FUNCTIONS (member)
12620                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
12621                               args);
12622                 member = (adjust_result_of_qualified_name_lookup
12623                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
12624                            object_type));
12625               }
12626             else
12627               {
12628                 qualified_name_lookup_error (object_type, tmpl, member,
12629                                              input_location);
12630                 return error_mark_node;
12631               }
12632           }
12633         else if (TREE_CODE (member) == SCOPE_REF
12634                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
12635                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
12636           {
12637             if (complain & tf_error)
12638               {
12639                 if (TYPE_P (TREE_OPERAND (member, 0)))
12640                   error ("%qT is not a class or namespace",
12641                          TREE_OPERAND (member, 0));
12642                 else
12643                   error ("%qD is not a class or namespace",
12644                          TREE_OPERAND (member, 0));
12645               }
12646             return error_mark_node;
12647           }
12648         else if (TREE_CODE (member) == FIELD_DECL)
12649           return finish_non_static_data_member (member, object, NULL_TREE);
12650
12651         return finish_class_member_access_expr (object, member,
12652                                                 /*template_p=*/false,
12653                                                 complain);
12654       }
12655
12656     case THROW_EXPR:
12657       return build_throw
12658         (RECUR (TREE_OPERAND (t, 0)));
12659
12660     case CONSTRUCTOR:
12661       {
12662         VEC(constructor_elt,gc) *n;
12663         constructor_elt *ce;
12664         unsigned HOST_WIDE_INT idx;
12665         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12666         bool process_index_p;
12667         int newlen;
12668         bool need_copy_p = false;
12669         tree r;
12670
12671         if (type == error_mark_node)
12672           return error_mark_node;
12673
12674         /* digest_init will do the wrong thing if we let it.  */
12675         if (type && TYPE_PTRMEMFUNC_P (type))
12676           return t;
12677
12678         /* We do not want to process the index of aggregate
12679            initializers as they are identifier nodes which will be
12680            looked up by digest_init.  */
12681         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
12682
12683         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
12684         newlen = VEC_length (constructor_elt, n);
12685         for (idx = 0; VEC_iterate (constructor_elt, n, idx, ce); idx++)
12686           {
12687             if (ce->index && process_index_p)
12688               ce->index = RECUR (ce->index);
12689
12690             if (PACK_EXPANSION_P (ce->value))
12691               {
12692                 /* Substitute into the pack expansion.  */
12693                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
12694                                                   in_decl);
12695
12696                 if (ce->value == error_mark_node)
12697                   ;
12698                 else if (TREE_VEC_LENGTH (ce->value) == 1)
12699                   /* Just move the argument into place.  */
12700                   ce->value = TREE_VEC_ELT (ce->value, 0);
12701                 else
12702                   {
12703                     /* Update the length of the final CONSTRUCTOR
12704                        arguments vector, and note that we will need to
12705                        copy.*/
12706                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
12707                     need_copy_p = true;
12708                   }
12709               }
12710             else
12711               ce->value = RECUR (ce->value);
12712           }
12713
12714         if (need_copy_p)
12715           {
12716             VEC(constructor_elt,gc) *old_n = n;
12717
12718             n = VEC_alloc (constructor_elt, gc, newlen);
12719             for (idx = 0; VEC_iterate (constructor_elt, old_n, idx, ce); 
12720                  idx++)
12721               {
12722                 if (TREE_CODE (ce->value) == TREE_VEC)
12723                   {
12724                     int i, len = TREE_VEC_LENGTH (ce->value);
12725                     for (i = 0; i < len; ++i)
12726                       CONSTRUCTOR_APPEND_ELT (n, 0,
12727                                               TREE_VEC_ELT (ce->value, i));
12728                   }
12729                 else
12730                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
12731               }
12732           }
12733
12734         r = build_constructor (init_list_type_node, n);
12735         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
12736
12737         if (TREE_HAS_CONSTRUCTOR (t))
12738           return finish_compound_literal (type, r);
12739
12740         return r;
12741       }
12742
12743     case TYPEID_EXPR:
12744       {
12745         tree operand_0 = RECUR (TREE_OPERAND (t, 0));
12746         if (TYPE_P (operand_0))
12747           return get_typeid (operand_0);
12748         return build_typeid (operand_0);
12749       }
12750
12751     case VAR_DECL:
12752       if (!args)
12753         return t;
12754       /* Fall through */
12755
12756     case PARM_DECL:
12757       {
12758         tree r = tsubst_copy (t, args, complain, in_decl);
12759
12760         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
12761           /* If the original type was a reference, we'll be wrapped in
12762              the appropriate INDIRECT_REF.  */
12763           r = convert_from_reference (r);
12764         return r;
12765       }
12766
12767     case VA_ARG_EXPR:
12768       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
12769                              tsubst_copy (TREE_TYPE (t), args, complain,
12770                                           in_decl));
12771
12772     case OFFSETOF_EXPR:
12773       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
12774
12775     case TRAIT_EXPR:
12776       {
12777         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
12778                                   complain, in_decl);
12779
12780         tree type2 = TRAIT_EXPR_TYPE2 (t);
12781         if (type2)
12782           type2 = tsubst_copy (type2, args, complain, in_decl);
12783         
12784         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
12785       }
12786
12787     case STMT_EXPR:
12788       {
12789         tree old_stmt_expr = cur_stmt_expr;
12790         tree stmt_expr = begin_stmt_expr ();
12791
12792         cur_stmt_expr = stmt_expr;
12793         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
12794                      integral_constant_expression_p);
12795         stmt_expr = finish_stmt_expr (stmt_expr, false);
12796         cur_stmt_expr = old_stmt_expr;
12797
12798         /* If the resulting list of expression statement is empty,
12799            fold it further into void_zero_node.  */
12800         if (empty_expr_stmt_p (stmt_expr))
12801           stmt_expr = void_zero_node;
12802
12803         return stmt_expr;
12804       }
12805
12806     case CONST_DECL:
12807       t = tsubst_copy (t, args, complain, in_decl);
12808       /* As in finish_id_expression, we resolve enumeration constants
12809          to their underlying values.  */
12810       if (TREE_CODE (t) == CONST_DECL)
12811         {
12812           used_types_insert (TREE_TYPE (t));
12813           return DECL_INITIAL (t);
12814         }
12815       return t;
12816
12817     case LAMBDA_EXPR:
12818       {
12819         tree r = build_lambda_expr ();
12820
12821         tree type = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
12822         TREE_TYPE (r) = type;
12823         CLASSTYPE_LAMBDA_EXPR (type) = r;
12824
12825         LAMBDA_EXPR_LOCATION (r)
12826           = LAMBDA_EXPR_LOCATION (t);
12827         LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
12828           = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
12829         LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
12830         LAMBDA_EXPR_DISCRIMINATOR (r)
12831           = (LAMBDA_EXPR_DISCRIMINATOR (t));
12832         LAMBDA_EXPR_CAPTURE_LIST (r)
12833           = RECUR (LAMBDA_EXPR_CAPTURE_LIST (t));
12834         LAMBDA_EXPR_THIS_CAPTURE (r)
12835           = RECUR (LAMBDA_EXPR_THIS_CAPTURE (t));
12836         LAMBDA_EXPR_EXTRA_SCOPE (r)
12837           = RECUR (LAMBDA_EXPR_EXTRA_SCOPE (t));
12838
12839         /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
12840         determine_visibility (TYPE_NAME (type));
12841         /* Now that we know visibility, instantiate the type so we have a
12842            declaration of the op() for later calls to lambda_function.  */
12843         complete_type (type);
12844
12845         type = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
12846         if (type)
12847           apply_lambda_return_type (r, type);
12848
12849         return build_lambda_object (r);
12850       }
12851
12852     default:
12853       /* Handle Objective-C++ constructs, if appropriate.  */
12854       {
12855         tree subst
12856           = objcp_tsubst_copy_and_build (t, args, complain,
12857                                          in_decl, /*function_p=*/false);
12858         if (subst)
12859           return subst;
12860       }
12861       return tsubst_copy (t, args, complain, in_decl);
12862     }
12863
12864 #undef RECUR
12865 }
12866
12867 /* Verify that the instantiated ARGS are valid. For type arguments,
12868    make sure that the type's linkage is ok. For non-type arguments,
12869    make sure they are constants if they are integral or enumerations.
12870    Emit an error under control of COMPLAIN, and return TRUE on error.  */
12871
12872 static bool
12873 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
12874 {
12875   if (ARGUMENT_PACK_P (t))
12876     {
12877       tree vec = ARGUMENT_PACK_ARGS (t);
12878       int len = TREE_VEC_LENGTH (vec);
12879       bool result = false;
12880       int i;
12881
12882       for (i = 0; i < len; ++i)
12883         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
12884           result = true;
12885       return result;
12886     }
12887   else if (TYPE_P (t))
12888     {
12889       /* [basic.link]: A name with no linkage (notably, the name
12890          of a class or enumeration declared in a local scope)
12891          shall not be used to declare an entity with linkage.
12892          This implies that names with no linkage cannot be used as
12893          template arguments
12894
12895          DR 757 relaxes this restriction for C++0x.  */
12896       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
12897                  : no_linkage_check (t, /*relaxed_p=*/false));
12898
12899       if (nt)
12900         {
12901           /* DR 488 makes use of a type with no linkage cause
12902              type deduction to fail.  */
12903           if (complain & tf_error)
12904             {
12905               if (TYPE_ANONYMOUS_P (nt))
12906                 error ("%qT is/uses anonymous type", t);
12907               else
12908                 error ("template argument for %qD uses local type %qT",
12909                        tmpl, t);
12910             }
12911           return true;
12912         }
12913       /* In order to avoid all sorts of complications, we do not
12914          allow variably-modified types as template arguments.  */
12915       else if (variably_modified_type_p (t, NULL_TREE))
12916         {
12917           if (complain & tf_error)
12918             error ("%qT is a variably modified type", t);
12919           return true;
12920         }
12921     }
12922   /* A non-type argument of integral or enumerated type must be a
12923      constant.  */
12924   else if (TREE_TYPE (t)
12925            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
12926            && !TREE_CONSTANT (t))
12927     {
12928       if (complain & tf_error)
12929         error ("integral expression %qE is not constant", t);
12930       return true;
12931     }
12932   return false;
12933 }
12934
12935 static bool
12936 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
12937 {
12938   int ix, len = DECL_NTPARMS (tmpl);
12939   bool result = false;
12940
12941   for (ix = 0; ix != len; ix++)
12942     {
12943       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
12944         result = true;
12945     }
12946   if (result && (complain & tf_error))
12947     error ("  trying to instantiate %qD", tmpl);
12948   return result;
12949 }
12950
12951 /* Instantiate the indicated variable or function template TMPL with
12952    the template arguments in TARG_PTR.  */
12953
12954 tree
12955 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
12956 {
12957   tree targ_ptr = orig_args;
12958   tree fndecl;
12959   tree gen_tmpl;
12960   tree spec;
12961   HOST_WIDE_INT saved_processing_template_decl;
12962
12963   if (tmpl == error_mark_node)
12964     return error_mark_node;
12965
12966   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
12967
12968   /* If this function is a clone, handle it specially.  */
12969   if (DECL_CLONED_FUNCTION_P (tmpl))
12970     {
12971       tree spec;
12972       tree clone;
12973
12974       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
12975          DECL_CLONED_FUNCTION.  */
12976       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
12977                                    targ_ptr, complain);
12978       if (spec == error_mark_node)
12979         return error_mark_node;
12980
12981       /* Look for the clone.  */
12982       FOR_EACH_CLONE (clone, spec)
12983         if (DECL_NAME (clone) == DECL_NAME (tmpl))
12984           return clone;
12985       /* We should always have found the clone by now.  */
12986       gcc_unreachable ();
12987       return NULL_TREE;
12988     }
12989
12990   /* Check to see if we already have this specialization.  */
12991   gen_tmpl = most_general_template (tmpl);
12992   if (tmpl != gen_tmpl)
12993     /* The TMPL is a partial instantiation.  To get a full set of
12994        arguments we must add the arguments used to perform the
12995        partial instantiation.  */
12996     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
12997                                             targ_ptr);
12998
12999   /* It would be nice to avoid hashing here and then again in tsubst_decl,
13000      but it doesn't seem to be on the hot path.  */
13001   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
13002
13003   gcc_assert (tmpl == gen_tmpl
13004               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
13005                   == spec)
13006               || fndecl == NULL_TREE);
13007
13008   if (spec != NULL_TREE)
13009     return spec;
13010
13011   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
13012                                complain))
13013     return error_mark_node;
13014
13015   /* We are building a FUNCTION_DECL, during which the access of its
13016      parameters and return types have to be checked.  However this
13017      FUNCTION_DECL which is the desired context for access checking
13018      is not built yet.  We solve this chicken-and-egg problem by
13019      deferring all checks until we have the FUNCTION_DECL.  */
13020   push_deferring_access_checks (dk_deferred);
13021
13022   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
13023      (because, for example, we have encountered a non-dependent
13024      function call in the body of a template function and must now
13025      determine which of several overloaded functions will be called),
13026      within the instantiation itself we are not processing a
13027      template.  */  
13028   saved_processing_template_decl = processing_template_decl;
13029   processing_template_decl = 0;
13030   /* Substitute template parameters to obtain the specialization.  */
13031   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
13032                    targ_ptr, complain, gen_tmpl);
13033   processing_template_decl = saved_processing_template_decl;
13034   if (fndecl == error_mark_node)
13035     return error_mark_node;
13036
13037   /* Now we know the specialization, compute access previously
13038      deferred.  */
13039   push_access_scope (fndecl);
13040
13041   /* Some typedefs referenced from within the template code need to be access
13042      checked at template instantiation time, i.e now. These types were
13043      added to the template at parsing time. Let's get those and perfom
13044      the acces checks then.  */
13045   perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
13046   perform_deferred_access_checks ();
13047   pop_access_scope (fndecl);
13048   pop_deferring_access_checks ();
13049
13050   /* The DECL_TI_TEMPLATE should always be the immediate parent
13051      template, not the most general template.  */
13052   DECL_TI_TEMPLATE (fndecl) = tmpl;
13053
13054   /* If we've just instantiated the main entry point for a function,
13055      instantiate all the alternate entry points as well.  We do this
13056      by cloning the instantiation of the main entry point, not by
13057      instantiating the template clones.  */
13058   if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
13059     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
13060
13061   return fndecl;
13062 }
13063
13064 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
13065    NARGS elements of the arguments that are being used when calling
13066    it.  TARGS is a vector into which the deduced template arguments
13067    are placed.
13068
13069    Return zero for success, 2 for an incomplete match that doesn't resolve
13070    all the types, and 1 for complete failure.  An error message will be
13071    printed only for an incomplete match.
13072
13073    If FN is a conversion operator, or we are trying to produce a specific
13074    specialization, RETURN_TYPE is the return type desired.
13075
13076    The EXPLICIT_TARGS are explicit template arguments provided via a
13077    template-id.
13078
13079    The parameter STRICT is one of:
13080
13081    DEDUCE_CALL:
13082      We are deducing arguments for a function call, as in
13083      [temp.deduct.call].
13084
13085    DEDUCE_CONV:
13086      We are deducing arguments for a conversion function, as in
13087      [temp.deduct.conv].
13088
13089    DEDUCE_EXACT:
13090      We are deducing arguments when doing an explicit instantiation
13091      as in [temp.explicit], when determining an explicit specialization
13092      as in [temp.expl.spec], or when taking the address of a function
13093      template, as in [temp.deduct.funcaddr].  */
13094
13095 int
13096 fn_type_unification (tree fn,
13097                      tree explicit_targs,
13098                      tree targs,
13099                      const tree *args,
13100                      unsigned int nargs,
13101                      tree return_type,
13102                      unification_kind_t strict,
13103                      int flags)
13104 {
13105   tree parms;
13106   tree fntype;
13107   int result;
13108   bool incomplete_argument_packs_p = false;
13109
13110   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
13111
13112   fntype = TREE_TYPE (fn);
13113   if (explicit_targs)
13114     {
13115       /* [temp.deduct]
13116
13117          The specified template arguments must match the template
13118          parameters in kind (i.e., type, nontype, template), and there
13119          must not be more arguments than there are parameters;
13120          otherwise type deduction fails.
13121
13122          Nontype arguments must match the types of the corresponding
13123          nontype template parameters, or must be convertible to the
13124          types of the corresponding nontype parameters as specified in
13125          _temp.arg.nontype_, otherwise type deduction fails.
13126
13127          All references in the function type of the function template
13128          to the corresponding template parameters are replaced by the
13129          specified template argument values.  If a substitution in a
13130          template parameter or in the function type of the function
13131          template results in an invalid type, type deduction fails.  */
13132       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
13133       int i, len = TREE_VEC_LENGTH (tparms);
13134       tree converted_args;
13135       bool incomplete = false;
13136
13137       if (explicit_targs == error_mark_node)
13138         return 1;
13139
13140       converted_args
13141         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
13142                                   /*require_all_args=*/false,
13143                                   /*use_default_args=*/false));
13144       if (converted_args == error_mark_node)
13145         return 1;
13146
13147       /* Substitute the explicit args into the function type.  This is
13148          necessary so that, for instance, explicitly declared function
13149          arguments can match null pointed constants.  If we were given
13150          an incomplete set of explicit args, we must not do semantic
13151          processing during substitution as we could create partial
13152          instantiations.  */
13153       for (i = 0; i < len; i++)
13154         {
13155           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13156           bool parameter_pack = false;
13157
13158           /* Dig out the actual parm.  */
13159           if (TREE_CODE (parm) == TYPE_DECL
13160               || TREE_CODE (parm) == TEMPLATE_DECL)
13161             {
13162               parm = TREE_TYPE (parm);
13163               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
13164             }
13165           else if (TREE_CODE (parm) == PARM_DECL)
13166             {
13167               parm = DECL_INITIAL (parm);
13168               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
13169             }
13170
13171           if (parameter_pack)
13172             {
13173               int level, idx;
13174               tree targ;
13175               template_parm_level_and_index (parm, &level, &idx);
13176
13177               /* Mark the argument pack as "incomplete". We could
13178                  still deduce more arguments during unification.  */
13179               targ = TMPL_ARG (converted_args, level, idx);
13180               if (targ)
13181                 {
13182                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
13183                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
13184                     = ARGUMENT_PACK_ARGS (targ);
13185                 }
13186
13187               /* We have some incomplete argument packs.  */
13188               incomplete_argument_packs_p = true;
13189             }
13190         }
13191
13192       if (incomplete_argument_packs_p)
13193         /* Any substitution is guaranteed to be incomplete if there
13194            are incomplete argument packs, because we can still deduce
13195            more arguments.  */
13196         incomplete = 1;
13197       else
13198         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
13199
13200       processing_template_decl += incomplete;
13201       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
13202       processing_template_decl -= incomplete;
13203
13204       if (fntype == error_mark_node)
13205         return 1;
13206
13207       /* Place the explicitly specified arguments in TARGS.  */
13208       for (i = NUM_TMPL_ARGS (converted_args); i--;)
13209         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
13210     }
13211
13212   /* Never do unification on the 'this' parameter.  */
13213   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
13214
13215   if (return_type)
13216     {
13217       tree *new_args;
13218
13219       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
13220       new_args = XALLOCAVEC (tree, nargs + 1);
13221       new_args[0] = return_type;
13222       memcpy (new_args + 1, args, nargs * sizeof (tree));
13223       args = new_args;
13224       ++nargs;
13225     }
13226
13227   /* We allow incomplete unification without an error message here
13228      because the standard doesn't seem to explicitly prohibit it.  Our
13229      callers must be ready to deal with unification failures in any
13230      event.  */
13231   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
13232                                   targs, parms, args, nargs, /*subr=*/0,
13233                                   strict, flags);
13234
13235   if (result == 0 && incomplete_argument_packs_p)
13236     {
13237       int i, len = NUM_TMPL_ARGS (targs);
13238
13239       /* Clear the "incomplete" flags on all argument packs.  */
13240       for (i = 0; i < len; i++)
13241         {
13242           tree arg = TREE_VEC_ELT (targs, i);
13243           if (ARGUMENT_PACK_P (arg))
13244             {
13245               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
13246               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
13247             }
13248         }
13249     }
13250
13251   /* Now that we have bindings for all of the template arguments,
13252      ensure that the arguments deduced for the template template
13253      parameters have compatible template parameter lists.  We cannot
13254      check this property before we have deduced all template
13255      arguments, because the template parameter types of a template
13256      template parameter might depend on prior template parameters
13257      deduced after the template template parameter.  The following
13258      ill-formed example illustrates this issue:
13259
13260        template<typename T, template<T> class C> void f(C<5>, T);
13261
13262        template<int N> struct X {};
13263
13264        void g() {
13265          f(X<5>(), 5l); // error: template argument deduction fails
13266        }
13267
13268      The template parameter list of 'C' depends on the template type
13269      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
13270      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
13271      time that we deduce 'C'.  */
13272   if (result == 0
13273       && !template_template_parm_bindings_ok_p 
13274            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
13275     return 1;
13276
13277   if (result == 0)
13278     /* All is well so far.  Now, check:
13279
13280        [temp.deduct]
13281
13282        When all template arguments have been deduced, all uses of
13283        template parameters in nondeduced contexts are replaced with
13284        the corresponding deduced argument values.  If the
13285        substitution results in an invalid type, as described above,
13286        type deduction fails.  */
13287     {
13288       tree substed = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
13289       if (substed == error_mark_node)
13290         return 1;
13291
13292       /* If we're looking for an exact match, check that what we got
13293          is indeed an exact match.  It might not be if some template
13294          parameters are used in non-deduced contexts.  */
13295       if (strict == DEDUCE_EXACT)
13296         {
13297           unsigned int i;
13298
13299           tree sarg
13300             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
13301           if (return_type)
13302             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
13303           for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
13304             if (!same_type_p (args[i], TREE_VALUE (sarg)))
13305               return 1;
13306         }
13307     }
13308
13309   return result;
13310 }
13311
13312 /* Adjust types before performing type deduction, as described in
13313    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
13314    sections are symmetric.  PARM is the type of a function parameter
13315    or the return type of the conversion function.  ARG is the type of
13316    the argument passed to the call, or the type of the value
13317    initialized with the result of the conversion function.
13318    ARG_EXPR is the original argument expression, which may be null.  */
13319
13320 static int
13321 maybe_adjust_types_for_deduction (unification_kind_t strict,
13322                                   tree* parm,
13323                                   tree* arg,
13324                                   tree arg_expr)
13325 {
13326   int result = 0;
13327
13328   switch (strict)
13329     {
13330     case DEDUCE_CALL:
13331       break;
13332
13333     case DEDUCE_CONV:
13334       {
13335         /* Swap PARM and ARG throughout the remainder of this
13336            function; the handling is precisely symmetric since PARM
13337            will initialize ARG rather than vice versa.  */
13338         tree* temp = parm;
13339         parm = arg;
13340         arg = temp;
13341         break;
13342       }
13343
13344     case DEDUCE_EXACT:
13345       /* Core issue #873: Do the DR606 thing (see below) for these cases,
13346          too, but here handle it by stripping the reference from PARM
13347          rather than by adding it to ARG.  */
13348       if (TREE_CODE (*parm) == REFERENCE_TYPE
13349           && TYPE_REF_IS_RVALUE (*parm)
13350           && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13351           && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13352           && TREE_CODE (*arg) == REFERENCE_TYPE
13353           && !TYPE_REF_IS_RVALUE (*arg))
13354         *parm = TREE_TYPE (*parm);
13355       /* Nothing else to do in this case.  */
13356       return 0;
13357
13358     default:
13359       gcc_unreachable ();
13360     }
13361
13362   if (TREE_CODE (*parm) != REFERENCE_TYPE)
13363     {
13364       /* [temp.deduct.call]
13365
13366          If P is not a reference type:
13367
13368          --If A is an array type, the pointer type produced by the
13369          array-to-pointer standard conversion (_conv.array_) is
13370          used in place of A for type deduction; otherwise,
13371
13372          --If A is a function type, the pointer type produced by
13373          the function-to-pointer standard conversion
13374          (_conv.func_) is used in place of A for type deduction;
13375          otherwise,
13376
13377          --If A is a cv-qualified type, the top level
13378          cv-qualifiers of A's type are ignored for type
13379          deduction.  */
13380       if (TREE_CODE (*arg) == ARRAY_TYPE)
13381         *arg = build_pointer_type (TREE_TYPE (*arg));
13382       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
13383         *arg = build_pointer_type (*arg);
13384       else
13385         *arg = TYPE_MAIN_VARIANT (*arg);
13386     }
13387
13388   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
13389      of the form T&&, where T is a template parameter, and the argument
13390      is an lvalue, T is deduced as A& */
13391   if (TREE_CODE (*parm) == REFERENCE_TYPE
13392       && TYPE_REF_IS_RVALUE (*parm)
13393       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13394       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13395       && arg_expr && real_lvalue_p (arg_expr))
13396     *arg = build_reference_type (*arg);
13397
13398   /* [temp.deduct.call]
13399
13400      If P is a cv-qualified type, the top level cv-qualifiers
13401      of P's type are ignored for type deduction.  If P is a
13402      reference type, the type referred to by P is used for
13403      type deduction.  */
13404   *parm = TYPE_MAIN_VARIANT (*parm);
13405   if (TREE_CODE (*parm) == REFERENCE_TYPE)
13406     {
13407       *parm = TREE_TYPE (*parm);
13408       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
13409     }
13410
13411   /* DR 322. For conversion deduction, remove a reference type on parm
13412      too (which has been swapped into ARG).  */
13413   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
13414     *arg = TREE_TYPE (*arg);
13415
13416   return result;
13417 }
13418
13419 /* Most parms like fn_type_unification.
13420
13421    If SUBR is 1, we're being called recursively (to unify the
13422    arguments of a function or method parameter of a function
13423    template). */
13424
13425 static int
13426 type_unification_real (tree tparms,
13427                        tree targs,
13428                        tree xparms,
13429                        const tree *xargs,
13430                        unsigned int xnargs,
13431                        int subr,
13432                        unification_kind_t strict,
13433                        int flags)
13434 {
13435   tree parm, arg, arg_expr;
13436   int i;
13437   int ntparms = TREE_VEC_LENGTH (tparms);
13438   int sub_strict;
13439   int saw_undeduced = 0;
13440   tree parms;
13441   const tree *args;
13442   unsigned int nargs;
13443   unsigned int ia;
13444
13445   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
13446   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
13447   gcc_assert (ntparms > 0);
13448
13449   /* Reset the number of non-defaulted template arguments contained
13450      in in TARGS.  */
13451   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
13452
13453   switch (strict)
13454     {
13455     case DEDUCE_CALL:
13456       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
13457                     | UNIFY_ALLOW_DERIVED);
13458       break;
13459
13460     case DEDUCE_CONV:
13461       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
13462       break;
13463
13464     case DEDUCE_EXACT:
13465       sub_strict = UNIFY_ALLOW_NONE;
13466       break;
13467
13468     default:
13469       gcc_unreachable ();
13470     }
13471
13472  again:
13473   parms = xparms;
13474   args = xargs;
13475   nargs = xnargs;
13476
13477   ia = 0;
13478   while (parms && parms != void_list_node
13479          && ia < nargs)
13480     {
13481       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13482         break;
13483
13484       parm = TREE_VALUE (parms);
13485       parms = TREE_CHAIN (parms);
13486       arg = args[ia];
13487       ++ia;
13488       arg_expr = NULL;
13489
13490       if (arg == error_mark_node)
13491         return 1;
13492       if (arg == unknown_type_node)
13493         /* We can't deduce anything from this, but we might get all the
13494            template args from other function args.  */
13495         continue;
13496
13497       /* Conversions will be performed on a function argument that
13498          corresponds with a function parameter that contains only
13499          non-deducible template parameters and explicitly specified
13500          template parameters.  */
13501       if (!uses_template_parms (parm))
13502         {
13503           tree type;
13504
13505           if (!TYPE_P (arg))
13506             type = TREE_TYPE (arg);
13507           else
13508             type = arg;
13509
13510           if (same_type_p (parm, type))
13511             continue;
13512           if (strict != DEDUCE_EXACT
13513               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
13514                                   flags))
13515             continue;
13516
13517           return 1;
13518         }
13519
13520       if (!TYPE_P (arg))
13521         {
13522           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
13523           if (type_unknown_p (arg))
13524             {
13525               /* [temp.deduct.type] 
13526
13527                  A template-argument can be deduced from a pointer to
13528                  function or pointer to member function argument if
13529                  the set of overloaded functions does not contain
13530                  function templates and at most one of a set of
13531                  overloaded functions provides a unique match.  */
13532               if (resolve_overloaded_unification
13533                   (tparms, targs, parm, arg, strict, sub_strict))
13534                 continue;
13535
13536               return 1;
13537             }
13538           arg_expr = arg;
13539           arg = unlowered_expr_type (arg);
13540           if (arg == error_mark_node)
13541             return 1;
13542         }
13543
13544       {
13545         int arg_strict = sub_strict;
13546
13547         if (!subr)
13548           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
13549                                                           arg_expr);
13550
13551         if (arg == init_list_type_node && arg_expr)
13552           arg = arg_expr;
13553         if (unify (tparms, targs, parm, arg, arg_strict))
13554           return 1;
13555       }
13556     }
13557
13558
13559   if (parms 
13560       && parms != void_list_node
13561       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13562     {
13563       /* Unify the remaining arguments with the pack expansion type.  */
13564       tree argvec;
13565       tree parmvec = make_tree_vec (1);
13566
13567       /* Allocate a TREE_VEC and copy in all of the arguments */ 
13568       argvec = make_tree_vec (nargs - ia);
13569       for (i = 0; ia < nargs; ++ia, ++i)
13570         TREE_VEC_ELT (argvec, i) = args[ia];
13571
13572       /* Copy the parameter into parmvec.  */
13573       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
13574       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
13575                                 /*call_args_p=*/true, /*subr=*/subr))
13576         return 1;
13577
13578       /* Advance to the end of the list of parameters.  */
13579       parms = TREE_CHAIN (parms);
13580     }
13581
13582   /* Fail if we've reached the end of the parm list, and more args
13583      are present, and the parm list isn't variadic.  */
13584   if (ia < nargs && parms == void_list_node)
13585     return 1;
13586   /* Fail if parms are left and they don't have default values.  */
13587   if (parms && parms != void_list_node
13588       && TREE_PURPOSE (parms) == NULL_TREE)
13589     return 1;
13590
13591   if (!subr)
13592     for (i = 0; i < ntparms; i++)
13593       if (!TREE_VEC_ELT (targs, i))
13594         {
13595           tree tparm;
13596
13597           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
13598             continue;
13599
13600           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13601
13602           /* If this is an undeduced nontype parameter that depends on
13603              a type parameter, try another pass; its type may have been
13604              deduced from a later argument than the one from which
13605              this parameter can be deduced.  */
13606           if (TREE_CODE (tparm) == PARM_DECL
13607               && uses_template_parms (TREE_TYPE (tparm))
13608               && !saw_undeduced++)
13609             goto again;
13610
13611           /* Core issue #226 (C++0x) [temp.deduct]:
13612
13613                If a template argument has not been deduced, its
13614                default template argument, if any, is used. 
13615
13616              When we are in C++98 mode, TREE_PURPOSE will either
13617              be NULL_TREE or ERROR_MARK_NODE, so we do not need
13618              to explicitly check cxx_dialect here.  */
13619           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
13620             {
13621               tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13622               tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
13623               arg = tsubst_template_arg (arg, targs, tf_none, NULL_TREE);
13624               arg = convert_template_argument (parm, arg, targs, tf_none,
13625                                                i, NULL_TREE);
13626               if (arg == error_mark_node)
13627                 return 1;
13628               else
13629                 {
13630                   TREE_VEC_ELT (targs, i) = arg;
13631                   /* The position of the first default template argument,
13632                      is also the number of non-defaulted arguments in TARGS.
13633                      Record that.  */
13634                   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
13635                     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
13636                   continue;
13637                 }
13638             }
13639
13640           /* If the type parameter is a parameter pack, then it will
13641              be deduced to an empty parameter pack.  */
13642           if (template_parameter_pack_p (tparm))
13643             {
13644               tree arg;
13645
13646               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
13647                 {
13648                   arg = make_node (NONTYPE_ARGUMENT_PACK);
13649                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
13650                   TREE_CONSTANT (arg) = 1;
13651                 }
13652               else
13653                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
13654
13655               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
13656
13657               TREE_VEC_ELT (targs, i) = arg;
13658               continue;
13659             }
13660
13661           return 2;
13662         }
13663 #ifdef ENABLE_CHECKING
13664   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
13665     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
13666 #endif
13667
13668   return 0;
13669 }
13670
13671 /* Subroutine of type_unification_real.  Args are like the variables
13672    at the call site.  ARG is an overloaded function (or template-id);
13673    we try deducing template args from each of the overloads, and if
13674    only one succeeds, we go with that.  Modifies TARGS and returns
13675    true on success.  */
13676
13677 static bool
13678 resolve_overloaded_unification (tree tparms,
13679                                 tree targs,
13680                                 tree parm,
13681                                 tree arg,
13682                                 unification_kind_t strict,
13683                                 int sub_strict)
13684 {
13685   tree tempargs = copy_node (targs);
13686   int good = 0;
13687   tree goodfn = NULL_TREE;
13688   bool addr_p;
13689
13690   if (TREE_CODE (arg) == ADDR_EXPR)
13691     {
13692       arg = TREE_OPERAND (arg, 0);
13693       addr_p = true;
13694     }
13695   else
13696     addr_p = false;
13697
13698   if (TREE_CODE (arg) == COMPONENT_REF)
13699     /* Handle `&x' where `x' is some static or non-static member
13700        function name.  */
13701     arg = TREE_OPERAND (arg, 1);
13702
13703   if (TREE_CODE (arg) == OFFSET_REF)
13704     arg = TREE_OPERAND (arg, 1);
13705
13706   /* Strip baselink information.  */
13707   if (BASELINK_P (arg))
13708     arg = BASELINK_FUNCTIONS (arg);
13709
13710   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
13711     {
13712       /* If we got some explicit template args, we need to plug them into
13713          the affected templates before we try to unify, in case the
13714          explicit args will completely resolve the templates in question.  */
13715
13716       tree expl_subargs = TREE_OPERAND (arg, 1);
13717       arg = TREE_OPERAND (arg, 0);
13718
13719       for (; arg; arg = OVL_NEXT (arg))
13720         {
13721           tree fn = OVL_CURRENT (arg);
13722           tree subargs, elem;
13723
13724           if (TREE_CODE (fn) != TEMPLATE_DECL)
13725             continue;
13726
13727           ++processing_template_decl;
13728           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13729                                   expl_subargs, /*check_ret=*/false);
13730           if (subargs)
13731             {
13732               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
13733               if (try_one_overload (tparms, targs, tempargs, parm,
13734                                     elem, strict, sub_strict, addr_p)
13735                   && (!goodfn || !decls_match (goodfn, elem)))
13736                 {
13737                   goodfn = elem;
13738                   ++good;
13739                 }
13740             }
13741           --processing_template_decl;
13742         }
13743     }
13744   else if (TREE_CODE (arg) != OVERLOAD
13745            && TREE_CODE (arg) != FUNCTION_DECL)
13746     /* If ARG is, for example, "(0, &f)" then its type will be unknown
13747        -- but the deduction does not succeed because the expression is
13748        not just the function on its own.  */
13749     return false;
13750   else
13751     for (; arg; arg = OVL_NEXT (arg))
13752       if (try_one_overload (tparms, targs, tempargs, parm,
13753                             TREE_TYPE (OVL_CURRENT (arg)),
13754                             strict, sub_strict, addr_p)
13755           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
13756         {
13757           goodfn = OVL_CURRENT (arg);
13758           ++good;
13759         }
13760
13761   /* [temp.deduct.type] A template-argument can be deduced from a pointer
13762      to function or pointer to member function argument if the set of
13763      overloaded functions does not contain function templates and at most
13764      one of a set of overloaded functions provides a unique match.
13765
13766      So if we found multiple possibilities, we return success but don't
13767      deduce anything.  */
13768
13769   if (good == 1)
13770     {
13771       int i = TREE_VEC_LENGTH (targs);
13772       for (; i--; )
13773         if (TREE_VEC_ELT (tempargs, i))
13774           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
13775     }
13776   if (good)
13777     return true;
13778
13779   return false;
13780 }
13781
13782 /* Core DR 115: In contexts where deduction is done and fails, or in
13783    contexts where deduction is not done, if a template argument list is
13784    specified and it, along with any default template arguments, identifies
13785    a single function template specialization, then the template-id is an
13786    lvalue for the function template specialization.  */
13787
13788 tree
13789 resolve_nondeduced_context (tree orig_expr)
13790 {
13791   tree expr, offset, baselink;
13792   bool addr;
13793
13794   if (!type_unknown_p (orig_expr))
13795     return orig_expr;
13796
13797   expr = orig_expr;
13798   addr = false;
13799   offset = NULL_TREE;
13800   baselink = NULL_TREE;
13801
13802   if (TREE_CODE (expr) == ADDR_EXPR)
13803     {
13804       expr = TREE_OPERAND (expr, 0);
13805       addr = true;
13806     }
13807   if (TREE_CODE (expr) == OFFSET_REF)
13808     {
13809       offset = expr;
13810       expr = TREE_OPERAND (expr, 1);
13811     }
13812   if (TREE_CODE (expr) == BASELINK)
13813     {
13814       baselink = expr;
13815       expr = BASELINK_FUNCTIONS (expr);
13816     }
13817
13818   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
13819     {
13820       int good = 0;
13821       tree goodfn = NULL_TREE;
13822
13823       /* If we got some explicit template args, we need to plug them into
13824          the affected templates before we try to unify, in case the
13825          explicit args will completely resolve the templates in question.  */
13826
13827       tree expl_subargs = TREE_OPERAND (expr, 1);
13828       tree arg = TREE_OPERAND (expr, 0);
13829       tree badfn = NULL_TREE;
13830       tree badargs = NULL_TREE;
13831
13832       for (; arg; arg = OVL_NEXT (arg))
13833         {
13834           tree fn = OVL_CURRENT (arg);
13835           tree subargs, elem;
13836
13837           if (TREE_CODE (fn) != TEMPLATE_DECL)
13838             continue;
13839
13840           ++processing_template_decl;
13841           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13842                                   expl_subargs, /*check_ret=*/false);
13843           if (subargs && !any_dependent_template_arguments_p (subargs))
13844             {
13845               elem = instantiate_template (fn, subargs, tf_none);
13846               if (elem == error_mark_node)
13847                 {
13848                   badfn = fn;
13849                   badargs = subargs;
13850                 }
13851               else if (elem && (!goodfn || !decls_match (goodfn, elem)))
13852                 {
13853                   goodfn = elem;
13854                   ++good;
13855                 }
13856             }
13857           --processing_template_decl;
13858         }
13859       if (good == 1)
13860         {
13861           expr = goodfn;
13862           if (baselink)
13863             expr = build_baselink (BASELINK_BINFO (baselink),
13864                                    BASELINK_ACCESS_BINFO (baselink),
13865                                    expr, BASELINK_OPTYPE (baselink));
13866           if (offset)
13867             expr = build2 (OFFSET_REF, TREE_TYPE (expr),
13868                            TREE_OPERAND (offset, 0), expr);
13869           if (addr)
13870             expr = build_address (expr);
13871           return expr;
13872         }
13873       else if (good == 0 && badargs)
13874         /* There were no good options and at least one bad one, so let the
13875            user know what the problem is.  */
13876         instantiate_template (badfn, badargs, tf_warning_or_error);
13877     }
13878   return orig_expr;
13879 }
13880
13881 /* Subroutine of resolve_overloaded_unification; does deduction for a single
13882    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
13883    different overloads deduce different arguments for a given parm.
13884    ADDR_P is true if the expression for which deduction is being
13885    performed was of the form "& fn" rather than simply "fn".
13886
13887    Returns 1 on success.  */
13888
13889 static int
13890 try_one_overload (tree tparms,
13891                   tree orig_targs,
13892                   tree targs,
13893                   tree parm,
13894                   tree arg,
13895                   unification_kind_t strict,
13896                   int sub_strict,
13897                   bool addr_p)
13898 {
13899   int nargs;
13900   tree tempargs;
13901   int i;
13902
13903   /* [temp.deduct.type] A template-argument can be deduced from a pointer
13904      to function or pointer to member function argument if the set of
13905      overloaded functions does not contain function templates and at most
13906      one of a set of overloaded functions provides a unique match.
13907
13908      So if this is a template, just return success.  */
13909
13910   if (uses_template_parms (arg))
13911     return 1;
13912
13913   if (TREE_CODE (arg) == METHOD_TYPE)
13914     arg = build_ptrmemfunc_type (build_pointer_type (arg));
13915   else if (addr_p)
13916     arg = build_pointer_type (arg);
13917
13918   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
13919
13920   /* We don't copy orig_targs for this because if we have already deduced
13921      some template args from previous args, unify would complain when we
13922      try to deduce a template parameter for the same argument, even though
13923      there isn't really a conflict.  */
13924   nargs = TREE_VEC_LENGTH (targs);
13925   tempargs = make_tree_vec (nargs);
13926
13927   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
13928     return 0;
13929
13930   /* First make sure we didn't deduce anything that conflicts with
13931      explicitly specified args.  */
13932   for (i = nargs; i--; )
13933     {
13934       tree elt = TREE_VEC_ELT (tempargs, i);
13935       tree oldelt = TREE_VEC_ELT (orig_targs, i);
13936
13937       if (!elt)
13938         /*NOP*/;
13939       else if (uses_template_parms (elt))
13940         /* Since we're unifying against ourselves, we will fill in
13941            template args used in the function parm list with our own
13942            template parms.  Discard them.  */
13943         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
13944       else if (oldelt && !template_args_equal (oldelt, elt))
13945         return 0;
13946     }
13947
13948   for (i = nargs; i--; )
13949     {
13950       tree elt = TREE_VEC_ELT (tempargs, i);
13951
13952       if (elt)
13953         TREE_VEC_ELT (targs, i) = elt;
13954     }
13955
13956   return 1;
13957 }
13958
13959 /* PARM is a template class (perhaps with unbound template
13960    parameters).  ARG is a fully instantiated type.  If ARG can be
13961    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
13962    TARGS are as for unify.  */
13963
13964 static tree
13965 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
13966 {
13967   tree copy_of_targs;
13968
13969   if (!CLASSTYPE_TEMPLATE_INFO (arg)
13970       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
13971           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
13972     return NULL_TREE;
13973
13974   /* We need to make a new template argument vector for the call to
13975      unify.  If we used TARGS, we'd clutter it up with the result of
13976      the attempted unification, even if this class didn't work out.
13977      We also don't want to commit ourselves to all the unifications
13978      we've already done, since unification is supposed to be done on
13979      an argument-by-argument basis.  In other words, consider the
13980      following pathological case:
13981
13982        template <int I, int J, int K>
13983        struct S {};
13984
13985        template <int I, int J>
13986        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
13987
13988        template <int I, int J, int K>
13989        void f(S<I, J, K>, S<I, I, I>);
13990
13991        void g() {
13992          S<0, 0, 0> s0;
13993          S<0, 1, 2> s2;
13994
13995          f(s0, s2);
13996        }
13997
13998      Now, by the time we consider the unification involving `s2', we
13999      already know that we must have `f<0, 0, 0>'.  But, even though
14000      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
14001      because there are two ways to unify base classes of S<0, 1, 2>
14002      with S<I, I, I>.  If we kept the already deduced knowledge, we
14003      would reject the possibility I=1.  */
14004   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
14005
14006   /* If unification failed, we're done.  */
14007   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
14008              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
14009     return NULL_TREE;
14010
14011   return arg;
14012 }
14013
14014 /* Given a template type PARM and a class type ARG, find the unique
14015    base type in ARG that is an instance of PARM.  We do not examine
14016    ARG itself; only its base-classes.  If there is not exactly one
14017    appropriate base class, return NULL_TREE.  PARM may be the type of
14018    a partial specialization, as well as a plain template type.  Used
14019    by unify.  */
14020
14021 static tree
14022 get_template_base (tree tparms, tree targs, tree parm, tree arg)
14023 {
14024   tree rval = NULL_TREE;
14025   tree binfo;
14026
14027   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
14028
14029   binfo = TYPE_BINFO (complete_type (arg));
14030   if (!binfo)
14031     /* The type could not be completed.  */
14032     return NULL_TREE;
14033
14034   /* Walk in inheritance graph order.  The search order is not
14035      important, and this avoids multiple walks of virtual bases.  */
14036   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
14037     {
14038       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
14039
14040       if (r)
14041         {
14042           /* If there is more than one satisfactory baseclass, then:
14043
14044                [temp.deduct.call]
14045
14046               If they yield more than one possible deduced A, the type
14047               deduction fails.
14048
14049              applies.  */
14050           if (rval && !same_type_p (r, rval))
14051             return NULL_TREE;
14052
14053           rval = r;
14054         }
14055     }
14056
14057   return rval;
14058 }
14059
14060 /* Returns the level of DECL, which declares a template parameter.  */
14061
14062 static int
14063 template_decl_level (tree decl)
14064 {
14065   switch (TREE_CODE (decl))
14066     {
14067     case TYPE_DECL:
14068     case TEMPLATE_DECL:
14069       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
14070
14071     case PARM_DECL:
14072       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
14073
14074     default:
14075       gcc_unreachable ();
14076     }
14077   return 0;
14078 }
14079
14080 /* Decide whether ARG can be unified with PARM, considering only the
14081    cv-qualifiers of each type, given STRICT as documented for unify.
14082    Returns nonzero iff the unification is OK on that basis.  */
14083
14084 static int
14085 check_cv_quals_for_unify (int strict, tree arg, tree parm)
14086 {
14087   int arg_quals = cp_type_quals (arg);
14088   int parm_quals = cp_type_quals (parm);
14089
14090   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14091       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
14092     {
14093       /*  Although a CVR qualifier is ignored when being applied to a
14094           substituted template parameter ([8.3.2]/1 for example), that
14095           does not apply during deduction [14.8.2.4]/1, (even though
14096           that is not explicitly mentioned, [14.8.2.4]/9 indicates
14097           this).  Except when we're allowing additional CV qualifiers
14098           at the outer level [14.8.2.1]/3,1st bullet.  */
14099       if ((TREE_CODE (arg) == REFERENCE_TYPE
14100            || TREE_CODE (arg) == FUNCTION_TYPE
14101            || TREE_CODE (arg) == METHOD_TYPE)
14102           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
14103         return 0;
14104
14105       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
14106           && (parm_quals & TYPE_QUAL_RESTRICT))
14107         return 0;
14108     }
14109
14110   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
14111       && (arg_quals & parm_quals) != parm_quals)
14112     return 0;
14113
14114   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
14115       && (parm_quals & arg_quals) != arg_quals)
14116     return 0;
14117
14118   return 1;
14119 }
14120
14121 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
14122 void 
14123 template_parm_level_and_index (tree parm, int* level, int* index)
14124 {
14125   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14126       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14127       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14128     {
14129       *index = TEMPLATE_TYPE_IDX (parm);
14130       *level = TEMPLATE_TYPE_LEVEL (parm);
14131     }
14132   else
14133     {
14134       *index = TEMPLATE_PARM_IDX (parm);
14135       *level = TEMPLATE_PARM_LEVEL (parm);
14136     }
14137 }
14138
14139 /* Unifies the remaining arguments in PACKED_ARGS with the pack
14140    expansion at the end of PACKED_PARMS. Returns 0 if the type
14141    deduction succeeds, 1 otherwise. STRICT is the same as in
14142    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
14143    call argument list. We'll need to adjust the arguments to make them
14144    types. SUBR tells us if this is from a recursive call to
14145    type_unification_real.  */
14146 int
14147 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
14148                       tree packed_args, int strict, bool call_args_p,
14149                       bool subr)
14150 {
14151   tree parm 
14152     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
14153   tree pattern = PACK_EXPANSION_PATTERN (parm);
14154   tree pack, packs = NULL_TREE;
14155   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
14156   int len = TREE_VEC_LENGTH (packed_args);
14157
14158   /* Determine the parameter packs we will be deducing from the
14159      pattern, and record their current deductions.  */
14160   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
14161        pack; pack = TREE_CHAIN (pack))
14162     {
14163       tree parm_pack = TREE_VALUE (pack);
14164       int idx, level;
14165
14166       /* Determine the index and level of this parameter pack.  */
14167       template_parm_level_and_index (parm_pack, &level, &idx);
14168
14169       /* Keep track of the parameter packs and their corresponding
14170          argument packs.  */
14171       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
14172       TREE_TYPE (packs) = make_tree_vec (len - start);
14173     }
14174   
14175   /* Loop through all of the arguments that have not yet been
14176      unified and unify each with the pattern.  */
14177   for (i = start; i < len; i++)
14178     {
14179       tree parm = pattern;
14180
14181       /* For each parameter pack, clear out the deduced value so that
14182          we can deduce it again.  */
14183       for (pack = packs; pack; pack = TREE_CHAIN (pack))
14184         {
14185           int idx, level;
14186           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14187
14188           TMPL_ARG (targs, level, idx) = NULL_TREE;
14189         }
14190
14191       /* Unify the pattern with the current argument.  */
14192       {
14193         tree arg = TREE_VEC_ELT (packed_args, i);
14194         tree arg_expr = NULL_TREE;
14195         int arg_strict = strict;
14196         bool skip_arg_p = false;
14197
14198         if (call_args_p)
14199           {
14200             int sub_strict;
14201
14202             /* This mirrors what we do in type_unification_real.  */
14203             switch (strict)
14204               {
14205               case DEDUCE_CALL:
14206                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
14207                               | UNIFY_ALLOW_MORE_CV_QUAL
14208                               | UNIFY_ALLOW_DERIVED);
14209                 break;
14210                 
14211               case DEDUCE_CONV:
14212                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
14213                 break;
14214                 
14215               case DEDUCE_EXACT:
14216                 sub_strict = UNIFY_ALLOW_NONE;
14217                 break;
14218                 
14219               default:
14220                 gcc_unreachable ();
14221               }
14222
14223             if (!TYPE_P (arg))
14224               {
14225                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
14226                 if (type_unknown_p (arg))
14227                   {
14228                     /* [temp.deduct.type] A template-argument can be
14229                        deduced from a pointer to function or pointer
14230                        to member function argument if the set of
14231                        overloaded functions does not contain function
14232                        templates and at most one of a set of
14233                        overloaded functions provides a unique
14234                        match.  */
14235
14236                     if (resolve_overloaded_unification
14237                         (tparms, targs, parm, arg,
14238                          (unification_kind_t) strict,
14239                          sub_strict)
14240                         != 0)
14241                       return 1;
14242                     skip_arg_p = true;
14243                   }
14244
14245                 if (!skip_arg_p)
14246                   {
14247                     arg_expr = arg;
14248                     arg = unlowered_expr_type (arg);
14249                     if (arg == error_mark_node)
14250                       return 1;
14251                   }
14252               }
14253       
14254             arg_strict = sub_strict;
14255
14256             if (!subr)
14257               arg_strict |= 
14258                 maybe_adjust_types_for_deduction ((unification_kind_t) strict,
14259                                                   &parm, &arg, arg_expr);
14260           }
14261
14262         if (!skip_arg_p)
14263           {
14264             /* For deduction from an init-list we need the actual list.  */
14265             if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
14266               arg = arg_expr;
14267             if (unify (tparms, targs, parm, arg, arg_strict))
14268               return 1;
14269           }
14270       }
14271
14272       /* For each parameter pack, collect the deduced value.  */
14273       for (pack = packs; pack; pack = TREE_CHAIN (pack))
14274         {
14275           int idx, level;
14276           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14277
14278           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
14279             TMPL_ARG (targs, level, idx);
14280         }
14281     }
14282
14283   /* Verify that the results of unification with the parameter packs
14284      produce results consistent with what we've seen before, and make
14285      the deduced argument packs available.  */
14286   for (pack = packs; pack; pack = TREE_CHAIN (pack))
14287     {
14288       tree old_pack = TREE_VALUE (pack);
14289       tree new_args = TREE_TYPE (pack);
14290       int i, len = TREE_VEC_LENGTH (new_args);
14291       int idx, level;
14292       bool nondeduced_p = false;
14293
14294       /* By default keep the original deduced argument pack.
14295          If necessary, more specific code is going to update the
14296          resulting deduced argument later down in this function.  */
14297       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14298       TMPL_ARG (targs, level, idx) = old_pack;
14299
14300       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
14301          actually deduce anything.  */
14302       for (i = 0; i < len && !nondeduced_p; ++i)
14303         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
14304           nondeduced_p = true;
14305       if (nondeduced_p)
14306         continue;
14307
14308       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
14309         {
14310           /* Prepend the explicit arguments onto NEW_ARGS.  */
14311           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14312           tree old_args = new_args;
14313           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
14314           int len = explicit_len + TREE_VEC_LENGTH (old_args);
14315
14316           /* Copy the explicit arguments.  */
14317           new_args = make_tree_vec (len);
14318           for (i = 0; i < explicit_len; i++)
14319             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
14320
14321           /* Copy the deduced arguments.  */
14322           for (; i < len; i++)
14323             TREE_VEC_ELT (new_args, i) =
14324               TREE_VEC_ELT (old_args, i - explicit_len);
14325         }
14326
14327       if (!old_pack)
14328         {
14329           tree result;
14330           /* Build the deduced *_ARGUMENT_PACK.  */
14331           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
14332             {
14333               result = make_node (NONTYPE_ARGUMENT_PACK);
14334               TREE_TYPE (result) = 
14335                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
14336               TREE_CONSTANT (result) = 1;
14337             }
14338           else
14339             result = cxx_make_type (TYPE_ARGUMENT_PACK);
14340
14341           SET_ARGUMENT_PACK_ARGS (result, new_args);
14342
14343           /* Note the deduced argument packs for this parameter
14344              pack.  */
14345           TMPL_ARG (targs, level, idx) = result;
14346         }
14347       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
14348                && (ARGUMENT_PACK_ARGS (old_pack) 
14349                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
14350         {
14351           /* We only had the explicitly-provided arguments before, but
14352              now we have a complete set of arguments.  */
14353           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14354
14355           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
14356           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
14357           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
14358         }
14359       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
14360                                     new_args))
14361         /* Inconsistent unification of this parameter pack.  */
14362         return 1;
14363     }
14364
14365   return 0;
14366 }
14367
14368 /* Deduce the value of template parameters.  TPARMS is the (innermost)
14369    set of template parameters to a template.  TARGS is the bindings
14370    for those template parameters, as determined thus far; TARGS may
14371    include template arguments for outer levels of template parameters
14372    as well.  PARM is a parameter to a template function, or a
14373    subcomponent of that parameter; ARG is the corresponding argument.
14374    This function attempts to match PARM with ARG in a manner
14375    consistent with the existing assignments in TARGS.  If more values
14376    are deduced, then TARGS is updated.
14377
14378    Returns 0 if the type deduction succeeds, 1 otherwise.  The
14379    parameter STRICT is a bitwise or of the following flags:
14380
14381      UNIFY_ALLOW_NONE:
14382        Require an exact match between PARM and ARG.
14383      UNIFY_ALLOW_MORE_CV_QUAL:
14384        Allow the deduced ARG to be more cv-qualified (by qualification
14385        conversion) than ARG.
14386      UNIFY_ALLOW_LESS_CV_QUAL:
14387        Allow the deduced ARG to be less cv-qualified than ARG.
14388      UNIFY_ALLOW_DERIVED:
14389        Allow the deduced ARG to be a template base class of ARG,
14390        or a pointer to a template base class of the type pointed to by
14391        ARG.
14392      UNIFY_ALLOW_INTEGER:
14393        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
14394        case for more information.
14395      UNIFY_ALLOW_OUTER_LEVEL:
14396        This is the outermost level of a deduction. Used to determine validity
14397        of qualification conversions. A valid qualification conversion must
14398        have const qualified pointers leading up to the inner type which
14399        requires additional CV quals, except at the outer level, where const
14400        is not required [conv.qual]. It would be normal to set this flag in
14401        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
14402      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
14403        This is the outermost level of a deduction, and PARM can be more CV
14404        qualified at this point.
14405      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
14406        This is the outermost level of a deduction, and PARM can be less CV
14407        qualified at this point.  */
14408
14409 static int
14410 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
14411 {
14412   int idx;
14413   tree targ;
14414   tree tparm;
14415   int strict_in = strict;
14416
14417   /* I don't think this will do the right thing with respect to types.
14418      But the only case I've seen it in so far has been array bounds, where
14419      signedness is the only information lost, and I think that will be
14420      okay.  */
14421   while (TREE_CODE (parm) == NOP_EXPR)
14422     parm = TREE_OPERAND (parm, 0);
14423
14424   if (arg == error_mark_node)
14425     return 1;
14426   if (arg == unknown_type_node
14427       || arg == init_list_type_node)
14428     /* We can't deduce anything from this, but we might get all the
14429        template args from other function args.  */
14430     return 0;
14431
14432   /* If PARM uses template parameters, then we can't bail out here,
14433      even if ARG == PARM, since we won't record unifications for the
14434      template parameters.  We might need them if we're trying to
14435      figure out which of two things is more specialized.  */
14436   if (arg == parm && !uses_template_parms (parm))
14437     return 0;
14438
14439   /* Handle init lists early, so the rest of the function can assume
14440      we're dealing with a type. */
14441   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
14442     {
14443       tree elt, elttype;
14444       unsigned i;
14445       tree orig_parm = parm;
14446
14447       /* Replace T with std::initializer_list<T> for deduction.  */
14448       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14449           && flag_deduce_init_list)
14450         parm = listify (parm);
14451
14452       if (!is_std_init_list (parm))
14453         /* We can only deduce from an initializer list argument if the
14454            parameter is std::initializer_list; otherwise this is a
14455            non-deduced context. */
14456         return 0;
14457
14458       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
14459
14460       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
14461         {
14462           int elt_strict = strict;
14463           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
14464             {
14465               tree type = TREE_TYPE (elt);
14466               /* It should only be possible to get here for a call.  */
14467               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
14468               elt_strict |= maybe_adjust_types_for_deduction
14469                 (DEDUCE_CALL, &elttype, &type, elt);
14470               elt = type;
14471             }
14472
14473           if (unify (tparms, targs, elttype, elt, elt_strict))
14474             return 1;
14475         }
14476
14477       /* If the std::initializer_list<T> deduction worked, replace the
14478          deduced A with std::initializer_list<A>.  */
14479       if (orig_parm != parm)
14480         {
14481           idx = TEMPLATE_TYPE_IDX (orig_parm);
14482           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14483           targ = listify (targ);
14484           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
14485         }
14486       return 0;
14487     }
14488
14489   /* Immediately reject some pairs that won't unify because of
14490      cv-qualification mismatches.  */
14491   if (TREE_CODE (arg) == TREE_CODE (parm)
14492       && TYPE_P (arg)
14493       /* It is the elements of the array which hold the cv quals of an array
14494          type, and the elements might be template type parms. We'll check
14495          when we recurse.  */
14496       && TREE_CODE (arg) != ARRAY_TYPE
14497       /* We check the cv-qualifiers when unifying with template type
14498          parameters below.  We want to allow ARG `const T' to unify with
14499          PARM `T' for example, when computing which of two templates
14500          is more specialized, for example.  */
14501       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
14502       && !check_cv_quals_for_unify (strict_in, arg, parm))
14503     return 1;
14504
14505   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
14506       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
14507     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
14508   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
14509   strict &= ~UNIFY_ALLOW_DERIVED;
14510   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
14511   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
14512
14513   switch (TREE_CODE (parm))
14514     {
14515     case TYPENAME_TYPE:
14516     case SCOPE_REF:
14517     case UNBOUND_CLASS_TEMPLATE:
14518       /* In a type which contains a nested-name-specifier, template
14519          argument values cannot be deduced for template parameters used
14520          within the nested-name-specifier.  */
14521       return 0;
14522
14523     case TEMPLATE_TYPE_PARM:
14524     case TEMPLATE_TEMPLATE_PARM:
14525     case BOUND_TEMPLATE_TEMPLATE_PARM:
14526       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14527       if (tparm == error_mark_node)
14528         return 1;
14529
14530       if (TEMPLATE_TYPE_LEVEL (parm)
14531           != template_decl_level (tparm))
14532         /* The PARM is not one we're trying to unify.  Just check
14533            to see if it matches ARG.  */
14534         return (TREE_CODE (arg) == TREE_CODE (parm)
14535                 && same_type_p (parm, arg)) ? 0 : 1;
14536       idx = TEMPLATE_TYPE_IDX (parm);
14537       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14538       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
14539
14540       /* Check for mixed types and values.  */
14541       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14542            && TREE_CODE (tparm) != TYPE_DECL)
14543           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14544               && TREE_CODE (tparm) != TEMPLATE_DECL))
14545         return 1;
14546
14547       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14548         {
14549           /* ARG must be constructed from a template class or a template
14550              template parameter.  */
14551           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
14552               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
14553             return 1;
14554
14555           {
14556             tree parmvec = TYPE_TI_ARGS (parm);
14557             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
14558             tree parm_parms 
14559               = DECL_INNERMOST_TEMPLATE_PARMS
14560                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
14561             int i, len;
14562             int parm_variadic_p = 0;
14563
14564             /* The resolution to DR150 makes clear that default
14565                arguments for an N-argument may not be used to bind T
14566                to a template template parameter with fewer than N
14567                parameters.  It is not safe to permit the binding of
14568                default arguments as an extension, as that may change
14569                the meaning of a conforming program.  Consider:
14570
14571                   struct Dense { static const unsigned int dim = 1; };
14572
14573                   template <template <typename> class View,
14574                             typename Block>
14575                   void operator+(float, View<Block> const&);
14576
14577                   template <typename Block,
14578                             unsigned int Dim = Block::dim>
14579                   struct Lvalue_proxy { operator float() const; };
14580
14581                   void
14582                   test_1d (void) {
14583                     Lvalue_proxy<Dense> p;
14584                     float b;
14585                     b + p;
14586                   }
14587
14588               Here, if Lvalue_proxy is permitted to bind to View, then
14589               the global operator+ will be used; if they are not, the
14590               Lvalue_proxy will be converted to float.  */
14591             if (coerce_template_parms (parm_parms,
14592                                        argvec,
14593                                        TYPE_TI_TEMPLATE (parm),
14594                                        tf_none,
14595                                        /*require_all_args=*/true,
14596                                        /*use_default_args=*/false)
14597                 == error_mark_node)
14598               return 1;
14599
14600             /* Deduce arguments T, i from TT<T> or TT<i>.
14601                We check each element of PARMVEC and ARGVEC individually
14602                rather than the whole TREE_VEC since they can have
14603                different number of elements.  */
14604
14605             parmvec = expand_template_argument_pack (parmvec);
14606             argvec = expand_template_argument_pack (argvec);
14607
14608             len = TREE_VEC_LENGTH (parmvec);
14609
14610             /* Check if the parameters end in a pack, making them
14611                variadic.  */
14612             if (len > 0
14613                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
14614               parm_variadic_p = 1;
14615             
14616             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
14617               return 1;
14618
14619              for (i = 0; i < len - parm_variadic_p; ++i)
14620               {
14621                 if (unify (tparms, targs,
14622                            TREE_VEC_ELT (parmvec, i),
14623                            TREE_VEC_ELT (argvec, i),
14624                            UNIFY_ALLOW_NONE))
14625                   return 1;
14626               }
14627
14628             if (parm_variadic_p
14629                 && unify_pack_expansion (tparms, targs,
14630                                          parmvec, argvec,
14631                                          UNIFY_ALLOW_NONE,
14632                                          /*call_args_p=*/false,
14633                                          /*subr=*/false))
14634               return 1;
14635           }
14636           arg = TYPE_TI_TEMPLATE (arg);
14637
14638           /* Fall through to deduce template name.  */
14639         }
14640
14641       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14642           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14643         {
14644           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
14645
14646           /* Simple cases: Value already set, does match or doesn't.  */
14647           if (targ != NULL_TREE && template_args_equal (targ, arg))
14648             return 0;
14649           else if (targ)
14650             return 1;
14651         }
14652       else
14653         {
14654           /* If PARM is `const T' and ARG is only `int', we don't have
14655              a match unless we are allowing additional qualification.
14656              If ARG is `const int' and PARM is just `T' that's OK;
14657              that binds `const int' to `T'.  */
14658           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
14659                                          arg, parm))
14660             return 1;
14661
14662           /* Consider the case where ARG is `const volatile int' and
14663              PARM is `const T'.  Then, T should be `volatile int'.  */
14664           arg = cp_build_qualified_type_real
14665             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
14666           if (arg == error_mark_node)
14667             return 1;
14668
14669           /* Simple cases: Value already set, does match or doesn't.  */
14670           if (targ != NULL_TREE && same_type_p (targ, arg))
14671             return 0;
14672           else if (targ)
14673             return 1;
14674
14675           /* Make sure that ARG is not a variable-sized array.  (Note
14676              that were talking about variable-sized arrays (like
14677              `int[n]'), rather than arrays of unknown size (like
14678              `int[]').)  We'll get very confused by such a type since
14679              the bound of the array will not be computable in an
14680              instantiation.  Besides, such types are not allowed in
14681              ISO C++, so we can do as we please here.  */
14682           if (variably_modified_type_p (arg, NULL_TREE))
14683             return 1;
14684
14685           /* Strip typedefs as in convert_template_argument.  */
14686           arg = strip_typedefs (arg);
14687         }
14688
14689       /* If ARG is a parameter pack or an expansion, we cannot unify
14690          against it unless PARM is also a parameter pack.  */
14691       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
14692           && !template_parameter_pack_p (parm))
14693         return 1;
14694
14695       /* If the argument deduction results is a METHOD_TYPE,
14696          then there is a problem.
14697          METHOD_TYPE doesn't map to any real C++ type the result of
14698          the deduction can not be of that type.  */
14699       if (TREE_CODE (arg) == METHOD_TYPE)
14700         return 1;
14701
14702       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
14703       return 0;
14704
14705     case TEMPLATE_PARM_INDEX:
14706       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14707       if (tparm == error_mark_node)
14708         return 1;
14709
14710       if (TEMPLATE_PARM_LEVEL (parm)
14711           != template_decl_level (tparm))
14712         /* The PARM is not one we're trying to unify.  Just check
14713            to see if it matches ARG.  */
14714         return !(TREE_CODE (arg) == TREE_CODE (parm)
14715                  && cp_tree_equal (parm, arg));
14716
14717       idx = TEMPLATE_PARM_IDX (parm);
14718       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14719
14720       if (targ)
14721         return !cp_tree_equal (targ, arg);
14722
14723       /* [temp.deduct.type] If, in the declaration of a function template
14724          with a non-type template-parameter, the non-type
14725          template-parameter is used in an expression in the function
14726          parameter-list and, if the corresponding template-argument is
14727          deduced, the template-argument type shall match the type of the
14728          template-parameter exactly, except that a template-argument
14729          deduced from an array bound may be of any integral type.
14730          The non-type parameter might use already deduced type parameters.  */
14731       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
14732       if (!TREE_TYPE (arg))
14733         /* Template-parameter dependent expression.  Just accept it for now.
14734            It will later be processed in convert_template_argument.  */
14735         ;
14736       else if (same_type_p (TREE_TYPE (arg), tparm))
14737         /* OK */;
14738       else if ((strict & UNIFY_ALLOW_INTEGER)
14739                && (TREE_CODE (tparm) == INTEGER_TYPE
14740                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
14741         /* Convert the ARG to the type of PARM; the deduced non-type
14742            template argument must exactly match the types of the
14743            corresponding parameter.  */
14744         arg = fold (build_nop (tparm, arg));
14745       else if (uses_template_parms (tparm))
14746         /* We haven't deduced the type of this parameter yet.  Try again
14747            later.  */
14748         return 0;
14749       else
14750         return 1;
14751
14752       /* If ARG is a parameter pack or an expansion, we cannot unify
14753          against it unless PARM is also a parameter pack.  */
14754       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
14755           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
14756         return 1;
14757
14758       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
14759       return 0;
14760
14761     case PTRMEM_CST:
14762      {
14763         /* A pointer-to-member constant can be unified only with
14764          another constant.  */
14765       if (TREE_CODE (arg) != PTRMEM_CST)
14766         return 1;
14767
14768       /* Just unify the class member. It would be useless (and possibly
14769          wrong, depending on the strict flags) to unify also
14770          PTRMEM_CST_CLASS, because we want to be sure that both parm and
14771          arg refer to the same variable, even if through different
14772          classes. For instance:
14773
14774          struct A { int x; };
14775          struct B : A { };
14776
14777          Unification of &A::x and &B::x must succeed.  */
14778       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
14779                     PTRMEM_CST_MEMBER (arg), strict);
14780      }
14781
14782     case POINTER_TYPE:
14783       {
14784         if (TREE_CODE (arg) != POINTER_TYPE)
14785           return 1;
14786
14787         /* [temp.deduct.call]
14788
14789            A can be another pointer or pointer to member type that can
14790            be converted to the deduced A via a qualification
14791            conversion (_conv.qual_).
14792
14793            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
14794            This will allow for additional cv-qualification of the
14795            pointed-to types if appropriate.  */
14796
14797         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
14798           /* The derived-to-base conversion only persists through one
14799              level of pointers.  */
14800           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
14801
14802         return unify (tparms, targs, TREE_TYPE (parm),
14803                       TREE_TYPE (arg), strict);
14804       }
14805
14806     case REFERENCE_TYPE:
14807       if (TREE_CODE (arg) != REFERENCE_TYPE)
14808         return 1;
14809       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14810                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
14811
14812     case ARRAY_TYPE:
14813       if (TREE_CODE (arg) != ARRAY_TYPE)
14814         return 1;
14815       if ((TYPE_DOMAIN (parm) == NULL_TREE)
14816           != (TYPE_DOMAIN (arg) == NULL_TREE))
14817         return 1;
14818       if (TYPE_DOMAIN (parm) != NULL_TREE)
14819         {
14820           tree parm_max;
14821           tree arg_max;
14822           bool parm_cst;
14823           bool arg_cst;
14824
14825           /* Our representation of array types uses "N - 1" as the
14826              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
14827              not an integer constant.  We cannot unify arbitrarily
14828              complex expressions, so we eliminate the MINUS_EXPRs
14829              here.  */
14830           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
14831           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
14832           if (!parm_cst)
14833             {
14834               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
14835               parm_max = TREE_OPERAND (parm_max, 0);
14836             }
14837           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
14838           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
14839           if (!arg_cst)
14840             {
14841               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
14842                  trying to unify the type of a variable with the type
14843                  of a template parameter.  For example:
14844
14845                    template <unsigned int N>
14846                    void f (char (&) [N]);
14847                    int g(); 
14848                    void h(int i) {
14849                      char a[g(i)];
14850                      f(a); 
14851                    }
14852
14853                 Here, the type of the ARG will be "int [g(i)]", and
14854                 may be a SAVE_EXPR, etc.  */
14855               if (TREE_CODE (arg_max) != MINUS_EXPR)
14856                 return 1;
14857               arg_max = TREE_OPERAND (arg_max, 0);
14858             }
14859
14860           /* If only one of the bounds used a MINUS_EXPR, compensate
14861              by adding one to the other bound.  */
14862           if (parm_cst && !arg_cst)
14863             parm_max = fold_build2_loc (input_location, PLUS_EXPR,
14864                                     integer_type_node,
14865                                     parm_max,
14866                                     integer_one_node);
14867           else if (arg_cst && !parm_cst)
14868             arg_max = fold_build2_loc (input_location, PLUS_EXPR,
14869                                    integer_type_node,
14870                                    arg_max,
14871                                    integer_one_node);
14872
14873           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
14874             return 1;
14875         }
14876       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14877                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
14878
14879     case REAL_TYPE:
14880     case COMPLEX_TYPE:
14881     case VECTOR_TYPE:
14882     case INTEGER_TYPE:
14883     case BOOLEAN_TYPE:
14884     case ENUMERAL_TYPE:
14885     case VOID_TYPE:
14886       if (TREE_CODE (arg) != TREE_CODE (parm))
14887         return 1;
14888
14889       /* We have already checked cv-qualification at the top of the
14890          function.  */
14891       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
14892         return 1;
14893
14894       /* As far as unification is concerned, this wins.  Later checks
14895          will invalidate it if necessary.  */
14896       return 0;
14897
14898       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
14899       /* Type INTEGER_CST can come from ordinary constant template args.  */
14900     case INTEGER_CST:
14901       while (TREE_CODE (arg) == NOP_EXPR)
14902         arg = TREE_OPERAND (arg, 0);
14903
14904       if (TREE_CODE (arg) != INTEGER_CST)
14905         return 1;
14906       return !tree_int_cst_equal (parm, arg);
14907
14908     case TREE_VEC:
14909       {
14910         int i;
14911         if (TREE_CODE (arg) != TREE_VEC)
14912           return 1;
14913         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
14914           return 1;
14915         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
14916           if (unify (tparms, targs,
14917                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
14918                      UNIFY_ALLOW_NONE))
14919             return 1;
14920         return 0;
14921       }
14922
14923     case RECORD_TYPE:
14924     case UNION_TYPE:
14925       if (TREE_CODE (arg) != TREE_CODE (parm))
14926         return 1;
14927
14928       if (TYPE_PTRMEMFUNC_P (parm))
14929         {
14930           if (!TYPE_PTRMEMFUNC_P (arg))
14931             return 1;
14932
14933           return unify (tparms, targs,
14934                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
14935                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
14936                         strict);
14937         }
14938
14939       if (CLASSTYPE_TEMPLATE_INFO (parm))
14940         {
14941           tree t = NULL_TREE;
14942
14943           if (strict_in & UNIFY_ALLOW_DERIVED)
14944             {
14945               /* First, we try to unify the PARM and ARG directly.  */
14946               t = try_class_unification (tparms, targs,
14947                                          parm, arg);
14948
14949               if (!t)
14950                 {
14951                   /* Fallback to the special case allowed in
14952                      [temp.deduct.call]:
14953
14954                        If P is a class, and P has the form
14955                        template-id, then A can be a derived class of
14956                        the deduced A.  Likewise, if P is a pointer to
14957                        a class of the form template-id, A can be a
14958                        pointer to a derived class pointed to by the
14959                        deduced A.  */
14960                   t = get_template_base (tparms, targs, parm, arg);
14961
14962                   if (!t)
14963                     return 1;
14964                 }
14965             }
14966           else if (CLASSTYPE_TEMPLATE_INFO (arg)
14967                    && (CLASSTYPE_TI_TEMPLATE (parm)
14968                        == CLASSTYPE_TI_TEMPLATE (arg)))
14969             /* Perhaps PARM is something like S<U> and ARG is S<int>.
14970                Then, we should unify `int' and `U'.  */
14971             t = arg;
14972           else
14973             /* There's no chance of unification succeeding.  */
14974             return 1;
14975
14976           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
14977                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
14978         }
14979       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
14980         return 1;
14981       return 0;
14982
14983     case METHOD_TYPE:
14984     case FUNCTION_TYPE:
14985       {
14986         unsigned int nargs;
14987         tree *args;
14988         tree a;
14989         unsigned int i;
14990
14991         if (TREE_CODE (arg) != TREE_CODE (parm))
14992           return 1;
14993
14994         /* CV qualifications for methods can never be deduced, they must
14995            match exactly.  We need to check them explicitly here,
14996            because type_unification_real treats them as any other
14997            cv-qualified parameter.  */
14998         if (TREE_CODE (parm) == METHOD_TYPE
14999             && (!check_cv_quals_for_unify
15000                 (UNIFY_ALLOW_NONE,
15001                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
15002                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
15003           return 1;
15004
15005         if (unify (tparms, targs, TREE_TYPE (parm),
15006                    TREE_TYPE (arg), UNIFY_ALLOW_NONE))
15007           return 1;
15008
15009         nargs = list_length (TYPE_ARG_TYPES (arg));
15010         args = XALLOCAVEC (tree, nargs);
15011         for (a = TYPE_ARG_TYPES (arg), i = 0;
15012              a != NULL_TREE && a != void_list_node;
15013              a = TREE_CHAIN (a), ++i)
15014           args[i] = TREE_VALUE (a);
15015         nargs = i;
15016
15017         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
15018                                       args, nargs, 1, DEDUCE_EXACT,
15019                                       LOOKUP_NORMAL);
15020       }
15021
15022     case OFFSET_TYPE:
15023       /* Unify a pointer to member with a pointer to member function, which
15024          deduces the type of the member as a function type. */
15025       if (TYPE_PTRMEMFUNC_P (arg))
15026         {
15027           tree method_type;
15028           tree fntype;
15029           cp_cv_quals cv_quals;
15030
15031           /* Check top-level cv qualifiers */
15032           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
15033             return 1;
15034
15035           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
15036                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
15037             return 1;
15038
15039           /* Determine the type of the function we are unifying against. */
15040           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
15041           fntype =
15042             build_function_type (TREE_TYPE (method_type),
15043                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
15044
15045           /* Extract the cv-qualifiers of the member function from the
15046              implicit object parameter and place them on the function
15047              type to be restored later. */
15048           cv_quals =
15049             cp_type_quals(TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (method_type))));
15050           fntype = build_qualified_type (fntype, cv_quals);
15051           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
15052         }
15053
15054       if (TREE_CODE (arg) != OFFSET_TYPE)
15055         return 1;
15056       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
15057                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
15058         return 1;
15059       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
15060                     strict);
15061
15062     case CONST_DECL:
15063       if (DECL_TEMPLATE_PARM_P (parm))
15064         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
15065       if (arg != integral_constant_value (parm))
15066         return 1;
15067       return 0;
15068
15069     case FIELD_DECL:
15070     case TEMPLATE_DECL:
15071       /* Matched cases are handled by the ARG == PARM test above.  */
15072       return 1;
15073
15074     case VAR_DECL:
15075       /* A non-type template parameter that is a variable should be a
15076          an integral constant, in which case, it whould have been
15077          folded into its (constant) value. So we should not be getting
15078          a variable here.  */
15079       gcc_unreachable ();
15080
15081     case TYPE_ARGUMENT_PACK:
15082     case NONTYPE_ARGUMENT_PACK:
15083       {
15084         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
15085         tree packed_args = ARGUMENT_PACK_ARGS (arg);
15086         int i, len = TREE_VEC_LENGTH (packed_parms);
15087         int argslen = TREE_VEC_LENGTH (packed_args);
15088         int parm_variadic_p = 0;
15089
15090         for (i = 0; i < len; ++i)
15091           {
15092             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
15093               {
15094                 if (i == len - 1)
15095                   /* We can unify against something with a trailing
15096                      parameter pack.  */
15097                   parm_variadic_p = 1;
15098                 else
15099                   /* Since there is something following the pack
15100                      expansion, we cannot unify this template argument
15101                      list.  */
15102                   return 0;
15103               }
15104           }
15105           
15106
15107         /* If we don't have enough arguments to satisfy the parameters
15108            (not counting the pack expression at the end), or we have
15109            too many arguments for a parameter list that doesn't end in
15110            a pack expression, we can't unify.  */
15111         if (argslen < (len - parm_variadic_p)
15112             || (argslen > len && !parm_variadic_p))
15113           return 1;
15114
15115         /* Unify all of the parameters that precede the (optional)
15116            pack expression.  */
15117         for (i = 0; i < len - parm_variadic_p; ++i)
15118           {
15119             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
15120                        TREE_VEC_ELT (packed_args, i), strict))
15121               return 1;
15122           }
15123
15124         if (parm_variadic_p)
15125           return unify_pack_expansion (tparms, targs, 
15126                                        packed_parms, packed_args,
15127                                        strict, /*call_args_p=*/false,
15128                                        /*subr=*/false);
15129         return 0;
15130       }
15131
15132       break;
15133
15134     case TYPEOF_TYPE:
15135     case DECLTYPE_TYPE:
15136       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
15137          nodes.  */
15138       return 0;
15139
15140     case ERROR_MARK:
15141       /* Unification fails if we hit an error node.  */
15142       return 1;
15143
15144     default:
15145       gcc_assert (EXPR_P (parm));
15146
15147       /* We must be looking at an expression.  This can happen with
15148          something like:
15149
15150            template <int I>
15151            void foo(S<I>, S<I + 2>);
15152
15153          This is a "nondeduced context":
15154
15155            [deduct.type]
15156
15157            The nondeduced contexts are:
15158
15159            --A type that is a template-id in which one or more of
15160              the template-arguments is an expression that references
15161              a template-parameter.
15162
15163          In these cases, we assume deduction succeeded, but don't
15164          actually infer any unifications.  */
15165
15166       if (!uses_template_parms (parm)
15167           && !template_args_equal (parm, arg))
15168         return 1;
15169       else
15170         return 0;
15171     }
15172 }
15173 \f
15174 /* Note that DECL can be defined in this translation unit, if
15175    required.  */
15176
15177 static void
15178 mark_definable (tree decl)
15179 {
15180   tree clone;
15181   DECL_NOT_REALLY_EXTERN (decl) = 1;
15182   FOR_EACH_CLONE (clone, decl)
15183     DECL_NOT_REALLY_EXTERN (clone) = 1;
15184 }
15185
15186 /* Called if RESULT is explicitly instantiated, or is a member of an
15187    explicitly instantiated class.  */
15188
15189 void
15190 mark_decl_instantiated (tree result, int extern_p)
15191 {
15192   SET_DECL_EXPLICIT_INSTANTIATION (result);
15193
15194   /* If this entity has already been written out, it's too late to
15195      make any modifications.  */
15196   if (TREE_ASM_WRITTEN (result))
15197     return;
15198
15199   if (TREE_CODE (result) != FUNCTION_DECL)
15200     /* The TREE_PUBLIC flag for function declarations will have been
15201        set correctly by tsubst.  */
15202     TREE_PUBLIC (result) = 1;
15203
15204   /* This might have been set by an earlier implicit instantiation.  */
15205   DECL_COMDAT (result) = 0;
15206
15207   if (extern_p)
15208     DECL_NOT_REALLY_EXTERN (result) = 0;
15209   else
15210     {
15211       mark_definable (result);
15212       /* Always make artificials weak.  */
15213       if (DECL_ARTIFICIAL (result) && flag_weak)
15214         comdat_linkage (result);
15215       /* For WIN32 we also want to put explicit instantiations in
15216          linkonce sections.  */
15217       else if (TREE_PUBLIC (result))
15218         maybe_make_one_only (result);
15219     }
15220
15221   /* If EXTERN_P, then this function will not be emitted -- unless
15222      followed by an explicit instantiation, at which point its linkage
15223      will be adjusted.  If !EXTERN_P, then this function will be
15224      emitted here.  In neither circumstance do we want
15225      import_export_decl to adjust the linkage.  */
15226   DECL_INTERFACE_KNOWN (result) = 1;
15227 }
15228
15229 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
15230    important template arguments.  If any are missing, we check whether
15231    they're important by using error_mark_node for substituting into any
15232    args that were used for partial ordering (the ones between ARGS and END)
15233    and seeing if it bubbles up.  */
15234
15235 static bool
15236 check_undeduced_parms (tree targs, tree args, tree end)
15237 {
15238   bool found = false;
15239   int i;
15240   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
15241     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
15242       {
15243         found = true;
15244         TREE_VEC_ELT (targs, i) = error_mark_node;
15245       }
15246   if (found)
15247     {
15248       for (; args != end; args = TREE_CHAIN (args))
15249         {
15250           tree substed = tsubst (TREE_VALUE (args), targs, tf_none, NULL_TREE);
15251           if (substed == error_mark_node)
15252             return true;
15253         }
15254     }
15255   return false;
15256 }
15257
15258 /* Given two function templates PAT1 and PAT2, return:
15259
15260    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
15261    -1 if PAT2 is more specialized than PAT1.
15262    0 if neither is more specialized.
15263
15264    LEN indicates the number of parameters we should consider
15265    (defaulted parameters should not be considered).
15266
15267    The 1998 std underspecified function template partial ordering, and
15268    DR214 addresses the issue.  We take pairs of arguments, one from
15269    each of the templates, and deduce them against each other.  One of
15270    the templates will be more specialized if all the *other*
15271    template's arguments deduce against its arguments and at least one
15272    of its arguments *does* *not* deduce against the other template's
15273    corresponding argument.  Deduction is done as for class templates.
15274    The arguments used in deduction have reference and top level cv
15275    qualifiers removed.  Iff both arguments were originally reference
15276    types *and* deduction succeeds in both directions, the template
15277    with the more cv-qualified argument wins for that pairing (if
15278    neither is more cv-qualified, they both are equal).  Unlike regular
15279    deduction, after all the arguments have been deduced in this way,
15280    we do *not* verify the deduced template argument values can be
15281    substituted into non-deduced contexts.
15282
15283    The logic can be a bit confusing here, because we look at deduce1 and
15284    targs1 to see if pat2 is at least as specialized, and vice versa; if we
15285    can find template arguments for pat1 to make arg1 look like arg2, that
15286    means that arg2 is at least as specialized as arg1.  */
15287
15288 int
15289 more_specialized_fn (tree pat1, tree pat2, int len)
15290 {
15291   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
15292   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
15293   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
15294   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
15295   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
15296   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
15297   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
15298   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
15299   tree origs1, origs2;
15300   bool lose1 = false;
15301   bool lose2 = false;
15302
15303   /* Remove the this parameter from non-static member functions.  If
15304      one is a non-static member function and the other is not a static
15305      member function, remove the first parameter from that function
15306      also.  This situation occurs for operator functions where we
15307      locate both a member function (with this pointer) and non-member
15308      operator (with explicit first operand).  */
15309   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
15310     {
15311       len--; /* LEN is the number of significant arguments for DECL1 */
15312       args1 = TREE_CHAIN (args1);
15313       if (!DECL_STATIC_FUNCTION_P (decl2))
15314         args2 = TREE_CHAIN (args2);
15315     }
15316   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
15317     {
15318       args2 = TREE_CHAIN (args2);
15319       if (!DECL_STATIC_FUNCTION_P (decl1))
15320         {
15321           len--;
15322           args1 = TREE_CHAIN (args1);
15323         }
15324     }
15325
15326   /* If only one is a conversion operator, they are unordered.  */
15327   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
15328     return 0;
15329
15330   /* Consider the return type for a conversion function */
15331   if (DECL_CONV_FN_P (decl1))
15332     {
15333       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
15334       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
15335       len++;
15336     }
15337
15338   processing_template_decl++;
15339
15340   origs1 = args1;
15341   origs2 = args2;
15342
15343   while (len--
15344          /* Stop when an ellipsis is seen.  */
15345          && args1 != NULL_TREE && args2 != NULL_TREE)
15346     {
15347       tree arg1 = TREE_VALUE (args1);
15348       tree arg2 = TREE_VALUE (args2);
15349       int deduce1, deduce2;
15350       int quals1 = -1;
15351       int quals2 = -1;
15352
15353       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15354           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15355         {
15356           /* When both arguments are pack expansions, we need only
15357              unify the patterns themselves.  */
15358           arg1 = PACK_EXPANSION_PATTERN (arg1);
15359           arg2 = PACK_EXPANSION_PATTERN (arg2);
15360
15361           /* This is the last comparison we need to do.  */
15362           len = 0;
15363         }
15364
15365       if (TREE_CODE (arg1) == REFERENCE_TYPE)
15366         {
15367           arg1 = TREE_TYPE (arg1);
15368           quals1 = cp_type_quals (arg1);
15369         }
15370
15371       if (TREE_CODE (arg2) == REFERENCE_TYPE)
15372         {
15373           arg2 = TREE_TYPE (arg2);
15374           quals2 = cp_type_quals (arg2);
15375         }
15376
15377       if ((quals1 < 0) != (quals2 < 0))
15378         {
15379           /* Only of the args is a reference, see if we should apply
15380              array/function pointer decay to it.  This is not part of
15381              DR214, but is, IMHO, consistent with the deduction rules
15382              for the function call itself, and with our earlier
15383              implementation of the underspecified partial ordering
15384              rules.  (nathan).  */
15385           if (quals1 >= 0)
15386             {
15387               switch (TREE_CODE (arg1))
15388                 {
15389                 case ARRAY_TYPE:
15390                   arg1 = TREE_TYPE (arg1);
15391                   /* FALLTHROUGH. */
15392                 case FUNCTION_TYPE:
15393                   arg1 = build_pointer_type (arg1);
15394                   break;
15395
15396                 default:
15397                   break;
15398                 }
15399             }
15400           else
15401             {
15402               switch (TREE_CODE (arg2))
15403                 {
15404                 case ARRAY_TYPE:
15405                   arg2 = TREE_TYPE (arg2);
15406                   /* FALLTHROUGH. */
15407                 case FUNCTION_TYPE:
15408                   arg2 = build_pointer_type (arg2);
15409                   break;
15410
15411                 default:
15412                   break;
15413                 }
15414             }
15415         }
15416
15417       arg1 = TYPE_MAIN_VARIANT (arg1);
15418       arg2 = TYPE_MAIN_VARIANT (arg2);
15419
15420       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
15421         {
15422           int i, len2 = list_length (args2);
15423           tree parmvec = make_tree_vec (1);
15424           tree argvec = make_tree_vec (len2);
15425           tree ta = args2;
15426
15427           /* Setup the parameter vector, which contains only ARG1.  */
15428           TREE_VEC_ELT (parmvec, 0) = arg1;
15429
15430           /* Setup the argument vector, which contains the remaining
15431              arguments.  */
15432           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
15433             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15434
15435           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
15436                                            argvec, UNIFY_ALLOW_NONE, 
15437                                            /*call_args_p=*/false, 
15438                                            /*subr=*/0);
15439
15440           /* We cannot deduce in the other direction, because ARG1 is
15441              a pack expansion but ARG2 is not.  */
15442           deduce2 = 0;
15443         }
15444       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15445         {
15446           int i, len1 = list_length (args1);
15447           tree parmvec = make_tree_vec (1);
15448           tree argvec = make_tree_vec (len1);
15449           tree ta = args1;
15450
15451           /* Setup the parameter vector, which contains only ARG1.  */
15452           TREE_VEC_ELT (parmvec, 0) = arg2;
15453
15454           /* Setup the argument vector, which contains the remaining
15455              arguments.  */
15456           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
15457             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15458
15459           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
15460                                            argvec, UNIFY_ALLOW_NONE, 
15461                                            /*call_args_p=*/false, 
15462                                            /*subr=*/0);
15463
15464           /* We cannot deduce in the other direction, because ARG2 is
15465              a pack expansion but ARG1 is not.*/
15466           deduce1 = 0;
15467         }
15468
15469       else
15470         {
15471           /* The normal case, where neither argument is a pack
15472              expansion.  */
15473           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
15474           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
15475         }
15476
15477       /* If we couldn't deduce arguments for tparms1 to make arg1 match
15478          arg2, then arg2 is not as specialized as arg1.  */
15479       if (!deduce1)
15480         lose2 = true;
15481       if (!deduce2)
15482         lose1 = true;
15483
15484       /* "If, for a given type, deduction succeeds in both directions
15485          (i.e., the types are identical after the transformations above)
15486          and if the type from the argument template is more cv-qualified
15487          than the type from the parameter template (as described above)
15488          that type is considered to be more specialized than the other. If
15489          neither type is more cv-qualified than the other then neither type
15490          is more specialized than the other."  */
15491
15492       if (deduce1 && deduce2
15493           && quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
15494         {
15495           if ((quals1 & quals2) == quals2)
15496             lose2 = true;
15497           if ((quals1 & quals2) == quals1)
15498             lose1 = true;
15499         }
15500
15501       if (lose1 && lose2)
15502         /* We've failed to deduce something in either direction.
15503            These must be unordered.  */
15504         break;
15505
15506       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15507           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15508         /* We have already processed all of the arguments in our
15509            handing of the pack expansion type.  */
15510         len = 0;
15511
15512       args1 = TREE_CHAIN (args1);
15513       args2 = TREE_CHAIN (args2);
15514     }
15515
15516   /* "In most cases, all template parameters must have values in order for
15517      deduction to succeed, but for partial ordering purposes a template
15518      parameter may remain without a value provided it is not used in the
15519      types being used for partial ordering."
15520
15521      Thus, if we are missing any of the targs1 we need to substitute into
15522      origs1, then pat2 is not as specialized as pat1.  This can happen when
15523      there is a nondeduced context.  */
15524   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
15525     lose2 = true;
15526   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
15527     lose1 = true;
15528
15529   processing_template_decl--;
15530
15531   /* All things being equal, if the next argument is a pack expansion
15532      for one function but not for the other, prefer the
15533      non-variadic function.  FIXME this is bogus; see c++/41958.  */
15534   if (lose1 == lose2
15535       && args1 && TREE_VALUE (args1)
15536       && args2 && TREE_VALUE (args2))
15537     {
15538       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
15539       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
15540     }
15541
15542   if (lose1 == lose2)
15543     return 0;
15544   else if (!lose1)
15545     return 1;
15546   else
15547     return -1;
15548 }
15549
15550 /* Determine which of two partial specializations is more specialized.
15551
15552    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
15553    to the first partial specialization.  The TREE_VALUE is the
15554    innermost set of template parameters for the partial
15555    specialization.  PAT2 is similar, but for the second template.
15556
15557    Return 1 if the first partial specialization is more specialized;
15558    -1 if the second is more specialized; 0 if neither is more
15559    specialized.
15560
15561    See [temp.class.order] for information about determining which of
15562    two templates is more specialized.  */
15563
15564 static int
15565 more_specialized_class (tree pat1, tree pat2)
15566 {
15567   tree targs;
15568   tree tmpl1, tmpl2;
15569   int winner = 0;
15570   bool any_deductions = false;
15571
15572   tmpl1 = TREE_TYPE (pat1);
15573   tmpl2 = TREE_TYPE (pat2);
15574
15575   /* Just like what happens for functions, if we are ordering between
15576      different class template specializations, we may encounter dependent
15577      types in the arguments, and we need our dependency check functions
15578      to behave correctly.  */
15579   ++processing_template_decl;
15580   targs = get_class_bindings (TREE_VALUE (pat1),
15581                               CLASSTYPE_TI_ARGS (tmpl1),
15582                               CLASSTYPE_TI_ARGS (tmpl2));
15583   if (targs)
15584     {
15585       --winner;
15586       any_deductions = true;
15587     }
15588
15589   targs = get_class_bindings (TREE_VALUE (pat2),
15590                               CLASSTYPE_TI_ARGS (tmpl2),
15591                               CLASSTYPE_TI_ARGS (tmpl1));
15592   if (targs)
15593     {
15594       ++winner;
15595       any_deductions = true;
15596     }
15597   --processing_template_decl;
15598
15599   /* In the case of a tie where at least one of the class templates
15600      has a parameter pack at the end, the template with the most
15601      non-packed parameters wins.  */
15602   if (winner == 0
15603       && any_deductions
15604       && (template_args_variadic_p (TREE_PURPOSE (pat1))
15605           || template_args_variadic_p (TREE_PURPOSE (pat2))))
15606     {
15607       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
15608       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
15609       int len1 = TREE_VEC_LENGTH (args1);
15610       int len2 = TREE_VEC_LENGTH (args2);
15611
15612       /* We don't count the pack expansion at the end.  */
15613       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
15614         --len1;
15615       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
15616         --len2;
15617
15618       if (len1 > len2)
15619         return 1;
15620       else if (len1 < len2)
15621         return -1;
15622     }
15623
15624   return winner;
15625 }
15626
15627 /* Return the template arguments that will produce the function signature
15628    DECL from the function template FN, with the explicit template
15629    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
15630    also match.  Return NULL_TREE if no satisfactory arguments could be
15631    found.  */
15632
15633 static tree
15634 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
15635 {
15636   int ntparms = DECL_NTPARMS (fn);
15637   tree targs = make_tree_vec (ntparms);
15638   tree decl_type;
15639   tree decl_arg_types;
15640   tree *args;
15641   unsigned int nargs, ix;
15642   tree arg;
15643
15644   /* Substitute the explicit template arguments into the type of DECL.
15645      The call to fn_type_unification will handle substitution into the
15646      FN.  */
15647   decl_type = TREE_TYPE (decl);
15648   if (explicit_args && uses_template_parms (decl_type))
15649     {
15650       tree tmpl;
15651       tree converted_args;
15652
15653       if (DECL_TEMPLATE_INFO (decl))
15654         tmpl = DECL_TI_TEMPLATE (decl);
15655       else
15656         /* We can get here for some invalid specializations.  */
15657         return NULL_TREE;
15658
15659       converted_args
15660         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
15661                                  explicit_args, NULL_TREE,
15662                                  tf_none,
15663                                  /*require_all_args=*/false,
15664                                  /*use_default_args=*/false);
15665       if (converted_args == error_mark_node)
15666         return NULL_TREE;
15667
15668       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
15669       if (decl_type == error_mark_node)
15670         return NULL_TREE;
15671     }
15672
15673   /* Never do unification on the 'this' parameter.  */
15674   decl_arg_types = skip_artificial_parms_for (decl, 
15675                                               TYPE_ARG_TYPES (decl_type));
15676
15677   nargs = list_length (decl_arg_types);
15678   args = XALLOCAVEC (tree, nargs);
15679   for (arg = decl_arg_types, ix = 0;
15680        arg != NULL_TREE && arg != void_list_node;
15681        arg = TREE_CHAIN (arg), ++ix)
15682     args[ix] = TREE_VALUE (arg);
15683
15684   if (fn_type_unification (fn, explicit_args, targs,
15685                            args, ix,
15686                            (check_rettype || DECL_CONV_FN_P (fn)
15687                             ? TREE_TYPE (decl_type) : NULL_TREE),
15688                            DEDUCE_EXACT, LOOKUP_NORMAL))
15689     return NULL_TREE;
15690
15691   return targs;
15692 }
15693
15694 /* Return the innermost template arguments that, when applied to a
15695    template specialization whose innermost template parameters are
15696    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
15697    ARGS.
15698
15699    For example, suppose we have:
15700
15701      template <class T, class U> struct S {};
15702      template <class T> struct S<T*, int> {};
15703
15704    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
15705    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
15706    int}.  The resulting vector will be {double}, indicating that `T'
15707    is bound to `double'.  */
15708
15709 static tree
15710 get_class_bindings (tree tparms, tree spec_args, tree args)
15711 {
15712   int i, ntparms = TREE_VEC_LENGTH (tparms);
15713   tree deduced_args;
15714   tree innermost_deduced_args;
15715
15716   innermost_deduced_args = make_tree_vec (ntparms);
15717   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
15718     {
15719       deduced_args = copy_node (args);
15720       SET_TMPL_ARGS_LEVEL (deduced_args,
15721                            TMPL_ARGS_DEPTH (deduced_args),
15722                            innermost_deduced_args);
15723     }
15724   else
15725     deduced_args = innermost_deduced_args;
15726
15727   if (unify (tparms, deduced_args,
15728              INNERMOST_TEMPLATE_ARGS (spec_args),
15729              INNERMOST_TEMPLATE_ARGS (args),
15730              UNIFY_ALLOW_NONE))
15731     return NULL_TREE;
15732
15733   for (i =  0; i < ntparms; ++i)
15734     if (! TREE_VEC_ELT (innermost_deduced_args, i))
15735       return NULL_TREE;
15736
15737   /* Verify that nondeduced template arguments agree with the type
15738      obtained from argument deduction.
15739
15740      For example:
15741
15742        struct A { typedef int X; };
15743        template <class T, class U> struct C {};
15744        template <class T> struct C<T, typename T::X> {};
15745
15746      Then with the instantiation `C<A, int>', we can deduce that
15747      `T' is `A' but unify () does not check whether `typename T::X'
15748      is `int'.  */
15749   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
15750   if (spec_args == error_mark_node
15751       /* We only need to check the innermost arguments; the other
15752          arguments will always agree.  */
15753       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
15754                               INNERMOST_TEMPLATE_ARGS (args)))
15755     return NULL_TREE;
15756
15757   /* Now that we have bindings for all of the template arguments,
15758      ensure that the arguments deduced for the template template
15759      parameters have compatible template parameter lists.  See the use
15760      of template_template_parm_bindings_ok_p in fn_type_unification
15761      for more information.  */
15762   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
15763     return NULL_TREE;
15764
15765   return deduced_args;
15766 }
15767
15768 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
15769    Return the TREE_LIST node with the most specialized template, if
15770    any.  If there is no most specialized template, the error_mark_node
15771    is returned.
15772
15773    Note that this function does not look at, or modify, the
15774    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
15775    returned is one of the elements of INSTANTIATIONS, callers may
15776    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
15777    and retrieve it from the value returned.  */
15778
15779 tree
15780 most_specialized_instantiation (tree templates)
15781 {
15782   tree fn, champ;
15783
15784   ++processing_template_decl;
15785
15786   champ = templates;
15787   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
15788     {
15789       int fate = 0;
15790
15791       if (get_bindings (TREE_VALUE (champ),
15792                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
15793                         NULL_TREE, /*check_ret=*/false))
15794         fate--;
15795
15796       if (get_bindings (TREE_VALUE (fn),
15797                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
15798                         NULL_TREE, /*check_ret=*/false))
15799         fate++;
15800
15801       if (fate == -1)
15802         champ = fn;
15803       else if (!fate)
15804         {
15805           /* Equally specialized, move to next function.  If there
15806              is no next function, nothing's most specialized.  */
15807           fn = TREE_CHAIN (fn);
15808           champ = fn;
15809           if (!fn)
15810             break;
15811         }
15812     }
15813
15814   if (champ)
15815     /* Now verify that champ is better than everything earlier in the
15816        instantiation list.  */
15817     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
15818       if (get_bindings (TREE_VALUE (champ),
15819                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
15820                         NULL_TREE, /*check_ret=*/false)
15821           || !get_bindings (TREE_VALUE (fn),
15822                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
15823                             NULL_TREE, /*check_ret=*/false))
15824         {
15825           champ = NULL_TREE;
15826           break;
15827         }
15828
15829   processing_template_decl--;
15830
15831   if (!champ)
15832     return error_mark_node;
15833
15834   return champ;
15835 }
15836
15837 /* If DECL is a specialization of some template, return the most
15838    general such template.  Otherwise, returns NULL_TREE.
15839
15840    For example, given:
15841
15842      template <class T> struct S { template <class U> void f(U); };
15843
15844    if TMPL is `template <class U> void S<int>::f(U)' this will return
15845    the full template.  This function will not trace past partial
15846    specializations, however.  For example, given in addition:
15847
15848      template <class T> struct S<T*> { template <class U> void f(U); };
15849
15850    if TMPL is `template <class U> void S<int*>::f(U)' this will return
15851    `template <class T> template <class U> S<T*>::f(U)'.  */
15852
15853 tree
15854 most_general_template (tree decl)
15855 {
15856   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
15857      an immediate specialization.  */
15858   if (TREE_CODE (decl) == FUNCTION_DECL)
15859     {
15860       if (DECL_TEMPLATE_INFO (decl)) {
15861         decl = DECL_TI_TEMPLATE (decl);
15862
15863         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
15864            template friend.  */
15865         if (TREE_CODE (decl) != TEMPLATE_DECL)
15866           return NULL_TREE;
15867       } else
15868         return NULL_TREE;
15869     }
15870
15871   /* Look for more and more general templates.  */
15872   while (DECL_TEMPLATE_INFO (decl))
15873     {
15874       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
15875          (See cp-tree.h for details.)  */
15876       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
15877         break;
15878
15879       if (CLASS_TYPE_P (TREE_TYPE (decl))
15880           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
15881         break;
15882
15883       /* Stop if we run into an explicitly specialized class template.  */
15884       if (!DECL_NAMESPACE_SCOPE_P (decl)
15885           && DECL_CONTEXT (decl)
15886           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
15887         break;
15888
15889       decl = DECL_TI_TEMPLATE (decl);
15890     }
15891
15892   return decl;
15893 }
15894
15895 /* Return the most specialized of the class template partial
15896    specializations of TMPL which can produce TYPE, a specialization of
15897    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
15898    a _TYPE node corresponding to the partial specialization, while the
15899    TREE_PURPOSE is the set of template arguments that must be
15900    substituted into the TREE_TYPE in order to generate TYPE.
15901
15902    If the choice of partial specialization is ambiguous, a diagnostic
15903    is issued, and the error_mark_node is returned.  If there are no
15904    partial specializations of TMPL matching TYPE, then NULL_TREE is
15905    returned.  */
15906
15907 static tree
15908 most_specialized_class (tree type, tree tmpl)
15909 {
15910   tree list = NULL_TREE;
15911   tree t;
15912   tree champ;
15913   int fate;
15914   bool ambiguous_p;
15915   tree args;
15916   tree outer_args = NULL_TREE;
15917
15918   tmpl = most_general_template (tmpl);
15919   args = CLASSTYPE_TI_ARGS (type);
15920
15921   /* For determining which partial specialization to use, only the
15922      innermost args are interesting.  */
15923   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
15924     {
15925       outer_args = strip_innermost_template_args (args, 1);
15926       args = INNERMOST_TEMPLATE_ARGS (args);
15927     }
15928
15929   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
15930     {
15931       tree partial_spec_args;
15932       tree spec_args;
15933       tree parms = TREE_VALUE (t);
15934
15935       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
15936       if (outer_args)
15937         {
15938           int i;
15939
15940           ++processing_template_decl;
15941
15942           /* Discard the outer levels of args, and then substitute in the
15943              template args from the enclosing class.  */
15944           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
15945           partial_spec_args = tsubst_template_args
15946             (partial_spec_args, outer_args, tf_none, NULL_TREE);
15947
15948           /* PARMS already refers to just the innermost parms, but the
15949              template parms in partial_spec_args had their levels lowered
15950              by tsubst, so we need to do the same for the parm list.  We
15951              can't just tsubst the TREE_VEC itself, as tsubst wants to
15952              treat a TREE_VEC as an argument vector.  */
15953           parms = copy_node (parms);
15954           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
15955             TREE_VEC_ELT (parms, i) =
15956               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
15957
15958           --processing_template_decl;
15959         }
15960
15961       partial_spec_args =
15962           coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
15963                                  add_to_template_args (outer_args,
15964                                                        partial_spec_args),
15965                                  tmpl, tf_none,
15966                                  /*require_all_args=*/true,
15967                                  /*use_default_args=*/true);
15968
15969       if (partial_spec_args == error_mark_node)
15970         return error_mark_node;
15971
15972       spec_args = get_class_bindings (parms,
15973                                       partial_spec_args,
15974                                       args);
15975       if (spec_args)
15976         {
15977           if (outer_args)
15978             spec_args = add_to_template_args (outer_args, spec_args);
15979           list = tree_cons (spec_args, TREE_VALUE (t), list);
15980           TREE_TYPE (list) = TREE_TYPE (t);
15981         }
15982     }
15983
15984   if (! list)
15985     return NULL_TREE;
15986
15987   ambiguous_p = false;
15988   t = list;
15989   champ = t;
15990   t = TREE_CHAIN (t);
15991   for (; t; t = TREE_CHAIN (t))
15992     {
15993       fate = more_specialized_class (champ, t);
15994       if (fate == 1)
15995         ;
15996       else
15997         {
15998           if (fate == 0)
15999             {
16000               t = TREE_CHAIN (t);
16001               if (! t)
16002                 {
16003                   ambiguous_p = true;
16004                   break;
16005                 }
16006             }
16007           champ = t;
16008         }
16009     }
16010
16011   if (!ambiguous_p)
16012     for (t = list; t && t != champ; t = TREE_CHAIN (t))
16013       {
16014         fate = more_specialized_class (champ, t);
16015         if (fate != 1)
16016           {
16017             ambiguous_p = true;
16018             break;
16019           }
16020       }
16021
16022   if (ambiguous_p)
16023     {
16024       const char *str;
16025       char *spaces = NULL;
16026       error ("ambiguous class template instantiation for %q#T", type);
16027       str = TREE_CHAIN (list) ? _("candidates are:") : _("candidate is:");
16028       for (t = list; t; t = TREE_CHAIN (t))
16029         {
16030           error ("%s %+#T", spaces ? spaces : str, TREE_TYPE (t));
16031           spaces = spaces ? spaces : get_spaces (str);
16032         }
16033       free (spaces);
16034       return error_mark_node;
16035     }
16036
16037   return champ;
16038 }
16039
16040 /* Explicitly instantiate DECL.  */
16041
16042 void
16043 do_decl_instantiation (tree decl, tree storage)
16044 {
16045   tree result = NULL_TREE;
16046   int extern_p = 0;
16047
16048   if (!decl || decl == error_mark_node)
16049     /* An error occurred, for which grokdeclarator has already issued
16050        an appropriate message.  */
16051     return;
16052   else if (! DECL_LANG_SPECIFIC (decl))
16053     {
16054       error ("explicit instantiation of non-template %q#D", decl);
16055       return;
16056     }
16057   else if (TREE_CODE (decl) == VAR_DECL)
16058     {
16059       /* There is an asymmetry here in the way VAR_DECLs and
16060          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
16061          the latter, the DECL we get back will be marked as a
16062          template instantiation, and the appropriate
16063          DECL_TEMPLATE_INFO will be set up.  This does not happen for
16064          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
16065          should handle VAR_DECLs as it currently handles
16066          FUNCTION_DECLs.  */
16067       if (!DECL_CLASS_SCOPE_P (decl))
16068         {
16069           error ("%qD is not a static data member of a class template", decl);
16070           return;
16071         }
16072       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
16073       if (!result || TREE_CODE (result) != VAR_DECL)
16074         {
16075           error ("no matching template for %qD found", decl);
16076           return;
16077         }
16078       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
16079         {
16080           error ("type %qT for explicit instantiation %qD does not match "
16081                  "declared type %qT", TREE_TYPE (result), decl,
16082                  TREE_TYPE (decl));
16083           return;
16084         }
16085     }
16086   else if (TREE_CODE (decl) != FUNCTION_DECL)
16087     {
16088       error ("explicit instantiation of %q#D", decl);
16089       return;
16090     }
16091   else
16092     result = decl;
16093
16094   /* Check for various error cases.  Note that if the explicit
16095      instantiation is valid the RESULT will currently be marked as an
16096      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
16097      until we get here.  */
16098
16099   if (DECL_TEMPLATE_SPECIALIZATION (result))
16100     {
16101       /* DR 259 [temp.spec].
16102
16103          Both an explicit instantiation and a declaration of an explicit
16104          specialization shall not appear in a program unless the explicit
16105          instantiation follows a declaration of the explicit specialization.
16106
16107          For a given set of template parameters, if an explicit
16108          instantiation of a template appears after a declaration of an
16109          explicit specialization for that template, the explicit
16110          instantiation has no effect.  */
16111       return;
16112     }
16113   else if (DECL_EXPLICIT_INSTANTIATION (result))
16114     {
16115       /* [temp.spec]
16116
16117          No program shall explicitly instantiate any template more
16118          than once.
16119
16120          We check DECL_NOT_REALLY_EXTERN so as not to complain when
16121          the first instantiation was `extern' and the second is not,
16122          and EXTERN_P for the opposite case.  */
16123       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
16124         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
16125       /* If an "extern" explicit instantiation follows an ordinary
16126          explicit instantiation, the template is instantiated.  */
16127       if (extern_p)
16128         return;
16129     }
16130   else if (!DECL_IMPLICIT_INSTANTIATION (result))
16131     {
16132       error ("no matching template for %qD found", result);
16133       return;
16134     }
16135   else if (!DECL_TEMPLATE_INFO (result))
16136     {
16137       permerror (input_location, "explicit instantiation of non-template %q#D", result);
16138       return;
16139     }
16140
16141   if (storage == NULL_TREE)
16142     ;
16143   else if (storage == ridpointers[(int) RID_EXTERN])
16144     {
16145       if (!in_system_header && (cxx_dialect == cxx98))
16146         pedwarn (input_location, OPT_pedantic, 
16147                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
16148                  "instantiations");
16149       extern_p = 1;
16150     }
16151   else
16152     error ("storage class %qD applied to template instantiation", storage);
16153
16154   check_explicit_instantiation_namespace (result);
16155   mark_decl_instantiated (result, extern_p);
16156   if (! extern_p)
16157     instantiate_decl (result, /*defer_ok=*/1,
16158                       /*expl_inst_class_mem_p=*/false);
16159 }
16160
16161 static void
16162 mark_class_instantiated (tree t, int extern_p)
16163 {
16164   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
16165   SET_CLASSTYPE_INTERFACE_KNOWN (t);
16166   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
16167   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
16168   if (! extern_p)
16169     {
16170       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
16171       rest_of_type_compilation (t, 1);
16172     }
16173 }
16174
16175 /* Called from do_type_instantiation through binding_table_foreach to
16176    do recursive instantiation for the type bound in ENTRY.  */
16177 static void
16178 bt_instantiate_type_proc (binding_entry entry, void *data)
16179 {
16180   tree storage = *(tree *) data;
16181
16182   if (MAYBE_CLASS_TYPE_P (entry->type)
16183       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
16184     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
16185 }
16186
16187 /* Called from do_type_instantiation to instantiate a member
16188    (a member function or a static member variable) of an
16189    explicitly instantiated class template.  */
16190 static void
16191 instantiate_class_member (tree decl, int extern_p)
16192 {
16193   mark_decl_instantiated (decl, extern_p);
16194   if (! extern_p)
16195     instantiate_decl (decl, /*defer_ok=*/1,
16196                       /*expl_inst_class_mem_p=*/true);
16197 }
16198
16199 /* Perform an explicit instantiation of template class T.  STORAGE, if
16200    non-null, is the RID for extern, inline or static.  COMPLAIN is
16201    nonzero if this is called from the parser, zero if called recursively,
16202    since the standard is unclear (as detailed below).  */
16203
16204 void
16205 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
16206 {
16207   int extern_p = 0;
16208   int nomem_p = 0;
16209   int static_p = 0;
16210   int previous_instantiation_extern_p = 0;
16211
16212   if (TREE_CODE (t) == TYPE_DECL)
16213     t = TREE_TYPE (t);
16214
16215   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
16216     {
16217       error ("explicit instantiation of non-template type %qT", t);
16218       return;
16219     }
16220
16221   complete_type (t);
16222
16223   if (!COMPLETE_TYPE_P (t))
16224     {
16225       if (complain & tf_error)
16226         error ("explicit instantiation of %q#T before definition of template",
16227                t);
16228       return;
16229     }
16230
16231   if (storage != NULL_TREE)
16232     {
16233       if (!in_system_header)
16234         {
16235           if (storage == ridpointers[(int) RID_EXTERN])
16236             {
16237               if (cxx_dialect == cxx98)
16238                 pedwarn (input_location, OPT_pedantic, 
16239                          "ISO C++ 1998 forbids the use of %<extern%> on "
16240                          "explicit instantiations");
16241             }
16242           else
16243             pedwarn (input_location, OPT_pedantic, 
16244                      "ISO C++ forbids the use of %qE"
16245                      " on explicit instantiations", storage);
16246         }
16247
16248       if (storage == ridpointers[(int) RID_INLINE])
16249         nomem_p = 1;
16250       else if (storage == ridpointers[(int) RID_EXTERN])
16251         extern_p = 1;
16252       else if (storage == ridpointers[(int) RID_STATIC])
16253         static_p = 1;
16254       else
16255         {
16256           error ("storage class %qD applied to template instantiation",
16257                  storage);
16258           extern_p = 0;
16259         }
16260     }
16261
16262   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
16263     {
16264       /* DR 259 [temp.spec].
16265
16266          Both an explicit instantiation and a declaration of an explicit
16267          specialization shall not appear in a program unless the explicit
16268          instantiation follows a declaration of the explicit specialization.
16269
16270          For a given set of template parameters, if an explicit
16271          instantiation of a template appears after a declaration of an
16272          explicit specialization for that template, the explicit
16273          instantiation has no effect.  */
16274       return;
16275     }
16276   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
16277     {
16278       /* [temp.spec]
16279
16280          No program shall explicitly instantiate any template more
16281          than once.
16282
16283          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
16284          instantiation was `extern'.  If EXTERN_P then the second is.
16285          These cases are OK.  */
16286       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
16287
16288       if (!previous_instantiation_extern_p && !extern_p
16289           && (complain & tf_error))
16290         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
16291
16292       /* If we've already instantiated the template, just return now.  */
16293       if (!CLASSTYPE_INTERFACE_ONLY (t))
16294         return;
16295     }
16296
16297   check_explicit_instantiation_namespace (TYPE_NAME (t));
16298   mark_class_instantiated (t, extern_p);
16299
16300   if (nomem_p)
16301     return;
16302
16303   {
16304     tree tmp;
16305
16306     /* In contrast to implicit instantiation, where only the
16307        declarations, and not the definitions, of members are
16308        instantiated, we have here:
16309
16310          [temp.explicit]
16311
16312          The explicit instantiation of a class template specialization
16313          implies the instantiation of all of its members not
16314          previously explicitly specialized in the translation unit
16315          containing the explicit instantiation.
16316
16317        Of course, we can't instantiate member template classes, since
16318        we don't have any arguments for them.  Note that the standard
16319        is unclear on whether the instantiation of the members are
16320        *explicit* instantiations or not.  However, the most natural
16321        interpretation is that it should be an explicit instantiation.  */
16322
16323     if (! static_p)
16324       for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
16325         if (TREE_CODE (tmp) == FUNCTION_DECL
16326             && DECL_TEMPLATE_INSTANTIATION (tmp))
16327           instantiate_class_member (tmp, extern_p);
16328
16329     for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
16330       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
16331         instantiate_class_member (tmp, extern_p);
16332
16333     if (CLASSTYPE_NESTED_UTDS (t))
16334       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
16335                              bt_instantiate_type_proc, &storage);
16336   }
16337 }
16338
16339 /* Given a function DECL, which is a specialization of TMPL, modify
16340    DECL to be a re-instantiation of TMPL with the same template
16341    arguments.  TMPL should be the template into which tsubst'ing
16342    should occur for DECL, not the most general template.
16343
16344    One reason for doing this is a scenario like this:
16345
16346      template <class T>
16347      void f(const T&, int i);
16348
16349      void g() { f(3, 7); }
16350
16351      template <class T>
16352      void f(const T& t, const int i) { }
16353
16354    Note that when the template is first instantiated, with
16355    instantiate_template, the resulting DECL will have no name for the
16356    first parameter, and the wrong type for the second.  So, when we go
16357    to instantiate the DECL, we regenerate it.  */
16358
16359 static void
16360 regenerate_decl_from_template (tree decl, tree tmpl)
16361 {
16362   /* The arguments used to instantiate DECL, from the most general
16363      template.  */
16364   tree args;
16365   tree code_pattern;
16366
16367   args = DECL_TI_ARGS (decl);
16368   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
16369
16370   /* Make sure that we can see identifiers, and compute access
16371      correctly.  */
16372   push_access_scope (decl);
16373
16374   if (TREE_CODE (decl) == FUNCTION_DECL)
16375     {
16376       tree decl_parm;
16377       tree pattern_parm;
16378       tree specs;
16379       int args_depth;
16380       int parms_depth;
16381
16382       args_depth = TMPL_ARGS_DEPTH (args);
16383       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
16384       if (args_depth > parms_depth)
16385         args = get_innermost_template_args (args, parms_depth);
16386
16387       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
16388                                               args, tf_error, NULL_TREE);
16389       if (specs)
16390         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
16391                                                     specs);
16392
16393       /* Merge parameter declarations.  */
16394       decl_parm = skip_artificial_parms_for (decl,
16395                                              DECL_ARGUMENTS (decl));
16396       pattern_parm
16397         = skip_artificial_parms_for (code_pattern,
16398                                      DECL_ARGUMENTS (code_pattern));
16399       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
16400         {
16401           tree parm_type;
16402           tree attributes;
16403           
16404           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16405             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
16406           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
16407                               NULL_TREE);
16408           parm_type = type_decays_to (parm_type);
16409           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16410             TREE_TYPE (decl_parm) = parm_type;
16411           attributes = DECL_ATTRIBUTES (pattern_parm);
16412           if (DECL_ATTRIBUTES (decl_parm) != attributes)
16413             {
16414               DECL_ATTRIBUTES (decl_parm) = attributes;
16415               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16416             }
16417           decl_parm = TREE_CHAIN (decl_parm);
16418           pattern_parm = TREE_CHAIN (pattern_parm);
16419         }
16420       /* Merge any parameters that match with the function parameter
16421          pack.  */
16422       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
16423         {
16424           int i, len;
16425           tree expanded_types;
16426           /* Expand the TYPE_PACK_EXPANSION that provides the types for
16427              the parameters in this function parameter pack.  */
16428           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
16429                                                  args, tf_error, NULL_TREE);
16430           len = TREE_VEC_LENGTH (expanded_types);
16431           for (i = 0; i < len; i++)
16432             {
16433               tree parm_type;
16434               tree attributes;
16435           
16436               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16437                 /* Rename the parameter to include the index.  */
16438                 DECL_NAME (decl_parm) = 
16439                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
16440               parm_type = TREE_VEC_ELT (expanded_types, i);
16441               parm_type = type_decays_to (parm_type);
16442               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16443                 TREE_TYPE (decl_parm) = parm_type;
16444               attributes = DECL_ATTRIBUTES (pattern_parm);
16445               if (DECL_ATTRIBUTES (decl_parm) != attributes)
16446                 {
16447                   DECL_ATTRIBUTES (decl_parm) = attributes;
16448                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16449                 }
16450               decl_parm = TREE_CHAIN (decl_parm);
16451             }
16452         }
16453       /* Merge additional specifiers from the CODE_PATTERN.  */
16454       if (DECL_DECLARED_INLINE_P (code_pattern)
16455           && !DECL_DECLARED_INLINE_P (decl))
16456         DECL_DECLARED_INLINE_P (decl) = 1;
16457     }
16458   else if (TREE_CODE (decl) == VAR_DECL)
16459     DECL_INITIAL (decl) =
16460       tsubst_expr (DECL_INITIAL (code_pattern), args,
16461                    tf_error, DECL_TI_TEMPLATE (decl),
16462                    /*integral_constant_expression_p=*/false);
16463   else
16464     gcc_unreachable ();
16465
16466   pop_access_scope (decl);
16467 }
16468
16469 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
16470    substituted to get DECL.  */
16471
16472 tree
16473 template_for_substitution (tree decl)
16474 {
16475   tree tmpl = DECL_TI_TEMPLATE (decl);
16476
16477   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
16478      for the instantiation.  This is not always the most general
16479      template.  Consider, for example:
16480
16481         template <class T>
16482         struct S { template <class U> void f();
16483                    template <> void f<int>(); };
16484
16485      and an instantiation of S<double>::f<int>.  We want TD to be the
16486      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
16487   while (/* An instantiation cannot have a definition, so we need a
16488             more general template.  */
16489          DECL_TEMPLATE_INSTANTIATION (tmpl)
16490            /* We must also deal with friend templates.  Given:
16491
16492                 template <class T> struct S {
16493                   template <class U> friend void f() {};
16494                 };
16495
16496               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
16497               so far as the language is concerned, but that's still
16498               where we get the pattern for the instantiation from.  On
16499               other hand, if the definition comes outside the class, say:
16500
16501                 template <class T> struct S {
16502                   template <class U> friend void f();
16503                 };
16504                 template <class U> friend void f() {}
16505
16506               we don't need to look any further.  That's what the check for
16507               DECL_INITIAL is for.  */
16508           || (TREE_CODE (decl) == FUNCTION_DECL
16509               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
16510               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
16511     {
16512       /* The present template, TD, should not be a definition.  If it
16513          were a definition, we should be using it!  Note that we
16514          cannot restructure the loop to just keep going until we find
16515          a template with a definition, since that might go too far if
16516          a specialization was declared, but not defined.  */
16517       gcc_assert (TREE_CODE (decl) != VAR_DECL
16518                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
16519
16520       /* Fetch the more general template.  */
16521       tmpl = DECL_TI_TEMPLATE (tmpl);
16522     }
16523
16524   return tmpl;
16525 }
16526
16527 /* Returns true if we need to instantiate this template instance even if we
16528    know we aren't going to emit it..  */
16529
16530 bool
16531 always_instantiate_p (tree decl)
16532 {
16533   /* We always instantiate inline functions so that we can inline them.  An
16534      explicit instantiation declaration prohibits implicit instantiation of
16535      non-inline functions.  With high levels of optimization, we would
16536      normally inline non-inline functions -- but we're not allowed to do
16537      that for "extern template" functions.  Therefore, we check
16538      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
16539   return ((TREE_CODE (decl) == FUNCTION_DECL
16540            && DECL_DECLARED_INLINE_P (decl))
16541           /* And we need to instantiate static data members so that
16542              their initializers are available in integral constant
16543              expressions.  */
16544           || (TREE_CODE (decl) == VAR_DECL
16545               && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl)));
16546 }
16547
16548 /* Produce the definition of D, a _DECL generated from a template.  If
16549    DEFER_OK is nonzero, then we don't have to actually do the
16550    instantiation now; we just have to do it sometime.  Normally it is
16551    an error if this is an explicit instantiation but D is undefined.
16552    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
16553    explicitly instantiated class template.  */
16554
16555 tree
16556 instantiate_decl (tree d, int defer_ok,
16557                   bool expl_inst_class_mem_p)
16558 {
16559   tree tmpl = DECL_TI_TEMPLATE (d);
16560   tree gen_args;
16561   tree args;
16562   tree td;
16563   tree code_pattern;
16564   tree spec;
16565   tree gen_tmpl;
16566   bool pattern_defined;
16567   int need_push;
16568   location_t saved_loc = input_location;
16569   bool external_p;
16570
16571   /* This function should only be used to instantiate templates for
16572      functions and static member variables.  */
16573   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
16574               || TREE_CODE (d) == VAR_DECL);
16575
16576   /* Variables are never deferred; if instantiation is required, they
16577      are instantiated right away.  That allows for better code in the
16578      case that an expression refers to the value of the variable --
16579      if the variable has a constant value the referring expression can
16580      take advantage of that fact.  */
16581   if (TREE_CODE (d) == VAR_DECL)
16582     defer_ok = 0;
16583
16584   /* Don't instantiate cloned functions.  Instead, instantiate the
16585      functions they cloned.  */
16586   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
16587     d = DECL_CLONED_FUNCTION (d);
16588
16589   if (DECL_TEMPLATE_INSTANTIATED (d)
16590       || DECL_TEMPLATE_SPECIALIZATION (d))
16591     /* D has already been instantiated or explicitly specialized, so
16592        there's nothing for us to do here.
16593
16594        It might seem reasonable to check whether or not D is an explicit
16595        instantiation, and, if so, stop here.  But when an explicit
16596        instantiation is deferred until the end of the compilation,
16597        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
16598        the instantiation.  */
16599     return d;
16600
16601   /* Check to see whether we know that this template will be
16602      instantiated in some other file, as with "extern template"
16603      extension.  */
16604   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
16605
16606   /* In general, we do not instantiate such templates.  */
16607   if (external_p && !always_instantiate_p (d))
16608     return d;
16609
16610   gen_tmpl = most_general_template (tmpl);
16611   gen_args = DECL_TI_ARGS (d);
16612
16613   if (tmpl != gen_tmpl)
16614     /* We should already have the extra args.  */
16615     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
16616                 == TMPL_ARGS_DEPTH (gen_args));
16617   /* And what's in the hash table should match D.  */
16618   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
16619               || spec == NULL_TREE);
16620
16621   /* This needs to happen before any tsubsting.  */
16622   if (! push_tinst_level (d))
16623     return d;
16624
16625   timevar_push (TV_PARSE);
16626
16627   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
16628      for the instantiation.  */
16629   td = template_for_substitution (d);
16630   code_pattern = DECL_TEMPLATE_RESULT (td);
16631
16632   /* We should never be trying to instantiate a member of a class
16633      template or partial specialization.  */
16634   gcc_assert (d != code_pattern);
16635
16636   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
16637       || DECL_TEMPLATE_SPECIALIZATION (td))
16638     /* In the case of a friend template whose definition is provided
16639        outside the class, we may have too many arguments.  Drop the
16640        ones we don't need.  The same is true for specializations.  */
16641     args = get_innermost_template_args
16642       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
16643   else
16644     args = gen_args;
16645
16646   if (TREE_CODE (d) == FUNCTION_DECL)
16647     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
16648   else
16649     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
16650
16651   /* We may be in the middle of deferred access check.  Disable it now.  */
16652   push_deferring_access_checks (dk_no_deferred);
16653
16654   /* Unless an explicit instantiation directive has already determined
16655      the linkage of D, remember that a definition is available for
16656      this entity.  */
16657   if (pattern_defined
16658       && !DECL_INTERFACE_KNOWN (d)
16659       && !DECL_NOT_REALLY_EXTERN (d))
16660     mark_definable (d);
16661
16662   input_location = DECL_SOURCE_LOCATION (d);
16663
16664   /* If D is a member of an explicitly instantiated class template,
16665      and no definition is available, treat it like an implicit
16666      instantiation.  */
16667   if (!pattern_defined && expl_inst_class_mem_p
16668       && DECL_EXPLICIT_INSTANTIATION (d))
16669     {
16670       DECL_NOT_REALLY_EXTERN (d) = 0;
16671       DECL_INTERFACE_KNOWN (d) = 0;
16672       SET_DECL_IMPLICIT_INSTANTIATION (d);
16673     }
16674
16675   /* Recheck the substitutions to obtain any warning messages
16676      about ignoring cv qualifiers.  Don't do this for artificial decls,
16677      as it breaks the context-sensitive substitution for lambda op(). */
16678   if (!defer_ok && !DECL_ARTIFICIAL (d))
16679     {
16680       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
16681       tree type = TREE_TYPE (gen);
16682
16683       /* Make sure that we can see identifiers, and compute access
16684          correctly.  D is already the target FUNCTION_DECL with the
16685          right context.  */
16686       push_access_scope (d);
16687
16688       if (TREE_CODE (gen) == FUNCTION_DECL)
16689         {
16690           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
16691           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
16692                                           d);
16693           /* Don't simply tsubst the function type, as that will give
16694              duplicate warnings about poor parameter qualifications.
16695              The function arguments are the same as the decl_arguments
16696              without the top level cv qualifiers.  */
16697           type = TREE_TYPE (type);
16698         }
16699       tsubst (type, gen_args, tf_warning_or_error, d);
16700
16701       pop_access_scope (d);
16702     }
16703
16704   /* Defer all other templates, unless we have been explicitly
16705      forbidden from doing so.  */
16706   if (/* If there is no definition, we cannot instantiate the
16707          template.  */
16708       ! pattern_defined
16709       /* If it's OK to postpone instantiation, do so.  */
16710       || defer_ok
16711       /* If this is a static data member that will be defined
16712          elsewhere, we don't want to instantiate the entire data
16713          member, but we do want to instantiate the initializer so that
16714          we can substitute that elsewhere.  */
16715       || (external_p && TREE_CODE (d) == VAR_DECL))
16716     {
16717       /* The definition of the static data member is now required so
16718          we must substitute the initializer.  */
16719       if (TREE_CODE (d) == VAR_DECL
16720           && !DECL_INITIAL (d)
16721           && DECL_INITIAL (code_pattern))
16722         {
16723           tree ns;
16724           tree init;
16725
16726           ns = decl_namespace_context (d);
16727           push_nested_namespace (ns);
16728           push_nested_class (DECL_CONTEXT (d));
16729           init = tsubst_expr (DECL_INITIAL (code_pattern),
16730                               args,
16731                               tf_warning_or_error, NULL_TREE,
16732                               /*integral_constant_expression_p=*/false);
16733           cp_finish_decl (d, init, /*init_const_expr_p=*/false,
16734                           /*asmspec_tree=*/NULL_TREE,
16735                           LOOKUP_ONLYCONVERTING);
16736           pop_nested_class ();
16737           pop_nested_namespace (ns);
16738         }
16739
16740       /* We restore the source position here because it's used by
16741          add_pending_template.  */
16742       input_location = saved_loc;
16743
16744       if (at_eof && !pattern_defined
16745           && DECL_EXPLICIT_INSTANTIATION (d)
16746           && DECL_NOT_REALLY_EXTERN (d))
16747         /* [temp.explicit]
16748
16749            The definition of a non-exported function template, a
16750            non-exported member function template, or a non-exported
16751            member function or static data member of a class template
16752            shall be present in every translation unit in which it is
16753            explicitly instantiated.  */
16754         permerror (input_location,  "explicit instantiation of %qD "
16755                    "but no definition available", d);
16756
16757       /* ??? Historically, we have instantiated inline functions, even
16758          when marked as "extern template".  */
16759       if (!(external_p && TREE_CODE (d) == VAR_DECL))
16760         add_pending_template (d);
16761       goto out;
16762     }
16763   /* Tell the repository that D is available in this translation unit
16764      -- and see if it is supposed to be instantiated here.  */
16765   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
16766     {
16767       /* In a PCH file, despite the fact that the repository hasn't
16768          requested instantiation in the PCH it is still possible that
16769          an instantiation will be required in a file that includes the
16770          PCH.  */
16771       if (pch_file)
16772         add_pending_template (d);
16773       /* Instantiate inline functions so that the inliner can do its
16774          job, even though we'll not be emitting a copy of this
16775          function.  */
16776       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
16777         goto out;
16778     }
16779
16780   need_push = !cfun || !global_bindings_p ();
16781   if (need_push)
16782     push_to_top_level ();
16783
16784   /* Mark D as instantiated so that recursive calls to
16785      instantiate_decl do not try to instantiate it again.  */
16786   DECL_TEMPLATE_INSTANTIATED (d) = 1;
16787
16788   /* Regenerate the declaration in case the template has been modified
16789      by a subsequent redeclaration.  */
16790   regenerate_decl_from_template (d, td);
16791
16792   /* We already set the file and line above.  Reset them now in case
16793      they changed as a result of calling regenerate_decl_from_template.  */
16794   input_location = DECL_SOURCE_LOCATION (d);
16795
16796   if (TREE_CODE (d) == VAR_DECL)
16797     {
16798       tree init;
16799
16800       /* Clear out DECL_RTL; whatever was there before may not be right
16801          since we've reset the type of the declaration.  */
16802       SET_DECL_RTL (d, NULL_RTX);
16803       DECL_IN_AGGR_P (d) = 0;
16804
16805       /* The initializer is placed in DECL_INITIAL by
16806          regenerate_decl_from_template.  Pull it out so that
16807          cp_finish_decl can process it.  */
16808       init = DECL_INITIAL (d);
16809       DECL_INITIAL (d) = NULL_TREE;
16810       DECL_INITIALIZED_P (d) = 0;
16811
16812       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
16813          initializer.  That function will defer actual emission until
16814          we have a chance to determine linkage.  */
16815       DECL_EXTERNAL (d) = 0;
16816
16817       /* Enter the scope of D so that access-checking works correctly.  */
16818       push_nested_class (DECL_CONTEXT (d));
16819       cp_finish_decl (d, init, false, NULL_TREE, 0);
16820       pop_nested_class ();
16821     }
16822   else if (TREE_CODE (d) == FUNCTION_DECL)
16823     {
16824       htab_t saved_local_specializations;
16825       tree subst_decl;
16826       tree tmpl_parm;
16827       tree spec_parm;
16828
16829       /* Save away the current list, in case we are instantiating one
16830          template from within the body of another.  */
16831       saved_local_specializations = local_specializations;
16832
16833       /* Set up the list of local specializations.  */
16834       local_specializations = htab_create (37,
16835                                            hash_local_specialization,
16836                                            eq_local_specializations,
16837                                            NULL);
16838
16839       /* Set up context.  */
16840       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
16841
16842       /* Create substitution entries for the parameters.  */
16843       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
16844       tmpl_parm = DECL_ARGUMENTS (subst_decl);
16845       spec_parm = DECL_ARGUMENTS (d);
16846       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
16847         {
16848           register_local_specialization (spec_parm, tmpl_parm);
16849           spec_parm = skip_artificial_parms_for (d, spec_parm);
16850           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
16851         }
16852       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
16853         {
16854           register_local_specialization (spec_parm, tmpl_parm);
16855           tmpl_parm = TREE_CHAIN (tmpl_parm);
16856           spec_parm = TREE_CHAIN (spec_parm);
16857         }
16858       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
16859         {
16860           /* Register the (value) argument pack as a specialization of
16861              TMPL_PARM, then move on.  */
16862           tree argpack = make_fnparm_pack (spec_parm);
16863           register_local_specialization (argpack, tmpl_parm);
16864           tmpl_parm = TREE_CHAIN (tmpl_parm);
16865           spec_parm = NULL_TREE;
16866         }
16867       gcc_assert (!spec_parm);
16868
16869       /* Substitute into the body of the function.  */
16870       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
16871                    tf_warning_or_error, tmpl,
16872                    /*integral_constant_expression_p=*/false);
16873
16874       /* Set the current input_location to the end of the function
16875          so that finish_function knows where we are.  */
16876       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
16877
16878       /* We don't need the local specializations any more.  */
16879       htab_delete (local_specializations);
16880       local_specializations = saved_local_specializations;
16881
16882       /* Finish the function.  */
16883       d = finish_function (0);
16884       expand_or_defer_fn (d);
16885     }
16886
16887   /* We're not deferring instantiation any more.  */
16888   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
16889
16890   if (need_push)
16891     pop_from_top_level ();
16892
16893 out:
16894   input_location = saved_loc;
16895   pop_deferring_access_checks ();
16896   pop_tinst_level ();
16897
16898   timevar_pop (TV_PARSE);
16899
16900   return d;
16901 }
16902
16903 /* Run through the list of templates that we wish we could
16904    instantiate, and instantiate any we can.  RETRIES is the
16905    number of times we retry pending template instantiation.  */
16906
16907 void
16908 instantiate_pending_templates (int retries)
16909 {
16910   int reconsider;
16911   location_t saved_loc = input_location;
16912
16913   /* Instantiating templates may trigger vtable generation.  This in turn
16914      may require further template instantiations.  We place a limit here
16915      to avoid infinite loop.  */
16916   if (pending_templates && retries >= max_tinst_depth)
16917     {
16918       tree decl = pending_templates->tinst->decl;
16919
16920       error ("template instantiation depth exceeds maximum of %d"
16921              " instantiating %q+D, possibly from virtual table generation"
16922              " (use -ftemplate-depth= to increase the maximum)",
16923              max_tinst_depth, decl);
16924       if (TREE_CODE (decl) == FUNCTION_DECL)
16925         /* Pretend that we defined it.  */
16926         DECL_INITIAL (decl) = error_mark_node;
16927       return;
16928     }
16929
16930   do
16931     {
16932       struct pending_template **t = &pending_templates;
16933       struct pending_template *last = NULL;
16934       reconsider = 0;
16935       while (*t)
16936         {
16937           tree instantiation = reopen_tinst_level ((*t)->tinst);
16938           bool complete = false;
16939
16940           if (TYPE_P (instantiation))
16941             {
16942               tree fn;
16943
16944               if (!COMPLETE_TYPE_P (instantiation))
16945                 {
16946                   instantiate_class_template (instantiation);
16947                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
16948                     for (fn = TYPE_METHODS (instantiation);
16949                          fn;
16950                          fn = TREE_CHAIN (fn))
16951                       if (! DECL_ARTIFICIAL (fn))
16952                         instantiate_decl (fn,
16953                                           /*defer_ok=*/0,
16954                                           /*expl_inst_class_mem_p=*/false);
16955                   if (COMPLETE_TYPE_P (instantiation))
16956                     reconsider = 1;
16957                 }
16958
16959               complete = COMPLETE_TYPE_P (instantiation);
16960             }
16961           else
16962             {
16963               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
16964                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
16965                 {
16966                   instantiation
16967                     = instantiate_decl (instantiation,
16968                                         /*defer_ok=*/0,
16969                                         /*expl_inst_class_mem_p=*/false);
16970                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
16971                     reconsider = 1;
16972                 }
16973
16974               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
16975                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
16976             }
16977
16978           if (complete)
16979             /* If INSTANTIATION has been instantiated, then we don't
16980                need to consider it again in the future.  */
16981             *t = (*t)->next;
16982           else
16983             {
16984               last = *t;
16985               t = &(*t)->next;
16986             }
16987           tinst_depth = 0;
16988           current_tinst_level = NULL;
16989         }
16990       last_pending_template = last;
16991     }
16992   while (reconsider);
16993
16994   input_location = saved_loc;
16995 }
16996
16997 /* Substitute ARGVEC into T, which is a list of initializers for
16998    either base class or a non-static data member.  The TREE_PURPOSEs
16999    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
17000    instantiate_decl.  */
17001
17002 static tree
17003 tsubst_initializer_list (tree t, tree argvec)
17004 {
17005   tree inits = NULL_TREE;
17006
17007   for (; t; t = TREE_CHAIN (t))
17008     {
17009       tree decl;
17010       tree init;
17011       tree expanded_bases = NULL_TREE;
17012       tree expanded_arguments = NULL_TREE;
17013       int i, len = 1;
17014
17015       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
17016         {
17017           tree expr;
17018           tree arg;
17019
17020           /* Expand the base class expansion type into separate base
17021              classes.  */
17022           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
17023                                                  tf_warning_or_error,
17024                                                  NULL_TREE);
17025           if (expanded_bases == error_mark_node)
17026             continue;
17027           
17028           /* We'll be building separate TREE_LISTs of arguments for
17029              each base.  */
17030           len = TREE_VEC_LENGTH (expanded_bases);
17031           expanded_arguments = make_tree_vec (len);
17032           for (i = 0; i < len; i++)
17033             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
17034
17035           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
17036              expand each argument in the TREE_VALUE of t.  */
17037           expr = make_node (EXPR_PACK_EXPANSION);
17038           PACK_EXPANSION_PARAMETER_PACKS (expr) =
17039             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
17040
17041           if (TREE_VALUE (t) == void_type_node)
17042             /* VOID_TYPE_NODE is used to indicate
17043                value-initialization.  */
17044             {
17045               for (i = 0; i < len; i++)
17046                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
17047             }
17048           else
17049             {
17050               /* Substitute parameter packs into each argument in the
17051                  TREE_LIST.  */
17052               in_base_initializer = 1;
17053               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
17054                 {
17055                   tree expanded_exprs;
17056
17057                   /* Expand the argument.  */
17058                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
17059                   expanded_exprs 
17060                     = tsubst_pack_expansion (expr, argvec,
17061                                              tf_warning_or_error,
17062                                              NULL_TREE);
17063                   if (expanded_exprs == error_mark_node)
17064                     continue;
17065
17066                   /* Prepend each of the expanded expressions to the
17067                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
17068                   for (i = 0; i < len; i++)
17069                     {
17070                       TREE_VEC_ELT (expanded_arguments, i) = 
17071                         tree_cons (NULL_TREE, 
17072                                    TREE_VEC_ELT (expanded_exprs, i),
17073                                    TREE_VEC_ELT (expanded_arguments, i));
17074                     }
17075                 }
17076               in_base_initializer = 0;
17077
17078               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
17079                  since we built them backwards.  */
17080               for (i = 0; i < len; i++)
17081                 {
17082                   TREE_VEC_ELT (expanded_arguments, i) = 
17083                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
17084                 }
17085             }
17086         }
17087
17088       for (i = 0; i < len; ++i)
17089         {
17090           if (expanded_bases)
17091             {
17092               decl = TREE_VEC_ELT (expanded_bases, i);
17093               decl = expand_member_init (decl);
17094               init = TREE_VEC_ELT (expanded_arguments, i);
17095             }
17096           else
17097             {
17098               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
17099                                   tf_warning_or_error, NULL_TREE);
17100
17101               decl = expand_member_init (decl);
17102               if (decl && !DECL_P (decl))
17103                 in_base_initializer = 1;
17104
17105               init = tsubst_expr (TREE_VALUE (t), argvec, 
17106                                   tf_warning_or_error, NULL_TREE,
17107                                   /*integral_constant_expression_p=*/false);
17108               in_base_initializer = 0;
17109             }
17110
17111           if (decl)
17112             {
17113               init = build_tree_list (decl, init);
17114               TREE_CHAIN (init) = inits;
17115               inits = init;
17116             }
17117         }
17118     }
17119   return inits;
17120 }
17121
17122 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
17123
17124 static void
17125 set_current_access_from_decl (tree decl)
17126 {
17127   if (TREE_PRIVATE (decl))
17128     current_access_specifier = access_private_node;
17129   else if (TREE_PROTECTED (decl))
17130     current_access_specifier = access_protected_node;
17131   else
17132     current_access_specifier = access_public_node;
17133 }
17134
17135 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
17136    is the instantiation (which should have been created with
17137    start_enum) and ARGS are the template arguments to use.  */
17138
17139 static void
17140 tsubst_enum (tree tag, tree newtag, tree args)
17141 {
17142   tree e;
17143
17144   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
17145     {
17146       tree value;
17147       tree decl;
17148
17149       decl = TREE_VALUE (e);
17150       /* Note that in a template enum, the TREE_VALUE is the
17151          CONST_DECL, not the corresponding INTEGER_CST.  */
17152       value = tsubst_expr (DECL_INITIAL (decl),
17153                            args, tf_warning_or_error, NULL_TREE,
17154                            /*integral_constant_expression_p=*/true);
17155
17156       /* Give this enumeration constant the correct access.  */
17157       set_current_access_from_decl (decl);
17158
17159       /* Actually build the enumerator itself.  */
17160       build_enumerator (DECL_NAME (decl), value, newtag);
17161     }
17162
17163   finish_enum (newtag);
17164   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
17165     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
17166 }
17167
17168 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
17169    its type -- but without substituting the innermost set of template
17170    arguments.  So, innermost set of template parameters will appear in
17171    the type.  */
17172
17173 tree
17174 get_mostly_instantiated_function_type (tree decl)
17175 {
17176   tree fn_type;
17177   tree tmpl;
17178   tree targs;
17179   tree tparms;
17180   int parm_depth;
17181
17182   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
17183   targs = DECL_TI_ARGS (decl);
17184   tparms = DECL_TEMPLATE_PARMS (tmpl);
17185   parm_depth = TMPL_PARMS_DEPTH (tparms);
17186
17187   /* There should be as many levels of arguments as there are levels
17188      of parameters.  */
17189   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
17190
17191   fn_type = TREE_TYPE (tmpl);
17192
17193   if (parm_depth == 1)
17194     /* No substitution is necessary.  */
17195     ;
17196   else
17197     {
17198       int i, save_access_control;
17199       tree partial_args;
17200
17201       /* Replace the innermost level of the TARGS with NULL_TREEs to
17202          let tsubst know not to substitute for those parameters.  */
17203       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
17204       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
17205         SET_TMPL_ARGS_LEVEL (partial_args, i,
17206                              TMPL_ARGS_LEVEL (targs, i));
17207       SET_TMPL_ARGS_LEVEL (partial_args,
17208                            TMPL_ARGS_DEPTH (targs),
17209                            make_tree_vec (DECL_NTPARMS (tmpl)));
17210
17211       /* Disable access control as this function is used only during
17212          name-mangling.  */
17213       save_access_control = flag_access_control;
17214       flag_access_control = 0;
17215
17216       ++processing_template_decl;
17217       /* Now, do the (partial) substitution to figure out the
17218          appropriate function type.  */
17219       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
17220       --processing_template_decl;
17221
17222       /* Substitute into the template parameters to obtain the real
17223          innermost set of parameters.  This step is important if the
17224          innermost set of template parameters contains value
17225          parameters whose types depend on outer template parameters.  */
17226       TREE_VEC_LENGTH (partial_args)--;
17227       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
17228
17229       flag_access_control = save_access_control;
17230     }
17231
17232   return fn_type;
17233 }
17234
17235 /* Return truthvalue if we're processing a template different from
17236    the last one involved in diagnostics.  */
17237 int
17238 problematic_instantiation_changed (void)
17239 {
17240   return last_template_error_tick != tinst_level_tick;
17241 }
17242
17243 /* Remember current template involved in diagnostics.  */
17244 void
17245 record_last_problematic_instantiation (void)
17246 {
17247   last_template_error_tick = tinst_level_tick;
17248 }
17249
17250 struct tinst_level *
17251 current_instantiation (void)
17252 {
17253   return current_tinst_level;
17254 }
17255
17256 /* [temp.param] Check that template non-type parm TYPE is of an allowable
17257    type. Return zero for ok, nonzero for disallowed. Issue error and
17258    warning messages under control of COMPLAIN.  */
17259
17260 static int
17261 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
17262 {
17263   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
17264     return 0;
17265   else if (POINTER_TYPE_P (type))
17266     return 0;
17267   else if (TYPE_PTR_TO_MEMBER_P (type))
17268     return 0;
17269   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
17270     return 0;
17271   else if (TREE_CODE (type) == TYPENAME_TYPE)
17272     return 0;
17273
17274   if (complain & tf_error)
17275     error ("%q#T is not a valid type for a template constant parameter", type);
17276   return 1;
17277 }
17278
17279 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
17280    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
17281
17282 static bool
17283 dependent_type_p_r (tree type)
17284 {
17285   tree scope;
17286
17287   /* [temp.dep.type]
17288
17289      A type is dependent if it is:
17290
17291      -- a template parameter. Template template parameters are types
17292         for us (since TYPE_P holds true for them) so we handle
17293         them here.  */
17294   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
17295       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
17296     return true;
17297   /* -- a qualified-id with a nested-name-specifier which contains a
17298         class-name that names a dependent type or whose unqualified-id
17299         names a dependent type.  */
17300   if (TREE_CODE (type) == TYPENAME_TYPE)
17301     return true;
17302   /* -- a cv-qualified type where the cv-unqualified type is
17303         dependent.  */
17304   type = TYPE_MAIN_VARIANT (type);
17305   /* -- a compound type constructed from any dependent type.  */
17306   if (TYPE_PTR_TO_MEMBER_P (type))
17307     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
17308             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
17309                                            (type)));
17310   else if (TREE_CODE (type) == POINTER_TYPE
17311            || TREE_CODE (type) == REFERENCE_TYPE)
17312     return dependent_type_p (TREE_TYPE (type));
17313   else if (TREE_CODE (type) == FUNCTION_TYPE
17314            || TREE_CODE (type) == METHOD_TYPE)
17315     {
17316       tree arg_type;
17317
17318       if (dependent_type_p (TREE_TYPE (type)))
17319         return true;
17320       for (arg_type = TYPE_ARG_TYPES (type);
17321            arg_type;
17322            arg_type = TREE_CHAIN (arg_type))
17323         if (dependent_type_p (TREE_VALUE (arg_type)))
17324           return true;
17325       return false;
17326     }
17327   /* -- an array type constructed from any dependent type or whose
17328         size is specified by a constant expression that is
17329         value-dependent.  */
17330   if (TREE_CODE (type) == ARRAY_TYPE)
17331     {
17332       if (TYPE_DOMAIN (type)
17333           && dependent_type_p (TYPE_DOMAIN (type)))
17334         return true;
17335       return dependent_type_p (TREE_TYPE (type));
17336     }
17337   else if (TREE_CODE (type) == INTEGER_TYPE
17338            && !TREE_CONSTANT (TYPE_MAX_VALUE (type)))
17339     {
17340       /* If this is the TYPE_DOMAIN of an array type, consider it
17341          dependent.  We already checked for value-dependence in
17342          compute_array_index_type.  */
17343       return type_dependent_expression_p (TYPE_MAX_VALUE (type));
17344     }
17345
17346   /* -- a template-id in which either the template name is a template
17347      parameter ...  */
17348   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
17349     return true;
17350   /* ... or any of the template arguments is a dependent type or
17351         an expression that is type-dependent or value-dependent.  */
17352   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
17353            && (any_dependent_template_arguments_p
17354                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
17355     return true;
17356
17357   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
17358      argument of the `typeof' expression is not type-dependent, then
17359      it should already been have resolved.  */
17360   if (TREE_CODE (type) == TYPEOF_TYPE
17361       || TREE_CODE (type) == DECLTYPE_TYPE)
17362     return true;
17363
17364   /* A template argument pack is dependent if any of its packed
17365      arguments are.  */
17366   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
17367     {
17368       tree args = ARGUMENT_PACK_ARGS (type);
17369       int i, len = TREE_VEC_LENGTH (args);
17370       for (i = 0; i < len; ++i)
17371         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
17372           return true;
17373     }
17374
17375   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
17376      be template parameters.  */
17377   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
17378     return true;
17379
17380   /* The standard does not specifically mention types that are local
17381      to template functions or local classes, but they should be
17382      considered dependent too.  For example:
17383
17384        template <int I> void f() {
17385          enum E { a = I };
17386          S<sizeof (E)> s;
17387        }
17388
17389      The size of `E' cannot be known until the value of `I' has been
17390      determined.  Therefore, `E' must be considered dependent.  */
17391   scope = TYPE_CONTEXT (type);
17392   if (scope && TYPE_P (scope))
17393     return dependent_type_p (scope);
17394   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
17395     return type_dependent_expression_p (scope);
17396
17397   /* Other types are non-dependent.  */
17398   return false;
17399 }
17400
17401 /* Returns TRUE if TYPE is dependent, in the sense of
17402    [temp.dep.type].  */
17403
17404 bool
17405 dependent_type_p (tree type)
17406 {
17407   /* If there are no template parameters in scope, then there can't be
17408      any dependent types.  */
17409   if (!processing_template_decl)
17410     {
17411       /* If we are not processing a template, then nobody should be
17412          providing us with a dependent type.  */
17413       gcc_assert (type);
17414       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
17415       return false;
17416     }
17417
17418   /* If the type is NULL, we have not computed a type for the entity
17419      in question; in that case, the type is dependent.  */
17420   if (!type)
17421     return true;
17422
17423   /* Erroneous types can be considered non-dependent.  */
17424   if (type == error_mark_node)
17425     return false;
17426
17427   /* If we have not already computed the appropriate value for TYPE,
17428      do so now.  */
17429   if (!TYPE_DEPENDENT_P_VALID (type))
17430     {
17431       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
17432       TYPE_DEPENDENT_P_VALID (type) = 1;
17433     }
17434
17435   return TYPE_DEPENDENT_P (type);
17436 }
17437
17438 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
17439    lookup.  In other words, a dependent type that is not the current
17440    instantiation.  */
17441
17442 bool
17443 dependent_scope_p (tree scope)
17444 {
17445   return (scope && TYPE_P (scope) && dependent_type_p (scope)
17446           && !currently_open_class (scope));
17447 }
17448
17449 /* Returns TRUE if EXPRESSION is dependent, according to CRITERION.  */
17450
17451 static bool
17452 dependent_scope_ref_p (tree expression, bool criterion (tree))
17453 {
17454   tree scope;
17455   tree name;
17456
17457   gcc_assert (TREE_CODE (expression) == SCOPE_REF);
17458
17459   if (!TYPE_P (TREE_OPERAND (expression, 0)))
17460     return true;
17461
17462   scope = TREE_OPERAND (expression, 0);
17463   name = TREE_OPERAND (expression, 1);
17464
17465   /* [temp.dep.expr]
17466
17467      An id-expression is type-dependent if it contains a
17468      nested-name-specifier that contains a class-name that names a
17469      dependent type.  */
17470   /* The suggested resolution to Core Issue 224 implies that if the
17471      qualifying type is the current class, then we must peek
17472      inside it.  */
17473   if (DECL_P (name)
17474       && currently_open_class (scope)
17475       && !criterion (name))
17476     return false;
17477   if (dependent_type_p (scope))
17478     return true;
17479
17480   return false;
17481 }
17482
17483 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
17484    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
17485    expression.  */
17486
17487 bool
17488 value_dependent_expression_p (tree expression)
17489 {
17490   if (!processing_template_decl)
17491     return false;
17492
17493   /* A name declared with a dependent type.  */
17494   if (DECL_P (expression) && type_dependent_expression_p (expression))
17495     return true;
17496
17497   switch (TREE_CODE (expression))
17498     {
17499     case IDENTIFIER_NODE:
17500       /* A name that has not been looked up -- must be dependent.  */
17501       return true;
17502
17503     case TEMPLATE_PARM_INDEX:
17504       /* A non-type template parm.  */
17505       return true;
17506
17507     case CONST_DECL:
17508       /* A non-type template parm.  */
17509       if (DECL_TEMPLATE_PARM_P (expression))
17510         return true;
17511       return value_dependent_expression_p (DECL_INITIAL (expression));
17512
17513     case VAR_DECL:
17514        /* A constant with integral or enumeration type and is initialized
17515           with an expression that is value-dependent.  */
17516       if (DECL_INITIAL (expression)
17517           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
17518           && value_dependent_expression_p (DECL_INITIAL (expression)))
17519         return true;
17520       return false;
17521
17522     case DYNAMIC_CAST_EXPR:
17523     case STATIC_CAST_EXPR:
17524     case CONST_CAST_EXPR:
17525     case REINTERPRET_CAST_EXPR:
17526     case CAST_EXPR:
17527       /* These expressions are value-dependent if the type to which
17528          the cast occurs is dependent or the expression being casted
17529          is value-dependent.  */
17530       {
17531         tree type = TREE_TYPE (expression);
17532
17533         if (dependent_type_p (type))
17534           return true;
17535
17536         /* A functional cast has a list of operands.  */
17537         expression = TREE_OPERAND (expression, 0);
17538         if (!expression)
17539           {
17540             /* If there are no operands, it must be an expression such
17541                as "int()". This should not happen for aggregate types
17542                because it would form non-constant expressions.  */
17543             gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
17544
17545             return false;
17546           }
17547
17548         if (TREE_CODE (expression) == TREE_LIST)
17549           return any_value_dependent_elements_p (expression);
17550
17551         return value_dependent_expression_p (expression);
17552       }
17553
17554     case SIZEOF_EXPR:
17555     case ALIGNOF_EXPR:
17556       /* A `sizeof' expression is value-dependent if the operand is
17557          type-dependent or is a pack expansion.  */
17558       expression = TREE_OPERAND (expression, 0);
17559       if (PACK_EXPANSION_P (expression))
17560         return true;
17561       else if (TYPE_P (expression))
17562         return dependent_type_p (expression);
17563       return type_dependent_expression_p (expression);
17564
17565     case SCOPE_REF:
17566       return dependent_scope_ref_p (expression, value_dependent_expression_p);
17567
17568     case COMPONENT_REF:
17569       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
17570               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
17571
17572     case CALL_EXPR:
17573       /* A CALL_EXPR may appear in a constant expression if it is a
17574          call to a builtin function, e.g., __builtin_constant_p.  All
17575          such calls are value-dependent.  */
17576       return true;
17577
17578     case NONTYPE_ARGUMENT_PACK:
17579       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
17580          is value-dependent.  */
17581       {
17582         tree values = ARGUMENT_PACK_ARGS (expression);
17583         int i, len = TREE_VEC_LENGTH (values);
17584         
17585         for (i = 0; i < len; ++i)
17586           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
17587             return true;
17588         
17589         return false;
17590       }
17591
17592     case TRAIT_EXPR:
17593       {
17594         tree type2 = TRAIT_EXPR_TYPE2 (expression);
17595         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
17596                 || (type2 ? dependent_type_p (type2) : false));
17597       }
17598
17599     case MODOP_EXPR:
17600       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
17601               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
17602
17603     default:
17604       /* A constant expression is value-dependent if any subexpression is
17605          value-dependent.  */
17606       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
17607         {
17608         case tcc_reference:
17609         case tcc_unary:
17610           return (value_dependent_expression_p
17611                   (TREE_OPERAND (expression, 0)));
17612
17613         case tcc_comparison:
17614         case tcc_binary:
17615           return ((value_dependent_expression_p
17616                    (TREE_OPERAND (expression, 0)))
17617                   || (value_dependent_expression_p
17618                       (TREE_OPERAND (expression, 1))));
17619
17620         case tcc_expression:
17621         case tcc_vl_exp:
17622           {
17623             int i;
17624             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
17625               /* In some cases, some of the operands may be missing.
17626                  (For example, in the case of PREDECREMENT_EXPR, the
17627                  amount to increment by may be missing.)  That doesn't
17628                  make the expression dependent.  */
17629               if (TREE_OPERAND (expression, i)
17630                   && (value_dependent_expression_p
17631                       (TREE_OPERAND (expression, i))))
17632                 return true;
17633             return false;
17634           }
17635
17636         default:
17637           break;
17638         }
17639     }
17640
17641   /* The expression is not value-dependent.  */
17642   return false;
17643 }
17644
17645 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
17646    [temp.dep.expr].  */
17647
17648 bool
17649 type_dependent_expression_p (tree expression)
17650 {
17651   if (!processing_template_decl)
17652     return false;
17653
17654   if (expression == error_mark_node)
17655     return false;
17656
17657   /* An unresolved name is always dependent.  */
17658   if (TREE_CODE (expression) == IDENTIFIER_NODE
17659       || TREE_CODE (expression) == USING_DECL)
17660     return true;
17661
17662   /* Some expression forms are never type-dependent.  */
17663   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
17664       || TREE_CODE (expression) == SIZEOF_EXPR
17665       || TREE_CODE (expression) == ALIGNOF_EXPR
17666       || TREE_CODE (expression) == TRAIT_EXPR
17667       || TREE_CODE (expression) == TYPEID_EXPR
17668       || TREE_CODE (expression) == DELETE_EXPR
17669       || TREE_CODE (expression) == VEC_DELETE_EXPR
17670       || TREE_CODE (expression) == THROW_EXPR)
17671     return false;
17672
17673   /* The types of these expressions depends only on the type to which
17674      the cast occurs.  */
17675   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
17676       || TREE_CODE (expression) == STATIC_CAST_EXPR
17677       || TREE_CODE (expression) == CONST_CAST_EXPR
17678       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
17679       || TREE_CODE (expression) == CAST_EXPR)
17680     return dependent_type_p (TREE_TYPE (expression));
17681
17682   /* The types of these expressions depends only on the type created
17683      by the expression.  */
17684   if (TREE_CODE (expression) == NEW_EXPR
17685       || TREE_CODE (expression) == VEC_NEW_EXPR)
17686     {
17687       /* For NEW_EXPR tree nodes created inside a template, either
17688          the object type itself or a TREE_LIST may appear as the
17689          operand 1.  */
17690       tree type = TREE_OPERAND (expression, 1);
17691       if (TREE_CODE (type) == TREE_LIST)
17692         /* This is an array type.  We need to check array dimensions
17693            as well.  */
17694         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
17695                || value_dependent_expression_p
17696                     (TREE_OPERAND (TREE_VALUE (type), 1));
17697       else
17698         return dependent_type_p (type);
17699     }
17700
17701   if (TREE_CODE (expression) == SCOPE_REF
17702       && dependent_scope_ref_p (expression,
17703                                 type_dependent_expression_p))
17704     return true;
17705
17706   if (TREE_CODE (expression) == FUNCTION_DECL
17707       && DECL_LANG_SPECIFIC (expression)
17708       && DECL_TEMPLATE_INFO (expression)
17709       && (any_dependent_template_arguments_p
17710           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
17711     return true;
17712
17713   if (TREE_CODE (expression) == TEMPLATE_DECL
17714       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
17715     return false;
17716
17717   if (TREE_CODE (expression) == STMT_EXPR)
17718     expression = stmt_expr_value_expr (expression);
17719
17720   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
17721     {
17722       tree elt;
17723       unsigned i;
17724
17725       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
17726         {
17727           if (type_dependent_expression_p (elt))
17728             return true;
17729         }
17730       return false;
17731     }
17732
17733   if (TREE_TYPE (expression) == unknown_type_node)
17734     {
17735       if (TREE_CODE (expression) == ADDR_EXPR)
17736         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
17737       if (TREE_CODE (expression) == COMPONENT_REF
17738           || TREE_CODE (expression) == OFFSET_REF)
17739         {
17740           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
17741             return true;
17742           expression = TREE_OPERAND (expression, 1);
17743           if (TREE_CODE (expression) == IDENTIFIER_NODE)
17744             return false;
17745         }
17746       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
17747       if (TREE_CODE (expression) == SCOPE_REF)
17748         return false;
17749
17750       if (TREE_CODE (expression) == BASELINK)
17751         expression = BASELINK_FUNCTIONS (expression);
17752
17753       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
17754         {
17755           if (any_dependent_template_arguments_p
17756               (TREE_OPERAND (expression, 1)))
17757             return true;
17758           expression = TREE_OPERAND (expression, 0);
17759         }
17760       gcc_assert (TREE_CODE (expression) == OVERLOAD
17761                   || TREE_CODE (expression) == FUNCTION_DECL);
17762
17763       while (expression)
17764         {
17765           if (type_dependent_expression_p (OVL_CURRENT (expression)))
17766             return true;
17767           expression = OVL_NEXT (expression);
17768         }
17769       return false;
17770     }
17771
17772   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
17773
17774   return (dependent_type_p (TREE_TYPE (expression)));
17775 }
17776
17777 /* Like type_dependent_expression_p, but it also works while not processing
17778    a template definition, i.e. during substitution or mangling.  */
17779
17780 bool
17781 type_dependent_expression_p_push (tree expr)
17782 {
17783   bool b;
17784   ++processing_template_decl;
17785   b = type_dependent_expression_p (expr);
17786   --processing_template_decl;
17787   return b;
17788 }
17789
17790 /* Returns TRUE if ARGS contains a type-dependent expression.  */
17791
17792 bool
17793 any_type_dependent_arguments_p (const VEC(tree,gc) *args)
17794 {
17795   unsigned int i;
17796   tree arg;
17797
17798   for (i = 0; VEC_iterate (tree, args, i, arg); ++i)
17799     {
17800       if (type_dependent_expression_p (arg))
17801         return true;
17802     }
17803   return false;
17804 }
17805
17806 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
17807    expressions) contains any value-dependent expressions.  */
17808
17809 bool
17810 any_value_dependent_elements_p (const_tree list)
17811 {
17812   for (; list; list = TREE_CHAIN (list))
17813     if (value_dependent_expression_p (TREE_VALUE (list)))
17814       return true;
17815
17816   return false;
17817 }
17818
17819 /* Returns TRUE if the ARG (a template argument) is dependent.  */
17820
17821 bool
17822 dependent_template_arg_p (tree arg)
17823 {
17824   if (!processing_template_decl)
17825     return false;
17826
17827   if (TREE_CODE (arg) == TEMPLATE_DECL
17828       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
17829     return dependent_template_p (arg);
17830   else if (ARGUMENT_PACK_P (arg))
17831     {
17832       tree args = ARGUMENT_PACK_ARGS (arg);
17833       int i, len = TREE_VEC_LENGTH (args);
17834       for (i = 0; i < len; ++i)
17835         {
17836           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
17837             return true;
17838         }
17839
17840       return false;
17841     }
17842   else if (TYPE_P (arg))
17843     return dependent_type_p (arg);
17844   else
17845     return (type_dependent_expression_p (arg)
17846             || value_dependent_expression_p (arg));
17847 }
17848
17849 /* Returns true if ARGS (a collection of template arguments) contains
17850    any types that require structural equality testing.  */
17851
17852 bool
17853 any_template_arguments_need_structural_equality_p (tree args)
17854 {
17855   int i;
17856   int j;
17857
17858   if (!args)
17859     return false;
17860   if (args == error_mark_node)
17861     return true;
17862
17863   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
17864     {
17865       tree level = TMPL_ARGS_LEVEL (args, i + 1);
17866       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
17867         {
17868           tree arg = TREE_VEC_ELT (level, j);
17869           tree packed_args = NULL_TREE;
17870           int k, len = 1;
17871
17872           if (ARGUMENT_PACK_P (arg))
17873             {
17874               /* Look inside the argument pack.  */
17875               packed_args = ARGUMENT_PACK_ARGS (arg);
17876               len = TREE_VEC_LENGTH (packed_args);
17877             }
17878
17879           for (k = 0; k < len; ++k)
17880             {
17881               if (packed_args)
17882                 arg = TREE_VEC_ELT (packed_args, k);
17883
17884               if (error_operand_p (arg))
17885                 return true;
17886               else if (TREE_CODE (arg) == TEMPLATE_DECL
17887                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
17888                 continue;
17889               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
17890                 return true;
17891               else if (!TYPE_P (arg) && TREE_TYPE (arg)
17892                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
17893                 return true;
17894             }
17895         }
17896     }
17897
17898   return false;
17899 }
17900
17901 /* Returns true if ARGS (a collection of template arguments) contains
17902    any dependent arguments.  */
17903
17904 bool
17905 any_dependent_template_arguments_p (const_tree args)
17906 {
17907   int i;
17908   int j;
17909
17910   if (!args)
17911     return false;
17912   if (args == error_mark_node)
17913     return true;
17914
17915   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
17916     {
17917       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
17918       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
17919         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
17920           return true;
17921     }
17922
17923   return false;
17924 }
17925
17926 /* Returns TRUE if the template TMPL is dependent.  */
17927
17928 bool
17929 dependent_template_p (tree tmpl)
17930 {
17931   if (TREE_CODE (tmpl) == OVERLOAD)
17932     {
17933       while (tmpl)
17934         {
17935           if (dependent_template_p (OVL_FUNCTION (tmpl)))
17936             return true;
17937           tmpl = OVL_CHAIN (tmpl);
17938         }
17939       return false;
17940     }
17941
17942   /* Template template parameters are dependent.  */
17943   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
17944       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
17945     return true;
17946   /* So are names that have not been looked up.  */
17947   if (TREE_CODE (tmpl) == SCOPE_REF
17948       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
17949     return true;
17950   /* So are member templates of dependent classes.  */
17951   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
17952     return dependent_type_p (DECL_CONTEXT (tmpl));
17953   return false;
17954 }
17955
17956 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
17957
17958 bool
17959 dependent_template_id_p (tree tmpl, tree args)
17960 {
17961   return (dependent_template_p (tmpl)
17962           || any_dependent_template_arguments_p (args));
17963 }
17964
17965 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
17966    is dependent.  */
17967
17968 bool
17969 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
17970 {
17971   int i;
17972
17973   if (!processing_template_decl)
17974     return false;
17975
17976   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
17977     {
17978       tree decl = TREE_VEC_ELT (declv, i);
17979       tree init = TREE_VEC_ELT (initv, i);
17980       tree cond = TREE_VEC_ELT (condv, i);
17981       tree incr = TREE_VEC_ELT (incrv, i);
17982
17983       if (type_dependent_expression_p (decl))
17984         return true;
17985
17986       if (init && type_dependent_expression_p (init))
17987         return true;
17988
17989       if (type_dependent_expression_p (cond))
17990         return true;
17991
17992       if (COMPARISON_CLASS_P (cond)
17993           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
17994               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
17995         return true;
17996
17997       if (TREE_CODE (incr) == MODOP_EXPR)
17998         {
17999           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
18000               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
18001             return true;
18002         }
18003       else if (type_dependent_expression_p (incr))
18004         return true;
18005       else if (TREE_CODE (incr) == MODIFY_EXPR)
18006         {
18007           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
18008             return true;
18009           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
18010             {
18011               tree t = TREE_OPERAND (incr, 1);
18012               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
18013                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
18014                 return true;
18015             }
18016         }
18017     }
18018
18019   return false;
18020 }
18021
18022 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
18023    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
18024    no such TYPE can be found.  Note that this function peers inside
18025    uninstantiated templates and therefore should be used only in
18026    extremely limited situations.  ONLY_CURRENT_P restricts this
18027    peering to the currently open classes hierarchy (which is required
18028    when comparing types).  */
18029
18030 tree
18031 resolve_typename_type (tree type, bool only_current_p)
18032 {
18033   tree scope;
18034   tree name;
18035   tree decl;
18036   int quals;
18037   tree pushed_scope;
18038   tree result;
18039
18040   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
18041
18042   scope = TYPE_CONTEXT (type);
18043   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
18044      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
18045      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
18046      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
18047      identifier  of the TYPENAME_TYPE anymore.
18048      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
18049      TYPENAME_TYPE instead, we avoid messing up with a possible
18050      typedef variant case.  */
18051   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
18052
18053   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
18054      it first before we can figure out what NAME refers to.  */
18055   if (TREE_CODE (scope) == TYPENAME_TYPE)
18056     scope = resolve_typename_type (scope, only_current_p);
18057   /* If we don't know what SCOPE refers to, then we cannot resolve the
18058      TYPENAME_TYPE.  */
18059   if (TREE_CODE (scope) == TYPENAME_TYPE)
18060     return type;
18061   /* If the SCOPE is a template type parameter, we have no way of
18062      resolving the name.  */
18063   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
18064     return type;
18065   /* If the SCOPE is not the current instantiation, there's no reason
18066      to look inside it.  */
18067   if (only_current_p && !currently_open_class (scope))
18068     return type;
18069   /* If this is a typedef, we don't want to look inside (c++/11987).  */
18070   if (typedef_variant_p (type))
18071     return type;
18072   /* If SCOPE isn't the template itself, it will not have a valid
18073      TYPE_FIELDS list.  */
18074   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
18075     /* scope is either the template itself or a compatible instantiation
18076        like X<T>, so look up the name in the original template.  */
18077     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
18078   else
18079     /* scope is a partial instantiation, so we can't do the lookup or we
18080        will lose the template arguments.  */
18081     return type;
18082   /* Enter the SCOPE so that name lookup will be resolved as if we
18083      were in the class definition.  In particular, SCOPE will no
18084      longer be considered a dependent type.  */
18085   pushed_scope = push_scope (scope);
18086   /* Look up the declaration.  */
18087   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
18088
18089   result = NULL_TREE;
18090   
18091   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
18092      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
18093   if (!decl)
18094     /*nop*/;
18095   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
18096            && TREE_CODE (decl) == TYPE_DECL)
18097     {
18098       result = TREE_TYPE (decl);
18099       if (result == error_mark_node)
18100         result = NULL_TREE;
18101     }
18102   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
18103            && DECL_CLASS_TEMPLATE_P (decl))
18104     {
18105       tree tmpl;
18106       tree args;
18107       /* Obtain the template and the arguments.  */
18108       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
18109       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
18110       /* Instantiate the template.  */
18111       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
18112                                       /*entering_scope=*/0,
18113                                       tf_error | tf_user);
18114       if (result == error_mark_node)
18115         result = NULL_TREE;
18116     }
18117   
18118   /* Leave the SCOPE.  */
18119   if (pushed_scope)
18120     pop_scope (pushed_scope);
18121
18122   /* If we failed to resolve it, return the original typename.  */
18123   if (!result)
18124     return type;
18125   
18126   /* If lookup found a typename type, resolve that too.  */
18127   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
18128     {
18129       /* Ill-formed programs can cause infinite recursion here, so we
18130          must catch that.  */
18131       TYPENAME_IS_RESOLVING_P (type) = 1;
18132       result = resolve_typename_type (result, only_current_p);
18133       TYPENAME_IS_RESOLVING_P (type) = 0;
18134     }
18135   
18136   /* Qualify the resulting type.  */
18137   quals = cp_type_quals (type);
18138   if (quals)
18139     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
18140
18141   return result;
18142 }
18143
18144 /* EXPR is an expression which is not type-dependent.  Return a proxy
18145    for EXPR that can be used to compute the types of larger
18146    expressions containing EXPR.  */
18147
18148 tree
18149 build_non_dependent_expr (tree expr)
18150 {
18151   tree inner_expr;
18152
18153   /* Preserve null pointer constants so that the type of things like
18154      "p == 0" where "p" is a pointer can be determined.  */
18155   if (null_ptr_cst_p (expr))
18156     return expr;
18157   /* Preserve OVERLOADs; the functions must be available to resolve
18158      types.  */
18159   inner_expr = expr;
18160   if (TREE_CODE (inner_expr) == STMT_EXPR)
18161     inner_expr = stmt_expr_value_expr (inner_expr);
18162   if (TREE_CODE (inner_expr) == ADDR_EXPR)
18163     inner_expr = TREE_OPERAND (inner_expr, 0);
18164   if (TREE_CODE (inner_expr) == COMPONENT_REF)
18165     inner_expr = TREE_OPERAND (inner_expr, 1);
18166   if (is_overloaded_fn (inner_expr)
18167       || TREE_CODE (inner_expr) == OFFSET_REF)
18168     return expr;
18169   /* There is no need to return a proxy for a variable.  */
18170   if (TREE_CODE (expr) == VAR_DECL)
18171     return expr;
18172   /* Preserve string constants; conversions from string constants to
18173      "char *" are allowed, even though normally a "const char *"
18174      cannot be used to initialize a "char *".  */
18175   if (TREE_CODE (expr) == STRING_CST)
18176     return expr;
18177   /* Preserve arithmetic constants, as an optimization -- there is no
18178      reason to create a new node.  */
18179   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
18180     return expr;
18181   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
18182      There is at least one place where we want to know that a
18183      particular expression is a throw-expression: when checking a ?:
18184      expression, there are special rules if the second or third
18185      argument is a throw-expression.  */
18186   if (TREE_CODE (expr) == THROW_EXPR)
18187     return expr;
18188
18189   if (TREE_CODE (expr) == COND_EXPR)
18190     return build3 (COND_EXPR,
18191                    TREE_TYPE (expr),
18192                    TREE_OPERAND (expr, 0),
18193                    (TREE_OPERAND (expr, 1)
18194                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
18195                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
18196                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
18197   if (TREE_CODE (expr) == COMPOUND_EXPR
18198       && !COMPOUND_EXPR_OVERLOADED (expr))
18199     return build2 (COMPOUND_EXPR,
18200                    TREE_TYPE (expr),
18201                    TREE_OPERAND (expr, 0),
18202                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
18203
18204   /* If the type is unknown, it can't really be non-dependent */
18205   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
18206
18207   /* Otherwise, build a NON_DEPENDENT_EXPR.
18208
18209      REFERENCE_TYPEs are not stripped for expressions in templates
18210      because doing so would play havoc with mangling.  Consider, for
18211      example:
18212
18213        template <typename T> void f<T& g>() { g(); }
18214
18215      In the body of "f", the expression for "g" will have
18216      REFERENCE_TYPE, even though the standard says that it should
18217      not.  The reason is that we must preserve the syntactic form of
18218      the expression so that mangling (say) "f<g>" inside the body of
18219      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
18220      stripped here.  */
18221   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
18222 }
18223
18224 /* ARGS is a vector of expressions as arguments to a function call.
18225    Replace the arguments with equivalent non-dependent expressions.
18226    This modifies ARGS in place.  */
18227
18228 void
18229 make_args_non_dependent (VEC(tree,gc) *args)
18230 {
18231   unsigned int ix;
18232   tree arg;
18233
18234   for (ix = 0; VEC_iterate (tree, args, ix, arg); ++ix)
18235     {
18236       tree newarg = build_non_dependent_expr (arg);
18237       if (newarg != arg)
18238         VEC_replace (tree, args, ix, newarg);
18239     }
18240 }
18241
18242 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
18243    with a level one deeper than the actual template parms.  */
18244
18245 tree
18246 make_auto (void)
18247 {
18248   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
18249   TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
18250                                TYPE_DECL, get_identifier ("auto"), au);
18251   TYPE_STUB_DECL (au) = TYPE_NAME (au);
18252   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
18253     (0, processing_template_decl + 1, processing_template_decl + 1,
18254      TYPE_NAME (au), NULL_TREE);
18255   TYPE_CANONICAL (au) = canonical_type_parameter (au);
18256   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
18257   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
18258
18259   return au;
18260 }
18261
18262 /* Given type ARG, return std::initializer_list<ARG>.  */
18263
18264 static tree
18265 listify (tree arg)
18266 {
18267   tree std_init_list = namespace_binding
18268     (get_identifier ("initializer_list"), std_node);
18269   tree argvec;
18270   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
18271     {    
18272       error ("deducing from brace-enclosed initializer list requires "
18273              "#include <initializer_list>");
18274       return error_mark_node;
18275     }
18276   argvec = make_tree_vec (1);
18277   TREE_VEC_ELT (argvec, 0) = arg;
18278   return lookup_template_class (std_init_list, argvec, NULL_TREE,
18279                                 NULL_TREE, 0, tf_warning_or_error);
18280 }
18281
18282 /* Replace auto in TYPE with std::initializer_list<auto>.  */
18283
18284 static tree
18285 listify_autos (tree type, tree auto_node)
18286 {
18287   tree init_auto = listify (auto_node);
18288   tree argvec = make_tree_vec (1);
18289   TREE_VEC_ELT (argvec, 0) = init_auto;
18290   if (processing_template_decl)
18291     argvec = add_to_template_args (current_template_args (), argvec);
18292   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
18293 }
18294
18295 /* walk_tree helper for do_auto_deduction.  */
18296
18297 static tree
18298 contains_auto_r (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
18299                  void *type)
18300 {
18301   /* Is this a variable with the type we're looking for?  */
18302   if (DECL_P (*tp)
18303       && TREE_TYPE (*tp) == type)
18304     return *tp;
18305   else
18306     return NULL_TREE;
18307 }
18308
18309 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
18310    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
18311
18312 tree
18313 do_auto_deduction (tree type, tree init, tree auto_node)
18314 {
18315   tree parms, tparms, targs;
18316   tree args[1];
18317   tree decl;
18318   int val;
18319
18320   /* The name of the object being declared shall not appear in the
18321      initializer expression.  */
18322   decl = cp_walk_tree_without_duplicates (&init, contains_auto_r, type);
18323   if (decl)
18324     {
18325       error ("variable %q#D with %<auto%> type used in its own "
18326              "initializer", decl);
18327       return error_mark_node;
18328     }
18329
18330   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
18331      with either a new invented type template parameter U or, if the
18332      initializer is a braced-init-list (8.5.4), with
18333      std::initializer_list<U>.  */
18334   if (BRACE_ENCLOSED_INITIALIZER_P (init))
18335     type = listify_autos (type, auto_node);
18336
18337   parms = build_tree_list (NULL_TREE, type);
18338   args[0] = init;
18339   tparms = make_tree_vec (1);
18340   targs = make_tree_vec (1);
18341   TREE_VEC_ELT (tparms, 0)
18342     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
18343   val = type_unification_real (tparms, targs, parms, args, 1, 0,
18344                                DEDUCE_CALL, LOOKUP_NORMAL);
18345   if (val > 0)
18346     {
18347       error ("unable to deduce %qT from %qE", type, init);
18348       return error_mark_node;
18349     }
18350
18351   /* If the list of declarators contains more than one declarator, the type
18352      of each declared variable is determined as described above. If the
18353      type deduced for the template parameter U is not the same in each
18354      deduction, the program is ill-formed.  */
18355   if (TREE_TYPE (auto_node)
18356       && !same_type_p (TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0)))
18357     {
18358       error ("inconsistent deduction for %qT: %qT and then %qT",
18359              auto_node, TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0));
18360       return error_mark_node;
18361     }
18362   TREE_TYPE (auto_node) = TREE_VEC_ELT (targs, 0);
18363
18364   if (processing_template_decl)
18365     targs = add_to_template_args (current_template_args (), targs);
18366   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
18367 }
18368
18369 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
18370    result.  */
18371
18372 tree
18373 splice_late_return_type (tree type, tree late_return_type)
18374 {
18375   tree argvec;
18376
18377   if (late_return_type == NULL_TREE)
18378     return type;
18379   argvec = make_tree_vec (1);
18380   TREE_VEC_ELT (argvec, 0) = late_return_type;
18381   if (processing_template_decl)
18382     argvec = add_to_template_args (current_template_args (), argvec);
18383   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
18384 }
18385
18386 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
18387
18388 bool
18389 is_auto (const_tree type)
18390 {
18391   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
18392       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
18393     return true;
18394   else
18395     return false;
18396 }
18397
18398 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
18399    appear as a type-specifier for the declaration in question, we don't
18400    have to look through the whole type.  */
18401
18402 tree
18403 type_uses_auto (tree type)
18404 {
18405   enum tree_code code;
18406   if (is_auto (type))
18407     return type;
18408
18409   code = TREE_CODE (type);
18410
18411   if (code == POINTER_TYPE || code == REFERENCE_TYPE
18412       || code == OFFSET_TYPE || code == FUNCTION_TYPE
18413       || code == METHOD_TYPE || code == ARRAY_TYPE)
18414     return type_uses_auto (TREE_TYPE (type));
18415
18416   if (TYPE_PTRMEMFUNC_P (type))
18417     return type_uses_auto (TREE_TYPE (TREE_TYPE
18418                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
18419
18420   return NULL_TREE;
18421 }
18422
18423 /* For a given template T, return the vector of typedefs referenced
18424    in T for which access check is needed at T instantiation time.
18425    T is either  a FUNCTION_DECL or a RECORD_TYPE.
18426    Those typedefs were added to T by the function
18427    append_type_to_template_for_access_check.  */
18428
18429 VEC(qualified_typedef_usage_t,gc)*
18430 get_types_needing_access_check (tree t)
18431 {
18432   tree ti;
18433   VEC(qualified_typedef_usage_t,gc) *result = NULL;
18434
18435   if (!t || t == error_mark_node)
18436     return NULL;
18437
18438   if (!(ti = get_template_info (t)))
18439     return NULL;
18440
18441   if (CLASS_TYPE_P (t)
18442       || TREE_CODE (t) == FUNCTION_DECL)
18443     {
18444       if (!TI_TEMPLATE (ti))
18445         return NULL;
18446
18447       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
18448     }
18449
18450   return result;
18451 }
18452
18453 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
18454    tied to T. That list of typedefs will be access checked at
18455    T instantiation time.
18456    T is either a FUNCTION_DECL or a RECORD_TYPE.
18457    TYPE_DECL is a TYPE_DECL node representing a typedef.
18458    SCOPE is the scope through which TYPE_DECL is accessed.
18459    LOCATION is the location of the usage point of TYPE_DECL.
18460
18461    This function is a subroutine of
18462    append_type_to_template_for_access_check.  */
18463
18464 static void
18465 append_type_to_template_for_access_check_1 (tree t,
18466                                             tree type_decl,
18467                                             tree scope,
18468                                             location_t location)
18469 {
18470   qualified_typedef_usage_t typedef_usage;
18471   tree ti;
18472
18473   if (!t || t == error_mark_node)
18474     return;
18475
18476   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
18477                || CLASS_TYPE_P (t))
18478               && type_decl
18479               && TREE_CODE (type_decl) == TYPE_DECL
18480               && scope);
18481
18482   if (!(ti = get_template_info (t)))
18483     return;
18484
18485   gcc_assert (TI_TEMPLATE (ti));
18486
18487   typedef_usage.typedef_decl = type_decl;
18488   typedef_usage.context = scope;
18489   typedef_usage.locus = location;
18490
18491   VEC_safe_push (qualified_typedef_usage_t, gc,
18492                  TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti),
18493                  &typedef_usage);
18494 }
18495
18496 /* Append TYPE_DECL to the template TEMPL.
18497    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
18498    At TEMPL instanciation time, TYPE_DECL will be checked to see
18499    if it can be accessed through SCOPE.
18500    LOCATION is the location of the usage point of TYPE_DECL.
18501
18502    e.g. consider the following code snippet:
18503
18504      class C
18505      {
18506        typedef int myint;
18507      };
18508
18509      template<class U> struct S
18510      {
18511        C::myint mi; // <-- usage point of the typedef C::myint
18512      };
18513
18514      S<char> s;
18515
18516    At S<char> instantiation time, we need to check the access of C::myint
18517    In other words, we need to check the access of the myint typedef through
18518    the C scope. For that purpose, this function will add the myint typedef
18519    and the scope C through which its being accessed to a list of typedefs
18520    tied to the template S. That list will be walked at template instantiation
18521    time and access check performed on each typedefs it contains.
18522    Note that this particular code snippet should yield an error because
18523    myint is private to C.  */
18524
18525 void
18526 append_type_to_template_for_access_check (tree templ,
18527                                           tree type_decl,
18528                                           tree scope,
18529                                           location_t location)
18530 {
18531   qualified_typedef_usage_t *iter;
18532   int i;
18533
18534   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
18535
18536   /* Make sure we don't append the type to the template twice.  */
18537   for (i = 0;
18538        VEC_iterate (qualified_typedef_usage_t,
18539                     get_types_needing_access_check (templ),
18540                     i, iter);
18541        ++i)
18542     if (iter->typedef_decl == type_decl && scope == iter->context)
18543       return;
18544
18545   append_type_to_template_for_access_check_1 (templ, type_decl,
18546                                               scope, location);
18547 }
18548
18549 /* Set up the hash tables for template instantiations.  */
18550
18551 void
18552 init_template_processing (void)
18553 {
18554   decl_specializations = htab_create_ggc (37,
18555                                           hash_specialization,
18556                                           eq_specializations,
18557                                           ggc_free);
18558   type_specializations = htab_create_ggc (37,
18559                                           hash_specialization,
18560                                           eq_specializations,
18561                                           ggc_free);
18562 }
18563
18564 /* Print stats about the template hash tables for -fstats.  */
18565
18566 void
18567 print_template_statistics (void)
18568 {
18569   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
18570            "%f collisions\n", (long) htab_size (decl_specializations),
18571            (long) htab_elements (decl_specializations),
18572            htab_collisions (decl_specializations));
18573   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
18574            "%f collisions\n", (long) htab_size (type_specializations),
18575            (long) htab_elements (type_specializations),
18576            htab_collisions (type_specializations));
18577 }
18578
18579 #include "gt-cp-pt.h"