OSDN Git Service

PR c++/26261
[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 int push_tinst_level (tree);
123 static void pop_tinst_level (void);
124 static tree reopen_tinst_level (struct tinst_level *);
125 static tree tsubst_initializer_list (tree, tree);
126 static tree get_class_bindings (tree, tree, tree);
127 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
128                                    bool, bool);
129 static void tsubst_enum (tree, tree, tree);
130 static tree add_to_template_args (tree, tree);
131 static tree add_outermost_template_args (tree, tree);
132 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
133 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
134                                              tree);
135 static int type_unification_real (tree, tree, tree, const tree *,
136                                   unsigned int, int, unification_kind_t, int);
137 static void note_template_header (int);
138 static tree convert_nontype_argument_function (tree, tree);
139 static tree convert_nontype_argument (tree, tree);
140 static tree convert_template_argument (tree, tree, tree,
141                                        tsubst_flags_t, int, tree);
142 static int for_each_template_parm (tree, tree_fn_t, void*,
143                                    struct pointer_set_t*, bool);
144 static tree expand_template_argument_pack (tree);
145 static tree build_template_parm_index (int, int, int, tree, tree);
146 static bool inline_needs_template_parms (tree);
147 static void push_inline_template_parms_recursive (tree, int);
148 static tree retrieve_local_specialization (tree);
149 static void register_local_specialization (tree, tree);
150 static hashval_t hash_specialization (const void *p);
151 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
152 static int mark_template_parm (tree, void *);
153 static int template_parm_this_level_p (tree, void *);
154 static tree tsubst_friend_function (tree, tree);
155 static tree tsubst_friend_class (tree, tree);
156 static int can_complete_type_without_circularity (tree);
157 static tree get_bindings (tree, tree, tree, bool);
158 static int template_decl_level (tree);
159 static int check_cv_quals_for_unify (int, tree, tree);
160 static void template_parm_level_and_index (tree, int*, int*);
161 static int unify_pack_expansion (tree, tree, tree, tree, int, bool, bool);
162 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
163 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
164 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
165 static void regenerate_decl_from_template (tree, tree);
166 static tree most_specialized_class (tree, tree);
167 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
168 static tree tsubst_arg_types (tree, tree, tsubst_flags_t, tree);
169 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
170 static bool check_specialization_scope (void);
171 static tree process_partial_specialization (tree);
172 static void set_current_access_from_decl (tree);
173 static tree get_template_base (tree, tree, tree, tree);
174 static tree try_class_unification (tree, tree, tree, tree);
175 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
176                                            tree, tree);
177 static bool template_template_parm_bindings_ok_p (tree, tree);
178 static int template_args_equal (tree, tree);
179 static void tsubst_default_arguments (tree);
180 static tree for_each_template_parm_r (tree *, int *, void *);
181 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
182 static void copy_default_args_to_explicit_spec (tree);
183 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
184 static int eq_local_specializations (const void *, const void *);
185 static bool dependent_template_arg_p (tree);
186 static bool any_template_arguments_need_structural_equality_p (tree);
187 static bool dependent_type_p_r (tree);
188 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree, bool);
189 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
190 static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
191 static tree tsubst_decl (tree, tree, tsubst_flags_t);
192 static void perform_typedefs_access_check (tree tmpl, tree targs);
193 static void append_type_to_template_for_access_check_1 (tree, tree, tree,
194                                                         location_t);
195 static hashval_t iterative_hash_template_arg (tree arg, hashval_t val);
196 static tree listify (tree);
197 static tree listify_autos (tree, tree);
198
199 /* Make the current scope suitable for access checking when we are
200    processing T.  T can be FUNCTION_DECL for instantiated function
201    template, or VAR_DECL for static member variable (need by
202    instantiate_decl).  */
203
204 static void
205 push_access_scope (tree t)
206 {
207   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
208               || TREE_CODE (t) == VAR_DECL);
209
210   if (DECL_FRIEND_CONTEXT (t))
211     push_nested_class (DECL_FRIEND_CONTEXT (t));
212   else if (DECL_CLASS_SCOPE_P (t))
213     push_nested_class (DECL_CONTEXT (t));
214   else
215     push_to_top_level ();
216
217   if (TREE_CODE (t) == FUNCTION_DECL)
218     {
219       saved_access_scope = tree_cons
220         (NULL_TREE, current_function_decl, saved_access_scope);
221       current_function_decl = t;
222     }
223 }
224
225 /* Restore the scope set up by push_access_scope.  T is the node we
226    are processing.  */
227
228 static void
229 pop_access_scope (tree t)
230 {
231   if (TREE_CODE (t) == FUNCTION_DECL)
232     {
233       current_function_decl = TREE_VALUE (saved_access_scope);
234       saved_access_scope = TREE_CHAIN (saved_access_scope);
235     }
236
237   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
238     pop_nested_class ();
239   else
240     pop_from_top_level ();
241 }
242
243 /* Do any processing required when DECL (a member template
244    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
245    to DECL, unless it is a specialization, in which case the DECL
246    itself is returned.  */
247
248 tree
249 finish_member_template_decl (tree decl)
250 {
251   if (decl == error_mark_node)
252     return error_mark_node;
253
254   gcc_assert (DECL_P (decl));
255
256   if (TREE_CODE (decl) == TYPE_DECL)
257     {
258       tree type;
259
260       type = TREE_TYPE (decl);
261       if (type == error_mark_node)
262         return error_mark_node;
263       if (MAYBE_CLASS_TYPE_P (type)
264           && CLASSTYPE_TEMPLATE_INFO (type)
265           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
266         {
267           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
268           check_member_template (tmpl);
269           return tmpl;
270         }
271       return NULL_TREE;
272     }
273   else if (TREE_CODE (decl) == FIELD_DECL)
274     error ("data member %qD cannot be a member template", decl);
275   else if (DECL_TEMPLATE_INFO (decl))
276     {
277       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
278         {
279           check_member_template (DECL_TI_TEMPLATE (decl));
280           return DECL_TI_TEMPLATE (decl);
281         }
282       else
283         return decl;
284     }
285   else
286     error ("invalid member template declaration %qD", decl);
287
288   return error_mark_node;
289 }
290
291 /* Create a template info node.  */
292
293 tree
294 build_template_info (tree template_decl, tree template_args)
295 {
296   tree result = make_node (TEMPLATE_INFO);
297   TI_TEMPLATE (result) = template_decl;
298   TI_ARGS (result) = template_args;
299   return result;
300 }
301
302 /* Return the template info node corresponding to T, whatever T is.  */
303
304 tree
305 get_template_info (const_tree t)
306 {
307   tree tinfo = NULL_TREE;
308
309   if (!t || t == error_mark_node)
310     return NULL;
311
312   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
313     tinfo = DECL_TEMPLATE_INFO (t);
314
315   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
316     t = TREE_TYPE (t);
317
318   if (TAGGED_TYPE_P (t))
319     tinfo = TYPE_TEMPLATE_INFO (t);
320   else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
321     tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
322
323   return tinfo;
324 }
325
326 /* Returns the template nesting level of the indicated class TYPE.
327
328    For example, in:
329      template <class T>
330      struct A
331      {
332        template <class U>
333        struct B {};
334      };
335
336    A<T>::B<U> has depth two, while A<T> has depth one.
337    Both A<T>::B<int> and A<int>::B<U> have depth one, if
338    they are instantiations, not specializations.
339
340    This function is guaranteed to return 0 if passed NULL_TREE so
341    that, for example, `template_class_depth (current_class_type)' is
342    always safe.  */
343
344 int
345 template_class_depth (tree type)
346 {
347   int depth;
348
349   for (depth = 0;
350        type && TREE_CODE (type) != NAMESPACE_DECL;
351        type = (TREE_CODE (type) == FUNCTION_DECL)
352          ? CP_DECL_CONTEXT (type) : TYPE_CONTEXT (type))
353     {
354       tree tinfo = get_template_info (type);
355
356       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
357           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
358         ++depth;
359     }
360
361   return depth;
362 }
363
364 /* Subroutine of maybe_begin_member_template_processing.
365    Returns true if processing DECL needs us to push template parms.  */
366
367 static bool
368 inline_needs_template_parms (tree decl)
369 {
370   if (! DECL_TEMPLATE_INFO (decl))
371     return false;
372
373   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
374           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
375 }
376
377 /* Subroutine of maybe_begin_member_template_processing.
378    Push the template parms in PARMS, starting from LEVELS steps into the
379    chain, and ending at the beginning, since template parms are listed
380    innermost first.  */
381
382 static void
383 push_inline_template_parms_recursive (tree parmlist, int levels)
384 {
385   tree parms = TREE_VALUE (parmlist);
386   int i;
387
388   if (levels > 1)
389     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
390
391   ++processing_template_decl;
392   current_template_parms
393     = tree_cons (size_int (processing_template_decl),
394                  parms, current_template_parms);
395   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
396
397   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
398                NULL);
399   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
400     {
401       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
402
403       if (parm == error_mark_node)
404         continue;
405
406       gcc_assert (DECL_P (parm));
407
408       switch (TREE_CODE (parm))
409         {
410         case TYPE_DECL:
411         case TEMPLATE_DECL:
412           pushdecl (parm);
413           break;
414
415         case PARM_DECL:
416           {
417             /* Make a CONST_DECL as is done in process_template_parm.
418                It is ugly that we recreate this here; the original
419                version built in process_template_parm is no longer
420                available.  */
421             tree decl = build_decl (DECL_SOURCE_LOCATION (parm),
422                                     CONST_DECL, DECL_NAME (parm),
423                                     TREE_TYPE (parm));
424             DECL_ARTIFICIAL (decl) = 1;
425             TREE_CONSTANT (decl) = 1;
426             TREE_READONLY (decl) = 1;
427             DECL_INITIAL (decl) = DECL_INITIAL (parm);
428             SET_DECL_TEMPLATE_PARM_P (decl);
429             pushdecl (decl);
430           }
431           break;
432
433         default:
434           gcc_unreachable ();
435         }
436     }
437 }
438
439 /* Restore the template parameter context for a member template or
440    a friend template defined in a class definition.  */
441
442 void
443 maybe_begin_member_template_processing (tree decl)
444 {
445   tree parms;
446   int levels = 0;
447
448   if (inline_needs_template_parms (decl))
449     {
450       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
451       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
452
453       if (DECL_TEMPLATE_SPECIALIZATION (decl))
454         {
455           --levels;
456           parms = TREE_CHAIN (parms);
457         }
458
459       push_inline_template_parms_recursive (parms, levels);
460     }
461
462   /* Remember how many levels of template parameters we pushed so that
463      we can pop them later.  */
464   VEC_safe_push (int, heap, inline_parm_levels, levels);
465 }
466
467 /* Undo the effects of maybe_begin_member_template_processing.  */
468
469 void
470 maybe_end_member_template_processing (void)
471 {
472   int i;
473   int last;
474
475   if (VEC_length (int, inline_parm_levels) == 0)
476     return;
477
478   last = VEC_pop (int, inline_parm_levels);
479   for (i = 0; i < last; ++i)
480     {
481       --processing_template_decl;
482       current_template_parms = TREE_CHAIN (current_template_parms);
483       poplevel (0, 0, 0);
484     }
485 }
486
487 /* Return a new template argument vector which contains all of ARGS,
488    but has as its innermost set of arguments the EXTRA_ARGS.  */
489
490 static tree
491 add_to_template_args (tree args, tree extra_args)
492 {
493   tree new_args;
494   int extra_depth;
495   int i;
496   int j;
497
498   extra_depth = TMPL_ARGS_DEPTH (extra_args);
499   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
500
501   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
502     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
503
504   for (j = 1; j <= extra_depth; ++j, ++i)
505     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
506
507   return new_args;
508 }
509
510 /* Like add_to_template_args, but only the outermost ARGS are added to
511    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
512    (EXTRA_ARGS) levels are added.  This function is used to combine
513    the template arguments from a partial instantiation with the
514    template arguments used to attain the full instantiation from the
515    partial instantiation.  */
516
517 static tree
518 add_outermost_template_args (tree args, tree extra_args)
519 {
520   tree new_args;
521
522   /* If there are more levels of EXTRA_ARGS than there are ARGS,
523      something very fishy is going on.  */
524   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
525
526   /* If *all* the new arguments will be the EXTRA_ARGS, just return
527      them.  */
528   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
529     return extra_args;
530
531   /* For the moment, we make ARGS look like it contains fewer levels.  */
532   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
533
534   new_args = add_to_template_args (args, extra_args);
535
536   /* Now, we restore ARGS to its full dimensions.  */
537   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
538
539   return new_args;
540 }
541
542 /* Return the N levels of innermost template arguments from the ARGS.  */
543
544 tree
545 get_innermost_template_args (tree args, int n)
546 {
547   tree new_args;
548   int extra_levels;
549   int i;
550
551   gcc_assert (n >= 0);
552
553   /* If N is 1, just return the innermost set of template arguments.  */
554   if (n == 1)
555     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
556
557   /* If we're not removing anything, just return the arguments we were
558      given.  */
559   extra_levels = TMPL_ARGS_DEPTH (args) - n;
560   gcc_assert (extra_levels >= 0);
561   if (extra_levels == 0)
562     return args;
563
564   /* Make a new set of arguments, not containing the outer arguments.  */
565   new_args = make_tree_vec (n);
566   for (i = 1; i <= n; ++i)
567     SET_TMPL_ARGS_LEVEL (new_args, i,
568                          TMPL_ARGS_LEVEL (args, i + extra_levels));
569
570   return new_args;
571 }
572
573 /* The inverse of get_innermost_template_args: Return all but the innermost
574    EXTRA_LEVELS levels of template arguments from the ARGS.  */
575
576 static tree
577 strip_innermost_template_args (tree args, int extra_levels)
578 {
579   tree new_args;
580   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
581   int i;
582
583   gcc_assert (n >= 0);
584
585   /* If N is 1, just return the outermost set of template arguments.  */
586   if (n == 1)
587     return TMPL_ARGS_LEVEL (args, 1);
588
589   /* If we're not removing anything, just return the arguments we were
590      given.  */
591   gcc_assert (extra_levels >= 0);
592   if (extra_levels == 0)
593     return args;
594
595   /* Make a new set of arguments, not containing the inner arguments.  */
596   new_args = make_tree_vec (n);
597   for (i = 1; i <= n; ++i)
598     SET_TMPL_ARGS_LEVEL (new_args, i,
599                          TMPL_ARGS_LEVEL (args, i));
600
601   return new_args;
602 }
603
604 /* We've got a template header coming up; push to a new level for storing
605    the parms.  */
606
607 void
608 begin_template_parm_list (void)
609 {
610   /* We use a non-tag-transparent scope here, which causes pushtag to
611      put tags in this scope, rather than in the enclosing class or
612      namespace scope.  This is the right thing, since we want
613      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
614      global template class, push_template_decl handles putting the
615      TEMPLATE_DECL into top-level scope.  For a nested template class,
616      e.g.:
617
618        template <class T> struct S1 {
619          template <class T> struct S2 {};
620        };
621
622      pushtag contains special code to call pushdecl_with_scope on the
623      TEMPLATE_DECL for S2.  */
624   begin_scope (sk_template_parms, NULL);
625   ++processing_template_decl;
626   ++processing_template_parmlist;
627   note_template_header (0);
628 }
629
630 /* This routine is called when a specialization is declared.  If it is
631    invalid to declare a specialization here, an error is reported and
632    false is returned, otherwise this routine will return true.  */
633
634 static bool
635 check_specialization_scope (void)
636 {
637   tree scope = current_scope ();
638
639   /* [temp.expl.spec]
640
641      An explicit specialization shall be declared in the namespace of
642      which the template is a member, or, for member templates, in the
643      namespace of which the enclosing class or enclosing class
644      template is a member.  An explicit specialization of a member
645      function, member class or static data member of a class template
646      shall be declared in the namespace of which the class template
647      is a member.  */
648   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
649     {
650       error ("explicit specialization in non-namespace scope %qD", scope);
651       return false;
652     }
653
654   /* [temp.expl.spec]
655
656      In an explicit specialization declaration for a member of a class
657      template or a member template that appears in namespace scope,
658      the member template and some of its enclosing class templates may
659      remain unspecialized, except that the declaration shall not
660      explicitly specialize a class member template if its enclosing
661      class templates are not explicitly specialized as well.  */
662   if (current_template_parms)
663     {
664       error ("enclosing class templates are not explicitly specialized");
665       return false;
666     }
667
668   return true;
669 }
670
671 /* We've just seen template <>.  */
672
673 bool
674 begin_specialization (void)
675 {
676   begin_scope (sk_template_spec, NULL);
677   note_template_header (1);
678   return check_specialization_scope ();
679 }
680
681 /* Called at then end of processing a declaration preceded by
682    template<>.  */
683
684 void
685 end_specialization (void)
686 {
687   finish_scope ();
688   reset_specialization ();
689 }
690
691 /* Any template <>'s that we have seen thus far are not referring to a
692    function specialization.  */
693
694 void
695 reset_specialization (void)
696 {
697   processing_specialization = 0;
698   template_header_count = 0;
699 }
700
701 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
702    it was of the form template <>.  */
703
704 static void
705 note_template_header (int specialization)
706 {
707   processing_specialization = specialization;
708   template_header_count++;
709 }
710
711 /* We're beginning an explicit instantiation.  */
712
713 void
714 begin_explicit_instantiation (void)
715 {
716   gcc_assert (!processing_explicit_instantiation);
717   processing_explicit_instantiation = true;
718 }
719
720
721 void
722 end_explicit_instantiation (void)
723 {
724   gcc_assert (processing_explicit_instantiation);
725   processing_explicit_instantiation = false;
726 }
727
728 /* An explicit specialization or partial specialization TMPL is being
729    declared.  Check that the namespace in which the specialization is
730    occurring is permissible.  Returns false iff it is invalid to
731    specialize TMPL in the current namespace.  */
732
733 static bool
734 check_specialization_namespace (tree tmpl)
735 {
736   tree tpl_ns = decl_namespace_context (tmpl);
737
738   /* [tmpl.expl.spec]
739
740      An explicit specialization shall be declared in the namespace of
741      which the template is a member, or, for member templates, in the
742      namespace of which the enclosing class or enclosing class
743      template is a member.  An explicit specialization of a member
744      function, member class or static data member of a class template
745      shall be declared in the namespace of which the class template is
746      a member.  */
747   if (current_scope() != DECL_CONTEXT (tmpl)
748       && !at_namespace_scope_p ())
749     {
750       error ("specialization of %qD must appear at namespace scope", tmpl);
751       return false;
752     }
753   if (is_associated_namespace (current_namespace, tpl_ns))
754     /* Same or super-using namespace.  */
755     return true;
756   else
757     {
758       permerror (input_location, "specialization of %qD in different namespace", tmpl);
759       permerror (input_location, "  from definition of %q+#D", tmpl);
760       return false;
761     }
762 }
763
764 /* SPEC is an explicit instantiation.  Check that it is valid to
765    perform this explicit instantiation in the current namespace.  */
766
767 static void
768 check_explicit_instantiation_namespace (tree spec)
769 {
770   tree ns;
771
772   /* DR 275: An explicit instantiation shall appear in an enclosing
773      namespace of its template.  */
774   ns = decl_namespace_context (spec);
775   if (!is_ancestor (current_namespace, ns))
776     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
777                "(which does not enclose namespace %qD)",
778                spec, current_namespace, ns);
779 }
780
781 /* The TYPE is being declared.  If it is a template type, that means it
782    is a partial specialization.  Do appropriate error-checking.  */
783
784 tree
785 maybe_process_partial_specialization (tree type)
786 {
787   tree context;
788
789   if (type == error_mark_node)
790     return error_mark_node;
791
792   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
793     {
794       error ("name of class shadows template template parameter %qD",
795              TYPE_NAME (type));
796       return error_mark_node;
797     }
798
799   context = TYPE_CONTEXT (type);
800
801   if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
802     {
803       /* This is for ordinary explicit specialization and partial
804          specialization of a template class such as:
805
806            template <> class C<int>;
807
808          or:
809
810            template <class T> class C<T*>;
811
812          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
813
814       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
815           && !COMPLETE_TYPE_P (type))
816         {
817           check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
818           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
819           if (processing_template_decl)
820             {
821               if (push_template_decl (TYPE_MAIN_DECL (type))
822                   == error_mark_node)
823                 return error_mark_node;
824             }
825         }
826       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
827         error ("specialization of %qT after instantiation", type);
828     }
829   else if (CLASS_TYPE_P (type)
830            && !CLASSTYPE_USE_TEMPLATE (type)
831            && CLASSTYPE_TEMPLATE_INFO (type)
832            && context && CLASS_TYPE_P (context)
833            && CLASSTYPE_TEMPLATE_INFO (context))
834     {
835       /* This is for an explicit specialization of member class
836          template according to [temp.expl.spec/18]:
837
838            template <> template <class U> class C<int>::D;
839
840          The context `C<int>' must be an implicit instantiation.
841          Otherwise this is just a member class template declared
842          earlier like:
843
844            template <> class C<int> { template <class U> class D; };
845            template <> template <class U> class C<int>::D;
846
847          In the first case, `C<int>::D' is a specialization of `C<T>::D'
848          while in the second case, `C<int>::D' is a primary template
849          and `C<T>::D' may not exist.  */
850
851       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
852           && !COMPLETE_TYPE_P (type))
853         {
854           tree t;
855           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
856
857           if (current_namespace
858               != decl_namespace_context (tmpl))
859             {
860               permerror (input_location, "specializing %q#T in different namespace", type);
861               permerror (input_location, "  from definition of %q+#D", tmpl);
862             }
863
864           /* Check for invalid specialization after instantiation:
865
866                template <> template <> class C<int>::D<int>;
867                template <> template <class U> class C<int>::D;  */
868
869           for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
870                t; t = TREE_CHAIN (t))
871             {
872               tree inst = TREE_VALUE (t);
873               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst))
874                 {
875                   /* We already have a full specialization of this partial
876                      instantiation.  Reassign it to the new member
877                      specialization template.  */
878                   spec_entry elt;
879                   spec_entry **slot;
880
881                   elt.tmpl = most_general_template (tmpl);
882                   elt.args = CLASSTYPE_TI_ARGS (inst);
883                   elt.spec = inst;
884
885                   htab_remove_elt (type_specializations, &elt);
886
887                   elt.tmpl = tmpl;
888                   elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
889
890                   slot = (spec_entry **)
891                     htab_find_slot (type_specializations, &elt, INSERT);
892                   *slot = GGC_NEW (spec_entry);
893                   **slot = elt;
894                 }
895               else if (COMPLETE_TYPE_P (inst) || TYPE_BEING_DEFINED (inst))
896                 /* But if we've had an implicit instantiation, that's a
897                    problem ([temp.expl.spec]/6).  */
898                 error ("specialization %qT after instantiation %qT",
899                        type, inst);
900             }
901
902           /* Mark TYPE as a specialization.  And as a result, we only
903              have one level of template argument for the innermost
904              class template.  */
905           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
906           CLASSTYPE_TI_ARGS (type)
907             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
908         }
909     }
910   else if (processing_specialization)
911     {
912       error ("explicit specialization of non-template %qT", type);
913       return error_mark_node;
914     }
915
916   return type;
917 }
918
919 /* Returns nonzero if we can optimize the retrieval of specializations
920    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
921    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
922
923 static inline bool
924 optimize_specialization_lookup_p (tree tmpl)
925 {
926   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
927           && DECL_CLASS_SCOPE_P (tmpl)
928           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
929              parameter.  */
930           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
931           /* The optimized lookup depends on the fact that the
932              template arguments for the member function template apply
933              purely to the containing class, which is not true if the
934              containing class is an explicit or partial
935              specialization.  */
936           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
937           && !DECL_MEMBER_TEMPLATE_P (tmpl)
938           && !DECL_CONV_FN_P (tmpl)
939           /* It is possible to have a template that is not a member
940              template and is not a member of a template class:
941
942              template <typename T>
943              struct S { friend A::f(); };
944
945              Here, the friend function is a template, but the context does
946              not have template information.  The optimized lookup relies
947              on having ARGS be the template arguments for both the class
948              and the function template.  */
949           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
950 }
951
952 /* Retrieve the specialization (in the sense of [temp.spec] - a
953    specialization is either an instantiation or an explicit
954    specialization) of TMPL for the given template ARGS.  If there is
955    no such specialization, return NULL_TREE.  The ARGS are a vector of
956    arguments, or a vector of vectors of arguments, in the case of
957    templates with more than one level of parameters.
958
959    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
960    then we search for a partial specialization matching ARGS.  This
961    parameter is ignored if TMPL is not a class template.  */
962
963 static tree
964 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
965 {
966   if (args == error_mark_node)
967     return NULL_TREE;
968
969   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
970
971   /* There should be as many levels of arguments as there are
972      levels of parameters.  */
973   gcc_assert (TMPL_ARGS_DEPTH (args)
974               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
975
976   if (optimize_specialization_lookup_p (tmpl))
977     {
978       tree class_template;
979       tree class_specialization;
980       VEC(tree,gc) *methods;
981       tree fns;
982       int idx;
983
984       /* The template arguments actually apply to the containing
985          class.  Find the class specialization with those
986          arguments.  */
987       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
988       class_specialization
989         = retrieve_specialization (class_template, args, 0);
990       if (!class_specialization)
991         return NULL_TREE;
992       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
993          for the specialization.  */
994       idx = class_method_index_for_fn (class_specialization, tmpl);
995       if (idx == -1)
996         return NULL_TREE;
997       /* Iterate through the methods with the indicated name, looking
998          for the one that has an instance of TMPL.  */
999       methods = CLASSTYPE_METHOD_VEC (class_specialization);
1000       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
1001         {
1002           tree fn = OVL_CURRENT (fns);
1003           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl
1004               /* using-declarations can add base methods to the method vec,
1005                  and we don't want those here.  */
1006               && DECL_CONTEXT (fn) == class_specialization)
1007             return fn;
1008         }
1009       return NULL_TREE;
1010     }
1011   else
1012     {
1013       spec_entry *found;
1014       spec_entry elt;
1015       htab_t specializations;
1016
1017       elt.tmpl = tmpl;
1018       elt.args = args;
1019       elt.spec = NULL_TREE;
1020
1021       if (DECL_CLASS_TEMPLATE_P (tmpl))
1022         specializations = type_specializations;
1023       else
1024         specializations = decl_specializations;
1025
1026       if (hash == 0)
1027         hash = hash_specialization (&elt);
1028       found = (spec_entry *) htab_find_with_hash (specializations, &elt, hash);
1029       if (found)
1030         return found->spec;
1031     }
1032
1033   return NULL_TREE;
1034 }
1035
1036 /* Like retrieve_specialization, but for local declarations.  */
1037
1038 static tree
1039 retrieve_local_specialization (tree tmpl)
1040 {
1041   tree spec;
1042
1043   if (local_specializations == NULL)
1044     return NULL_TREE;
1045
1046   spec = (tree) htab_find_with_hash (local_specializations, tmpl,
1047                                      htab_hash_pointer (tmpl));
1048   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
1049 }
1050
1051 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1052
1053 int
1054 is_specialization_of (tree decl, tree tmpl)
1055 {
1056   tree t;
1057
1058   if (TREE_CODE (decl) == FUNCTION_DECL)
1059     {
1060       for (t = decl;
1061            t != NULL_TREE;
1062            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1063         if (t == tmpl)
1064           return 1;
1065     }
1066   else
1067     {
1068       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1069
1070       for (t = TREE_TYPE (decl);
1071            t != NULL_TREE;
1072            t = CLASSTYPE_USE_TEMPLATE (t)
1073              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1074         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1075           return 1;
1076     }
1077
1078   return 0;
1079 }
1080
1081 /* Returns nonzero iff DECL is a specialization of friend declaration
1082    FRIEND_DECL according to [temp.friend].  */
1083
1084 bool
1085 is_specialization_of_friend (tree decl, tree friend_decl)
1086 {
1087   bool need_template = true;
1088   int template_depth;
1089
1090   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1091               || TREE_CODE (decl) == TYPE_DECL);
1092
1093   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1094      of a template class, we want to check if DECL is a specialization
1095      if this.  */
1096   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1097       && DECL_TEMPLATE_INFO (friend_decl)
1098       && !DECL_USE_TEMPLATE (friend_decl))
1099     {
1100       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1101       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1102       need_template = false;
1103     }
1104   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1105            && !PRIMARY_TEMPLATE_P (friend_decl))
1106     need_template = false;
1107
1108   /* There is nothing to do if this is not a template friend.  */
1109   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1110     return false;
1111
1112   if (is_specialization_of (decl, friend_decl))
1113     return true;
1114
1115   /* [temp.friend/6]
1116      A member of a class template may be declared to be a friend of a
1117      non-template class.  In this case, the corresponding member of
1118      every specialization of the class template is a friend of the
1119      class granting friendship.
1120
1121      For example, given a template friend declaration
1122
1123        template <class T> friend void A<T>::f();
1124
1125      the member function below is considered a friend
1126
1127        template <> struct A<int> {
1128          void f();
1129        };
1130
1131      For this type of template friend, TEMPLATE_DEPTH below will be
1132      nonzero.  To determine if DECL is a friend of FRIEND, we first
1133      check if the enclosing class is a specialization of another.  */
1134
1135   template_depth = template_class_depth (DECL_CONTEXT (friend_decl));
1136   if (template_depth
1137       && DECL_CLASS_SCOPE_P (decl)
1138       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1139                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1140     {
1141       /* Next, we check the members themselves.  In order to handle
1142          a few tricky cases, such as when FRIEND_DECL's are
1143
1144            template <class T> friend void A<T>::g(T t);
1145            template <class T> template <T t> friend void A<T>::h();
1146
1147          and DECL's are
1148
1149            void A<int>::g(int);
1150            template <int> void A<int>::h();
1151
1152          we need to figure out ARGS, the template arguments from
1153          the context of DECL.  This is required for template substitution
1154          of `T' in the function parameter of `g' and template parameter
1155          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1156
1157       tree context = DECL_CONTEXT (decl);
1158       tree args = NULL_TREE;
1159       int current_depth = 0;
1160
1161       while (current_depth < template_depth)
1162         {
1163           if (CLASSTYPE_TEMPLATE_INFO (context))
1164             {
1165               if (current_depth == 0)
1166                 args = TYPE_TI_ARGS (context);
1167               else
1168                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1169               current_depth++;
1170             }
1171           context = TYPE_CONTEXT (context);
1172         }
1173
1174       if (TREE_CODE (decl) == FUNCTION_DECL)
1175         {
1176           bool is_template;
1177           tree friend_type;
1178           tree decl_type;
1179           tree friend_args_type;
1180           tree decl_args_type;
1181
1182           /* Make sure that both DECL and FRIEND_DECL are templates or
1183              non-templates.  */
1184           is_template = DECL_TEMPLATE_INFO (decl)
1185                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1186           if (need_template ^ is_template)
1187             return false;
1188           else if (is_template)
1189             {
1190               /* If both are templates, check template parameter list.  */
1191               tree friend_parms
1192                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1193                                          args, tf_none);
1194               if (!comp_template_parms
1195                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1196                       friend_parms))
1197                 return false;
1198
1199               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1200             }
1201           else
1202             decl_type = TREE_TYPE (decl);
1203
1204           friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1205                                               tf_none, NULL_TREE);
1206           if (friend_type == error_mark_node)
1207             return false;
1208
1209           /* Check if return types match.  */
1210           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1211             return false;
1212
1213           /* Check if function parameter types match, ignoring the
1214              `this' parameter.  */
1215           friend_args_type = TYPE_ARG_TYPES (friend_type);
1216           decl_args_type = TYPE_ARG_TYPES (decl_type);
1217           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1218             friend_args_type = TREE_CHAIN (friend_args_type);
1219           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1220             decl_args_type = TREE_CHAIN (decl_args_type);
1221
1222           return compparms (decl_args_type, friend_args_type);
1223         }
1224       else
1225         {
1226           /* DECL is a TYPE_DECL */
1227           bool is_template;
1228           tree decl_type = TREE_TYPE (decl);
1229
1230           /* Make sure that both DECL and FRIEND_DECL are templates or
1231              non-templates.  */
1232           is_template
1233             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1234               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1235
1236           if (need_template ^ is_template)
1237             return false;
1238           else if (is_template)
1239             {
1240               tree friend_parms;
1241               /* If both are templates, check the name of the two
1242                  TEMPLATE_DECL's first because is_friend didn't.  */
1243               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1244                   != DECL_NAME (friend_decl))
1245                 return false;
1246
1247               /* Now check template parameter list.  */
1248               friend_parms
1249                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1250                                          args, tf_none);
1251               return comp_template_parms
1252                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1253                  friend_parms);
1254             }
1255           else
1256             return (DECL_NAME (decl)
1257                     == DECL_NAME (friend_decl));
1258         }
1259     }
1260   return false;
1261 }
1262
1263 /* Register the specialization SPEC as a specialization of TMPL with
1264    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1265    is actually just a friend declaration.  Returns SPEC, or an
1266    equivalent prior declaration, if available.  */
1267
1268 static tree
1269 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1270                          hashval_t hash)
1271 {
1272   tree fn;
1273   spec_entry **slot = NULL;
1274   spec_entry elt;
1275
1276   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec));
1277
1278   if (TREE_CODE (spec) == FUNCTION_DECL
1279       && uses_template_parms (DECL_TI_ARGS (spec)))
1280     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1281        register it; we want the corresponding TEMPLATE_DECL instead.
1282        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1283        the more obvious `uses_template_parms (spec)' to avoid problems
1284        with default function arguments.  In particular, given
1285        something like this:
1286
1287           template <class T> void f(T t1, T t = T())
1288
1289        the default argument expression is not substituted for in an
1290        instantiation unless and until it is actually needed.  */
1291     return spec;
1292
1293   if (optimize_specialization_lookup_p (tmpl))
1294     /* We don't put these specializations in the hash table, but we might
1295        want to give an error about a mismatch.  */
1296     fn = retrieve_specialization (tmpl, args, 0);
1297   else
1298     {
1299       elt.tmpl = tmpl;
1300       elt.args = args;
1301       elt.spec = spec;
1302
1303       if (hash == 0)
1304         hash = hash_specialization (&elt);
1305
1306       slot = (spec_entry **)
1307         htab_find_slot_with_hash (decl_specializations, &elt, hash, INSERT);
1308       if (*slot)
1309         fn = (*slot)->spec;
1310       else
1311         fn = NULL_TREE;
1312     }
1313
1314   /* We can sometimes try to re-register a specialization that we've
1315      already got.  In particular, regenerate_decl_from_template calls
1316      duplicate_decls which will update the specialization list.  But,
1317      we'll still get called again here anyhow.  It's more convenient
1318      to simply allow this than to try to prevent it.  */
1319   if (fn == spec)
1320     return spec;
1321   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1322     {
1323       if (DECL_TEMPLATE_INSTANTIATION (fn))
1324         {
1325           if (DECL_ODR_USED (fn)
1326               || DECL_EXPLICIT_INSTANTIATION (fn))
1327             {
1328               error ("specialization of %qD after instantiation",
1329                      fn);
1330               return error_mark_node;
1331             }
1332           else
1333             {
1334               tree clone;
1335               /* This situation should occur only if the first
1336                  specialization is an implicit instantiation, the
1337                  second is an explicit specialization, and the
1338                  implicit instantiation has not yet been used.  That
1339                  situation can occur if we have implicitly
1340                  instantiated a member function and then specialized
1341                  it later.
1342
1343                  We can also wind up here if a friend declaration that
1344                  looked like an instantiation turns out to be a
1345                  specialization:
1346
1347                    template <class T> void foo(T);
1348                    class S { friend void foo<>(int) };
1349                    template <> void foo(int);
1350
1351                  We transform the existing DECL in place so that any
1352                  pointers to it become pointers to the updated
1353                  declaration.
1354
1355                  If there was a definition for the template, but not
1356                  for the specialization, we want this to look as if
1357                  there were no definition, and vice versa.  */
1358               DECL_INITIAL (fn) = NULL_TREE;
1359               duplicate_decls (spec, fn, is_friend);
1360               /* The call to duplicate_decls will have applied
1361                  [temp.expl.spec]:
1362
1363                    An explicit specialization of a function template
1364                    is inline only if it is explicitly declared to be,
1365                    and independently of whether its function template
1366                    is.
1367
1368                 to the primary function; now copy the inline bits to
1369                 the various clones.  */
1370               FOR_EACH_CLONE (clone, fn)
1371                 {
1372                   DECL_DECLARED_INLINE_P (clone)
1373                     = DECL_DECLARED_INLINE_P (fn);
1374                   DECL_SOURCE_LOCATION (clone)
1375                     = DECL_SOURCE_LOCATION (fn);
1376                 }
1377               check_specialization_namespace (fn);
1378
1379               return fn;
1380             }
1381         }
1382       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1383         {
1384           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1385             /* Dup decl failed, but this is a new definition. Set the
1386                line number so any errors match this new
1387                definition.  */
1388             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1389
1390           return fn;
1391         }
1392     }
1393   else if (fn)
1394     return duplicate_decls (spec, fn, is_friend);
1395
1396   /* A specialization must be declared in the same namespace as the
1397      template it is specializing.  */
1398   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1399       && !check_specialization_namespace (tmpl))
1400     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1401
1402   if (!optimize_specialization_lookup_p (tmpl))
1403     {
1404       gcc_assert (tmpl && args && spec);
1405       *slot = GGC_NEW (spec_entry);
1406       **slot = elt;
1407       if (TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1408           && PRIMARY_TEMPLATE_P (tmpl)
1409           && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1410         /* TMPL is a forward declaration of a template function; keep a list
1411            of all specializations in case we need to reassign them to a friend
1412            template later in tsubst_friend_function.  */
1413         DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1414           = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1415     }
1416
1417   return spec;
1418 }
1419
1420 /* Returns true iff two spec_entry nodes are equivalent.  Only compares the
1421    TMPL and ARGS members, ignores SPEC.  */
1422
1423 static int
1424 eq_specializations (const void *p1, const void *p2)
1425 {
1426   const spec_entry *e1 = (const spec_entry *)p1;
1427   const spec_entry *e2 = (const spec_entry *)p2;
1428
1429   return (e1->tmpl == e2->tmpl
1430           && comp_template_args (e1->args, e2->args));
1431 }
1432
1433 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1434
1435 static hashval_t
1436 hash_tmpl_and_args (tree tmpl, tree args)
1437 {
1438   hashval_t val = DECL_UID (tmpl);
1439   return iterative_hash_template_arg (args, val);
1440 }
1441
1442 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1443    ignoring SPEC.  */
1444
1445 static hashval_t
1446 hash_specialization (const void *p)
1447 {
1448   const spec_entry *e = (const spec_entry *)p;
1449   return hash_tmpl_and_args (e->tmpl, e->args);
1450 }
1451
1452 /* Recursively calculate a hash value for a template argument ARG, for use
1453    in the hash tables of template specializations.  */
1454
1455 static hashval_t
1456 iterative_hash_template_arg (tree arg, hashval_t val)
1457 {
1458   unsigned HOST_WIDE_INT i;
1459   enum tree_code code;
1460   char tclass;
1461
1462   if (arg == NULL_TREE)
1463     return iterative_hash_object (arg, val);
1464
1465   if (!TYPE_P (arg))
1466     STRIP_NOPS (arg);
1467
1468   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
1469     /* We can get one of these when re-hashing a previous entry in the middle
1470        of substituting into a pack expansion.  Just look through it.  */
1471     arg = ARGUMENT_PACK_SELECT_FROM_PACK (arg);
1472
1473   code = TREE_CODE (arg);
1474   tclass = TREE_CODE_CLASS (code);
1475
1476   val = iterative_hash_object (code, val);
1477
1478   switch (code)
1479     {
1480     case ERROR_MARK:
1481       return val;
1482
1483     case IDENTIFIER_NODE:
1484       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1485
1486     case TREE_VEC:
1487       {
1488         int i, len = TREE_VEC_LENGTH (arg);
1489         for (i = 0; i < len; ++i)
1490           val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1491         return val;
1492       }
1493
1494     case TYPE_PACK_EXPANSION:
1495     case EXPR_PACK_EXPANSION:
1496       return iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1497
1498     case TYPE_ARGUMENT_PACK:
1499     case NONTYPE_ARGUMENT_PACK:
1500       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1501
1502     case TREE_LIST:
1503       for (; arg; arg = TREE_CHAIN (arg))
1504         val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1505       return val;
1506
1507     case OVERLOAD:
1508       for (; arg; arg = OVL_CHAIN (arg))
1509         val = iterative_hash_template_arg (OVL_FUNCTION (arg), val);
1510       return val;
1511
1512     case CONSTRUCTOR:
1513       {
1514         tree field, value;
1515         FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1516           {
1517             val = iterative_hash_template_arg (field, val);
1518             val = iterative_hash_template_arg (value, val);
1519           }
1520         return val;
1521       }
1522
1523     case PARM_DECL:
1524       if (!DECL_ARTIFICIAL (arg))
1525         val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1526       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1527
1528     case TARGET_EXPR:
1529       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1530
1531     case PTRMEM_CST:
1532       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1533       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1534
1535     case TEMPLATE_PARM_INDEX:
1536       val = iterative_hash_template_arg
1537         (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1538       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1539       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1540
1541     case TRAIT_EXPR:
1542       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1543       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1544       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1545
1546     case BASELINK:
1547       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1548                                          val);
1549       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1550                                           val);
1551
1552     case MODOP_EXPR:
1553       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1554       code = TREE_CODE (TREE_OPERAND (arg, 1));
1555       val = iterative_hash_object (code, val);
1556       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1557
1558     case ARRAY_TYPE:
1559       /* layout_type sets structural equality for arrays of
1560          incomplete type, so we can't rely on the canonical type
1561          for hashing.  */
1562       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1563       return iterative_hash_template_arg (TYPE_DOMAIN (arg), val);
1564
1565     default:
1566       switch (tclass)
1567         {
1568         case tcc_type:
1569           if (TYPE_CANONICAL (arg))
1570             return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1571                                           val);
1572           else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1573             return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1574           /* Otherwise just compare the types during lookup.  */
1575           return val;
1576
1577         case tcc_declaration:
1578         case tcc_constant:
1579           return iterative_hash_expr (arg, val);
1580
1581         default:
1582           gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1583           {
1584             unsigned n = TREE_OPERAND_LENGTH (arg);
1585             for (i = 0; i < n; ++i)
1586               val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1587             return val;
1588           }
1589         }
1590     }
1591   gcc_unreachable ();
1592   return 0;
1593 }
1594
1595 /* Unregister the specialization SPEC as a specialization of TMPL.
1596    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1597    if the SPEC was listed as a specialization of TMPL.
1598
1599    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1600
1601 bool
1602 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1603 {
1604   spec_entry **slot;
1605   spec_entry elt;
1606
1607   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1608   elt.args = TI_ARGS (tinfo);
1609   elt.spec = NULL_TREE;
1610
1611   slot = (spec_entry **) htab_find_slot (decl_specializations, &elt, INSERT);
1612   if (*slot)
1613     {
1614       gcc_assert ((*slot)->spec == spec || (*slot)->spec == new_spec);
1615       gcc_assert (new_spec != NULL_TREE);
1616       (*slot)->spec = new_spec;
1617       return 1;
1618     }
1619
1620   return 0;
1621 }
1622
1623 /* Compare an entry in the local specializations hash table P1 (which
1624    is really a pointer to a TREE_LIST) with P2 (which is really a
1625    DECL).  */
1626
1627 static int
1628 eq_local_specializations (const void *p1, const void *p2)
1629 {
1630   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1631 }
1632
1633 /* Hash P1, an entry in the local specializations table.  */
1634
1635 static hashval_t
1636 hash_local_specialization (const void* p1)
1637 {
1638   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1639 }
1640
1641 /* Like register_specialization, but for local declarations.  We are
1642    registering SPEC, an instantiation of TMPL.  */
1643
1644 static void
1645 register_local_specialization (tree spec, tree tmpl)
1646 {
1647   void **slot;
1648
1649   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1650                                    htab_hash_pointer (tmpl), INSERT);
1651   *slot = build_tree_list (spec, tmpl);
1652 }
1653
1654 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1655    specialized class.  */
1656
1657 bool
1658 explicit_class_specialization_p (tree type)
1659 {
1660   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1661     return false;
1662   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1663 }
1664
1665 /* Print the list of functions at FNS, going through all the overloads
1666    for each element of the list.  Alternatively, FNS can not be a
1667    TREE_LIST, in which case it will be printed together with all the
1668    overloads.
1669
1670    MORE and *STR should respectively be FALSE and NULL when the function
1671    is called from the outside.  They are used internally on recursive
1672    calls.  print_candidates manages the two parameters and leaves NULL
1673    in *STR when it ends.  */
1674
1675 static void
1676 print_candidates_1 (tree fns, bool more, const char **str)
1677 {
1678   tree fn, fn2;
1679   char *spaces = NULL;
1680
1681   for (fn = fns; fn; fn = OVL_NEXT (fn))
1682     if (TREE_CODE (fn) == TREE_LIST)
1683       {
1684         gcc_assert (!OVL_NEXT (fn) && !is_overloaded_fn (fn));
1685         for (fn2 = fn; fn2 != NULL_TREE; fn2 = TREE_CHAIN (fn2))
1686           print_candidates_1 (TREE_VALUE (fn2),
1687                               TREE_CHAIN (fn2) || more, str);
1688       }
1689     else
1690       {
1691         if (!*str)
1692           {
1693             /* Pick the prefix string.  */
1694             if (!more && !OVL_NEXT (fns))
1695               {
1696                 error ("candidate is: %+#D", OVL_CURRENT (fn));
1697                 continue;
1698               }
1699
1700             *str = _("candidates are:");
1701             spaces = get_spaces (*str);
1702           }
1703         error ("%s %+#D", *str, OVL_CURRENT (fn));
1704         *str = spaces ? spaces : *str;
1705       }
1706
1707   if (!more)
1708     {
1709       free (spaces);
1710       *str = NULL;
1711     }
1712 }
1713
1714 /* Print the list of candidate FNS in an error message.  */
1715
1716 void
1717 print_candidates (tree fns)
1718 {
1719   const char *str = NULL;
1720   print_candidates_1 (fns, false, &str);
1721   gcc_assert (str == NULL);
1722 }
1723
1724 /* Returns the template (one of the functions given by TEMPLATE_ID)
1725    which can be specialized to match the indicated DECL with the
1726    explicit template args given in TEMPLATE_ID.  The DECL may be
1727    NULL_TREE if none is available.  In that case, the functions in
1728    TEMPLATE_ID are non-members.
1729
1730    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1731    specialization of a member template.
1732
1733    The TEMPLATE_COUNT is the number of references to qualifying
1734    template classes that appeared in the name of the function. See
1735    check_explicit_specialization for a more accurate description.
1736
1737    TSK indicates what kind of template declaration (if any) is being
1738    declared.  TSK_TEMPLATE indicates that the declaration given by
1739    DECL, though a FUNCTION_DECL, has template parameters, and is
1740    therefore a template function.
1741
1742    The template args (those explicitly specified and those deduced)
1743    are output in a newly created vector *TARGS_OUT.
1744
1745    If it is impossible to determine the result, an error message is
1746    issued.  The error_mark_node is returned to indicate failure.  */
1747
1748 static tree
1749 determine_specialization (tree template_id,
1750                           tree decl,
1751                           tree* targs_out,
1752                           int need_member_template,
1753                           int template_count,
1754                           tmpl_spec_kind tsk)
1755 {
1756   tree fns;
1757   tree targs;
1758   tree explicit_targs;
1759   tree candidates = NULL_TREE;
1760   /* A TREE_LIST of templates of which DECL may be a specialization.
1761      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1762      corresponding TREE_PURPOSE is the set of template arguments that,
1763      when used to instantiate the template, would produce a function
1764      with the signature of DECL.  */
1765   tree templates = NULL_TREE;
1766   int header_count;
1767   struct cp_binding_level *b;
1768
1769   *targs_out = NULL_TREE;
1770
1771   if (template_id == error_mark_node || decl == error_mark_node)
1772     return error_mark_node;
1773
1774   fns = TREE_OPERAND (template_id, 0);
1775   explicit_targs = TREE_OPERAND (template_id, 1);
1776
1777   if (fns == error_mark_node)
1778     return error_mark_node;
1779
1780   /* Check for baselinks.  */
1781   if (BASELINK_P (fns))
1782     fns = BASELINK_FUNCTIONS (fns);
1783
1784   if (!is_overloaded_fn (fns))
1785     {
1786       error ("%qD is not a function template", fns);
1787       return error_mark_node;
1788     }
1789
1790   /* Count the number of template headers specified for this
1791      specialization.  */
1792   header_count = 0;
1793   for (b = current_binding_level;
1794        b->kind == sk_template_parms;
1795        b = b->level_chain)
1796     ++header_count;
1797
1798   for (; fns; fns = OVL_NEXT (fns))
1799     {
1800       tree fn = OVL_CURRENT (fns);
1801
1802       if (TREE_CODE (fn) == TEMPLATE_DECL)
1803         {
1804           tree decl_arg_types;
1805           tree fn_arg_types;
1806
1807           /* In case of explicit specialization, we need to check if
1808              the number of template headers appearing in the specialization
1809              is correct. This is usually done in check_explicit_specialization,
1810              but the check done there cannot be exhaustive when specializing
1811              member functions. Consider the following code:
1812
1813              template <> void A<int>::f(int);
1814              template <> template <> void A<int>::f(int);
1815
1816              Assuming that A<int> is not itself an explicit specialization
1817              already, the first line specializes "f" which is a non-template
1818              member function, whilst the second line specializes "f" which
1819              is a template member function. So both lines are syntactically
1820              correct, and check_explicit_specialization does not reject
1821              them.
1822
1823              Here, we can do better, as we are matching the specialization
1824              against the declarations. We count the number of template
1825              headers, and we check if they match TEMPLATE_COUNT + 1
1826              (TEMPLATE_COUNT is the number of qualifying template classes,
1827              plus there must be another header for the member template
1828              itself).
1829
1830              Notice that if header_count is zero, this is not a
1831              specialization but rather a template instantiation, so there
1832              is no check we can perform here.  */
1833           if (header_count && header_count != template_count + 1)
1834             continue;
1835
1836           /* Check that the number of template arguments at the
1837              innermost level for DECL is the same as for FN.  */
1838           if (current_binding_level->kind == sk_template_parms
1839               && !current_binding_level->explicit_spec_p
1840               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1841                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1842                                       (current_template_parms))))
1843             continue;
1844
1845           /* DECL might be a specialization of FN.  */
1846           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1847           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1848
1849           /* For a non-static member function, we need to make sure
1850              that the const qualification is the same.  Since
1851              get_bindings does not try to merge the "this" parameter,
1852              we must do the comparison explicitly.  */
1853           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1854               && !same_type_p (TREE_VALUE (fn_arg_types),
1855                                TREE_VALUE (decl_arg_types)))
1856             continue;
1857
1858           /* Skip the "this" parameter and, for constructors of
1859              classes with virtual bases, the VTT parameter.  A
1860              full specialization of a constructor will have a VTT
1861              parameter, but a template never will.  */ 
1862           decl_arg_types 
1863             = skip_artificial_parms_for (decl, decl_arg_types);
1864           fn_arg_types 
1865             = skip_artificial_parms_for (fn, fn_arg_types);
1866
1867           /* Check that the number of function parameters matches.
1868              For example,
1869                template <class T> void f(int i = 0);
1870                template <> void f<int>();
1871              The specialization f<int> is invalid but is not caught
1872              by get_bindings below.  */
1873           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1874             continue;
1875
1876           /* Function templates cannot be specializations; there are
1877              no partial specializations of functions.  Therefore, if
1878              the type of DECL does not match FN, there is no
1879              match.  */
1880           if (tsk == tsk_template)
1881             {
1882               if (compparms (fn_arg_types, decl_arg_types))
1883                 candidates = tree_cons (NULL_TREE, fn, candidates);
1884               continue;
1885             }
1886
1887           /* See whether this function might be a specialization of this
1888              template.  */
1889           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1890
1891           if (!targs)
1892             /* We cannot deduce template arguments that when used to
1893                specialize TMPL will produce DECL.  */
1894             continue;
1895
1896           /* Save this template, and the arguments deduced.  */
1897           templates = tree_cons (targs, fn, templates);
1898         }
1899       else if (need_member_template)
1900         /* FN is an ordinary member function, and we need a
1901            specialization of a member template.  */
1902         ;
1903       else if (TREE_CODE (fn) != FUNCTION_DECL)
1904         /* We can get IDENTIFIER_NODEs here in certain erroneous
1905            cases.  */
1906         ;
1907       else if (!DECL_FUNCTION_MEMBER_P (fn))
1908         /* This is just an ordinary non-member function.  Nothing can
1909            be a specialization of that.  */
1910         ;
1911       else if (DECL_ARTIFICIAL (fn))
1912         /* Cannot specialize functions that are created implicitly.  */
1913         ;
1914       else
1915         {
1916           tree decl_arg_types;
1917
1918           /* This is an ordinary member function.  However, since
1919              we're here, we can assume it's enclosing class is a
1920              template class.  For example,
1921
1922                template <typename T> struct S { void f(); };
1923                template <> void S<int>::f() {}
1924
1925              Here, S<int>::f is a non-template, but S<int> is a
1926              template class.  If FN has the same type as DECL, we
1927              might be in business.  */
1928
1929           if (!DECL_TEMPLATE_INFO (fn))
1930             /* Its enclosing class is an explicit specialization
1931                of a template class.  This is not a candidate.  */
1932             continue;
1933
1934           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1935                             TREE_TYPE (TREE_TYPE (fn))))
1936             /* The return types differ.  */
1937             continue;
1938
1939           /* Adjust the type of DECL in case FN is a static member.  */
1940           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1941           if (DECL_STATIC_FUNCTION_P (fn)
1942               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1943             decl_arg_types = TREE_CHAIN (decl_arg_types);
1944
1945           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1946                          decl_arg_types))
1947             /* They match!  */
1948             candidates = tree_cons (NULL_TREE, fn, candidates);
1949         }
1950     }
1951
1952   if (templates && TREE_CHAIN (templates))
1953     {
1954       /* We have:
1955
1956            [temp.expl.spec]
1957
1958            It is possible for a specialization with a given function
1959            signature to be instantiated from more than one function
1960            template.  In such cases, explicit specification of the
1961            template arguments must be used to uniquely identify the
1962            function template specialization being specialized.
1963
1964          Note that here, there's no suggestion that we're supposed to
1965          determine which of the candidate templates is most
1966          specialized.  However, we, also have:
1967
1968            [temp.func.order]
1969
1970            Partial ordering of overloaded function template
1971            declarations is used in the following contexts to select
1972            the function template to which a function template
1973            specialization refers:
1974
1975            -- when an explicit specialization refers to a function
1976               template.
1977
1978          So, we do use the partial ordering rules, at least for now.
1979          This extension can only serve to make invalid programs valid,
1980          so it's safe.  And, there is strong anecdotal evidence that
1981          the committee intended the partial ordering rules to apply;
1982          the EDG front end has that behavior, and John Spicer claims
1983          that the committee simply forgot to delete the wording in
1984          [temp.expl.spec].  */
1985       tree tmpl = most_specialized_instantiation (templates);
1986       if (tmpl != error_mark_node)
1987         {
1988           templates = tmpl;
1989           TREE_CHAIN (templates) = NULL_TREE;
1990         }
1991     }
1992
1993   if (templates == NULL_TREE && candidates == NULL_TREE)
1994     {
1995       error ("template-id %qD for %q+D does not match any template "
1996              "declaration", template_id, decl);
1997       if (header_count && header_count != template_count + 1)
1998         inform (input_location, "saw %d %<template<>%>, need %d for "
1999                 "specializing a member function template",
2000                 header_count, template_count + 1);
2001       return error_mark_node;
2002     }
2003   else if ((templates && TREE_CHAIN (templates))
2004            || (candidates && TREE_CHAIN (candidates))
2005            || (templates && candidates))
2006     {
2007       error ("ambiguous template specialization %qD for %q+D",
2008              template_id, decl);
2009       candidates = chainon (candidates, templates);
2010       print_candidates (candidates);
2011       return error_mark_node;
2012     }
2013
2014   /* We have one, and exactly one, match.  */
2015   if (candidates)
2016     {
2017       tree fn = TREE_VALUE (candidates);
2018       *targs_out = copy_node (DECL_TI_ARGS (fn));
2019       /* DECL is a re-declaration or partial instantiation of a template
2020          function.  */
2021       if (TREE_CODE (fn) == TEMPLATE_DECL)
2022         return fn;
2023       /* It was a specialization of an ordinary member function in a
2024          template class.  */
2025       return DECL_TI_TEMPLATE (fn);
2026     }
2027
2028   /* It was a specialization of a template.  */
2029   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2030   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2031     {
2032       *targs_out = copy_node (targs);
2033       SET_TMPL_ARGS_LEVEL (*targs_out,
2034                            TMPL_ARGS_DEPTH (*targs_out),
2035                            TREE_PURPOSE (templates));
2036     }
2037   else
2038     *targs_out = TREE_PURPOSE (templates);
2039   return TREE_VALUE (templates);
2040 }
2041
2042 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2043    but with the default argument values filled in from those in the
2044    TMPL_TYPES.  */
2045
2046 static tree
2047 copy_default_args_to_explicit_spec_1 (tree spec_types,
2048                                       tree tmpl_types)
2049 {
2050   tree new_spec_types;
2051
2052   if (!spec_types)
2053     return NULL_TREE;
2054
2055   if (spec_types == void_list_node)
2056     return void_list_node;
2057
2058   /* Substitute into the rest of the list.  */
2059   new_spec_types =
2060     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2061                                           TREE_CHAIN (tmpl_types));
2062
2063   /* Add the default argument for this parameter.  */
2064   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2065                          TREE_VALUE (spec_types),
2066                          new_spec_types);
2067 }
2068
2069 /* DECL is an explicit specialization.  Replicate default arguments
2070    from the template it specializes.  (That way, code like:
2071
2072      template <class T> void f(T = 3);
2073      template <> void f(double);
2074      void g () { f (); }
2075
2076    works, as required.)  An alternative approach would be to look up
2077    the correct default arguments at the call-site, but this approach
2078    is consistent with how implicit instantiations are handled.  */
2079
2080 static void
2081 copy_default_args_to_explicit_spec (tree decl)
2082 {
2083   tree tmpl;
2084   tree spec_types;
2085   tree tmpl_types;
2086   tree new_spec_types;
2087   tree old_type;
2088   tree new_type;
2089   tree t;
2090   tree object_type = NULL_TREE;
2091   tree in_charge = NULL_TREE;
2092   tree vtt = NULL_TREE;
2093
2094   /* See if there's anything we need to do.  */
2095   tmpl = DECL_TI_TEMPLATE (decl);
2096   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2097   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2098     if (TREE_PURPOSE (t))
2099       break;
2100   if (!t)
2101     return;
2102
2103   old_type = TREE_TYPE (decl);
2104   spec_types = TYPE_ARG_TYPES (old_type);
2105
2106   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2107     {
2108       /* Remove the this pointer, but remember the object's type for
2109          CV quals.  */
2110       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2111       spec_types = TREE_CHAIN (spec_types);
2112       tmpl_types = TREE_CHAIN (tmpl_types);
2113
2114       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2115         {
2116           /* DECL may contain more parameters than TMPL due to the extra
2117              in-charge parameter in constructors and destructors.  */
2118           in_charge = spec_types;
2119           spec_types = TREE_CHAIN (spec_types);
2120         }
2121       if (DECL_HAS_VTT_PARM_P (decl))
2122         {
2123           vtt = spec_types;
2124           spec_types = TREE_CHAIN (spec_types);
2125         }
2126     }
2127
2128   /* Compute the merged default arguments.  */
2129   new_spec_types =
2130     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2131
2132   /* Compute the new FUNCTION_TYPE.  */
2133   if (object_type)
2134     {
2135       if (vtt)
2136         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2137                                          TREE_VALUE (vtt),
2138                                          new_spec_types);
2139
2140       if (in_charge)
2141         /* Put the in-charge parameter back.  */
2142         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2143                                          TREE_VALUE (in_charge),
2144                                          new_spec_types);
2145
2146       new_type = build_method_type_directly (object_type,
2147                                              TREE_TYPE (old_type),
2148                                              new_spec_types);
2149     }
2150   else
2151     new_type = build_function_type (TREE_TYPE (old_type),
2152                                     new_spec_types);
2153   new_type = cp_build_type_attribute_variant (new_type,
2154                                               TYPE_ATTRIBUTES (old_type));
2155   new_type = build_exception_variant (new_type,
2156                                       TYPE_RAISES_EXCEPTIONS (old_type));
2157   TREE_TYPE (decl) = new_type;
2158 }
2159
2160 /* Check to see if the function just declared, as indicated in
2161    DECLARATOR, and in DECL, is a specialization of a function
2162    template.  We may also discover that the declaration is an explicit
2163    instantiation at this point.
2164
2165    Returns DECL, or an equivalent declaration that should be used
2166    instead if all goes well.  Issues an error message if something is
2167    amiss.  Returns error_mark_node if the error is not easily
2168    recoverable.
2169
2170    FLAGS is a bitmask consisting of the following flags:
2171
2172    2: The function has a definition.
2173    4: The function is a friend.
2174
2175    The TEMPLATE_COUNT is the number of references to qualifying
2176    template classes that appeared in the name of the function.  For
2177    example, in
2178
2179      template <class T> struct S { void f(); };
2180      void S<int>::f();
2181
2182    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2183    classes are not counted in the TEMPLATE_COUNT, so that in
2184
2185      template <class T> struct S {};
2186      template <> struct S<int> { void f(); }
2187      template <> void S<int>::f();
2188
2189    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2190    invalid; there should be no template <>.)
2191
2192    If the function is a specialization, it is marked as such via
2193    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2194    is set up correctly, and it is added to the list of specializations
2195    for that template.  */
2196
2197 tree
2198 check_explicit_specialization (tree declarator,
2199                                tree decl,
2200                                int template_count,
2201                                int flags)
2202 {
2203   int have_def = flags & 2;
2204   int is_friend = flags & 4;
2205   int specialization = 0;
2206   int explicit_instantiation = 0;
2207   int member_specialization = 0;
2208   tree ctype = DECL_CLASS_CONTEXT (decl);
2209   tree dname = DECL_NAME (decl);
2210   tmpl_spec_kind tsk;
2211
2212   if (is_friend)
2213     {
2214       if (!processing_specialization)
2215         tsk = tsk_none;
2216       else
2217         tsk = tsk_excessive_parms;
2218     }
2219   else
2220     tsk = current_tmpl_spec_kind (template_count);
2221
2222   switch (tsk)
2223     {
2224     case tsk_none:
2225       if (processing_specialization)
2226         {
2227           specialization = 1;
2228           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2229         }
2230       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2231         {
2232           if (is_friend)
2233             /* This could be something like:
2234
2235                template <class T> void f(T);
2236                class S { friend void f<>(int); }  */
2237             specialization = 1;
2238           else
2239             {
2240               /* This case handles bogus declarations like template <>
2241                  template <class T> void f<int>(); */
2242
2243               error ("template-id %qD in declaration of primary template",
2244                      declarator);
2245               return decl;
2246             }
2247         }
2248       break;
2249
2250     case tsk_invalid_member_spec:
2251       /* The error has already been reported in
2252          check_specialization_scope.  */
2253       return error_mark_node;
2254
2255     case tsk_invalid_expl_inst:
2256       error ("template parameter list used in explicit instantiation");
2257
2258       /* Fall through.  */
2259
2260     case tsk_expl_inst:
2261       if (have_def)
2262         error ("definition provided for explicit instantiation");
2263
2264       explicit_instantiation = 1;
2265       break;
2266
2267     case tsk_excessive_parms:
2268     case tsk_insufficient_parms:
2269       if (tsk == tsk_excessive_parms)
2270         error ("too many template parameter lists in declaration of %qD",
2271                decl);
2272       else if (template_header_count)
2273         error("too few template parameter lists in declaration of %qD", decl);
2274       else
2275         error("explicit specialization of %qD must be introduced by "
2276               "%<template <>%>", decl);
2277
2278       /* Fall through.  */
2279     case tsk_expl_spec:
2280       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2281       if (ctype)
2282         member_specialization = 1;
2283       else
2284         specialization = 1;
2285       break;
2286
2287     case tsk_template:
2288       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2289         {
2290           /* This case handles bogus declarations like template <>
2291              template <class T> void f<int>(); */
2292
2293           if (uses_template_parms (declarator))
2294             error ("function template partial specialization %qD "
2295                    "is not allowed", declarator);
2296           else
2297             error ("template-id %qD in declaration of primary template",
2298                    declarator);
2299           return decl;
2300         }
2301
2302       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2303         /* This is a specialization of a member template, without
2304            specialization the containing class.  Something like:
2305
2306              template <class T> struct S {
2307                template <class U> void f (U);
2308              };
2309              template <> template <class U> void S<int>::f(U) {}
2310
2311            That's a specialization -- but of the entire template.  */
2312         specialization = 1;
2313       break;
2314
2315     default:
2316       gcc_unreachable ();
2317     }
2318
2319   if (specialization || member_specialization)
2320     {
2321       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2322       for (; t; t = TREE_CHAIN (t))
2323         if (TREE_PURPOSE (t))
2324           {
2325             permerror (input_location, 
2326                        "default argument specified in explicit specialization");
2327             break;
2328           }
2329     }
2330
2331   if (specialization || member_specialization || explicit_instantiation)
2332     {
2333       tree tmpl = NULL_TREE;
2334       tree targs = NULL_TREE;
2335
2336       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2337       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2338         {
2339           tree fns;
2340
2341           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2342           if (ctype)
2343             fns = dname;
2344           else
2345             {
2346               /* If there is no class context, the explicit instantiation
2347                  must be at namespace scope.  */
2348               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2349
2350               /* Find the namespace binding, using the declaration
2351                  context.  */
2352               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2353                                            false, true);
2354               if (fns == error_mark_node || !is_overloaded_fn (fns))
2355                 {
2356                   error ("%qD is not a template function", dname);
2357                   fns = error_mark_node;
2358                 }
2359               else
2360                 {
2361                   tree fn = OVL_CURRENT (fns);
2362                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2363                                                 CP_DECL_CONTEXT (fn)))
2364                     error ("%qD is not declared in %qD",
2365                            decl, current_namespace);
2366                 }
2367             }
2368
2369           declarator = lookup_template_function (fns, NULL_TREE);
2370         }
2371
2372       if (declarator == error_mark_node)
2373         return error_mark_node;
2374
2375       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2376         {
2377           if (!explicit_instantiation)
2378             /* A specialization in class scope.  This is invalid,
2379                but the error will already have been flagged by
2380                check_specialization_scope.  */
2381             return error_mark_node;
2382           else
2383             {
2384               /* It's not valid to write an explicit instantiation in
2385                  class scope, e.g.:
2386
2387                    class C { template void f(); }
2388
2389                    This case is caught by the parser.  However, on
2390                    something like:
2391
2392                    template class C { void f(); };
2393
2394                    (which is invalid) we can get here.  The error will be
2395                    issued later.  */
2396               ;
2397             }
2398
2399           return decl;
2400         }
2401       else if (ctype != NULL_TREE
2402                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2403                    IDENTIFIER_NODE))
2404         {
2405           /* Find the list of functions in ctype that have the same
2406              name as the declared function.  */
2407           tree name = TREE_OPERAND (declarator, 0);
2408           tree fns = NULL_TREE;
2409           int idx;
2410
2411           if (constructor_name_p (name, ctype))
2412             {
2413               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2414
2415               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2416                   : !CLASSTYPE_DESTRUCTORS (ctype))
2417                 {
2418                   /* From [temp.expl.spec]:
2419
2420                      If such an explicit specialization for the member
2421                      of a class template names an implicitly-declared
2422                      special member function (clause _special_), the
2423                      program is ill-formed.
2424
2425                      Similar language is found in [temp.explicit].  */
2426                   error ("specialization of implicitly-declared special member function");
2427                   return error_mark_node;
2428                 }
2429
2430               name = is_constructor ? ctor_identifier : dtor_identifier;
2431             }
2432
2433           if (!DECL_CONV_FN_P (decl))
2434             {
2435               idx = lookup_fnfields_1 (ctype, name);
2436               if (idx >= 0)
2437                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2438             }
2439           else
2440             {
2441               VEC(tree,gc) *methods;
2442               tree ovl;
2443
2444               /* For a type-conversion operator, we cannot do a
2445                  name-based lookup.  We might be looking for `operator
2446                  int' which will be a specialization of `operator T'.
2447                  So, we find *all* the conversion operators, and then
2448                  select from them.  */
2449               fns = NULL_TREE;
2450
2451               methods = CLASSTYPE_METHOD_VEC (ctype);
2452               if (methods)
2453                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2454                      VEC_iterate (tree, methods, idx, ovl);
2455                      ++idx)
2456                   {
2457                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2458                       /* There are no more conversion functions.  */
2459                       break;
2460
2461                     /* Glue all these conversion functions together
2462                        with those we already have.  */
2463                     for (; ovl; ovl = OVL_NEXT (ovl))
2464                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2465                   }
2466             }
2467
2468           if (fns == NULL_TREE)
2469             {
2470               error ("no member function %qD declared in %qT", name, ctype);
2471               return error_mark_node;
2472             }
2473           else
2474             TREE_OPERAND (declarator, 0) = fns;
2475         }
2476
2477       /* Figure out what exactly is being specialized at this point.
2478          Note that for an explicit instantiation, even one for a
2479          member function, we cannot tell apriori whether the
2480          instantiation is for a member template, or just a member
2481          function of a template class.  Even if a member template is
2482          being instantiated, the member template arguments may be
2483          elided if they can be deduced from the rest of the
2484          declaration.  */
2485       tmpl = determine_specialization (declarator, decl,
2486                                        &targs,
2487                                        member_specialization,
2488                                        template_count,
2489                                        tsk);
2490
2491       if (!tmpl || tmpl == error_mark_node)
2492         /* We couldn't figure out what this declaration was
2493            specializing.  */
2494         return error_mark_node;
2495       else
2496         {
2497           tree gen_tmpl = most_general_template (tmpl);
2498
2499           if (explicit_instantiation)
2500             {
2501               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2502                  is done by do_decl_instantiation later.  */
2503
2504               int arg_depth = TMPL_ARGS_DEPTH (targs);
2505               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2506
2507               if (arg_depth > parm_depth)
2508                 {
2509                   /* If TMPL is not the most general template (for
2510                      example, if TMPL is a friend template that is
2511                      injected into namespace scope), then there will
2512                      be too many levels of TARGS.  Remove some of them
2513                      here.  */
2514                   int i;
2515                   tree new_targs;
2516
2517                   new_targs = make_tree_vec (parm_depth);
2518                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2519                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2520                       = TREE_VEC_ELT (targs, i);
2521                   targs = new_targs;
2522                 }
2523
2524               return instantiate_template (tmpl, targs, tf_error);
2525             }
2526
2527           /* If we thought that the DECL was a member function, but it
2528              turns out to be specializing a static member function,
2529              make DECL a static member function as well.  */
2530           if (DECL_STATIC_FUNCTION_P (tmpl)
2531               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2532             revert_static_member_fn (decl);
2533
2534           /* If this is a specialization of a member template of a
2535              template class, we want to return the TEMPLATE_DECL, not
2536              the specialization of it.  */
2537           if (tsk == tsk_template)
2538             {
2539               tree result = DECL_TEMPLATE_RESULT (tmpl);
2540               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2541               DECL_INITIAL (result) = NULL_TREE;
2542               if (have_def)
2543                 {
2544                   tree parm;
2545                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2546                   DECL_SOURCE_LOCATION (result)
2547                     = DECL_SOURCE_LOCATION (decl);
2548                   /* We want to use the argument list specified in the
2549                      definition, not in the original declaration.  */
2550                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2551                   for (parm = DECL_ARGUMENTS (result); parm;
2552                        parm = TREE_CHAIN (parm))
2553                     DECL_CONTEXT (parm) = result;
2554                 }
2555               return register_specialization (tmpl, gen_tmpl, targs,
2556                                               is_friend, 0);
2557             }
2558
2559           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2560           DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
2561
2562           /* Inherit default function arguments from the template
2563              DECL is specializing.  */
2564           copy_default_args_to_explicit_spec (decl);
2565
2566           /* This specialization has the same protection as the
2567              template it specializes.  */
2568           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2569           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2570
2571           /* 7.1.1-1 [dcl.stc]
2572
2573              A storage-class-specifier shall not be specified in an
2574              explicit specialization...
2575
2576              The parser rejects these, so unless action is taken here,
2577              explicit function specializations will always appear with
2578              global linkage.
2579
2580              The action recommended by the C++ CWG in response to C++
2581              defect report 605 is to make the storage class and linkage
2582              of the explicit specialization match the templated function:
2583
2584              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2585            */
2586           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2587             {
2588               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2589               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2590
2591               /* This specialization has the same linkage and visibility as
2592                  the function template it specializes.  */
2593               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2594               if (! TREE_PUBLIC (decl))
2595                 {
2596                   DECL_INTERFACE_KNOWN (decl) = 1;
2597                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2598                 }
2599               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2600               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2601                 {
2602                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2603                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2604                 }
2605             }
2606
2607           /* If DECL is a friend declaration, declared using an
2608              unqualified name, the namespace associated with DECL may
2609              have been set incorrectly.  For example, in:
2610
2611                template <typename T> void f(T);
2612                namespace N {
2613                  struct S { friend void f<int>(int); }
2614                }
2615
2616              we will have set the DECL_CONTEXT for the friend
2617              declaration to N, rather than to the global namespace.  */
2618           if (DECL_NAMESPACE_SCOPE_P (decl))
2619             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2620
2621           if (is_friend && !have_def)
2622             /* This is not really a declaration of a specialization.
2623                It's just the name of an instantiation.  But, it's not
2624                a request for an instantiation, either.  */
2625             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2626           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2627             /* This is indeed a specialization.  In case of constructors
2628                and destructors, we need in-charge and not-in-charge
2629                versions in V3 ABI.  */
2630             clone_function_decl (decl, /*update_method_vec_p=*/0);
2631
2632           /* Register this specialization so that we can find it
2633              again.  */
2634           decl = register_specialization (decl, gen_tmpl, targs, is_friend, 0);
2635         }
2636     }
2637
2638   return decl;
2639 }
2640
2641 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2642    parameters.  These are represented in the same format used for
2643    DECL_TEMPLATE_PARMS.  */
2644
2645 int
2646 comp_template_parms (const_tree parms1, const_tree parms2)
2647 {
2648   const_tree p1;
2649   const_tree p2;
2650
2651   if (parms1 == parms2)
2652     return 1;
2653
2654   for (p1 = parms1, p2 = parms2;
2655        p1 != NULL_TREE && p2 != NULL_TREE;
2656        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2657     {
2658       tree t1 = TREE_VALUE (p1);
2659       tree t2 = TREE_VALUE (p2);
2660       int i;
2661
2662       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2663       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2664
2665       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2666         return 0;
2667
2668       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2669         {
2670           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2671           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2672
2673           /* If either of the template parameters are invalid, assume
2674              they match for the sake of error recovery. */
2675           if (parm1 == error_mark_node || parm2 == error_mark_node)
2676             return 1;
2677
2678           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2679             return 0;
2680
2681           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2682               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2683                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2684             continue;
2685           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2686             return 0;
2687         }
2688     }
2689
2690   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2691     /* One set of parameters has more parameters lists than the
2692        other.  */
2693     return 0;
2694
2695   return 1;
2696 }
2697
2698 /* Determine whether PARM is a parameter pack.  */
2699
2700 bool 
2701 template_parameter_pack_p (const_tree parm)
2702 {
2703   /* Determine if we have a non-type template parameter pack.  */
2704   if (TREE_CODE (parm) == PARM_DECL)
2705     return (DECL_TEMPLATE_PARM_P (parm) 
2706             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2707
2708   /* If this is a list of template parameters, we could get a
2709      TYPE_DECL or a TEMPLATE_DECL.  */ 
2710   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2711     parm = TREE_TYPE (parm);
2712
2713   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2714            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2715           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2716 }
2717
2718 /* Determine if T is a function parameter pack.  */
2719
2720 bool
2721 function_parameter_pack_p (const_tree t)
2722 {
2723   if (t && TREE_CODE (t) == PARM_DECL)
2724     return FUNCTION_PARAMETER_PACK_P (t);
2725   return false;
2726 }
2727
2728 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
2729    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
2730
2731 tree
2732 get_function_template_decl (const_tree primary_func_tmpl_inst)
2733 {
2734   if (! primary_func_tmpl_inst
2735       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
2736       || ! primary_template_instantiation_p (primary_func_tmpl_inst))
2737     return NULL;
2738
2739   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
2740 }
2741
2742 /* Return true iff the function parameter PARAM_DECL was expanded
2743    from the function parameter pack PACK.  */
2744
2745 bool
2746 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
2747 {
2748   if (DECL_ARTIFICIAL (param_decl)
2749       || !function_parameter_pack_p (pack))
2750     return false;
2751
2752   /* The parameter pack and its pack arguments have the same
2753      DECL_PARM_INDEX.  */
2754   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
2755 }
2756
2757 /* Determine whether ARGS describes a variadic template args list,
2758    i.e., one that is terminated by a template argument pack.  */
2759
2760 static bool 
2761 template_args_variadic_p (tree args)
2762 {
2763   int nargs;
2764   tree last_parm;
2765
2766   if (args == NULL_TREE)
2767     return false;
2768
2769   args = INNERMOST_TEMPLATE_ARGS (args);
2770   nargs = TREE_VEC_LENGTH (args);
2771
2772   if (nargs == 0)
2773     return false;
2774
2775   last_parm = TREE_VEC_ELT (args, nargs - 1);
2776
2777   return ARGUMENT_PACK_P (last_parm);
2778 }
2779
2780 /* Generate a new name for the parameter pack name NAME (an
2781    IDENTIFIER_NODE) that incorporates its */
2782
2783 static tree
2784 make_ith_pack_parameter_name (tree name, int i)
2785 {
2786   /* Munge the name to include the parameter index.  */
2787 #define NUMBUF_LEN 128
2788   char numbuf[NUMBUF_LEN];
2789   char* newname;
2790   int newname_len;
2791
2792   snprintf (numbuf, NUMBUF_LEN, "%i", i);
2793   newname_len = IDENTIFIER_LENGTH (name)
2794                 + strlen (numbuf) + 2;
2795   newname = (char*)alloca (newname_len);
2796   snprintf (newname, newname_len,
2797             "%s#%i", IDENTIFIER_POINTER (name), i);
2798   return get_identifier (newname);
2799 }
2800
2801 /* Return true if T is a primary function
2802    or class template instantiation.  */
2803
2804 bool
2805 primary_template_instantiation_p (const_tree t)
2806 {
2807   if (!t)
2808     return false;
2809
2810   if (TREE_CODE (t) == FUNCTION_DECL)
2811     return DECL_LANG_SPECIFIC (t)
2812            && DECL_TEMPLATE_INSTANTIATION (t)
2813            && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t));
2814   else if (CLASS_TYPE_P (t))
2815     return CLASSTYPE_TEMPLATE_INSTANTIATION (t)
2816            && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t));
2817   return false;
2818 }
2819
2820 /* Return true if PARM is a template template parameter.  */
2821
2822 bool
2823 template_template_parameter_p (const_tree parm)
2824 {
2825   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
2826 }
2827
2828 /* Return the template parameters of T if T is a
2829    primary template instantiation, NULL otherwise.  */
2830
2831 tree
2832 get_primary_template_innermost_parameters (const_tree t)
2833 {
2834   tree parms = NULL, template_info = NULL;
2835
2836   if ((template_info = get_template_info (t))
2837       && primary_template_instantiation_p (t))
2838     parms = INNERMOST_TEMPLATE_PARMS
2839         (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
2840
2841   return parms;
2842 }
2843
2844 /* Returns the template arguments of T if T is a template instantiation,
2845    NULL otherwise.  */
2846
2847 tree
2848 get_template_innermost_arguments (const_tree t)
2849 {
2850   tree args = NULL, template_info = NULL;
2851
2852   if ((template_info = get_template_info (t))
2853       && TI_ARGS (template_info))
2854     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
2855
2856   return args;
2857 }
2858
2859 /* Return the argument pack elements of T if T is a template argument pack,
2860    NULL otherwise.  */
2861
2862 tree
2863 get_template_argument_pack_elems (const_tree t)
2864 {
2865   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
2866       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
2867     return NULL;
2868
2869   return ARGUMENT_PACK_ARGS (t);
2870 }
2871
2872 /* Structure used to track the progress of find_parameter_packs_r.  */
2873 struct find_parameter_pack_data 
2874 {
2875   /* TREE_LIST that will contain all of the parameter packs found by
2876      the traversal.  */
2877   tree* parameter_packs;
2878
2879   /* Set of AST nodes that have been visited by the traversal.  */
2880   struct pointer_set_t *visited;
2881 };
2882
2883 /* Identifies all of the argument packs that occur in a template
2884    argument and appends them to the TREE_LIST inside DATA, which is a
2885    find_parameter_pack_data structure. This is a subroutine of
2886    make_pack_expansion and uses_parameter_packs.  */
2887 static tree
2888 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2889 {
2890   tree t = *tp;
2891   struct find_parameter_pack_data* ppd = 
2892     (struct find_parameter_pack_data*)data;
2893   bool parameter_pack_p = false;
2894
2895   /* Identify whether this is a parameter pack or not.  */
2896   switch (TREE_CODE (t))
2897     {
2898     case TEMPLATE_PARM_INDEX:
2899       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2900         parameter_pack_p = true;
2901       break;
2902
2903     case TEMPLATE_TYPE_PARM:
2904     case TEMPLATE_TEMPLATE_PARM:
2905       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2906         parameter_pack_p = true;
2907       break;
2908
2909     case PARM_DECL:
2910       if (FUNCTION_PARAMETER_PACK_P (t))
2911         {
2912           /* We don't want to walk into the type of a PARM_DECL,
2913              because we don't want to see the type parameter pack.  */
2914           *walk_subtrees = 0;
2915           parameter_pack_p = true;
2916         }
2917       break;
2918
2919     default:
2920       /* Not a parameter pack.  */
2921       break;
2922     }
2923
2924   if (parameter_pack_p)
2925     {
2926       /* Add this parameter pack to the list.  */
2927       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2928     }
2929
2930   if (TYPE_P (t))
2931     cp_walk_tree (&TYPE_CONTEXT (t), 
2932                   &find_parameter_packs_r, ppd, ppd->visited);
2933
2934   /* This switch statement will return immediately if we don't find a
2935      parameter pack.  */
2936   switch (TREE_CODE (t)) 
2937     {
2938     case TEMPLATE_PARM_INDEX:
2939       return NULL_TREE;
2940
2941     case BOUND_TEMPLATE_TEMPLATE_PARM:
2942       /* Check the template itself.  */
2943       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
2944                     &find_parameter_packs_r, ppd, ppd->visited);
2945       /* Check the template arguments.  */
2946       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
2947                     ppd->visited);
2948       *walk_subtrees = 0;
2949       return NULL_TREE;
2950
2951     case TEMPLATE_TYPE_PARM:
2952     case TEMPLATE_TEMPLATE_PARM:
2953       return NULL_TREE;
2954
2955     case PARM_DECL:
2956       return NULL_TREE;
2957
2958     case RECORD_TYPE:
2959       if (TYPE_PTRMEMFUNC_P (t))
2960         return NULL_TREE;
2961       /* Fall through.  */
2962
2963     case UNION_TYPE:
2964     case ENUMERAL_TYPE:
2965       if (TYPE_TEMPLATE_INFO (t))
2966         cp_walk_tree (&TI_ARGS (TYPE_TEMPLATE_INFO (t)),
2967                       &find_parameter_packs_r, ppd, ppd->visited);
2968
2969       *walk_subtrees = 0;
2970       return NULL_TREE;
2971
2972     case TEMPLATE_DECL:
2973       cp_walk_tree (&TREE_TYPE (t),
2974                     &find_parameter_packs_r, ppd, ppd->visited);
2975       return NULL_TREE;
2976  
2977     case TYPENAME_TYPE:
2978       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
2979                    ppd, ppd->visited);
2980       *walk_subtrees = 0;
2981       return NULL_TREE;
2982       
2983     case TYPE_PACK_EXPANSION:
2984     case EXPR_PACK_EXPANSION:
2985       *walk_subtrees = 0;
2986       return NULL_TREE;
2987
2988     case INTEGER_TYPE:
2989       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
2990                     ppd, ppd->visited);
2991       *walk_subtrees = 0;
2992       return NULL_TREE;
2993
2994     case IDENTIFIER_NODE:
2995       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
2996                     ppd->visited);
2997       *walk_subtrees = 0;
2998       return NULL_TREE;
2999
3000     default:
3001       return NULL_TREE;
3002     }
3003
3004   return NULL_TREE;
3005 }
3006
3007 /* Determines if the expression or type T uses any parameter packs.  */
3008 bool
3009 uses_parameter_packs (tree t)
3010 {
3011   tree parameter_packs = NULL_TREE;
3012   struct find_parameter_pack_data ppd;
3013   ppd.parameter_packs = &parameter_packs;
3014   ppd.visited = pointer_set_create ();
3015   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3016   pointer_set_destroy (ppd.visited);
3017   return parameter_packs != NULL_TREE;
3018 }
3019
3020 /* Turn ARG, which may be an expression, type, or a TREE_LIST
3021    representation a base-class initializer into a parameter pack
3022    expansion. If all goes well, the resulting node will be an
3023    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
3024    respectively.  */
3025 tree 
3026 make_pack_expansion (tree arg)
3027 {
3028   tree result;
3029   tree parameter_packs = NULL_TREE;
3030   bool for_types = false;
3031   struct find_parameter_pack_data ppd;
3032
3033   if (!arg || arg == error_mark_node)
3034     return arg;
3035
3036   if (TREE_CODE (arg) == TREE_LIST)
3037     {
3038       /* The only time we will see a TREE_LIST here is for a base
3039          class initializer.  In this case, the TREE_PURPOSE will be a
3040          _TYPE node (representing the base class expansion we're
3041          initializing) and the TREE_VALUE will be a TREE_LIST
3042          containing the initialization arguments. 
3043
3044          The resulting expansion looks somewhat different from most
3045          expansions. Rather than returning just one _EXPANSION, we
3046          return a TREE_LIST whose TREE_PURPOSE is a
3047          TYPE_PACK_EXPANSION containing the bases that will be
3048          initialized.  The TREE_VALUE will be identical to the
3049          original TREE_VALUE, which is a list of arguments that will
3050          be passed to each base.  We do not introduce any new pack
3051          expansion nodes into the TREE_VALUE (although it is possible
3052          that some already exist), because the TREE_PURPOSE and
3053          TREE_VALUE all need to be expanded together with the same
3054          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3055          resulting TREE_PURPOSE will mention the parameter packs in
3056          both the bases and the arguments to the bases.  */
3057       tree purpose;
3058       tree value;
3059       tree parameter_packs = NULL_TREE;
3060
3061       /* Determine which parameter packs will be used by the base
3062          class expansion.  */
3063       ppd.visited = pointer_set_create ();
3064       ppd.parameter_packs = &parameter_packs;
3065       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
3066                     &ppd, ppd.visited);
3067
3068       if (parameter_packs == NULL_TREE)
3069         {
3070           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
3071           pointer_set_destroy (ppd.visited);
3072           return error_mark_node;
3073         }
3074
3075       if (TREE_VALUE (arg) != void_type_node)
3076         {
3077           /* Collect the sets of parameter packs used in each of the
3078              initialization arguments.  */
3079           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3080             {
3081               /* Determine which parameter packs will be expanded in this
3082                  argument.  */
3083               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
3084                             &ppd, ppd.visited);
3085             }
3086         }
3087
3088       pointer_set_destroy (ppd.visited);
3089
3090       /* Create the pack expansion type for the base type.  */
3091       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3092       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3093       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3094
3095       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3096          they will rarely be compared to anything.  */
3097       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3098
3099       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3100     }
3101
3102   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3103     for_types = true;
3104
3105   /* Build the PACK_EXPANSION_* node.  */
3106   result = for_types
3107      ? cxx_make_type (TYPE_PACK_EXPANSION)
3108      : make_node (EXPR_PACK_EXPANSION);
3109   SET_PACK_EXPANSION_PATTERN (result, arg);
3110   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3111     {
3112       /* Propagate type and const-expression information.  */
3113       TREE_TYPE (result) = TREE_TYPE (arg);
3114       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3115     }
3116   else
3117     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3118        they will rarely be compared to anything.  */
3119     SET_TYPE_STRUCTURAL_EQUALITY (result);
3120
3121   /* Determine which parameter packs will be expanded.  */
3122   ppd.parameter_packs = &parameter_packs;
3123   ppd.visited = pointer_set_create ();
3124   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3125   pointer_set_destroy (ppd.visited);
3126
3127   /* Make sure we found some parameter packs.  */
3128   if (parameter_packs == NULL_TREE)
3129     {
3130       if (TYPE_P (arg))
3131         error ("expansion pattern %<%T%> contains no argument packs", arg);
3132       else
3133         error ("expansion pattern %<%E%> contains no argument packs", arg);
3134       return error_mark_node;
3135     }
3136   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
3137
3138   return result;
3139 }
3140
3141 /* Checks T for any "bare" parameter packs, which have not yet been
3142    expanded, and issues an error if any are found. This operation can
3143    only be done on full expressions or types (e.g., an expression
3144    statement, "if" condition, etc.), because we could have expressions like:
3145
3146      foo(f(g(h(args)))...)
3147
3148    where "args" is a parameter pack. check_for_bare_parameter_packs
3149    should not be called for the subexpressions args, h(args),
3150    g(h(args)), or f(g(h(args))), because we would produce erroneous
3151    error messages. 
3152
3153    Returns TRUE and emits an error if there were bare parameter packs,
3154    returns FALSE otherwise.  */
3155 bool 
3156 check_for_bare_parameter_packs (tree t)
3157 {
3158   tree parameter_packs = NULL_TREE;
3159   struct find_parameter_pack_data ppd;
3160
3161   if (!processing_template_decl || !t || t == error_mark_node)
3162     return false;
3163
3164   if (TREE_CODE (t) == TYPE_DECL)
3165     t = TREE_TYPE (t);
3166
3167   ppd.parameter_packs = &parameter_packs;
3168   ppd.visited = pointer_set_create ();
3169   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3170   pointer_set_destroy (ppd.visited);
3171
3172   if (parameter_packs) 
3173     {
3174       error ("parameter packs not expanded with %<...%>:");
3175       while (parameter_packs)
3176         {
3177           tree pack = TREE_VALUE (parameter_packs);
3178           tree name = NULL_TREE;
3179
3180           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
3181               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
3182             name = TYPE_NAME (pack);
3183           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
3184             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
3185           else
3186             name = DECL_NAME (pack);
3187
3188           if (name)
3189             inform (input_location, "        %qD", name);
3190           else
3191             inform (input_location, "        <anonymous>");
3192
3193           parameter_packs = TREE_CHAIN (parameter_packs);
3194         }
3195
3196       return true;
3197     }
3198
3199   return false;
3200 }
3201
3202 /* Expand any parameter packs that occur in the template arguments in
3203    ARGS.  */
3204 tree
3205 expand_template_argument_pack (tree args)
3206 {
3207   tree result_args = NULL_TREE;
3208   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3209   int num_result_args = -1;
3210   int non_default_args_count = -1;
3211
3212   /* First, determine if we need to expand anything, and the number of
3213      slots we'll need.  */
3214   for (in_arg = 0; in_arg < nargs; ++in_arg)
3215     {
3216       tree arg = TREE_VEC_ELT (args, in_arg);
3217       if (arg == NULL_TREE)
3218         return args;
3219       if (ARGUMENT_PACK_P (arg))
3220         {
3221           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3222           if (num_result_args < 0)
3223             num_result_args = in_arg + num_packed;
3224           else
3225             num_result_args += num_packed;
3226         }
3227       else
3228         {
3229           if (num_result_args >= 0)
3230             num_result_args++;
3231         }
3232     }
3233
3234   /* If no expansion is necessary, we're done.  */
3235   if (num_result_args < 0)
3236     return args;
3237
3238   /* Expand arguments.  */
3239   result_args = make_tree_vec (num_result_args);
3240   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
3241     non_default_args_count =
3242       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
3243   for (in_arg = 0; in_arg < nargs; ++in_arg)
3244     {
3245       tree arg = TREE_VEC_ELT (args, in_arg);
3246       if (ARGUMENT_PACK_P (arg))
3247         {
3248           tree packed = ARGUMENT_PACK_ARGS (arg);
3249           int i, num_packed = TREE_VEC_LENGTH (packed);
3250           for (i = 0; i < num_packed; ++i, ++out_arg)
3251             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3252           if (non_default_args_count > 0)
3253             non_default_args_count += num_packed;
3254         }
3255       else
3256         {
3257           TREE_VEC_ELT (result_args, out_arg) = arg;
3258           ++out_arg;
3259         }
3260     }
3261   if (non_default_args_count >= 0)
3262     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
3263   return result_args;
3264 }
3265
3266 /* Checks if DECL shadows a template parameter.
3267
3268    [temp.local]: A template-parameter shall not be redeclared within its
3269    scope (including nested scopes).
3270
3271    Emits an error and returns TRUE if the DECL shadows a parameter,
3272    returns FALSE otherwise.  */
3273
3274 bool
3275 check_template_shadow (tree decl)
3276 {
3277   tree olddecl;
3278
3279   /* If we're not in a template, we can't possibly shadow a template
3280      parameter.  */
3281   if (!current_template_parms)
3282     return true;
3283
3284   /* Figure out what we're shadowing.  */
3285   if (TREE_CODE (decl) == OVERLOAD)
3286     decl = OVL_CURRENT (decl);
3287   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3288
3289   /* If there's no previous binding for this name, we're not shadowing
3290      anything, let alone a template parameter.  */
3291   if (!olddecl)
3292     return true;
3293
3294   /* If we're not shadowing a template parameter, we're done.  Note
3295      that OLDDECL might be an OVERLOAD (or perhaps even an
3296      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3297      node.  */
3298   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3299     return true;
3300
3301   /* We check for decl != olddecl to avoid bogus errors for using a
3302      name inside a class.  We check TPFI to avoid duplicate errors for
3303      inline member templates.  */
3304   if (decl == olddecl
3305       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
3306     return true;
3307
3308   error ("declaration of %q+#D", decl);
3309   error (" shadows template parm %q+#D", olddecl);
3310   return false;
3311 }
3312
3313 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3314    ORIG_LEVEL, DECL, and TYPE.  */
3315
3316 static tree
3317 build_template_parm_index (int index,
3318                            int level,
3319                            int orig_level,
3320                            tree decl,
3321                            tree type)
3322 {
3323   tree t = make_node (TEMPLATE_PARM_INDEX);
3324   TEMPLATE_PARM_IDX (t) = index;
3325   TEMPLATE_PARM_LEVEL (t) = level;
3326   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3327   TEMPLATE_PARM_DECL (t) = decl;
3328   TREE_TYPE (t) = type;
3329   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3330   TREE_READONLY (t) = TREE_READONLY (decl);
3331
3332   return t;
3333 }
3334
3335 /* Find the canonical type parameter for the given template type
3336    parameter.  Returns the canonical type parameter, which may be TYPE
3337    if no such parameter existed.  */
3338 static tree
3339 canonical_type_parameter (tree type)
3340 {
3341   tree list;
3342   int idx = TEMPLATE_TYPE_IDX (type);
3343   if (!canonical_template_parms)
3344     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
3345
3346   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
3347     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
3348
3349   list = VEC_index (tree, canonical_template_parms, idx);
3350   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3351     list = TREE_CHAIN (list);
3352
3353   if (list)
3354     return TREE_VALUE (list);
3355   else
3356     {
3357       VEC_replace(tree, canonical_template_parms, idx,
3358                   tree_cons (NULL_TREE, type, 
3359                              VEC_index (tree, canonical_template_parms, idx)));
3360       return type;
3361     }
3362 }
3363
3364 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3365    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3366    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3367    new one is created.  */
3368
3369 static tree
3370 reduce_template_parm_level (tree index, tree type, int levels, tree args,
3371                             tsubst_flags_t complain)
3372 {
3373   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3374       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3375           != TEMPLATE_PARM_LEVEL (index) - levels)
3376       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
3377     {
3378       tree orig_decl = TEMPLATE_PARM_DECL (index);
3379       tree decl, t;
3380
3381       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3382                          TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3383       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
3384       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
3385       DECL_ARTIFICIAL (decl) = 1;
3386       SET_DECL_TEMPLATE_PARM_P (decl);
3387
3388       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
3389                                      TEMPLATE_PARM_LEVEL (index) - levels,
3390                                      TEMPLATE_PARM_ORIG_LEVEL (index),
3391                                      decl, type);
3392       TEMPLATE_PARM_DESCENDANTS (index) = t;
3393       TEMPLATE_PARM_PARAMETER_PACK (t) 
3394         = TEMPLATE_PARM_PARAMETER_PACK (index);
3395
3396         /* Template template parameters need this.  */
3397       if (TREE_CODE (decl) == TEMPLATE_DECL)
3398         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
3399           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
3400            args, complain);
3401     }
3402
3403   return TEMPLATE_PARM_DESCENDANTS (index);
3404 }
3405
3406 /* Process information from new template parameter PARM and append it to the
3407    LIST being built.  This new parameter is a non-type parameter iff
3408    IS_NON_TYPE is true. This new parameter is a parameter
3409    pack iff IS_PARAMETER_PACK is true.  The location of PARM is in 
3410    PARM_LOC.  */
3411
3412 tree
3413 process_template_parm (tree list, location_t parm_loc, tree parm, bool is_non_type, 
3414                        bool is_parameter_pack)
3415 {
3416   tree decl = 0;
3417   tree defval;
3418   tree err_parm_list;
3419   int idx = 0;
3420
3421   gcc_assert (TREE_CODE (parm) == TREE_LIST);
3422   defval = TREE_PURPOSE (parm);
3423
3424   if (list)
3425     {
3426       tree p = tree_last (list);
3427
3428       if (p && TREE_VALUE (p) != error_mark_node)
3429         {
3430           p = TREE_VALUE (p);
3431           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3432             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3433           else
3434             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3435         }
3436
3437       ++idx;
3438     }
3439   else
3440     idx = 0;
3441
3442   if (is_non_type)
3443     {
3444       parm = TREE_VALUE (parm);
3445
3446       SET_DECL_TEMPLATE_PARM_P (parm);
3447
3448       if (TREE_TYPE (parm) == error_mark_node)
3449         {
3450           err_parm_list = build_tree_list (defval, parm);
3451           TREE_VALUE (err_parm_list) = error_mark_node;
3452            return chainon (list, err_parm_list);
3453         }
3454       else
3455       {
3456         /* [temp.param]
3457
3458            The top-level cv-qualifiers on the template-parameter are
3459            ignored when determining its type.  */
3460         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3461         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3462           {
3463             err_parm_list = build_tree_list (defval, parm);
3464             TREE_VALUE (err_parm_list) = error_mark_node;
3465              return chainon (list, err_parm_list);
3466           }
3467
3468         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3469           {
3470             /* This template parameter is not a parameter pack, but it
3471                should be. Complain about "bare" parameter packs.  */
3472             check_for_bare_parameter_packs (TREE_TYPE (parm));
3473             
3474             /* Recover by calling this a parameter pack.  */
3475             is_parameter_pack = true;
3476           }
3477       }
3478
3479       /* A template parameter is not modifiable.  */
3480       TREE_CONSTANT (parm) = 1;
3481       TREE_READONLY (parm) = 1;
3482       decl = build_decl (parm_loc,
3483                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3484       TREE_CONSTANT (decl) = 1;
3485       TREE_READONLY (decl) = 1;
3486       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3487         = build_template_parm_index (idx, processing_template_decl,
3488                                      processing_template_decl,
3489                                      decl, TREE_TYPE (parm));
3490
3491       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3492         = is_parameter_pack;
3493     }
3494   else
3495     {
3496       tree t;
3497       parm = TREE_VALUE (TREE_VALUE (parm));
3498
3499       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3500         {
3501           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3502           /* This is for distinguishing between real templates and template
3503              template parameters */
3504           TREE_TYPE (parm) = t;
3505           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3506           decl = parm;
3507         }
3508       else
3509         {
3510           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3511           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3512           decl = build_decl (parm_loc,
3513                              TYPE_DECL, parm, t);
3514         }
3515
3516       TYPE_NAME (t) = decl;
3517       TYPE_STUB_DECL (t) = decl;
3518       parm = decl;
3519       TEMPLATE_TYPE_PARM_INDEX (t)
3520         = build_template_parm_index (idx, processing_template_decl,
3521                                      processing_template_decl,
3522                                      decl, TREE_TYPE (parm));
3523       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3524       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3525     }
3526   DECL_ARTIFICIAL (decl) = 1;
3527   SET_DECL_TEMPLATE_PARM_P (decl);
3528   pushdecl (decl);
3529   parm = build_tree_list (defval, parm);
3530   return chainon (list, parm);
3531 }
3532
3533 /* The end of a template parameter list has been reached.  Process the
3534    tree list into a parameter vector, converting each parameter into a more
3535    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3536    as PARM_DECLs.  */
3537
3538 tree
3539 end_template_parm_list (tree parms)
3540 {
3541   int nparms;
3542   tree parm, next;
3543   tree saved_parmlist = make_tree_vec (list_length (parms));
3544
3545   current_template_parms
3546     = tree_cons (size_int (processing_template_decl),
3547                  saved_parmlist, current_template_parms);
3548
3549   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3550     {
3551       next = TREE_CHAIN (parm);
3552       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3553       TREE_CHAIN (parm) = NULL_TREE;
3554     }
3555
3556   --processing_template_parmlist;
3557
3558   return saved_parmlist;
3559 }
3560
3561 /* end_template_decl is called after a template declaration is seen.  */
3562
3563 void
3564 end_template_decl (void)
3565 {
3566   reset_specialization ();
3567
3568   if (! processing_template_decl)
3569     return;
3570
3571   /* This matches the pushlevel in begin_template_parm_list.  */
3572   finish_scope ();
3573
3574   --processing_template_decl;
3575   current_template_parms = TREE_CHAIN (current_template_parms);
3576 }
3577
3578 /* Within the declaration of a template, return all levels of template
3579    parameters that apply.  The template parameters are represented as
3580    a TREE_VEC, in the form documented in cp-tree.h for template
3581    arguments.  */
3582
3583 static tree
3584 current_template_args (void)
3585 {
3586   tree header;
3587   tree args = NULL_TREE;
3588   int length = TMPL_PARMS_DEPTH (current_template_parms);
3589   int l = length;
3590
3591   /* If there is only one level of template parameters, we do not
3592      create a TREE_VEC of TREE_VECs.  Instead, we return a single
3593      TREE_VEC containing the arguments.  */
3594   if (length > 1)
3595     args = make_tree_vec (length);
3596
3597   for (header = current_template_parms; header; header = TREE_CHAIN (header))
3598     {
3599       tree a = copy_node (TREE_VALUE (header));
3600       int i;
3601
3602       TREE_TYPE (a) = NULL_TREE;
3603       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3604         {
3605           tree t = TREE_VEC_ELT (a, i);
3606
3607           /* T will be a list if we are called from within a
3608              begin/end_template_parm_list pair, but a vector directly
3609              if within a begin/end_member_template_processing pair.  */
3610           if (TREE_CODE (t) == TREE_LIST)
3611             {
3612               t = TREE_VALUE (t);
3613
3614               if (!error_operand_p (t))
3615                 {
3616                   if (TREE_CODE (t) == TYPE_DECL
3617                       || TREE_CODE (t) == TEMPLATE_DECL)
3618                     {
3619                       t = TREE_TYPE (t);
3620                       
3621                       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3622                         {
3623                           /* Turn this argument into a TYPE_ARGUMENT_PACK
3624                              with a single element, which expands T.  */
3625                           tree vec = make_tree_vec (1);
3626 #ifdef ENABLE_CHECKING
3627                           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3628                                 (vec, TREE_VEC_LENGTH (vec));
3629 #endif
3630                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3631                           
3632                           t = cxx_make_type (TYPE_ARGUMENT_PACK);
3633                           SET_ARGUMENT_PACK_ARGS (t, vec);
3634                         }
3635                     }
3636                   else
3637                     {
3638                       t = DECL_INITIAL (t);
3639                       
3640                       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3641                         {
3642                           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3643                              with a single element, which expands T.  */
3644                           tree vec = make_tree_vec (1);
3645                           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3646 #ifdef ENABLE_CHECKING
3647                           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3648                                 (vec, TREE_VEC_LENGTH (vec));
3649 #endif
3650                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3651                           
3652                           t  = make_node (NONTYPE_ARGUMENT_PACK);
3653                           SET_ARGUMENT_PACK_ARGS (t, vec);
3654                           TREE_TYPE (t) = type;
3655                         }
3656                     }
3657                   TREE_VEC_ELT (a, i) = t;
3658                 }
3659             }
3660         }
3661
3662 #ifdef ENABLE_CHECKING
3663       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
3664 #endif
3665
3666       if (length > 1)
3667         TREE_VEC_ELT (args, --l) = a;
3668       else
3669         args = a;
3670     }
3671
3672   return args;
3673 }
3674
3675 /* Update the declared TYPE by doing any lookups which were thought to be
3676    dependent, but are not now that we know the SCOPE of the declarator.  */
3677
3678 tree
3679 maybe_update_decl_type (tree orig_type, tree scope)
3680 {
3681   tree type = orig_type;
3682
3683   if (type == NULL_TREE)
3684     return type;
3685
3686   if (TREE_CODE (orig_type) == TYPE_DECL)
3687     type = TREE_TYPE (type);
3688
3689   if (scope && TYPE_P (scope) && dependent_type_p (scope)
3690       && dependent_type_p (type)
3691       /* Don't bother building up the args in this case.  */
3692       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
3693     {
3694       /* tsubst in the args corresponding to the template parameters,
3695          including auto if present.  Most things will be unchanged, but
3696          make_typename_type and tsubst_qualified_id will resolve
3697          TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
3698       tree args = current_template_args ();
3699       tree auto_node = type_uses_auto (type);
3700       if (auto_node)
3701         {
3702           tree auto_vec = make_tree_vec (1);
3703           TREE_VEC_ELT (auto_vec, 0) = auto_node;
3704           args = add_to_template_args (args, auto_vec);
3705         }
3706       push_scope (scope);
3707       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
3708       pop_scope (scope);
3709     }
3710
3711   if (type == error_mark_node)
3712     return orig_type;
3713
3714   if (TREE_CODE (orig_type) == TYPE_DECL)
3715     {
3716       if (same_type_p (type, TREE_TYPE (orig_type)))
3717         type = orig_type;
3718       else
3719         type = TYPE_NAME (type);
3720     }
3721   return type;
3722 }
3723
3724 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
3725    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
3726    a member template.  Used by push_template_decl below.  */
3727
3728 static tree
3729 build_template_decl (tree decl, tree parms, bool member_template_p)
3730 {
3731   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
3732   DECL_TEMPLATE_PARMS (tmpl) = parms;
3733   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
3734   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
3735
3736   return tmpl;
3737 }
3738
3739 struct template_parm_data
3740 {
3741   /* The level of the template parameters we are currently
3742      processing.  */
3743   int level;
3744
3745   /* The index of the specialization argument we are currently
3746      processing.  */
3747   int current_arg;
3748
3749   /* An array whose size is the number of template parameters.  The
3750      elements are nonzero if the parameter has been used in any one
3751      of the arguments processed so far.  */
3752   int* parms;
3753
3754   /* An array whose size is the number of template arguments.  The
3755      elements are nonzero if the argument makes use of template
3756      parameters of this level.  */
3757   int* arg_uses_template_parms;
3758 };
3759
3760 /* Subroutine of push_template_decl used to see if each template
3761    parameter in a partial specialization is used in the explicit
3762    argument list.  If T is of the LEVEL given in DATA (which is
3763    treated as a template_parm_data*), then DATA->PARMS is marked
3764    appropriately.  */
3765
3766 static int
3767 mark_template_parm (tree t, void* data)
3768 {
3769   int level;
3770   int idx;
3771   struct template_parm_data* tpd = (struct template_parm_data*) data;
3772
3773   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3774     {
3775       level = TEMPLATE_PARM_LEVEL (t);
3776       idx = TEMPLATE_PARM_IDX (t);
3777     }
3778   else
3779     {
3780       level = TEMPLATE_TYPE_LEVEL (t);
3781       idx = TEMPLATE_TYPE_IDX (t);
3782     }
3783
3784   if (level == tpd->level)
3785     {
3786       tpd->parms[idx] = 1;
3787       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
3788     }
3789
3790   /* Return zero so that for_each_template_parm will continue the
3791      traversal of the tree; we want to mark *every* template parm.  */
3792   return 0;
3793 }
3794
3795 /* Process the partial specialization DECL.  */
3796
3797 static tree
3798 process_partial_specialization (tree decl)
3799 {
3800   tree type = TREE_TYPE (decl);
3801   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
3802   tree specargs = CLASSTYPE_TI_ARGS (type);
3803   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
3804   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
3805   tree inner_parms;
3806   int nargs = TREE_VEC_LENGTH (inner_args);
3807   int ntparms;
3808   int  i;
3809   int did_error_intro = 0;
3810   struct template_parm_data tpd;
3811   struct template_parm_data tpd2;
3812
3813   gcc_assert (current_template_parms);
3814
3815   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3816   ntparms = TREE_VEC_LENGTH (inner_parms);
3817
3818   /* We check that each of the template parameters given in the
3819      partial specialization is used in the argument list to the
3820      specialization.  For example:
3821
3822        template <class T> struct S;
3823        template <class T> struct S<T*>;
3824
3825      The second declaration is OK because `T*' uses the template
3826      parameter T, whereas
3827
3828        template <class T> struct S<int>;
3829
3830      is no good.  Even trickier is:
3831
3832        template <class T>
3833        struct S1
3834        {
3835           template <class U>
3836           struct S2;
3837           template <class U>
3838           struct S2<T>;
3839        };
3840
3841      The S2<T> declaration is actually invalid; it is a
3842      full-specialization.  Of course,
3843
3844           template <class U>
3845           struct S2<T (*)(U)>;
3846
3847      or some such would have been OK.  */
3848   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
3849   tpd.parms = (int *) alloca (sizeof (int) * ntparms);
3850   memset (tpd.parms, 0, sizeof (int) * ntparms);
3851
3852   tpd.arg_uses_template_parms = (int *) alloca (sizeof (int) * nargs);
3853   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
3854   for (i = 0; i < nargs; ++i)
3855     {
3856       tpd.current_arg = i;
3857       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
3858                               &mark_template_parm,
3859                               &tpd,
3860                               NULL,
3861                               /*include_nondeduced_p=*/false);
3862     }
3863   for (i = 0; i < ntparms; ++i)
3864     if (tpd.parms[i] == 0)
3865       {
3866         /* One of the template parms was not used in the
3867            specialization.  */
3868         if (!did_error_intro)
3869           {
3870             error ("template parameters not used in partial specialization:");
3871             did_error_intro = 1;
3872           }
3873
3874         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
3875       }
3876
3877   /* [temp.class.spec]
3878
3879      The argument list of the specialization shall not be identical to
3880      the implicit argument list of the primary template.  */
3881   if (comp_template_args
3882       (inner_args,
3883        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
3884                                                    (maintmpl)))))
3885     error ("partial specialization %qT does not specialize any template arguments", type);
3886
3887   /* [temp.class.spec]
3888
3889      A partially specialized non-type argument expression shall not
3890      involve template parameters of the partial specialization except
3891      when the argument expression is a simple identifier.
3892
3893      The type of a template parameter corresponding to a specialized
3894      non-type argument shall not be dependent on a parameter of the
3895      specialization. 
3896
3897      Also, we verify that pack expansions only occur at the
3898      end of the argument list.  */
3899   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
3900   tpd2.parms = 0;
3901   for (i = 0; i < nargs; ++i)
3902     {
3903       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
3904       tree arg = TREE_VEC_ELT (inner_args, i);
3905       tree packed_args = NULL_TREE;
3906       int j, len = 1;
3907
3908       if (ARGUMENT_PACK_P (arg))
3909         {
3910           /* Extract the arguments from the argument pack. We'll be
3911              iterating over these in the following loop.  */
3912           packed_args = ARGUMENT_PACK_ARGS (arg);
3913           len = TREE_VEC_LENGTH (packed_args);
3914         }
3915
3916       for (j = 0; j < len; j++)
3917         {
3918           if (packed_args)
3919             /* Get the Jth argument in the parameter pack.  */
3920             arg = TREE_VEC_ELT (packed_args, j);
3921
3922           if (PACK_EXPANSION_P (arg))
3923             {
3924               /* Pack expansions must come at the end of the
3925                  argument list.  */
3926               if ((packed_args && j < len - 1)
3927                   || (!packed_args && i < nargs - 1))
3928                 {
3929                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3930                     error ("parameter pack argument %qE must be at the "
3931                            "end of the template argument list", arg);
3932                   else
3933                     error ("parameter pack argument %qT must be at the "
3934                            "end of the template argument list", arg);
3935                 }
3936             }
3937
3938           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3939             /* We only care about the pattern.  */
3940             arg = PACK_EXPANSION_PATTERN (arg);
3941
3942           if (/* These first two lines are the `non-type' bit.  */
3943               !TYPE_P (arg)
3944               && TREE_CODE (arg) != TEMPLATE_DECL
3945               /* This next line is the `argument expression is not just a
3946                  simple identifier' condition and also the `specialized
3947                  non-type argument' bit.  */
3948               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
3949             {
3950               if ((!packed_args && tpd.arg_uses_template_parms[i])
3951                   || (packed_args && uses_template_parms (arg)))
3952                 error ("template argument %qE involves template parameter(s)",
3953                        arg);
3954               else 
3955                 {
3956                   /* Look at the corresponding template parameter,
3957                      marking which template parameters its type depends
3958                      upon.  */
3959                   tree type = TREE_TYPE (parm);
3960
3961                   if (!tpd2.parms)
3962                     {
3963                       /* We haven't yet initialized TPD2.  Do so now.  */
3964                       tpd2.arg_uses_template_parms 
3965                         = (int *) alloca (sizeof (int) * nargs);
3966                       /* The number of parameters here is the number in the
3967                          main template, which, as checked in the assertion
3968                          above, is NARGS.  */
3969                       tpd2.parms = (int *) alloca (sizeof (int) * nargs);
3970                       tpd2.level = 
3971                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
3972                     }
3973
3974                   /* Mark the template parameters.  But this time, we're
3975                      looking for the template parameters of the main
3976                      template, not in the specialization.  */
3977                   tpd2.current_arg = i;
3978                   tpd2.arg_uses_template_parms[i] = 0;
3979                   memset (tpd2.parms, 0, sizeof (int) * nargs);
3980                   for_each_template_parm (type,
3981                                           &mark_template_parm,
3982                                           &tpd2,
3983                                           NULL,
3984                                           /*include_nondeduced_p=*/false);
3985
3986                   if (tpd2.arg_uses_template_parms [i])
3987                     {
3988                       /* The type depended on some template parameters.
3989                          If they are fully specialized in the
3990                          specialization, that's OK.  */
3991                       int j;
3992                       for (j = 0; j < nargs; ++j)
3993                         if (tpd2.parms[j] != 0
3994                             && tpd.arg_uses_template_parms [j])
3995                           {
3996                             error ("type %qT of template argument %qE depends "
3997                                    "on template parameter(s)", 
3998                                    type,
3999                                    arg);
4000                             break;
4001                           }
4002                     }
4003                 }
4004             }
4005         }
4006     }
4007
4008   /* We should only get here once.  */
4009   gcc_assert (!COMPLETE_TYPE_P (type));
4010
4011   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
4012     = tree_cons (specargs, inner_parms,
4013                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
4014   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
4015   return decl;
4016 }
4017
4018 /* Check that a template declaration's use of default arguments and
4019    parameter packs is not invalid.  Here, PARMS are the template
4020    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
4021    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
4022    specialization.
4023    
4024
4025    IS_FRIEND_DECL is nonzero if DECL is a friend function template
4026    declaration (but not a definition); 1 indicates a declaration, 2
4027    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
4028    emitted for extraneous default arguments.
4029
4030    Returns TRUE if there were no errors found, FALSE otherwise. */
4031
4032 bool
4033 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
4034                          int is_partial, int is_friend_decl)
4035 {
4036   const char *msg;
4037   int last_level_to_check;
4038   tree parm_level;
4039   bool no_errors = true;
4040
4041   /* [temp.param]
4042
4043      A default template-argument shall not be specified in a
4044      function template declaration or a function template definition, nor
4045      in the template-parameter-list of the definition of a member of a
4046      class template.  */
4047
4048   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
4049     /* You can't have a function template declaration in a local
4050        scope, nor you can you define a member of a class template in a
4051        local scope.  */
4052     return true;
4053
4054   if (current_class_type
4055       && !TYPE_BEING_DEFINED (current_class_type)
4056       && DECL_LANG_SPECIFIC (decl)
4057       && DECL_DECLARES_FUNCTION_P (decl)
4058       /* If this is either a friend defined in the scope of the class
4059          or a member function.  */
4060       && (DECL_FUNCTION_MEMBER_P (decl)
4061           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
4062           : DECL_FRIEND_CONTEXT (decl)
4063           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
4064           : false)
4065       /* And, if it was a member function, it really was defined in
4066          the scope of the class.  */
4067       && (!DECL_FUNCTION_MEMBER_P (decl)
4068           || DECL_INITIALIZED_IN_CLASS_P (decl)))
4069     /* We already checked these parameters when the template was
4070        declared, so there's no need to do it again now.  This function
4071        was defined in class scope, but we're processing it's body now
4072        that the class is complete.  */
4073     return true;
4074
4075   /* Core issue 226 (C++0x only): the following only applies to class
4076      templates.  */
4077   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
4078     {
4079       /* [temp.param]
4080
4081          If a template-parameter has a default template-argument, all
4082          subsequent template-parameters shall have a default
4083          template-argument supplied.  */
4084       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
4085         {
4086           tree inner_parms = TREE_VALUE (parm_level);
4087           int ntparms = TREE_VEC_LENGTH (inner_parms);
4088           int seen_def_arg_p = 0;
4089           int i;
4090
4091           for (i = 0; i < ntparms; ++i)
4092             {
4093               tree parm = TREE_VEC_ELT (inner_parms, i);
4094
4095               if (parm == error_mark_node)
4096                 continue;
4097
4098               if (TREE_PURPOSE (parm))
4099                 seen_def_arg_p = 1;
4100               else if (seen_def_arg_p
4101                        && !template_parameter_pack_p (TREE_VALUE (parm)))
4102                 {
4103                   error ("no default argument for %qD", TREE_VALUE (parm));
4104                   /* For better subsequent error-recovery, we indicate that
4105                      there should have been a default argument.  */
4106                   TREE_PURPOSE (parm) = error_mark_node;
4107                   no_errors = false;
4108                 }
4109               else if (is_primary
4110                        && !is_partial
4111                        && !is_friend_decl
4112                        /* Don't complain about an enclosing partial
4113                           specialization.  */
4114                        && parm_level == parms
4115                        && TREE_CODE (decl) == TYPE_DECL
4116                        && i < ntparms - 1
4117                        && template_parameter_pack_p (TREE_VALUE (parm)))
4118                 {
4119                   /* A primary class template can only have one
4120                      parameter pack, at the end of the template
4121                      parameter list.  */
4122
4123                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
4124                     error ("parameter pack %qE must be at the end of the"
4125                            " template parameter list", TREE_VALUE (parm));
4126                   else
4127                     error ("parameter pack %qT must be at the end of the"
4128                            " template parameter list", 
4129                            TREE_TYPE (TREE_VALUE (parm)));
4130
4131                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
4132                     = error_mark_node;
4133                   no_errors = false;
4134                 }
4135             }
4136         }
4137     }
4138
4139   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
4140       || is_partial 
4141       || !is_primary
4142       || is_friend_decl)
4143     /* For an ordinary class template, default template arguments are
4144        allowed at the innermost level, e.g.:
4145          template <class T = int>
4146          struct S {};
4147        but, in a partial specialization, they're not allowed even
4148        there, as we have in [temp.class.spec]:
4149
4150          The template parameter list of a specialization shall not
4151          contain default template argument values.
4152
4153        So, for a partial specialization, or for a function template
4154        (in C++98/C++03), we look at all of them.  */
4155     ;
4156   else
4157     /* But, for a primary class template that is not a partial
4158        specialization we look at all template parameters except the
4159        innermost ones.  */
4160     parms = TREE_CHAIN (parms);
4161
4162   /* Figure out what error message to issue.  */
4163   if (is_friend_decl == 2)
4164     msg = G_("default template arguments may not be used in function template "
4165              "friend re-declaration");
4166   else if (is_friend_decl)
4167     msg = G_("default template arguments may not be used in function template "
4168              "friend declarations");
4169   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
4170     msg = G_("default template arguments may not be used in function templates "
4171              "without -std=c++0x or -std=gnu++0x");
4172   else if (is_partial)
4173     msg = G_("default template arguments may not be used in "
4174              "partial specializations");
4175   else
4176     msg = G_("default argument for template parameter for class enclosing %qD");
4177
4178   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
4179     /* If we're inside a class definition, there's no need to
4180        examine the parameters to the class itself.  On the one
4181        hand, they will be checked when the class is defined, and,
4182        on the other, default arguments are valid in things like:
4183          template <class T = double>
4184          struct S { template <class U> void f(U); };
4185        Here the default argument for `S' has no bearing on the
4186        declaration of `f'.  */
4187     last_level_to_check = template_class_depth (current_class_type) + 1;
4188   else
4189     /* Check everything.  */
4190     last_level_to_check = 0;
4191
4192   for (parm_level = parms;
4193        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
4194        parm_level = TREE_CHAIN (parm_level))
4195     {
4196       tree inner_parms = TREE_VALUE (parm_level);
4197       int i;
4198       int ntparms;
4199
4200       ntparms = TREE_VEC_LENGTH (inner_parms);
4201       for (i = 0; i < ntparms; ++i)
4202         {
4203           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
4204             continue;
4205
4206           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
4207             {
4208               if (msg)
4209                 {
4210                   no_errors = false;
4211                   if (is_friend_decl == 2)
4212                     return no_errors;
4213
4214                   error (msg, decl);
4215                   msg = 0;
4216                 }
4217
4218               /* Clear out the default argument so that we are not
4219                  confused later.  */
4220               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
4221             }
4222         }
4223
4224       /* At this point, if we're still interested in issuing messages,
4225          they must apply to classes surrounding the object declared.  */
4226       if (msg)
4227         msg = G_("default argument for template parameter for class "
4228                  "enclosing %qD");
4229     }
4230
4231   return no_errors;
4232 }
4233
4234 /* Worker for push_template_decl_real, called via
4235    for_each_template_parm.  DATA is really an int, indicating the
4236    level of the parameters we are interested in.  If T is a template
4237    parameter of that level, return nonzero.  */
4238
4239 static int
4240 template_parm_this_level_p (tree t, void* data)
4241 {
4242   int this_level = *(int *)data;
4243   int level;
4244
4245   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4246     level = TEMPLATE_PARM_LEVEL (t);
4247   else
4248     level = TEMPLATE_TYPE_LEVEL (t);
4249   return level == this_level;
4250 }
4251
4252 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
4253    parameters given by current_template_args, or reuses a
4254    previously existing one, if appropriate.  Returns the DECL, or an
4255    equivalent one, if it is replaced via a call to duplicate_decls.
4256
4257    If IS_FRIEND is true, DECL is a friend declaration.  */
4258
4259 tree
4260 push_template_decl_real (tree decl, bool is_friend)
4261 {
4262   tree tmpl;
4263   tree args;
4264   tree info;
4265   tree ctx;
4266   int primary;
4267   int is_partial;
4268   int new_template_p = 0;
4269   /* True if the template is a member template, in the sense of
4270      [temp.mem].  */
4271   bool member_template_p = false;
4272
4273   if (decl == error_mark_node || !current_template_parms)
4274     return error_mark_node;
4275
4276   /* See if this is a partial specialization.  */
4277   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
4278                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
4279                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
4280
4281   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
4282     is_friend = true;
4283
4284   if (is_friend)
4285     /* For a friend, we want the context of the friend function, not
4286        the type of which it is a friend.  */
4287     ctx = DECL_CONTEXT (decl);
4288   else if (CP_DECL_CONTEXT (decl)
4289            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
4290     /* In the case of a virtual function, we want the class in which
4291        it is defined.  */
4292     ctx = CP_DECL_CONTEXT (decl);
4293   else
4294     /* Otherwise, if we're currently defining some class, the DECL
4295        is assumed to be a member of the class.  */
4296     ctx = current_scope ();
4297
4298   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
4299     ctx = NULL_TREE;
4300
4301   if (!DECL_CONTEXT (decl))
4302     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4303
4304   /* See if this is a primary template.  */
4305   if (is_friend && ctx)
4306     /* A friend template that specifies a class context, i.e.
4307          template <typename T> friend void A<T>::f();
4308        is not primary.  */
4309     primary = 0;
4310   else
4311     primary = template_parm_scope_p ();
4312
4313   if (primary)
4314     {
4315       if (DECL_CLASS_SCOPE_P (decl))
4316         member_template_p = true;
4317       if (TREE_CODE (decl) == TYPE_DECL
4318           && ANON_AGGRNAME_P (DECL_NAME (decl)))
4319         {
4320           error ("template class without a name");
4321           return error_mark_node;
4322         }
4323       else if (TREE_CODE (decl) == FUNCTION_DECL)
4324         {
4325           if (DECL_DESTRUCTOR_P (decl))
4326             {
4327               /* [temp.mem]
4328
4329                  A destructor shall not be a member template.  */
4330               error ("destructor %qD declared as member template", decl);
4331               return error_mark_node;
4332             }
4333           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
4334               && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
4335                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
4336                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
4337                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
4338                       == void_list_node)))
4339             {
4340               /* [basic.stc.dynamic.allocation]
4341
4342                  An allocation function can be a function
4343                  template. ... Template allocation functions shall
4344                  have two or more parameters.  */
4345               error ("invalid template declaration of %qD", decl);
4346               return error_mark_node;
4347             }
4348         }
4349       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4350                && CLASS_TYPE_P (TREE_TYPE (decl)))
4351         /* OK */;
4352       else
4353         {
4354           error ("template declaration of %q#D", decl);
4355           return error_mark_node;
4356         }
4357     }
4358
4359   /* Check to see that the rules regarding the use of default
4360      arguments are not being violated.  */
4361   check_default_tmpl_args (decl, current_template_parms,
4362                            primary, is_partial, /*is_friend_decl=*/0);
4363
4364   /* Ensure that there are no parameter packs in the type of this
4365      declaration that have not been expanded.  */
4366   if (TREE_CODE (decl) == FUNCTION_DECL)
4367     {
4368       /* Check each of the arguments individually to see if there are
4369          any bare parameter packs.  */
4370       tree type = TREE_TYPE (decl);
4371       tree arg = DECL_ARGUMENTS (decl);
4372       tree argtype = TYPE_ARG_TYPES (type);
4373
4374       while (arg && argtype)
4375         {
4376           if (!FUNCTION_PARAMETER_PACK_P (arg)
4377               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
4378             {
4379             /* This is a PARM_DECL that contains unexpanded parameter
4380                packs. We have already complained about this in the
4381                check_for_bare_parameter_packs call, so just replace
4382                these types with ERROR_MARK_NODE.  */
4383               TREE_TYPE (arg) = error_mark_node;
4384               TREE_VALUE (argtype) = error_mark_node;
4385             }
4386
4387           arg = TREE_CHAIN (arg);
4388           argtype = TREE_CHAIN (argtype);
4389         }
4390
4391       /* Check for bare parameter packs in the return type and the
4392          exception specifiers.  */
4393       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
4394         /* Errors were already issued, set return type to int
4395            as the frontend doesn't expect error_mark_node as
4396            the return type.  */
4397         TREE_TYPE (type) = integer_type_node;
4398       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
4399         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
4400     }
4401   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
4402     {
4403       TREE_TYPE (decl) = error_mark_node;
4404       return error_mark_node;
4405     }
4406
4407   if (is_partial)
4408     return process_partial_specialization (decl);
4409
4410   args = current_template_args ();
4411
4412   if (!ctx
4413       || TREE_CODE (ctx) == FUNCTION_DECL
4414       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
4415       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
4416     {
4417       if (DECL_LANG_SPECIFIC (decl)
4418           && DECL_TEMPLATE_INFO (decl)
4419           && DECL_TI_TEMPLATE (decl))
4420         tmpl = DECL_TI_TEMPLATE (decl);
4421       /* If DECL is a TYPE_DECL for a class-template, then there won't
4422          be DECL_LANG_SPECIFIC.  The information equivalent to
4423          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
4424       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4425                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
4426                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
4427         {
4428           /* Since a template declaration already existed for this
4429              class-type, we must be redeclaring it here.  Make sure
4430              that the redeclaration is valid.  */
4431           redeclare_class_template (TREE_TYPE (decl),
4432                                     current_template_parms);
4433           /* We don't need to create a new TEMPLATE_DECL; just use the
4434              one we already had.  */
4435           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
4436         }
4437       else
4438         {
4439           tmpl = build_template_decl (decl, current_template_parms,
4440                                       member_template_p);
4441           new_template_p = 1;
4442
4443           if (DECL_LANG_SPECIFIC (decl)
4444               && DECL_TEMPLATE_SPECIALIZATION (decl))
4445             {
4446               /* A specialization of a member template of a template
4447                  class.  */
4448               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4449               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
4450               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
4451             }
4452         }
4453     }
4454   else
4455     {
4456       tree a, t, current, parms;
4457       int i;
4458       tree tinfo = get_template_info (decl);
4459
4460       if (!tinfo)
4461         {
4462           error ("template definition of non-template %q#D", decl);
4463           return error_mark_node;
4464         }
4465
4466       tmpl = TI_TEMPLATE (tinfo);
4467
4468       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
4469           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
4470           && DECL_TEMPLATE_SPECIALIZATION (decl)
4471           && DECL_MEMBER_TEMPLATE_P (tmpl))
4472         {
4473           tree new_tmpl;
4474
4475           /* The declaration is a specialization of a member
4476              template, declared outside the class.  Therefore, the
4477              innermost template arguments will be NULL, so we
4478              replace them with the arguments determined by the
4479              earlier call to check_explicit_specialization.  */
4480           args = DECL_TI_ARGS (decl);
4481
4482           new_tmpl
4483             = build_template_decl (decl, current_template_parms,
4484                                    member_template_p);
4485           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4486           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4487           DECL_TI_TEMPLATE (decl) = new_tmpl;
4488           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4489           DECL_TEMPLATE_INFO (new_tmpl)
4490             = build_template_info (tmpl, args);
4491
4492           register_specialization (new_tmpl,
4493                                    most_general_template (tmpl),
4494                                    args,
4495                                    is_friend, 0);
4496           return decl;
4497         }
4498
4499       /* Make sure the template headers we got make sense.  */
4500
4501       parms = DECL_TEMPLATE_PARMS (tmpl);
4502       i = TMPL_PARMS_DEPTH (parms);
4503       if (TMPL_ARGS_DEPTH (args) != i)
4504         {
4505           error ("expected %d levels of template parms for %q#D, got %d",
4506                  i, decl, TMPL_ARGS_DEPTH (args));
4507         }
4508       else
4509         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4510           {
4511             a = TMPL_ARGS_LEVEL (args, i);
4512             t = INNERMOST_TEMPLATE_PARMS (parms);
4513
4514             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4515               {
4516                 if (current == decl)
4517                   error ("got %d template parameters for %q#D",
4518                          TREE_VEC_LENGTH (a), decl);
4519                 else
4520                   error ("got %d template parameters for %q#T",
4521                          TREE_VEC_LENGTH (a), current);
4522                 error ("  but %d required", TREE_VEC_LENGTH (t));
4523                 return error_mark_node;
4524               }
4525
4526             if (current == decl)
4527               current = ctx;
4528             else
4529               current = (TYPE_P (current)
4530                          ? TYPE_CONTEXT (current)
4531                          : DECL_CONTEXT (current));
4532           }
4533
4534       /* Check that the parms are used in the appropriate qualifying scopes
4535          in the declarator.  */
4536       if (!comp_template_args
4537           (TI_ARGS (tinfo),
4538            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4539         {
4540           error ("\
4541 template arguments to %qD do not match original template %qD",
4542                  decl, DECL_TEMPLATE_RESULT (tmpl));
4543           if (!uses_template_parms (TI_ARGS (tinfo)))
4544             inform (input_location, "use template<> for an explicit specialization");
4545           /* Avoid crash in import_export_decl.  */
4546           DECL_INTERFACE_KNOWN (decl) = 1;
4547           return error_mark_node;
4548         }
4549     }
4550
4551   DECL_TEMPLATE_RESULT (tmpl) = decl;
4552   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4553
4554   /* Push template declarations for global functions and types.  Note
4555      that we do not try to push a global template friend declared in a
4556      template class; such a thing may well depend on the template
4557      parameters of the class.  */
4558   if (new_template_p && !ctx
4559       && !(is_friend && template_class_depth (current_class_type) > 0))
4560     {
4561       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4562       if (tmpl == error_mark_node)
4563         return error_mark_node;
4564
4565       /* Hide template friend classes that haven't been declared yet.  */
4566       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4567         {
4568           DECL_ANTICIPATED (tmpl) = 1;
4569           DECL_FRIEND_P (tmpl) = 1;
4570         }
4571     }
4572
4573   if (primary)
4574     {
4575       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4576       int i;
4577
4578       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4579       if (DECL_CONV_FN_P (tmpl))
4580         {
4581           int depth = TMPL_PARMS_DEPTH (parms);
4582
4583           /* It is a conversion operator. See if the type converted to
4584              depends on innermost template operands.  */
4585
4586           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4587                                          depth))
4588             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4589         }
4590
4591       /* Give template template parms a DECL_CONTEXT of the template
4592          for which they are a parameter.  */
4593       parms = INNERMOST_TEMPLATE_PARMS (parms);
4594       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
4595         {
4596           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4597           if (TREE_CODE (parm) == TEMPLATE_DECL)
4598             DECL_CONTEXT (parm) = tmpl;
4599
4600           if (TREE_CODE (TREE_TYPE (parm)) == TEMPLATE_TYPE_PARM)
4601             DECL_CONTEXT (TYPE_NAME (TREE_TYPE (parm))) = tmpl;
4602         }
4603     }
4604
4605   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
4606      back to its most general template.  If TMPL is a specialization,
4607      ARGS may only have the innermost set of arguments.  Add the missing
4608      argument levels if necessary.  */
4609   if (DECL_TEMPLATE_INFO (tmpl))
4610     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
4611
4612   info = build_template_info (tmpl, args);
4613
4614   if (DECL_IMPLICIT_TYPEDEF_P (decl))
4615     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
4616   else if (DECL_LANG_SPECIFIC (decl))
4617     DECL_TEMPLATE_INFO (decl) = info;
4618
4619   return DECL_TEMPLATE_RESULT (tmpl);
4620 }
4621
4622 tree
4623 push_template_decl (tree decl)
4624 {
4625   return push_template_decl_real (decl, false);
4626 }
4627
4628 /* Called when a class template TYPE is redeclared with the indicated
4629    template PARMS, e.g.:
4630
4631      template <class T> struct S;
4632      template <class T> struct S {};  */
4633
4634 bool
4635 redeclare_class_template (tree type, tree parms)
4636 {
4637   tree tmpl;
4638   tree tmpl_parms;
4639   int i;
4640
4641   if (!TYPE_TEMPLATE_INFO (type))
4642     {
4643       error ("%qT is not a template type", type);
4644       return false;
4645     }
4646
4647   tmpl = TYPE_TI_TEMPLATE (type);
4648   if (!PRIMARY_TEMPLATE_P (tmpl))
4649     /* The type is nested in some template class.  Nothing to worry
4650        about here; there are no new template parameters for the nested
4651        type.  */
4652     return true;
4653
4654   if (!parms)
4655     {
4656       error ("template specifiers not specified in declaration of %qD",
4657              tmpl);
4658       return false;
4659     }
4660
4661   parms = INNERMOST_TEMPLATE_PARMS (parms);
4662   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
4663
4664   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
4665     {
4666       error ("redeclared with %d template parameter(s)", 
4667              TREE_VEC_LENGTH (parms));
4668       inform (input_location, "previous declaration %q+D used %d template parameter(s)", 
4669              tmpl, TREE_VEC_LENGTH (tmpl_parms));
4670       return false;
4671     }
4672
4673   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
4674     {
4675       tree tmpl_parm;
4676       tree parm;
4677       tree tmpl_default;
4678       tree parm_default;
4679
4680       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
4681           || TREE_VEC_ELT (parms, i) == error_mark_node)
4682         continue;
4683
4684       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
4685       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4686       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
4687       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
4688
4689       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
4690          TEMPLATE_DECL.  */
4691       if (tmpl_parm != error_mark_node
4692           && (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
4693               || (TREE_CODE (tmpl_parm) != TYPE_DECL
4694                   && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
4695               || (TREE_CODE (tmpl_parm) != PARM_DECL
4696                   && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
4697                       != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
4698               || (TREE_CODE (tmpl_parm) == PARM_DECL
4699                   && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
4700                       != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm))))))
4701         {
4702           error ("template parameter %q+#D", tmpl_parm);
4703           error ("redeclared here as %q#D", parm);
4704           return false;
4705         }
4706
4707       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
4708         {
4709           /* We have in [temp.param]:
4710
4711              A template-parameter may not be given default arguments
4712              by two different declarations in the same scope.  */
4713           error_at (input_location, "redefinition of default argument for %q#D", parm);
4714           inform (DECL_SOURCE_LOCATION (tmpl_parm),
4715                   "original definition appeared here");
4716           return false;
4717         }
4718
4719       if (parm_default != NULL_TREE)
4720         /* Update the previous template parameters (which are the ones
4721            that will really count) with the new default value.  */
4722         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
4723       else if (tmpl_default != NULL_TREE)
4724         /* Update the new parameters, too; they'll be used as the
4725            parameters for any members.  */
4726         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
4727     }
4728
4729     return true;
4730 }
4731
4732 /* Simplify EXPR if it is a non-dependent expression.  Returns the
4733    (possibly simplified) expression.  */
4734
4735 tree
4736 fold_non_dependent_expr (tree expr)
4737 {
4738   if (expr == NULL_TREE)
4739     return NULL_TREE;
4740
4741   /* If we're in a template, but EXPR isn't value dependent, simplify
4742      it.  We're supposed to treat:
4743
4744        template <typename T> void f(T[1 + 1]);
4745        template <typename T> void f(T[2]);
4746
4747      as two declarations of the same function, for example.  */
4748   if (processing_template_decl
4749       && !type_dependent_expression_p (expr)
4750       && !value_dependent_expression_p (expr))
4751     {
4752       HOST_WIDE_INT saved_processing_template_decl;
4753
4754       saved_processing_template_decl = processing_template_decl;
4755       processing_template_decl = 0;
4756       expr = tsubst_copy_and_build (expr,
4757                                     /*args=*/NULL_TREE,
4758                                     tf_error,
4759                                     /*in_decl=*/NULL_TREE,
4760                                     /*function_p=*/false,
4761                                     /*integral_constant_expression_p=*/true);
4762       processing_template_decl = saved_processing_template_decl;
4763     }
4764   return expr;
4765 }
4766
4767 /* EXPR is an expression which is used in a constant-expression context.
4768    For instance, it could be a VAR_DECL with a constant initializer.
4769    Extract the innermost constant expression.
4770
4771    This is basically a more powerful version of
4772    integral_constant_value, which can be used also in templates where
4773    initializers can maintain a syntactic rather than semantic form
4774    (even if they are non-dependent, for access-checking purposes).  */
4775
4776 static tree
4777 fold_decl_constant_value (tree expr)
4778 {
4779   tree const_expr = expr;
4780   do
4781     {
4782       expr = fold_non_dependent_expr (const_expr);
4783       const_expr = integral_constant_value (expr);
4784     }
4785   while (expr != const_expr);
4786
4787   return expr;
4788 }
4789
4790 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
4791    must be a function or a pointer-to-function type, as specified
4792    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
4793    and check that the resulting function has external linkage.  */
4794
4795 static tree
4796 convert_nontype_argument_function (tree type, tree expr)
4797 {
4798   tree fns = expr;
4799   tree fn, fn_no_ptr;
4800
4801   fn = instantiate_type (type, fns, tf_none);
4802   if (fn == error_mark_node)
4803     return error_mark_node;
4804
4805   fn_no_ptr = fn;
4806   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
4807     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
4808   if (TREE_CODE (fn_no_ptr) == BASELINK)
4809     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
4810  
4811   /* [temp.arg.nontype]/1
4812
4813      A template-argument for a non-type, non-template template-parameter
4814      shall be one of:
4815      [...]
4816      -- the address of an object or function with external linkage.  */
4817   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
4818     {
4819       error ("%qE is not a valid template argument for type %qT "
4820              "because function %qD has not external linkage",
4821              expr, type, fn_no_ptr);
4822       return NULL_TREE;
4823     }
4824
4825   return fn;
4826 }
4827
4828 /* Subroutine of convert_nontype_argument.
4829    Check if EXPR of type TYPE is a valid pointer-to-member constant.
4830    Emit an error otherwise.  */
4831
4832 static bool
4833 check_valid_ptrmem_cst_expr (tree type, tree expr)
4834 {
4835   STRIP_NOPS (expr);
4836   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
4837     return true;
4838   error ("%qE is not a valid template argument for type %qT",
4839          expr, type);
4840   error ("it must be a pointer-to-member of the form `&X::Y'");
4841   return false;
4842 }
4843
4844 /* Attempt to convert the non-type template parameter EXPR to the
4845    indicated TYPE.  If the conversion is successful, return the
4846    converted value.  If the conversion is unsuccessful, return
4847    NULL_TREE if we issued an error message, or error_mark_node if we
4848    did not.  We issue error messages for out-and-out bad template
4849    parameters, but not simply because the conversion failed, since we
4850    might be just trying to do argument deduction.  Both TYPE and EXPR
4851    must be non-dependent.
4852
4853    The conversion follows the special rules described in
4854    [temp.arg.nontype], and it is much more strict than an implicit
4855    conversion.
4856
4857    This function is called twice for each template argument (see
4858    lookup_template_class for a more accurate description of this
4859    problem). This means that we need to handle expressions which
4860    are not valid in a C++ source, but can be created from the
4861    first call (for instance, casts to perform conversions). These
4862    hacks can go away after we fix the double coercion problem.  */
4863
4864 static tree
4865 convert_nontype_argument (tree type, tree expr)
4866 {
4867   tree expr_type;
4868
4869   /* Detect immediately string literals as invalid non-type argument.
4870      This special-case is not needed for correctness (we would easily
4871      catch this later), but only to provide better diagnostic for this
4872      common user mistake. As suggested by DR 100, we do not mention
4873      linkage issues in the diagnostic as this is not the point.  */
4874   if (TREE_CODE (expr) == STRING_CST)
4875     {
4876       error ("%qE is not a valid template argument for type %qT "
4877              "because string literals can never be used in this context",
4878              expr, type);
4879       return NULL_TREE;
4880     }
4881
4882   /* If we are in a template, EXPR may be non-dependent, but still
4883      have a syntactic, rather than semantic, form.  For example, EXPR
4884      might be a SCOPE_REF, rather than the VAR_DECL to which the
4885      SCOPE_REF refers.  Preserving the qualifying scope is necessary
4886      so that access checking can be performed when the template is
4887      instantiated -- but here we need the resolved form so that we can
4888      convert the argument.  */
4889   expr = fold_non_dependent_expr (expr);
4890   if (error_operand_p (expr))
4891     return error_mark_node;
4892   expr_type = TREE_TYPE (expr);
4893
4894   /* HACK: Due to double coercion, we can get a
4895      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
4896      which is the tree that we built on the first call (see
4897      below when coercing to reference to object or to reference to
4898      function). We just strip everything and get to the arg.
4899      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
4900      for examples.  */
4901   if (TREE_CODE (expr) == NOP_EXPR)
4902     {
4903       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
4904         {
4905           /* ??? Maybe we could use convert_from_reference here, but we
4906              would need to relax its constraints because the NOP_EXPR
4907              could actually change the type to something more cv-qualified,
4908              and this is not folded by convert_from_reference.  */
4909           tree addr = TREE_OPERAND (expr, 0);
4910           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
4911           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
4912           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
4913           gcc_assert (same_type_ignoring_top_level_qualifiers_p
4914                       (TREE_TYPE (expr_type),
4915                        TREE_TYPE (TREE_TYPE (addr))));
4916
4917           expr = TREE_OPERAND (addr, 0);
4918           expr_type = TREE_TYPE (expr);
4919         }
4920
4921       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
4922          parameter is a pointer to object, through decay and
4923          qualification conversion. Let's strip everything.  */
4924       else if (TYPE_PTROBV_P (type))
4925         {
4926           STRIP_NOPS (expr);
4927           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
4928           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
4929           /* Skip the ADDR_EXPR only if it is part of the decay for
4930              an array. Otherwise, it is part of the original argument
4931              in the source code.  */
4932           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
4933             expr = TREE_OPERAND (expr, 0);
4934           expr_type = TREE_TYPE (expr);
4935         }
4936     }
4937
4938   /* [temp.arg.nontype]/5, bullet 1
4939
4940      For a non-type template-parameter of integral or enumeration type,
4941      integral promotions (_conv.prom_) and integral conversions
4942      (_conv.integral_) are applied.  */
4943   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
4944     {
4945       if (!INTEGRAL_OR_ENUMERATION_TYPE_P (expr_type))
4946         return error_mark_node;
4947
4948       expr = fold_decl_constant_value (expr);
4949       /* Notice that there are constant expressions like '4 % 0' which
4950          do not fold into integer constants.  */
4951       if (TREE_CODE (expr) != INTEGER_CST)
4952         {
4953           error ("%qE is not a valid template argument for type %qT "
4954                  "because it is a non-constant expression", expr, type);
4955           return NULL_TREE;
4956         }
4957
4958       /* At this point, an implicit conversion does what we want,
4959          because we already know that the expression is of integral
4960          type.  */
4961       expr = ocp_convert (type, expr, CONV_IMPLICIT, LOOKUP_PROTECT);
4962       if (expr == error_mark_node)
4963         return error_mark_node;
4964
4965       /* Conversion was allowed: fold it to a bare integer constant.  */
4966       expr = fold (expr);
4967     }
4968   /* [temp.arg.nontype]/5, bullet 2
4969
4970      For a non-type template-parameter of type pointer to object,
4971      qualification conversions (_conv.qual_) and the array-to-pointer
4972      conversion (_conv.array_) are applied.  */
4973   else if (TYPE_PTROBV_P (type))
4974     {
4975       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
4976
4977          A template-argument for a non-type, non-template template-parameter
4978          shall be one of: [...]
4979
4980          -- the name of a non-type template-parameter;
4981          -- the address of an object or function with external linkage, [...]
4982             expressed as "& id-expression" where the & is optional if the name
4983             refers to a function or array, or if the corresponding
4984             template-parameter is a reference.
4985
4986         Here, we do not care about functions, as they are invalid anyway
4987         for a parameter of type pointer-to-object.  */
4988
4989       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
4990         /* Non-type template parameters are OK.  */
4991         ;
4992       else if (TREE_CODE (expr) != ADDR_EXPR
4993                && TREE_CODE (expr_type) != ARRAY_TYPE)
4994         {
4995           if (TREE_CODE (expr) == VAR_DECL)
4996             {
4997               error ("%qD is not a valid template argument "
4998                      "because %qD is a variable, not the address of "
4999                      "a variable",
5000                      expr, expr);
5001               return NULL_TREE;
5002             }
5003           /* Other values, like integer constants, might be valid
5004              non-type arguments of some other type.  */
5005           return error_mark_node;
5006         }
5007       else
5008         {
5009           tree decl;
5010
5011           decl = ((TREE_CODE (expr) == ADDR_EXPR)
5012                   ? TREE_OPERAND (expr, 0) : expr);
5013           if (TREE_CODE (decl) != VAR_DECL)
5014             {
5015               error ("%qE is not a valid template argument of type %qT "
5016                      "because %qE is not a variable",
5017                      expr, type, decl);
5018               return NULL_TREE;
5019             }
5020           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
5021             {
5022               error ("%qE is not a valid template argument of type %qT "
5023                      "because %qD does not have external linkage",
5024                      expr, type, decl);
5025               return NULL_TREE;
5026             }
5027         }
5028
5029       expr = decay_conversion (expr);
5030       if (expr == error_mark_node)
5031         return error_mark_node;
5032
5033       expr = perform_qualification_conversions (type, expr);
5034       if (expr == error_mark_node)
5035         return error_mark_node;
5036     }
5037   /* [temp.arg.nontype]/5, bullet 3
5038
5039      For a non-type template-parameter of type reference to object, no
5040      conversions apply. The type referred to by the reference may be more
5041      cv-qualified than the (otherwise identical) type of the
5042      template-argument. The template-parameter is bound directly to the
5043      template-argument, which must be an lvalue.  */
5044   else if (TYPE_REF_OBJ_P (type))
5045     {
5046       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
5047                                                       expr_type))
5048         return error_mark_node;
5049
5050       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
5051         {
5052           error ("%qE is not a valid template argument for type %qT "
5053                  "because of conflicts in cv-qualification", expr, type);
5054           return NULL_TREE;
5055         }
5056
5057       if (!real_lvalue_p (expr))
5058         {
5059           error ("%qE is not a valid template argument for type %qT "
5060                  "because it is not an lvalue", expr, type);
5061           return NULL_TREE;
5062         }
5063
5064       /* [temp.arg.nontype]/1
5065
5066          A template-argument for a non-type, non-template template-parameter
5067          shall be one of: [...]
5068
5069          -- the address of an object or function with external linkage.  */
5070       if (TREE_CODE (expr) == INDIRECT_REF
5071           && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
5072         {
5073           expr = TREE_OPERAND (expr, 0);
5074           if (DECL_P (expr))
5075             {
5076               error ("%q#D is not a valid template argument for type %qT "
5077                      "because a reference variable does not have a constant "
5078                      "address", expr, type);
5079               return NULL_TREE;
5080             }
5081         }
5082
5083       if (!DECL_P (expr))
5084         {
5085           error ("%qE is not a valid template argument for type %qT "
5086                  "because it is not an object with external linkage",
5087                  expr, type);
5088           return NULL_TREE;
5089         }
5090
5091       if (!DECL_EXTERNAL_LINKAGE_P (expr))
5092         {
5093           error ("%qE is not a valid template argument for type %qT "
5094                  "because object %qD has not external linkage",
5095                  expr, type, expr);
5096           return NULL_TREE;
5097         }
5098
5099       expr = build_nop (type, build_address (expr));
5100     }
5101   /* [temp.arg.nontype]/5, bullet 4
5102
5103      For a non-type template-parameter of type pointer to function, only
5104      the function-to-pointer conversion (_conv.func_) is applied. If the
5105      template-argument represents a set of overloaded functions (or a
5106      pointer to such), the matching function is selected from the set
5107      (_over.over_).  */
5108   else if (TYPE_PTRFN_P (type))
5109     {
5110       /* If the argument is a template-id, we might not have enough
5111          context information to decay the pointer.  */
5112       if (!type_unknown_p (expr_type))
5113         {
5114           expr = decay_conversion (expr);
5115           if (expr == error_mark_node)
5116             return error_mark_node;
5117         }
5118
5119       expr = convert_nontype_argument_function (type, expr);
5120       if (!expr || expr == error_mark_node)
5121         return expr;
5122
5123       if (TREE_CODE (expr) != ADDR_EXPR)
5124         {
5125           error ("%qE is not a valid template argument for type %qT", expr, type);
5126           error ("it must be the address of a function with external linkage");
5127           return NULL_TREE;
5128         }
5129     }
5130   /* [temp.arg.nontype]/5, bullet 5
5131
5132      For a non-type template-parameter of type reference to function, no
5133      conversions apply. If the template-argument represents a set of
5134      overloaded functions, the matching function is selected from the set
5135      (_over.over_).  */
5136   else if (TYPE_REFFN_P (type))
5137     {
5138       if (TREE_CODE (expr) == ADDR_EXPR)
5139         {
5140           error ("%qE is not a valid template argument for type %qT "
5141                  "because it is a pointer", expr, type);
5142           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
5143           return NULL_TREE;
5144         }
5145
5146       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
5147       if (!expr || expr == error_mark_node)
5148         return expr;
5149
5150       expr = build_nop (type, build_address (expr));
5151     }
5152   /* [temp.arg.nontype]/5, bullet 6
5153
5154      For a non-type template-parameter of type pointer to member function,
5155      no conversions apply. If the template-argument represents a set of
5156      overloaded member functions, the matching member function is selected
5157      from the set (_over.over_).  */
5158   else if (TYPE_PTRMEMFUNC_P (type))
5159     {
5160       expr = instantiate_type (type, expr, tf_none);
5161       if (expr == error_mark_node)
5162         return error_mark_node;
5163
5164       /* [temp.arg.nontype] bullet 1 says the pointer to member
5165          expression must be a pointer-to-member constant.  */
5166       if (!check_valid_ptrmem_cst_expr (type, expr))
5167         return error_mark_node;
5168
5169       /* There is no way to disable standard conversions in
5170          resolve_address_of_overloaded_function (called by
5171          instantiate_type). It is possible that the call succeeded by
5172          converting &B::I to &D::I (where B is a base of D), so we need
5173          to reject this conversion here.
5174
5175          Actually, even if there was a way to disable standard conversions,
5176          it would still be better to reject them here so that we can
5177          provide a superior diagnostic.  */
5178       if (!same_type_p (TREE_TYPE (expr), type))
5179         {
5180           error ("%qE is not a valid template argument for type %qT "
5181                  "because it is of type %qT", expr, type,
5182                  TREE_TYPE (expr));
5183           /* If we are just one standard conversion off, explain.  */
5184           if (can_convert (type, TREE_TYPE (expr)))
5185             inform (input_location,
5186                     "standard conversions are not allowed in this context");
5187           return NULL_TREE;
5188         }
5189     }
5190   /* [temp.arg.nontype]/5, bullet 7
5191
5192      For a non-type template-parameter of type pointer to data member,
5193      qualification conversions (_conv.qual_) are applied.  */
5194   else if (TYPE_PTRMEM_P (type))
5195     {
5196       /* [temp.arg.nontype] bullet 1 says the pointer to member
5197          expression must be a pointer-to-member constant.  */
5198       if (!check_valid_ptrmem_cst_expr (type, expr))
5199         return error_mark_node;
5200
5201       expr = perform_qualification_conversions (type, expr);
5202       if (expr == error_mark_node)
5203         return expr;
5204     }
5205   /* A template non-type parameter must be one of the above.  */
5206   else
5207     gcc_unreachable ();
5208
5209   /* Sanity check: did we actually convert the argument to the
5210      right type?  */
5211   gcc_assert (same_type_p (type, TREE_TYPE (expr)));
5212   return expr;
5213 }
5214
5215 /* Subroutine of coerce_template_template_parms, which returns 1 if
5216    PARM_PARM and ARG_PARM match using the rule for the template
5217    parameters of template template parameters. Both PARM and ARG are
5218    template parameters; the rest of the arguments are the same as for
5219    coerce_template_template_parms.
5220  */
5221 static int
5222 coerce_template_template_parm (tree parm,
5223                               tree arg,
5224                               tsubst_flags_t complain,
5225                               tree in_decl,
5226                               tree outer_args)
5227 {
5228   if (arg == NULL_TREE || arg == error_mark_node
5229       || parm == NULL_TREE || parm == error_mark_node)
5230     return 0;
5231   
5232   if (TREE_CODE (arg) != TREE_CODE (parm))
5233     return 0;
5234   
5235   switch (TREE_CODE (parm))
5236     {
5237     case TEMPLATE_DECL:
5238       /* We encounter instantiations of templates like
5239          template <template <template <class> class> class TT>
5240          class C;  */
5241       {
5242         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5243         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5244         
5245         if (!coerce_template_template_parms
5246             (parmparm, argparm, complain, in_decl, outer_args))
5247           return 0;
5248       }
5249       /* Fall through.  */
5250       
5251     case TYPE_DECL:
5252       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
5253           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5254         /* Argument is a parameter pack but parameter is not.  */
5255         return 0;
5256       break;
5257       
5258     case PARM_DECL:
5259       /* The tsubst call is used to handle cases such as
5260          
5261            template <int> class C {};
5262            template <class T, template <T> class TT> class D {};
5263            D<int, C> d;
5264
5265          i.e. the parameter list of TT depends on earlier parameters.  */
5266       if (!uses_template_parms (TREE_TYPE (arg))
5267           && !same_type_p
5268                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
5269                  TREE_TYPE (arg)))
5270         return 0;
5271       
5272       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
5273           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5274         /* Argument is a parameter pack but parameter is not.  */
5275         return 0;
5276       
5277       break;
5278
5279     default:
5280       gcc_unreachable ();
5281     }
5282
5283   return 1;
5284 }
5285
5286
5287 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
5288    template template parameters.  Both PARM_PARMS and ARG_PARMS are
5289    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
5290    or PARM_DECL.
5291
5292    Consider the example:
5293      template <class T> class A;
5294      template<template <class U> class TT> class B;
5295
5296    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
5297    the parameters to A, and OUTER_ARGS contains A.  */
5298
5299 static int
5300 coerce_template_template_parms (tree parm_parms,
5301                                 tree arg_parms,
5302                                 tsubst_flags_t complain,
5303                                 tree in_decl,
5304                                 tree outer_args)
5305 {
5306   int nparms, nargs, i;
5307   tree parm, arg;
5308   int variadic_p = 0;
5309
5310   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
5311   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
5312
5313   nparms = TREE_VEC_LENGTH (parm_parms);
5314   nargs = TREE_VEC_LENGTH (arg_parms);
5315
5316   /* Determine whether we have a parameter pack at the end of the
5317      template template parameter's template parameter list.  */
5318   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
5319     {
5320       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
5321       
5322       if (parm == error_mark_node)
5323         return 0;
5324
5325       switch (TREE_CODE (parm))
5326         {
5327         case TEMPLATE_DECL:
5328         case TYPE_DECL:
5329           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5330             variadic_p = 1;
5331           break;
5332           
5333         case PARM_DECL:
5334           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5335             variadic_p = 1;
5336           break;
5337           
5338         default:
5339           gcc_unreachable ();
5340         }
5341     }
5342  
5343   if (nargs != nparms
5344       && !(variadic_p && nargs >= nparms - 1))
5345     return 0;
5346
5347   /* Check all of the template parameters except the parameter pack at
5348      the end (if any).  */
5349   for (i = 0; i < nparms - variadic_p; ++i)
5350     {
5351       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
5352           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5353         continue;
5354
5355       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5356       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5357
5358       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5359                                           outer_args))
5360         return 0;
5361
5362     }
5363
5364   if (variadic_p)
5365     {
5366       /* Check each of the template parameters in the template
5367          argument against the template parameter pack at the end of
5368          the template template parameter.  */
5369       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
5370         return 0;
5371
5372       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5373
5374       for (; i < nargs; ++i)
5375         {
5376           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5377             continue;
5378  
5379           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5380  
5381           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5382                                               outer_args))
5383             return 0;
5384         }
5385     }
5386
5387   return 1;
5388 }
5389
5390 /* Verifies that the deduced template arguments (in TARGS) for the
5391    template template parameters (in TPARMS) represent valid bindings,
5392    by comparing the template parameter list of each template argument
5393    to the template parameter list of its corresponding template
5394    template parameter, in accordance with DR150. This
5395    routine can only be called after all template arguments have been
5396    deduced. It will return TRUE if all of the template template
5397    parameter bindings are okay, FALSE otherwise.  */
5398 bool 
5399 template_template_parm_bindings_ok_p (tree tparms, tree targs)
5400 {
5401   int i, ntparms = TREE_VEC_LENGTH (tparms);
5402   bool ret = true;
5403
5404   /* We're dealing with template parms in this process.  */
5405   ++processing_template_decl;
5406
5407   targs = INNERMOST_TEMPLATE_ARGS (targs);
5408
5409   for (i = 0; i < ntparms; ++i)
5410     {
5411       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
5412       tree targ = TREE_VEC_ELT (targs, i);
5413
5414       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
5415         {
5416           tree packed_args = NULL_TREE;
5417           int idx, len = 1;
5418
5419           if (ARGUMENT_PACK_P (targ))
5420             {
5421               /* Look inside the argument pack.  */
5422               packed_args = ARGUMENT_PACK_ARGS (targ);
5423               len = TREE_VEC_LENGTH (packed_args);
5424             }
5425
5426           for (idx = 0; idx < len; ++idx)
5427             {
5428               tree targ_parms = NULL_TREE;
5429
5430               if (packed_args)
5431                 /* Extract the next argument from the argument
5432                    pack.  */
5433                 targ = TREE_VEC_ELT (packed_args, idx);
5434
5435               if (PACK_EXPANSION_P (targ))
5436                 /* Look at the pattern of the pack expansion.  */
5437                 targ = PACK_EXPANSION_PATTERN (targ);
5438
5439               /* Extract the template parameters from the template
5440                  argument.  */
5441               if (TREE_CODE (targ) == TEMPLATE_DECL)
5442                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
5443               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
5444                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
5445
5446               /* Verify that we can coerce the template template
5447                  parameters from the template argument to the template
5448                  parameter.  This requires an exact match.  */
5449               if (targ_parms
5450                   && !coerce_template_template_parms
5451                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
5452                         targ_parms,
5453                         tf_none,
5454                         tparm,
5455                         targs))
5456                 {
5457                   ret = false;
5458                   goto out;
5459                 }
5460             }
5461         }
5462     }
5463
5464  out:
5465
5466   --processing_template_decl;
5467   return ret;
5468 }
5469
5470 /* Convert the indicated template ARG as necessary to match the
5471    indicated template PARM.  Returns the converted ARG, or
5472    error_mark_node if the conversion was unsuccessful.  Error and
5473    warning messages are issued under control of COMPLAIN.  This
5474    conversion is for the Ith parameter in the parameter list.  ARGS is
5475    the full set of template arguments deduced so far.  */
5476
5477 static tree
5478 convert_template_argument (tree parm,
5479                            tree arg,
5480                            tree args,
5481                            tsubst_flags_t complain,
5482                            int i,
5483                            tree in_decl)
5484 {
5485   tree orig_arg;
5486   tree val;
5487   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
5488
5489   if (TREE_CODE (arg) == TREE_LIST
5490       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
5491     {
5492       /* The template argument was the name of some
5493          member function.  That's usually
5494          invalid, but static members are OK.  In any
5495          case, grab the underlying fields/functions
5496          and issue an error later if required.  */
5497       orig_arg = TREE_VALUE (arg);
5498       TREE_TYPE (arg) = unknown_type_node;
5499     }
5500
5501   orig_arg = arg;
5502
5503   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
5504   requires_type = (TREE_CODE (parm) == TYPE_DECL
5505                    || requires_tmpl_type);
5506
5507   /* When determining whether an argument pack expansion is a template,
5508      look at the pattern.  */
5509   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
5510     arg = PACK_EXPANSION_PATTERN (arg);
5511
5512   /* Deal with an injected-class-name used as a template template arg.  */
5513   if (requires_tmpl_type && CLASS_TYPE_P (arg))
5514     {
5515       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
5516       if (TREE_CODE (t) == TEMPLATE_DECL)
5517         {
5518           if (complain & tf_warning_or_error)
5519             pedwarn (input_location, OPT_pedantic, "injected-class-name %qD"
5520                      " used as template template argument", TYPE_NAME (arg));
5521           else if (flag_pedantic_errors)
5522             t = arg;
5523
5524           arg = t;
5525         }
5526     }
5527
5528   is_tmpl_type = 
5529     ((TREE_CODE (arg) == TEMPLATE_DECL
5530       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
5531      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5532      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
5533
5534   if (is_tmpl_type
5535       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5536           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
5537     arg = TYPE_STUB_DECL (arg);
5538
5539   is_type = TYPE_P (arg) || is_tmpl_type;
5540
5541   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
5542       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
5543     {
5544       permerror (input_location, "to refer to a type member of a template parameter, "
5545                  "use %<typename %E%>", orig_arg);
5546
5547       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
5548                                      TREE_OPERAND (arg, 1),
5549                                      typename_type,
5550                                      complain & tf_error);
5551       arg = orig_arg;
5552       is_type = 1;
5553     }
5554   if (is_type != requires_type)
5555     {
5556       if (in_decl)
5557         {
5558           if (complain & tf_error)
5559             {
5560               error ("type/value mismatch at argument %d in template "
5561                      "parameter list for %qD",
5562                      i + 1, in_decl);
5563               if (is_type)
5564                 error ("  expected a constant of type %qT, got %qT",
5565                        TREE_TYPE (parm),
5566                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
5567               else if (requires_tmpl_type)
5568                 error ("  expected a class template, got %qE", orig_arg);
5569               else
5570                 error ("  expected a type, got %qE", orig_arg);
5571             }
5572         }
5573       return error_mark_node;
5574     }
5575   if (is_tmpl_type ^ requires_tmpl_type)
5576     {
5577       if (in_decl && (complain & tf_error))
5578         {
5579           error ("type/value mismatch at argument %d in template "
5580                  "parameter list for %qD",
5581                  i + 1, in_decl);
5582           if (is_tmpl_type)
5583             error ("  expected a type, got %qT", DECL_NAME (arg));
5584           else
5585             error ("  expected a class template, got %qT", orig_arg);
5586         }
5587       return error_mark_node;
5588     }
5589
5590   if (is_type)
5591     {
5592       if (requires_tmpl_type)
5593         {
5594           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
5595             /* The number of argument required is not known yet.
5596                Just accept it for now.  */
5597             val = TREE_TYPE (arg);
5598           else
5599             {
5600               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5601               tree argparm;
5602
5603               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5604
5605               if (coerce_template_template_parms (parmparm, argparm,
5606                                                   complain, in_decl,
5607                                                   args))
5608                 {
5609                   val = arg;
5610
5611                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
5612                      TEMPLATE_DECL.  */
5613                   if (val != error_mark_node)
5614                     {
5615                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
5616                         val = TREE_TYPE (val);
5617                       if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
5618                         val = make_pack_expansion (val);
5619                     }
5620                 }
5621               else
5622                 {
5623                   if (in_decl && (complain & tf_error))
5624                     {
5625                       error ("type/value mismatch at argument %d in "
5626                              "template parameter list for %qD",
5627                              i + 1, in_decl);
5628                       error ("  expected a template of type %qD, got %qT",
5629                              parm, orig_arg);
5630                     }
5631
5632                   val = error_mark_node;
5633                 }
5634             }
5635         }
5636       else
5637         val = orig_arg;
5638       /* We only form one instance of each template specialization.
5639          Therefore, if we use a non-canonical variant (i.e., a
5640          typedef), any future messages referring to the type will use
5641          the typedef, which is confusing if those future uses do not
5642          themselves also use the typedef.  */
5643       if (TYPE_P (val))
5644         val = strip_typedefs (val);
5645     }
5646   else
5647     {
5648       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
5649
5650       if (invalid_nontype_parm_type_p (t, complain))
5651         return error_mark_node;
5652
5653       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
5654         {
5655           if (same_type_p (t, TREE_TYPE (orig_arg)))
5656             val = orig_arg;
5657           else
5658             {
5659               /* Not sure if this is reachable, but it doesn't hurt
5660                  to be robust.  */
5661               error ("type mismatch in nontype parameter pack");
5662               val = error_mark_node;
5663             }
5664         }
5665       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
5666         /* We used to call digest_init here.  However, digest_init
5667            will report errors, which we don't want when complain
5668            is zero.  More importantly, digest_init will try too
5669            hard to convert things: for example, `0' should not be
5670            converted to pointer type at this point according to
5671            the standard.  Accepting this is not merely an
5672            extension, since deciding whether or not these
5673            conversions can occur is part of determining which
5674            function template to call, or whether a given explicit
5675            argument specification is valid.  */
5676         val = convert_nontype_argument (t, orig_arg);
5677       else
5678         val = orig_arg;
5679
5680       if (val == NULL_TREE)
5681         val = error_mark_node;
5682       else if (val == error_mark_node && (complain & tf_error))
5683         error ("could not convert template argument %qE to %qT",  orig_arg, t);
5684
5685       if (TREE_CODE (val) == SCOPE_REF)
5686         {
5687           /* Strip typedefs from the SCOPE_REF.  */
5688           tree type = strip_typedefs (TREE_TYPE (val));
5689           tree scope = strip_typedefs (TREE_OPERAND (val, 0));
5690           val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
5691                                       QUALIFIED_NAME_IS_TEMPLATE (val));
5692         }
5693     }
5694
5695   return val;
5696 }
5697
5698 /* Coerces the remaining template arguments in INNER_ARGS (from
5699    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
5700    Returns the coerced argument pack. PARM_IDX is the position of this
5701    parameter in the template parameter list. ARGS is the original
5702    template argument list.  */
5703 static tree
5704 coerce_template_parameter_pack (tree parms,
5705                                 int parm_idx,
5706                                 tree args,
5707                                 tree inner_args,
5708                                 int arg_idx,
5709                                 tree new_args,
5710                                 int* lost,
5711                                 tree in_decl,
5712                                 tsubst_flags_t complain)
5713 {
5714   tree parm = TREE_VEC_ELT (parms, parm_idx);
5715   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5716   tree packed_args;
5717   tree argument_pack;
5718   tree packed_types = NULL_TREE;
5719
5720   if (arg_idx > nargs)
5721     arg_idx = nargs;
5722
5723   packed_args = make_tree_vec (nargs - arg_idx);
5724
5725   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
5726       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
5727     {
5728       /* When the template parameter is a non-type template
5729          parameter pack whose type uses parameter packs, we need
5730          to look at each of the template arguments
5731          separately. Build a vector of the types for these
5732          non-type template parameters in PACKED_TYPES.  */
5733       tree expansion 
5734         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
5735       packed_types = tsubst_pack_expansion (expansion, args,
5736                                             complain, in_decl);
5737
5738       if (packed_types == error_mark_node)
5739         return error_mark_node;
5740
5741       /* Check that we have the right number of arguments.  */
5742       if (arg_idx < nargs
5743           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
5744           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
5745         {
5746           int needed_parms 
5747             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
5748           error ("wrong number of template arguments (%d, should be %d)",
5749                  nargs, needed_parms);
5750           return error_mark_node;
5751         }
5752
5753       /* If we aren't able to check the actual arguments now
5754          (because they haven't been expanded yet), we can at least
5755          verify that all of the types used for the non-type
5756          template parameter pack are, in fact, valid for non-type
5757          template parameters.  */
5758       if (arg_idx < nargs 
5759           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
5760         {
5761           int j, len = TREE_VEC_LENGTH (packed_types);
5762           for (j = 0; j < len; ++j)
5763             {
5764               tree t = TREE_VEC_ELT (packed_types, j);
5765               if (invalid_nontype_parm_type_p (t, complain))
5766                 return error_mark_node;
5767             }
5768         }
5769     }
5770
5771   /* Convert the remaining arguments, which will be a part of the
5772      parameter pack "parm".  */
5773   for (; arg_idx < nargs; ++arg_idx)
5774     {
5775       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
5776       tree actual_parm = TREE_VALUE (parm);
5777
5778       if (packed_types && !PACK_EXPANSION_P (arg))
5779         {
5780           /* When we have a vector of types (corresponding to the
5781              non-type template parameter pack that uses parameter
5782              packs in its type, as mention above), and the
5783              argument is not an expansion (which expands to a
5784              currently unknown number of arguments), clone the
5785              parm and give it the next type in PACKED_TYPES.  */
5786           actual_parm = copy_node (actual_parm);
5787           TREE_TYPE (actual_parm) = 
5788             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
5789         }
5790
5791       if (arg != error_mark_node)
5792         arg = convert_template_argument (actual_parm, 
5793                                          arg, new_args, complain, parm_idx,
5794                                          in_decl);
5795       if (arg == error_mark_node)
5796         (*lost)++;
5797       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
5798     }
5799
5800   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
5801       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
5802     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
5803   else
5804     {
5805       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
5806       TREE_TYPE (argument_pack) 
5807         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
5808       TREE_CONSTANT (argument_pack) = 1;
5809     }
5810
5811   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
5812 #ifdef ENABLE_CHECKING
5813   SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
5814                                        TREE_VEC_LENGTH (packed_args));
5815 #endif
5816   return argument_pack;
5817 }
5818
5819 /* Convert all template arguments to their appropriate types, and
5820    return a vector containing the innermost resulting template
5821    arguments.  If any error occurs, return error_mark_node. Error and
5822    warning messages are issued under control of COMPLAIN.
5823
5824    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
5825    for arguments not specified in ARGS.  Otherwise, if
5826    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
5827    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
5828    USE_DEFAULT_ARGS is false, then all arguments must be specified in
5829    ARGS.  */
5830
5831 static tree
5832 coerce_template_parms (tree parms,
5833                        tree args,
5834                        tree in_decl,
5835                        tsubst_flags_t complain,
5836                        bool require_all_args,
5837                        bool use_default_args)
5838 {
5839   int nparms, nargs, parm_idx, arg_idx, lost = 0;
5840   tree inner_args;
5841   tree new_args;
5842   tree new_inner_args;
5843   int saved_unevaluated_operand;
5844   int saved_inhibit_evaluation_warnings;
5845
5846   /* When used as a boolean value, indicates whether this is a
5847      variadic template parameter list. Since it's an int, we can also
5848      subtract it from nparms to get the number of non-variadic
5849      parameters.  */
5850   int variadic_p = 0;
5851
5852   nparms = TREE_VEC_LENGTH (parms);
5853
5854   /* Determine if there are any parameter packs.  */
5855   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
5856     {
5857       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
5858       if (template_parameter_pack_p (tparm))
5859         ++variadic_p;
5860     }
5861
5862   inner_args = INNERMOST_TEMPLATE_ARGS (args);
5863   /* If there are 0 or 1 parameter packs, we need to expand any argument
5864      packs so that we can deduce a parameter pack from some non-packed args
5865      followed by an argument pack, as in variadic85.C.  If there are more
5866      than that, we need to leave argument packs intact so the arguments are
5867      assigned to the right parameter packs.  This should only happen when
5868      dealing with a nested class inside a partial specialization of a class
5869      template, as in variadic92.C.  */
5870   if (variadic_p <= 1)
5871     inner_args = expand_template_argument_pack (inner_args);
5872
5873   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5874   if ((nargs > nparms && !variadic_p)
5875       || (nargs < nparms - variadic_p
5876           && require_all_args
5877           && (!use_default_args
5878               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
5879                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
5880     {
5881       if (complain & tf_error)
5882         {
5883           const char *or_more = "";
5884           if (variadic_p)
5885             {
5886               or_more = " or more";
5887               --nparms;
5888             }
5889
5890           error ("wrong number of template arguments (%d, should be %d%s)",
5891                  nargs, nparms, or_more);
5892
5893           if (in_decl)
5894             error ("provided for %q+D", in_decl);
5895         }
5896
5897       return error_mark_node;
5898     }
5899
5900   /* We need to evaluate the template arguments, even though this
5901      template-id may be nested within a "sizeof".  */
5902   saved_unevaluated_operand = cp_unevaluated_operand;
5903   cp_unevaluated_operand = 0;
5904   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
5905   c_inhibit_evaluation_warnings = 0;
5906   new_inner_args = make_tree_vec (nparms);
5907   new_args = add_outermost_template_args (args, new_inner_args);
5908   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
5909     {
5910       tree arg;
5911       tree parm;
5912
5913       /* Get the Ith template parameter.  */
5914       parm = TREE_VEC_ELT (parms, parm_idx);
5915  
5916       if (parm == error_mark_node)
5917       {
5918         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
5919         continue;
5920       }
5921
5922       /* Calculate the next argument.  */
5923       if (arg_idx < nargs)
5924         arg = TREE_VEC_ELT (inner_args, arg_idx);
5925       else
5926         arg = NULL_TREE;
5927
5928       if (template_parameter_pack_p (TREE_VALUE (parm))
5929           && !(arg && ARGUMENT_PACK_P (arg)))
5930         {
5931           /* All remaining arguments will be placed in the
5932              template parameter pack PARM.  */
5933           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
5934                                                 inner_args, arg_idx,
5935                                                 new_args, &lost,
5936                                                 in_decl, complain);
5937
5938           /* Store this argument.  */
5939           if (arg == error_mark_node)
5940             lost++;
5941           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
5942
5943           /* We are done with all of the arguments.  */
5944           arg_idx = nargs;
5945           
5946           continue;
5947         }
5948       else if (arg)
5949         {
5950           if (PACK_EXPANSION_P (arg))
5951             {
5952               if (complain & tf_error)
5953                 {
5954                   /* FIXME this restriction was removed by N2555; see
5955                      bug 35722.  */
5956                   /* If ARG is a pack expansion, but PARM is not a
5957                      template parameter pack (if it were, we would have
5958                      handled it above), we're trying to expand into a
5959                      fixed-length argument list.  */
5960                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
5961                     sorry ("cannot expand %<%E%> into a fixed-length "
5962                            "argument list", arg);
5963                   else
5964                     sorry ("cannot expand %<%T%> into a fixed-length "
5965                            "argument list", arg);
5966                 }
5967               return error_mark_node;
5968             }
5969         }
5970       else if (require_all_args)
5971         {
5972           /* There must be a default arg in this case.  */
5973           arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
5974                                      complain, in_decl);
5975           /* The position of the first default template argument,
5976              is also the number of non-defaulted arguments in NEW_INNER_ARGS.
5977              Record that.  */
5978           if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
5979             SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args, arg_idx);
5980         }
5981       else
5982         break;
5983
5984       if (arg == error_mark_node)
5985         {
5986           if (complain & tf_error)
5987             error ("template argument %d is invalid", arg_idx + 1);
5988         }
5989       else if (!arg)
5990         /* This only occurs if there was an error in the template
5991            parameter list itself (which we would already have
5992            reported) that we are trying to recover from, e.g., a class
5993            template with a parameter list such as
5994            template<typename..., typename>.  */
5995         return error_mark_node;
5996       else
5997         arg = convert_template_argument (TREE_VALUE (parm),
5998                                          arg, new_args, complain, 
5999                                          parm_idx, in_decl);
6000
6001       if (arg == error_mark_node)
6002         lost++;
6003       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
6004     }
6005   cp_unevaluated_operand = saved_unevaluated_operand;
6006   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
6007
6008   if (lost)
6009     return error_mark_node;
6010
6011 #ifdef ENABLE_CHECKING
6012   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6013     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
6014                                          TREE_VEC_LENGTH (new_inner_args));
6015 #endif
6016
6017   return new_inner_args;
6018 }
6019
6020 /* Returns 1 if template args OT and NT are equivalent.  */
6021
6022 static int
6023 template_args_equal (tree ot, tree nt)
6024 {
6025   if (nt == ot)
6026     return 1;
6027
6028   if (TREE_CODE (nt) == TREE_VEC)
6029     /* For member templates */
6030     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
6031   else if (PACK_EXPANSION_P (ot))
6032     return PACK_EXPANSION_P (nt) 
6033       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
6034                               PACK_EXPANSION_PATTERN (nt));
6035   else if (ARGUMENT_PACK_P (ot))
6036     {
6037       int i, len;
6038       tree opack, npack;
6039
6040       if (!ARGUMENT_PACK_P (nt))
6041         return 0;
6042
6043       opack = ARGUMENT_PACK_ARGS (ot);
6044       npack = ARGUMENT_PACK_ARGS (nt);
6045       len = TREE_VEC_LENGTH (opack);
6046       if (TREE_VEC_LENGTH (npack) != len)
6047         return 0;
6048       for (i = 0; i < len; ++i)
6049         if (!template_args_equal (TREE_VEC_ELT (opack, i),
6050                                   TREE_VEC_ELT (npack, i)))
6051           return 0;
6052       return 1;
6053     }
6054   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
6055     {
6056       /* We get here probably because we are in the middle of substituting
6057          into the pattern of a pack expansion. In that case the
6058          ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
6059          interested in. So we want to use the initial pack argument for
6060          the comparison.  */
6061       ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
6062       if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
6063         nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
6064       return template_args_equal (ot, nt);
6065     }
6066   else if (TYPE_P (nt))
6067     return TYPE_P (ot) && same_type_p (ot, nt);
6068   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
6069     return 0;
6070   else
6071     return cp_tree_equal (ot, nt);
6072 }
6073
6074 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
6075    of template arguments.  Returns 0 otherwise.  */
6076
6077 int
6078 comp_template_args (tree oldargs, tree newargs)
6079 {
6080   int i;
6081
6082   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
6083     return 0;
6084
6085   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
6086     {
6087       tree nt = TREE_VEC_ELT (newargs, i);
6088       tree ot = TREE_VEC_ELT (oldargs, i);
6089
6090       if (! template_args_equal (ot, nt))
6091         return 0;
6092     }
6093   return 1;
6094 }
6095
6096 static void
6097 add_pending_template (tree d)
6098 {
6099   tree ti = (TYPE_P (d)
6100              ? CLASSTYPE_TEMPLATE_INFO (d)
6101              : DECL_TEMPLATE_INFO (d));
6102   struct pending_template *pt;
6103   int level;
6104
6105   if (TI_PENDING_TEMPLATE_FLAG (ti))
6106     return;
6107
6108   /* We are called both from instantiate_decl, where we've already had a
6109      tinst_level pushed, and instantiate_template, where we haven't.
6110      Compensate.  */
6111   level = !current_tinst_level || current_tinst_level->decl != d;
6112
6113   if (level)
6114     push_tinst_level (d);
6115
6116   pt = GGC_NEW (struct pending_template);
6117   pt->next = NULL;
6118   pt->tinst = current_tinst_level;
6119   if (last_pending_template)
6120     last_pending_template->next = pt;
6121   else
6122     pending_templates = pt;
6123
6124   last_pending_template = pt;
6125
6126   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
6127
6128   if (level)
6129     pop_tinst_level ();
6130 }
6131
6132
6133 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
6134    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
6135    documentation for TEMPLATE_ID_EXPR.  */
6136
6137 tree
6138 lookup_template_function (tree fns, tree arglist)
6139 {
6140   tree type;
6141
6142   if (fns == error_mark_node || arglist == error_mark_node)
6143     return error_mark_node;
6144
6145   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
6146   gcc_assert (fns && (is_overloaded_fn (fns)
6147                       || TREE_CODE (fns) == IDENTIFIER_NODE));
6148
6149   if (BASELINK_P (fns))
6150     {
6151       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
6152                                          unknown_type_node,
6153                                          BASELINK_FUNCTIONS (fns),
6154                                          arglist);
6155       return fns;
6156     }
6157
6158   type = TREE_TYPE (fns);
6159   if (TREE_CODE (fns) == OVERLOAD || !type)
6160     type = unknown_type_node;
6161
6162   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
6163 }
6164
6165 /* Within the scope of a template class S<T>, the name S gets bound
6166    (in build_self_reference) to a TYPE_DECL for the class, not a
6167    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
6168    or one of its enclosing classes, and that type is a template,
6169    return the associated TEMPLATE_DECL.  Otherwise, the original
6170    DECL is returned.
6171
6172    Also handle the case when DECL is a TREE_LIST of ambiguous
6173    injected-class-names from different bases.  */
6174
6175 tree
6176 maybe_get_template_decl_from_type_decl (tree decl)
6177 {
6178   if (decl == NULL_TREE)
6179     return decl;
6180
6181   /* DR 176: A lookup that finds an injected-class-name (10.2
6182      [class.member.lookup]) can result in an ambiguity in certain cases
6183      (for example, if it is found in more than one base class). If all of
6184      the injected-class-names that are found refer to specializations of
6185      the same class template, and if the name is followed by a
6186      template-argument-list, the reference refers to the class template
6187      itself and not a specialization thereof, and is not ambiguous.  */
6188   if (TREE_CODE (decl) == TREE_LIST)
6189     {
6190       tree t, tmpl = NULL_TREE;
6191       for (t = decl; t; t = TREE_CHAIN (t))
6192         {
6193           tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
6194           if (!tmpl)
6195             tmpl = elt;
6196           else if (tmpl != elt)
6197             break;
6198         }
6199       if (tmpl && t == NULL_TREE)
6200         return tmpl;
6201       else
6202         return decl;
6203     }
6204
6205   return (decl != NULL_TREE
6206           && DECL_SELF_REFERENCE_P (decl)
6207           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
6208     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
6209 }
6210
6211 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
6212    parameters, find the desired type.
6213
6214    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
6215
6216    IN_DECL, if non-NULL, is the template declaration we are trying to
6217    instantiate.
6218
6219    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
6220    the class we are looking up.
6221
6222    Issue error and warning messages under control of COMPLAIN.
6223
6224    If the template class is really a local class in a template
6225    function, then the FUNCTION_CONTEXT is the function in which it is
6226    being instantiated.
6227
6228    ??? Note that this function is currently called *twice* for each
6229    template-id: the first time from the parser, while creating the
6230    incomplete type (finish_template_type), and the second type during the
6231    real instantiation (instantiate_template_class). This is surely something
6232    that we want to avoid. It also causes some problems with argument
6233    coercion (see convert_nontype_argument for more information on this).  */
6234
6235 tree
6236 lookup_template_class (tree d1,
6237                        tree arglist,
6238                        tree in_decl,
6239                        tree context,
6240                        int entering_scope,
6241                        tsubst_flags_t complain)
6242 {
6243   tree templ = NULL_TREE, parmlist;
6244   tree t;
6245   spec_entry **slot;
6246   spec_entry *entry;
6247   spec_entry elt;
6248   hashval_t hash;
6249
6250   timevar_push (TV_NAME_LOOKUP);
6251
6252   if (TREE_CODE (d1) == IDENTIFIER_NODE)
6253     {
6254       tree value = innermost_non_namespace_value (d1);
6255       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
6256         templ = value;
6257       else
6258         {
6259           if (context)
6260             push_decl_namespace (context);
6261           templ = lookup_name (d1);
6262           templ = maybe_get_template_decl_from_type_decl (templ);
6263           if (context)
6264             pop_decl_namespace ();
6265         }
6266       if (templ)
6267         context = DECL_CONTEXT (templ);
6268     }
6269   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
6270     {
6271       tree type = TREE_TYPE (d1);
6272
6273       /* If we are declaring a constructor, say A<T>::A<T>, we will get
6274          an implicit typename for the second A.  Deal with it.  */
6275       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
6276         type = TREE_TYPE (type);
6277
6278       if (CLASSTYPE_TEMPLATE_INFO (type))
6279         {
6280           templ = CLASSTYPE_TI_TEMPLATE (type);
6281           d1 = DECL_NAME (templ);
6282         }
6283     }
6284   else if (TREE_CODE (d1) == ENUMERAL_TYPE
6285            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
6286     {
6287       templ = TYPE_TI_TEMPLATE (d1);
6288       d1 = DECL_NAME (templ);
6289     }
6290   else if (TREE_CODE (d1) == TEMPLATE_DECL
6291            && DECL_TEMPLATE_RESULT (d1)
6292            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
6293     {
6294       templ = d1;
6295       d1 = DECL_NAME (templ);
6296       context = DECL_CONTEXT (templ);
6297     }
6298
6299   /* Issue an error message if we didn't find a template.  */
6300   if (! templ)
6301     {
6302       if (complain & tf_error)
6303         error ("%qT is not a template", d1);
6304       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6305     }
6306
6307   if (TREE_CODE (templ) != TEMPLATE_DECL
6308          /* Make sure it's a user visible template, if it was named by
6309             the user.  */
6310       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
6311           && !PRIMARY_TEMPLATE_P (templ)))
6312     {
6313       if (complain & tf_error)
6314         {
6315           error ("non-template type %qT used as a template", d1);
6316           if (in_decl)
6317             error ("for template declaration %q+D", in_decl);
6318         }
6319       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6320     }
6321
6322   complain &= ~tf_user;
6323
6324   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
6325     {
6326       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
6327          template arguments */
6328
6329       tree parm;
6330       tree arglist2;
6331       tree outer;
6332
6333       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
6334
6335       /* Consider an example where a template template parameter declared as
6336
6337            template <class T, class U = std::allocator<T> > class TT
6338
6339          The template parameter level of T and U are one level larger than
6340          of TT.  To proper process the default argument of U, say when an
6341          instantiation `TT<int>' is seen, we need to build the full
6342          arguments containing {int} as the innermost level.  Outer levels,
6343          available when not appearing as default template argument, can be
6344          obtained from the arguments of the enclosing template.
6345
6346          Suppose that TT is later substituted with std::vector.  The above
6347          instantiation is `TT<int, std::allocator<T> >' with TT at
6348          level 1, and T at level 2, while the template arguments at level 1
6349          becomes {std::vector} and the inner level 2 is {int}.  */
6350
6351       outer = DECL_CONTEXT (templ);
6352       if (outer)
6353         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
6354       else if (current_template_parms)
6355         /* This is an argument of the current template, so we haven't set
6356            DECL_CONTEXT yet.  */
6357         outer = current_template_args ();
6358
6359       if (outer)
6360         arglist = add_to_template_args (outer, arglist);
6361
6362       arglist2 = coerce_template_parms (parmlist, arglist, templ,
6363                                         complain,
6364                                         /*require_all_args=*/true,
6365                                         /*use_default_args=*/true);
6366       if (arglist2 == error_mark_node
6367           || (!uses_template_parms (arglist2)
6368               && check_instantiated_args (templ, arglist2, complain)))
6369         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6370
6371       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
6372       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
6373     }
6374   else
6375     {
6376       tree template_type = TREE_TYPE (templ);
6377       tree gen_tmpl;
6378       tree type_decl;
6379       tree found = NULL_TREE;
6380       int arg_depth;
6381       int parm_depth;
6382       int is_partial_instantiation;
6383
6384       gen_tmpl = most_general_template (templ);
6385       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
6386       parm_depth = TMPL_PARMS_DEPTH (parmlist);
6387       arg_depth = TMPL_ARGS_DEPTH (arglist);
6388
6389       if (arg_depth == 1 && parm_depth > 1)
6390         {
6391           /* We've been given an incomplete set of template arguments.
6392              For example, given:
6393
6394                template <class T> struct S1 {
6395                  template <class U> struct S2 {};
6396                  template <class U> struct S2<U*> {};
6397                 };
6398
6399              we will be called with an ARGLIST of `U*', but the
6400              TEMPLATE will be `template <class T> template
6401              <class U> struct S1<T>::S2'.  We must fill in the missing
6402              arguments.  */
6403           arglist
6404             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
6405                                            arglist);
6406           arg_depth = TMPL_ARGS_DEPTH (arglist);
6407         }
6408
6409       /* Now we should have enough arguments.  */
6410       gcc_assert (parm_depth == arg_depth);
6411
6412       /* From here on, we're only interested in the most general
6413          template.  */
6414
6415       /* Calculate the BOUND_ARGS.  These will be the args that are
6416          actually tsubst'd into the definition to create the
6417          instantiation.  */
6418       if (parm_depth > 1)
6419         {
6420           /* We have multiple levels of arguments to coerce, at once.  */
6421           int i;
6422           int saved_depth = TMPL_ARGS_DEPTH (arglist);
6423
6424           tree bound_args = make_tree_vec (parm_depth);
6425
6426           for (i = saved_depth,
6427                  t = DECL_TEMPLATE_PARMS (gen_tmpl);
6428                i > 0 && t != NULL_TREE;
6429                --i, t = TREE_CHAIN (t))
6430             {
6431               tree a = coerce_template_parms (TREE_VALUE (t),
6432                                               arglist, gen_tmpl,
6433                                               complain,
6434                                               /*require_all_args=*/true,
6435                                               /*use_default_args=*/true);
6436
6437               /* Don't process further if one of the levels fails.  */
6438               if (a == error_mark_node)
6439                 {
6440                   /* Restore the ARGLIST to its full size.  */
6441                   TREE_VEC_LENGTH (arglist) = saved_depth;
6442                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6443                 }
6444
6445               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
6446
6447               /* We temporarily reduce the length of the ARGLIST so
6448                  that coerce_template_parms will see only the arguments
6449                  corresponding to the template parameters it is
6450                  examining.  */
6451               TREE_VEC_LENGTH (arglist)--;
6452             }
6453
6454           /* Restore the ARGLIST to its full size.  */
6455           TREE_VEC_LENGTH (arglist) = saved_depth;
6456
6457           arglist = bound_args;
6458         }
6459       else
6460         arglist
6461           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
6462                                    INNERMOST_TEMPLATE_ARGS (arglist),
6463                                    gen_tmpl,
6464                                    complain,
6465                                    /*require_all_args=*/true,
6466                                    /*use_default_args=*/true);
6467
6468       if (arglist == error_mark_node)
6469         /* We were unable to bind the arguments.  */
6470         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6471
6472       /* In the scope of a template class, explicit references to the
6473          template class refer to the type of the template, not any
6474          instantiation of it.  For example, in:
6475
6476            template <class T> class C { void f(C<T>); }
6477
6478          the `C<T>' is just the same as `C'.  Outside of the
6479          class, however, such a reference is an instantiation.  */
6480       if ((entering_scope
6481            || !PRIMARY_TEMPLATE_P (gen_tmpl)
6482            || currently_open_class (template_type))
6483           /* comp_template_args is expensive, check it last.  */
6484           && comp_template_args (TYPE_TI_ARGS (template_type),
6485                                  arglist))
6486         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, template_type);
6487
6488       /* If we already have this specialization, return it.  */
6489       elt.tmpl = gen_tmpl;
6490       elt.args = arglist;
6491       hash = hash_specialization (&elt);
6492       entry = (spec_entry *) htab_find_with_hash (type_specializations,
6493                                                   &elt, hash);
6494
6495       if (entry)
6496         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, entry->spec);
6497
6498       /* This type is a "partial instantiation" if any of the template
6499          arguments still involve template parameters.  Note that we set
6500          IS_PARTIAL_INSTANTIATION for partial specializations as
6501          well.  */
6502       is_partial_instantiation = uses_template_parms (arglist);
6503
6504       /* If the deduced arguments are invalid, then the binding
6505          failed.  */
6506       if (!is_partial_instantiation
6507           && check_instantiated_args (gen_tmpl,
6508                                       INNERMOST_TEMPLATE_ARGS (arglist),
6509                                       complain))
6510         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6511
6512       if (!is_partial_instantiation
6513           && !PRIMARY_TEMPLATE_P (gen_tmpl)
6514           && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
6515           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
6516         {
6517           found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
6518                                       DECL_NAME (gen_tmpl),
6519                                       /*tag_scope=*/ts_global);
6520           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
6521         }
6522
6523       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
6524                         complain, in_decl);
6525       if (!context)
6526         context = global_namespace;
6527
6528       /* Create the type.  */
6529       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
6530         {
6531           if (!is_partial_instantiation)
6532             {
6533               set_current_access_from_decl (TYPE_NAME (template_type));
6534               t = start_enum (TYPE_IDENTIFIER (template_type),
6535                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
6536                                       arglist, complain, in_decl),
6537                               SCOPED_ENUM_P (template_type));
6538             }
6539           else
6540             {
6541               /* We don't want to call start_enum for this type, since
6542                  the values for the enumeration constants may involve
6543                  template parameters.  And, no one should be interested
6544                  in the enumeration constants for such a type.  */
6545               t = cxx_make_type (ENUMERAL_TYPE);
6546               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
6547             }
6548         }
6549       else
6550         {
6551           t = make_class_type (TREE_CODE (template_type));
6552           CLASSTYPE_DECLARED_CLASS (t)
6553             = CLASSTYPE_DECLARED_CLASS (template_type);
6554           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
6555           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
6556
6557           /* A local class.  Make sure the decl gets registered properly.  */
6558           if (context == current_function_decl)
6559             pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
6560
6561           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
6562             /* This instantiation is another name for the primary
6563                template type. Set the TYPE_CANONICAL field
6564                appropriately. */
6565             TYPE_CANONICAL (t) = template_type;
6566           else if (any_template_arguments_need_structural_equality_p (arglist))
6567             /* Some of the template arguments require structural
6568                equality testing, so this template class requires
6569                structural equality testing. */
6570             SET_TYPE_STRUCTURAL_EQUALITY (t);
6571         }
6572
6573       /* If we called start_enum or pushtag above, this information
6574          will already be set up.  */
6575       if (!TYPE_NAME (t))
6576         {
6577           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
6578
6579           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
6580           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
6581           DECL_SOURCE_LOCATION (type_decl)
6582             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
6583         }
6584       else
6585         type_decl = TYPE_NAME (t);
6586
6587       TREE_PRIVATE (type_decl)
6588         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
6589       TREE_PROTECTED (type_decl)
6590         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
6591       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
6592         {
6593           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
6594           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
6595         }
6596
6597       /* Set up the template information.  We have to figure out which
6598          template is the immediate parent if this is a full
6599          instantiation.  */
6600       if (parm_depth == 1 || is_partial_instantiation
6601           || !PRIMARY_TEMPLATE_P (gen_tmpl))
6602         /* This case is easy; there are no member templates involved.  */
6603         found = gen_tmpl;
6604       else
6605         {
6606           /* This is a full instantiation of a member template.  Find
6607              the partial instantiation of which this is an instance.  */
6608
6609           /* Temporarily reduce by one the number of levels in the ARGLIST
6610              so as to avoid comparing the last set of arguments.  */
6611           TREE_VEC_LENGTH (arglist)--;
6612           found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
6613           TREE_VEC_LENGTH (arglist)++;
6614           found = CLASSTYPE_TI_TEMPLATE (found);
6615         }
6616
6617       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
6618
6619       elt.spec = t;
6620       slot = (spec_entry **) htab_find_slot_with_hash (type_specializations,
6621                                                        &elt, hash, INSERT);
6622       *slot = GGC_NEW (spec_entry);
6623       **slot = elt;
6624
6625       /* Note this use of the partial instantiation so we can check it
6626          later in maybe_process_partial_specialization.  */
6627       DECL_TEMPLATE_INSTANTIATIONS (templ)
6628         = tree_cons (arglist, t,
6629                      DECL_TEMPLATE_INSTANTIATIONS (templ));
6630
6631       if (TREE_CODE (t) == ENUMERAL_TYPE
6632           && !is_partial_instantiation)
6633         /* Now that the type has been registered on the instantiations
6634            list, we set up the enumerators.  Because the enumeration
6635            constants may involve the enumeration type itself, we make
6636            sure to register the type first, and then create the
6637            constants.  That way, doing tsubst_expr for the enumeration
6638            constants won't result in recursive calls here; we'll find
6639            the instantiation and exit above.  */
6640         tsubst_enum (template_type, t, arglist);
6641
6642       if (is_partial_instantiation)
6643         /* If the type makes use of template parameters, the
6644            code that generates debugging information will crash.  */
6645         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
6646
6647       /* Possibly limit visibility based on template args.  */
6648       TREE_PUBLIC (type_decl) = 1;
6649       determine_visibility (type_decl);
6650
6651       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
6652     }
6653   timevar_pop (TV_NAME_LOOKUP);
6654 }
6655 \f
6656 struct pair_fn_data
6657 {
6658   tree_fn_t fn;
6659   void *data;
6660   /* True when we should also visit template parameters that occur in
6661      non-deduced contexts.  */
6662   bool include_nondeduced_p;
6663   struct pointer_set_t *visited;
6664 };
6665
6666 /* Called from for_each_template_parm via walk_tree.  */
6667
6668 static tree
6669 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
6670 {
6671   tree t = *tp;
6672   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
6673   tree_fn_t fn = pfd->fn;
6674   void *data = pfd->data;
6675
6676   if (TYPE_P (t)
6677       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
6678       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
6679                                  pfd->include_nondeduced_p))
6680     return error_mark_node;
6681
6682   switch (TREE_CODE (t))
6683     {
6684     case RECORD_TYPE:
6685       if (TYPE_PTRMEMFUNC_P (t))
6686         break;
6687       /* Fall through.  */
6688
6689     case UNION_TYPE:
6690     case ENUMERAL_TYPE:
6691       if (!TYPE_TEMPLATE_INFO (t))
6692         *walk_subtrees = 0;
6693       else if (for_each_template_parm (TI_ARGS (TYPE_TEMPLATE_INFO (t)),
6694                                        fn, data, pfd->visited, 
6695                                        pfd->include_nondeduced_p))
6696         return error_mark_node;
6697       break;
6698
6699     case INTEGER_TYPE:
6700       if (for_each_template_parm (TYPE_MIN_VALUE (t),
6701                                   fn, data, pfd->visited, 
6702                                   pfd->include_nondeduced_p)
6703           || for_each_template_parm (TYPE_MAX_VALUE (t),
6704                                      fn, data, pfd->visited,
6705                                      pfd->include_nondeduced_p))
6706         return error_mark_node;
6707       break;
6708
6709     case METHOD_TYPE:
6710       /* Since we're not going to walk subtrees, we have to do this
6711          explicitly here.  */
6712       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
6713                                   pfd->visited, pfd->include_nondeduced_p))
6714         return error_mark_node;
6715       /* Fall through.  */
6716
6717     case FUNCTION_TYPE:
6718       /* Check the return type.  */
6719       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6720                                   pfd->include_nondeduced_p))
6721         return error_mark_node;
6722
6723       /* Check the parameter types.  Since default arguments are not
6724          instantiated until they are needed, the TYPE_ARG_TYPES may
6725          contain expressions that involve template parameters.  But,
6726          no-one should be looking at them yet.  And, once they're
6727          instantiated, they don't contain template parameters, so
6728          there's no point in looking at them then, either.  */
6729       {
6730         tree parm;
6731
6732         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
6733           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
6734                                       pfd->visited, pfd->include_nondeduced_p))
6735             return error_mark_node;
6736
6737         /* Since we've already handled the TYPE_ARG_TYPES, we don't
6738            want walk_tree walking into them itself.  */
6739         *walk_subtrees = 0;
6740       }
6741       break;
6742
6743     case TYPEOF_TYPE:
6744       if (pfd->include_nondeduced_p
6745           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
6746                                      pfd->visited, 
6747                                      pfd->include_nondeduced_p))
6748         return error_mark_node;
6749       break;
6750
6751     case FUNCTION_DECL:
6752     case VAR_DECL:
6753       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
6754           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
6755                                      pfd->visited, pfd->include_nondeduced_p))
6756         return error_mark_node;
6757       /* Fall through.  */
6758
6759     case PARM_DECL:
6760     case CONST_DECL:
6761       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
6762           && for_each_template_parm (DECL_INITIAL (t), fn, data,
6763                                      pfd->visited, pfd->include_nondeduced_p))
6764         return error_mark_node;
6765       if (DECL_CONTEXT (t)
6766           && pfd->include_nondeduced_p
6767           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
6768                                      pfd->visited, pfd->include_nondeduced_p))
6769         return error_mark_node;
6770       break;
6771
6772     case BOUND_TEMPLATE_TEMPLATE_PARM:
6773       /* Record template parameters such as `T' inside `TT<T>'.  */
6774       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
6775                                   pfd->include_nondeduced_p))
6776         return error_mark_node;
6777       /* Fall through.  */
6778
6779     case TEMPLATE_TEMPLATE_PARM:
6780     case TEMPLATE_TYPE_PARM:
6781     case TEMPLATE_PARM_INDEX:
6782       if (fn && (*fn)(t, data))
6783         return error_mark_node;
6784       else if (!fn)
6785         return error_mark_node;
6786       break;
6787
6788     case TEMPLATE_DECL:
6789       /* A template template parameter is encountered.  */
6790       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
6791           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6792                                      pfd->include_nondeduced_p))
6793         return error_mark_node;
6794
6795       /* Already substituted template template parameter */
6796       *walk_subtrees = 0;
6797       break;
6798
6799     case TYPENAME_TYPE:
6800       if (!fn
6801           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
6802                                      data, pfd->visited, 
6803                                      pfd->include_nondeduced_p))
6804         return error_mark_node;
6805       break;
6806
6807     case CONSTRUCTOR:
6808       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
6809           && pfd->include_nondeduced_p
6810           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
6811                                      (TREE_TYPE (t)), fn, data,
6812                                      pfd->visited, pfd->include_nondeduced_p))
6813         return error_mark_node;
6814       break;
6815
6816     case INDIRECT_REF:
6817     case COMPONENT_REF:
6818       /* If there's no type, then this thing must be some expression
6819          involving template parameters.  */
6820       if (!fn && !TREE_TYPE (t))
6821         return error_mark_node;
6822       break;
6823
6824     case MODOP_EXPR:
6825     case CAST_EXPR:
6826     case REINTERPRET_CAST_EXPR:
6827     case CONST_CAST_EXPR:
6828     case STATIC_CAST_EXPR:
6829     case DYNAMIC_CAST_EXPR:
6830     case ARROW_EXPR:
6831     case DOTSTAR_EXPR:
6832     case TYPEID_EXPR:
6833     case PSEUDO_DTOR_EXPR:
6834       if (!fn)
6835         return error_mark_node;
6836       break;
6837
6838     default:
6839       break;
6840     }
6841
6842   /* We didn't find any template parameters we liked.  */
6843   return NULL_TREE;
6844 }
6845
6846 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
6847    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
6848    call FN with the parameter and the DATA.
6849    If FN returns nonzero, the iteration is terminated, and
6850    for_each_template_parm returns 1.  Otherwise, the iteration
6851    continues.  If FN never returns a nonzero value, the value
6852    returned by for_each_template_parm is 0.  If FN is NULL, it is
6853    considered to be the function which always returns 1.
6854
6855    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
6856    parameters that occur in non-deduced contexts.  When false, only
6857    visits those template parameters that can be deduced.  */
6858
6859 static int
6860 for_each_template_parm (tree t, tree_fn_t fn, void* data,
6861                         struct pointer_set_t *visited,
6862                         bool include_nondeduced_p)
6863 {
6864   struct pair_fn_data pfd;
6865   int result;
6866
6867   /* Set up.  */
6868   pfd.fn = fn;
6869   pfd.data = data;
6870   pfd.include_nondeduced_p = include_nondeduced_p;
6871
6872   /* Walk the tree.  (Conceptually, we would like to walk without
6873      duplicates, but for_each_template_parm_r recursively calls
6874      for_each_template_parm, so we would need to reorganize a fair
6875      bit to use walk_tree_without_duplicates, so we keep our own
6876      visited list.)  */
6877   if (visited)
6878     pfd.visited = visited;
6879   else
6880     pfd.visited = pointer_set_create ();
6881   result = cp_walk_tree (&t,
6882                          for_each_template_parm_r,
6883                          &pfd,
6884                          pfd.visited) != NULL_TREE;
6885
6886   /* Clean up.  */
6887   if (!visited)
6888     {
6889       pointer_set_destroy (pfd.visited);
6890       pfd.visited = 0;
6891     }
6892
6893   return result;
6894 }
6895
6896 /* Returns true if T depends on any template parameter.  */
6897
6898 int
6899 uses_template_parms (tree t)
6900 {
6901   bool dependent_p;
6902   int saved_processing_template_decl;
6903
6904   saved_processing_template_decl = processing_template_decl;
6905   if (!saved_processing_template_decl)
6906     processing_template_decl = 1;
6907   if (TYPE_P (t))
6908     dependent_p = dependent_type_p (t);
6909   else if (TREE_CODE (t) == TREE_VEC)
6910     dependent_p = any_dependent_template_arguments_p (t);
6911   else if (TREE_CODE (t) == TREE_LIST)
6912     dependent_p = (uses_template_parms (TREE_VALUE (t))
6913                    || uses_template_parms (TREE_CHAIN (t)));
6914   else if (TREE_CODE (t) == TYPE_DECL)
6915     dependent_p = dependent_type_p (TREE_TYPE (t));
6916   else if (DECL_P (t)
6917            || EXPR_P (t)
6918            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
6919            || TREE_CODE (t) == OVERLOAD
6920            || TREE_CODE (t) == BASELINK
6921            || TREE_CODE (t) == IDENTIFIER_NODE
6922            || TREE_CODE (t) == TRAIT_EXPR
6923            || TREE_CODE (t) == CONSTRUCTOR
6924            || CONSTANT_CLASS_P (t))
6925     dependent_p = (type_dependent_expression_p (t)
6926                    || value_dependent_expression_p (t));
6927   else
6928     {
6929       gcc_assert (t == error_mark_node);
6930       dependent_p = false;
6931     }
6932
6933   processing_template_decl = saved_processing_template_decl;
6934
6935   return dependent_p;
6936 }
6937
6938 /* Returns true if T depends on any template parameter with level LEVEL.  */
6939
6940 int
6941 uses_template_parms_level (tree t, int level)
6942 {
6943   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
6944                                  /*include_nondeduced_p=*/true);
6945 }
6946
6947 static int tinst_depth;
6948 extern int max_tinst_depth;
6949 #ifdef GATHER_STATISTICS
6950 int depth_reached;
6951 #endif
6952 static int tinst_level_tick;
6953 static int last_template_error_tick;
6954
6955 /* We're starting to instantiate D; record the template instantiation context
6956    for diagnostics and to restore it later.  */
6957
6958 static int
6959 push_tinst_level (tree d)
6960 {
6961   struct tinst_level *new_level;
6962
6963   if (tinst_depth >= max_tinst_depth)
6964     {
6965       /* If the instantiation in question still has unbound template parms,
6966          we don't really care if we can't instantiate it, so just return.
6967          This happens with base instantiation for implicit `typename'.  */
6968       if (uses_template_parms (d))
6969         return 0;
6970
6971       last_template_error_tick = tinst_level_tick;
6972       error ("template instantiation depth exceeds maximum of %d (use "
6973              "-ftemplate-depth-NN to increase the maximum) instantiating %qD",
6974              max_tinst_depth, d);
6975
6976       print_instantiation_context ();
6977
6978       return 0;
6979     }
6980
6981   new_level = GGC_NEW (struct tinst_level);
6982   new_level->decl = d;
6983   new_level->locus = input_location;
6984   new_level->in_system_header_p = in_system_header;
6985   new_level->next = current_tinst_level;
6986   current_tinst_level = new_level;
6987
6988   ++tinst_depth;
6989 #ifdef GATHER_STATISTICS
6990   if (tinst_depth > depth_reached)
6991     depth_reached = tinst_depth;
6992 #endif
6993
6994   ++tinst_level_tick;
6995   return 1;
6996 }
6997
6998 /* We're done instantiating this template; return to the instantiation
6999    context.  */
7000
7001 static void
7002 pop_tinst_level (void)
7003 {
7004   /* Restore the filename and line number stashed away when we started
7005      this instantiation.  */
7006   input_location = current_tinst_level->locus;
7007   current_tinst_level = current_tinst_level->next;
7008   --tinst_depth;
7009   ++tinst_level_tick;
7010 }
7011
7012 /* We're instantiating a deferred template; restore the template
7013    instantiation context in which the instantiation was requested, which
7014    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
7015
7016 static tree
7017 reopen_tinst_level (struct tinst_level *level)
7018 {
7019   struct tinst_level *t;
7020
7021   tinst_depth = 0;
7022   for (t = level; t; t = t->next)
7023     ++tinst_depth;
7024
7025   current_tinst_level = level;
7026   pop_tinst_level ();
7027   return level->decl;
7028 }
7029
7030 /* Returns the TINST_LEVEL which gives the original instantiation
7031    context.  */
7032
7033 struct tinst_level *
7034 outermost_tinst_level (void)
7035 {
7036   struct tinst_level *level = current_tinst_level;
7037   if (level)
7038     while (level->next)
7039       level = level->next;
7040   return level;
7041 }
7042
7043 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
7044
7045 bool
7046 parameter_of_template_p (tree parm, tree templ)
7047 {
7048   tree parms;
7049   int i;
7050
7051   if (!parm || !templ)
7052     return false;
7053
7054   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
7055   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7056
7057   parms = DECL_TEMPLATE_PARMS (templ);
7058   parms = INNERMOST_TEMPLATE_PARMS (parms);
7059
7060   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
7061     if (parm == TREE_VALUE (TREE_VEC_ELT (parms, i)))
7062       return true;
7063
7064   return false;
7065 }
7066
7067 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
7068    vector of template arguments, as for tsubst.
7069
7070    Returns an appropriate tsubst'd friend declaration.  */
7071
7072 static tree
7073 tsubst_friend_function (tree decl, tree args)
7074 {
7075   tree new_friend;
7076
7077   if (TREE_CODE (decl) == FUNCTION_DECL
7078       && DECL_TEMPLATE_INSTANTIATION (decl)
7079       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
7080     /* This was a friend declared with an explicit template
7081        argument list, e.g.:
7082
7083        friend void f<>(T);
7084
7085        to indicate that f was a template instantiation, not a new
7086        function declaration.  Now, we have to figure out what
7087        instantiation of what template.  */
7088     {
7089       tree template_id, arglist, fns;
7090       tree new_args;
7091       tree tmpl;
7092       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
7093
7094       /* Friend functions are looked up in the containing namespace scope.
7095          We must enter that scope, to avoid finding member functions of the
7096          current class with same name.  */
7097       push_nested_namespace (ns);
7098       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
7099                          tf_warning_or_error, NULL_TREE,
7100                          /*integral_constant_expression_p=*/false);
7101       pop_nested_namespace (ns);
7102       arglist = tsubst (DECL_TI_ARGS (decl), args,
7103                         tf_warning_or_error, NULL_TREE);
7104       template_id = lookup_template_function (fns, arglist);
7105
7106       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7107       tmpl = determine_specialization (template_id, new_friend,
7108                                        &new_args,
7109                                        /*need_member_template=*/0,
7110                                        TREE_VEC_LENGTH (args),
7111                                        tsk_none);
7112       return instantiate_template (tmpl, new_args, tf_error);
7113     }
7114
7115   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7116
7117   /* The NEW_FRIEND will look like an instantiation, to the
7118      compiler, but is not an instantiation from the point of view of
7119      the language.  For example, we might have had:
7120
7121      template <class T> struct S {
7122        template <class U> friend void f(T, U);
7123      };
7124
7125      Then, in S<int>, template <class U> void f(int, U) is not an
7126      instantiation of anything.  */
7127   if (new_friend == error_mark_node)
7128     return error_mark_node;
7129
7130   DECL_USE_TEMPLATE (new_friend) = 0;
7131   if (TREE_CODE (decl) == TEMPLATE_DECL)
7132     {
7133       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
7134       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
7135         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
7136     }
7137
7138   /* The mangled name for the NEW_FRIEND is incorrect.  The function
7139      is not a template instantiation and should not be mangled like
7140      one.  Therefore, we forget the mangling here; we'll recompute it
7141      later if we need it.  */
7142   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
7143     {
7144       SET_DECL_RTL (new_friend, NULL_RTX);
7145       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
7146     }
7147
7148   if (DECL_NAMESPACE_SCOPE_P (new_friend))
7149     {
7150       tree old_decl;
7151       tree new_friend_template_info;
7152       tree new_friend_result_template_info;
7153       tree ns;
7154       int  new_friend_is_defn;
7155
7156       /* We must save some information from NEW_FRIEND before calling
7157          duplicate decls since that function will free NEW_FRIEND if
7158          possible.  */
7159       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
7160       new_friend_is_defn =
7161             (DECL_INITIAL (DECL_TEMPLATE_RESULT
7162                            (template_for_substitution (new_friend)))
7163              != NULL_TREE);
7164       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
7165         {
7166           /* This declaration is a `primary' template.  */
7167           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
7168
7169           new_friend_result_template_info
7170             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
7171         }
7172       else
7173         new_friend_result_template_info = NULL_TREE;
7174
7175       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
7176       if (new_friend_is_defn)
7177         DECL_INITIAL (new_friend) = error_mark_node;
7178
7179       /* Inside pushdecl_namespace_level, we will push into the
7180          current namespace. However, the friend function should go
7181          into the namespace of the template.  */
7182       ns = decl_namespace_context (new_friend);
7183       push_nested_namespace (ns);
7184       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
7185       pop_nested_namespace (ns);
7186
7187       if (old_decl == error_mark_node)
7188         return error_mark_node;
7189
7190       if (old_decl != new_friend)
7191         {
7192           /* This new friend declaration matched an existing
7193              declaration.  For example, given:
7194
7195                template <class T> void f(T);
7196                template <class U> class C {
7197                  template <class T> friend void f(T) {}
7198                };
7199
7200              the friend declaration actually provides the definition
7201              of `f', once C has been instantiated for some type.  So,
7202              old_decl will be the out-of-class template declaration,
7203              while new_friend is the in-class definition.
7204
7205              But, if `f' was called before this point, the
7206              instantiation of `f' will have DECL_TI_ARGS corresponding
7207              to `T' but not to `U', references to which might appear
7208              in the definition of `f'.  Previously, the most general
7209              template for an instantiation of `f' was the out-of-class
7210              version; now it is the in-class version.  Therefore, we
7211              run through all specialization of `f', adding to their
7212              DECL_TI_ARGS appropriately.  In particular, they need a
7213              new set of outer arguments, corresponding to the
7214              arguments for this class instantiation.
7215
7216              The same situation can arise with something like this:
7217
7218                friend void f(int);
7219                template <class T> class C {
7220                  friend void f(T) {}
7221                };
7222
7223              when `C<int>' is instantiated.  Now, `f(int)' is defined
7224              in the class.  */
7225
7226           if (!new_friend_is_defn)
7227             /* On the other hand, if the in-class declaration does
7228                *not* provide a definition, then we don't want to alter
7229                existing definitions.  We can just leave everything
7230                alone.  */
7231             ;
7232           else
7233             {
7234               tree new_template = TI_TEMPLATE (new_friend_template_info);
7235               tree new_args = TI_ARGS (new_friend_template_info);
7236
7237               /* Overwrite whatever template info was there before, if
7238                  any, with the new template information pertaining to
7239                  the declaration.  */
7240               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
7241
7242               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
7243                 /* We should have called reregister_specialization in
7244                    duplicate_decls.  */
7245                 gcc_assert (retrieve_specialization (new_template,
7246                                                      new_args, 0)
7247                             == old_decl);
7248               else
7249                 {
7250                   tree t;
7251
7252                   /* Indicate that the old function template is a partial
7253                      instantiation.  */
7254                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
7255                     = new_friend_result_template_info;
7256
7257                   gcc_assert (new_template
7258                               == most_general_template (new_template));
7259                   gcc_assert (new_template != old_decl);
7260
7261                   /* Reassign any specializations already in the hash table
7262                      to the new more general template, and add the
7263                      additional template args.  */
7264                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
7265                        t != NULL_TREE;
7266                        t = TREE_CHAIN (t))
7267                     {
7268                       tree spec = TREE_VALUE (t);
7269                       spec_entry elt;
7270
7271                       elt.tmpl = old_decl;
7272                       elt.args = DECL_TI_ARGS (spec);
7273                       elt.spec = NULL_TREE;
7274
7275                       htab_remove_elt (decl_specializations, &elt);
7276
7277                       DECL_TI_ARGS (spec)
7278                         = add_outermost_template_args (new_args,
7279                                                        DECL_TI_ARGS (spec));
7280
7281                       register_specialization
7282                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
7283
7284                     }
7285                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
7286                 }
7287             }
7288
7289           /* The information from NEW_FRIEND has been merged into OLD_DECL
7290              by duplicate_decls.  */
7291           new_friend = old_decl;
7292         }
7293     }
7294   else
7295     {
7296       tree context = DECL_CONTEXT (new_friend);
7297       bool dependent_p;
7298
7299       /* In the code
7300            template <class T> class C {
7301              template <class U> friend void C1<U>::f (); // case 1
7302              friend void C2<T>::f ();                    // case 2
7303            };
7304          we only need to make sure CONTEXT is a complete type for
7305          case 2.  To distinguish between the two cases, we note that
7306          CONTEXT of case 1 remains dependent type after tsubst while
7307          this isn't true for case 2.  */
7308       ++processing_template_decl;
7309       dependent_p = dependent_type_p (context);
7310       --processing_template_decl;
7311
7312       if (!dependent_p
7313           && !complete_type_or_else (context, NULL_TREE))
7314         return error_mark_node;
7315
7316       if (COMPLETE_TYPE_P (context))
7317         {
7318           /* Check to see that the declaration is really present, and,
7319              possibly obtain an improved declaration.  */
7320           tree fn = check_classfn (context,
7321                                    new_friend, NULL_TREE);
7322
7323           if (fn)
7324             new_friend = fn;
7325         }
7326     }
7327
7328   return new_friend;
7329 }
7330
7331 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
7332    template arguments, as for tsubst.
7333
7334    Returns an appropriate tsubst'd friend type or error_mark_node on
7335    failure.  */
7336
7337 static tree
7338 tsubst_friend_class (tree friend_tmpl, tree args)
7339 {
7340   tree friend_type;
7341   tree tmpl;
7342   tree context;
7343
7344   context = DECL_CONTEXT (friend_tmpl);
7345
7346   if (context)
7347     {
7348       if (TREE_CODE (context) == NAMESPACE_DECL)
7349         push_nested_namespace (context);
7350       else
7351         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
7352     }
7353
7354   /* Look for a class template declaration.  We look for hidden names
7355      because two friend declarations of the same template are the
7356      same.  For example, in:
7357
7358        struct A { 
7359          template <typename> friend class F;
7360        };
7361        template <typename> struct B { 
7362          template <typename> friend class F;
7363        };
7364
7365      both F templates are the same.  */
7366   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
7367                            /*block_p=*/true, 0, 
7368                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
7369
7370   /* But, if we don't find one, it might be because we're in a
7371      situation like this:
7372
7373        template <class T>
7374        struct S {
7375          template <class U>
7376          friend struct S;
7377        };
7378
7379      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
7380      for `S<int>', not the TEMPLATE_DECL.  */
7381   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
7382     {
7383       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
7384       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
7385     }
7386
7387   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
7388     {
7389       /* The friend template has already been declared.  Just
7390          check to see that the declarations match, and install any new
7391          default parameters.  We must tsubst the default parameters,
7392          of course.  We only need the innermost template parameters
7393          because that is all that redeclare_class_template will look
7394          at.  */
7395       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
7396           > TMPL_ARGS_DEPTH (args))
7397         {
7398           tree parms;
7399           location_t saved_input_location;
7400           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
7401                                          args, tf_warning_or_error);
7402
7403           saved_input_location = input_location;
7404           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
7405           redeclare_class_template (TREE_TYPE (tmpl), parms);
7406           input_location = saved_input_location;
7407           
7408         }
7409
7410       friend_type = TREE_TYPE (tmpl);
7411     }
7412   else
7413     {
7414       /* The friend template has not already been declared.  In this
7415          case, the instantiation of the template class will cause the
7416          injection of this template into the global scope.  */
7417       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
7418       if (tmpl == error_mark_node)
7419         return error_mark_node;
7420
7421       /* The new TMPL is not an instantiation of anything, so we
7422          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
7423          the new type because that is supposed to be the corresponding
7424          template decl, i.e., TMPL.  */
7425       DECL_USE_TEMPLATE (tmpl) = 0;
7426       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
7427       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
7428       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
7429         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
7430
7431       /* Inject this template into the global scope.  */
7432       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
7433     }
7434
7435   if (context)
7436     {
7437       if (TREE_CODE (context) == NAMESPACE_DECL)
7438         pop_nested_namespace (context);
7439       else
7440         pop_nested_class ();
7441     }
7442
7443   return friend_type;
7444 }
7445
7446 /* Returns zero if TYPE cannot be completed later due to circularity.
7447    Otherwise returns one.  */
7448
7449 static int
7450 can_complete_type_without_circularity (tree type)
7451 {
7452   if (type == NULL_TREE || type == error_mark_node)
7453     return 0;
7454   else if (COMPLETE_TYPE_P (type))
7455     return 1;
7456   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
7457     return can_complete_type_without_circularity (TREE_TYPE (type));
7458   else if (CLASS_TYPE_P (type)
7459            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
7460     return 0;
7461   else
7462     return 1;
7463 }
7464
7465 /* Apply any attributes which had to be deferred until instantiation
7466    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
7467    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
7468
7469 static void
7470 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
7471                                 tree args, tsubst_flags_t complain, tree in_decl)
7472 {
7473   tree last_dep = NULL_TREE;
7474   tree t;
7475   tree *p;
7476
7477   for (t = attributes; t; t = TREE_CHAIN (t))
7478     if (ATTR_IS_DEPENDENT (t))
7479       {
7480         last_dep = t;
7481         attributes = copy_list (attributes);
7482         break;
7483       }
7484
7485   if (DECL_P (*decl_p))
7486     {
7487       if (TREE_TYPE (*decl_p) == error_mark_node)
7488         return;
7489       p = &DECL_ATTRIBUTES (*decl_p);
7490     }
7491   else
7492     p = &TYPE_ATTRIBUTES (*decl_p);
7493
7494   if (last_dep)
7495     {
7496       tree late_attrs = NULL_TREE;
7497       tree *q = &late_attrs;
7498
7499       for (*p = attributes; *p; )
7500         {
7501           t = *p;
7502           if (ATTR_IS_DEPENDENT (t))
7503             {
7504               *p = TREE_CHAIN (t);
7505               TREE_CHAIN (t) = NULL_TREE;
7506               /* If the first attribute argument is an identifier, don't
7507                  pass it through tsubst.  Attributes like mode, format,
7508                  cleanup and several target specific attributes expect it
7509                  unmodified.  */
7510               if (TREE_VALUE (t)
7511                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
7512                   && TREE_VALUE (TREE_VALUE (t))
7513                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
7514                       == IDENTIFIER_NODE))
7515                 {
7516                   tree chain
7517                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
7518                                    in_decl,
7519                                    /*integral_constant_expression_p=*/false);
7520                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
7521                     TREE_VALUE (t)
7522                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
7523                                    chain);
7524                 }
7525               else
7526                 TREE_VALUE (t)
7527                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
7528                                  /*integral_constant_expression_p=*/false);
7529               *q = t;
7530               q = &TREE_CHAIN (t);
7531             }
7532           else
7533             p = &TREE_CHAIN (t);
7534         }
7535
7536       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
7537     }
7538 }
7539
7540 /* Perform (or defer) access check for typedefs that were referenced
7541    from within the template TMPL code.
7542    This is a subroutine of instantiate_template and instantiate_class_template.
7543    TMPL is the template to consider and TARGS is the list of arguments of
7544    that template.  */
7545
7546 static void
7547 perform_typedefs_access_check (tree tmpl, tree targs)
7548 {
7549   location_t saved_location;
7550   int i;
7551   qualified_typedef_usage_t *iter;
7552
7553   if (!tmpl
7554       || (!CLASS_TYPE_P (tmpl)
7555           && TREE_CODE (tmpl) != FUNCTION_DECL))
7556     return;
7557
7558   saved_location = input_location;
7559   for (i = 0;
7560        VEC_iterate (qualified_typedef_usage_t,
7561                     get_types_needing_access_check (tmpl),
7562                     i, iter);
7563         ++i)
7564     {
7565       tree type_decl = iter->typedef_decl;
7566       tree type_scope = iter->context;
7567
7568       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
7569         continue;
7570
7571       if (uses_template_parms (type_decl))
7572         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
7573       if (uses_template_parms (type_scope))
7574         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
7575
7576       /* Make access check error messages point to the location
7577          of the use of the typedef.  */
7578       input_location = iter->locus;
7579       perform_or_defer_access_check (TYPE_BINFO (type_scope),
7580                                      type_decl, type_decl);
7581     }
7582     input_location = saved_location;
7583 }
7584
7585 tree
7586 instantiate_class_template (tree type)
7587 {
7588   tree templ, args, pattern, t, member;
7589   tree typedecl;
7590   tree pbinfo;
7591   tree base_list;
7592   unsigned int saved_maximum_field_alignment;
7593
7594   if (type == error_mark_node)
7595     return error_mark_node;
7596
7597   if (TYPE_BEING_DEFINED (type)
7598       || COMPLETE_TYPE_P (type)
7599       || uses_template_parms (type))
7600     return type;
7601
7602   /* Figure out which template is being instantiated.  */
7603   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
7604   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7605
7606   /* Determine what specialization of the original template to
7607      instantiate.  */
7608   t = most_specialized_class (type, templ);
7609   if (t == error_mark_node)
7610     {
7611       TYPE_BEING_DEFINED (type) = 1;
7612       return error_mark_node;
7613     }
7614   else if (t)
7615     {
7616       /* This TYPE is actually an instantiation of a partial
7617          specialization.  We replace the innermost set of ARGS with
7618          the arguments appropriate for substitution.  For example,
7619          given:
7620
7621            template <class T> struct S {};
7622            template <class T> struct S<T*> {};
7623
7624          and supposing that we are instantiating S<int*>, ARGS will
7625          presently be {int*} -- but we need {int}.  */
7626       pattern = TREE_TYPE (t);
7627       args = TREE_PURPOSE (t);
7628     }
7629   else
7630     {
7631       pattern = TREE_TYPE (templ);
7632       args = CLASSTYPE_TI_ARGS (type);
7633     }
7634
7635   /* If the template we're instantiating is incomplete, then clearly
7636      there's nothing we can do.  */
7637   if (!COMPLETE_TYPE_P (pattern))
7638     return type;
7639
7640   /* If we've recursively instantiated too many templates, stop.  */
7641   if (! push_tinst_level (type))
7642     return type;
7643
7644   /* Now we're really doing the instantiation.  Mark the type as in
7645      the process of being defined.  */
7646   TYPE_BEING_DEFINED (type) = 1;
7647
7648   /* We may be in the middle of deferred access check.  Disable
7649      it now.  */
7650   push_deferring_access_checks (dk_no_deferred);
7651
7652   push_to_top_level ();
7653   /* Use #pragma pack from the template context.  */
7654   saved_maximum_field_alignment = maximum_field_alignment;
7655   maximum_field_alignment = TYPE_PRECISION (pattern);
7656
7657   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
7658
7659   /* Set the input location to the most specialized template definition.
7660      This is needed if tsubsting causes an error.  */
7661   typedecl = TYPE_MAIN_DECL (pattern);
7662   input_location = DECL_SOURCE_LOCATION (typedecl);
7663
7664   TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
7665   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
7666   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
7667   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
7668   TYPE_HAS_ASSIGN_REF (type) = TYPE_HAS_ASSIGN_REF (pattern);
7669   TYPE_HAS_CONST_ASSIGN_REF (type) = TYPE_HAS_CONST_ASSIGN_REF (pattern);
7670   TYPE_HAS_INIT_REF (type) = TYPE_HAS_INIT_REF (pattern);
7671   TYPE_HAS_CONST_INIT_REF (type) = TYPE_HAS_CONST_INIT_REF (pattern);
7672   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
7673   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
7674   TYPE_PACKED (type) = TYPE_PACKED (pattern);
7675   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
7676   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
7677   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
7678   if (ANON_AGGR_TYPE_P (pattern))
7679     SET_ANON_AGGR_TYPE_P (type);
7680   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
7681     {
7682       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
7683       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
7684     }
7685
7686   pbinfo = TYPE_BINFO (pattern);
7687
7688   /* We should never instantiate a nested class before its enclosing
7689      class; we need to look up the nested class by name before we can
7690      instantiate it, and that lookup should instantiate the enclosing
7691      class.  */
7692   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
7693               || COMPLETE_TYPE_P (TYPE_CONTEXT (type))
7694               || TYPE_BEING_DEFINED (TYPE_CONTEXT (type)));
7695
7696   base_list = NULL_TREE;
7697   if (BINFO_N_BASE_BINFOS (pbinfo))
7698     {
7699       tree pbase_binfo;
7700       tree context = TYPE_CONTEXT (type);
7701       tree pushed_scope;
7702       int i;
7703
7704       /* We must enter the scope containing the type, as that is where
7705          the accessibility of types named in dependent bases are
7706          looked up from.  */
7707       pushed_scope = push_scope (context ? context : global_namespace);
7708
7709       /* Substitute into each of the bases to determine the actual
7710          basetypes.  */
7711       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
7712         {
7713           tree base;
7714           tree access = BINFO_BASE_ACCESS (pbinfo, i);
7715           tree expanded_bases = NULL_TREE;
7716           int idx, len = 1;
7717
7718           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
7719             {
7720               expanded_bases = 
7721                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
7722                                        args, tf_error, NULL_TREE);
7723               if (expanded_bases == error_mark_node)
7724                 continue;
7725
7726               len = TREE_VEC_LENGTH (expanded_bases);
7727             }
7728
7729           for (idx = 0; idx < len; idx++)
7730             {
7731               if (expanded_bases)
7732                 /* Extract the already-expanded base class.  */
7733                 base = TREE_VEC_ELT (expanded_bases, idx);
7734               else
7735                 /* Substitute to figure out the base class.  */
7736                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
7737                                NULL_TREE);
7738
7739               if (base == error_mark_node)
7740                 continue;
7741
7742               base_list = tree_cons (access, base, base_list);
7743               if (BINFO_VIRTUAL_P (pbase_binfo))
7744                 TREE_TYPE (base_list) = integer_type_node;
7745             }
7746         }
7747
7748       /* The list is now in reverse order; correct that.  */
7749       base_list = nreverse (base_list);
7750
7751       if (pushed_scope)
7752         pop_scope (pushed_scope);
7753     }
7754   /* Now call xref_basetypes to set up all the base-class
7755      information.  */
7756   xref_basetypes (type, base_list);
7757
7758   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
7759                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
7760                                   args, tf_error, NULL_TREE);
7761
7762   /* Now that our base classes are set up, enter the scope of the
7763      class, so that name lookups into base classes, etc. will work
7764      correctly.  This is precisely analogous to what we do in
7765      begin_class_definition when defining an ordinary non-template
7766      class, except we also need to push the enclosing classes.  */
7767   push_nested_class (type);
7768
7769   /* Now members are processed in the order of declaration.  */
7770   for (member = CLASSTYPE_DECL_LIST (pattern);
7771        member; member = TREE_CHAIN (member))
7772     {
7773       tree t = TREE_VALUE (member);
7774
7775       if (TREE_PURPOSE (member))
7776         {
7777           if (TYPE_P (t))
7778             {
7779               /* Build new CLASSTYPE_NESTED_UTDS.  */
7780
7781               tree newtag;
7782               bool class_template_p;
7783
7784               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
7785                                   && TYPE_LANG_SPECIFIC (t)
7786                                   && CLASSTYPE_IS_TEMPLATE (t));
7787               /* If the member is a class template, then -- even after
7788                  substitution -- there may be dependent types in the
7789                  template argument list for the class.  We increment
7790                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
7791                  that function will assume that no types are dependent
7792                  when outside of a template.  */
7793               if (class_template_p)
7794                 ++processing_template_decl;
7795               newtag = tsubst (t, args, tf_error, NULL_TREE);
7796               if (class_template_p)
7797                 --processing_template_decl;
7798               if (newtag == error_mark_node)
7799                 continue;
7800
7801               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
7802                 {
7803                   tree name = TYPE_IDENTIFIER (t);
7804
7805                   if (class_template_p)
7806                     /* Unfortunately, lookup_template_class sets
7807                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
7808                        instantiation (i.e., for the type of a member
7809                        template class nested within a template class.)
7810                        This behavior is required for
7811                        maybe_process_partial_specialization to work
7812                        correctly, but is not accurate in this case;
7813                        the TAG is not an instantiation of anything.
7814                        (The corresponding TEMPLATE_DECL is an
7815                        instantiation, but the TYPE is not.) */
7816                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
7817
7818                   /* Now, we call pushtag to put this NEWTAG into the scope of
7819                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
7820                      pushtag calling push_template_decl.  We don't have to do
7821                      this for enums because it will already have been done in
7822                      tsubst_enum.  */
7823                   if (name)
7824                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
7825                   pushtag (name, newtag, /*tag_scope=*/ts_current);
7826                 }
7827             }
7828           else if (TREE_CODE (t) == FUNCTION_DECL
7829                    || DECL_FUNCTION_TEMPLATE_P (t))
7830             {
7831               /* Build new TYPE_METHODS.  */
7832               tree r;
7833
7834               if (TREE_CODE (t) == TEMPLATE_DECL)
7835                 ++processing_template_decl;
7836               r = tsubst (t, args, tf_error, NULL_TREE);
7837               if (TREE_CODE (t) == TEMPLATE_DECL)
7838                 --processing_template_decl;
7839               set_current_access_from_decl (r);
7840               finish_member_declaration (r);
7841             }
7842           else
7843             {
7844               /* Build new TYPE_FIELDS.  */
7845               if (TREE_CODE (t) == STATIC_ASSERT)
7846                 {
7847                   tree condition = 
7848                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
7849                                  tf_warning_or_error, NULL_TREE,
7850                                  /*integral_constant_expression_p=*/true);
7851                   finish_static_assert (condition,
7852                                         STATIC_ASSERT_MESSAGE (t), 
7853                                         STATIC_ASSERT_SOURCE_LOCATION (t),
7854                                         /*member_p=*/true);
7855                 }
7856               else if (TREE_CODE (t) != CONST_DECL)
7857                 {
7858                   tree r;
7859
7860                   /* The file and line for this declaration, to
7861                      assist in error message reporting.  Since we
7862                      called push_tinst_level above, we don't need to
7863                      restore these.  */
7864                   input_location = DECL_SOURCE_LOCATION (t);
7865
7866                   if (TREE_CODE (t) == TEMPLATE_DECL)
7867                     ++processing_template_decl;
7868                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
7869                   if (TREE_CODE (t) == TEMPLATE_DECL)
7870                     --processing_template_decl;
7871                   if (TREE_CODE (r) == VAR_DECL)
7872                     {
7873                       /* In [temp.inst]:
7874
7875                            [t]he initialization (and any associated
7876                            side-effects) of a static data member does
7877                            not occur unless the static data member is
7878                            itself used in a way that requires the
7879                            definition of the static data member to
7880                            exist.
7881
7882                          Therefore, we do not substitute into the
7883                          initialized for the static data member here.  */
7884                       finish_static_data_member_decl
7885                         (r,
7886                          /*init=*/NULL_TREE,
7887                          /*init_const_expr_p=*/false,
7888                          /*asmspec_tree=*/NULL_TREE,
7889                          /*flags=*/0);
7890                       if (DECL_INITIALIZED_IN_CLASS_P (r))
7891                         check_static_variable_definition (r, TREE_TYPE (r));
7892                     }
7893                   else if (TREE_CODE (r) == FIELD_DECL)
7894                     {
7895                       /* Determine whether R has a valid type and can be
7896                          completed later.  If R is invalid, then it is
7897                          replaced by error_mark_node so that it will not be
7898                          added to TYPE_FIELDS.  */
7899                       tree rtype = TREE_TYPE (r);
7900                       if (can_complete_type_without_circularity (rtype))
7901                         complete_type (rtype);
7902
7903                       if (!COMPLETE_TYPE_P (rtype))
7904                         {
7905                           cxx_incomplete_type_error (r, rtype);
7906                           r = error_mark_node;
7907                         }
7908                     }
7909
7910                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
7911                      such a thing will already have been added to the field
7912                      list by tsubst_enum in finish_member_declaration in the
7913                      CLASSTYPE_NESTED_UTDS case above.  */
7914                   if (!(TREE_CODE (r) == TYPE_DECL
7915                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
7916                         && DECL_ARTIFICIAL (r)))
7917                     {
7918                       set_current_access_from_decl (r);
7919                       finish_member_declaration (r);
7920                     }
7921                 }
7922             }
7923         }
7924       else
7925         {
7926           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
7927             {
7928               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
7929
7930               tree friend_type = t;
7931               bool adjust_processing_template_decl = false;
7932
7933               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7934                 {
7935                   /* template <class T> friend class C;  */
7936                   friend_type = tsubst_friend_class (friend_type, args);
7937                   adjust_processing_template_decl = true;
7938                 }
7939               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
7940                 {
7941                   /* template <class T> friend class C::D;  */
7942                   friend_type = tsubst (friend_type, args,
7943                                         tf_warning_or_error, NULL_TREE);
7944                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
7945                     friend_type = TREE_TYPE (friend_type);
7946                   adjust_processing_template_decl = true;
7947                 }
7948               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
7949                 {
7950                   /* This could be either
7951
7952                        friend class T::C;
7953
7954                      when dependent_type_p is false or
7955
7956                        template <class U> friend class T::C;
7957
7958                      otherwise.  */
7959                   friend_type = tsubst (friend_type, args,
7960                                         tf_warning_or_error, NULL_TREE);
7961                   /* Bump processing_template_decl for correct
7962                      dependent_type_p calculation.  */
7963                   ++processing_template_decl;
7964                   if (dependent_type_p (friend_type))
7965                     adjust_processing_template_decl = true;
7966                   --processing_template_decl;
7967                 }
7968               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
7969                        && hidden_name_p (TYPE_NAME (friend_type)))
7970                 {
7971                   /* friend class C;
7972
7973                      where C hasn't been declared yet.  Let's lookup name
7974                      from namespace scope directly, bypassing any name that
7975                      come from dependent base class.  */
7976                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
7977
7978                   /* The call to xref_tag_from_type does injection for friend
7979                      classes.  */
7980                   push_nested_namespace (ns);
7981                   friend_type =
7982                     xref_tag_from_type (friend_type, NULL_TREE,
7983                                         /*tag_scope=*/ts_current);
7984                   pop_nested_namespace (ns);
7985                 }
7986               else if (uses_template_parms (friend_type))
7987                 /* friend class C<T>;  */
7988                 friend_type = tsubst (friend_type, args,
7989                                       tf_warning_or_error, NULL_TREE);
7990               /* Otherwise it's
7991
7992                    friend class C;
7993
7994                  where C is already declared or
7995
7996                    friend class C<int>;
7997
7998                  We don't have to do anything in these cases.  */
7999
8000               if (adjust_processing_template_decl)
8001                 /* Trick make_friend_class into realizing that the friend
8002                    we're adding is a template, not an ordinary class.  It's
8003                    important that we use make_friend_class since it will
8004                    perform some error-checking and output cross-reference
8005                    information.  */
8006                 ++processing_template_decl;
8007
8008               if (friend_type != error_mark_node)
8009                 make_friend_class (type, friend_type, /*complain=*/false);
8010
8011               if (adjust_processing_template_decl)
8012                 --processing_template_decl;
8013             }
8014           else
8015             {
8016               /* Build new DECL_FRIENDLIST.  */
8017               tree r;
8018
8019               /* The file and line for this declaration, to
8020                  assist in error message reporting.  Since we
8021                  called push_tinst_level above, we don't need to
8022                  restore these.  */
8023               input_location = DECL_SOURCE_LOCATION (t);
8024
8025               if (TREE_CODE (t) == TEMPLATE_DECL)
8026                 {
8027                   ++processing_template_decl;
8028                   push_deferring_access_checks (dk_no_check);
8029                 }
8030
8031               r = tsubst_friend_function (t, args);
8032               add_friend (type, r, /*complain=*/false);
8033               if (TREE_CODE (t) == TEMPLATE_DECL)
8034                 {
8035                   pop_deferring_access_checks ();
8036                   --processing_template_decl;
8037                 }
8038             }
8039         }
8040     }
8041
8042   /* Set the file and line number information to whatever is given for
8043      the class itself.  This puts error messages involving generated
8044      implicit functions at a predictable point, and the same point
8045      that would be used for non-template classes.  */
8046   input_location = DECL_SOURCE_LOCATION (typedecl);
8047
8048   unreverse_member_declarations (type);
8049   finish_struct_1 (type);
8050   TYPE_BEING_DEFINED (type) = 0;
8051
8052   /* Now that the class is complete, instantiate default arguments for
8053      any member functions.  We don't do this earlier because the
8054      default arguments may reference members of the class.  */
8055   if (!PRIMARY_TEMPLATE_P (templ))
8056     for (t = TYPE_METHODS (type); t; t = TREE_CHAIN (t))
8057       if (TREE_CODE (t) == FUNCTION_DECL
8058           /* Implicitly generated member functions will not have template
8059              information; they are not instantiations, but instead are
8060              created "fresh" for each instantiation.  */
8061           && DECL_TEMPLATE_INFO (t))
8062         tsubst_default_arguments (t);
8063
8064   /* Some typedefs referenced from within the template code need to be access
8065      checked at template instantiation time, i.e now. These types were
8066      added to the template at parsing time. Let's get those and perform
8067      the access checks then.  */
8068   perform_typedefs_access_check (pattern, args);
8069   perform_deferred_access_checks ();
8070   pop_nested_class ();
8071   maximum_field_alignment = saved_maximum_field_alignment;
8072   pop_from_top_level ();
8073   pop_deferring_access_checks ();
8074   pop_tinst_level ();
8075
8076   /* The vtable for a template class can be emitted in any translation
8077      unit in which the class is instantiated.  When there is no key
8078      method, however, finish_struct_1 will already have added TYPE to
8079      the keyed_classes list.  */
8080   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
8081     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
8082
8083   return type;
8084 }
8085
8086 static tree
8087 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8088 {
8089   tree r;
8090
8091   if (!t)
8092     r = t;
8093   else if (TYPE_P (t))
8094     r = tsubst (t, args, complain, in_decl);
8095   else
8096     {
8097       r = tsubst_expr (t, args, complain, in_decl,
8098                        /*integral_constant_expression_p=*/true);
8099       r = fold_non_dependent_expr (r);
8100     }
8101   return r;
8102 }
8103
8104 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
8105    NONTYPE_ARGUMENT_PACK.  */
8106
8107 static tree
8108 make_fnparm_pack (tree spec_parm)
8109 {
8110   /* Collect all of the extra "packed" parameters into an
8111      argument pack.  */
8112   tree parmvec;
8113   tree parmtypevec;
8114   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
8115   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
8116   int i, len = list_length (spec_parm);
8117
8118   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
8119   parmvec = make_tree_vec (len);
8120   parmtypevec = make_tree_vec (len);
8121   for (i = 0; i < len; i++, spec_parm = TREE_CHAIN (spec_parm))
8122     {
8123       TREE_VEC_ELT (parmvec, i) = spec_parm;
8124       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
8125     }
8126
8127   /* Build the argument packs.  */
8128   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
8129   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
8130   TREE_TYPE (argpack) = argtypepack;
8131
8132   return argpack;
8133 }        
8134
8135 /* Substitute ARGS into T, which is an pack expansion
8136    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
8137    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
8138    (if only a partial substitution could be performed) or
8139    ERROR_MARK_NODE if there was an error.  */
8140 tree
8141 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
8142                        tree in_decl)
8143 {
8144   tree pattern;
8145   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
8146   int i, len = -1;
8147   tree result;
8148   int incomplete = 0;
8149   bool very_local_specializations = false;
8150
8151   gcc_assert (PACK_EXPANSION_P (t));
8152   pattern = PACK_EXPANSION_PATTERN (t);
8153
8154   /* Determine the argument packs that will instantiate the parameter
8155      packs used in the expansion expression. While we're at it,
8156      compute the number of arguments to be expanded and make sure it
8157      is consistent.  */
8158   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
8159        pack = TREE_CHAIN (pack))
8160     {
8161       tree parm_pack = TREE_VALUE (pack);
8162       tree arg_pack = NULL_TREE;
8163       tree orig_arg = NULL_TREE;
8164
8165       if (TREE_CODE (parm_pack) == PARM_DECL)
8166         {
8167           arg_pack = retrieve_local_specialization (parm_pack);
8168           if (arg_pack == NULL_TREE)
8169             {
8170               /* This can happen for a parameter name used later in a function
8171                  declaration (such as in a late-specified return type).  Just
8172                  make a dummy decl, since it's only used for its type.  */
8173               gcc_assert (cp_unevaluated_operand != 0);
8174               arg_pack = tsubst_decl (parm_pack, args, complain);
8175               arg_pack = make_fnparm_pack (arg_pack);
8176             }
8177         }
8178       else
8179         {
8180           int level, idx, levels;
8181           template_parm_level_and_index (parm_pack, &level, &idx);
8182
8183           levels = TMPL_ARGS_DEPTH (args);
8184           if (level <= levels)
8185             arg_pack = TMPL_ARG (args, level, idx);
8186         }
8187
8188       orig_arg = arg_pack;
8189       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
8190         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
8191       
8192       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
8193         /* This can only happen if we forget to expand an argument
8194            pack somewhere else. Just return an error, silently.  */
8195         {
8196           result = make_tree_vec (1);
8197           TREE_VEC_ELT (result, 0) = error_mark_node;
8198           return result;
8199         }
8200
8201       if (arg_pack
8202           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
8203           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
8204         {
8205           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
8206           tree pattern = PACK_EXPANSION_PATTERN (expansion);
8207           if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
8208               || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
8209             /* The argument pack that the parameter maps to is just an
8210                expansion of the parameter itself, such as one would
8211                find in the implicit typedef of a class inside the
8212                class itself.  Consider this parameter "unsubstituted",
8213                so that we will maintain the outer pack expansion.  */
8214             arg_pack = NULL_TREE;
8215         }
8216           
8217       if (arg_pack)
8218         {
8219           int my_len = 
8220             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
8221
8222           /* It's all-or-nothing with incomplete argument packs.  */
8223           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8224             return error_mark_node;
8225           
8226           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8227             incomplete = 1;
8228
8229           if (len < 0)
8230             len = my_len;
8231           else if (len != my_len)
8232             {
8233               if (incomplete)
8234                 /* We got explicit args for some packs but not others;
8235                    do nothing now and try again after deduction.  */
8236                 return t;
8237               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
8238                 error ("mismatched argument pack lengths while expanding "
8239                        "%<%T%>",
8240                        pattern);
8241               else
8242                 error ("mismatched argument pack lengths while expanding "
8243                        "%<%E%>",
8244                        pattern);
8245               return error_mark_node;
8246             }
8247
8248           /* Keep track of the parameter packs and their corresponding
8249              argument packs.  */
8250           packs = tree_cons (parm_pack, arg_pack, packs);
8251           TREE_TYPE (packs) = orig_arg;
8252         }
8253       else
8254         /* We can't substitute for this parameter pack.  */
8255         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
8256                                          TREE_VALUE (pack),
8257                                          unsubstituted_packs);
8258     }
8259
8260   /* We cannot expand this expansion expression, because we don't have
8261      all of the argument packs we need. Substitute into the pattern
8262      and return a PACK_EXPANSION_*. The caller will need to deal with
8263      that.  */
8264   if (unsubstituted_packs)
8265     {
8266       tree new_pat;
8267       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8268         new_pat = tsubst_expr (pattern, args, complain, in_decl,
8269                                /*integral_constant_expression_p=*/false);
8270       else
8271         new_pat = tsubst (pattern, args, complain, in_decl);
8272       return make_pack_expansion (new_pat);
8273     }
8274
8275   /* We could not find any argument packs that work.  */
8276   if (len < 0)
8277     return error_mark_node;
8278
8279   if (!local_specializations)
8280     {
8281       /* We're in a late-specified return type, so we don't have a local
8282          specializations table.  Create one for doing this expansion.  */
8283       very_local_specializations = true;
8284       local_specializations = htab_create (37,
8285                                            hash_local_specialization,
8286                                            eq_local_specializations,
8287                                            NULL);
8288     }
8289
8290   /* For each argument in each argument pack, substitute into the
8291      pattern.  */
8292   result = make_tree_vec (len + incomplete);
8293   for (i = 0; i < len + incomplete; ++i)
8294     {
8295       /* For parameter pack, change the substitution of the parameter
8296          pack to the ith argument in its argument pack, then expand
8297          the pattern.  */
8298       for (pack = packs; pack; pack = TREE_CHAIN (pack))
8299         {
8300           tree parm = TREE_PURPOSE (pack);
8301
8302           if (TREE_CODE (parm) == PARM_DECL)
8303             {
8304               /* Select the Ith argument from the pack.  */
8305               tree arg = make_node (ARGUMENT_PACK_SELECT);
8306               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
8307               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
8308               mark_used (parm);
8309               register_local_specialization (arg, parm);
8310             }
8311           else
8312             {
8313               tree value = parm;
8314               int idx, level;
8315               template_parm_level_and_index (parm, &level, &idx);
8316               
8317               if (i < len) 
8318                 {
8319                   /* Select the Ith argument from the pack. */
8320                   value = make_node (ARGUMENT_PACK_SELECT);
8321                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
8322                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
8323                 }
8324
8325               /* Update the corresponding argument.  */
8326               TMPL_ARG (args, level, idx) = value;
8327             }
8328         }
8329
8330       /* Substitute into the PATTERN with the altered arguments.  */
8331       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8332         TREE_VEC_ELT (result, i) = 
8333           tsubst_expr (pattern, args, complain, in_decl,
8334                        /*integral_constant_expression_p=*/false);
8335       else
8336         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
8337
8338       if (i == len)
8339         /* When we have incomplete argument packs, the last "expanded"
8340            result is itself a pack expansion, which allows us
8341            to deduce more arguments.  */
8342         TREE_VEC_ELT (result, i) = 
8343           make_pack_expansion (TREE_VEC_ELT (result, i));
8344
8345       if (TREE_VEC_ELT (result, i) == error_mark_node)
8346         {
8347           result = error_mark_node;
8348           break;
8349         }
8350     }
8351
8352   /* Update ARGS to restore the substitution from parameter packs to
8353      their argument packs.  */
8354   for (pack = packs; pack; pack = TREE_CHAIN (pack))
8355     {
8356       tree parm = TREE_PURPOSE (pack);
8357
8358       if (TREE_CODE (parm) == PARM_DECL)
8359         register_local_specialization (TREE_TYPE (pack), parm);
8360       else
8361         {
8362           int idx, level;
8363           template_parm_level_and_index (parm, &level, &idx);
8364           
8365           /* Update the corresponding argument.  */
8366           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
8367             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
8368               TREE_TYPE (pack);
8369           else
8370             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
8371         }
8372     }
8373
8374   if (very_local_specializations)
8375     {
8376       htab_delete (local_specializations);
8377       local_specializations = NULL;
8378     }
8379   
8380   return result;
8381 }
8382
8383 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
8384    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
8385    parameter packs; all parms generated from a function parameter pack will
8386    have the same DECL_PARM_INDEX.  */
8387
8388 tree
8389 get_pattern_parm (tree parm, tree tmpl)
8390 {
8391   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
8392   tree patparm;
8393
8394   if (DECL_ARTIFICIAL (parm))
8395     {
8396       for (patparm = DECL_ARGUMENTS (pattern);
8397            patparm; patparm = TREE_CHAIN (patparm))
8398         if (DECL_ARTIFICIAL (patparm)
8399             && DECL_NAME (parm) == DECL_NAME (patparm))
8400           break;
8401     }
8402   else
8403     {
8404       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
8405       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
8406       gcc_assert (DECL_PARM_INDEX (patparm)
8407                   == DECL_PARM_INDEX (parm));
8408     }
8409
8410   return patparm;
8411 }
8412
8413 /* Substitute ARGS into the vector or list of template arguments T.  */
8414
8415 static tree
8416 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8417 {
8418   tree orig_t = t;
8419   int len = TREE_VEC_LENGTH (t);
8420   int need_new = 0, i, expanded_len_adjust = 0, out;
8421   tree *elts = (tree *) alloca (len * sizeof (tree));
8422
8423   for (i = 0; i < len; i++)
8424     {
8425       tree orig_arg = TREE_VEC_ELT (t, i);
8426       tree new_arg;
8427
8428       if (TREE_CODE (orig_arg) == TREE_VEC)
8429         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
8430       else if (PACK_EXPANSION_P (orig_arg))
8431         {
8432           /* Substitute into an expansion expression.  */
8433           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
8434
8435           if (TREE_CODE (new_arg) == TREE_VEC)
8436             /* Add to the expanded length adjustment the number of
8437                expanded arguments. We subtract one from this
8438                measurement, because the argument pack expression
8439                itself is already counted as 1 in
8440                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
8441                the argument pack is empty.  */
8442             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
8443         }
8444       else if (ARGUMENT_PACK_P (orig_arg))
8445         {
8446           /* Substitute into each of the arguments.  */
8447           new_arg = TYPE_P (orig_arg)
8448             ? cxx_make_type (TREE_CODE (orig_arg))
8449             : make_node (TREE_CODE (orig_arg));
8450           
8451           SET_ARGUMENT_PACK_ARGS (
8452             new_arg,
8453             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
8454                                   args, complain, in_decl));
8455
8456           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
8457             new_arg = error_mark_node;
8458
8459           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
8460             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
8461                                           complain, in_decl);
8462             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
8463
8464             if (TREE_TYPE (new_arg) == error_mark_node)
8465               new_arg = error_mark_node;
8466           }
8467         }
8468       else
8469         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
8470
8471       if (new_arg == error_mark_node)
8472         return error_mark_node;
8473
8474       elts[i] = new_arg;
8475       if (new_arg != orig_arg)
8476         need_new = 1;
8477     }
8478
8479   if (!need_new)
8480     return t;
8481
8482   /* Make space for the expanded arguments coming from template
8483      argument packs.  */
8484   t = make_tree_vec (len + expanded_len_adjust);
8485   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
8486      arguments for a member template.
8487      In that case each TREE_VEC in ORIG_T represents a level of template
8488      arguments, and ORIG_T won't carry any non defaulted argument count.
8489      It will rather be the nested TREE_VECs that will carry one.
8490      In other words, ORIG_T carries a non defaulted argument count only
8491      if it doesn't contain any nested TREE_VEC.  */
8492   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
8493     {
8494       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
8495       count += expanded_len_adjust;
8496       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
8497     }
8498   for (i = 0, out = 0; i < len; i++)
8499     {
8500       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
8501            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
8502           && TREE_CODE (elts[i]) == TREE_VEC)
8503         {
8504           int idx;
8505
8506           /* Now expand the template argument pack "in place".  */
8507           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
8508             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
8509         }
8510       else
8511         {
8512           TREE_VEC_ELT (t, out) = elts[i];
8513           out++;
8514         }
8515     }
8516
8517   return t;
8518 }
8519
8520 /* Return the result of substituting ARGS into the template parameters
8521    given by PARMS.  If there are m levels of ARGS and m + n levels of
8522    PARMS, then the result will contain n levels of PARMS.  For
8523    example, if PARMS is `template <class T> template <class U>
8524    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
8525    result will be `template <int*, double, class V>'.  */
8526
8527 static tree
8528 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
8529 {
8530   tree r = NULL_TREE;
8531   tree* new_parms;
8532
8533   /* When substituting into a template, we must set
8534      PROCESSING_TEMPLATE_DECL as the template parameters may be
8535      dependent if they are based on one-another, and the dependency
8536      predicates are short-circuit outside of templates.  */
8537   ++processing_template_decl;
8538
8539   for (new_parms = &r;
8540        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
8541        new_parms = &(TREE_CHAIN (*new_parms)),
8542          parms = TREE_CHAIN (parms))
8543     {
8544       tree new_vec =
8545         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
8546       int i;
8547
8548       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
8549         {
8550           tree tuple;
8551           tree default_value;
8552           tree parm_decl;
8553
8554           if (parms == error_mark_node)
8555             continue;
8556
8557           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
8558
8559           if (tuple == error_mark_node)
8560             continue;
8561
8562           default_value = TREE_PURPOSE (tuple);
8563           parm_decl = TREE_VALUE (tuple);
8564
8565           parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
8566           if (TREE_CODE (parm_decl) == PARM_DECL
8567               && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
8568             parm_decl = error_mark_node;
8569           default_value = tsubst_template_arg (default_value, args,
8570                                                complain, NULL_TREE);
8571
8572           tuple = build_tree_list (default_value, parm_decl);
8573           TREE_VEC_ELT (new_vec, i) = tuple;
8574         }
8575
8576       *new_parms =
8577         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
8578                              - TMPL_ARGS_DEPTH (args)),
8579                    new_vec, NULL_TREE);
8580     }
8581
8582   --processing_template_decl;
8583
8584   return r;
8585 }
8586
8587 /* Substitute the ARGS into the indicated aggregate (or enumeration)
8588    type T.  If T is not an aggregate or enumeration type, it is
8589    handled as if by tsubst.  IN_DECL is as for tsubst.  If
8590    ENTERING_SCOPE is nonzero, T is the context for a template which
8591    we are presently tsubst'ing.  Return the substituted value.  */
8592
8593 static tree
8594 tsubst_aggr_type (tree t,
8595                   tree args,
8596                   tsubst_flags_t complain,
8597                   tree in_decl,
8598                   int entering_scope)
8599 {
8600   if (t == NULL_TREE)
8601     return NULL_TREE;
8602
8603   switch (TREE_CODE (t))
8604     {
8605     case RECORD_TYPE:
8606       if (TYPE_PTRMEMFUNC_P (t))
8607         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
8608
8609       /* Else fall through.  */
8610     case ENUMERAL_TYPE:
8611     case UNION_TYPE:
8612       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
8613         {
8614           tree argvec;
8615           tree context;
8616           tree r;
8617           int saved_unevaluated_operand;
8618           int saved_inhibit_evaluation_warnings;
8619
8620           /* In "sizeof(X<I>)" we need to evaluate "I".  */
8621           saved_unevaluated_operand = cp_unevaluated_operand;
8622           cp_unevaluated_operand = 0;
8623           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
8624           c_inhibit_evaluation_warnings = 0;
8625
8626           /* First, determine the context for the type we are looking
8627              up.  */
8628           context = TYPE_CONTEXT (t);
8629           if (context)
8630             {
8631               context = tsubst_aggr_type (context, args, complain,
8632                                           in_decl, /*entering_scope=*/1);
8633               /* If context is a nested class inside a class template,
8634                  it may still need to be instantiated (c++/33959).  */
8635               if (TYPE_P (context))
8636                 context = complete_type (context);
8637             }
8638
8639           /* Then, figure out what arguments are appropriate for the
8640              type we are trying to find.  For example, given:
8641
8642                template <class T> struct S;
8643                template <class T, class U> void f(T, U) { S<U> su; }
8644
8645              and supposing that we are instantiating f<int, double>,
8646              then our ARGS will be {int, double}, but, when looking up
8647              S we only want {double}.  */
8648           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
8649                                          complain, in_decl);
8650           if (argvec == error_mark_node)
8651             r = error_mark_node;
8652           else
8653             {
8654               r = lookup_template_class (t, argvec, in_decl, context,
8655                                          entering_scope, complain);
8656               r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
8657             }
8658
8659           cp_unevaluated_operand = saved_unevaluated_operand;
8660           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
8661
8662           return r;
8663         }
8664       else
8665         /* This is not a template type, so there's nothing to do.  */
8666         return t;
8667
8668     default:
8669       return tsubst (t, args, complain, in_decl);
8670     }
8671 }
8672
8673 /* Substitute into the default argument ARG (a default argument for
8674    FN), which has the indicated TYPE.  */
8675
8676 tree
8677 tsubst_default_argument (tree fn, tree type, tree arg)
8678 {
8679   tree saved_class_ptr = NULL_TREE;
8680   tree saved_class_ref = NULL_TREE;
8681
8682   /* This default argument came from a template.  Instantiate the
8683      default argument here, not in tsubst.  In the case of
8684      something like:
8685
8686        template <class T>
8687        struct S {
8688          static T t();
8689          void f(T = t());
8690        };
8691
8692      we must be careful to do name lookup in the scope of S<T>,
8693      rather than in the current class.  */
8694   push_access_scope (fn);
8695   /* The "this" pointer is not valid in a default argument.  */
8696   if (cfun)
8697     {
8698       saved_class_ptr = current_class_ptr;
8699       cp_function_chain->x_current_class_ptr = NULL_TREE;
8700       saved_class_ref = current_class_ref;
8701       cp_function_chain->x_current_class_ref = NULL_TREE;
8702     }
8703
8704   push_deferring_access_checks(dk_no_deferred);
8705   /* The default argument expression may cause implicitly defined
8706      member functions to be synthesized, which will result in garbage
8707      collection.  We must treat this situation as if we were within
8708      the body of function so as to avoid collecting live data on the
8709      stack.  */
8710   ++function_depth;
8711   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
8712                      tf_warning_or_error, NULL_TREE,
8713                      /*integral_constant_expression_p=*/false);
8714   --function_depth;
8715   pop_deferring_access_checks();
8716
8717   /* Restore the "this" pointer.  */
8718   if (cfun)
8719     {
8720       cp_function_chain->x_current_class_ptr = saved_class_ptr;
8721       cp_function_chain->x_current_class_ref = saved_class_ref;
8722     }
8723
8724   /* Make sure the default argument is reasonable.  */
8725   arg = check_default_argument (type, arg);
8726
8727   pop_access_scope (fn);
8728
8729   return arg;
8730 }
8731
8732 /* Substitute into all the default arguments for FN.  */
8733
8734 static void
8735 tsubst_default_arguments (tree fn)
8736 {
8737   tree arg;
8738   tree tmpl_args;
8739
8740   tmpl_args = DECL_TI_ARGS (fn);
8741
8742   /* If this function is not yet instantiated, we certainly don't need
8743      its default arguments.  */
8744   if (uses_template_parms (tmpl_args))
8745     return;
8746
8747   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
8748        arg;
8749        arg = TREE_CHAIN (arg))
8750     if (TREE_PURPOSE (arg))
8751       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
8752                                                     TREE_VALUE (arg),
8753                                                     TREE_PURPOSE (arg));
8754 }
8755
8756 /* Substitute the ARGS into the T, which is a _DECL.  Return the
8757    result of the substitution.  Issue error and warning messages under
8758    control of COMPLAIN.  */
8759
8760 static tree
8761 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
8762 {
8763 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
8764   location_t saved_loc;
8765   tree r = NULL_TREE;
8766   tree in_decl = t;
8767   hashval_t hash = 0;
8768
8769   /* Set the filename and linenumber to improve error-reporting.  */
8770   saved_loc = input_location;
8771   input_location = DECL_SOURCE_LOCATION (t);
8772
8773   switch (TREE_CODE (t))
8774     {
8775     case TEMPLATE_DECL:
8776       {
8777         /* We can get here when processing a member function template,
8778            member class template, or template template parameter.  */
8779         tree decl = DECL_TEMPLATE_RESULT (t);
8780         tree spec;
8781         tree tmpl_args;
8782         tree full_args;
8783
8784         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
8785           {
8786             /* Template template parameter is treated here.  */
8787             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8788             if (new_type == error_mark_node)
8789               RETURN (error_mark_node);
8790
8791             r = copy_decl (t);
8792             TREE_CHAIN (r) = NULL_TREE;
8793             TREE_TYPE (r) = new_type;
8794             DECL_TEMPLATE_RESULT (r)
8795               = build_decl (DECL_SOURCE_LOCATION (decl),
8796                             TYPE_DECL, DECL_NAME (decl), new_type);
8797             DECL_TEMPLATE_PARMS (r)
8798               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8799                                        complain);
8800             TYPE_NAME (new_type) = r;
8801             break;
8802           }
8803
8804         /* We might already have an instance of this template.
8805            The ARGS are for the surrounding class type, so the
8806            full args contain the tsubst'd args for the context,
8807            plus the innermost args from the template decl.  */
8808         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
8809           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
8810           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
8811         /* Because this is a template, the arguments will still be
8812            dependent, even after substitution.  If
8813            PROCESSING_TEMPLATE_DECL is not set, the dependency
8814            predicates will short-circuit.  */
8815         ++processing_template_decl;
8816         full_args = tsubst_template_args (tmpl_args, args,
8817                                           complain, in_decl);
8818         --processing_template_decl;
8819         if (full_args == error_mark_node)
8820           RETURN (error_mark_node);
8821
8822         /* If this is a default template template argument,
8823            tsubst might not have changed anything.  */
8824         if (full_args == tmpl_args)
8825           RETURN (t);
8826
8827         hash = hash_tmpl_and_args (t, full_args);
8828         spec = retrieve_specialization (t, full_args, hash);
8829         if (spec != NULL_TREE)
8830           {
8831             r = spec;
8832             break;
8833           }
8834
8835         /* Make a new template decl.  It will be similar to the
8836            original, but will record the current template arguments.
8837            We also create a new function declaration, which is just
8838            like the old one, but points to this new template, rather
8839            than the old one.  */
8840         r = copy_decl (t);
8841         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
8842         TREE_CHAIN (r) = NULL_TREE;
8843
8844         DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
8845
8846         if (TREE_CODE (decl) == TYPE_DECL)
8847           {
8848             tree new_type;
8849             ++processing_template_decl;
8850             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8851             --processing_template_decl;
8852             if (new_type == error_mark_node)
8853               RETURN (error_mark_node);
8854
8855             TREE_TYPE (r) = new_type;
8856             CLASSTYPE_TI_TEMPLATE (new_type) = r;
8857             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
8858             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
8859             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
8860           }
8861         else
8862           {
8863             tree new_decl;
8864             ++processing_template_decl;
8865             new_decl = tsubst (decl, args, complain, in_decl);
8866             --processing_template_decl;
8867             if (new_decl == error_mark_node)
8868               RETURN (error_mark_node);
8869
8870             DECL_TEMPLATE_RESULT (r) = new_decl;
8871             DECL_TI_TEMPLATE (new_decl) = r;
8872             TREE_TYPE (r) = TREE_TYPE (new_decl);
8873             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
8874             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
8875           }
8876
8877         SET_DECL_IMPLICIT_INSTANTIATION (r);
8878         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
8879         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
8880
8881         /* The template parameters for this new template are all the
8882            template parameters for the old template, except the
8883            outermost level of parameters.  */
8884         DECL_TEMPLATE_PARMS (r)
8885           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8886                                    complain);
8887
8888         if (PRIMARY_TEMPLATE_P (t))
8889           DECL_PRIMARY_TEMPLATE (r) = r;
8890
8891         if (TREE_CODE (decl) != TYPE_DECL)
8892           /* Record this non-type partial instantiation.  */
8893           register_specialization (r, t,
8894                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
8895                                    false, hash);
8896       }
8897       break;
8898
8899     case FUNCTION_DECL:
8900       {
8901         tree ctx;
8902         tree argvec = NULL_TREE;
8903         tree *friends;
8904         tree gen_tmpl;
8905         tree type;
8906         int member;
8907         int args_depth;
8908         int parms_depth;
8909
8910         /* Nobody should be tsubst'ing into non-template functions.  */
8911         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
8912
8913         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
8914           {
8915             tree spec;
8916             bool dependent_p;
8917
8918             /* If T is not dependent, just return it.  We have to
8919                increment PROCESSING_TEMPLATE_DECL because
8920                value_dependent_expression_p assumes that nothing is
8921                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
8922             ++processing_template_decl;
8923             dependent_p = value_dependent_expression_p (t);
8924             --processing_template_decl;
8925             if (!dependent_p)
8926               RETURN (t);
8927
8928             /* Calculate the most general template of which R is a
8929                specialization, and the complete set of arguments used to
8930                specialize R.  */
8931             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
8932             argvec = tsubst_template_args (DECL_TI_ARGS
8933                                            (DECL_TEMPLATE_RESULT (gen_tmpl)),
8934                                            args, complain, in_decl);
8935
8936             /* Check to see if we already have this specialization.  */
8937             hash = hash_tmpl_and_args (gen_tmpl, argvec);
8938             spec = retrieve_specialization (gen_tmpl, argvec, hash);
8939
8940             if (spec)
8941               {
8942                 r = spec;
8943                 break;
8944               }
8945
8946             /* We can see more levels of arguments than parameters if
8947                there was a specialization of a member template, like
8948                this:
8949
8950                  template <class T> struct S { template <class U> void f(); }
8951                  template <> template <class U> void S<int>::f(U);
8952
8953                Here, we'll be substituting into the specialization,
8954                because that's where we can find the code we actually
8955                want to generate, but we'll have enough arguments for
8956                the most general template.
8957
8958                We also deal with the peculiar case:
8959
8960                  template <class T> struct S {
8961                    template <class U> friend void f();
8962                  };
8963                  template <class U> void f() {}
8964                  template S<int>;
8965                  template void f<double>();
8966
8967                Here, the ARGS for the instantiation of will be {int,
8968                double}.  But, we only need as many ARGS as there are
8969                levels of template parameters in CODE_PATTERN.  We are
8970                careful not to get fooled into reducing the ARGS in
8971                situations like:
8972
8973                  template <class T> struct S { template <class U> void f(U); }
8974                  template <class T> template <> void S<T>::f(int) {}
8975
8976                which we can spot because the pattern will be a
8977                specialization in this case.  */
8978             args_depth = TMPL_ARGS_DEPTH (args);
8979             parms_depth =
8980               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
8981             if (args_depth > parms_depth
8982                 && !DECL_TEMPLATE_SPECIALIZATION (t))
8983               args = get_innermost_template_args (args, parms_depth);
8984           }
8985         else
8986           {
8987             /* This special case arises when we have something like this:
8988
8989                  template <class T> struct S {
8990                    friend void f<int>(int, double);
8991                  };
8992
8993                Here, the DECL_TI_TEMPLATE for the friend declaration
8994                will be an IDENTIFIER_NODE.  We are being called from
8995                tsubst_friend_function, and we want only to create a
8996                new decl (R) with appropriate types so that we can call
8997                determine_specialization.  */
8998             gen_tmpl = NULL_TREE;
8999           }
9000
9001         if (DECL_CLASS_SCOPE_P (t))
9002           {
9003             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
9004               member = 2;
9005             else
9006               member = 1;
9007             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
9008                                     complain, t, /*entering_scope=*/1);
9009           }
9010         else
9011           {
9012             member = 0;
9013             ctx = DECL_CONTEXT (t);
9014           }
9015         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9016         if (type == error_mark_node)
9017           RETURN (error_mark_node);
9018
9019         /* We do NOT check for matching decls pushed separately at this
9020            point, as they may not represent instantiations of this
9021            template, and in any case are considered separate under the
9022            discrete model.  */
9023         r = copy_decl (t);
9024         DECL_USE_TEMPLATE (r) = 0;
9025         TREE_TYPE (r) = type;
9026         /* Clear out the mangled name and RTL for the instantiation.  */
9027         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9028         SET_DECL_RTL (r, NULL_RTX);
9029         /* Leave DECL_INITIAL set on deleted instantiations.  */
9030         if (!DECL_DELETED_FN (r))
9031           DECL_INITIAL (r) = NULL_TREE;
9032         DECL_CONTEXT (r) = ctx;
9033
9034         if (member && DECL_CONV_FN_P (r))
9035           /* Type-conversion operator.  Reconstruct the name, in
9036              case it's the name of one of the template's parameters.  */
9037           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
9038
9039         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
9040                                      complain, t);
9041         DECL_RESULT (r) = NULL_TREE;
9042
9043         TREE_STATIC (r) = 0;
9044         TREE_PUBLIC (r) = TREE_PUBLIC (t);
9045         DECL_EXTERNAL (r) = 1;
9046         /* If this is an instantiation of a function with internal
9047            linkage, we already know what object file linkage will be
9048            assigned to the instantiation.  */
9049         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
9050         DECL_DEFER_OUTPUT (r) = 0;
9051         TREE_CHAIN (r) = NULL_TREE;
9052         DECL_PENDING_INLINE_INFO (r) = 0;
9053         DECL_PENDING_INLINE_P (r) = 0;
9054         DECL_SAVED_TREE (r) = NULL_TREE;
9055         DECL_STRUCT_FUNCTION (r) = NULL;
9056         TREE_USED (r) = 0;
9057         /* We'll re-clone as appropriate in instantiate_template.  */
9058         DECL_CLONED_FUNCTION (r) = NULL_TREE;
9059
9060         /* If we aren't complaining now, return on error before we register
9061            the specialization so that we'll complain eventually.  */
9062         if ((complain & tf_error) == 0
9063             && IDENTIFIER_OPNAME_P (DECL_NAME (r))
9064             && !grok_op_properties (r, /*complain=*/false))
9065           RETURN (error_mark_node);
9066
9067         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
9068            this in the special friend case mentioned above where
9069            GEN_TMPL is NULL.  */
9070         if (gen_tmpl)
9071           {
9072             DECL_TEMPLATE_INFO (r)
9073               = build_template_info (gen_tmpl, argvec);
9074             SET_DECL_IMPLICIT_INSTANTIATION (r);
9075             register_specialization (r, gen_tmpl, argvec, false, hash);
9076
9077             /* We're not supposed to instantiate default arguments
9078                until they are called, for a template.  But, for a
9079                declaration like:
9080
9081                  template <class T> void f ()
9082                  { extern void g(int i = T()); }
9083
9084                we should do the substitution when the template is
9085                instantiated.  We handle the member function case in
9086                instantiate_class_template since the default arguments
9087                might refer to other members of the class.  */
9088             if (!member
9089                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
9090                 && !uses_template_parms (argvec))
9091               tsubst_default_arguments (r);
9092           }
9093         else
9094           DECL_TEMPLATE_INFO (r) = NULL_TREE;
9095
9096         /* Copy the list of befriending classes.  */
9097         for (friends = &DECL_BEFRIENDING_CLASSES (r);
9098              *friends;
9099              friends = &TREE_CHAIN (*friends))
9100           {
9101             *friends = copy_node (*friends);
9102             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
9103                                             args, complain,
9104                                             in_decl);
9105           }
9106
9107         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
9108           {
9109             maybe_retrofit_in_chrg (r);
9110             if (DECL_CONSTRUCTOR_P (r))
9111               grok_ctor_properties (ctx, r);
9112             /* If this is an instantiation of a member template, clone it.
9113                If it isn't, that'll be handled by
9114                clone_constructors_and_destructors.  */
9115             if (PRIMARY_TEMPLATE_P (gen_tmpl))
9116               clone_function_decl (r, /*update_method_vec_p=*/0);
9117           }
9118         else if ((complain & tf_error) != 0
9119                  && IDENTIFIER_OPNAME_P (DECL_NAME (r))
9120                  && !grok_op_properties (r, /*complain=*/true))
9121           RETURN (error_mark_node);
9122
9123         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
9124           SET_DECL_FRIEND_CONTEXT (r,
9125                                    tsubst (DECL_FRIEND_CONTEXT (t),
9126                                             args, complain, in_decl));
9127
9128         /* Possibly limit visibility based on template args.  */
9129         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
9130         if (DECL_VISIBILITY_SPECIFIED (t))
9131           {
9132             DECL_VISIBILITY_SPECIFIED (r) = 0;
9133             DECL_ATTRIBUTES (r)
9134               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
9135           }
9136         determine_visibility (r);
9137         if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
9138             && !processing_template_decl)
9139           defaulted_late_check (r);
9140
9141         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9142                                         args, complain, in_decl);
9143       }
9144       break;
9145
9146     case PARM_DECL:
9147       {
9148         tree type = NULL_TREE;
9149         int i, len = 1;
9150         tree expanded_types = NULL_TREE;
9151         tree prev_r = NULL_TREE;
9152         tree first_r = NULL_TREE;
9153
9154         if (FUNCTION_PARAMETER_PACK_P (t))
9155           {
9156             /* If there is a local specialization that isn't a
9157                parameter pack, it means that we're doing a "simple"
9158                substitution from inside tsubst_pack_expansion. Just
9159                return the local specialization (which will be a single
9160                parm).  */
9161             tree spec = retrieve_local_specialization (t);
9162             if (spec 
9163                 && TREE_CODE (spec) == PARM_DECL
9164                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
9165               RETURN (spec);
9166
9167             /* Expand the TYPE_PACK_EXPANSION that provides the types for
9168                the parameters in this function parameter pack.  */
9169             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
9170                                                     complain, in_decl);
9171             if (TREE_CODE (expanded_types) == TREE_VEC)
9172               {
9173                 len = TREE_VEC_LENGTH (expanded_types);
9174
9175                 /* Zero-length parameter packs are boring. Just substitute
9176                    into the chain.  */
9177                 if (len == 0)
9178                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
9179                                   TREE_CHAIN (t)));
9180               }
9181             else
9182               {
9183                 /* All we did was update the type. Make a note of that.  */
9184                 type = expanded_types;
9185                 expanded_types = NULL_TREE;
9186               }
9187           }
9188
9189         /* Loop through all of the parameter's we'll build. When T is
9190            a function parameter pack, LEN is the number of expanded
9191            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
9192         r = NULL_TREE;
9193         for (i = 0; i < len; ++i)
9194           {
9195             prev_r = r;
9196             r = copy_node (t);
9197             if (DECL_TEMPLATE_PARM_P (t))
9198               SET_DECL_TEMPLATE_PARM_P (r);
9199
9200             /* An argument of a function parameter pack is not a parameter
9201                pack.  */
9202             FUNCTION_PARAMETER_PACK_P (r) = false;
9203
9204             if (expanded_types)
9205               /* We're on the Ith parameter of the function parameter
9206                  pack.  */
9207               {
9208                 /* Get the Ith type.  */
9209                 type = TREE_VEC_ELT (expanded_types, i);
9210
9211                 if (DECL_NAME (r))
9212                   /* Rename the parameter to include the index.  */
9213                   DECL_NAME (r) =
9214                     make_ith_pack_parameter_name (DECL_NAME (r), i);
9215               }
9216             else if (!type)
9217               /* We're dealing with a normal parameter.  */
9218               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9219
9220             type = type_decays_to (type);
9221             TREE_TYPE (r) = type;
9222             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9223
9224             if (DECL_INITIAL (r))
9225               {
9226                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
9227                   DECL_INITIAL (r) = TREE_TYPE (r);
9228                 else
9229                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
9230                                              complain, in_decl);
9231               }
9232
9233             DECL_CONTEXT (r) = NULL_TREE;
9234
9235             if (!DECL_TEMPLATE_PARM_P (r))
9236               DECL_ARG_TYPE (r) = type_passed_as (type);
9237
9238             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9239                                             args, complain, in_decl);
9240
9241             /* Keep track of the first new parameter we
9242                generate. That's what will be returned to the
9243                caller.  */
9244             if (!first_r)
9245               first_r = r;
9246
9247             /* Build a proper chain of parameters when substituting
9248                into a function parameter pack.  */
9249             if (prev_r)
9250               TREE_CHAIN (prev_r) = r;
9251           }
9252
9253         if (TREE_CHAIN (t))
9254           TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args,
9255                                    complain, TREE_CHAIN (t));
9256
9257         /* FIRST_R contains the start of the chain we've built.  */
9258         r = first_r;
9259       }
9260       break;
9261
9262     case FIELD_DECL:
9263       {
9264         tree type;
9265
9266         r = copy_decl (t);
9267         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9268         if (type == error_mark_node)
9269           RETURN (error_mark_node);
9270         TREE_TYPE (r) = type;
9271         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9272
9273         /* DECL_INITIAL gives the number of bits in a bit-field.  */
9274         DECL_INITIAL (r)
9275           = tsubst_expr (DECL_INITIAL (t), args,
9276                          complain, in_decl,
9277                          /*integral_constant_expression_p=*/true);
9278         /* We don't have to set DECL_CONTEXT here; it is set by
9279            finish_member_declaration.  */
9280         TREE_CHAIN (r) = NULL_TREE;
9281         if (VOID_TYPE_P (type))
9282           error ("instantiation of %q+D as type %qT", r, type);
9283
9284         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9285                                         args, complain, in_decl);
9286       }
9287       break;
9288
9289     case USING_DECL:
9290       /* We reach here only for member using decls.  */
9291       if (DECL_DEPENDENT_P (t))
9292         {
9293           r = do_class_using_decl
9294             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
9295              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
9296           if (!r)
9297             r = error_mark_node;
9298           else
9299             {
9300               TREE_PROTECTED (r) = TREE_PROTECTED (t);
9301               TREE_PRIVATE (r) = TREE_PRIVATE (t);
9302             }
9303         }
9304       else
9305         {
9306           r = copy_node (t);
9307           TREE_CHAIN (r) = NULL_TREE;
9308         }
9309       break;
9310
9311     case TYPE_DECL:
9312     case VAR_DECL:
9313       {
9314         tree argvec = NULL_TREE;
9315         tree gen_tmpl = NULL_TREE;
9316         tree spec;
9317         tree tmpl = NULL_TREE;
9318         tree ctx;
9319         tree type = NULL_TREE;
9320         bool local_p;
9321
9322         if (TREE_CODE (t) == TYPE_DECL
9323             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
9324           {
9325             /* If this is the canonical decl, we don't have to
9326                mess with instantiations, and often we can't (for
9327                typename, template type parms and such).  Note that
9328                TYPE_NAME is not correct for the above test if
9329                we've copied the type for a typedef.  */
9330             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9331             if (type == error_mark_node)
9332               RETURN (error_mark_node);
9333             r = TYPE_NAME (type);
9334             break;
9335           }
9336
9337         /* Check to see if we already have the specialization we
9338            need.  */
9339         spec = NULL_TREE;
9340         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
9341           {
9342             /* T is a static data member or namespace-scope entity.
9343                We have to substitute into namespace-scope variables
9344                (even though such entities are never templates) because
9345                of cases like:
9346                
9347                  template <class T> void f() { extern T t; }
9348
9349                where the entity referenced is not known until
9350                instantiation time.  */
9351             local_p = false;
9352             ctx = DECL_CONTEXT (t);
9353             if (DECL_CLASS_SCOPE_P (t))
9354               {
9355                 ctx = tsubst_aggr_type (ctx, args,
9356                                         complain,
9357                                         in_decl, /*entering_scope=*/1);
9358                 /* If CTX is unchanged, then T is in fact the
9359                    specialization we want.  That situation occurs when
9360                    referencing a static data member within in its own
9361                    class.  We can use pointer equality, rather than
9362                    same_type_p, because DECL_CONTEXT is always
9363                    canonical.  */
9364                 if (ctx == DECL_CONTEXT (t))
9365                   spec = t;
9366               }
9367
9368             if (!spec)
9369               {
9370                 tmpl = DECL_TI_TEMPLATE (t);
9371                 gen_tmpl = most_general_template (tmpl);
9372                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
9373                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
9374                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
9375               }
9376           }
9377         else
9378           {
9379             /* A local variable.  */
9380             local_p = true;
9381             /* Subsequent calls to pushdecl will fill this in.  */
9382             ctx = NULL_TREE;
9383             spec = retrieve_local_specialization (t);
9384           }
9385         /* If we already have the specialization we need, there is
9386            nothing more to do.  */ 
9387         if (spec)
9388           {
9389             r = spec;
9390             break;
9391           }
9392
9393         /* Create a new node for the specialization we need.  */
9394         r = copy_decl (t);
9395         if (type == NULL_TREE)
9396           {
9397             if (is_typedef_decl (t))
9398               type = DECL_ORIGINAL_TYPE (t);
9399             else
9400               type = TREE_TYPE (t);
9401             type = tsubst (type, args, complain, in_decl);
9402           }
9403         if (TREE_CODE (r) == VAR_DECL)
9404           {
9405             /* Even if the original location is out of scope, the
9406                newly substituted one is not.  */
9407             DECL_DEAD_FOR_LOCAL (r) = 0;
9408             DECL_INITIALIZED_P (r) = 0;
9409             DECL_TEMPLATE_INSTANTIATED (r) = 0;
9410             if (type == error_mark_node)
9411               RETURN (error_mark_node);
9412             if (TREE_CODE (type) == FUNCTION_TYPE)
9413               {
9414                 /* It may seem that this case cannot occur, since:
9415
9416                      typedef void f();
9417                      void g() { f x; }
9418
9419                    declares a function, not a variable.  However:
9420       
9421                      typedef void f();
9422                      template <typename T> void g() { T t; }
9423                      template void g<f>();
9424
9425                    is an attempt to declare a variable with function
9426                    type.  */
9427                 error ("variable %qD has function type",
9428                        /* R is not yet sufficiently initialized, so we
9429                           just use its name.  */
9430                        DECL_NAME (r));
9431                 RETURN (error_mark_node);
9432               }
9433             type = complete_type (type);
9434             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
9435               = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t);
9436             type = check_var_type (DECL_NAME (r), type);
9437
9438             if (DECL_HAS_VALUE_EXPR_P (t))
9439               {
9440                 tree ve = DECL_VALUE_EXPR (t);
9441                 ve = tsubst_expr (ve, args, complain, in_decl,
9442                                   /*constant_expression_p=*/false);
9443                 SET_DECL_VALUE_EXPR (r, ve);
9444               }
9445           }
9446         else if (DECL_SELF_REFERENCE_P (t))
9447           SET_DECL_SELF_REFERENCE_P (r);
9448         TREE_TYPE (r) = type;
9449         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9450         DECL_CONTEXT (r) = ctx;
9451         /* Clear out the mangled name and RTL for the instantiation.  */
9452         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9453         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9454           SET_DECL_RTL (r, NULL_RTX);
9455         /* The initializer must not be expanded until it is required;
9456            see [temp.inst].  */
9457         DECL_INITIAL (r) = NULL_TREE;
9458         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9459           SET_DECL_RTL (r, NULL_RTX);
9460         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
9461         if (TREE_CODE (r) == VAR_DECL)
9462           {
9463             /* Possibly limit visibility based on template args.  */
9464             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
9465             if (DECL_VISIBILITY_SPECIFIED (t))
9466               {
9467                 DECL_VISIBILITY_SPECIFIED (r) = 0;
9468                 DECL_ATTRIBUTES (r)
9469                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
9470               }
9471             determine_visibility (r);
9472           }
9473
9474         if (!local_p)
9475           {
9476             /* A static data member declaration is always marked
9477                external when it is declared in-class, even if an
9478                initializer is present.  We mimic the non-template
9479                processing here.  */
9480             DECL_EXTERNAL (r) = 1;
9481
9482             register_specialization (r, gen_tmpl, argvec, false, hash);
9483             DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
9484             SET_DECL_IMPLICIT_INSTANTIATION (r);
9485           }
9486         else if (cp_unevaluated_operand)
9487           {
9488             /* We're substituting this var in a decltype outside of its
9489                scope, such as for a lambda return type.  Don't add it to
9490                local_specializations, do perform auto deduction.  */
9491             tree auto_node = type_uses_auto (type);
9492             tree init
9493               = tsubst_expr (DECL_INITIAL (t), args, complain, in_decl,
9494                              /*constant_expression_p=*/false);
9495
9496             if (auto_node && init && describable_type (init))
9497               {
9498                 type = do_auto_deduction (type, init, auto_node);
9499                 TREE_TYPE (r) = type;
9500               }
9501           }
9502         else
9503           register_local_specialization (r, t);
9504
9505         TREE_CHAIN (r) = NULL_TREE;
9506
9507         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
9508                                         /*flags=*/0,
9509                                         args, complain, in_decl);
9510
9511         /* Preserve a typedef that names a type.  */
9512         if (is_typedef_decl (r))
9513           {
9514             DECL_ORIGINAL_TYPE (r) = NULL_TREE;
9515             set_underlying_type (r);
9516           }
9517
9518         layout_decl (r, 0);
9519       }
9520       break;
9521
9522     default:
9523       gcc_unreachable ();
9524     }
9525 #undef RETURN
9526
9527  out:
9528   /* Restore the file and line information.  */
9529   input_location = saved_loc;
9530
9531   return r;
9532 }
9533
9534 /* Substitute into the ARG_TYPES of a function type.  */
9535
9536 static tree
9537 tsubst_arg_types (tree arg_types,
9538                   tree args,
9539                   tsubst_flags_t complain,
9540                   tree in_decl)
9541 {
9542   tree remaining_arg_types;
9543   tree type = NULL_TREE;
9544   int i = 1;
9545   tree expanded_args = NULL_TREE;
9546   tree default_arg;
9547
9548   if (!arg_types || arg_types == void_list_node)
9549     return arg_types;
9550
9551   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
9552                                           args, complain, in_decl);
9553   if (remaining_arg_types == error_mark_node)
9554     return error_mark_node;
9555
9556   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
9557     {
9558       /* For a pack expansion, perform substitution on the
9559          entire expression. Later on, we'll handle the arguments
9560          one-by-one.  */
9561       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
9562                                             args, complain, in_decl);
9563
9564       if (TREE_CODE (expanded_args) == TREE_VEC)
9565         /* So that we'll spin through the parameters, one by one.  */
9566         i = TREE_VEC_LENGTH (expanded_args);
9567       else
9568         {
9569           /* We only partially substituted into the parameter
9570              pack. Our type is TYPE_PACK_EXPANSION.  */
9571           type = expanded_args;
9572           expanded_args = NULL_TREE;
9573         }
9574     }
9575
9576   while (i > 0) {
9577     --i;
9578     
9579     if (expanded_args)
9580       type = TREE_VEC_ELT (expanded_args, i);
9581     else if (!type)
9582       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
9583
9584     if (type == error_mark_node)
9585       return error_mark_node;
9586     if (VOID_TYPE_P (type))
9587       {
9588         if (complain & tf_error)
9589           {
9590             error ("invalid parameter type %qT", type);
9591             if (in_decl)
9592               error ("in declaration %q+D", in_decl);
9593           }
9594         return error_mark_node;
9595     }
9596     
9597     /* Do array-to-pointer, function-to-pointer conversion, and ignore
9598        top-level qualifiers as required.  */
9599     type = TYPE_MAIN_VARIANT (type_decays_to (type));
9600
9601     /* We do not substitute into default arguments here.  The standard
9602        mandates that they be instantiated only when needed, which is
9603        done in build_over_call.  */
9604     default_arg = TREE_PURPOSE (arg_types);
9605
9606     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
9607       {
9608         /* We've instantiated a template before its default arguments
9609            have been parsed.  This can happen for a nested template
9610            class, and is not an error unless we require the default
9611            argument in a call of this function.  */
9612         remaining_arg_types = 
9613           tree_cons (default_arg, type, remaining_arg_types);
9614         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
9615                        remaining_arg_types);
9616       }
9617     else
9618       remaining_arg_types = 
9619         hash_tree_cons (default_arg, type, remaining_arg_types);
9620   }
9621         
9622   return remaining_arg_types;
9623 }
9624
9625 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
9626    *not* handle the exception-specification for FNTYPE, because the
9627    initial substitution of explicitly provided template parameters
9628    during argument deduction forbids substitution into the
9629    exception-specification:
9630
9631      [temp.deduct]
9632
9633      All references in the function type of the function template to  the
9634      corresponding template parameters are replaced by the specified tem-
9635      plate argument values.  If a substitution in a template parameter or
9636      in  the function type of the function template results in an invalid
9637      type, type deduction fails.  [Note: The equivalent  substitution  in
9638      exception specifications is done only when the function is instanti-
9639      ated, at which point a program is  ill-formed  if  the  substitution
9640      results in an invalid type.]  */
9641
9642 static tree
9643 tsubst_function_type (tree t,
9644                       tree args,
9645                       tsubst_flags_t complain,
9646                       tree in_decl)
9647 {
9648   tree return_type;
9649   tree arg_types;
9650   tree fntype;
9651
9652   /* The TYPE_CONTEXT is not used for function/method types.  */
9653   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
9654
9655   /* Substitute the return type.  */
9656   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9657   if (return_type == error_mark_node)
9658     return error_mark_node;
9659   /* The standard does not presently indicate that creation of a
9660      function type with an invalid return type is a deduction failure.
9661      However, that is clearly analogous to creating an array of "void"
9662      or a reference to a reference.  This is core issue #486.  */
9663   if (TREE_CODE (return_type) == ARRAY_TYPE
9664       || TREE_CODE (return_type) == FUNCTION_TYPE)
9665     {
9666       if (complain & tf_error)
9667         {
9668           if (TREE_CODE (return_type) == ARRAY_TYPE)
9669             error ("function returning an array");
9670           else
9671             error ("function returning a function");
9672         }
9673       return error_mark_node;
9674     }
9675
9676   /* Substitute the argument types.  */
9677   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
9678                                 complain, in_decl);
9679   if (arg_types == error_mark_node)
9680     return error_mark_node;
9681
9682   /* Construct a new type node and return it.  */
9683   if (TREE_CODE (t) == FUNCTION_TYPE)
9684     fntype = build_function_type (return_type, arg_types);
9685   else
9686     {
9687       tree r = TREE_TYPE (TREE_VALUE (arg_types));
9688       if (! MAYBE_CLASS_TYPE_P (r))
9689         {
9690           /* [temp.deduct]
9691
9692              Type deduction may fail for any of the following
9693              reasons:
9694
9695              -- Attempting to create "pointer to member of T" when T
9696              is not a class type.  */
9697           if (complain & tf_error)
9698             error ("creating pointer to member function of non-class type %qT",
9699                       r);
9700           return error_mark_node;
9701         }
9702
9703       fntype = build_method_type_directly (r, return_type,
9704                                            TREE_CHAIN (arg_types));
9705     }
9706   fntype = cp_build_qualified_type_real (fntype, TYPE_QUALS (t), complain);
9707   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
9708
9709   return fntype;
9710 }
9711
9712 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
9713    ARGS into that specification, and return the substituted
9714    specification.  If there is no specification, return NULL_TREE.  */
9715
9716 static tree
9717 tsubst_exception_specification (tree fntype,
9718                                 tree args,
9719                                 tsubst_flags_t complain,
9720                                 tree in_decl)
9721 {
9722   tree specs;
9723   tree new_specs;
9724
9725   specs = TYPE_RAISES_EXCEPTIONS (fntype);
9726   new_specs = NULL_TREE;
9727   if (specs)
9728     {
9729       if (! TREE_VALUE (specs))
9730         new_specs = specs;
9731       else
9732         while (specs)
9733           {
9734             tree spec;
9735             int i, len = 1;
9736             tree expanded_specs = NULL_TREE;
9737
9738             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
9739               {
9740                 /* Expand the pack expansion type.  */
9741                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
9742                                                        args, complain,
9743                                                        in_decl);
9744
9745                 if (expanded_specs == error_mark_node)
9746                   return error_mark_node;
9747                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
9748                   len = TREE_VEC_LENGTH (expanded_specs);
9749                 else
9750                   {
9751                     /* We're substituting into a member template, so
9752                        we got a TYPE_PACK_EXPANSION back.  Add that
9753                        expansion and move on.  */
9754                     gcc_assert (TREE_CODE (expanded_specs) 
9755                                 == TYPE_PACK_EXPANSION);
9756                     new_specs = add_exception_specifier (new_specs,
9757                                                          expanded_specs,
9758                                                          complain);
9759                     specs = TREE_CHAIN (specs);
9760                     continue;
9761                   }
9762               }
9763
9764             for (i = 0; i < len; ++i)
9765               {
9766                 if (expanded_specs)
9767                   spec = TREE_VEC_ELT (expanded_specs, i);
9768                 else
9769                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
9770                 if (spec == error_mark_node)
9771                   return spec;
9772                 new_specs = add_exception_specifier (new_specs, spec, 
9773                                                      complain);
9774               }
9775
9776             specs = TREE_CHAIN (specs);
9777           }
9778     }
9779   return new_specs;
9780 }
9781
9782 /* Take the tree structure T and replace template parameters used
9783    therein with the argument vector ARGS.  IN_DECL is an associated
9784    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
9785    Issue error and warning messages under control of COMPLAIN.  Note
9786    that we must be relatively non-tolerant of extensions here, in
9787    order to preserve conformance; if we allow substitutions that
9788    should not be allowed, we may allow argument deductions that should
9789    not succeed, and therefore report ambiguous overload situations
9790    where there are none.  In theory, we could allow the substitution,
9791    but indicate that it should have failed, and allow our caller to
9792    make sure that the right thing happens, but we don't try to do this
9793    yet.
9794
9795    This function is used for dealing with types, decls and the like;
9796    for expressions, use tsubst_expr or tsubst_copy.  */
9797
9798 tree
9799 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9800 {
9801   tree type, r;
9802
9803   if (t == NULL_TREE || t == error_mark_node
9804       || t == integer_type_node
9805       || t == void_type_node
9806       || t == char_type_node
9807       || t == unknown_type_node
9808       || TREE_CODE (t) == NAMESPACE_DECL)
9809     return t;
9810
9811   if (DECL_P (t))
9812     return tsubst_decl (t, args, complain);
9813
9814   if (args == NULL_TREE)
9815     return t;
9816
9817   if (TREE_CODE (t) == IDENTIFIER_NODE)
9818     type = IDENTIFIER_TYPE_VALUE (t);
9819   else
9820     type = TREE_TYPE (t);
9821
9822   gcc_assert (type != unknown_type_node);
9823
9824   /* Reuse typedefs.  We need to do this to handle dependent attributes,
9825      such as attribute aligned.  */
9826   if (TYPE_P (t)
9827       && TYPE_NAME (t)
9828       && TYPE_NAME (t) != TYPE_MAIN_DECL (t))
9829     {
9830       tree decl = TYPE_NAME (t);
9831       
9832       if (DECL_CLASS_SCOPE_P (decl)
9833           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
9834           && uses_template_parms (DECL_CONTEXT (decl)))
9835         {
9836           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
9837           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
9838           r = retrieve_specialization (tmpl, gen_args, 0);
9839         }
9840       else if (DECL_FUNCTION_SCOPE_P (decl)
9841                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
9842                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
9843         r = retrieve_local_specialization (decl);
9844       else
9845         /* The typedef is from a non-template context.  */
9846         return t;
9847
9848       if (r)
9849         {
9850           r = TREE_TYPE (r);
9851           r = cp_build_qualified_type_real
9852             (r, cp_type_quals (t) | cp_type_quals (r),
9853              complain | tf_ignore_bad_quals);
9854           return r;
9855         }
9856       /* Else we must be instantiating the typedef, so fall through.  */
9857     }
9858
9859   if (type
9860       && TREE_CODE (t) != TYPENAME_TYPE
9861       && TREE_CODE (t) != IDENTIFIER_NODE
9862       && TREE_CODE (t) != FUNCTION_TYPE
9863       && TREE_CODE (t) != METHOD_TYPE)
9864     type = tsubst (type, args, complain, in_decl);
9865   if (type == error_mark_node)
9866     return error_mark_node;
9867
9868   switch (TREE_CODE (t))
9869     {
9870     case RECORD_TYPE:
9871     case UNION_TYPE:
9872     case ENUMERAL_TYPE:
9873       return tsubst_aggr_type (t, args, complain, in_decl,
9874                                /*entering_scope=*/0);
9875
9876     case ERROR_MARK:
9877     case IDENTIFIER_NODE:
9878     case VOID_TYPE:
9879     case REAL_TYPE:
9880     case COMPLEX_TYPE:
9881     case VECTOR_TYPE:
9882     case BOOLEAN_TYPE:
9883     case INTEGER_CST:
9884     case REAL_CST:
9885     case STRING_CST:
9886       return t;
9887
9888     case INTEGER_TYPE:
9889       if (t == integer_type_node)
9890         return t;
9891
9892       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
9893           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
9894         return t;
9895
9896       {
9897         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
9898
9899         max = tsubst_expr (omax, args, complain, in_decl,
9900                            /*integral_constant_expression_p=*/false);
9901
9902         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
9903            needed.  */
9904         if (TREE_CODE (max) == NOP_EXPR
9905             && TREE_SIDE_EFFECTS (omax)
9906             && !TREE_TYPE (max))
9907           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
9908
9909         max = fold_decl_constant_value (max);
9910
9911         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
9912            with TREE_SIDE_EFFECTS that indicates this is not an integral
9913            constant expression.  */
9914         if (processing_template_decl
9915             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
9916           {
9917             gcc_assert (TREE_CODE (max) == NOP_EXPR);
9918             TREE_SIDE_EFFECTS (max) = 1;
9919           }
9920
9921         if (TREE_CODE (max) != INTEGER_CST
9922             && !at_function_scope_p ()
9923             && !TREE_SIDE_EFFECTS (max)
9924             && !value_dependent_expression_p (max))
9925           {
9926             if (complain & tf_error)
9927               error ("array bound is not an integer constant");
9928             return error_mark_node;
9929           }
9930
9931         /* [temp.deduct]
9932
9933            Type deduction may fail for any of the following
9934            reasons:
9935
9936              Attempting to create an array with a size that is
9937              zero or negative.  */
9938         if (integer_zerop (max) && !(complain & tf_error))
9939           /* We must fail if performing argument deduction (as
9940              indicated by the state of complain), so that
9941              another substitution can be found.  */
9942           return error_mark_node;
9943         else if (TREE_CODE (max) == INTEGER_CST
9944                  && INT_CST_LT (max, integer_zero_node))
9945           {
9946             if (complain & tf_error)
9947               error ("creating array with negative size (%qE)", max);
9948
9949             return error_mark_node;
9950           }
9951
9952         return compute_array_index_type (NULL_TREE, max);
9953       }
9954
9955     case TEMPLATE_TYPE_PARM:
9956     case TEMPLATE_TEMPLATE_PARM:
9957     case BOUND_TEMPLATE_TEMPLATE_PARM:
9958     case TEMPLATE_PARM_INDEX:
9959       {
9960         int idx;
9961         int level;
9962         int levels;
9963         tree arg = NULL_TREE;
9964
9965         r = NULL_TREE;
9966
9967         gcc_assert (TREE_VEC_LENGTH (args) > 0);
9968         template_parm_level_and_index (t, &level, &idx); 
9969
9970         levels = TMPL_ARGS_DEPTH (args);
9971         if (level <= levels)
9972           {
9973             arg = TMPL_ARG (args, level, idx);
9974
9975             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
9976               /* See through ARGUMENT_PACK_SELECT arguments. */
9977               arg = ARGUMENT_PACK_SELECT_ARG (arg);
9978           }
9979
9980         if (arg == error_mark_node)
9981           return error_mark_node;
9982         else if (arg != NULL_TREE)
9983           {
9984             if (ARGUMENT_PACK_P (arg))
9985               /* If ARG is an argument pack, we don't actually want to
9986                  perform a substitution here, because substitutions
9987                  for argument packs are only done
9988                  element-by-element. We can get to this point when
9989                  substituting the type of a non-type template
9990                  parameter pack, when that type actually contains
9991                  template parameter packs from an outer template, e.g.,
9992
9993                  template<typename... Types> struct A {
9994                    template<Types... Values> struct B { };
9995                  };  */
9996               return t;
9997
9998             if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
9999               {
10000                 int quals;
10001                 gcc_assert (TYPE_P (arg));
10002
10003                 /* cv-quals from the template are discarded when
10004                    substituting in a function or reference type.  */
10005                 if (TREE_CODE (arg) == FUNCTION_TYPE
10006                     || TREE_CODE (arg) == METHOD_TYPE
10007                     || TREE_CODE (arg) == REFERENCE_TYPE)
10008                   quals = cp_type_quals (arg);
10009                 else
10010                   quals = cp_type_quals (arg) | cp_type_quals (t);
10011                   
10012                 return cp_build_qualified_type_real
10013                   (arg, quals, complain | tf_ignore_bad_quals);
10014               }
10015             else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
10016               {
10017                 /* We are processing a type constructed from a
10018                    template template parameter.  */
10019                 tree argvec = tsubst (TYPE_TI_ARGS (t),
10020                                       args, complain, in_decl);
10021                 if (argvec == error_mark_node)
10022                   return error_mark_node;
10023
10024                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
10025                    are resolving nested-types in the signature of a
10026                    member function templates.  Otherwise ARG is a
10027                    TEMPLATE_DECL and is the real template to be
10028                    instantiated.  */
10029                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
10030                   arg = TYPE_NAME (arg);
10031
10032                 r = lookup_template_class (arg,
10033                                            argvec, in_decl,
10034                                            DECL_CONTEXT (arg),
10035                                             /*entering_scope=*/0,
10036                                            complain);
10037                 return cp_build_qualified_type_real
10038                   (r, TYPE_QUALS (t), complain);
10039               }
10040             else
10041               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
10042               return arg;
10043           }
10044
10045         if (level == 1)
10046           /* This can happen during the attempted tsubst'ing in
10047              unify.  This means that we don't yet have any information
10048              about the template parameter in question.  */
10049           return t;
10050
10051         /* If we get here, we must have been looking at a parm for a
10052            more deeply nested template.  Make a new version of this
10053            template parameter, but with a lower level.  */
10054         switch (TREE_CODE (t))
10055           {
10056           case TEMPLATE_TYPE_PARM:
10057           case TEMPLATE_TEMPLATE_PARM:
10058           case BOUND_TEMPLATE_TEMPLATE_PARM:
10059             if (cp_type_quals (t))
10060               {
10061                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
10062                 r = cp_build_qualified_type_real
10063                   (r, cp_type_quals (t),
10064                    complain | (TREE_CODE (t) == TEMPLATE_TYPE_PARM
10065                                ? tf_ignore_bad_quals : 0));
10066               }
10067             else
10068               {
10069                 r = copy_type (t);
10070                 TEMPLATE_TYPE_PARM_INDEX (r)
10071                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
10072                                                 r, levels, args, complain);
10073                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
10074                 TYPE_MAIN_VARIANT (r) = r;
10075                 TYPE_POINTER_TO (r) = NULL_TREE;
10076                 TYPE_REFERENCE_TO (r) = NULL_TREE;
10077
10078                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
10079                   /* We have reduced the level of the template
10080                      template parameter, but not the levels of its
10081                      template parameters, so canonical_type_parameter
10082                      will not be able to find the canonical template
10083                      template parameter for this level. Thus, we
10084                      require structural equality checking to compare
10085                      TEMPLATE_TEMPLATE_PARMs. */
10086                   SET_TYPE_STRUCTURAL_EQUALITY (r);
10087                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
10088                   SET_TYPE_STRUCTURAL_EQUALITY (r);
10089                 else
10090                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
10091
10092                 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
10093                   {
10094                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
10095                                           complain, in_decl);
10096                     if (argvec == error_mark_node)
10097                       return error_mark_node;
10098
10099                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
10100                       = build_template_info (TYPE_TI_TEMPLATE (t), argvec);
10101                   }
10102               }
10103             break;
10104
10105           case TEMPLATE_PARM_INDEX:
10106             r = reduce_template_parm_level (t, type, levels, args, complain);
10107             break;
10108
10109           default:
10110             gcc_unreachable ();
10111           }
10112
10113         return r;
10114       }
10115
10116     case TREE_LIST:
10117       {
10118         tree purpose, value, chain;
10119
10120         if (t == void_list_node)
10121           return t;
10122
10123         purpose = TREE_PURPOSE (t);
10124         if (purpose)
10125           {
10126             purpose = tsubst (purpose, args, complain, in_decl);
10127             if (purpose == error_mark_node)
10128               return error_mark_node;
10129           }
10130         value = TREE_VALUE (t);
10131         if (value)
10132           {
10133             value = tsubst (value, args, complain, in_decl);
10134             if (value == error_mark_node)
10135               return error_mark_node;
10136           }
10137         chain = TREE_CHAIN (t);
10138         if (chain && chain != void_type_node)
10139           {
10140             chain = tsubst (chain, args, complain, in_decl);
10141             if (chain == error_mark_node)
10142               return error_mark_node;
10143           }
10144         if (purpose == TREE_PURPOSE (t)
10145             && value == TREE_VALUE (t)
10146             && chain == TREE_CHAIN (t))
10147           return t;
10148         return hash_tree_cons (purpose, value, chain);
10149       }
10150
10151     case TREE_BINFO:
10152       /* We should never be tsubsting a binfo.  */
10153       gcc_unreachable ();
10154
10155     case TREE_VEC:
10156       /* A vector of template arguments.  */
10157       gcc_assert (!type);
10158       return tsubst_template_args (t, args, complain, in_decl);
10159
10160     case POINTER_TYPE:
10161     case REFERENCE_TYPE:
10162       {
10163         enum tree_code code;
10164
10165         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
10166           return t;
10167
10168         code = TREE_CODE (t);
10169
10170
10171         /* [temp.deduct]
10172
10173            Type deduction may fail for any of the following
10174            reasons:
10175
10176            -- Attempting to create a pointer to reference type.
10177            -- Attempting to create a reference to a reference type or
10178               a reference to void.
10179
10180           Core issue 106 says that creating a reference to a reference
10181           during instantiation is no longer a cause for failure. We
10182           only enforce this check in strict C++98 mode.  */
10183         if ((TREE_CODE (type) == REFERENCE_TYPE
10184              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
10185             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
10186           {
10187             static location_t last_loc;
10188
10189             /* We keep track of the last time we issued this error
10190                message to avoid spewing a ton of messages during a
10191                single bad template instantiation.  */
10192             if (complain & tf_error
10193                 && last_loc != input_location)
10194               {
10195                 if (TREE_CODE (type) == VOID_TYPE)
10196                   error ("forming reference to void");
10197                else if (code == POINTER_TYPE)
10198                  error ("forming pointer to reference type %qT", type);
10199                else
10200                   error ("forming reference to reference type %qT", type);
10201                 last_loc = input_location;
10202               }
10203
10204             return error_mark_node;
10205           }
10206         else if (code == POINTER_TYPE)
10207           {
10208             r = build_pointer_type (type);
10209             if (TREE_CODE (type) == METHOD_TYPE)
10210               r = build_ptrmemfunc_type (r);
10211           }
10212         else if (TREE_CODE (type) == REFERENCE_TYPE)
10213           /* In C++0x, during template argument substitution, when there is an
10214              attempt to create a reference to a reference type, reference
10215              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
10216
10217              "If a template-argument for a template-parameter T names a type
10218              that is a reference to a type A, an attempt to create the type
10219              'lvalue reference to cv T' creates the type 'lvalue reference to
10220              A,' while an attempt to create the type type rvalue reference to
10221              cv T' creates the type T"
10222           */
10223           r = cp_build_reference_type
10224               (TREE_TYPE (type),
10225                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
10226         else
10227           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
10228         r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
10229
10230         if (r != error_mark_node)
10231           /* Will this ever be needed for TYPE_..._TO values?  */
10232           layout_type (r);
10233
10234         return r;
10235       }
10236     case OFFSET_TYPE:
10237       {
10238         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
10239         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
10240           {
10241             /* [temp.deduct]
10242
10243                Type deduction may fail for any of the following
10244                reasons:
10245
10246                -- Attempting to create "pointer to member of T" when T
10247                   is not a class type.  */
10248             if (complain & tf_error)
10249               error ("creating pointer to member of non-class type %qT", r);
10250             return error_mark_node;
10251           }
10252         if (TREE_CODE (type) == REFERENCE_TYPE)
10253           {
10254             if (complain & tf_error)
10255               error ("creating pointer to member reference type %qT", type);
10256             return error_mark_node;
10257           }
10258         if (TREE_CODE (type) == VOID_TYPE)
10259           {
10260             if (complain & tf_error)
10261               error ("creating pointer to member of type void");
10262             return error_mark_node;
10263           }
10264         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
10265         if (TREE_CODE (type) == FUNCTION_TYPE)
10266           {
10267             /* The type of the implicit object parameter gets its
10268                cv-qualifiers from the FUNCTION_TYPE. */
10269             tree memptr;
10270             tree method_type = build_memfn_type (type, r, cp_type_quals (type));
10271             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
10272             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
10273                                                  complain);
10274           }
10275         else
10276           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
10277                                                TYPE_QUALS (t),
10278                                                complain);
10279       }
10280     case FUNCTION_TYPE:
10281     case METHOD_TYPE:
10282       {
10283         tree fntype;
10284         tree specs;
10285         fntype = tsubst_function_type (t, args, complain, in_decl);
10286         if (fntype == error_mark_node)
10287           return error_mark_node;
10288
10289         /* Substitute the exception specification.  */
10290         specs = tsubst_exception_specification (t, args, complain,
10291                                                 in_decl);
10292         if (specs == error_mark_node)
10293           return error_mark_node;
10294         if (specs)
10295           fntype = build_exception_variant (fntype, specs);
10296         return fntype;
10297       }
10298     case ARRAY_TYPE:
10299       {
10300         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
10301         if (domain == error_mark_node)
10302           return error_mark_node;
10303
10304         /* As an optimization, we avoid regenerating the array type if
10305            it will obviously be the same as T.  */
10306         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
10307           return t;
10308
10309         /* These checks should match the ones in grokdeclarator.
10310
10311            [temp.deduct]
10312
10313            The deduction may fail for any of the following reasons:
10314
10315            -- Attempting to create an array with an element type that
10316               is void, a function type, or a reference type, or [DR337]
10317               an abstract class type.  */
10318         if (TREE_CODE (type) == VOID_TYPE
10319             || TREE_CODE (type) == FUNCTION_TYPE
10320             || TREE_CODE (type) == REFERENCE_TYPE)
10321           {
10322             if (complain & tf_error)
10323               error ("creating array of %qT", type);
10324             return error_mark_node;
10325           }
10326         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
10327           {
10328             if (complain & tf_error)
10329               error ("creating array of %qT, which is an abstract class type",
10330                      type);
10331             return error_mark_node;
10332           }
10333
10334         r = build_cplus_array_type (type, domain);
10335
10336         if (TYPE_USER_ALIGN (t))
10337           {
10338             TYPE_ALIGN (r) = TYPE_ALIGN (t);
10339             TYPE_USER_ALIGN (r) = 1;
10340           }
10341
10342         return r;
10343       }
10344
10345     case PLUS_EXPR:
10346     case MINUS_EXPR:
10347       {
10348         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10349         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
10350
10351         if (e1 == error_mark_node || e2 == error_mark_node)
10352           return error_mark_node;
10353
10354         return fold_build2_loc (input_location,
10355                             TREE_CODE (t), TREE_TYPE (t), e1, e2);
10356       }
10357
10358     case NEGATE_EXPR:
10359     case NOP_EXPR:
10360       {
10361         tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10362         if (e == error_mark_node)
10363           return error_mark_node;
10364
10365         return fold_build1_loc (input_location, TREE_CODE (t), TREE_TYPE (t), e);
10366       }
10367
10368     case TYPENAME_TYPE:
10369       {
10370         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10371                                      in_decl, /*entering_scope=*/1);
10372         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
10373                               complain, in_decl);
10374
10375         if (ctx == error_mark_node || f == error_mark_node)
10376           return error_mark_node;
10377
10378         if (!MAYBE_CLASS_TYPE_P (ctx))
10379           {
10380             if (complain & tf_error)
10381               error ("%qT is not a class, struct, or union type", ctx);
10382             return error_mark_node;
10383           }
10384         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
10385           {
10386             /* Normally, make_typename_type does not require that the CTX
10387                have complete type in order to allow things like:
10388
10389                  template <class T> struct S { typename S<T>::X Y; };
10390
10391                But, such constructs have already been resolved by this
10392                point, so here CTX really should have complete type, unless
10393                it's a partial instantiation.  */
10394             if (!(complain & tf_no_class_instantiations))
10395               ctx = complete_type (ctx);
10396             if (!COMPLETE_TYPE_P (ctx))
10397               {
10398                 if (complain & tf_error)
10399                   cxx_incomplete_type_error (NULL_TREE, ctx);
10400                 return error_mark_node;
10401               }
10402           }
10403
10404         f = make_typename_type (ctx, f, typename_type,
10405                                 (complain & tf_error) | tf_keep_type_decl);
10406         if (f == error_mark_node)
10407           return f;
10408         if (TREE_CODE (f) == TYPE_DECL)
10409           {
10410             complain |= tf_ignore_bad_quals;
10411             f = TREE_TYPE (f);
10412           }
10413
10414         if (TREE_CODE (f) != TYPENAME_TYPE)
10415           {
10416             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
10417               error ("%qT resolves to %qT, which is not an enumeration type",
10418                      t, f);
10419             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
10420               error ("%qT resolves to %qT, which is is not a class type",
10421                      t, f);
10422           }
10423
10424         return cp_build_qualified_type_real
10425           (f, cp_type_quals (f) | cp_type_quals (t), complain);
10426       }
10427
10428     case UNBOUND_CLASS_TEMPLATE:
10429       {
10430         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10431                                      in_decl, /*entering_scope=*/1);
10432         tree name = TYPE_IDENTIFIER (t);
10433         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
10434
10435         if (ctx == error_mark_node || name == error_mark_node)
10436           return error_mark_node;
10437
10438         if (parm_list)
10439           parm_list = tsubst_template_parms (parm_list, args, complain);
10440         return make_unbound_class_template (ctx, name, parm_list, complain);
10441       }
10442
10443     case INDIRECT_REF:
10444     case ADDR_EXPR:
10445     case CALL_EXPR:
10446       gcc_unreachable ();
10447
10448     case ARRAY_REF:
10449       {
10450         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10451         tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl,
10452                                /*integral_constant_expression_p=*/false);
10453         if (e1 == error_mark_node || e2 == error_mark_node)
10454           return error_mark_node;
10455
10456         return build_nt (ARRAY_REF, e1, e2, NULL_TREE, NULL_TREE);
10457       }
10458
10459     case SCOPE_REF:
10460       {
10461         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10462         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
10463         if (e1 == error_mark_node || e2 == error_mark_node)
10464           return error_mark_node;
10465
10466         return build_qualified_name (/*type=*/NULL_TREE,
10467                                      e1, e2, QUALIFIED_NAME_IS_TEMPLATE (t));
10468       }
10469
10470     case TYPEOF_TYPE:
10471       {
10472         tree type;
10473
10474         ++cp_unevaluated_operand;
10475         ++c_inhibit_evaluation_warnings;
10476
10477         type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
10478                             complain, in_decl,
10479                             /*integral_constant_expression_p=*/false);
10480
10481         --cp_unevaluated_operand;
10482         --c_inhibit_evaluation_warnings;
10483
10484         type = finish_typeof (type);
10485         return cp_build_qualified_type_real (type,
10486                                              cp_type_quals (t)
10487                                              | cp_type_quals (type),
10488                                              complain);
10489       }
10490
10491     case DECLTYPE_TYPE:
10492       {
10493         tree type;
10494
10495         ++cp_unevaluated_operand;
10496         ++c_inhibit_evaluation_warnings;
10497
10498         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
10499                             complain, in_decl,
10500                             /*integral_constant_expression_p=*/false);
10501
10502         --cp_unevaluated_operand;
10503         --c_inhibit_evaluation_warnings;
10504
10505         if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
10506           type = lambda_capture_field_type (type);
10507         else if (DECLTYPE_FOR_LAMBDA_RETURN (t))
10508           type = lambda_return_type (type);
10509         else
10510           type = finish_decltype_type
10511             (type, DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
10512         return cp_build_qualified_type_real (type,
10513                                              cp_type_quals (t)
10514                                              | cp_type_quals (type),
10515                                              complain);
10516       }
10517
10518     case TYPE_ARGUMENT_PACK:
10519     case NONTYPE_ARGUMENT_PACK:
10520       {
10521         tree r = TYPE_P (t)
10522           ? cxx_make_type (TREE_CODE (t))
10523           : make_node (TREE_CODE (t));
10524         tree packed_out = 
10525           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
10526                                 args,
10527                                 complain,
10528                                 in_decl);
10529         SET_ARGUMENT_PACK_ARGS (r, packed_out);
10530
10531         /* For template nontype argument packs, also substitute into
10532            the type.  */
10533         if (TREE_CODE (t) == NONTYPE_ARGUMENT_PACK)
10534           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
10535
10536         return r;
10537       }
10538       break;
10539
10540     default:
10541       sorry ("use of %qs in template",
10542              tree_code_name [(int) TREE_CODE (t)]);
10543       return error_mark_node;
10544     }
10545 }
10546
10547 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
10548    type of the expression on the left-hand side of the "." or "->"
10549    operator.  */
10550
10551 static tree
10552 tsubst_baselink (tree baselink, tree object_type,
10553                  tree args, tsubst_flags_t complain, tree in_decl)
10554 {
10555     tree name;
10556     tree qualifying_scope;
10557     tree fns;
10558     tree optype;
10559     tree template_args = 0;
10560     bool template_id_p = false;
10561
10562     /* A baselink indicates a function from a base class.  Both the
10563        BASELINK_ACCESS_BINFO and the base class referenced may
10564        indicate bases of the template class, rather than the
10565        instantiated class.  In addition, lookups that were not
10566        ambiguous before may be ambiguous now.  Therefore, we perform
10567        the lookup again.  */
10568     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
10569     qualifying_scope = tsubst (qualifying_scope, args,
10570                                complain, in_decl);
10571     fns = BASELINK_FUNCTIONS (baselink);
10572     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
10573     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
10574       {
10575         template_id_p = true;
10576         template_args = TREE_OPERAND (fns, 1);
10577         fns = TREE_OPERAND (fns, 0);
10578         if (template_args)
10579           template_args = tsubst_template_args (template_args, args,
10580                                                 complain, in_decl);
10581       }
10582     name = DECL_NAME (get_first_fn (fns));
10583     if (IDENTIFIER_TYPENAME_P (name))
10584       name = mangle_conv_op_name_for_type (optype);
10585     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
10586
10587     /* If lookup found a single function, mark it as used at this
10588        point.  (If it lookup found multiple functions the one selected
10589        later by overload resolution will be marked as used at that
10590        point.)  */
10591     if (BASELINK_P (baselink))
10592       fns = BASELINK_FUNCTIONS (baselink);
10593     if (!template_id_p && !really_overloaded_fn (fns))
10594       mark_used (OVL_CURRENT (fns));
10595
10596     /* Add back the template arguments, if present.  */
10597     if (BASELINK_P (baselink) && template_id_p)
10598       BASELINK_FUNCTIONS (baselink)
10599         = build_nt (TEMPLATE_ID_EXPR,
10600                     BASELINK_FUNCTIONS (baselink),
10601                     template_args);
10602     /* Update the conversion operator type.  */
10603     BASELINK_OPTYPE (baselink) = optype;
10604
10605     if (!object_type)
10606       object_type = current_class_type;
10607     return adjust_result_of_qualified_name_lookup (baselink,
10608                                                    qualifying_scope,
10609                                                    object_type);
10610 }
10611
10612 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
10613    true if the qualified-id will be a postfix-expression in-and-of
10614    itself; false if more of the postfix-expression follows the
10615    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
10616    of "&".  */
10617
10618 static tree
10619 tsubst_qualified_id (tree qualified_id, tree args,
10620                      tsubst_flags_t complain, tree in_decl,
10621                      bool done, bool address_p)
10622 {
10623   tree expr;
10624   tree scope;
10625   tree name;
10626   bool is_template;
10627   tree template_args;
10628
10629   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
10630
10631   /* Figure out what name to look up.  */
10632   name = TREE_OPERAND (qualified_id, 1);
10633   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
10634     {
10635       is_template = true;
10636       template_args = TREE_OPERAND (name, 1);
10637       if (template_args)
10638         template_args = tsubst_template_args (template_args, args,
10639                                               complain, in_decl);
10640       name = TREE_OPERAND (name, 0);
10641     }
10642   else
10643     {
10644       is_template = false;
10645       template_args = NULL_TREE;
10646     }
10647
10648   /* Substitute into the qualifying scope.  When there are no ARGS, we
10649      are just trying to simplify a non-dependent expression.  In that
10650      case the qualifying scope may be dependent, and, in any case,
10651      substituting will not help.  */
10652   scope = TREE_OPERAND (qualified_id, 0);
10653   if (args)
10654     {
10655       scope = tsubst (scope, args, complain, in_decl);
10656       expr = tsubst_copy (name, args, complain, in_decl);
10657     }
10658   else
10659     expr = name;
10660
10661   if (dependent_scope_p (scope))
10662     return build_qualified_name (NULL_TREE, scope, expr,
10663                                  QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
10664
10665   if (!BASELINK_P (name) && !DECL_P (expr))
10666     {
10667       if (TREE_CODE (expr) == BIT_NOT_EXPR)
10668         {
10669           /* A BIT_NOT_EXPR is used to represent a destructor.  */
10670           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
10671             {
10672               error ("qualifying type %qT does not match destructor name ~%qT",
10673                      scope, TREE_OPERAND (expr, 0));
10674               expr = error_mark_node;
10675             }
10676           else
10677             expr = lookup_qualified_name (scope, complete_dtor_identifier,
10678                                           /*is_type_p=*/0, false);
10679         }
10680       else
10681         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
10682       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
10683                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
10684         {
10685           if (complain & tf_error)
10686             {
10687               error ("dependent-name %qE is parsed as a non-type, but "
10688                      "instantiation yields a type", qualified_id);
10689               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
10690             }
10691           return error_mark_node;
10692         }
10693     }
10694
10695   if (DECL_P (expr))
10696     {
10697       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
10698                                            scope);
10699       /* Remember that there was a reference to this entity.  */
10700       mark_used (expr);
10701     }
10702
10703   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
10704     {
10705       if (complain & tf_error)
10706         qualified_name_lookup_error (scope,
10707                                      TREE_OPERAND (qualified_id, 1),
10708                                      expr, input_location);
10709       return error_mark_node;
10710     }
10711
10712   if (is_template)
10713     expr = lookup_template_function (expr, template_args);
10714
10715   if (expr == error_mark_node && complain & tf_error)
10716     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
10717                                  expr, input_location);
10718   else if (TYPE_P (scope))
10719     {
10720       expr = (adjust_result_of_qualified_name_lookup
10721               (expr, scope, current_class_type));
10722       expr = (finish_qualified_id_expr
10723               (scope, expr, done, address_p,
10724                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
10725                /*template_arg_p=*/false));
10726     }
10727
10728   /* Expressions do not generally have reference type.  */
10729   if (TREE_CODE (expr) != SCOPE_REF
10730       /* However, if we're about to form a pointer-to-member, we just
10731          want the referenced member referenced.  */
10732       && TREE_CODE (expr) != OFFSET_REF)
10733     expr = convert_from_reference (expr);
10734
10735   return expr;
10736 }
10737
10738 /* Like tsubst, but deals with expressions.  This function just replaces
10739    template parms; to finish processing the resultant expression, use
10740    tsubst_expr.  */
10741
10742 static tree
10743 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10744 {
10745   enum tree_code code;
10746   tree r;
10747
10748   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
10749     return t;
10750
10751   code = TREE_CODE (t);
10752
10753   switch (code)
10754     {
10755     case PARM_DECL:
10756       r = retrieve_local_specialization (t);
10757
10758       if (r == NULL)
10759         {
10760           tree c;
10761           /* This can happen for a parameter name used later in a function
10762              declaration (such as in a late-specified return type).  Just
10763              make a dummy decl, since it's only used for its type.  */
10764           gcc_assert (cp_unevaluated_operand != 0);
10765           /* We copy T because want to tsubst the PARM_DECL only,
10766              not the following PARM_DECLs that are chained to T.  */
10767           c = copy_node (t);
10768           r = tsubst_decl (c, args, complain);
10769           /* Give it the template pattern as its context; its true context
10770              hasn't been instantiated yet and this is good enough for
10771              mangling.  */
10772           DECL_CONTEXT (r) = DECL_CONTEXT (t);
10773         }
10774       
10775       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
10776         r = ARGUMENT_PACK_SELECT_ARG (r);
10777       mark_used (r);
10778       return r;
10779
10780     case CONST_DECL:
10781       {
10782         tree enum_type;
10783         tree v;
10784
10785         if (DECL_TEMPLATE_PARM_P (t))
10786           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
10787         /* There is no need to substitute into namespace-scope
10788            enumerators.  */
10789         if (DECL_NAMESPACE_SCOPE_P (t))
10790           return t;
10791         /* If ARGS is NULL, then T is known to be non-dependent.  */
10792         if (args == NULL_TREE)
10793           return integral_constant_value (t);
10794
10795         /* Unfortunately, we cannot just call lookup_name here.
10796            Consider:
10797
10798              template <int I> int f() {
10799              enum E { a = I };
10800              struct S { void g() { E e = a; } };
10801              };
10802
10803            When we instantiate f<7>::S::g(), say, lookup_name is not
10804            clever enough to find f<7>::a.  */
10805         enum_type
10806           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
10807                               /*entering_scope=*/0);
10808
10809         for (v = TYPE_VALUES (enum_type);
10810              v != NULL_TREE;
10811              v = TREE_CHAIN (v))
10812           if (TREE_PURPOSE (v) == DECL_NAME (t))
10813             return TREE_VALUE (v);
10814
10815           /* We didn't find the name.  That should never happen; if
10816              name-lookup found it during preliminary parsing, we
10817              should find it again here during instantiation.  */
10818         gcc_unreachable ();
10819       }
10820       return t;
10821
10822     case FIELD_DECL:
10823       if (DECL_CONTEXT (t))
10824         {
10825           tree ctx;
10826
10827           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
10828                                   /*entering_scope=*/1);
10829           if (ctx != DECL_CONTEXT (t))
10830             {
10831               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
10832               if (!r)
10833                 {
10834                   if (complain & tf_error)
10835                     error ("using invalid field %qD", t);
10836                   return error_mark_node;
10837                 }
10838               return r;
10839             }
10840         }
10841
10842       return t;
10843
10844     case VAR_DECL:
10845     case FUNCTION_DECL:
10846       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10847           || local_variable_p (t))
10848         t = tsubst (t, args, complain, in_decl);
10849       mark_used (t);
10850       return t;
10851
10852     case BASELINK:
10853       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
10854
10855     case TEMPLATE_DECL:
10856       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10857         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
10858                        args, complain, in_decl);
10859       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
10860         return tsubst (t, args, complain, in_decl);
10861       else if (DECL_CLASS_SCOPE_P (t)
10862                && uses_template_parms (DECL_CONTEXT (t)))
10863         {
10864           /* Template template argument like the following example need
10865              special treatment:
10866
10867                template <template <class> class TT> struct C {};
10868                template <class T> struct D {
10869                  template <class U> struct E {};
10870                  C<E> c;                                // #1
10871                };
10872                D<int> d;                                // #2
10873
10874              We are processing the template argument `E' in #1 for
10875              the template instantiation #2.  Originally, `E' is a
10876              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
10877              have to substitute this with one having context `D<int>'.  */
10878
10879           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
10880           return lookup_field (context, DECL_NAME(t), 0, false);
10881         }
10882       else
10883         /* Ordinary template template argument.  */
10884         return t;
10885
10886     case CAST_EXPR:
10887     case REINTERPRET_CAST_EXPR:
10888     case CONST_CAST_EXPR:
10889     case STATIC_CAST_EXPR:
10890     case DYNAMIC_CAST_EXPR:
10891     case NOP_EXPR:
10892       return build1
10893         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10894          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10895
10896     case SIZEOF_EXPR:
10897       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
10898         {
10899           /* We only want to compute the number of arguments.  */
10900           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
10901                                                 complain, in_decl);
10902           int len = 0;
10903
10904           if (TREE_CODE (expanded) == TREE_VEC)
10905             len = TREE_VEC_LENGTH (expanded);
10906
10907           if (expanded == error_mark_node)
10908             return error_mark_node;
10909           else if (PACK_EXPANSION_P (expanded)
10910                    || (TREE_CODE (expanded) == TREE_VEC
10911                        && len > 0
10912                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
10913             {
10914               if (TREE_CODE (expanded) == TREE_VEC)
10915                 expanded = TREE_VEC_ELT (expanded, len - 1);
10916
10917               if (TYPE_P (expanded))
10918                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
10919                                                    complain & tf_error);
10920               else
10921                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
10922                                                    complain & tf_error);
10923             }
10924           else
10925             return build_int_cst (size_type_node, len);
10926         }
10927       /* Fall through */
10928
10929     case INDIRECT_REF:
10930     case NEGATE_EXPR:
10931     case TRUTH_NOT_EXPR:
10932     case BIT_NOT_EXPR:
10933     case ADDR_EXPR:
10934     case UNARY_PLUS_EXPR:      /* Unary + */
10935     case ALIGNOF_EXPR:
10936     case ARROW_EXPR:
10937     case THROW_EXPR:
10938     case TYPEID_EXPR:
10939     case REALPART_EXPR:
10940     case IMAGPART_EXPR:
10941       return build1
10942         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
10943          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
10944
10945     case COMPONENT_REF:
10946       {
10947         tree object;
10948         tree name;
10949
10950         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
10951         name = TREE_OPERAND (t, 1);
10952         if (TREE_CODE (name) == BIT_NOT_EXPR)
10953           {
10954             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10955                                 complain, in_decl);
10956             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10957           }
10958         else if (TREE_CODE (name) == SCOPE_REF
10959                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
10960           {
10961             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
10962                                      complain, in_decl);
10963             name = TREE_OPERAND (name, 1);
10964             name = tsubst_copy (TREE_OPERAND (name, 0), args,
10965                                 complain, in_decl);
10966             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
10967             name = build_qualified_name (/*type=*/NULL_TREE,
10968                                          base, name,
10969                                          /*template_p=*/false);
10970           }
10971         else if (TREE_CODE (name) == BASELINK)
10972           name = tsubst_baselink (name,
10973                                   non_reference (TREE_TYPE (object)),
10974                                   args, complain,
10975                                   in_decl);
10976         else
10977           name = tsubst_copy (name, args, complain, in_decl);
10978         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
10979       }
10980
10981     case PLUS_EXPR:
10982     case MINUS_EXPR:
10983     case MULT_EXPR:
10984     case TRUNC_DIV_EXPR:
10985     case CEIL_DIV_EXPR:
10986     case FLOOR_DIV_EXPR:
10987     case ROUND_DIV_EXPR:
10988     case EXACT_DIV_EXPR:
10989     case BIT_AND_EXPR:
10990     case BIT_IOR_EXPR:
10991     case BIT_XOR_EXPR:
10992     case TRUNC_MOD_EXPR:
10993     case FLOOR_MOD_EXPR:
10994     case TRUTH_ANDIF_EXPR:
10995     case TRUTH_ORIF_EXPR:
10996     case TRUTH_AND_EXPR:
10997     case TRUTH_OR_EXPR:
10998     case RSHIFT_EXPR:
10999     case LSHIFT_EXPR:
11000     case RROTATE_EXPR:
11001     case LROTATE_EXPR:
11002     case EQ_EXPR:
11003     case NE_EXPR:
11004     case MAX_EXPR:
11005     case MIN_EXPR:
11006     case LE_EXPR:
11007     case GE_EXPR:
11008     case LT_EXPR:
11009     case GT_EXPR:
11010     case COMPOUND_EXPR:
11011     case DOTSTAR_EXPR:
11012     case MEMBER_REF:
11013     case PREDECREMENT_EXPR:
11014     case PREINCREMENT_EXPR:
11015     case POSTDECREMENT_EXPR:
11016     case POSTINCREMENT_EXPR:
11017       return build_nt
11018         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11019          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11020
11021     case SCOPE_REF:
11022       return build_qualified_name (/*type=*/NULL_TREE,
11023                                    tsubst_copy (TREE_OPERAND (t, 0),
11024                                                 args, complain, in_decl),
11025                                    tsubst_copy (TREE_OPERAND (t, 1),
11026                                                 args, complain, in_decl),
11027                                    QUALIFIED_NAME_IS_TEMPLATE (t));
11028
11029     case ARRAY_REF:
11030       return build_nt
11031         (ARRAY_REF,
11032          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11033          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11034          NULL_TREE, NULL_TREE);
11035
11036     case CALL_EXPR:
11037       {
11038         int n = VL_EXP_OPERAND_LENGTH (t);
11039         tree result = build_vl_exp (CALL_EXPR, n);
11040         int i;
11041         for (i = 0; i < n; i++)
11042           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
11043                                              complain, in_decl);
11044         return result;
11045       }
11046
11047     case COND_EXPR:
11048     case MODOP_EXPR:
11049     case PSEUDO_DTOR_EXPR:
11050       {
11051         r = build_nt
11052           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11053            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11054            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
11055         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
11056         return r;
11057       }
11058
11059     case NEW_EXPR:
11060       {
11061         r = build_nt
11062         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11063          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11064          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
11065         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
11066         return r;
11067       }
11068
11069     case DELETE_EXPR:
11070       {
11071         r = build_nt
11072         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11073          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11074         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
11075         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
11076         return r;
11077       }
11078
11079     case TEMPLATE_ID_EXPR:
11080       {
11081         /* Substituted template arguments */
11082         tree fn = TREE_OPERAND (t, 0);
11083         tree targs = TREE_OPERAND (t, 1);
11084
11085         fn = tsubst_copy (fn, args, complain, in_decl);
11086         if (targs)
11087           targs = tsubst_template_args (targs, args, complain, in_decl);
11088
11089         return lookup_template_function (fn, targs);
11090       }
11091
11092     case TREE_LIST:
11093       {
11094         tree purpose, value, chain;
11095
11096         if (t == void_list_node)
11097           return t;
11098
11099         purpose = TREE_PURPOSE (t);
11100         if (purpose)
11101           purpose = tsubst_copy (purpose, args, complain, in_decl);
11102         value = TREE_VALUE (t);
11103         if (value)
11104           value = tsubst_copy (value, args, complain, in_decl);
11105         chain = TREE_CHAIN (t);
11106         if (chain && chain != void_type_node)
11107           chain = tsubst_copy (chain, args, complain, in_decl);
11108         if (purpose == TREE_PURPOSE (t)
11109             && value == TREE_VALUE (t)
11110             && chain == TREE_CHAIN (t))
11111           return t;
11112         return tree_cons (purpose, value, chain);
11113       }
11114
11115     case RECORD_TYPE:
11116     case UNION_TYPE:
11117     case ENUMERAL_TYPE:
11118     case INTEGER_TYPE:
11119     case TEMPLATE_TYPE_PARM:
11120     case TEMPLATE_TEMPLATE_PARM:
11121     case BOUND_TEMPLATE_TEMPLATE_PARM:
11122     case TEMPLATE_PARM_INDEX:
11123     case POINTER_TYPE:
11124     case REFERENCE_TYPE:
11125     case OFFSET_TYPE:
11126     case FUNCTION_TYPE:
11127     case METHOD_TYPE:
11128     case ARRAY_TYPE:
11129     case TYPENAME_TYPE:
11130     case UNBOUND_CLASS_TEMPLATE:
11131     case TYPEOF_TYPE:
11132     case DECLTYPE_TYPE:
11133     case TYPE_DECL:
11134       return tsubst (t, args, complain, in_decl);
11135
11136     case IDENTIFIER_NODE:
11137       if (IDENTIFIER_TYPENAME_P (t))
11138         {
11139           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11140           return mangle_conv_op_name_for_type (new_type);
11141         }
11142       else
11143         return t;
11144
11145     case CONSTRUCTOR:
11146       /* This is handled by tsubst_copy_and_build.  */
11147       gcc_unreachable ();
11148
11149     case VA_ARG_EXPR:
11150       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
11151                                           in_decl),
11152                              tsubst (TREE_TYPE (t), args, complain, in_decl));
11153
11154     case CLEANUP_POINT_EXPR:
11155       /* We shouldn't have built any of these during initial template
11156          generation.  Instead, they should be built during instantiation
11157          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
11158       gcc_unreachable ();
11159
11160     case OFFSET_REF:
11161       mark_used (TREE_OPERAND (t, 1));
11162       return t;
11163
11164     case EXPR_PACK_EXPANSION:
11165       error ("invalid use of pack expansion expression");
11166       return error_mark_node;
11167
11168     case NONTYPE_ARGUMENT_PACK:
11169       error ("use %<...%> to expand argument pack");
11170       return error_mark_node;
11171
11172     default:
11173       return t;
11174     }
11175 }
11176
11177 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
11178
11179 static tree
11180 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
11181                     tree in_decl)
11182 {
11183   tree new_clauses = NULL, nc, oc;
11184
11185   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
11186     {
11187       nc = copy_node (oc);
11188       OMP_CLAUSE_CHAIN (nc) = new_clauses;
11189       new_clauses = nc;
11190
11191       switch (OMP_CLAUSE_CODE (nc))
11192         {
11193         case OMP_CLAUSE_LASTPRIVATE:
11194           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
11195             {
11196               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
11197               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
11198                            in_decl, /*integral_constant_expression_p=*/false);
11199               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
11200                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
11201             }
11202           /* FALLTHRU */
11203         case OMP_CLAUSE_PRIVATE:
11204         case OMP_CLAUSE_SHARED:
11205         case OMP_CLAUSE_FIRSTPRIVATE:
11206         case OMP_CLAUSE_REDUCTION:
11207         case OMP_CLAUSE_COPYIN:
11208         case OMP_CLAUSE_COPYPRIVATE:
11209         case OMP_CLAUSE_IF:
11210         case OMP_CLAUSE_NUM_THREADS:
11211         case OMP_CLAUSE_SCHEDULE:
11212         case OMP_CLAUSE_COLLAPSE:
11213           OMP_CLAUSE_OPERAND (nc, 0)
11214             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
11215                            in_decl, /*integral_constant_expression_p=*/false);
11216           break;
11217         case OMP_CLAUSE_NOWAIT:
11218         case OMP_CLAUSE_ORDERED:
11219         case OMP_CLAUSE_DEFAULT:
11220         case OMP_CLAUSE_UNTIED:
11221           break;
11222         default:
11223           gcc_unreachable ();
11224         }
11225     }
11226
11227   return finish_omp_clauses (nreverse (new_clauses));
11228 }
11229
11230 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
11231
11232 static tree
11233 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
11234                           tree in_decl)
11235 {
11236 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
11237
11238   tree purpose, value, chain;
11239
11240   if (t == NULL)
11241     return t;
11242
11243   if (TREE_CODE (t) != TREE_LIST)
11244     return tsubst_copy_and_build (t, args, complain, in_decl,
11245                                   /*function_p=*/false,
11246                                   /*integral_constant_expression_p=*/false);
11247
11248   if (t == void_list_node)
11249     return t;
11250
11251   purpose = TREE_PURPOSE (t);
11252   if (purpose)
11253     purpose = RECUR (purpose);
11254   value = TREE_VALUE (t);
11255   if (value && TREE_CODE (value) != LABEL_DECL)
11256     value = RECUR (value);
11257   chain = TREE_CHAIN (t);
11258   if (chain && chain != void_type_node)
11259     chain = RECUR (chain);
11260   return tree_cons (purpose, value, chain);
11261 #undef RECUR
11262 }
11263
11264 /* Substitute one OMP_FOR iterator.  */
11265
11266 static void
11267 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
11268                          tree condv, tree incrv, tree *clauses,
11269                          tree args, tsubst_flags_t complain, tree in_decl,
11270                          bool integral_constant_expression_p)
11271 {
11272 #define RECUR(NODE)                             \
11273   tsubst_expr ((NODE), args, complain, in_decl, \
11274                integral_constant_expression_p)
11275   tree decl, init, cond, incr, auto_node;
11276
11277   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
11278   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
11279   decl = RECUR (TREE_OPERAND (init, 0));
11280   init = TREE_OPERAND (init, 1);
11281   auto_node = type_uses_auto (TREE_TYPE (decl));
11282   if (auto_node && init)
11283     {
11284       tree init_expr = init;
11285       if (TREE_CODE (init_expr) == DECL_EXPR)
11286         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
11287       init_expr = RECUR (init_expr);
11288       TREE_TYPE (decl)
11289         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
11290     }
11291   gcc_assert (!type_dependent_expression_p (decl));
11292
11293   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
11294     {
11295       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
11296       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11297       if (TREE_CODE (incr) == MODIFY_EXPR)
11298         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
11299                                     RECUR (TREE_OPERAND (incr, 1)),
11300                                     complain);
11301       else
11302         incr = RECUR (incr);
11303       TREE_VEC_ELT (declv, i) = decl;
11304       TREE_VEC_ELT (initv, i) = init;
11305       TREE_VEC_ELT (condv, i) = cond;
11306       TREE_VEC_ELT (incrv, i) = incr;
11307       return;
11308     }
11309
11310   if (init && TREE_CODE (init) != DECL_EXPR)
11311     {
11312       tree c;
11313       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
11314         {
11315           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
11316                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
11317               && OMP_CLAUSE_DECL (c) == decl)
11318             break;
11319           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
11320                    && OMP_CLAUSE_DECL (c) == decl)
11321             error ("iteration variable %qD should not be firstprivate", decl);
11322           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
11323                    && OMP_CLAUSE_DECL (c) == decl)
11324             error ("iteration variable %qD should not be reduction", decl);
11325         }
11326       if (c == NULL)
11327         {
11328           c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
11329           OMP_CLAUSE_DECL (c) = decl;
11330           c = finish_omp_clauses (c);
11331           if (c)
11332             {
11333               OMP_CLAUSE_CHAIN (c) = *clauses;
11334               *clauses = c;
11335             }
11336         }
11337     }
11338   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
11339   if (COMPARISON_CLASS_P (cond))
11340     cond = build2 (TREE_CODE (cond), boolean_type_node,
11341                    RECUR (TREE_OPERAND (cond, 0)),
11342                    RECUR (TREE_OPERAND (cond, 1)));
11343   else
11344     cond = RECUR (cond);
11345   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11346   switch (TREE_CODE (incr))
11347     {
11348     case PREINCREMENT_EXPR:
11349     case PREDECREMENT_EXPR:
11350     case POSTINCREMENT_EXPR:
11351     case POSTDECREMENT_EXPR:
11352       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
11353                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
11354       break;
11355     case MODIFY_EXPR:
11356       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11357           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11358         {
11359           tree rhs = TREE_OPERAND (incr, 1);
11360           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11361                          RECUR (TREE_OPERAND (incr, 0)),
11362                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11363                                  RECUR (TREE_OPERAND (rhs, 0)),
11364                                  RECUR (TREE_OPERAND (rhs, 1))));
11365         }
11366       else
11367         incr = RECUR (incr);
11368       break;
11369     case MODOP_EXPR:
11370       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11371           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11372         {
11373           tree lhs = RECUR (TREE_OPERAND (incr, 0));
11374           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
11375                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
11376                                  TREE_TYPE (decl), lhs,
11377                                  RECUR (TREE_OPERAND (incr, 2))));
11378         }
11379       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
11380                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
11381                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
11382         {
11383           tree rhs = TREE_OPERAND (incr, 2);
11384           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11385                          RECUR (TREE_OPERAND (incr, 0)),
11386                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11387                                  RECUR (TREE_OPERAND (rhs, 0)),
11388                                  RECUR (TREE_OPERAND (rhs, 1))));
11389         }
11390       else
11391         incr = RECUR (incr);
11392       break;
11393     default:
11394       incr = RECUR (incr);
11395       break;
11396     }
11397
11398   TREE_VEC_ELT (declv, i) = decl;
11399   TREE_VEC_ELT (initv, i) = init;
11400   TREE_VEC_ELT (condv, i) = cond;
11401   TREE_VEC_ELT (incrv, i) = incr;
11402 #undef RECUR
11403 }
11404
11405 /* Like tsubst_copy for expressions, etc. but also does semantic
11406    processing.  */
11407
11408 static tree
11409 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
11410              bool integral_constant_expression_p)
11411 {
11412 #define RECUR(NODE)                             \
11413   tsubst_expr ((NODE), args, complain, in_decl, \
11414                integral_constant_expression_p)
11415
11416   tree stmt, tmp;
11417
11418   if (t == NULL_TREE || t == error_mark_node)
11419     return t;
11420
11421   if (EXPR_HAS_LOCATION (t))
11422     input_location = EXPR_LOCATION (t);
11423   if (STATEMENT_CODE_P (TREE_CODE (t)))
11424     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
11425
11426   switch (TREE_CODE (t))
11427     {
11428     case STATEMENT_LIST:
11429       {
11430         tree_stmt_iterator i;
11431         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
11432           RECUR (tsi_stmt (i));
11433         break;
11434       }
11435
11436     case CTOR_INITIALIZER:
11437       finish_mem_initializers (tsubst_initializer_list
11438                                (TREE_OPERAND (t, 0), args));
11439       break;
11440
11441     case RETURN_EXPR:
11442       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
11443       break;
11444
11445     case EXPR_STMT:
11446       tmp = RECUR (EXPR_STMT_EXPR (t));
11447       if (EXPR_STMT_STMT_EXPR_RESULT (t))
11448         finish_stmt_expr_expr (tmp, cur_stmt_expr);
11449       else
11450         finish_expr_stmt (tmp);
11451       break;
11452
11453     case USING_STMT:
11454       do_using_directive (RECUR (USING_STMT_NAMESPACE (t)));
11455       break;
11456
11457     case DECL_EXPR:
11458       {
11459         tree decl;
11460         tree init;
11461
11462         decl = DECL_EXPR_DECL (t);
11463         if (TREE_CODE (decl) == LABEL_DECL)
11464           finish_label_decl (DECL_NAME (decl));
11465         else if (TREE_CODE (decl) == USING_DECL)
11466           {
11467             tree scope = USING_DECL_SCOPE (decl);
11468             tree name = DECL_NAME (decl);
11469             tree decl;
11470
11471             scope = RECUR (scope);
11472             decl = lookup_qualified_name (scope, name,
11473                                           /*is_type_p=*/false,
11474                                           /*complain=*/false);
11475             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
11476               qualified_name_lookup_error (scope, name, decl, input_location);
11477             else
11478               do_local_using_decl (decl, scope, name);
11479           }
11480         else
11481           {
11482             init = DECL_INITIAL (decl);
11483             decl = tsubst (decl, args, complain, in_decl);
11484             if (decl != error_mark_node)
11485               {
11486                 /* By marking the declaration as instantiated, we avoid
11487                    trying to instantiate it.  Since instantiate_decl can't
11488                    handle local variables, and since we've already done
11489                    all that needs to be done, that's the right thing to
11490                    do.  */
11491                 if (TREE_CODE (decl) == VAR_DECL)
11492                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11493                 if (TREE_CODE (decl) == VAR_DECL
11494                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
11495                   /* Anonymous aggregates are a special case.  */
11496                   finish_anon_union (decl);
11497                 else
11498                   {
11499                     maybe_push_decl (decl);
11500                     if (TREE_CODE (decl) == VAR_DECL
11501                         && DECL_PRETTY_FUNCTION_P (decl))
11502                       {
11503                         /* For __PRETTY_FUNCTION__ we have to adjust the
11504                            initializer.  */
11505                         const char *const name
11506                           = cxx_printable_name (current_function_decl, 2);
11507                         init = cp_fname_init (name, &TREE_TYPE (decl));
11508                       }
11509                     else
11510                       {
11511                         tree t = RECUR (init);
11512
11513                         if (init && !t)
11514                           /* If we had an initializer but it
11515                              instantiated to nothing,
11516                              value-initialize the object.  This will
11517                              only occur when the initializer was a
11518                              pack expansion where the parameter packs
11519                              used in that expansion were of length
11520                              zero.  */
11521                           init = build_value_init (TREE_TYPE (decl));
11522                         else
11523                           init = t;
11524                       }
11525
11526                     cp_finish_decl (decl, init, false, NULL_TREE, 0);
11527                   }
11528               }
11529           }
11530
11531         /* A DECL_EXPR can also be used as an expression, in the condition
11532            clause of an if/for/while construct.  */
11533         return decl;
11534       }
11535
11536     case FOR_STMT:
11537       stmt = begin_for_stmt ();
11538                           RECUR (FOR_INIT_STMT (t));
11539       finish_for_init_stmt (stmt);
11540       tmp = RECUR (FOR_COND (t));
11541       finish_for_cond (tmp, stmt);
11542       tmp = RECUR (FOR_EXPR (t));
11543       finish_for_expr (tmp, stmt);
11544       RECUR (FOR_BODY (t));
11545       finish_for_stmt (stmt);
11546       break;
11547
11548     case WHILE_STMT:
11549       stmt = begin_while_stmt ();
11550       tmp = RECUR (WHILE_COND (t));
11551       finish_while_stmt_cond (tmp, stmt);
11552       RECUR (WHILE_BODY (t));
11553       finish_while_stmt (stmt);
11554       break;
11555
11556     case DO_STMT:
11557       stmt = begin_do_stmt ();
11558       RECUR (DO_BODY (t));
11559       finish_do_body (stmt);
11560       tmp = RECUR (DO_COND (t));
11561       finish_do_stmt (tmp, stmt);
11562       break;
11563
11564     case IF_STMT:
11565       stmt = begin_if_stmt ();
11566       tmp = RECUR (IF_COND (t));
11567       finish_if_stmt_cond (tmp, stmt);
11568       RECUR (THEN_CLAUSE (t));
11569       finish_then_clause (stmt);
11570
11571       if (ELSE_CLAUSE (t))
11572         {
11573           begin_else_clause (stmt);
11574           RECUR (ELSE_CLAUSE (t));
11575           finish_else_clause (stmt);
11576         }
11577
11578       finish_if_stmt (stmt);
11579       break;
11580
11581     case BIND_EXPR:
11582       if (BIND_EXPR_BODY_BLOCK (t))
11583         stmt = begin_function_body ();
11584       else
11585         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
11586                                     ? BCS_TRY_BLOCK : 0);
11587
11588       RECUR (BIND_EXPR_BODY (t));
11589
11590       if (BIND_EXPR_BODY_BLOCK (t))
11591         finish_function_body (stmt);
11592       else
11593         finish_compound_stmt (stmt);
11594       break;
11595
11596     case BREAK_STMT:
11597       finish_break_stmt ();
11598       break;
11599
11600     case CONTINUE_STMT:
11601       finish_continue_stmt ();
11602       break;
11603
11604     case SWITCH_STMT:
11605       stmt = begin_switch_stmt ();
11606       tmp = RECUR (SWITCH_STMT_COND (t));
11607       finish_switch_cond (tmp, stmt);
11608       RECUR (SWITCH_STMT_BODY (t));
11609       finish_switch_stmt (stmt);
11610       break;
11611
11612     case CASE_LABEL_EXPR:
11613       finish_case_label (EXPR_LOCATION (t),
11614                          RECUR (CASE_LOW (t)),
11615                          RECUR (CASE_HIGH (t)));
11616       break;
11617
11618     case LABEL_EXPR:
11619       {
11620         tree decl = LABEL_EXPR_LABEL (t);
11621         tree label;
11622
11623         label = finish_label_stmt (DECL_NAME (decl));
11624         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
11625           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
11626       }
11627       break;
11628
11629     case GOTO_EXPR:
11630       tmp = GOTO_DESTINATION (t);
11631       if (TREE_CODE (tmp) != LABEL_DECL)
11632         /* Computed goto's must be tsubst'd into.  On the other hand,
11633            non-computed gotos must not be; the identifier in question
11634            will have no binding.  */
11635         tmp = RECUR (tmp);
11636       else
11637         tmp = DECL_NAME (tmp);
11638       finish_goto_stmt (tmp);
11639       break;
11640
11641     case ASM_EXPR:
11642       tmp = finish_asm_stmt
11643         (ASM_VOLATILE_P (t),
11644          RECUR (ASM_STRING (t)),
11645          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
11646          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
11647          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl),
11648          tsubst_copy_asm_operands (ASM_LABELS (t), args, complain, in_decl));
11649       {
11650         tree asm_expr = tmp;
11651         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
11652           asm_expr = TREE_OPERAND (asm_expr, 0);
11653         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
11654       }
11655       break;
11656
11657     case TRY_BLOCK:
11658       if (CLEANUP_P (t))
11659         {
11660           stmt = begin_try_block ();
11661           RECUR (TRY_STMTS (t));
11662           finish_cleanup_try_block (stmt);
11663           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
11664         }
11665       else
11666         {
11667           tree compound_stmt = NULL_TREE;
11668
11669           if (FN_TRY_BLOCK_P (t))
11670             stmt = begin_function_try_block (&compound_stmt);
11671           else
11672             stmt = begin_try_block ();
11673
11674           RECUR (TRY_STMTS (t));
11675
11676           if (FN_TRY_BLOCK_P (t))
11677             finish_function_try_block (stmt);
11678           else
11679             finish_try_block (stmt);
11680
11681           RECUR (TRY_HANDLERS (t));
11682           if (FN_TRY_BLOCK_P (t))
11683             finish_function_handler_sequence (stmt, compound_stmt);
11684           else
11685             finish_handler_sequence (stmt);
11686         }
11687       break;
11688
11689     case HANDLER:
11690       {
11691         tree decl = HANDLER_PARMS (t);
11692
11693         if (decl)
11694           {
11695             decl = tsubst (decl, args, complain, in_decl);
11696             /* Prevent instantiate_decl from trying to instantiate
11697                this variable.  We've already done all that needs to be
11698                done.  */
11699             if (decl != error_mark_node)
11700               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11701           }
11702         stmt = begin_handler ();
11703         finish_handler_parms (decl, stmt);
11704         RECUR (HANDLER_BODY (t));
11705         finish_handler (stmt);
11706       }
11707       break;
11708
11709     case TAG_DEFN:
11710       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
11711       break;
11712
11713     case STATIC_ASSERT:
11714       {
11715         tree condition = 
11716           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
11717                        args,
11718                        complain, in_decl,
11719                        /*integral_constant_expression_p=*/true);
11720         finish_static_assert (condition,
11721                               STATIC_ASSERT_MESSAGE (t),
11722                               STATIC_ASSERT_SOURCE_LOCATION (t),
11723                               /*member_p=*/false);
11724       }
11725       break;
11726
11727     case OMP_PARALLEL:
11728       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
11729                                 args, complain, in_decl);
11730       stmt = begin_omp_parallel ();
11731       RECUR (OMP_PARALLEL_BODY (t));
11732       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
11733         = OMP_PARALLEL_COMBINED (t);
11734       break;
11735
11736     case OMP_TASK:
11737       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
11738                                 args, complain, in_decl);
11739       stmt = begin_omp_task ();
11740       RECUR (OMP_TASK_BODY (t));
11741       finish_omp_task (tmp, stmt);
11742       break;
11743
11744     case OMP_FOR:
11745       {
11746         tree clauses, body, pre_body;
11747         tree declv, initv, condv, incrv;
11748         int i;
11749
11750         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
11751                                       args, complain, in_decl);
11752         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11753         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11754         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11755         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11756
11757         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
11758           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
11759                                    &clauses, args, complain, in_decl,
11760                                    integral_constant_expression_p);
11761
11762         stmt = begin_omp_structured_block ();
11763
11764         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
11765           if (TREE_VEC_ELT (initv, i) == NULL
11766               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
11767             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
11768           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
11769             {
11770               tree init = RECUR (TREE_VEC_ELT (initv, i));
11771               gcc_assert (init == TREE_VEC_ELT (declv, i));
11772               TREE_VEC_ELT (initv, i) = NULL_TREE;
11773             }
11774           else
11775             {
11776               tree decl_expr = TREE_VEC_ELT (initv, i);
11777               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
11778               gcc_assert (init != NULL);
11779               TREE_VEC_ELT (initv, i) = RECUR (init);
11780               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
11781               RECUR (decl_expr);
11782               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
11783             }
11784
11785         pre_body = push_stmt_list ();
11786         RECUR (OMP_FOR_PRE_BODY (t));
11787         pre_body = pop_stmt_list (pre_body);
11788
11789         body = push_stmt_list ();
11790         RECUR (OMP_FOR_BODY (t));
11791         body = pop_stmt_list (body);
11792
11793         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
11794                             body, pre_body, clauses);
11795
11796         add_stmt (finish_omp_structured_block (stmt));
11797       }
11798       break;
11799
11800     case OMP_SECTIONS:
11801     case OMP_SINGLE:
11802       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
11803       stmt = push_stmt_list ();
11804       RECUR (OMP_BODY (t));
11805       stmt = pop_stmt_list (stmt);
11806
11807       t = copy_node (t);
11808       OMP_BODY (t) = stmt;
11809       OMP_CLAUSES (t) = tmp;
11810       add_stmt (t);
11811       break;
11812
11813     case OMP_SECTION:
11814     case OMP_CRITICAL:
11815     case OMP_MASTER:
11816     case OMP_ORDERED:
11817       stmt = push_stmt_list ();
11818       RECUR (OMP_BODY (t));
11819       stmt = pop_stmt_list (stmt);
11820
11821       t = copy_node (t);
11822       OMP_BODY (t) = stmt;
11823       add_stmt (t);
11824       break;
11825
11826     case OMP_ATOMIC:
11827       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
11828       {
11829         tree op1 = TREE_OPERAND (t, 1);
11830         tree lhs = RECUR (TREE_OPERAND (op1, 0));
11831         tree rhs = RECUR (TREE_OPERAND (op1, 1));
11832         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
11833       }
11834       break;
11835
11836     case EXPR_PACK_EXPANSION:
11837       error ("invalid use of pack expansion expression");
11838       return error_mark_node;
11839
11840     case NONTYPE_ARGUMENT_PACK:
11841       error ("use %<...%> to expand argument pack");
11842       return error_mark_node;
11843
11844     default:
11845       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
11846
11847       return tsubst_copy_and_build (t, args, complain, in_decl,
11848                                     /*function_p=*/false,
11849                                     integral_constant_expression_p);
11850     }
11851
11852   return NULL_TREE;
11853 #undef RECUR
11854 }
11855
11856 /* T is a postfix-expression that is not being used in a function
11857    call.  Return the substituted version of T.  */
11858
11859 static tree
11860 tsubst_non_call_postfix_expression (tree t, tree args,
11861                                     tsubst_flags_t complain,
11862                                     tree in_decl)
11863 {
11864   if (TREE_CODE (t) == SCOPE_REF)
11865     t = tsubst_qualified_id (t, args, complain, in_decl,
11866                              /*done=*/false, /*address_p=*/false);
11867   else
11868     t = tsubst_copy_and_build (t, args, complain, in_decl,
11869                                /*function_p=*/false,
11870                                /*integral_constant_expression_p=*/false);
11871
11872   return t;
11873 }
11874
11875 /* Like tsubst but deals with expressions and performs semantic
11876    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
11877
11878 tree
11879 tsubst_copy_and_build (tree t,
11880                        tree args,
11881                        tsubst_flags_t complain,
11882                        tree in_decl,
11883                        bool function_p,
11884                        bool integral_constant_expression_p)
11885 {
11886 #define RECUR(NODE)                                             \
11887   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
11888                          /*function_p=*/false,                  \
11889                          integral_constant_expression_p)
11890
11891   tree op1;
11892
11893   if (t == NULL_TREE || t == error_mark_node)
11894     return t;
11895
11896   switch (TREE_CODE (t))
11897     {
11898     case USING_DECL:
11899       t = DECL_NAME (t);
11900       /* Fall through.  */
11901     case IDENTIFIER_NODE:
11902       {
11903         tree decl;
11904         cp_id_kind idk;
11905         bool non_integral_constant_expression_p;
11906         const char *error_msg;
11907
11908         if (IDENTIFIER_TYPENAME_P (t))
11909           {
11910             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11911             t = mangle_conv_op_name_for_type (new_type);
11912           }
11913
11914         /* Look up the name.  */
11915         decl = lookup_name (t);
11916
11917         /* By convention, expressions use ERROR_MARK_NODE to indicate
11918            failure, not NULL_TREE.  */
11919         if (decl == NULL_TREE)
11920           decl = error_mark_node;
11921
11922         decl = finish_id_expression (t, decl, NULL_TREE,
11923                                      &idk,
11924                                      integral_constant_expression_p,
11925                                      /*allow_non_integral_constant_expression_p=*/false,
11926                                      &non_integral_constant_expression_p,
11927                                      /*template_p=*/false,
11928                                      /*done=*/true,
11929                                      /*address_p=*/false,
11930                                      /*template_arg_p=*/false,
11931                                      &error_msg,
11932                                      input_location);
11933         if (error_msg)
11934           error (error_msg);
11935         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
11936           decl = unqualified_name_lookup_error (decl);
11937         return decl;
11938       }
11939
11940     case TEMPLATE_ID_EXPR:
11941       {
11942         tree object;
11943         tree templ = RECUR (TREE_OPERAND (t, 0));
11944         tree targs = TREE_OPERAND (t, 1);
11945
11946         if (targs)
11947           targs = tsubst_template_args (targs, args, complain, in_decl);
11948
11949         if (TREE_CODE (templ) == COMPONENT_REF)
11950           {
11951             object = TREE_OPERAND (templ, 0);
11952             templ = TREE_OPERAND (templ, 1);
11953           }
11954         else
11955           object = NULL_TREE;
11956         templ = lookup_template_function (templ, targs);
11957
11958         if (object)
11959           return build3 (COMPONENT_REF, TREE_TYPE (templ),
11960                          object, templ, NULL_TREE);
11961         else
11962           return baselink_for_fns (templ);
11963       }
11964
11965     case INDIRECT_REF:
11966       {
11967         tree r = RECUR (TREE_OPERAND (t, 0));
11968
11969         if (REFERENCE_REF_P (t))
11970           {
11971             /* A type conversion to reference type will be enclosed in
11972                such an indirect ref, but the substitution of the cast
11973                will have also added such an indirect ref.  */
11974             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
11975               r = convert_from_reference (r);
11976           }
11977         else
11978           r = build_x_indirect_ref (r, RO_UNARY_STAR, complain);
11979         return r;
11980       }
11981
11982     case NOP_EXPR:
11983       return build_nop
11984         (tsubst (TREE_TYPE (t), args, complain, in_decl),
11985          RECUR (TREE_OPERAND (t, 0)));
11986
11987     case CAST_EXPR:
11988     case REINTERPRET_CAST_EXPR:
11989     case CONST_CAST_EXPR:
11990     case DYNAMIC_CAST_EXPR:
11991     case STATIC_CAST_EXPR:
11992       {
11993         tree type;
11994         tree op;
11995
11996         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11997         if (integral_constant_expression_p
11998             && !cast_valid_in_integral_constant_expression_p (type))
11999           {
12000             if (complain & tf_error)
12001               error ("a cast to a type other than an integral or "
12002                      "enumeration type cannot appear in a constant-expression");
12003             return error_mark_node; 
12004           }
12005
12006         op = RECUR (TREE_OPERAND (t, 0));
12007
12008         switch (TREE_CODE (t))
12009           {
12010           case CAST_EXPR:
12011             return build_functional_cast (type, op, complain);
12012           case REINTERPRET_CAST_EXPR:
12013             return build_reinterpret_cast (type, op, complain);
12014           case CONST_CAST_EXPR:
12015             return build_const_cast (type, op, complain);
12016           case DYNAMIC_CAST_EXPR:
12017             return build_dynamic_cast (type, op, complain);
12018           case STATIC_CAST_EXPR:
12019             return build_static_cast (type, op, complain);
12020           default:
12021             gcc_unreachable ();
12022           }
12023       }
12024
12025     case POSTDECREMENT_EXPR:
12026     case POSTINCREMENT_EXPR:
12027       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12028                                                 args, complain, in_decl);
12029       return build_x_unary_op (TREE_CODE (t), op1, complain);
12030
12031     case PREDECREMENT_EXPR:
12032     case PREINCREMENT_EXPR:
12033     case NEGATE_EXPR:
12034     case BIT_NOT_EXPR:
12035     case ABS_EXPR:
12036     case TRUTH_NOT_EXPR:
12037     case UNARY_PLUS_EXPR:  /* Unary + */
12038     case REALPART_EXPR:
12039     case IMAGPART_EXPR:
12040       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
12041                                complain);
12042
12043     case ADDR_EXPR:
12044       op1 = TREE_OPERAND (t, 0);
12045       if (TREE_CODE (op1) == SCOPE_REF)
12046         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
12047                                    /*done=*/true, /*address_p=*/true);
12048       else
12049         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
12050                                                   in_decl);
12051       if (TREE_CODE (op1) == LABEL_DECL)
12052         return finish_label_address_expr (DECL_NAME (op1),
12053                                           EXPR_LOCATION (op1));
12054       return build_x_unary_op (ADDR_EXPR, op1, complain);
12055
12056     case PLUS_EXPR:
12057     case MINUS_EXPR:
12058     case MULT_EXPR:
12059     case TRUNC_DIV_EXPR:
12060     case CEIL_DIV_EXPR:
12061     case FLOOR_DIV_EXPR:
12062     case ROUND_DIV_EXPR:
12063     case EXACT_DIV_EXPR:
12064     case BIT_AND_EXPR:
12065     case BIT_IOR_EXPR:
12066     case BIT_XOR_EXPR:
12067     case TRUNC_MOD_EXPR:
12068     case FLOOR_MOD_EXPR:
12069     case TRUTH_ANDIF_EXPR:
12070     case TRUTH_ORIF_EXPR:
12071     case TRUTH_AND_EXPR:
12072     case TRUTH_OR_EXPR:
12073     case RSHIFT_EXPR:
12074     case LSHIFT_EXPR:
12075     case RROTATE_EXPR:
12076     case LROTATE_EXPR:
12077     case EQ_EXPR:
12078     case NE_EXPR:
12079     case MAX_EXPR:
12080     case MIN_EXPR:
12081     case LE_EXPR:
12082     case GE_EXPR:
12083     case LT_EXPR:
12084     case GT_EXPR:
12085     case MEMBER_REF:
12086     case DOTSTAR_EXPR:
12087       return build_x_binary_op
12088         (TREE_CODE (t),
12089          RECUR (TREE_OPERAND (t, 0)),
12090          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
12091           ? ERROR_MARK
12092           : TREE_CODE (TREE_OPERAND (t, 0))),
12093          RECUR (TREE_OPERAND (t, 1)),
12094          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
12095           ? ERROR_MARK
12096           : TREE_CODE (TREE_OPERAND (t, 1))),
12097          /*overloaded_p=*/NULL,
12098          complain);
12099
12100     case SCOPE_REF:
12101       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
12102                                   /*address_p=*/false);
12103     case ARRAY_REF:
12104       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12105                                                 args, complain, in_decl);
12106       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
12107
12108     case SIZEOF_EXPR:
12109       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
12110         return tsubst_copy (t, args, complain, in_decl);
12111       /* Fall through */
12112       
12113     case ALIGNOF_EXPR:
12114       op1 = TREE_OPERAND (t, 0);
12115       if (!args)
12116         {
12117           /* When there are no ARGS, we are trying to evaluate a
12118              non-dependent expression from the parser.  Trying to do
12119              the substitutions may not work.  */
12120           if (!TYPE_P (op1))
12121             op1 = TREE_TYPE (op1);
12122         }
12123       else
12124         {
12125           ++cp_unevaluated_operand;
12126           ++c_inhibit_evaluation_warnings;
12127           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
12128                                        /*function_p=*/false,
12129                                        /*integral_constant_expression_p=*/false);
12130           --cp_unevaluated_operand;
12131           --c_inhibit_evaluation_warnings;
12132         }
12133       if (TYPE_P (op1))
12134         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
12135                                            complain & tf_error);
12136       else
12137         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
12138                                            complain & tf_error);
12139
12140     case MODOP_EXPR:
12141       {
12142         tree r = build_x_modify_expr
12143           (RECUR (TREE_OPERAND (t, 0)),
12144            TREE_CODE (TREE_OPERAND (t, 1)),
12145            RECUR (TREE_OPERAND (t, 2)),
12146            complain);
12147         /* TREE_NO_WARNING must be set if either the expression was
12148            parenthesized or it uses an operator such as >>= rather
12149            than plain assignment.  In the former case, it was already
12150            set and must be copied.  In the latter case,
12151            build_x_modify_expr sets it and it must not be reset
12152            here.  */
12153         if (TREE_NO_WARNING (t))
12154           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
12155         return r;
12156       }
12157
12158     case ARROW_EXPR:
12159       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12160                                                 args, complain, in_decl);
12161       /* Remember that there was a reference to this entity.  */
12162       if (DECL_P (op1))
12163         mark_used (op1);
12164       return build_x_arrow (op1);
12165
12166     case NEW_EXPR:
12167       {
12168         tree placement = RECUR (TREE_OPERAND (t, 0));
12169         tree init = RECUR (TREE_OPERAND (t, 3));
12170         VEC(tree,gc) *placement_vec;
12171         VEC(tree,gc) *init_vec;
12172         tree ret;
12173
12174         if (placement == NULL_TREE)
12175           placement_vec = NULL;
12176         else
12177           {
12178             placement_vec = make_tree_vector ();
12179             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
12180               VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
12181           }
12182
12183         /* If there was an initializer in the original tree, but it
12184            instantiated to an empty list, then we should pass a
12185            non-NULL empty vector to tell build_new that it was an
12186            empty initializer() rather than no initializer.  This can
12187            only happen when the initializer is a pack expansion whose
12188            parameter packs are of length zero.  */
12189         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
12190           init_vec = NULL;
12191         else
12192           {
12193             init_vec = make_tree_vector ();
12194             if (init == void_zero_node)
12195               gcc_assert (init_vec != NULL);
12196             else
12197               {
12198                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
12199                   VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
12200               }
12201           }
12202
12203         ret = build_new (&placement_vec,
12204                          RECUR (TREE_OPERAND (t, 1)),
12205                          RECUR (TREE_OPERAND (t, 2)),
12206                          &init_vec,
12207                          NEW_EXPR_USE_GLOBAL (t),
12208                          complain);
12209
12210         if (placement_vec != NULL)
12211           release_tree_vector (placement_vec);
12212         if (init_vec != NULL)
12213           release_tree_vector (init_vec);
12214
12215         return ret;
12216       }
12217
12218     case DELETE_EXPR:
12219      return delete_sanity
12220        (RECUR (TREE_OPERAND (t, 0)),
12221         RECUR (TREE_OPERAND (t, 1)),
12222         DELETE_EXPR_USE_VEC (t),
12223         DELETE_EXPR_USE_GLOBAL (t));
12224
12225     case COMPOUND_EXPR:
12226       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
12227                                     RECUR (TREE_OPERAND (t, 1)),
12228                                     complain);
12229
12230     case CALL_EXPR:
12231       {
12232         tree function;
12233         VEC(tree,gc) *call_args;
12234         unsigned int nargs, i;
12235         bool qualified_p;
12236         bool koenig_p;
12237         tree ret;
12238
12239         function = CALL_EXPR_FN (t);
12240         /* When we parsed the expression,  we determined whether or
12241            not Koenig lookup should be performed.  */
12242         koenig_p = KOENIG_LOOKUP_P (t);
12243         if (TREE_CODE (function) == SCOPE_REF)
12244           {
12245             qualified_p = true;
12246             function = tsubst_qualified_id (function, args, complain, in_decl,
12247                                             /*done=*/false,
12248                                             /*address_p=*/false);
12249           }
12250         else
12251           {
12252             if (TREE_CODE (function) == COMPONENT_REF)
12253               {
12254                 tree op = TREE_OPERAND (function, 1);
12255
12256                 qualified_p = (TREE_CODE (op) == SCOPE_REF
12257                                || (BASELINK_P (op)
12258                                    && BASELINK_QUALIFIED_P (op)));
12259               }
12260             else
12261               qualified_p = false;
12262
12263             function = tsubst_copy_and_build (function, args, complain,
12264                                               in_decl,
12265                                               !qualified_p,
12266                                               integral_constant_expression_p);
12267
12268             if (BASELINK_P (function))
12269               qualified_p = true;
12270           }
12271
12272         nargs = call_expr_nargs (t);
12273         call_args = make_tree_vector ();
12274         for (i = 0; i < nargs; ++i)
12275           {
12276             tree arg = CALL_EXPR_ARG (t, i);
12277
12278             if (!PACK_EXPANSION_P (arg))
12279               VEC_safe_push (tree, gc, call_args,
12280                              RECUR (CALL_EXPR_ARG (t, i)));
12281             else
12282               {
12283                 /* Expand the pack expansion and push each entry onto
12284                    CALL_ARGS.  */
12285                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
12286                 if (TREE_CODE (arg) == TREE_VEC)
12287                   {
12288                     unsigned int len, j;
12289
12290                     len = TREE_VEC_LENGTH (arg);
12291                     for (j = 0; j < len; ++j)
12292                       {
12293                         tree value = TREE_VEC_ELT (arg, j);
12294                         if (value != NULL_TREE)
12295                           value = convert_from_reference (value);
12296                         VEC_safe_push (tree, gc, call_args, value);
12297                       }
12298                   }
12299                 else
12300                   {
12301                     /* A partial substitution.  Add one entry.  */
12302                     VEC_safe_push (tree, gc, call_args, arg);
12303                   }
12304               }
12305           }
12306
12307         /* We do not perform argument-dependent lookup if normal
12308            lookup finds a non-function, in accordance with the
12309            expected resolution of DR 218.  */
12310         if (koenig_p
12311             && ((is_overloaded_fn (function)
12312                  /* If lookup found a member function, the Koenig lookup is
12313                     not appropriate, even if an unqualified-name was used
12314                     to denote the function.  */
12315                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
12316                 || TREE_CODE (function) == IDENTIFIER_NODE)
12317             /* Only do this when substitution turns a dependent call
12318                into a non-dependent call.  */
12319             && type_dependent_expression_p_push (t)
12320             && !any_type_dependent_arguments_p (call_args))
12321           function = perform_koenig_lookup (function, call_args);
12322
12323         if (TREE_CODE (function) == IDENTIFIER_NODE)
12324           {
12325             unqualified_name_lookup_error (function);
12326             release_tree_vector (call_args);
12327             return error_mark_node;
12328           }
12329
12330         /* Remember that there was a reference to this entity.  */
12331         if (DECL_P (function))
12332           mark_used (function);
12333
12334         if (TREE_CODE (function) == OFFSET_REF)
12335           ret = build_offset_ref_call_from_tree (function, &call_args);
12336         else if (TREE_CODE (function) == COMPONENT_REF)
12337           {
12338             if (!BASELINK_P (TREE_OPERAND (function, 1)))
12339               ret = finish_call_expr (function, &call_args,
12340                                        /*disallow_virtual=*/false,
12341                                        /*koenig_p=*/false,
12342                                        complain);
12343             else
12344               ret = (build_new_method_call
12345                       (TREE_OPERAND (function, 0),
12346                        TREE_OPERAND (function, 1),
12347                        &call_args, NULL_TREE,
12348                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
12349                        /*fn_p=*/NULL,
12350                        complain));
12351           }
12352         else
12353           ret = finish_call_expr (function, &call_args,
12354                                   /*disallow_virtual=*/qualified_p,
12355                                   koenig_p,
12356                                   complain);
12357
12358         release_tree_vector (call_args);
12359
12360         return ret;
12361       }
12362
12363     case COND_EXPR:
12364       return build_x_conditional_expr
12365         (RECUR (TREE_OPERAND (t, 0)),
12366          RECUR (TREE_OPERAND (t, 1)),
12367          RECUR (TREE_OPERAND (t, 2)),
12368          complain);
12369
12370     case PSEUDO_DTOR_EXPR:
12371       return finish_pseudo_destructor_expr
12372         (RECUR (TREE_OPERAND (t, 0)),
12373          RECUR (TREE_OPERAND (t, 1)),
12374          RECUR (TREE_OPERAND (t, 2)));
12375
12376     case TREE_LIST:
12377       {
12378         tree purpose, value, chain;
12379
12380         if (t == void_list_node)
12381           return t;
12382
12383         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
12384             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
12385           {
12386             /* We have pack expansions, so expand those and
12387                create a new list out of it.  */
12388             tree purposevec = NULL_TREE;
12389             tree valuevec = NULL_TREE;
12390             tree chain;
12391             int i, len = -1;
12392
12393             /* Expand the argument expressions.  */
12394             if (TREE_PURPOSE (t))
12395               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
12396                                                  complain, in_decl);
12397             if (TREE_VALUE (t))
12398               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
12399                                                complain, in_decl);
12400
12401             /* Build the rest of the list.  */
12402             chain = TREE_CHAIN (t);
12403             if (chain && chain != void_type_node)
12404               chain = RECUR (chain);
12405
12406             /* Determine the number of arguments.  */
12407             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
12408               {
12409                 len = TREE_VEC_LENGTH (purposevec);
12410                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
12411               }
12412             else if (TREE_CODE (valuevec) == TREE_VEC)
12413               len = TREE_VEC_LENGTH (valuevec);
12414             else
12415               {
12416                 /* Since we only performed a partial substitution into
12417                    the argument pack, we only return a single list
12418                    node.  */
12419                 if (purposevec == TREE_PURPOSE (t)
12420                     && valuevec == TREE_VALUE (t)
12421                     && chain == TREE_CHAIN (t))
12422                   return t;
12423
12424                 return tree_cons (purposevec, valuevec, chain);
12425               }
12426             
12427             /* Convert the argument vectors into a TREE_LIST */
12428             i = len;
12429             while (i > 0)
12430               {
12431                 /* Grab the Ith values.  */
12432                 i--;
12433                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
12434                                      : NULL_TREE;
12435                 value 
12436                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
12437                              : NULL_TREE;
12438
12439                 /* Build the list (backwards).  */
12440                 chain = tree_cons (purpose, value, chain);
12441               }
12442
12443             return chain;
12444           }
12445
12446         purpose = TREE_PURPOSE (t);
12447         if (purpose)
12448           purpose = RECUR (purpose);
12449         value = TREE_VALUE (t);
12450         if (value)
12451           value = RECUR (value);
12452         chain = TREE_CHAIN (t);
12453         if (chain && chain != void_type_node)
12454           chain = RECUR (chain);
12455         if (purpose == TREE_PURPOSE (t)
12456             && value == TREE_VALUE (t)
12457             && chain == TREE_CHAIN (t))
12458           return t;
12459         return tree_cons (purpose, value, chain);
12460       }
12461
12462     case COMPONENT_REF:
12463       {
12464         tree object;
12465         tree object_type;
12466         tree member;
12467
12468         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12469                                                      args, complain, in_decl);
12470         /* Remember that there was a reference to this entity.  */
12471         if (DECL_P (object))
12472           mark_used (object);
12473         object_type = TREE_TYPE (object);
12474
12475         member = TREE_OPERAND (t, 1);
12476         if (BASELINK_P (member))
12477           member = tsubst_baselink (member,
12478                                     non_reference (TREE_TYPE (object)),
12479                                     args, complain, in_decl);
12480         else
12481           member = tsubst_copy (member, args, complain, in_decl);
12482         if (member == error_mark_node)
12483           return error_mark_node;
12484
12485         if (object_type && !CLASS_TYPE_P (object_type))
12486           {
12487             if (SCALAR_TYPE_P (object_type))
12488               {
12489                 tree s = NULL_TREE;
12490                 tree dtor = member;
12491
12492                 if (TREE_CODE (dtor) == SCOPE_REF)
12493                   {
12494                     s = TREE_OPERAND (dtor, 0);
12495                     dtor = TREE_OPERAND (dtor, 1);
12496                   }
12497                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
12498                   {
12499                     dtor = TREE_OPERAND (dtor, 0);
12500                     if (TYPE_P (dtor))
12501                       return finish_pseudo_destructor_expr (object, s, dtor);
12502                   }
12503               }
12504           }
12505         else if (TREE_CODE (member) == SCOPE_REF
12506                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
12507           {
12508             tree tmpl;
12509             tree args;
12510
12511             /* Lookup the template functions now that we know what the
12512                scope is.  */
12513             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
12514             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
12515             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
12516                                             /*is_type_p=*/false,
12517                                             /*complain=*/false);
12518             if (BASELINK_P (member))
12519               {
12520                 BASELINK_FUNCTIONS (member)
12521                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
12522                               args);
12523                 member = (adjust_result_of_qualified_name_lookup
12524                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
12525                            object_type));
12526               }
12527             else
12528               {
12529                 qualified_name_lookup_error (object_type, tmpl, member,
12530                                              input_location);
12531                 return error_mark_node;
12532               }
12533           }
12534         else if (TREE_CODE (member) == SCOPE_REF
12535                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
12536                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
12537           {
12538             if (complain & tf_error)
12539               {
12540                 if (TYPE_P (TREE_OPERAND (member, 0)))
12541                   error ("%qT is not a class or namespace",
12542                          TREE_OPERAND (member, 0));
12543                 else
12544                   error ("%qD is not a class or namespace",
12545                          TREE_OPERAND (member, 0));
12546               }
12547             return error_mark_node;
12548           }
12549         else if (TREE_CODE (member) == FIELD_DECL)
12550           return finish_non_static_data_member (member, object, NULL_TREE);
12551
12552         return finish_class_member_access_expr (object, member,
12553                                                 /*template_p=*/false,
12554                                                 complain);
12555       }
12556
12557     case THROW_EXPR:
12558       return build_throw
12559         (RECUR (TREE_OPERAND (t, 0)));
12560
12561     case CONSTRUCTOR:
12562       {
12563         VEC(constructor_elt,gc) *n;
12564         constructor_elt *ce;
12565         unsigned HOST_WIDE_INT idx;
12566         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12567         bool process_index_p;
12568         int newlen;
12569         bool need_copy_p = false;
12570         tree r;
12571
12572         if (type == error_mark_node)
12573           return error_mark_node;
12574
12575         /* digest_init will do the wrong thing if we let it.  */
12576         if (type && TYPE_PTRMEMFUNC_P (type))
12577           return t;
12578
12579         /* We do not want to process the index of aggregate
12580            initializers as they are identifier nodes which will be
12581            looked up by digest_init.  */
12582         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
12583
12584         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
12585         newlen = VEC_length (constructor_elt, n);
12586         for (idx = 0; VEC_iterate (constructor_elt, n, idx, ce); idx++)
12587           {
12588             if (ce->index && process_index_p)
12589               ce->index = RECUR (ce->index);
12590
12591             if (PACK_EXPANSION_P (ce->value))
12592               {
12593                 /* Substitute into the pack expansion.  */
12594                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
12595                                                   in_decl);
12596
12597                 if (ce->value == error_mark_node)
12598                   ;
12599                 else if (TREE_VEC_LENGTH (ce->value) == 1)
12600                   /* Just move the argument into place.  */
12601                   ce->value = TREE_VEC_ELT (ce->value, 0);
12602                 else
12603                   {
12604                     /* Update the length of the final CONSTRUCTOR
12605                        arguments vector, and note that we will need to
12606                        copy.*/
12607                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
12608                     need_copy_p = true;
12609                   }
12610               }
12611             else
12612               ce->value = RECUR (ce->value);
12613           }
12614
12615         if (need_copy_p)
12616           {
12617             VEC(constructor_elt,gc) *old_n = n;
12618
12619             n = VEC_alloc (constructor_elt, gc, newlen);
12620             for (idx = 0; VEC_iterate (constructor_elt, old_n, idx, ce); 
12621                  idx++)
12622               {
12623                 if (TREE_CODE (ce->value) == TREE_VEC)
12624                   {
12625                     int i, len = TREE_VEC_LENGTH (ce->value);
12626                     for (i = 0; i < len; ++i)
12627                       CONSTRUCTOR_APPEND_ELT (n, 0,
12628                                               TREE_VEC_ELT (ce->value, i));
12629                   }
12630                 else
12631                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
12632               }
12633           }
12634
12635         r = build_constructor (init_list_type_node, n);
12636         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
12637
12638         if (TREE_HAS_CONSTRUCTOR (t))
12639           return finish_compound_literal (type, r);
12640
12641         return r;
12642       }
12643
12644     case TYPEID_EXPR:
12645       {
12646         tree operand_0 = RECUR (TREE_OPERAND (t, 0));
12647         if (TYPE_P (operand_0))
12648           return get_typeid (operand_0);
12649         return build_typeid (operand_0);
12650       }
12651
12652     case VAR_DECL:
12653       if (!args)
12654         return t;
12655       /* Fall through */
12656
12657     case PARM_DECL:
12658       {
12659         tree r = tsubst_copy (t, args, complain, in_decl);
12660
12661         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
12662           /* If the original type was a reference, we'll be wrapped in
12663              the appropriate INDIRECT_REF.  */
12664           r = convert_from_reference (r);
12665         return r;
12666       }
12667
12668     case VA_ARG_EXPR:
12669       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
12670                              tsubst_copy (TREE_TYPE (t), args, complain,
12671                                           in_decl));
12672
12673     case OFFSETOF_EXPR:
12674       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
12675
12676     case TRAIT_EXPR:
12677       {
12678         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
12679                                   complain, in_decl);
12680
12681         tree type2 = TRAIT_EXPR_TYPE2 (t);
12682         if (type2)
12683           type2 = tsubst_copy (type2, args, complain, in_decl);
12684         
12685         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
12686       }
12687
12688     case STMT_EXPR:
12689       {
12690         tree old_stmt_expr = cur_stmt_expr;
12691         tree stmt_expr = begin_stmt_expr ();
12692
12693         cur_stmt_expr = stmt_expr;
12694         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
12695                      integral_constant_expression_p);
12696         stmt_expr = finish_stmt_expr (stmt_expr, false);
12697         cur_stmt_expr = old_stmt_expr;
12698
12699         /* If the resulting list of expression statement is empty,
12700            fold it further into void_zero_node.  */
12701         if (empty_expr_stmt_p (stmt_expr))
12702           stmt_expr = void_zero_node;
12703
12704         return stmt_expr;
12705       }
12706
12707     case CONST_DECL:
12708       t = tsubst_copy (t, args, complain, in_decl);
12709       /* As in finish_id_expression, we resolve enumeration constants
12710          to their underlying values.  */
12711       if (TREE_CODE (t) == CONST_DECL)
12712         {
12713           used_types_insert (TREE_TYPE (t));
12714           return DECL_INITIAL (t);
12715         }
12716       return t;
12717
12718     case LAMBDA_EXPR:
12719       {
12720         tree r = build_lambda_expr ();
12721
12722         tree type = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
12723         TREE_TYPE (r) = type;
12724         CLASSTYPE_LAMBDA_EXPR (type) = r;
12725
12726         LAMBDA_EXPR_LOCATION (r)
12727           = LAMBDA_EXPR_LOCATION (t);
12728         LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
12729           = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
12730         LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
12731         LAMBDA_EXPR_DISCRIMINATOR (r)
12732           = (LAMBDA_EXPR_DISCRIMINATOR (t));
12733         LAMBDA_EXPR_CAPTURE_LIST (r)
12734           = RECUR (LAMBDA_EXPR_CAPTURE_LIST (t));
12735         LAMBDA_EXPR_THIS_CAPTURE (r)
12736           = RECUR (LAMBDA_EXPR_THIS_CAPTURE (t));
12737         LAMBDA_EXPR_EXTRA_SCOPE (r)
12738           = RECUR (LAMBDA_EXPR_EXTRA_SCOPE (t));
12739
12740         /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
12741         determine_visibility (TYPE_NAME (type));
12742         /* Now that we know visibility, instantiate the type so we have a
12743            declaration of the op() for later calls to lambda_function.  */
12744         complete_type (type);
12745
12746         type = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
12747         if (type)
12748           apply_lambda_return_type (r, type);
12749
12750         return build_lambda_object (r);
12751       }
12752
12753     default:
12754       /* Handle Objective-C++ constructs, if appropriate.  */
12755       {
12756         tree subst
12757           = objcp_tsubst_copy_and_build (t, args, complain,
12758                                          in_decl, /*function_p=*/false);
12759         if (subst)
12760           return subst;
12761       }
12762       return tsubst_copy (t, args, complain, in_decl);
12763     }
12764
12765 #undef RECUR
12766 }
12767
12768 /* Verify that the instantiated ARGS are valid. For type arguments,
12769    make sure that the type's linkage is ok. For non-type arguments,
12770    make sure they are constants if they are integral or enumerations.
12771    Emit an error under control of COMPLAIN, and return TRUE on error.  */
12772
12773 static bool
12774 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
12775 {
12776   if (ARGUMENT_PACK_P (t))
12777     {
12778       tree vec = ARGUMENT_PACK_ARGS (t);
12779       int len = TREE_VEC_LENGTH (vec);
12780       bool result = false;
12781       int i;
12782
12783       for (i = 0; i < len; ++i)
12784         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
12785           result = true;
12786       return result;
12787     }
12788   else if (TYPE_P (t))
12789     {
12790       /* [basic.link]: A name with no linkage (notably, the name
12791          of a class or enumeration declared in a local scope)
12792          shall not be used to declare an entity with linkage.
12793          This implies that names with no linkage cannot be used as
12794          template arguments
12795
12796          DR 757 relaxes this restriction for C++0x.  */
12797       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
12798                  : no_linkage_check (t, /*relaxed_p=*/false));
12799
12800       if (nt)
12801         {
12802           /* DR 488 makes use of a type with no linkage cause
12803              type deduction to fail.  */
12804           if (complain & tf_error)
12805             {
12806               if (TYPE_ANONYMOUS_P (nt))
12807                 error ("%qT is/uses anonymous type", t);
12808               else
12809                 error ("template argument for %qD uses local type %qT",
12810                        tmpl, t);
12811             }
12812           return true;
12813         }
12814       /* In order to avoid all sorts of complications, we do not
12815          allow variably-modified types as template arguments.  */
12816       else if (variably_modified_type_p (t, NULL_TREE))
12817         {
12818           if (complain & tf_error)
12819             error ("%qT is a variably modified type", t);
12820           return true;
12821         }
12822     }
12823   /* A non-type argument of integral or enumerated type must be a
12824      constant.  */
12825   else if (TREE_TYPE (t)
12826            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
12827            && !TREE_CONSTANT (t))
12828     {
12829       if (complain & tf_error)
12830         error ("integral expression %qE is not constant", t);
12831       return true;
12832     }
12833   return false;
12834 }
12835
12836 static bool
12837 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
12838 {
12839   int ix, len = DECL_NTPARMS (tmpl);
12840   bool result = false;
12841
12842   for (ix = 0; ix != len; ix++)
12843     {
12844       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
12845         result = true;
12846     }
12847   if (result && (complain & tf_error))
12848     error ("  trying to instantiate %qD", tmpl);
12849   return result;
12850 }
12851
12852 /* Instantiate the indicated variable or function template TMPL with
12853    the template arguments in TARG_PTR.  */
12854
12855 tree
12856 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
12857 {
12858   tree targ_ptr = orig_args;
12859   tree fndecl;
12860   tree gen_tmpl;
12861   tree spec;
12862   HOST_WIDE_INT saved_processing_template_decl;
12863
12864   if (tmpl == error_mark_node)
12865     return error_mark_node;
12866
12867   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
12868
12869   /* If this function is a clone, handle it specially.  */
12870   if (DECL_CLONED_FUNCTION_P (tmpl))
12871     {
12872       tree spec;
12873       tree clone;
12874
12875       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
12876          DECL_CLONED_FUNCTION.  */
12877       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
12878                                    targ_ptr, complain);
12879       if (spec == error_mark_node)
12880         return error_mark_node;
12881
12882       /* Look for the clone.  */
12883       FOR_EACH_CLONE (clone, spec)
12884         if (DECL_NAME (clone) == DECL_NAME (tmpl))
12885           return clone;
12886       /* We should always have found the clone by now.  */
12887       gcc_unreachable ();
12888       return NULL_TREE;
12889     }
12890
12891   /* Check to see if we already have this specialization.  */
12892   gen_tmpl = most_general_template (tmpl);
12893   if (tmpl != gen_tmpl)
12894     /* The TMPL is a partial instantiation.  To get a full set of
12895        arguments we must add the arguments used to perform the
12896        partial instantiation.  */
12897     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
12898                                             targ_ptr);
12899
12900   /* It would be nice to avoid hashing here and then again in tsubst_decl,
12901      but it doesn't seem to be on the hot path.  */
12902   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
12903
12904   gcc_assert (tmpl == gen_tmpl
12905               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
12906                   == spec)
12907               || fndecl == NULL_TREE);
12908
12909   if (spec != NULL_TREE)
12910     return spec;
12911
12912   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
12913                                complain))
12914     return error_mark_node;
12915
12916   /* We are building a FUNCTION_DECL, during which the access of its
12917      parameters and return types have to be checked.  However this
12918      FUNCTION_DECL which is the desired context for access checking
12919      is not built yet.  We solve this chicken-and-egg problem by
12920      deferring all checks until we have the FUNCTION_DECL.  */
12921   push_deferring_access_checks (dk_deferred);
12922
12923   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
12924      (because, for example, we have encountered a non-dependent
12925      function call in the body of a template function and must now
12926      determine which of several overloaded functions will be called),
12927      within the instantiation itself we are not processing a
12928      template.  */  
12929   saved_processing_template_decl = processing_template_decl;
12930   processing_template_decl = 0;
12931   /* Substitute template parameters to obtain the specialization.  */
12932   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
12933                    targ_ptr, complain, gen_tmpl);
12934   processing_template_decl = saved_processing_template_decl;
12935   if (fndecl == error_mark_node)
12936     return error_mark_node;
12937
12938   /* Now we know the specialization, compute access previously
12939      deferred.  */
12940   push_access_scope (fndecl);
12941
12942   /* Some typedefs referenced from within the template code need to be access
12943      checked at template instantiation time, i.e now. These types were
12944      added to the template at parsing time. Let's get those and perfom
12945      the acces checks then.  */
12946   perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
12947   perform_deferred_access_checks ();
12948   pop_access_scope (fndecl);
12949   pop_deferring_access_checks ();
12950
12951   /* The DECL_TI_TEMPLATE should always be the immediate parent
12952      template, not the most general template.  */
12953   DECL_TI_TEMPLATE (fndecl) = tmpl;
12954
12955   /* If we've just instantiated the main entry point for a function,
12956      instantiate all the alternate entry points as well.  We do this
12957      by cloning the instantiation of the main entry point, not by
12958      instantiating the template clones.  */
12959   if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
12960     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
12961
12962   return fndecl;
12963 }
12964
12965 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
12966    NARGS elements of the arguments that are being used when calling
12967    it.  TARGS is a vector into which the deduced template arguments
12968    are placed.
12969
12970    Return zero for success, 2 for an incomplete match that doesn't resolve
12971    all the types, and 1 for complete failure.  An error message will be
12972    printed only for an incomplete match.
12973
12974    If FN is a conversion operator, or we are trying to produce a specific
12975    specialization, RETURN_TYPE is the return type desired.
12976
12977    The EXPLICIT_TARGS are explicit template arguments provided via a
12978    template-id.
12979
12980    The parameter STRICT is one of:
12981
12982    DEDUCE_CALL:
12983      We are deducing arguments for a function call, as in
12984      [temp.deduct.call].
12985
12986    DEDUCE_CONV:
12987      We are deducing arguments for a conversion function, as in
12988      [temp.deduct.conv].
12989
12990    DEDUCE_EXACT:
12991      We are deducing arguments when doing an explicit instantiation
12992      as in [temp.explicit], when determining an explicit specialization
12993      as in [temp.expl.spec], or when taking the address of a function
12994      template, as in [temp.deduct.funcaddr].  */
12995
12996 int
12997 fn_type_unification (tree fn,
12998                      tree explicit_targs,
12999                      tree targs,
13000                      const tree *args,
13001                      unsigned int nargs,
13002                      tree return_type,
13003                      unification_kind_t strict,
13004                      int flags)
13005 {
13006   tree parms;
13007   tree fntype;
13008   int result;
13009   bool incomplete_argument_packs_p = false;
13010
13011   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
13012
13013   fntype = TREE_TYPE (fn);
13014   if (explicit_targs)
13015     {
13016       /* [temp.deduct]
13017
13018          The specified template arguments must match the template
13019          parameters in kind (i.e., type, nontype, template), and there
13020          must not be more arguments than there are parameters;
13021          otherwise type deduction fails.
13022
13023          Nontype arguments must match the types of the corresponding
13024          nontype template parameters, or must be convertible to the
13025          types of the corresponding nontype parameters as specified in
13026          _temp.arg.nontype_, otherwise type deduction fails.
13027
13028          All references in the function type of the function template
13029          to the corresponding template parameters are replaced by the
13030          specified template argument values.  If a substitution in a
13031          template parameter or in the function type of the function
13032          template results in an invalid type, type deduction fails.  */
13033       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
13034       int i, len = TREE_VEC_LENGTH (tparms);
13035       tree converted_args;
13036       bool incomplete = false;
13037
13038       if (explicit_targs == error_mark_node)
13039         return 1;
13040
13041       converted_args
13042         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
13043                                   /*require_all_args=*/false,
13044                                   /*use_default_args=*/false));
13045       if (converted_args == error_mark_node)
13046         return 1;
13047
13048       /* Substitute the explicit args into the function type.  This is
13049          necessary so that, for instance, explicitly declared function
13050          arguments can match null pointed constants.  If we were given
13051          an incomplete set of explicit args, we must not do semantic
13052          processing during substitution as we could create partial
13053          instantiations.  */
13054       for (i = 0; i < len; i++)
13055         {
13056           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13057           bool parameter_pack = false;
13058
13059           /* Dig out the actual parm.  */
13060           if (TREE_CODE (parm) == TYPE_DECL
13061               || TREE_CODE (parm) == TEMPLATE_DECL)
13062             {
13063               parm = TREE_TYPE (parm);
13064               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
13065             }
13066           else if (TREE_CODE (parm) == PARM_DECL)
13067             {
13068               parm = DECL_INITIAL (parm);
13069               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
13070             }
13071
13072           if (parameter_pack)
13073             {
13074               int level, idx;
13075               tree targ;
13076               template_parm_level_and_index (parm, &level, &idx);
13077
13078               /* Mark the argument pack as "incomplete". We could
13079                  still deduce more arguments during unification.  */
13080               targ = TMPL_ARG (converted_args, level, idx);
13081               if (targ)
13082                 {
13083                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
13084                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
13085                     = ARGUMENT_PACK_ARGS (targ);
13086                 }
13087
13088               /* We have some incomplete argument packs.  */
13089               incomplete_argument_packs_p = true;
13090             }
13091         }
13092
13093       if (incomplete_argument_packs_p)
13094         /* Any substitution is guaranteed to be incomplete if there
13095            are incomplete argument packs, because we can still deduce
13096            more arguments.  */
13097         incomplete = 1;
13098       else
13099         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
13100
13101       processing_template_decl += incomplete;
13102       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
13103       processing_template_decl -= incomplete;
13104
13105       if (fntype == error_mark_node)
13106         return 1;
13107
13108       /* Place the explicitly specified arguments in TARGS.  */
13109       for (i = NUM_TMPL_ARGS (converted_args); i--;)
13110         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
13111     }
13112
13113   /* Never do unification on the 'this' parameter.  */
13114   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
13115
13116   if (return_type)
13117     {
13118       tree *new_args;
13119
13120       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
13121       new_args = XALLOCAVEC (tree, nargs + 1);
13122       new_args[0] = return_type;
13123       memcpy (new_args + 1, args, nargs * sizeof (tree));
13124       args = new_args;
13125       ++nargs;
13126     }
13127
13128   /* We allow incomplete unification without an error message here
13129      because the standard doesn't seem to explicitly prohibit it.  Our
13130      callers must be ready to deal with unification failures in any
13131      event.  */
13132   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
13133                                   targs, parms, args, nargs, /*subr=*/0,
13134                                   strict, flags);
13135
13136   if (result == 0 && incomplete_argument_packs_p)
13137     {
13138       int i, len = NUM_TMPL_ARGS (targs);
13139
13140       /* Clear the "incomplete" flags on all argument packs.  */
13141       for (i = 0; i < len; i++)
13142         {
13143           tree arg = TREE_VEC_ELT (targs, i);
13144           if (ARGUMENT_PACK_P (arg))
13145             {
13146               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
13147               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
13148             }
13149         }
13150     }
13151
13152   /* Now that we have bindings for all of the template arguments,
13153      ensure that the arguments deduced for the template template
13154      parameters have compatible template parameter lists.  We cannot
13155      check this property before we have deduced all template
13156      arguments, because the template parameter types of a template
13157      template parameter might depend on prior template parameters
13158      deduced after the template template parameter.  The following
13159      ill-formed example illustrates this issue:
13160
13161        template<typename T, template<T> class C> void f(C<5>, T);
13162
13163        template<int N> struct X {};
13164
13165        void g() {
13166          f(X<5>(), 5l); // error: template argument deduction fails
13167        }
13168
13169      The template parameter list of 'C' depends on the template type
13170      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
13171      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
13172      time that we deduce 'C'.  */
13173   if (result == 0
13174       && !template_template_parm_bindings_ok_p 
13175            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
13176     return 1;
13177
13178   if (result == 0)
13179     /* All is well so far.  Now, check:
13180
13181        [temp.deduct]
13182
13183        When all template arguments have been deduced, all uses of
13184        template parameters in nondeduced contexts are replaced with
13185        the corresponding deduced argument values.  If the
13186        substitution results in an invalid type, as described above,
13187        type deduction fails.  */
13188     {
13189       tree substed = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
13190       if (substed == error_mark_node)
13191         return 1;
13192
13193       /* If we're looking for an exact match, check that what we got
13194          is indeed an exact match.  It might not be if some template
13195          parameters are used in non-deduced contexts.  */
13196       if (strict == DEDUCE_EXACT)
13197         {
13198           unsigned int i;
13199
13200           tree sarg
13201             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
13202           if (return_type)
13203             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
13204           for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
13205             if (!same_type_p (args[i], TREE_VALUE (sarg)))
13206               return 1;
13207         }
13208     }
13209
13210   return result;
13211 }
13212
13213 /* Adjust types before performing type deduction, as described in
13214    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
13215    sections are symmetric.  PARM is the type of a function parameter
13216    or the return type of the conversion function.  ARG is the type of
13217    the argument passed to the call, or the type of the value
13218    initialized with the result of the conversion function.
13219    ARG_EXPR is the original argument expression, which may be null.  */
13220
13221 static int
13222 maybe_adjust_types_for_deduction (unification_kind_t strict,
13223                                   tree* parm,
13224                                   tree* arg,
13225                                   tree arg_expr)
13226 {
13227   int result = 0;
13228
13229   switch (strict)
13230     {
13231     case DEDUCE_CALL:
13232       break;
13233
13234     case DEDUCE_CONV:
13235       {
13236         /* Swap PARM and ARG throughout the remainder of this
13237            function; the handling is precisely symmetric since PARM
13238            will initialize ARG rather than vice versa.  */
13239         tree* temp = parm;
13240         parm = arg;
13241         arg = temp;
13242         break;
13243       }
13244
13245     case DEDUCE_EXACT:
13246       /* Core issue #873: Do the DR606 thing (see below) for these cases,
13247          too, but here handle it by stripping the reference from PARM
13248          rather than by adding it to ARG.  */
13249       if (TREE_CODE (*parm) == REFERENCE_TYPE
13250           && TYPE_REF_IS_RVALUE (*parm)
13251           && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13252           && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13253           && TREE_CODE (*arg) == REFERENCE_TYPE
13254           && !TYPE_REF_IS_RVALUE (*arg))
13255         *parm = TREE_TYPE (*parm);
13256       /* Nothing else to do in this case.  */
13257       return 0;
13258
13259     default:
13260       gcc_unreachable ();
13261     }
13262
13263   if (TREE_CODE (*parm) != REFERENCE_TYPE)
13264     {
13265       /* [temp.deduct.call]
13266
13267          If P is not a reference type:
13268
13269          --If A is an array type, the pointer type produced by the
13270          array-to-pointer standard conversion (_conv.array_) is
13271          used in place of A for type deduction; otherwise,
13272
13273          --If A is a function type, the pointer type produced by
13274          the function-to-pointer standard conversion
13275          (_conv.func_) is used in place of A for type deduction;
13276          otherwise,
13277
13278          --If A is a cv-qualified type, the top level
13279          cv-qualifiers of A's type are ignored for type
13280          deduction.  */
13281       if (TREE_CODE (*arg) == ARRAY_TYPE)
13282         *arg = build_pointer_type (TREE_TYPE (*arg));
13283       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
13284         *arg = build_pointer_type (*arg);
13285       else
13286         *arg = TYPE_MAIN_VARIANT (*arg);
13287     }
13288
13289   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
13290      of the form T&&, where T is a template parameter, and the argument
13291      is an lvalue, T is deduced as A& */
13292   if (TREE_CODE (*parm) == REFERENCE_TYPE
13293       && TYPE_REF_IS_RVALUE (*parm)
13294       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13295       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13296       && arg_expr && real_lvalue_p (arg_expr))
13297     *arg = build_reference_type (*arg);
13298
13299   /* [temp.deduct.call]
13300
13301      If P is a cv-qualified type, the top level cv-qualifiers
13302      of P's type are ignored for type deduction.  If P is a
13303      reference type, the type referred to by P is used for
13304      type deduction.  */
13305   *parm = TYPE_MAIN_VARIANT (*parm);
13306   if (TREE_CODE (*parm) == REFERENCE_TYPE)
13307     {
13308       *parm = TREE_TYPE (*parm);
13309       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
13310     }
13311
13312   /* DR 322. For conversion deduction, remove a reference type on parm
13313      too (which has been swapped into ARG).  */
13314   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
13315     *arg = TREE_TYPE (*arg);
13316
13317   return result;
13318 }
13319
13320 /* Most parms like fn_type_unification.
13321
13322    If SUBR is 1, we're being called recursively (to unify the
13323    arguments of a function or method parameter of a function
13324    template). */
13325
13326 static int
13327 type_unification_real (tree tparms,
13328                        tree targs,
13329                        tree xparms,
13330                        const tree *xargs,
13331                        unsigned int xnargs,
13332                        int subr,
13333                        unification_kind_t strict,
13334                        int flags)
13335 {
13336   tree parm, arg, arg_expr;
13337   int i;
13338   int ntparms = TREE_VEC_LENGTH (tparms);
13339   int sub_strict;
13340   int saw_undeduced = 0;
13341   tree parms;
13342   const tree *args;
13343   unsigned int nargs;
13344   unsigned int ia;
13345
13346   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
13347   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
13348   gcc_assert (ntparms > 0);
13349
13350   /* Reset the number of non-defaulted template arguments contained
13351      in in TARGS.  */
13352   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
13353
13354   switch (strict)
13355     {
13356     case DEDUCE_CALL:
13357       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
13358                     | UNIFY_ALLOW_DERIVED);
13359       break;
13360
13361     case DEDUCE_CONV:
13362       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
13363       break;
13364
13365     case DEDUCE_EXACT:
13366       sub_strict = UNIFY_ALLOW_NONE;
13367       break;
13368
13369     default:
13370       gcc_unreachable ();
13371     }
13372
13373  again:
13374   parms = xparms;
13375   args = xargs;
13376   nargs = xnargs;
13377
13378   ia = 0;
13379   while (parms && parms != void_list_node
13380          && ia < nargs)
13381     {
13382       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13383         break;
13384
13385       parm = TREE_VALUE (parms);
13386       parms = TREE_CHAIN (parms);
13387       arg = args[ia];
13388       ++ia;
13389       arg_expr = NULL;
13390
13391       if (arg == error_mark_node)
13392         return 1;
13393       if (arg == unknown_type_node)
13394         /* We can't deduce anything from this, but we might get all the
13395            template args from other function args.  */
13396         continue;
13397
13398       /* Conversions will be performed on a function argument that
13399          corresponds with a function parameter that contains only
13400          non-deducible template parameters and explicitly specified
13401          template parameters.  */
13402       if (!uses_template_parms (parm))
13403         {
13404           tree type;
13405
13406           if (!TYPE_P (arg))
13407             type = TREE_TYPE (arg);
13408           else
13409             type = arg;
13410
13411           if (same_type_p (parm, type))
13412             continue;
13413           if (strict != DEDUCE_EXACT
13414               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
13415                                   flags))
13416             continue;
13417
13418           return 1;
13419         }
13420
13421       if (!TYPE_P (arg))
13422         {
13423           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
13424           if (type_unknown_p (arg))
13425             {
13426               /* [temp.deduct.type] 
13427
13428                  A template-argument can be deduced from a pointer to
13429                  function or pointer to member function argument if
13430                  the set of overloaded functions does not contain
13431                  function templates and at most one of a set of
13432                  overloaded functions provides a unique match.  */
13433               if (resolve_overloaded_unification
13434                   (tparms, targs, parm, arg, strict, sub_strict))
13435                 continue;
13436
13437               return 1;
13438             }
13439           arg_expr = arg;
13440           arg = unlowered_expr_type (arg);
13441           if (arg == error_mark_node)
13442             return 1;
13443         }
13444
13445       {
13446         int arg_strict = sub_strict;
13447
13448         if (!subr)
13449           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
13450                                                           arg_expr);
13451
13452         if (arg == init_list_type_node && arg_expr)
13453           arg = arg_expr;
13454         if (unify (tparms, targs, parm, arg, arg_strict))
13455           return 1;
13456       }
13457     }
13458
13459
13460   if (parms 
13461       && parms != void_list_node
13462       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13463     {
13464       /* Unify the remaining arguments with the pack expansion type.  */
13465       tree argvec;
13466       tree parmvec = make_tree_vec (1);
13467
13468       /* Allocate a TREE_VEC and copy in all of the arguments */ 
13469       argvec = make_tree_vec (nargs - ia);
13470       for (i = 0; ia < nargs; ++ia, ++i)
13471         TREE_VEC_ELT (argvec, i) = args[ia];
13472
13473       /* Copy the parameter into parmvec.  */
13474       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
13475       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
13476                                 /*call_args_p=*/true, /*subr=*/subr))
13477         return 1;
13478
13479       /* Advance to the end of the list of parameters.  */
13480       parms = TREE_CHAIN (parms);
13481     }
13482
13483   /* Fail if we've reached the end of the parm list, and more args
13484      are present, and the parm list isn't variadic.  */
13485   if (ia < nargs && parms == void_list_node)
13486     return 1;
13487   /* Fail if parms are left and they don't have default values.  */
13488   if (parms && parms != void_list_node
13489       && TREE_PURPOSE (parms) == NULL_TREE)
13490     return 1;
13491
13492   if (!subr)
13493     for (i = 0; i < ntparms; i++)
13494       if (!TREE_VEC_ELT (targs, i))
13495         {
13496           tree tparm;
13497
13498           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
13499             continue;
13500
13501           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13502
13503           /* If this is an undeduced nontype parameter that depends on
13504              a type parameter, try another pass; its type may have been
13505              deduced from a later argument than the one from which
13506              this parameter can be deduced.  */
13507           if (TREE_CODE (tparm) == PARM_DECL
13508               && uses_template_parms (TREE_TYPE (tparm))
13509               && !saw_undeduced++)
13510             goto again;
13511
13512           /* Core issue #226 (C++0x) [temp.deduct]:
13513
13514                If a template argument has not been deduced, its
13515                default template argument, if any, is used. 
13516
13517              When we are in C++98 mode, TREE_PURPOSE will either
13518              be NULL_TREE or ERROR_MARK_NODE, so we do not need
13519              to explicitly check cxx_dialect here.  */
13520           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
13521             {
13522               tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13523               tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
13524               arg = tsubst_template_arg (arg, targs, tf_none, NULL_TREE);
13525               arg = convert_template_argument (parm, arg, targs, tf_none,
13526                                                i, NULL_TREE);
13527               if (arg == error_mark_node)
13528                 return 1;
13529               else
13530                 {
13531                   TREE_VEC_ELT (targs, i) = arg;
13532                   /* The position of the first default template argument,
13533                      is also the number of non-defaulted arguments in TARGS.
13534                      Record that.  */
13535                   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
13536                     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
13537                   continue;
13538                 }
13539             }
13540
13541           /* If the type parameter is a parameter pack, then it will
13542              be deduced to an empty parameter pack.  */
13543           if (template_parameter_pack_p (tparm))
13544             {
13545               tree arg;
13546
13547               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
13548                 {
13549                   arg = make_node (NONTYPE_ARGUMENT_PACK);
13550                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
13551                   TREE_CONSTANT (arg) = 1;
13552                 }
13553               else
13554                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
13555
13556               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
13557
13558               TREE_VEC_ELT (targs, i) = arg;
13559               continue;
13560             }
13561
13562           return 2;
13563         }
13564 #ifdef ENABLE_CHECKING
13565   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
13566     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
13567 #endif
13568
13569   return 0;
13570 }
13571
13572 /* Subroutine of type_unification_real.  Args are like the variables
13573    at the call site.  ARG is an overloaded function (or template-id);
13574    we try deducing template args from each of the overloads, and if
13575    only one succeeds, we go with that.  Modifies TARGS and returns
13576    true on success.  */
13577
13578 static bool
13579 resolve_overloaded_unification (tree tparms,
13580                                 tree targs,
13581                                 tree parm,
13582                                 tree arg,
13583                                 unification_kind_t strict,
13584                                 int sub_strict)
13585 {
13586   tree tempargs = copy_node (targs);
13587   int good = 0;
13588   tree goodfn = NULL_TREE;
13589   bool addr_p;
13590
13591   if (TREE_CODE (arg) == ADDR_EXPR)
13592     {
13593       arg = TREE_OPERAND (arg, 0);
13594       addr_p = true;
13595     }
13596   else
13597     addr_p = false;
13598
13599   if (TREE_CODE (arg) == COMPONENT_REF)
13600     /* Handle `&x' where `x' is some static or non-static member
13601        function name.  */
13602     arg = TREE_OPERAND (arg, 1);
13603
13604   if (TREE_CODE (arg) == OFFSET_REF)
13605     arg = TREE_OPERAND (arg, 1);
13606
13607   /* Strip baselink information.  */
13608   if (BASELINK_P (arg))
13609     arg = BASELINK_FUNCTIONS (arg);
13610
13611   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
13612     {
13613       /* If we got some explicit template args, we need to plug them into
13614          the affected templates before we try to unify, in case the
13615          explicit args will completely resolve the templates in question.  */
13616
13617       tree expl_subargs = TREE_OPERAND (arg, 1);
13618       arg = TREE_OPERAND (arg, 0);
13619
13620       for (; arg; arg = OVL_NEXT (arg))
13621         {
13622           tree fn = OVL_CURRENT (arg);
13623           tree subargs, elem;
13624
13625           if (TREE_CODE (fn) != TEMPLATE_DECL)
13626             continue;
13627
13628           ++processing_template_decl;
13629           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13630                                   expl_subargs, /*check_ret=*/false);
13631           if (subargs)
13632             {
13633               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
13634               if (try_one_overload (tparms, targs, tempargs, parm,
13635                                     elem, strict, sub_strict, addr_p)
13636                   && (!goodfn || !decls_match (goodfn, elem)))
13637                 {
13638                   goodfn = elem;
13639                   ++good;
13640                 }
13641             }
13642           --processing_template_decl;
13643         }
13644     }
13645   else if (TREE_CODE (arg) != OVERLOAD
13646            && TREE_CODE (arg) != FUNCTION_DECL)
13647     /* If ARG is, for example, "(0, &f)" then its type will be unknown
13648        -- but the deduction does not succeed because the expression is
13649        not just the function on its own.  */
13650     return false;
13651   else
13652     for (; arg; arg = OVL_NEXT (arg))
13653       if (try_one_overload (tparms, targs, tempargs, parm,
13654                             TREE_TYPE (OVL_CURRENT (arg)),
13655                             strict, sub_strict, addr_p)
13656           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
13657         {
13658           goodfn = OVL_CURRENT (arg);
13659           ++good;
13660         }
13661
13662   /* [temp.deduct.type] A template-argument can be deduced from a pointer
13663      to function or pointer to member function argument if the set of
13664      overloaded functions does not contain function templates and at most
13665      one of a set of overloaded functions provides a unique match.
13666
13667      So if we found multiple possibilities, we return success but don't
13668      deduce anything.  */
13669
13670   if (good == 1)
13671     {
13672       int i = TREE_VEC_LENGTH (targs);
13673       for (; i--; )
13674         if (TREE_VEC_ELT (tempargs, i))
13675           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
13676     }
13677   if (good)
13678     return true;
13679
13680   return false;
13681 }
13682
13683 /* Core DR 115: In contexts where deduction is done and fails, or in
13684    contexts where deduction is not done, if a template argument list is
13685    specified and it, along with any default template arguments, identifies
13686    a single function template specialization, then the template-id is an
13687    lvalue for the function template specialization.  */
13688
13689 tree
13690 resolve_nondeduced_context (tree orig_expr)
13691 {
13692   tree expr, offset, baselink;
13693   bool addr;
13694
13695   if (!type_unknown_p (orig_expr))
13696     return orig_expr;
13697
13698   expr = orig_expr;
13699   addr = false;
13700   offset = NULL_TREE;
13701   baselink = NULL_TREE;
13702
13703   if (TREE_CODE (expr) == ADDR_EXPR)
13704     {
13705       expr = TREE_OPERAND (expr, 0);
13706       addr = true;
13707     }
13708   if (TREE_CODE (expr) == OFFSET_REF)
13709     {
13710       offset = expr;
13711       expr = TREE_OPERAND (expr, 1);
13712     }
13713   if (TREE_CODE (expr) == BASELINK)
13714     {
13715       baselink = expr;
13716       expr = BASELINK_FUNCTIONS (expr);
13717     }
13718
13719   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
13720     {
13721       int good = 0;
13722       tree goodfn = NULL_TREE;
13723
13724       /* If we got some explicit template args, we need to plug them into
13725          the affected templates before we try to unify, in case the
13726          explicit args will completely resolve the templates in question.  */
13727
13728       tree expl_subargs = TREE_OPERAND (expr, 1);
13729       tree arg = TREE_OPERAND (expr, 0);
13730       tree badfn = NULL_TREE;
13731       tree badargs = NULL_TREE;
13732
13733       for (; arg; arg = OVL_NEXT (arg))
13734         {
13735           tree fn = OVL_CURRENT (arg);
13736           tree subargs, elem;
13737
13738           if (TREE_CODE (fn) != TEMPLATE_DECL)
13739             continue;
13740
13741           ++processing_template_decl;
13742           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13743                                   expl_subargs, /*check_ret=*/false);
13744           if (subargs && !any_dependent_template_arguments_p (subargs))
13745             {
13746               elem = instantiate_template (fn, subargs, tf_none);
13747               if (elem == error_mark_node)
13748                 {
13749                   badfn = fn;
13750                   badargs = subargs;
13751                 }
13752               else if (elem && (!goodfn || !decls_match (goodfn, elem)))
13753                 {
13754                   goodfn = elem;
13755                   ++good;
13756                 }
13757             }
13758           --processing_template_decl;
13759         }
13760       if (good == 1)
13761         {
13762           expr = goodfn;
13763           if (baselink)
13764             expr = build_baselink (BASELINK_BINFO (baselink),
13765                                    BASELINK_ACCESS_BINFO (baselink),
13766                                    expr, BASELINK_OPTYPE (baselink));
13767           if (offset)
13768             expr = build2 (OFFSET_REF, TREE_TYPE (expr),
13769                            TREE_OPERAND (offset, 0), expr);
13770           if (addr)
13771             expr = build_address (expr);
13772           return expr;
13773         }
13774       else if (good == 0 && badargs)
13775         /* There were no good options and at least one bad one, so let the
13776            user know what the problem is.  */
13777         instantiate_template (badfn, badargs, tf_warning_or_error);
13778     }
13779   return orig_expr;
13780 }
13781
13782 /* Subroutine of resolve_overloaded_unification; does deduction for a single
13783    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
13784    different overloads deduce different arguments for a given parm.
13785    ADDR_P is true if the expression for which deduction is being
13786    performed was of the form "& fn" rather than simply "fn".
13787
13788    Returns 1 on success.  */
13789
13790 static int
13791 try_one_overload (tree tparms,
13792                   tree orig_targs,
13793                   tree targs,
13794                   tree parm,
13795                   tree arg,
13796                   unification_kind_t strict,
13797                   int sub_strict,
13798                   bool addr_p)
13799 {
13800   int nargs;
13801   tree tempargs;
13802   int i;
13803
13804   /* [temp.deduct.type] A template-argument can be deduced from a pointer
13805      to function or pointer to member function argument if the set of
13806      overloaded functions does not contain function templates and at most
13807      one of a set of overloaded functions provides a unique match.
13808
13809      So if this is a template, just return success.  */
13810
13811   if (uses_template_parms (arg))
13812     return 1;
13813
13814   if (TREE_CODE (arg) == METHOD_TYPE)
13815     arg = build_ptrmemfunc_type (build_pointer_type (arg));
13816   else if (addr_p)
13817     arg = build_pointer_type (arg);
13818
13819   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
13820
13821   /* We don't copy orig_targs for this because if we have already deduced
13822      some template args from previous args, unify would complain when we
13823      try to deduce a template parameter for the same argument, even though
13824      there isn't really a conflict.  */
13825   nargs = TREE_VEC_LENGTH (targs);
13826   tempargs = make_tree_vec (nargs);
13827
13828   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
13829     return 0;
13830
13831   /* First make sure we didn't deduce anything that conflicts with
13832      explicitly specified args.  */
13833   for (i = nargs; i--; )
13834     {
13835       tree elt = TREE_VEC_ELT (tempargs, i);
13836       tree oldelt = TREE_VEC_ELT (orig_targs, i);
13837
13838       if (!elt)
13839         /*NOP*/;
13840       else if (uses_template_parms (elt))
13841         /* Since we're unifying against ourselves, we will fill in
13842            template args used in the function parm list with our own
13843            template parms.  Discard them.  */
13844         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
13845       else if (oldelt && !template_args_equal (oldelt, elt))
13846         return 0;
13847     }
13848
13849   for (i = nargs; i--; )
13850     {
13851       tree elt = TREE_VEC_ELT (tempargs, i);
13852
13853       if (elt)
13854         TREE_VEC_ELT (targs, i) = elt;
13855     }
13856
13857   return 1;
13858 }
13859
13860 /* PARM is a template class (perhaps with unbound template
13861    parameters).  ARG is a fully instantiated type.  If ARG can be
13862    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
13863    TARGS are as for unify.  */
13864
13865 static tree
13866 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
13867 {
13868   tree copy_of_targs;
13869
13870   if (!CLASSTYPE_TEMPLATE_INFO (arg)
13871       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
13872           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
13873     return NULL_TREE;
13874
13875   /* We need to make a new template argument vector for the call to
13876      unify.  If we used TARGS, we'd clutter it up with the result of
13877      the attempted unification, even if this class didn't work out.
13878      We also don't want to commit ourselves to all the unifications
13879      we've already done, since unification is supposed to be done on
13880      an argument-by-argument basis.  In other words, consider the
13881      following pathological case:
13882
13883        template <int I, int J, int K>
13884        struct S {};
13885
13886        template <int I, int J>
13887        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
13888
13889        template <int I, int J, int K>
13890        void f(S<I, J, K>, S<I, I, I>);
13891
13892        void g() {
13893          S<0, 0, 0> s0;
13894          S<0, 1, 2> s2;
13895
13896          f(s0, s2);
13897        }
13898
13899      Now, by the time we consider the unification involving `s2', we
13900      already know that we must have `f<0, 0, 0>'.  But, even though
13901      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
13902      because there are two ways to unify base classes of S<0, 1, 2>
13903      with S<I, I, I>.  If we kept the already deduced knowledge, we
13904      would reject the possibility I=1.  */
13905   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
13906
13907   /* If unification failed, we're done.  */
13908   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
13909              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
13910     return NULL_TREE;
13911
13912   return arg;
13913 }
13914
13915 /* Given a template type PARM and a class type ARG, find the unique
13916    base type in ARG that is an instance of PARM.  We do not examine
13917    ARG itself; only its base-classes.  If there is not exactly one
13918    appropriate base class, return NULL_TREE.  PARM may be the type of
13919    a partial specialization, as well as a plain template type.  Used
13920    by unify.  */
13921
13922 static tree
13923 get_template_base (tree tparms, tree targs, tree parm, tree arg)
13924 {
13925   tree rval = NULL_TREE;
13926   tree binfo;
13927
13928   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
13929
13930   binfo = TYPE_BINFO (complete_type (arg));
13931   if (!binfo)
13932     /* The type could not be completed.  */
13933     return NULL_TREE;
13934
13935   /* Walk in inheritance graph order.  The search order is not
13936      important, and this avoids multiple walks of virtual bases.  */
13937   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
13938     {
13939       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
13940
13941       if (r)
13942         {
13943           /* If there is more than one satisfactory baseclass, then:
13944
13945                [temp.deduct.call]
13946
13947               If they yield more than one possible deduced A, the type
13948               deduction fails.
13949
13950              applies.  */
13951           if (rval && !same_type_p (r, rval))
13952             return NULL_TREE;
13953
13954           rval = r;
13955         }
13956     }
13957
13958   return rval;
13959 }
13960
13961 /* Returns the level of DECL, which declares a template parameter.  */
13962
13963 static int
13964 template_decl_level (tree decl)
13965 {
13966   switch (TREE_CODE (decl))
13967     {
13968     case TYPE_DECL:
13969     case TEMPLATE_DECL:
13970       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
13971
13972     case PARM_DECL:
13973       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
13974
13975     default:
13976       gcc_unreachable ();
13977     }
13978   return 0;
13979 }
13980
13981 /* Decide whether ARG can be unified with PARM, considering only the
13982    cv-qualifiers of each type, given STRICT as documented for unify.
13983    Returns nonzero iff the unification is OK on that basis.  */
13984
13985 static int
13986 check_cv_quals_for_unify (int strict, tree arg, tree parm)
13987 {
13988   int arg_quals = cp_type_quals (arg);
13989   int parm_quals = cp_type_quals (parm);
13990
13991   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
13992       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
13993     {
13994       /*  Although a CVR qualifier is ignored when being applied to a
13995           substituted template parameter ([8.3.2]/1 for example), that
13996           does not apply during deduction [14.8.2.4]/1, (even though
13997           that is not explicitly mentioned, [14.8.2.4]/9 indicates
13998           this).  Except when we're allowing additional CV qualifiers
13999           at the outer level [14.8.2.1]/3,1st bullet.  */
14000       if ((TREE_CODE (arg) == REFERENCE_TYPE
14001            || TREE_CODE (arg) == FUNCTION_TYPE
14002            || TREE_CODE (arg) == METHOD_TYPE)
14003           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
14004         return 0;
14005
14006       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
14007           && (parm_quals & TYPE_QUAL_RESTRICT))
14008         return 0;
14009     }
14010
14011   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
14012       && (arg_quals & parm_quals) != parm_quals)
14013     return 0;
14014
14015   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
14016       && (parm_quals & arg_quals) != arg_quals)
14017     return 0;
14018
14019   return 1;
14020 }
14021
14022 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
14023 void 
14024 template_parm_level_and_index (tree parm, int* level, int* index)
14025 {
14026   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14027       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14028       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14029     {
14030       *index = TEMPLATE_TYPE_IDX (parm);
14031       *level = TEMPLATE_TYPE_LEVEL (parm);
14032     }
14033   else
14034     {
14035       *index = TEMPLATE_PARM_IDX (parm);
14036       *level = TEMPLATE_PARM_LEVEL (parm);
14037     }
14038 }
14039
14040 /* Unifies the remaining arguments in PACKED_ARGS with the pack
14041    expansion at the end of PACKED_PARMS. Returns 0 if the type
14042    deduction succeeds, 1 otherwise. STRICT is the same as in
14043    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
14044    call argument list. We'll need to adjust the arguments to make them
14045    types. SUBR tells us if this is from a recursive call to
14046    type_unification_real.  */
14047 int
14048 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
14049                       tree packed_args, int strict, bool call_args_p,
14050                       bool subr)
14051 {
14052   tree parm 
14053     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
14054   tree pattern = PACK_EXPANSION_PATTERN (parm);
14055   tree pack, packs = NULL_TREE;
14056   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
14057   int len = TREE_VEC_LENGTH (packed_args);
14058
14059   /* Determine the parameter packs we will be deducing from the
14060      pattern, and record their current deductions.  */
14061   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
14062        pack; pack = TREE_CHAIN (pack))
14063     {
14064       tree parm_pack = TREE_VALUE (pack);
14065       int idx, level;
14066
14067       /* Determine the index and level of this parameter pack.  */
14068       template_parm_level_and_index (parm_pack, &level, &idx);
14069
14070       /* Keep track of the parameter packs and their corresponding
14071          argument packs.  */
14072       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
14073       TREE_TYPE (packs) = make_tree_vec (len - start);
14074     }
14075   
14076   /* Loop through all of the arguments that have not yet been
14077      unified and unify each with the pattern.  */
14078   for (i = start; i < len; i++)
14079     {
14080       tree parm = pattern;
14081
14082       /* For each parameter pack, clear out the deduced value so that
14083          we can deduce it again.  */
14084       for (pack = packs; pack; pack = TREE_CHAIN (pack))
14085         {
14086           int idx, level;
14087           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14088
14089           TMPL_ARG (targs, level, idx) = NULL_TREE;
14090         }
14091
14092       /* Unify the pattern with the current argument.  */
14093       {
14094         tree arg = TREE_VEC_ELT (packed_args, i);
14095         tree arg_expr = NULL_TREE;
14096         int arg_strict = strict;
14097         bool skip_arg_p = false;
14098
14099         if (call_args_p)
14100           {
14101             int sub_strict;
14102
14103             /* This mirrors what we do in type_unification_real.  */
14104             switch (strict)
14105               {
14106               case DEDUCE_CALL:
14107                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
14108                               | UNIFY_ALLOW_MORE_CV_QUAL
14109                               | UNIFY_ALLOW_DERIVED);
14110                 break;
14111                 
14112               case DEDUCE_CONV:
14113                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
14114                 break;
14115                 
14116               case DEDUCE_EXACT:
14117                 sub_strict = UNIFY_ALLOW_NONE;
14118                 break;
14119                 
14120               default:
14121                 gcc_unreachable ();
14122               }
14123
14124             if (!TYPE_P (arg))
14125               {
14126                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
14127                 if (type_unknown_p (arg))
14128                   {
14129                     /* [temp.deduct.type] A template-argument can be
14130                        deduced from a pointer to function or pointer
14131                        to member function argument if the set of
14132                        overloaded functions does not contain function
14133                        templates and at most one of a set of
14134                        overloaded functions provides a unique
14135                        match.  */
14136
14137                     if (resolve_overloaded_unification
14138                         (tparms, targs, parm, arg,
14139                          (unification_kind_t) strict,
14140                          sub_strict)
14141                         != 0)
14142                       return 1;
14143                     skip_arg_p = true;
14144                   }
14145
14146                 if (!skip_arg_p)
14147                   {
14148                     arg_expr = arg;
14149                     arg = unlowered_expr_type (arg);
14150                     if (arg == error_mark_node)
14151                       return 1;
14152                   }
14153               }
14154       
14155             arg_strict = sub_strict;
14156
14157             if (!subr)
14158               arg_strict |= 
14159                 maybe_adjust_types_for_deduction ((unification_kind_t) strict,
14160                                                   &parm, &arg, arg_expr);
14161           }
14162
14163         if (!skip_arg_p)
14164           {
14165             /* For deduction from an init-list we need the actual list.  */
14166             if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
14167               arg = arg_expr;
14168             if (unify (tparms, targs, parm, arg, arg_strict))
14169               return 1;
14170           }
14171       }
14172
14173       /* For each parameter pack, collect the deduced value.  */
14174       for (pack = packs; pack; pack = TREE_CHAIN (pack))
14175         {
14176           int idx, level;
14177           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14178
14179           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
14180             TMPL_ARG (targs, level, idx);
14181         }
14182     }
14183
14184   /* Verify that the results of unification with the parameter packs
14185      produce results consistent with what we've seen before, and make
14186      the deduced argument packs available.  */
14187   for (pack = packs; pack; pack = TREE_CHAIN (pack))
14188     {
14189       tree old_pack = TREE_VALUE (pack);
14190       tree new_args = TREE_TYPE (pack);
14191       int i, len = TREE_VEC_LENGTH (new_args);
14192       int idx, level;
14193       bool nondeduced_p = false;
14194
14195       /* By default keep the original deduced argument pack.
14196          If necessary, more specific code is going to update the
14197          resulting deduced argument later down in this function.  */
14198       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14199       TMPL_ARG (targs, level, idx) = old_pack;
14200
14201       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
14202          actually deduce anything.  */
14203       for (i = 0; i < len && !nondeduced_p; ++i)
14204         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
14205           nondeduced_p = true;
14206       if (nondeduced_p)
14207         continue;
14208
14209       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
14210         {
14211           /* Prepend the explicit arguments onto NEW_ARGS.  */
14212           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14213           tree old_args = new_args;
14214           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
14215           int len = explicit_len + TREE_VEC_LENGTH (old_args);
14216
14217           /* Copy the explicit arguments.  */
14218           new_args = make_tree_vec (len);
14219           for (i = 0; i < explicit_len; i++)
14220             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
14221
14222           /* Copy the deduced arguments.  */
14223           for (; i < len; i++)
14224             TREE_VEC_ELT (new_args, i) =
14225               TREE_VEC_ELT (old_args, i - explicit_len);
14226         }
14227
14228       if (!old_pack)
14229         {
14230           tree result;
14231           /* Build the deduced *_ARGUMENT_PACK.  */
14232           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
14233             {
14234               result = make_node (NONTYPE_ARGUMENT_PACK);
14235               TREE_TYPE (result) = 
14236                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
14237               TREE_CONSTANT (result) = 1;
14238             }
14239           else
14240             result = cxx_make_type (TYPE_ARGUMENT_PACK);
14241
14242           SET_ARGUMENT_PACK_ARGS (result, new_args);
14243
14244           /* Note the deduced argument packs for this parameter
14245              pack.  */
14246           TMPL_ARG (targs, level, idx) = result;
14247         }
14248       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
14249                && (ARGUMENT_PACK_ARGS (old_pack) 
14250                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
14251         {
14252           /* We only had the explicitly-provided arguments before, but
14253              now we have a complete set of arguments.  */
14254           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14255
14256           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
14257           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
14258           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
14259         }
14260       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
14261                                     new_args))
14262         /* Inconsistent unification of this parameter pack.  */
14263         return 1;
14264     }
14265
14266   return 0;
14267 }
14268
14269 /* Deduce the value of template parameters.  TPARMS is the (innermost)
14270    set of template parameters to a template.  TARGS is the bindings
14271    for those template parameters, as determined thus far; TARGS may
14272    include template arguments for outer levels of template parameters
14273    as well.  PARM is a parameter to a template function, or a
14274    subcomponent of that parameter; ARG is the corresponding argument.
14275    This function attempts to match PARM with ARG in a manner
14276    consistent with the existing assignments in TARGS.  If more values
14277    are deduced, then TARGS is updated.
14278
14279    Returns 0 if the type deduction succeeds, 1 otherwise.  The
14280    parameter STRICT is a bitwise or of the following flags:
14281
14282      UNIFY_ALLOW_NONE:
14283        Require an exact match between PARM and ARG.
14284      UNIFY_ALLOW_MORE_CV_QUAL:
14285        Allow the deduced ARG to be more cv-qualified (by qualification
14286        conversion) than ARG.
14287      UNIFY_ALLOW_LESS_CV_QUAL:
14288        Allow the deduced ARG to be less cv-qualified than ARG.
14289      UNIFY_ALLOW_DERIVED:
14290        Allow the deduced ARG to be a template base class of ARG,
14291        or a pointer to a template base class of the type pointed to by
14292        ARG.
14293      UNIFY_ALLOW_INTEGER:
14294        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
14295        case for more information.
14296      UNIFY_ALLOW_OUTER_LEVEL:
14297        This is the outermost level of a deduction. Used to determine validity
14298        of qualification conversions. A valid qualification conversion must
14299        have const qualified pointers leading up to the inner type which
14300        requires additional CV quals, except at the outer level, where const
14301        is not required [conv.qual]. It would be normal to set this flag in
14302        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
14303      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
14304        This is the outermost level of a deduction, and PARM can be more CV
14305        qualified at this point.
14306      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
14307        This is the outermost level of a deduction, and PARM can be less CV
14308        qualified at this point.  */
14309
14310 static int
14311 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
14312 {
14313   int idx;
14314   tree targ;
14315   tree tparm;
14316   int strict_in = strict;
14317
14318   /* I don't think this will do the right thing with respect to types.
14319      But the only case I've seen it in so far has been array bounds, where
14320      signedness is the only information lost, and I think that will be
14321      okay.  */
14322   while (TREE_CODE (parm) == NOP_EXPR)
14323     parm = TREE_OPERAND (parm, 0);
14324
14325   if (arg == error_mark_node)
14326     return 1;
14327   if (arg == unknown_type_node
14328       || arg == init_list_type_node)
14329     /* We can't deduce anything from this, but we might get all the
14330        template args from other function args.  */
14331     return 0;
14332
14333   /* If PARM uses template parameters, then we can't bail out here,
14334      even if ARG == PARM, since we won't record unifications for the
14335      template parameters.  We might need them if we're trying to
14336      figure out which of two things is more specialized.  */
14337   if (arg == parm && !uses_template_parms (parm))
14338     return 0;
14339
14340   /* Handle init lists early, so the rest of the function can assume
14341      we're dealing with a type. */
14342   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
14343     {
14344       tree elt, elttype;
14345       unsigned i;
14346       tree orig_parm = parm;
14347
14348       /* Replace T with std::initializer_list<T> for deduction.  */
14349       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14350           && flag_deduce_init_list)
14351         parm = listify (parm);
14352
14353       if (!is_std_init_list (parm))
14354         /* We can only deduce from an initializer list argument if the
14355            parameter is std::initializer_list; otherwise this is a
14356            non-deduced context. */
14357         return 0;
14358
14359       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
14360
14361       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
14362         {
14363           int elt_strict = strict;
14364           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
14365             {
14366               tree type = TREE_TYPE (elt);
14367               /* It should only be possible to get here for a call.  */
14368               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
14369               elt_strict |= maybe_adjust_types_for_deduction
14370                 (DEDUCE_CALL, &elttype, &type, elt);
14371               elt = type;
14372             }
14373
14374           if (unify (tparms, targs, elttype, elt, elt_strict))
14375             return 1;
14376         }
14377
14378       /* If the std::initializer_list<T> deduction worked, replace the
14379          deduced A with std::initializer_list<A>.  */
14380       if (orig_parm != parm)
14381         {
14382           idx = TEMPLATE_TYPE_IDX (orig_parm);
14383           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14384           targ = listify (targ);
14385           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
14386         }
14387       return 0;
14388     }
14389
14390   /* Immediately reject some pairs that won't unify because of
14391      cv-qualification mismatches.  */
14392   if (TREE_CODE (arg) == TREE_CODE (parm)
14393       && TYPE_P (arg)
14394       /* It is the elements of the array which hold the cv quals of an array
14395          type, and the elements might be template type parms. We'll check
14396          when we recurse.  */
14397       && TREE_CODE (arg) != ARRAY_TYPE
14398       /* We check the cv-qualifiers when unifying with template type
14399          parameters below.  We want to allow ARG `const T' to unify with
14400          PARM `T' for example, when computing which of two templates
14401          is more specialized, for example.  */
14402       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
14403       && !check_cv_quals_for_unify (strict_in, arg, parm))
14404     return 1;
14405
14406   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
14407       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
14408     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
14409   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
14410   strict &= ~UNIFY_ALLOW_DERIVED;
14411   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
14412   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
14413
14414   switch (TREE_CODE (parm))
14415     {
14416     case TYPENAME_TYPE:
14417     case SCOPE_REF:
14418     case UNBOUND_CLASS_TEMPLATE:
14419       /* In a type which contains a nested-name-specifier, template
14420          argument values cannot be deduced for template parameters used
14421          within the nested-name-specifier.  */
14422       return 0;
14423
14424     case TEMPLATE_TYPE_PARM:
14425     case TEMPLATE_TEMPLATE_PARM:
14426     case BOUND_TEMPLATE_TEMPLATE_PARM:
14427       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14428       if (tparm == error_mark_node)
14429         return 1;
14430
14431       if (TEMPLATE_TYPE_LEVEL (parm)
14432           != template_decl_level (tparm))
14433         /* The PARM is not one we're trying to unify.  Just check
14434            to see if it matches ARG.  */
14435         return (TREE_CODE (arg) == TREE_CODE (parm)
14436                 && same_type_p (parm, arg)) ? 0 : 1;
14437       idx = TEMPLATE_TYPE_IDX (parm);
14438       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14439       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
14440
14441       /* Check for mixed types and values.  */
14442       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14443            && TREE_CODE (tparm) != TYPE_DECL)
14444           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14445               && TREE_CODE (tparm) != TEMPLATE_DECL))
14446         return 1;
14447
14448       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14449         {
14450           /* ARG must be constructed from a template class or a template
14451              template parameter.  */
14452           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
14453               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
14454             return 1;
14455
14456           {
14457             tree parmvec = TYPE_TI_ARGS (parm);
14458             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
14459             tree parm_parms 
14460               = DECL_INNERMOST_TEMPLATE_PARMS
14461                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
14462             int i, len;
14463             int parm_variadic_p = 0;
14464
14465             /* The resolution to DR150 makes clear that default
14466                arguments for an N-argument may not be used to bind T
14467                to a template template parameter with fewer than N
14468                parameters.  It is not safe to permit the binding of
14469                default arguments as an extension, as that may change
14470                the meaning of a conforming program.  Consider:
14471
14472                   struct Dense { static const unsigned int dim = 1; };
14473
14474                   template <template <typename> class View,
14475                             typename Block>
14476                   void operator+(float, View<Block> const&);
14477
14478                   template <typename Block,
14479                             unsigned int Dim = Block::dim>
14480                   struct Lvalue_proxy { operator float() const; };
14481
14482                   void
14483                   test_1d (void) {
14484                     Lvalue_proxy<Dense> p;
14485                     float b;
14486                     b + p;
14487                   }
14488
14489               Here, if Lvalue_proxy is permitted to bind to View, then
14490               the global operator+ will be used; if they are not, the
14491               Lvalue_proxy will be converted to float.  */
14492             if (coerce_template_parms (parm_parms,
14493                                        argvec,
14494                                        TYPE_TI_TEMPLATE (parm),
14495                                        tf_none,
14496                                        /*require_all_args=*/true,
14497                                        /*use_default_args=*/false)
14498                 == error_mark_node)
14499               return 1;
14500
14501             /* Deduce arguments T, i from TT<T> or TT<i>.
14502                We check each element of PARMVEC and ARGVEC individually
14503                rather than the whole TREE_VEC since they can have
14504                different number of elements.  */
14505
14506             parmvec = expand_template_argument_pack (parmvec);
14507             argvec = expand_template_argument_pack (argvec);
14508
14509             len = TREE_VEC_LENGTH (parmvec);
14510
14511             /* Check if the parameters end in a pack, making them
14512                variadic.  */
14513             if (len > 0
14514                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
14515               parm_variadic_p = 1;
14516             
14517             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
14518               return 1;
14519
14520              for (i = 0; i < len - parm_variadic_p; ++i)
14521               {
14522                 if (unify (tparms, targs,
14523                            TREE_VEC_ELT (parmvec, i),
14524                            TREE_VEC_ELT (argvec, i),
14525                            UNIFY_ALLOW_NONE))
14526                   return 1;
14527               }
14528
14529             if (parm_variadic_p
14530                 && unify_pack_expansion (tparms, targs,
14531                                          parmvec, argvec,
14532                                          UNIFY_ALLOW_NONE,
14533                                          /*call_args_p=*/false,
14534                                          /*subr=*/false))
14535               return 1;
14536           }
14537           arg = TYPE_TI_TEMPLATE (arg);
14538
14539           /* Fall through to deduce template name.  */
14540         }
14541
14542       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14543           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14544         {
14545           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
14546
14547           /* Simple cases: Value already set, does match or doesn't.  */
14548           if (targ != NULL_TREE && template_args_equal (targ, arg))
14549             return 0;
14550           else if (targ)
14551             return 1;
14552         }
14553       else
14554         {
14555           /* If PARM is `const T' and ARG is only `int', we don't have
14556              a match unless we are allowing additional qualification.
14557              If ARG is `const int' and PARM is just `T' that's OK;
14558              that binds `const int' to `T'.  */
14559           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
14560                                          arg, parm))
14561             return 1;
14562
14563           /* Consider the case where ARG is `const volatile int' and
14564              PARM is `const T'.  Then, T should be `volatile int'.  */
14565           arg = cp_build_qualified_type_real
14566             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
14567           if (arg == error_mark_node)
14568             return 1;
14569
14570           /* Simple cases: Value already set, does match or doesn't.  */
14571           if (targ != NULL_TREE && same_type_p (targ, arg))
14572             return 0;
14573           else if (targ)
14574             return 1;
14575
14576           /* Make sure that ARG is not a variable-sized array.  (Note
14577              that were talking about variable-sized arrays (like
14578              `int[n]'), rather than arrays of unknown size (like
14579              `int[]').)  We'll get very confused by such a type since
14580              the bound of the array will not be computable in an
14581              instantiation.  Besides, such types are not allowed in
14582              ISO C++, so we can do as we please here.  */
14583           if (variably_modified_type_p (arg, NULL_TREE))
14584             return 1;
14585
14586           /* Strip typedefs as in convert_template_argument.  */
14587           arg = strip_typedefs (arg);
14588         }
14589
14590       /* If ARG is a parameter pack or an expansion, we cannot unify
14591          against it unless PARM is also a parameter pack.  */
14592       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
14593           && !template_parameter_pack_p (parm))
14594         return 1;
14595
14596       /* If the argument deduction results is a METHOD_TYPE,
14597          then there is a problem.
14598          METHOD_TYPE doesn't map to any real C++ type the result of
14599          the deduction can not be of that type.  */
14600       if (TREE_CODE (arg) == METHOD_TYPE)
14601         return 1;
14602
14603       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
14604       return 0;
14605
14606     case TEMPLATE_PARM_INDEX:
14607       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14608       if (tparm == error_mark_node)
14609         return 1;
14610
14611       if (TEMPLATE_PARM_LEVEL (parm)
14612           != template_decl_level (tparm))
14613         /* The PARM is not one we're trying to unify.  Just check
14614            to see if it matches ARG.  */
14615         return !(TREE_CODE (arg) == TREE_CODE (parm)
14616                  && cp_tree_equal (parm, arg));
14617
14618       idx = TEMPLATE_PARM_IDX (parm);
14619       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14620
14621       if (targ)
14622         return !cp_tree_equal (targ, arg);
14623
14624       /* [temp.deduct.type] If, in the declaration of a function template
14625          with a non-type template-parameter, the non-type
14626          template-parameter is used in an expression in the function
14627          parameter-list and, if the corresponding template-argument is
14628          deduced, the template-argument type shall match the type of the
14629          template-parameter exactly, except that a template-argument
14630          deduced from an array bound may be of any integral type.
14631          The non-type parameter might use already deduced type parameters.  */
14632       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
14633       if (!TREE_TYPE (arg))
14634         /* Template-parameter dependent expression.  Just accept it for now.
14635            It will later be processed in convert_template_argument.  */
14636         ;
14637       else if (same_type_p (TREE_TYPE (arg), tparm))
14638         /* OK */;
14639       else if ((strict & UNIFY_ALLOW_INTEGER)
14640                && (TREE_CODE (tparm) == INTEGER_TYPE
14641                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
14642         /* Convert the ARG to the type of PARM; the deduced non-type
14643            template argument must exactly match the types of the
14644            corresponding parameter.  */
14645         arg = fold (build_nop (tparm, arg));
14646       else if (uses_template_parms (tparm))
14647         /* We haven't deduced the type of this parameter yet.  Try again
14648            later.  */
14649         return 0;
14650       else
14651         return 1;
14652
14653       /* If ARG is a parameter pack or an expansion, we cannot unify
14654          against it unless PARM is also a parameter pack.  */
14655       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
14656           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
14657         return 1;
14658
14659       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
14660       return 0;
14661
14662     case PTRMEM_CST:
14663      {
14664         /* A pointer-to-member constant can be unified only with
14665          another constant.  */
14666       if (TREE_CODE (arg) != PTRMEM_CST)
14667         return 1;
14668
14669       /* Just unify the class member. It would be useless (and possibly
14670          wrong, depending on the strict flags) to unify also
14671          PTRMEM_CST_CLASS, because we want to be sure that both parm and
14672          arg refer to the same variable, even if through different
14673          classes. For instance:
14674
14675          struct A { int x; };
14676          struct B : A { };
14677
14678          Unification of &A::x and &B::x must succeed.  */
14679       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
14680                     PTRMEM_CST_MEMBER (arg), strict);
14681      }
14682
14683     case POINTER_TYPE:
14684       {
14685         if (TREE_CODE (arg) != POINTER_TYPE)
14686           return 1;
14687
14688         /* [temp.deduct.call]
14689
14690            A can be another pointer or pointer to member type that can
14691            be converted to the deduced A via a qualification
14692            conversion (_conv.qual_).
14693
14694            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
14695            This will allow for additional cv-qualification of the
14696            pointed-to types if appropriate.  */
14697
14698         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
14699           /* The derived-to-base conversion only persists through one
14700              level of pointers.  */
14701           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
14702
14703         return unify (tparms, targs, TREE_TYPE (parm),
14704                       TREE_TYPE (arg), strict);
14705       }
14706
14707     case REFERENCE_TYPE:
14708       if (TREE_CODE (arg) != REFERENCE_TYPE)
14709         return 1;
14710       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14711                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
14712
14713     case ARRAY_TYPE:
14714       if (TREE_CODE (arg) != ARRAY_TYPE)
14715         return 1;
14716       if ((TYPE_DOMAIN (parm) == NULL_TREE)
14717           != (TYPE_DOMAIN (arg) == NULL_TREE))
14718         return 1;
14719       if (TYPE_DOMAIN (parm) != NULL_TREE)
14720         {
14721           tree parm_max;
14722           tree arg_max;
14723           bool parm_cst;
14724           bool arg_cst;
14725
14726           /* Our representation of array types uses "N - 1" as the
14727              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
14728              not an integer constant.  We cannot unify arbitrarily
14729              complex expressions, so we eliminate the MINUS_EXPRs
14730              here.  */
14731           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
14732           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
14733           if (!parm_cst)
14734             {
14735               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
14736               parm_max = TREE_OPERAND (parm_max, 0);
14737             }
14738           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
14739           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
14740           if (!arg_cst)
14741             {
14742               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
14743                  trying to unify the type of a variable with the type
14744                  of a template parameter.  For example:
14745
14746                    template <unsigned int N>
14747                    void f (char (&) [N]);
14748                    int g(); 
14749                    void h(int i) {
14750                      char a[g(i)];
14751                      f(a); 
14752                    }
14753
14754                 Here, the type of the ARG will be "int [g(i)]", and
14755                 may be a SAVE_EXPR, etc.  */
14756               if (TREE_CODE (arg_max) != MINUS_EXPR)
14757                 return 1;
14758               arg_max = TREE_OPERAND (arg_max, 0);
14759             }
14760
14761           /* If only one of the bounds used a MINUS_EXPR, compensate
14762              by adding one to the other bound.  */
14763           if (parm_cst && !arg_cst)
14764             parm_max = fold_build2_loc (input_location, PLUS_EXPR,
14765                                     integer_type_node,
14766                                     parm_max,
14767                                     integer_one_node);
14768           else if (arg_cst && !parm_cst)
14769             arg_max = fold_build2_loc (input_location, PLUS_EXPR,
14770                                    integer_type_node,
14771                                    arg_max,
14772                                    integer_one_node);
14773
14774           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
14775             return 1;
14776         }
14777       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14778                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
14779
14780     case REAL_TYPE:
14781     case COMPLEX_TYPE:
14782     case VECTOR_TYPE:
14783     case INTEGER_TYPE:
14784     case BOOLEAN_TYPE:
14785     case ENUMERAL_TYPE:
14786     case VOID_TYPE:
14787       if (TREE_CODE (arg) != TREE_CODE (parm))
14788         return 1;
14789
14790       /* We have already checked cv-qualification at the top of the
14791          function.  */
14792       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
14793         return 1;
14794
14795       /* As far as unification is concerned, this wins.  Later checks
14796          will invalidate it if necessary.  */
14797       return 0;
14798
14799       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
14800       /* Type INTEGER_CST can come from ordinary constant template args.  */
14801     case INTEGER_CST:
14802       while (TREE_CODE (arg) == NOP_EXPR)
14803         arg = TREE_OPERAND (arg, 0);
14804
14805       if (TREE_CODE (arg) != INTEGER_CST)
14806         return 1;
14807       return !tree_int_cst_equal (parm, arg);
14808
14809     case TREE_VEC:
14810       {
14811         int i;
14812         if (TREE_CODE (arg) != TREE_VEC)
14813           return 1;
14814         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
14815           return 1;
14816         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
14817           if (unify (tparms, targs,
14818                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
14819                      UNIFY_ALLOW_NONE))
14820             return 1;
14821         return 0;
14822       }
14823
14824     case RECORD_TYPE:
14825     case UNION_TYPE:
14826       if (TREE_CODE (arg) != TREE_CODE (parm))
14827         return 1;
14828
14829       if (TYPE_PTRMEMFUNC_P (parm))
14830         {
14831           if (!TYPE_PTRMEMFUNC_P (arg))
14832             return 1;
14833
14834           return unify (tparms, targs,
14835                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
14836                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
14837                         strict);
14838         }
14839
14840       if (CLASSTYPE_TEMPLATE_INFO (parm))
14841         {
14842           tree t = NULL_TREE;
14843
14844           if (strict_in & UNIFY_ALLOW_DERIVED)
14845             {
14846               /* First, we try to unify the PARM and ARG directly.  */
14847               t = try_class_unification (tparms, targs,
14848                                          parm, arg);
14849
14850               if (!t)
14851                 {
14852                   /* Fallback to the special case allowed in
14853                      [temp.deduct.call]:
14854
14855                        If P is a class, and P has the form
14856                        template-id, then A can be a derived class of
14857                        the deduced A.  Likewise, if P is a pointer to
14858                        a class of the form template-id, A can be a
14859                        pointer to a derived class pointed to by the
14860                        deduced A.  */
14861                   t = get_template_base (tparms, targs, parm, arg);
14862
14863                   if (!t)
14864                     return 1;
14865                 }
14866             }
14867           else if (CLASSTYPE_TEMPLATE_INFO (arg)
14868                    && (CLASSTYPE_TI_TEMPLATE (parm)
14869                        == CLASSTYPE_TI_TEMPLATE (arg)))
14870             /* Perhaps PARM is something like S<U> and ARG is S<int>.
14871                Then, we should unify `int' and `U'.  */
14872             t = arg;
14873           else
14874             /* There's no chance of unification succeeding.  */
14875             return 1;
14876
14877           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
14878                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
14879         }
14880       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
14881         return 1;
14882       return 0;
14883
14884     case METHOD_TYPE:
14885     case FUNCTION_TYPE:
14886       {
14887         unsigned int nargs;
14888         tree *args;
14889         tree a;
14890         unsigned int i;
14891
14892         if (TREE_CODE (arg) != TREE_CODE (parm))
14893           return 1;
14894
14895         /* CV qualifications for methods can never be deduced, they must
14896            match exactly.  We need to check them explicitly here,
14897            because type_unification_real treats them as any other
14898            cv-qualified parameter.  */
14899         if (TREE_CODE (parm) == METHOD_TYPE
14900             && (!check_cv_quals_for_unify
14901                 (UNIFY_ALLOW_NONE,
14902                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
14903                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
14904           return 1;
14905
14906         if (unify (tparms, targs, TREE_TYPE (parm),
14907                    TREE_TYPE (arg), UNIFY_ALLOW_NONE))
14908           return 1;
14909
14910         nargs = list_length (TYPE_ARG_TYPES (arg));
14911         args = XALLOCAVEC (tree, nargs);
14912         for (a = TYPE_ARG_TYPES (arg), i = 0;
14913              a != NULL_TREE && a != void_list_node;
14914              a = TREE_CHAIN (a), ++i)
14915           args[i] = TREE_VALUE (a);
14916         nargs = i;
14917
14918         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
14919                                       args, nargs, 1, DEDUCE_EXACT,
14920                                       LOOKUP_NORMAL);
14921       }
14922
14923     case OFFSET_TYPE:
14924       /* Unify a pointer to member with a pointer to member function, which
14925          deduces the type of the member as a function type. */
14926       if (TYPE_PTRMEMFUNC_P (arg))
14927         {
14928           tree method_type;
14929           tree fntype;
14930           cp_cv_quals cv_quals;
14931
14932           /* Check top-level cv qualifiers */
14933           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
14934             return 1;
14935
14936           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
14937                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
14938             return 1;
14939
14940           /* Determine the type of the function we are unifying against. */
14941           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
14942           fntype =
14943             build_function_type (TREE_TYPE (method_type),
14944                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
14945
14946           /* Extract the cv-qualifiers of the member function from the
14947              implicit object parameter and place them on the function
14948              type to be restored later. */
14949           cv_quals =
14950             cp_type_quals(TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (method_type))));
14951           fntype = build_qualified_type (fntype, cv_quals);
14952           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
14953         }
14954
14955       if (TREE_CODE (arg) != OFFSET_TYPE)
14956         return 1;
14957       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
14958                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
14959         return 1;
14960       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14961                     strict);
14962
14963     case CONST_DECL:
14964       if (DECL_TEMPLATE_PARM_P (parm))
14965         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
14966       if (arg != integral_constant_value (parm))
14967         return 1;
14968       return 0;
14969
14970     case FIELD_DECL:
14971     case TEMPLATE_DECL:
14972       /* Matched cases are handled by the ARG == PARM test above.  */
14973       return 1;
14974
14975     case TYPE_ARGUMENT_PACK:
14976     case NONTYPE_ARGUMENT_PACK:
14977       {
14978         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
14979         tree packed_args = ARGUMENT_PACK_ARGS (arg);
14980         int i, len = TREE_VEC_LENGTH (packed_parms);
14981         int argslen = TREE_VEC_LENGTH (packed_args);
14982         int parm_variadic_p = 0;
14983
14984         for (i = 0; i < len; ++i)
14985           {
14986             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
14987               {
14988                 if (i == len - 1)
14989                   /* We can unify against something with a trailing
14990                      parameter pack.  */
14991                   parm_variadic_p = 1;
14992                 else
14993                   /* Since there is something following the pack
14994                      expansion, we cannot unify this template argument
14995                      list.  */
14996                   return 0;
14997               }
14998           }
14999           
15000
15001         /* If we don't have enough arguments to satisfy the parameters
15002            (not counting the pack expression at the end), or we have
15003            too many arguments for a parameter list that doesn't end in
15004            a pack expression, we can't unify.  */
15005         if (argslen < (len - parm_variadic_p)
15006             || (argslen > len && !parm_variadic_p))
15007           return 1;
15008
15009         /* Unify all of the parameters that precede the (optional)
15010            pack expression.  */
15011         for (i = 0; i < len - parm_variadic_p; ++i)
15012           {
15013             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
15014                        TREE_VEC_ELT (packed_args, i), strict))
15015               return 1;
15016           }
15017
15018         if (parm_variadic_p)
15019           return unify_pack_expansion (tparms, targs, 
15020                                        packed_parms, packed_args,
15021                                        strict, /*call_args_p=*/false,
15022                                        /*subr=*/false);
15023         return 0;
15024       }
15025
15026       break;
15027
15028     case TYPEOF_TYPE:
15029     case DECLTYPE_TYPE:
15030       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
15031          nodes.  */
15032       return 0;
15033
15034     case ERROR_MARK:
15035       /* Unification fails if we hit an error node.  */
15036       return 1;
15037
15038     default:
15039       gcc_assert (EXPR_P (parm));
15040
15041       /* We must be looking at an expression.  This can happen with
15042          something like:
15043
15044            template <int I>
15045            void foo(S<I>, S<I + 2>);
15046
15047          This is a "nondeduced context":
15048
15049            [deduct.type]
15050
15051            The nondeduced contexts are:
15052
15053            --A type that is a template-id in which one or more of
15054              the template-arguments is an expression that references
15055              a template-parameter.
15056
15057          In these cases, we assume deduction succeeded, but don't
15058          actually infer any unifications.  */
15059
15060       if (!uses_template_parms (parm)
15061           && !template_args_equal (parm, arg))
15062         return 1;
15063       else
15064         return 0;
15065     }
15066 }
15067 \f
15068 /* Note that DECL can be defined in this translation unit, if
15069    required.  */
15070
15071 static void
15072 mark_definable (tree decl)
15073 {
15074   tree clone;
15075   DECL_NOT_REALLY_EXTERN (decl) = 1;
15076   FOR_EACH_CLONE (clone, decl)
15077     DECL_NOT_REALLY_EXTERN (clone) = 1;
15078 }
15079
15080 /* Called if RESULT is explicitly instantiated, or is a member of an
15081    explicitly instantiated class.  */
15082
15083 void
15084 mark_decl_instantiated (tree result, int extern_p)
15085 {
15086   SET_DECL_EXPLICIT_INSTANTIATION (result);
15087
15088   /* If this entity has already been written out, it's too late to
15089      make any modifications.  */
15090   if (TREE_ASM_WRITTEN (result))
15091     return;
15092
15093   if (TREE_CODE (result) != FUNCTION_DECL)
15094     /* The TREE_PUBLIC flag for function declarations will have been
15095        set correctly by tsubst.  */
15096     TREE_PUBLIC (result) = 1;
15097
15098   /* This might have been set by an earlier implicit instantiation.  */
15099   DECL_COMDAT (result) = 0;
15100
15101   if (extern_p)
15102     DECL_NOT_REALLY_EXTERN (result) = 0;
15103   else
15104     {
15105       mark_definable (result);
15106       /* Always make artificials weak.  */
15107       if (DECL_ARTIFICIAL (result) && flag_weak)
15108         comdat_linkage (result);
15109       /* For WIN32 we also want to put explicit instantiations in
15110          linkonce sections.  */
15111       else if (TREE_PUBLIC (result))
15112         maybe_make_one_only (result);
15113     }
15114
15115   /* If EXTERN_P, then this function will not be emitted -- unless
15116      followed by an explicit instantiation, at which point its linkage
15117      will be adjusted.  If !EXTERN_P, then this function will be
15118      emitted here.  In neither circumstance do we want
15119      import_export_decl to adjust the linkage.  */
15120   DECL_INTERFACE_KNOWN (result) = 1;
15121 }
15122
15123 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
15124    important template arguments.  If any are missing, we check whether
15125    they're important by using error_mark_node for substituting into any
15126    args that were used for partial ordering (the ones between ARGS and END)
15127    and seeing if it bubbles up.  */
15128
15129 static bool
15130 check_undeduced_parms (tree targs, tree args, tree end)
15131 {
15132   bool found = false;
15133   int i;
15134   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
15135     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
15136       {
15137         found = true;
15138         TREE_VEC_ELT (targs, i) = error_mark_node;
15139       }
15140   if (found)
15141     {
15142       for (; args != end; args = TREE_CHAIN (args))
15143         {
15144           tree substed = tsubst (TREE_VALUE (args), targs, tf_none, NULL_TREE);
15145           if (substed == error_mark_node)
15146             return true;
15147         }
15148     }
15149   return false;
15150 }
15151
15152 /* Given two function templates PAT1 and PAT2, return:
15153
15154    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
15155    -1 if PAT2 is more specialized than PAT1.
15156    0 if neither is more specialized.
15157
15158    LEN indicates the number of parameters we should consider
15159    (defaulted parameters should not be considered).
15160
15161    The 1998 std underspecified function template partial ordering, and
15162    DR214 addresses the issue.  We take pairs of arguments, one from
15163    each of the templates, and deduce them against each other.  One of
15164    the templates will be more specialized if all the *other*
15165    template's arguments deduce against its arguments and at least one
15166    of its arguments *does* *not* deduce against the other template's
15167    corresponding argument.  Deduction is done as for class templates.
15168    The arguments used in deduction have reference and top level cv
15169    qualifiers removed.  Iff both arguments were originally reference
15170    types *and* deduction succeeds in both directions, the template
15171    with the more cv-qualified argument wins for that pairing (if
15172    neither is more cv-qualified, they both are equal).  Unlike regular
15173    deduction, after all the arguments have been deduced in this way,
15174    we do *not* verify the deduced template argument values can be
15175    substituted into non-deduced contexts.
15176
15177    The logic can be a bit confusing here, because we look at deduce1 and
15178    targs1 to see if pat2 is at least as specialized, and vice versa; if we
15179    can find template arguments for pat1 to make arg1 look like arg2, that
15180    means that arg2 is at least as specialized as arg1.  */
15181
15182 int
15183 more_specialized_fn (tree pat1, tree pat2, int len)
15184 {
15185   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
15186   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
15187   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
15188   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
15189   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
15190   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
15191   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
15192   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
15193   tree origs1, origs2;
15194   bool lose1 = false;
15195   bool lose2 = false;
15196
15197   /* Remove the this parameter from non-static member functions.  If
15198      one is a non-static member function and the other is not a static
15199      member function, remove the first parameter from that function
15200      also.  This situation occurs for operator functions where we
15201      locate both a member function (with this pointer) and non-member
15202      operator (with explicit first operand).  */
15203   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
15204     {
15205       len--; /* LEN is the number of significant arguments for DECL1 */
15206       args1 = TREE_CHAIN (args1);
15207       if (!DECL_STATIC_FUNCTION_P (decl2))
15208         args2 = TREE_CHAIN (args2);
15209     }
15210   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
15211     {
15212       args2 = TREE_CHAIN (args2);
15213       if (!DECL_STATIC_FUNCTION_P (decl1))
15214         {
15215           len--;
15216           args1 = TREE_CHAIN (args1);
15217         }
15218     }
15219
15220   /* If only one is a conversion operator, they are unordered.  */
15221   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
15222     return 0;
15223
15224   /* Consider the return type for a conversion function */
15225   if (DECL_CONV_FN_P (decl1))
15226     {
15227       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
15228       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
15229       len++;
15230     }
15231
15232   processing_template_decl++;
15233
15234   origs1 = args1;
15235   origs2 = args2;
15236
15237   while (len--
15238          /* Stop when an ellipsis is seen.  */
15239          && args1 != NULL_TREE && args2 != NULL_TREE)
15240     {
15241       tree arg1 = TREE_VALUE (args1);
15242       tree arg2 = TREE_VALUE (args2);
15243       int deduce1, deduce2;
15244       int quals1 = -1;
15245       int quals2 = -1;
15246
15247       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15248           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15249         {
15250           /* When both arguments are pack expansions, we need only
15251              unify the patterns themselves.  */
15252           arg1 = PACK_EXPANSION_PATTERN (arg1);
15253           arg2 = PACK_EXPANSION_PATTERN (arg2);
15254
15255           /* This is the last comparison we need to do.  */
15256           len = 0;
15257         }
15258
15259       if (TREE_CODE (arg1) == REFERENCE_TYPE)
15260         {
15261           arg1 = TREE_TYPE (arg1);
15262           quals1 = cp_type_quals (arg1);
15263         }
15264
15265       if (TREE_CODE (arg2) == REFERENCE_TYPE)
15266         {
15267           arg2 = TREE_TYPE (arg2);
15268           quals2 = cp_type_quals (arg2);
15269         }
15270
15271       if ((quals1 < 0) != (quals2 < 0))
15272         {
15273           /* Only of the args is a reference, see if we should apply
15274              array/function pointer decay to it.  This is not part of
15275              DR214, but is, IMHO, consistent with the deduction rules
15276              for the function call itself, and with our earlier
15277              implementation of the underspecified partial ordering
15278              rules.  (nathan).  */
15279           if (quals1 >= 0)
15280             {
15281               switch (TREE_CODE (arg1))
15282                 {
15283                 case ARRAY_TYPE:
15284                   arg1 = TREE_TYPE (arg1);
15285                   /* FALLTHROUGH. */
15286                 case FUNCTION_TYPE:
15287                   arg1 = build_pointer_type (arg1);
15288                   break;
15289
15290                 default:
15291                   break;
15292                 }
15293             }
15294           else
15295             {
15296               switch (TREE_CODE (arg2))
15297                 {
15298                 case ARRAY_TYPE:
15299                   arg2 = TREE_TYPE (arg2);
15300                   /* FALLTHROUGH. */
15301                 case FUNCTION_TYPE:
15302                   arg2 = build_pointer_type (arg2);
15303                   break;
15304
15305                 default:
15306                   break;
15307                 }
15308             }
15309         }
15310
15311       arg1 = TYPE_MAIN_VARIANT (arg1);
15312       arg2 = TYPE_MAIN_VARIANT (arg2);
15313
15314       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
15315         {
15316           int i, len2 = list_length (args2);
15317           tree parmvec = make_tree_vec (1);
15318           tree argvec = make_tree_vec (len2);
15319           tree ta = args2;
15320
15321           /* Setup the parameter vector, which contains only ARG1.  */
15322           TREE_VEC_ELT (parmvec, 0) = arg1;
15323
15324           /* Setup the argument vector, which contains the remaining
15325              arguments.  */
15326           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
15327             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15328
15329           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
15330                                            argvec, UNIFY_ALLOW_NONE, 
15331                                            /*call_args_p=*/false, 
15332                                            /*subr=*/0);
15333
15334           /* We cannot deduce in the other direction, because ARG1 is
15335              a pack expansion but ARG2 is not.  */
15336           deduce2 = 0;
15337         }
15338       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15339         {
15340           int i, len1 = list_length (args1);
15341           tree parmvec = make_tree_vec (1);
15342           tree argvec = make_tree_vec (len1);
15343           tree ta = args1;
15344
15345           /* Setup the parameter vector, which contains only ARG1.  */
15346           TREE_VEC_ELT (parmvec, 0) = arg2;
15347
15348           /* Setup the argument vector, which contains the remaining
15349              arguments.  */
15350           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
15351             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15352
15353           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
15354                                            argvec, UNIFY_ALLOW_NONE, 
15355                                            /*call_args_p=*/false, 
15356                                            /*subr=*/0);
15357
15358           /* We cannot deduce in the other direction, because ARG2 is
15359              a pack expansion but ARG1 is not.*/
15360           deduce1 = 0;
15361         }
15362
15363       else
15364         {
15365           /* The normal case, where neither argument is a pack
15366              expansion.  */
15367           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
15368           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
15369         }
15370
15371       /* If we couldn't deduce arguments for tparms1 to make arg1 match
15372          arg2, then arg2 is not as specialized as arg1.  */
15373       if (!deduce1)
15374         lose2 = true;
15375       if (!deduce2)
15376         lose1 = true;
15377
15378       /* "If, for a given type, deduction succeeds in both directions
15379          (i.e., the types are identical after the transformations above)
15380          and if the type from the argument template is more cv-qualified
15381          than the type from the parameter template (as described above)
15382          that type is considered to be more specialized than the other. If
15383          neither type is more cv-qualified than the other then neither type
15384          is more specialized than the other."
15385
15386          We check same_type_p explicitly because deduction can also succeed
15387          in both directions when there is a nondeduced context.  */
15388       if (deduce1 && deduce2
15389           && quals1 != quals2 && quals1 >= 0 && quals2 >= 0
15390           && same_type_p (arg1, arg2))
15391         {
15392           if ((quals1 & quals2) == quals2)
15393             lose2 = true;
15394           if ((quals1 & quals2) == quals1)
15395             lose1 = true;
15396         }
15397
15398       if (lose1 && lose2)
15399         /* We've failed to deduce something in either direction.
15400            These must be unordered.  */
15401         break;
15402
15403       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15404           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15405         /* We have already processed all of the arguments in our
15406            handing of the pack expansion type.  */
15407         len = 0;
15408
15409       args1 = TREE_CHAIN (args1);
15410       args2 = TREE_CHAIN (args2);
15411     }
15412
15413   /* "In most cases, all template parameters must have values in order for
15414      deduction to succeed, but for partial ordering purposes a template
15415      parameter may remain without a value provided it is not used in the
15416      types being used for partial ordering."
15417
15418      Thus, if we are missing any of the targs1 we need to substitute into
15419      origs1, then pat2 is not as specialized as pat1.  This can happen when
15420      there is a nondeduced context.  */
15421   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
15422     lose2 = true;
15423   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
15424     lose1 = true;
15425
15426   processing_template_decl--;
15427
15428   /* All things being equal, if the next argument is a pack expansion
15429      for one function but not for the other, prefer the
15430      non-variadic function.  FIXME this is bogus; see c++/41958.  */
15431   if (lose1 == lose2
15432       && args1 && TREE_VALUE (args1)
15433       && args2 && TREE_VALUE (args2))
15434     {
15435       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
15436       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
15437     }
15438
15439   if (lose1 == lose2)
15440     return 0;
15441   else if (!lose1)
15442     return 1;
15443   else
15444     return -1;
15445 }
15446
15447 /* Determine which of two partial specializations is more specialized.
15448
15449    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
15450    to the first partial specialization.  The TREE_VALUE is the
15451    innermost set of template parameters for the partial
15452    specialization.  PAT2 is similar, but for the second template.
15453
15454    Return 1 if the first partial specialization is more specialized;
15455    -1 if the second is more specialized; 0 if neither is more
15456    specialized.
15457
15458    See [temp.class.order] for information about determining which of
15459    two templates is more specialized.  */
15460
15461 static int
15462 more_specialized_class (tree pat1, tree pat2)
15463 {
15464   tree targs;
15465   tree tmpl1, tmpl2;
15466   int winner = 0;
15467   bool any_deductions = false;
15468
15469   tmpl1 = TREE_TYPE (pat1);
15470   tmpl2 = TREE_TYPE (pat2);
15471
15472   /* Just like what happens for functions, if we are ordering between
15473      different class template specializations, we may encounter dependent
15474      types in the arguments, and we need our dependency check functions
15475      to behave correctly.  */
15476   ++processing_template_decl;
15477   targs = get_class_bindings (TREE_VALUE (pat1),
15478                               CLASSTYPE_TI_ARGS (tmpl1),
15479                               CLASSTYPE_TI_ARGS (tmpl2));
15480   if (targs)
15481     {
15482       --winner;
15483       any_deductions = true;
15484     }
15485
15486   targs = get_class_bindings (TREE_VALUE (pat2),
15487                               CLASSTYPE_TI_ARGS (tmpl2),
15488                               CLASSTYPE_TI_ARGS (tmpl1));
15489   if (targs)
15490     {
15491       ++winner;
15492       any_deductions = true;
15493     }
15494   --processing_template_decl;
15495
15496   /* In the case of a tie where at least one of the class templates
15497      has a parameter pack at the end, the template with the most
15498      non-packed parameters wins.  */
15499   if (winner == 0
15500       && any_deductions
15501       && (template_args_variadic_p (TREE_PURPOSE (pat1))
15502           || template_args_variadic_p (TREE_PURPOSE (pat2))))
15503     {
15504       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
15505       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
15506       int len1 = TREE_VEC_LENGTH (args1);
15507       int len2 = TREE_VEC_LENGTH (args2);
15508
15509       /* We don't count the pack expansion at the end.  */
15510       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
15511         --len1;
15512       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
15513         --len2;
15514
15515       if (len1 > len2)
15516         return 1;
15517       else if (len1 < len2)
15518         return -1;
15519     }
15520
15521   return winner;
15522 }
15523
15524 /* Return the template arguments that will produce the function signature
15525    DECL from the function template FN, with the explicit template
15526    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
15527    also match.  Return NULL_TREE if no satisfactory arguments could be
15528    found.  */
15529
15530 static tree
15531 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
15532 {
15533   int ntparms = DECL_NTPARMS (fn);
15534   tree targs = make_tree_vec (ntparms);
15535   tree decl_type;
15536   tree decl_arg_types;
15537   tree *args;
15538   unsigned int nargs, ix;
15539   tree arg;
15540
15541   /* Substitute the explicit template arguments into the type of DECL.
15542      The call to fn_type_unification will handle substitution into the
15543      FN.  */
15544   decl_type = TREE_TYPE (decl);
15545   if (explicit_args && uses_template_parms (decl_type))
15546     {
15547       tree tmpl;
15548       tree converted_args;
15549
15550       if (DECL_TEMPLATE_INFO (decl))
15551         tmpl = DECL_TI_TEMPLATE (decl);
15552       else
15553         /* We can get here for some invalid specializations.  */
15554         return NULL_TREE;
15555
15556       converted_args
15557         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
15558                                  explicit_args, NULL_TREE,
15559                                  tf_none,
15560                                  /*require_all_args=*/false,
15561                                  /*use_default_args=*/false);
15562       if (converted_args == error_mark_node)
15563         return NULL_TREE;
15564
15565       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
15566       if (decl_type == error_mark_node)
15567         return NULL_TREE;
15568     }
15569
15570   /* Never do unification on the 'this' parameter.  */
15571   decl_arg_types = skip_artificial_parms_for (decl, 
15572                                               TYPE_ARG_TYPES (decl_type));
15573
15574   nargs = list_length (decl_arg_types);
15575   args = XALLOCAVEC (tree, nargs);
15576   for (arg = decl_arg_types, ix = 0;
15577        arg != NULL_TREE && arg != void_list_node;
15578        arg = TREE_CHAIN (arg), ++ix)
15579     args[ix] = TREE_VALUE (arg);
15580
15581   if (fn_type_unification (fn, explicit_args, targs,
15582                            args, ix,
15583                            (check_rettype || DECL_CONV_FN_P (fn)
15584                             ? TREE_TYPE (decl_type) : NULL_TREE),
15585                            DEDUCE_EXACT, LOOKUP_NORMAL))
15586     return NULL_TREE;
15587
15588   return targs;
15589 }
15590
15591 /* Return the innermost template arguments that, when applied to a
15592    template specialization whose innermost template parameters are
15593    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
15594    ARGS.
15595
15596    For example, suppose we have:
15597
15598      template <class T, class U> struct S {};
15599      template <class T> struct S<T*, int> {};
15600
15601    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
15602    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
15603    int}.  The resulting vector will be {double}, indicating that `T'
15604    is bound to `double'.  */
15605
15606 static tree
15607 get_class_bindings (tree tparms, tree spec_args, tree args)
15608 {
15609   int i, ntparms = TREE_VEC_LENGTH (tparms);
15610   tree deduced_args;
15611   tree innermost_deduced_args;
15612
15613   innermost_deduced_args = make_tree_vec (ntparms);
15614   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
15615     {
15616       deduced_args = copy_node (args);
15617       SET_TMPL_ARGS_LEVEL (deduced_args,
15618                            TMPL_ARGS_DEPTH (deduced_args),
15619                            innermost_deduced_args);
15620     }
15621   else
15622     deduced_args = innermost_deduced_args;
15623
15624   if (unify (tparms, deduced_args,
15625              INNERMOST_TEMPLATE_ARGS (spec_args),
15626              INNERMOST_TEMPLATE_ARGS (args),
15627              UNIFY_ALLOW_NONE))
15628     return NULL_TREE;
15629
15630   for (i =  0; i < ntparms; ++i)
15631     if (! TREE_VEC_ELT (innermost_deduced_args, i))
15632       return NULL_TREE;
15633
15634   /* Verify that nondeduced template arguments agree with the type
15635      obtained from argument deduction.
15636
15637      For example:
15638
15639        struct A { typedef int X; };
15640        template <class T, class U> struct C {};
15641        template <class T> struct C<T, typename T::X> {};
15642
15643      Then with the instantiation `C<A, int>', we can deduce that
15644      `T' is `A' but unify () does not check whether `typename T::X'
15645      is `int'.  */
15646   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
15647   if (spec_args == error_mark_node
15648       /* We only need to check the innermost arguments; the other
15649          arguments will always agree.  */
15650       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
15651                               INNERMOST_TEMPLATE_ARGS (args)))
15652     return NULL_TREE;
15653
15654   /* Now that we have bindings for all of the template arguments,
15655      ensure that the arguments deduced for the template template
15656      parameters have compatible template parameter lists.  See the use
15657      of template_template_parm_bindings_ok_p in fn_type_unification
15658      for more information.  */
15659   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
15660     return NULL_TREE;
15661
15662   return deduced_args;
15663 }
15664
15665 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
15666    Return the TREE_LIST node with the most specialized template, if
15667    any.  If there is no most specialized template, the error_mark_node
15668    is returned.
15669
15670    Note that this function does not look at, or modify, the
15671    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
15672    returned is one of the elements of INSTANTIATIONS, callers may
15673    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
15674    and retrieve it from the value returned.  */
15675
15676 tree
15677 most_specialized_instantiation (tree templates)
15678 {
15679   tree fn, champ;
15680
15681   ++processing_template_decl;
15682
15683   champ = templates;
15684   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
15685     {
15686       int fate = 0;
15687
15688       if (get_bindings (TREE_VALUE (champ),
15689                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
15690                         NULL_TREE, /*check_ret=*/false))
15691         fate--;
15692
15693       if (get_bindings (TREE_VALUE (fn),
15694                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
15695                         NULL_TREE, /*check_ret=*/false))
15696         fate++;
15697
15698       if (fate == -1)
15699         champ = fn;
15700       else if (!fate)
15701         {
15702           /* Equally specialized, move to next function.  If there
15703              is no next function, nothing's most specialized.  */
15704           fn = TREE_CHAIN (fn);
15705           champ = fn;
15706           if (!fn)
15707             break;
15708         }
15709     }
15710
15711   if (champ)
15712     /* Now verify that champ is better than everything earlier in the
15713        instantiation list.  */
15714     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
15715       if (get_bindings (TREE_VALUE (champ),
15716                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
15717                         NULL_TREE, /*check_ret=*/false)
15718           || !get_bindings (TREE_VALUE (fn),
15719                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
15720                             NULL_TREE, /*check_ret=*/false))
15721         {
15722           champ = NULL_TREE;
15723           break;
15724         }
15725
15726   processing_template_decl--;
15727
15728   if (!champ)
15729     return error_mark_node;
15730
15731   return champ;
15732 }
15733
15734 /* If DECL is a specialization of some template, return the most
15735    general such template.  Otherwise, returns NULL_TREE.
15736
15737    For example, given:
15738
15739      template <class T> struct S { template <class U> void f(U); };
15740
15741    if TMPL is `template <class U> void S<int>::f(U)' this will return
15742    the full template.  This function will not trace past partial
15743    specializations, however.  For example, given in addition:
15744
15745      template <class T> struct S<T*> { template <class U> void f(U); };
15746
15747    if TMPL is `template <class U> void S<int*>::f(U)' this will return
15748    `template <class T> template <class U> S<T*>::f(U)'.  */
15749
15750 tree
15751 most_general_template (tree decl)
15752 {
15753   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
15754      an immediate specialization.  */
15755   if (TREE_CODE (decl) == FUNCTION_DECL)
15756     {
15757       if (DECL_TEMPLATE_INFO (decl)) {
15758         decl = DECL_TI_TEMPLATE (decl);
15759
15760         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
15761            template friend.  */
15762         if (TREE_CODE (decl) != TEMPLATE_DECL)
15763           return NULL_TREE;
15764       } else
15765         return NULL_TREE;
15766     }
15767
15768   /* Look for more and more general templates.  */
15769   while (DECL_TEMPLATE_INFO (decl))
15770     {
15771       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
15772          (See cp-tree.h for details.)  */
15773       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
15774         break;
15775
15776       if (CLASS_TYPE_P (TREE_TYPE (decl))
15777           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
15778         break;
15779
15780       /* Stop if we run into an explicitly specialized class template.  */
15781       if (!DECL_NAMESPACE_SCOPE_P (decl)
15782           && DECL_CONTEXT (decl)
15783           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
15784         break;
15785
15786       decl = DECL_TI_TEMPLATE (decl);
15787     }
15788
15789   return decl;
15790 }
15791
15792 /* Return the most specialized of the class template partial
15793    specializations of TMPL which can produce TYPE, a specialization of
15794    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
15795    a _TYPE node corresponding to the partial specialization, while the
15796    TREE_PURPOSE is the set of template arguments that must be
15797    substituted into the TREE_TYPE in order to generate TYPE.
15798
15799    If the choice of partial specialization is ambiguous, a diagnostic
15800    is issued, and the error_mark_node is returned.  If there are no
15801    partial specializations of TMPL matching TYPE, then NULL_TREE is
15802    returned.  */
15803
15804 static tree
15805 most_specialized_class (tree type, tree tmpl)
15806 {
15807   tree list = NULL_TREE;
15808   tree t;
15809   tree champ;
15810   int fate;
15811   bool ambiguous_p;
15812   tree args;
15813   tree outer_args = NULL_TREE;
15814
15815   tmpl = most_general_template (tmpl);
15816   args = CLASSTYPE_TI_ARGS (type);
15817
15818   /* For determining which partial specialization to use, only the
15819      innermost args are interesting.  */
15820   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
15821     {
15822       outer_args = strip_innermost_template_args (args, 1);
15823       args = INNERMOST_TEMPLATE_ARGS (args);
15824     }
15825
15826   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
15827     {
15828       tree partial_spec_args;
15829       tree spec_args;
15830       tree parms = TREE_VALUE (t);
15831
15832       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
15833       if (outer_args)
15834         {
15835           int i;
15836
15837           ++processing_template_decl;
15838
15839           /* Discard the outer levels of args, and then substitute in the
15840              template args from the enclosing class.  */
15841           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
15842           partial_spec_args = tsubst_template_args
15843             (partial_spec_args, outer_args, tf_none, NULL_TREE);
15844
15845           /* PARMS already refers to just the innermost parms, but the
15846              template parms in partial_spec_args had their levels lowered
15847              by tsubst, so we need to do the same for the parm list.  We
15848              can't just tsubst the TREE_VEC itself, as tsubst wants to
15849              treat a TREE_VEC as an argument vector.  */
15850           parms = copy_node (parms);
15851           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
15852             TREE_VEC_ELT (parms, i) =
15853               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
15854
15855           --processing_template_decl;
15856         }
15857       spec_args = get_class_bindings (parms,
15858                                       partial_spec_args,
15859                                       args);
15860       if (spec_args)
15861         {
15862           if (outer_args)
15863             spec_args = add_to_template_args (outer_args, spec_args);
15864           list = tree_cons (spec_args, TREE_VALUE (t), list);
15865           TREE_TYPE (list) = TREE_TYPE (t);
15866         }
15867     }
15868
15869   if (! list)
15870     return NULL_TREE;
15871
15872   ambiguous_p = false;
15873   t = list;
15874   champ = t;
15875   t = TREE_CHAIN (t);
15876   for (; t; t = TREE_CHAIN (t))
15877     {
15878       fate = more_specialized_class (champ, t);
15879       if (fate == 1)
15880         ;
15881       else
15882         {
15883           if (fate == 0)
15884             {
15885               t = TREE_CHAIN (t);
15886               if (! t)
15887                 {
15888                   ambiguous_p = true;
15889                   break;
15890                 }
15891             }
15892           champ = t;
15893         }
15894     }
15895
15896   if (!ambiguous_p)
15897     for (t = list; t && t != champ; t = TREE_CHAIN (t))
15898       {
15899         fate = more_specialized_class (champ, t);
15900         if (fate != 1)
15901           {
15902             ambiguous_p = true;
15903             break;
15904           }
15905       }
15906
15907   if (ambiguous_p)
15908     {
15909       const char *str;
15910       char *spaces = NULL;
15911       error ("ambiguous class template instantiation for %q#T", type);
15912       str = TREE_CHAIN (list) ? _("candidates are:") : _("candidate is:");
15913       for (t = list; t; t = TREE_CHAIN (t))
15914         {
15915           error ("%s %+#T", spaces ? spaces : str, TREE_TYPE (t));
15916           spaces = spaces ? spaces : get_spaces (str);
15917         }
15918       free (spaces);
15919       return error_mark_node;
15920     }
15921
15922   return champ;
15923 }
15924
15925 /* Explicitly instantiate DECL.  */
15926
15927 void
15928 do_decl_instantiation (tree decl, tree storage)
15929 {
15930   tree result = NULL_TREE;
15931   int extern_p = 0;
15932
15933   if (!decl || decl == error_mark_node)
15934     /* An error occurred, for which grokdeclarator has already issued
15935        an appropriate message.  */
15936     return;
15937   else if (! DECL_LANG_SPECIFIC (decl))
15938     {
15939       error ("explicit instantiation of non-template %q#D", decl);
15940       return;
15941     }
15942   else if (TREE_CODE (decl) == VAR_DECL)
15943     {
15944       /* There is an asymmetry here in the way VAR_DECLs and
15945          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
15946          the latter, the DECL we get back will be marked as a
15947          template instantiation, and the appropriate
15948          DECL_TEMPLATE_INFO will be set up.  This does not happen for
15949          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
15950          should handle VAR_DECLs as it currently handles
15951          FUNCTION_DECLs.  */
15952       if (!DECL_CLASS_SCOPE_P (decl))
15953         {
15954           error ("%qD is not a static data member of a class template", decl);
15955           return;
15956         }
15957       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
15958       if (!result || TREE_CODE (result) != VAR_DECL)
15959         {
15960           error ("no matching template for %qD found", decl);
15961           return;
15962         }
15963       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
15964         {
15965           error ("type %qT for explicit instantiation %qD does not match "
15966                  "declared type %qT", TREE_TYPE (result), decl,
15967                  TREE_TYPE (decl));
15968           return;
15969         }
15970     }
15971   else if (TREE_CODE (decl) != FUNCTION_DECL)
15972     {
15973       error ("explicit instantiation of %q#D", decl);
15974       return;
15975     }
15976   else
15977     result = decl;
15978
15979   /* Check for various error cases.  Note that if the explicit
15980      instantiation is valid the RESULT will currently be marked as an
15981      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
15982      until we get here.  */
15983
15984   if (DECL_TEMPLATE_SPECIALIZATION (result))
15985     {
15986       /* DR 259 [temp.spec].
15987
15988          Both an explicit instantiation and a declaration of an explicit
15989          specialization shall not appear in a program unless the explicit
15990          instantiation follows a declaration of the explicit specialization.
15991
15992          For a given set of template parameters, if an explicit
15993          instantiation of a template appears after a declaration of an
15994          explicit specialization for that template, the explicit
15995          instantiation has no effect.  */
15996       return;
15997     }
15998   else if (DECL_EXPLICIT_INSTANTIATION (result))
15999     {
16000       /* [temp.spec]
16001
16002          No program shall explicitly instantiate any template more
16003          than once.
16004
16005          We check DECL_NOT_REALLY_EXTERN so as not to complain when
16006          the first instantiation was `extern' and the second is not,
16007          and EXTERN_P for the opposite case.  */
16008       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
16009         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
16010       /* If an "extern" explicit instantiation follows an ordinary
16011          explicit instantiation, the template is instantiated.  */
16012       if (extern_p)
16013         return;
16014     }
16015   else if (!DECL_IMPLICIT_INSTANTIATION (result))
16016     {
16017       error ("no matching template for %qD found", result);
16018       return;
16019     }
16020   else if (!DECL_TEMPLATE_INFO (result))
16021     {
16022       permerror (input_location, "explicit instantiation of non-template %q#D", result);
16023       return;
16024     }
16025
16026   if (storage == NULL_TREE)
16027     ;
16028   else if (storage == ridpointers[(int) RID_EXTERN])
16029     {
16030       if (!in_system_header && (cxx_dialect == cxx98))
16031         pedwarn (input_location, OPT_pedantic, 
16032                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
16033                  "instantiations");
16034       extern_p = 1;
16035     }
16036   else
16037     error ("storage class %qD applied to template instantiation", storage);
16038
16039   check_explicit_instantiation_namespace (result);
16040   mark_decl_instantiated (result, extern_p);
16041   if (! extern_p)
16042     instantiate_decl (result, /*defer_ok=*/1,
16043                       /*expl_inst_class_mem_p=*/false);
16044 }
16045
16046 static void
16047 mark_class_instantiated (tree t, int extern_p)
16048 {
16049   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
16050   SET_CLASSTYPE_INTERFACE_KNOWN (t);
16051   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
16052   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
16053   if (! extern_p)
16054     {
16055       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
16056       rest_of_type_compilation (t, 1);
16057     }
16058 }
16059
16060 /* Called from do_type_instantiation through binding_table_foreach to
16061    do recursive instantiation for the type bound in ENTRY.  */
16062 static void
16063 bt_instantiate_type_proc (binding_entry entry, void *data)
16064 {
16065   tree storage = *(tree *) data;
16066
16067   if (MAYBE_CLASS_TYPE_P (entry->type)
16068       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
16069     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
16070 }
16071
16072 /* Called from do_type_instantiation to instantiate a member
16073    (a member function or a static member variable) of an
16074    explicitly instantiated class template.  */
16075 static void
16076 instantiate_class_member (tree decl, int extern_p)
16077 {
16078   mark_decl_instantiated (decl, extern_p);
16079   if (! extern_p)
16080     instantiate_decl (decl, /*defer_ok=*/1,
16081                       /*expl_inst_class_mem_p=*/true);
16082 }
16083
16084 /* Perform an explicit instantiation of template class T.  STORAGE, if
16085    non-null, is the RID for extern, inline or static.  COMPLAIN is
16086    nonzero if this is called from the parser, zero if called recursively,
16087    since the standard is unclear (as detailed below).  */
16088
16089 void
16090 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
16091 {
16092   int extern_p = 0;
16093   int nomem_p = 0;
16094   int static_p = 0;
16095   int previous_instantiation_extern_p = 0;
16096
16097   if (TREE_CODE (t) == TYPE_DECL)
16098     t = TREE_TYPE (t);
16099
16100   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
16101     {
16102       error ("explicit instantiation of non-template type %qT", t);
16103       return;
16104     }
16105
16106   complete_type (t);
16107
16108   if (!COMPLETE_TYPE_P (t))
16109     {
16110       if (complain & tf_error)
16111         error ("explicit instantiation of %q#T before definition of template",
16112                t);
16113       return;
16114     }
16115
16116   if (storage != NULL_TREE)
16117     {
16118       if (!in_system_header)
16119         {
16120           if (storage == ridpointers[(int) RID_EXTERN])
16121             {
16122               if (cxx_dialect == cxx98)
16123                 pedwarn (input_location, OPT_pedantic, 
16124                          "ISO C++ 1998 forbids the use of %<extern%> on "
16125                          "explicit instantiations");
16126             }
16127           else
16128             pedwarn (input_location, OPT_pedantic, 
16129                      "ISO C++ forbids the use of %qE"
16130                      " on explicit instantiations", storage);
16131         }
16132
16133       if (storage == ridpointers[(int) RID_INLINE])
16134         nomem_p = 1;
16135       else if (storage == ridpointers[(int) RID_EXTERN])
16136         extern_p = 1;
16137       else if (storage == ridpointers[(int) RID_STATIC])
16138         static_p = 1;
16139       else
16140         {
16141           error ("storage class %qD applied to template instantiation",
16142                  storage);
16143           extern_p = 0;
16144         }
16145     }
16146
16147   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
16148     {
16149       /* DR 259 [temp.spec].
16150
16151          Both an explicit instantiation and a declaration of an explicit
16152          specialization shall not appear in a program unless the explicit
16153          instantiation follows a declaration of the explicit specialization.
16154
16155          For a given set of template parameters, if an explicit
16156          instantiation of a template appears after a declaration of an
16157          explicit specialization for that template, the explicit
16158          instantiation has no effect.  */
16159       return;
16160     }
16161   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
16162     {
16163       /* [temp.spec]
16164
16165          No program shall explicitly instantiate any template more
16166          than once.
16167
16168          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
16169          instantiation was `extern'.  If EXTERN_P then the second is.
16170          These cases are OK.  */
16171       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
16172
16173       if (!previous_instantiation_extern_p && !extern_p
16174           && (complain & tf_error))
16175         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
16176
16177       /* If we've already instantiated the template, just return now.  */
16178       if (!CLASSTYPE_INTERFACE_ONLY (t))
16179         return;
16180     }
16181
16182   check_explicit_instantiation_namespace (TYPE_NAME (t));
16183   mark_class_instantiated (t, extern_p);
16184
16185   if (nomem_p)
16186     return;
16187
16188   {
16189     tree tmp;
16190
16191     /* In contrast to implicit instantiation, where only the
16192        declarations, and not the definitions, of members are
16193        instantiated, we have here:
16194
16195          [temp.explicit]
16196
16197          The explicit instantiation of a class template specialization
16198          implies the instantiation of all of its members not
16199          previously explicitly specialized in the translation unit
16200          containing the explicit instantiation.
16201
16202        Of course, we can't instantiate member template classes, since
16203        we don't have any arguments for them.  Note that the standard
16204        is unclear on whether the instantiation of the members are
16205        *explicit* instantiations or not.  However, the most natural
16206        interpretation is that it should be an explicit instantiation.  */
16207
16208     if (! static_p)
16209       for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
16210         if (TREE_CODE (tmp) == FUNCTION_DECL
16211             && DECL_TEMPLATE_INSTANTIATION (tmp))
16212           instantiate_class_member (tmp, extern_p);
16213
16214     for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
16215       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
16216         instantiate_class_member (tmp, extern_p);
16217
16218     if (CLASSTYPE_NESTED_UTDS (t))
16219       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
16220                              bt_instantiate_type_proc, &storage);
16221   }
16222 }
16223
16224 /* Given a function DECL, which is a specialization of TMPL, modify
16225    DECL to be a re-instantiation of TMPL with the same template
16226    arguments.  TMPL should be the template into which tsubst'ing
16227    should occur for DECL, not the most general template.
16228
16229    One reason for doing this is a scenario like this:
16230
16231      template <class T>
16232      void f(const T&, int i);
16233
16234      void g() { f(3, 7); }
16235
16236      template <class T>
16237      void f(const T& t, const int i) { }
16238
16239    Note that when the template is first instantiated, with
16240    instantiate_template, the resulting DECL will have no name for the
16241    first parameter, and the wrong type for the second.  So, when we go
16242    to instantiate the DECL, we regenerate it.  */
16243
16244 static void
16245 regenerate_decl_from_template (tree decl, tree tmpl)
16246 {
16247   /* The arguments used to instantiate DECL, from the most general
16248      template.  */
16249   tree args;
16250   tree code_pattern;
16251
16252   args = DECL_TI_ARGS (decl);
16253   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
16254
16255   /* Make sure that we can see identifiers, and compute access
16256      correctly.  */
16257   push_access_scope (decl);
16258
16259   if (TREE_CODE (decl) == FUNCTION_DECL)
16260     {
16261       tree decl_parm;
16262       tree pattern_parm;
16263       tree specs;
16264       int args_depth;
16265       int parms_depth;
16266
16267       args_depth = TMPL_ARGS_DEPTH (args);
16268       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
16269       if (args_depth > parms_depth)
16270         args = get_innermost_template_args (args, parms_depth);
16271
16272       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
16273                                               args, tf_error, NULL_TREE);
16274       if (specs)
16275         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
16276                                                     specs);
16277
16278       /* Merge parameter declarations.  */
16279       decl_parm = skip_artificial_parms_for (decl,
16280                                              DECL_ARGUMENTS (decl));
16281       pattern_parm
16282         = skip_artificial_parms_for (code_pattern,
16283                                      DECL_ARGUMENTS (code_pattern));
16284       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
16285         {
16286           tree parm_type;
16287           tree attributes;
16288           
16289           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16290             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
16291           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
16292                               NULL_TREE);
16293           parm_type = type_decays_to (parm_type);
16294           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16295             TREE_TYPE (decl_parm) = parm_type;
16296           attributes = DECL_ATTRIBUTES (pattern_parm);
16297           if (DECL_ATTRIBUTES (decl_parm) != attributes)
16298             {
16299               DECL_ATTRIBUTES (decl_parm) = attributes;
16300               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16301             }
16302           decl_parm = TREE_CHAIN (decl_parm);
16303           pattern_parm = TREE_CHAIN (pattern_parm);
16304         }
16305       /* Merge any parameters that match with the function parameter
16306          pack.  */
16307       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
16308         {
16309           int i, len;
16310           tree expanded_types;
16311           /* Expand the TYPE_PACK_EXPANSION that provides the types for
16312              the parameters in this function parameter pack.  */
16313           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
16314                                                  args, tf_error, NULL_TREE);
16315           len = TREE_VEC_LENGTH (expanded_types);
16316           for (i = 0; i < len; i++)
16317             {
16318               tree parm_type;
16319               tree attributes;
16320           
16321               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16322                 /* Rename the parameter to include the index.  */
16323                 DECL_NAME (decl_parm) = 
16324                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
16325               parm_type = TREE_VEC_ELT (expanded_types, i);
16326               parm_type = type_decays_to (parm_type);
16327               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16328                 TREE_TYPE (decl_parm) = parm_type;
16329               attributes = DECL_ATTRIBUTES (pattern_parm);
16330               if (DECL_ATTRIBUTES (decl_parm) != attributes)
16331                 {
16332                   DECL_ATTRIBUTES (decl_parm) = attributes;
16333                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16334                 }
16335               decl_parm = TREE_CHAIN (decl_parm);
16336             }
16337         }
16338       /* Merge additional specifiers from the CODE_PATTERN.  */
16339       if (DECL_DECLARED_INLINE_P (code_pattern)
16340           && !DECL_DECLARED_INLINE_P (decl))
16341         DECL_DECLARED_INLINE_P (decl) = 1;
16342     }
16343   else if (TREE_CODE (decl) == VAR_DECL)
16344     DECL_INITIAL (decl) =
16345       tsubst_expr (DECL_INITIAL (code_pattern), args,
16346                    tf_error, DECL_TI_TEMPLATE (decl),
16347                    /*integral_constant_expression_p=*/false);
16348   else
16349     gcc_unreachable ();
16350
16351   pop_access_scope (decl);
16352 }
16353
16354 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
16355    substituted to get DECL.  */
16356
16357 tree
16358 template_for_substitution (tree decl)
16359 {
16360   tree tmpl = DECL_TI_TEMPLATE (decl);
16361
16362   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
16363      for the instantiation.  This is not always the most general
16364      template.  Consider, for example:
16365
16366         template <class T>
16367         struct S { template <class U> void f();
16368                    template <> void f<int>(); };
16369
16370      and an instantiation of S<double>::f<int>.  We want TD to be the
16371      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
16372   while (/* An instantiation cannot have a definition, so we need a
16373             more general template.  */
16374          DECL_TEMPLATE_INSTANTIATION (tmpl)
16375            /* We must also deal with friend templates.  Given:
16376
16377                 template <class T> struct S {
16378                   template <class U> friend void f() {};
16379                 };
16380
16381               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
16382               so far as the language is concerned, but that's still
16383               where we get the pattern for the instantiation from.  On
16384               other hand, if the definition comes outside the class, say:
16385
16386                 template <class T> struct S {
16387                   template <class U> friend void f();
16388                 };
16389                 template <class U> friend void f() {}
16390
16391               we don't need to look any further.  That's what the check for
16392               DECL_INITIAL is for.  */
16393           || (TREE_CODE (decl) == FUNCTION_DECL
16394               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
16395               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
16396     {
16397       /* The present template, TD, should not be a definition.  If it
16398          were a definition, we should be using it!  Note that we
16399          cannot restructure the loop to just keep going until we find
16400          a template with a definition, since that might go too far if
16401          a specialization was declared, but not defined.  */
16402       gcc_assert (TREE_CODE (decl) != VAR_DECL
16403                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
16404
16405       /* Fetch the more general template.  */
16406       tmpl = DECL_TI_TEMPLATE (tmpl);
16407     }
16408
16409   return tmpl;
16410 }
16411
16412 /* Returns true if we need to instantiate this template instance even if we
16413    know we aren't going to emit it..  */
16414
16415 bool
16416 always_instantiate_p (tree decl)
16417 {
16418   /* We always instantiate inline functions so that we can inline them.  An
16419      explicit instantiation declaration prohibits implicit instantiation of
16420      non-inline functions.  With high levels of optimization, we would
16421      normally inline non-inline functions -- but we're not allowed to do
16422      that for "extern template" functions.  Therefore, we check
16423      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
16424   return ((TREE_CODE (decl) == FUNCTION_DECL
16425            && DECL_DECLARED_INLINE_P (decl))
16426           /* And we need to instantiate static data members so that
16427              their initializers are available in integral constant
16428              expressions.  */
16429           || (TREE_CODE (decl) == VAR_DECL
16430               && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl)));
16431 }
16432
16433 /* Produce the definition of D, a _DECL generated from a template.  If
16434    DEFER_OK is nonzero, then we don't have to actually do the
16435    instantiation now; we just have to do it sometime.  Normally it is
16436    an error if this is an explicit instantiation but D is undefined.
16437    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
16438    explicitly instantiated class template.  */
16439
16440 tree
16441 instantiate_decl (tree d, int defer_ok,
16442                   bool expl_inst_class_mem_p)
16443 {
16444   tree tmpl = DECL_TI_TEMPLATE (d);
16445   tree gen_args;
16446   tree args;
16447   tree td;
16448   tree code_pattern;
16449   tree spec;
16450   tree gen_tmpl;
16451   bool pattern_defined;
16452   int need_push;
16453   location_t saved_loc = input_location;
16454   bool external_p;
16455
16456   /* This function should only be used to instantiate templates for
16457      functions and static member variables.  */
16458   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
16459               || TREE_CODE (d) == VAR_DECL);
16460
16461   /* Variables are never deferred; if instantiation is required, they
16462      are instantiated right away.  That allows for better code in the
16463      case that an expression refers to the value of the variable --
16464      if the variable has a constant value the referring expression can
16465      take advantage of that fact.  */
16466   if (TREE_CODE (d) == VAR_DECL)
16467     defer_ok = 0;
16468
16469   /* Don't instantiate cloned functions.  Instead, instantiate the
16470      functions they cloned.  */
16471   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
16472     d = DECL_CLONED_FUNCTION (d);
16473
16474   if (DECL_TEMPLATE_INSTANTIATED (d)
16475       || DECL_TEMPLATE_SPECIALIZATION (d))
16476     /* D has already been instantiated or explicitly specialized, so
16477        there's nothing for us to do here.
16478
16479        It might seem reasonable to check whether or not D is an explicit
16480        instantiation, and, if so, stop here.  But when an explicit
16481        instantiation is deferred until the end of the compilation,
16482        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
16483        the instantiation.  */
16484     return d;
16485
16486   /* Check to see whether we know that this template will be
16487      instantiated in some other file, as with "extern template"
16488      extension.  */
16489   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
16490
16491   /* In general, we do not instantiate such templates.  */
16492   if (external_p && !always_instantiate_p (d))
16493     return d;
16494
16495   gen_tmpl = most_general_template (tmpl);
16496   gen_args = DECL_TI_ARGS (d);
16497
16498   if (tmpl != gen_tmpl)
16499     /* We should already have the extra args.  */
16500     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
16501                 == TMPL_ARGS_DEPTH (gen_args));
16502   /* And what's in the hash table should match D.  */
16503   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
16504               || spec == NULL_TREE);
16505
16506   /* This needs to happen before any tsubsting.  */
16507   if (! push_tinst_level (d))
16508     return d;
16509
16510   timevar_push (TV_PARSE);
16511
16512   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
16513      for the instantiation.  */
16514   td = template_for_substitution (d);
16515   code_pattern = DECL_TEMPLATE_RESULT (td);
16516
16517   /* We should never be trying to instantiate a member of a class
16518      template or partial specialization.  */
16519   gcc_assert (d != code_pattern);
16520
16521   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
16522       || DECL_TEMPLATE_SPECIALIZATION (td))
16523     /* In the case of a friend template whose definition is provided
16524        outside the class, we may have too many arguments.  Drop the
16525        ones we don't need.  The same is true for specializations.  */
16526     args = get_innermost_template_args
16527       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
16528   else
16529     args = gen_args;
16530
16531   if (TREE_CODE (d) == FUNCTION_DECL)
16532     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
16533   else
16534     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
16535
16536   /* We may be in the middle of deferred access check.  Disable it now.  */
16537   push_deferring_access_checks (dk_no_deferred);
16538
16539   /* Unless an explicit instantiation directive has already determined
16540      the linkage of D, remember that a definition is available for
16541      this entity.  */
16542   if (pattern_defined
16543       && !DECL_INTERFACE_KNOWN (d)
16544       && !DECL_NOT_REALLY_EXTERN (d))
16545     mark_definable (d);
16546
16547   input_location = DECL_SOURCE_LOCATION (d);
16548
16549   /* If D is a member of an explicitly instantiated class template,
16550      and no definition is available, treat it like an implicit
16551      instantiation.  */
16552   if (!pattern_defined && expl_inst_class_mem_p
16553       && DECL_EXPLICIT_INSTANTIATION (d))
16554     {
16555       DECL_NOT_REALLY_EXTERN (d) = 0;
16556       DECL_INTERFACE_KNOWN (d) = 0;
16557       SET_DECL_IMPLICIT_INSTANTIATION (d);
16558     }
16559
16560   /* Recheck the substitutions to obtain any warning messages
16561      about ignoring cv qualifiers.  Don't do this for artificial decls,
16562      as it breaks the context-sensitive substitution for lambda op(). */
16563   if (!defer_ok && !DECL_ARTIFICIAL (d))
16564     {
16565       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
16566       tree type = TREE_TYPE (gen);
16567
16568       /* Make sure that we can see identifiers, and compute access
16569          correctly.  D is already the target FUNCTION_DECL with the
16570          right context.  */
16571       push_access_scope (d);
16572
16573       if (TREE_CODE (gen) == FUNCTION_DECL)
16574         {
16575           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
16576           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
16577                                           d);
16578           /* Don't simply tsubst the function type, as that will give
16579              duplicate warnings about poor parameter qualifications.
16580              The function arguments are the same as the decl_arguments
16581              without the top level cv qualifiers.  */
16582           type = TREE_TYPE (type);
16583         }
16584       tsubst (type, gen_args, tf_warning_or_error, d);
16585
16586       pop_access_scope (d);
16587     }
16588
16589   /* Defer all other templates, unless we have been explicitly
16590      forbidden from doing so.  */
16591   if (/* If there is no definition, we cannot instantiate the
16592          template.  */
16593       ! pattern_defined
16594       /* If it's OK to postpone instantiation, do so.  */
16595       || defer_ok
16596       /* If this is a static data member that will be defined
16597          elsewhere, we don't want to instantiate the entire data
16598          member, but we do want to instantiate the initializer so that
16599          we can substitute that elsewhere.  */
16600       || (external_p && TREE_CODE (d) == VAR_DECL))
16601     {
16602       /* The definition of the static data member is now required so
16603          we must substitute the initializer.  */
16604       if (TREE_CODE (d) == VAR_DECL
16605           && !DECL_INITIAL (d)
16606           && DECL_INITIAL (code_pattern))
16607         {
16608           tree ns;
16609           tree init;
16610
16611           ns = decl_namespace_context (d);
16612           push_nested_namespace (ns);
16613           push_nested_class (DECL_CONTEXT (d));
16614           init = tsubst_expr (DECL_INITIAL (code_pattern),
16615                               args,
16616                               tf_warning_or_error, NULL_TREE,
16617                               /*integral_constant_expression_p=*/false);
16618           cp_finish_decl (d, init, /*init_const_expr_p=*/false,
16619                           /*asmspec_tree=*/NULL_TREE,
16620                           LOOKUP_ONLYCONVERTING);
16621           pop_nested_class ();
16622           pop_nested_namespace (ns);
16623         }
16624
16625       /* We restore the source position here because it's used by
16626          add_pending_template.  */
16627       input_location = saved_loc;
16628
16629       if (at_eof && !pattern_defined
16630           && DECL_EXPLICIT_INSTANTIATION (d)
16631           && DECL_NOT_REALLY_EXTERN (d))
16632         /* [temp.explicit]
16633
16634            The definition of a non-exported function template, a
16635            non-exported member function template, or a non-exported
16636            member function or static data member of a class template
16637            shall be present in every translation unit in which it is
16638            explicitly instantiated.  */
16639         permerror (input_location,  "explicit instantiation of %qD "
16640                    "but no definition available", d);
16641
16642       /* ??? Historically, we have instantiated inline functions, even
16643          when marked as "extern template".  */
16644       if (!(external_p && TREE_CODE (d) == VAR_DECL))
16645         add_pending_template (d);
16646       goto out;
16647     }
16648   /* Tell the repository that D is available in this translation unit
16649      -- and see if it is supposed to be instantiated here.  */
16650   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
16651     {
16652       /* In a PCH file, despite the fact that the repository hasn't
16653          requested instantiation in the PCH it is still possible that
16654          an instantiation will be required in a file that includes the
16655          PCH.  */
16656       if (pch_file)
16657         add_pending_template (d);
16658       /* Instantiate inline functions so that the inliner can do its
16659          job, even though we'll not be emitting a copy of this
16660          function.  */
16661       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
16662         goto out;
16663     }
16664
16665   need_push = !cfun || !global_bindings_p ();
16666   if (need_push)
16667     push_to_top_level ();
16668
16669   /* Mark D as instantiated so that recursive calls to
16670      instantiate_decl do not try to instantiate it again.  */
16671   DECL_TEMPLATE_INSTANTIATED (d) = 1;
16672
16673   /* Regenerate the declaration in case the template has been modified
16674      by a subsequent redeclaration.  */
16675   regenerate_decl_from_template (d, td);
16676
16677   /* We already set the file and line above.  Reset them now in case
16678      they changed as a result of calling regenerate_decl_from_template.  */
16679   input_location = DECL_SOURCE_LOCATION (d);
16680
16681   if (TREE_CODE (d) == VAR_DECL)
16682     {
16683       tree init;
16684
16685       /* Clear out DECL_RTL; whatever was there before may not be right
16686          since we've reset the type of the declaration.  */
16687       SET_DECL_RTL (d, NULL_RTX);
16688       DECL_IN_AGGR_P (d) = 0;
16689
16690       /* The initializer is placed in DECL_INITIAL by
16691          regenerate_decl_from_template.  Pull it out so that
16692          cp_finish_decl can process it.  */
16693       init = DECL_INITIAL (d);
16694       DECL_INITIAL (d) = NULL_TREE;
16695       DECL_INITIALIZED_P (d) = 0;
16696
16697       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
16698          initializer.  That function will defer actual emission until
16699          we have a chance to determine linkage.  */
16700       DECL_EXTERNAL (d) = 0;
16701
16702       /* Enter the scope of D so that access-checking works correctly.  */
16703       push_nested_class (DECL_CONTEXT (d));
16704       cp_finish_decl (d, init, false, NULL_TREE, 0);
16705       pop_nested_class ();
16706     }
16707   else if (TREE_CODE (d) == FUNCTION_DECL)
16708     {
16709       htab_t saved_local_specializations;
16710       tree subst_decl;
16711       tree tmpl_parm;
16712       tree spec_parm;
16713
16714       /* Save away the current list, in case we are instantiating one
16715          template from within the body of another.  */
16716       saved_local_specializations = local_specializations;
16717
16718       /* Set up the list of local specializations.  */
16719       local_specializations = htab_create (37,
16720                                            hash_local_specialization,
16721                                            eq_local_specializations,
16722                                            NULL);
16723
16724       /* Set up context.  */
16725       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
16726
16727       /* Create substitution entries for the parameters.  */
16728       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
16729       tmpl_parm = DECL_ARGUMENTS (subst_decl);
16730       spec_parm = DECL_ARGUMENTS (d);
16731       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
16732         {
16733           register_local_specialization (spec_parm, tmpl_parm);
16734           spec_parm = skip_artificial_parms_for (d, spec_parm);
16735           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
16736         }
16737       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
16738         {
16739           register_local_specialization (spec_parm, tmpl_parm);
16740           tmpl_parm = TREE_CHAIN (tmpl_parm);
16741           spec_parm = TREE_CHAIN (spec_parm);
16742         }
16743       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
16744         {
16745           /* Register the (value) argument pack as a specialization of
16746              TMPL_PARM, then move on.  */
16747           tree argpack = make_fnparm_pack (spec_parm);
16748           register_local_specialization (argpack, tmpl_parm);
16749           tmpl_parm = TREE_CHAIN (tmpl_parm);
16750           spec_parm = NULL_TREE;
16751         }
16752       gcc_assert (!spec_parm);
16753
16754       /* Substitute into the body of the function.  */
16755       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
16756                    tf_warning_or_error, tmpl,
16757                    /*integral_constant_expression_p=*/false);
16758
16759       /* Set the current input_location to the end of the function
16760          so that finish_function knows where we are.  */
16761       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
16762
16763       /* We don't need the local specializations any more.  */
16764       htab_delete (local_specializations);
16765       local_specializations = saved_local_specializations;
16766
16767       /* Finish the function.  */
16768       d = finish_function (0);
16769       expand_or_defer_fn (d);
16770     }
16771
16772   /* We're not deferring instantiation any more.  */
16773   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
16774
16775   if (need_push)
16776     pop_from_top_level ();
16777
16778 out:
16779   input_location = saved_loc;
16780   pop_deferring_access_checks ();
16781   pop_tinst_level ();
16782
16783   timevar_pop (TV_PARSE);
16784
16785   return d;
16786 }
16787
16788 /* Run through the list of templates that we wish we could
16789    instantiate, and instantiate any we can.  RETRIES is the
16790    number of times we retry pending template instantiation.  */
16791
16792 void
16793 instantiate_pending_templates (int retries)
16794 {
16795   int reconsider;
16796   location_t saved_loc = input_location;
16797
16798   /* Instantiating templates may trigger vtable generation.  This in turn
16799      may require further template instantiations.  We place a limit here
16800      to avoid infinite loop.  */
16801   if (pending_templates && retries >= max_tinst_depth)
16802     {
16803       tree decl = pending_templates->tinst->decl;
16804
16805       error ("template instantiation depth exceeds maximum of %d"
16806              " instantiating %q+D, possibly from virtual table generation"
16807              " (use -ftemplate-depth-NN to increase the maximum)",
16808              max_tinst_depth, decl);
16809       if (TREE_CODE (decl) == FUNCTION_DECL)
16810         /* Pretend that we defined it.  */
16811         DECL_INITIAL (decl) = error_mark_node;
16812       return;
16813     }
16814
16815   do
16816     {
16817       struct pending_template **t = &pending_templates;
16818       struct pending_template *last = NULL;
16819       reconsider = 0;
16820       while (*t)
16821         {
16822           tree instantiation = reopen_tinst_level ((*t)->tinst);
16823           bool complete = false;
16824
16825           if (TYPE_P (instantiation))
16826             {
16827               tree fn;
16828
16829               if (!COMPLETE_TYPE_P (instantiation))
16830                 {
16831                   instantiate_class_template (instantiation);
16832                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
16833                     for (fn = TYPE_METHODS (instantiation);
16834                          fn;
16835                          fn = TREE_CHAIN (fn))
16836                       if (! DECL_ARTIFICIAL (fn))
16837                         instantiate_decl (fn,
16838                                           /*defer_ok=*/0,
16839                                           /*expl_inst_class_mem_p=*/false);
16840                   if (COMPLETE_TYPE_P (instantiation))
16841                     reconsider = 1;
16842                 }
16843
16844               complete = COMPLETE_TYPE_P (instantiation);
16845             }
16846           else
16847             {
16848               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
16849                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
16850                 {
16851                   instantiation
16852                     = instantiate_decl (instantiation,
16853                                         /*defer_ok=*/0,
16854                                         /*expl_inst_class_mem_p=*/false);
16855                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
16856                     reconsider = 1;
16857                 }
16858
16859               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
16860                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
16861             }
16862
16863           if (complete)
16864             /* If INSTANTIATION has been instantiated, then we don't
16865                need to consider it again in the future.  */
16866             *t = (*t)->next;
16867           else
16868             {
16869               last = *t;
16870               t = &(*t)->next;
16871             }
16872           tinst_depth = 0;
16873           current_tinst_level = NULL;
16874         }
16875       last_pending_template = last;
16876     }
16877   while (reconsider);
16878
16879   input_location = saved_loc;
16880 }
16881
16882 /* Substitute ARGVEC into T, which is a list of initializers for
16883    either base class or a non-static data member.  The TREE_PURPOSEs
16884    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
16885    instantiate_decl.  */
16886
16887 static tree
16888 tsubst_initializer_list (tree t, tree argvec)
16889 {
16890   tree inits = NULL_TREE;
16891
16892   for (; t; t = TREE_CHAIN (t))
16893     {
16894       tree decl;
16895       tree init;
16896       tree expanded_bases = NULL_TREE;
16897       tree expanded_arguments = NULL_TREE;
16898       int i, len = 1;
16899
16900       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
16901         {
16902           tree expr;
16903           tree arg;
16904
16905           /* Expand the base class expansion type into separate base
16906              classes.  */
16907           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
16908                                                  tf_warning_or_error,
16909                                                  NULL_TREE);
16910           if (expanded_bases == error_mark_node)
16911             continue;
16912           
16913           /* We'll be building separate TREE_LISTs of arguments for
16914              each base.  */
16915           len = TREE_VEC_LENGTH (expanded_bases);
16916           expanded_arguments = make_tree_vec (len);
16917           for (i = 0; i < len; i++)
16918             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
16919
16920           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
16921              expand each argument in the TREE_VALUE of t.  */
16922           expr = make_node (EXPR_PACK_EXPANSION);
16923           PACK_EXPANSION_PARAMETER_PACKS (expr) =
16924             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
16925
16926           if (TREE_VALUE (t) == void_type_node)
16927             /* VOID_TYPE_NODE is used to indicate
16928                value-initialization.  */
16929             {
16930               for (i = 0; i < len; i++)
16931                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
16932             }
16933           else
16934             {
16935               /* Substitute parameter packs into each argument in the
16936                  TREE_LIST.  */
16937               in_base_initializer = 1;
16938               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
16939                 {
16940                   tree expanded_exprs;
16941
16942                   /* Expand the argument.  */
16943                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
16944                   expanded_exprs 
16945                     = tsubst_pack_expansion (expr, argvec,
16946                                              tf_warning_or_error,
16947                                              NULL_TREE);
16948                   if (expanded_exprs == error_mark_node)
16949                     continue;
16950
16951                   /* Prepend each of the expanded expressions to the
16952                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
16953                   for (i = 0; i < len; i++)
16954                     {
16955                       TREE_VEC_ELT (expanded_arguments, i) = 
16956                         tree_cons (NULL_TREE, 
16957                                    TREE_VEC_ELT (expanded_exprs, i),
16958                                    TREE_VEC_ELT (expanded_arguments, i));
16959                     }
16960                 }
16961               in_base_initializer = 0;
16962
16963               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
16964                  since we built them backwards.  */
16965               for (i = 0; i < len; i++)
16966                 {
16967                   TREE_VEC_ELT (expanded_arguments, i) = 
16968                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
16969                 }
16970             }
16971         }
16972
16973       for (i = 0; i < len; ++i)
16974         {
16975           if (expanded_bases)
16976             {
16977               decl = TREE_VEC_ELT (expanded_bases, i);
16978               decl = expand_member_init (decl);
16979               init = TREE_VEC_ELT (expanded_arguments, i);
16980             }
16981           else
16982             {
16983               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
16984                                   tf_warning_or_error, NULL_TREE);
16985
16986               decl = expand_member_init (decl);
16987               if (decl && !DECL_P (decl))
16988                 in_base_initializer = 1;
16989
16990               init = tsubst_expr (TREE_VALUE (t), argvec, 
16991                                   tf_warning_or_error, NULL_TREE,
16992                                   /*integral_constant_expression_p=*/false);
16993               in_base_initializer = 0;
16994             }
16995
16996           if (decl)
16997             {
16998               init = build_tree_list (decl, init);
16999               TREE_CHAIN (init) = inits;
17000               inits = init;
17001             }
17002         }
17003     }
17004   return inits;
17005 }
17006
17007 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
17008
17009 static void
17010 set_current_access_from_decl (tree decl)
17011 {
17012   if (TREE_PRIVATE (decl))
17013     current_access_specifier = access_private_node;
17014   else if (TREE_PROTECTED (decl))
17015     current_access_specifier = access_protected_node;
17016   else
17017     current_access_specifier = access_public_node;
17018 }
17019
17020 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
17021    is the instantiation (which should have been created with
17022    start_enum) and ARGS are the template arguments to use.  */
17023
17024 static void
17025 tsubst_enum (tree tag, tree newtag, tree args)
17026 {
17027   tree e;
17028
17029   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
17030     {
17031       tree value;
17032       tree decl;
17033
17034       decl = TREE_VALUE (e);
17035       /* Note that in a template enum, the TREE_VALUE is the
17036          CONST_DECL, not the corresponding INTEGER_CST.  */
17037       value = tsubst_expr (DECL_INITIAL (decl),
17038                            args, tf_warning_or_error, NULL_TREE,
17039                            /*integral_constant_expression_p=*/true);
17040
17041       /* Give this enumeration constant the correct access.  */
17042       set_current_access_from_decl (decl);
17043
17044       /* Actually build the enumerator itself.  */
17045       build_enumerator (DECL_NAME (decl), value, newtag);
17046     }
17047
17048   finish_enum (newtag);
17049   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
17050     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
17051 }
17052
17053 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
17054    its type -- but without substituting the innermost set of template
17055    arguments.  So, innermost set of template parameters will appear in
17056    the type.  */
17057
17058 tree
17059 get_mostly_instantiated_function_type (tree decl)
17060 {
17061   tree fn_type;
17062   tree tmpl;
17063   tree targs;
17064   tree tparms;
17065   int parm_depth;
17066
17067   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
17068   targs = DECL_TI_ARGS (decl);
17069   tparms = DECL_TEMPLATE_PARMS (tmpl);
17070   parm_depth = TMPL_PARMS_DEPTH (tparms);
17071
17072   /* There should be as many levels of arguments as there are levels
17073      of parameters.  */
17074   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
17075
17076   fn_type = TREE_TYPE (tmpl);
17077
17078   if (parm_depth == 1)
17079     /* No substitution is necessary.  */
17080     ;
17081   else
17082     {
17083       int i, save_access_control;
17084       tree partial_args;
17085
17086       /* Replace the innermost level of the TARGS with NULL_TREEs to
17087          let tsubst know not to substitute for those parameters.  */
17088       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
17089       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
17090         SET_TMPL_ARGS_LEVEL (partial_args, i,
17091                              TMPL_ARGS_LEVEL (targs, i));
17092       SET_TMPL_ARGS_LEVEL (partial_args,
17093                            TMPL_ARGS_DEPTH (targs),
17094                            make_tree_vec (DECL_NTPARMS (tmpl)));
17095
17096       /* Disable access control as this function is used only during
17097          name-mangling.  */
17098       save_access_control = flag_access_control;
17099       flag_access_control = 0;
17100
17101       ++processing_template_decl;
17102       /* Now, do the (partial) substitution to figure out the
17103          appropriate function type.  */
17104       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
17105       --processing_template_decl;
17106
17107       /* Substitute into the template parameters to obtain the real
17108          innermost set of parameters.  This step is important if the
17109          innermost set of template parameters contains value
17110          parameters whose types depend on outer template parameters.  */
17111       TREE_VEC_LENGTH (partial_args)--;
17112       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
17113
17114       flag_access_control = save_access_control;
17115     }
17116
17117   return fn_type;
17118 }
17119
17120 /* Return truthvalue if we're processing a template different from
17121    the last one involved in diagnostics.  */
17122 int
17123 problematic_instantiation_changed (void)
17124 {
17125   return last_template_error_tick != tinst_level_tick;
17126 }
17127
17128 /* Remember current template involved in diagnostics.  */
17129 void
17130 record_last_problematic_instantiation (void)
17131 {
17132   last_template_error_tick = tinst_level_tick;
17133 }
17134
17135 struct tinst_level *
17136 current_instantiation (void)
17137 {
17138   return current_tinst_level;
17139 }
17140
17141 /* [temp.param] Check that template non-type parm TYPE is of an allowable
17142    type. Return zero for ok, nonzero for disallowed. Issue error and
17143    warning messages under control of COMPLAIN.  */
17144
17145 static int
17146 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
17147 {
17148   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
17149     return 0;
17150   else if (POINTER_TYPE_P (type))
17151     return 0;
17152   else if (TYPE_PTR_TO_MEMBER_P (type))
17153     return 0;
17154   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
17155     return 0;
17156   else if (TREE_CODE (type) == TYPENAME_TYPE)
17157     return 0;
17158
17159   if (complain & tf_error)
17160     error ("%q#T is not a valid type for a template constant parameter", type);
17161   return 1;
17162 }
17163
17164 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
17165    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
17166
17167 static bool
17168 dependent_type_p_r (tree type)
17169 {
17170   tree scope;
17171
17172   /* [temp.dep.type]
17173
17174      A type is dependent if it is:
17175
17176      -- a template parameter. Template template parameters are types
17177         for us (since TYPE_P holds true for them) so we handle
17178         them here.  */
17179   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
17180       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
17181     return true;
17182   /* -- a qualified-id with a nested-name-specifier which contains a
17183         class-name that names a dependent type or whose unqualified-id
17184         names a dependent type.  */
17185   if (TREE_CODE (type) == TYPENAME_TYPE)
17186     return true;
17187   /* -- a cv-qualified type where the cv-unqualified type is
17188         dependent.  */
17189   type = TYPE_MAIN_VARIANT (type);
17190   /* -- a compound type constructed from any dependent type.  */
17191   if (TYPE_PTR_TO_MEMBER_P (type))
17192     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
17193             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
17194                                            (type)));
17195   else if (TREE_CODE (type) == POINTER_TYPE
17196            || TREE_CODE (type) == REFERENCE_TYPE)
17197     return dependent_type_p (TREE_TYPE (type));
17198   else if (TREE_CODE (type) == FUNCTION_TYPE
17199            || TREE_CODE (type) == METHOD_TYPE)
17200     {
17201       tree arg_type;
17202
17203       if (dependent_type_p (TREE_TYPE (type)))
17204         return true;
17205       for (arg_type = TYPE_ARG_TYPES (type);
17206            arg_type;
17207            arg_type = TREE_CHAIN (arg_type))
17208         if (dependent_type_p (TREE_VALUE (arg_type)))
17209           return true;
17210       return false;
17211     }
17212   /* -- an array type constructed from any dependent type or whose
17213         size is specified by a constant expression that is
17214         value-dependent.  */
17215   if (TREE_CODE (type) == ARRAY_TYPE)
17216     {
17217       if (TYPE_DOMAIN (type)
17218           && dependent_type_p (TYPE_DOMAIN (type)))
17219         return true;
17220       return dependent_type_p (TREE_TYPE (type));
17221     }
17222   else if (TREE_CODE (type) == INTEGER_TYPE
17223            && !TREE_CONSTANT (TYPE_MAX_VALUE (type)))
17224     {
17225       /* If this is the TYPE_DOMAIN of an array type, consider it
17226          dependent.  We already checked for value-dependence in
17227          compute_array_index_type.  */
17228       return type_dependent_expression_p (TYPE_MAX_VALUE (type));
17229     }
17230
17231   /* -- a template-id in which either the template name is a template
17232      parameter ...  */
17233   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
17234     return true;
17235   /* ... or any of the template arguments is a dependent type or
17236         an expression that is type-dependent or value-dependent.  */
17237   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
17238            && (any_dependent_template_arguments_p
17239                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
17240     return true;
17241
17242   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
17243      argument of the `typeof' expression is not type-dependent, then
17244      it should already been have resolved.  */
17245   if (TREE_CODE (type) == TYPEOF_TYPE
17246       || TREE_CODE (type) == DECLTYPE_TYPE)
17247     return true;
17248
17249   /* A template argument pack is dependent if any of its packed
17250      arguments are.  */
17251   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
17252     {
17253       tree args = ARGUMENT_PACK_ARGS (type);
17254       int i, len = TREE_VEC_LENGTH (args);
17255       for (i = 0; i < len; ++i)
17256         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
17257           return true;
17258     }
17259
17260   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
17261      be template parameters.  */
17262   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
17263     return true;
17264
17265   /* The standard does not specifically mention types that are local
17266      to template functions or local classes, but they should be
17267      considered dependent too.  For example:
17268
17269        template <int I> void f() {
17270          enum E { a = I };
17271          S<sizeof (E)> s;
17272        }
17273
17274      The size of `E' cannot be known until the value of `I' has been
17275      determined.  Therefore, `E' must be considered dependent.  */
17276   scope = TYPE_CONTEXT (type);
17277   if (scope && TYPE_P (scope))
17278     return dependent_type_p (scope);
17279   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
17280     return type_dependent_expression_p (scope);
17281
17282   /* Other types are non-dependent.  */
17283   return false;
17284 }
17285
17286 /* Returns TRUE if TYPE is dependent, in the sense of
17287    [temp.dep.type].  */
17288
17289 bool
17290 dependent_type_p (tree type)
17291 {
17292   /* If there are no template parameters in scope, then there can't be
17293      any dependent types.  */
17294   if (!processing_template_decl)
17295     {
17296       /* If we are not processing a template, then nobody should be
17297          providing us with a dependent type.  */
17298       gcc_assert (type);
17299       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
17300       return false;
17301     }
17302
17303   /* If the type is NULL, we have not computed a type for the entity
17304      in question; in that case, the type is dependent.  */
17305   if (!type)
17306     return true;
17307
17308   /* Erroneous types can be considered non-dependent.  */
17309   if (type == error_mark_node)
17310     return false;
17311
17312   /* If we have not already computed the appropriate value for TYPE,
17313      do so now.  */
17314   if (!TYPE_DEPENDENT_P_VALID (type))
17315     {
17316       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
17317       TYPE_DEPENDENT_P_VALID (type) = 1;
17318     }
17319
17320   return TYPE_DEPENDENT_P (type);
17321 }
17322
17323 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
17324    lookup.  In other words, a dependent type that is not the current
17325    instantiation.  */
17326
17327 bool
17328 dependent_scope_p (tree scope)
17329 {
17330   return (scope && TYPE_P (scope) && dependent_type_p (scope)
17331           && !currently_open_class (scope));
17332 }
17333
17334 /* Returns TRUE if EXPRESSION is dependent, according to CRITERION.  */
17335
17336 static bool
17337 dependent_scope_ref_p (tree expression, bool criterion (tree))
17338 {
17339   tree scope;
17340   tree name;
17341
17342   gcc_assert (TREE_CODE (expression) == SCOPE_REF);
17343
17344   if (!TYPE_P (TREE_OPERAND (expression, 0)))
17345     return true;
17346
17347   scope = TREE_OPERAND (expression, 0);
17348   name = TREE_OPERAND (expression, 1);
17349
17350   /* [temp.dep.expr]
17351
17352      An id-expression is type-dependent if it contains a
17353      nested-name-specifier that contains a class-name that names a
17354      dependent type.  */
17355   /* The suggested resolution to Core Issue 224 implies that if the
17356      qualifying type is the current class, then we must peek
17357      inside it.  */
17358   if (DECL_P (name)
17359       && currently_open_class (scope)
17360       && !criterion (name))
17361     return false;
17362   if (dependent_type_p (scope))
17363     return true;
17364
17365   return false;
17366 }
17367
17368 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
17369    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
17370    expression.  */
17371
17372 bool
17373 value_dependent_expression_p (tree expression)
17374 {
17375   if (!processing_template_decl)
17376     return false;
17377
17378   /* A name declared with a dependent type.  */
17379   if (DECL_P (expression) && type_dependent_expression_p (expression))
17380     return true;
17381
17382   switch (TREE_CODE (expression))
17383     {
17384     case IDENTIFIER_NODE:
17385       /* A name that has not been looked up -- must be dependent.  */
17386       return true;
17387
17388     case TEMPLATE_PARM_INDEX:
17389       /* A non-type template parm.  */
17390       return true;
17391
17392     case CONST_DECL:
17393       /* A non-type template parm.  */
17394       if (DECL_TEMPLATE_PARM_P (expression))
17395         return true;
17396       return value_dependent_expression_p (DECL_INITIAL (expression));
17397
17398     case VAR_DECL:
17399        /* A constant with integral or enumeration type and is initialized
17400           with an expression that is value-dependent.  */
17401       if (DECL_INITIAL (expression)
17402           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
17403           && value_dependent_expression_p (DECL_INITIAL (expression)))
17404         return true;
17405       return false;
17406
17407     case DYNAMIC_CAST_EXPR:
17408     case STATIC_CAST_EXPR:
17409     case CONST_CAST_EXPR:
17410     case REINTERPRET_CAST_EXPR:
17411     case CAST_EXPR:
17412       /* These expressions are value-dependent if the type to which
17413          the cast occurs is dependent or the expression being casted
17414          is value-dependent.  */
17415       {
17416         tree type = TREE_TYPE (expression);
17417
17418         if (dependent_type_p (type))
17419           return true;
17420
17421         /* A functional cast has a list of operands.  */
17422         expression = TREE_OPERAND (expression, 0);
17423         if (!expression)
17424           {
17425             /* If there are no operands, it must be an expression such
17426                as "int()". This should not happen for aggregate types
17427                because it would form non-constant expressions.  */
17428             gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
17429
17430             return false;
17431           }
17432
17433         if (TREE_CODE (expression) == TREE_LIST)
17434           return any_value_dependent_elements_p (expression);
17435
17436         return value_dependent_expression_p (expression);
17437       }
17438
17439     case SIZEOF_EXPR:
17440     case ALIGNOF_EXPR:
17441       /* A `sizeof' expression is value-dependent if the operand is
17442          type-dependent or is a pack expansion.  */
17443       expression = TREE_OPERAND (expression, 0);
17444       if (PACK_EXPANSION_P (expression))
17445         return true;
17446       else if (TYPE_P (expression))
17447         return dependent_type_p (expression);
17448       return type_dependent_expression_p (expression);
17449
17450     case SCOPE_REF:
17451       return dependent_scope_ref_p (expression, value_dependent_expression_p);
17452
17453     case COMPONENT_REF:
17454       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
17455               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
17456
17457     case CALL_EXPR:
17458       /* A CALL_EXPR may appear in a constant expression if it is a
17459          call to a builtin function, e.g., __builtin_constant_p.  All
17460          such calls are value-dependent.  */
17461       return true;
17462
17463     case NONTYPE_ARGUMENT_PACK:
17464       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
17465          is value-dependent.  */
17466       {
17467         tree values = ARGUMENT_PACK_ARGS (expression);
17468         int i, len = TREE_VEC_LENGTH (values);
17469         
17470         for (i = 0; i < len; ++i)
17471           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
17472             return true;
17473         
17474         return false;
17475       }
17476
17477     case TRAIT_EXPR:
17478       {
17479         tree type2 = TRAIT_EXPR_TYPE2 (expression);
17480         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
17481                 || (type2 ? dependent_type_p (type2) : false));
17482       }
17483
17484     case MODOP_EXPR:
17485       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
17486               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
17487
17488     default:
17489       /* A constant expression is value-dependent if any subexpression is
17490          value-dependent.  */
17491       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
17492         {
17493         case tcc_reference:
17494         case tcc_unary:
17495           return (value_dependent_expression_p
17496                   (TREE_OPERAND (expression, 0)));
17497
17498         case tcc_comparison:
17499         case tcc_binary:
17500           return ((value_dependent_expression_p
17501                    (TREE_OPERAND (expression, 0)))
17502                   || (value_dependent_expression_p
17503                       (TREE_OPERAND (expression, 1))));
17504
17505         case tcc_expression:
17506         case tcc_vl_exp:
17507           {
17508             int i;
17509             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
17510               /* In some cases, some of the operands may be missing.
17511                  (For example, in the case of PREDECREMENT_EXPR, the
17512                  amount to increment by may be missing.)  That doesn't
17513                  make the expression dependent.  */
17514               if (TREE_OPERAND (expression, i)
17515                   && (value_dependent_expression_p
17516                       (TREE_OPERAND (expression, i))))
17517                 return true;
17518             return false;
17519           }
17520
17521         default:
17522           break;
17523         }
17524     }
17525
17526   /* The expression is not value-dependent.  */
17527   return false;
17528 }
17529
17530 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
17531    [temp.dep.expr].  */
17532
17533 bool
17534 type_dependent_expression_p (tree expression)
17535 {
17536   if (!processing_template_decl)
17537     return false;
17538
17539   if (expression == error_mark_node)
17540     return false;
17541
17542   /* An unresolved name is always dependent.  */
17543   if (TREE_CODE (expression) == IDENTIFIER_NODE
17544       || TREE_CODE (expression) == USING_DECL)
17545     return true;
17546
17547   /* Some expression forms are never type-dependent.  */
17548   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
17549       || TREE_CODE (expression) == SIZEOF_EXPR
17550       || TREE_CODE (expression) == ALIGNOF_EXPR
17551       || TREE_CODE (expression) == TRAIT_EXPR
17552       || TREE_CODE (expression) == TYPEID_EXPR
17553       || TREE_CODE (expression) == DELETE_EXPR
17554       || TREE_CODE (expression) == VEC_DELETE_EXPR
17555       || TREE_CODE (expression) == THROW_EXPR)
17556     return false;
17557
17558   /* The types of these expressions depends only on the type to which
17559      the cast occurs.  */
17560   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
17561       || TREE_CODE (expression) == STATIC_CAST_EXPR
17562       || TREE_CODE (expression) == CONST_CAST_EXPR
17563       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
17564       || TREE_CODE (expression) == CAST_EXPR)
17565     return dependent_type_p (TREE_TYPE (expression));
17566
17567   /* The types of these expressions depends only on the type created
17568      by the expression.  */
17569   if (TREE_CODE (expression) == NEW_EXPR
17570       || TREE_CODE (expression) == VEC_NEW_EXPR)
17571     {
17572       /* For NEW_EXPR tree nodes created inside a template, either
17573          the object type itself or a TREE_LIST may appear as the
17574          operand 1.  */
17575       tree type = TREE_OPERAND (expression, 1);
17576       if (TREE_CODE (type) == TREE_LIST)
17577         /* This is an array type.  We need to check array dimensions
17578            as well.  */
17579         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
17580                || value_dependent_expression_p
17581                     (TREE_OPERAND (TREE_VALUE (type), 1));
17582       else
17583         return dependent_type_p (type);
17584     }
17585
17586   if (TREE_CODE (expression) == SCOPE_REF
17587       && dependent_scope_ref_p (expression,
17588                                 type_dependent_expression_p))
17589     return true;
17590
17591   if (TREE_CODE (expression) == FUNCTION_DECL
17592       && DECL_LANG_SPECIFIC (expression)
17593       && DECL_TEMPLATE_INFO (expression)
17594       && (any_dependent_template_arguments_p
17595           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
17596     return true;
17597
17598   if (TREE_CODE (expression) == TEMPLATE_DECL
17599       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
17600     return false;
17601
17602   if (TREE_CODE (expression) == STMT_EXPR)
17603     expression = stmt_expr_value_expr (expression);
17604
17605   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
17606     {
17607       tree elt;
17608       unsigned i;
17609
17610       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
17611         {
17612           if (type_dependent_expression_p (elt))
17613             return true;
17614         }
17615       return false;
17616     }
17617
17618   if (TREE_TYPE (expression) == unknown_type_node)
17619     {
17620       if (TREE_CODE (expression) == ADDR_EXPR)
17621         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
17622       if (TREE_CODE (expression) == COMPONENT_REF
17623           || TREE_CODE (expression) == OFFSET_REF)
17624         {
17625           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
17626             return true;
17627           expression = TREE_OPERAND (expression, 1);
17628           if (TREE_CODE (expression) == IDENTIFIER_NODE)
17629             return false;
17630         }
17631       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
17632       if (TREE_CODE (expression) == SCOPE_REF)
17633         return false;
17634
17635       if (TREE_CODE (expression) == BASELINK)
17636         expression = BASELINK_FUNCTIONS (expression);
17637
17638       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
17639         {
17640           if (any_dependent_template_arguments_p
17641               (TREE_OPERAND (expression, 1)))
17642             return true;
17643           expression = TREE_OPERAND (expression, 0);
17644         }
17645       gcc_assert (TREE_CODE (expression) == OVERLOAD
17646                   || TREE_CODE (expression) == FUNCTION_DECL);
17647
17648       while (expression)
17649         {
17650           if (type_dependent_expression_p (OVL_CURRENT (expression)))
17651             return true;
17652           expression = OVL_NEXT (expression);
17653         }
17654       return false;
17655     }
17656
17657   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
17658
17659   return (dependent_type_p (TREE_TYPE (expression)));
17660 }
17661
17662 /* Like type_dependent_expression_p, but it also works while not processing
17663    a template definition, i.e. during substitution or mangling.  */
17664
17665 bool
17666 type_dependent_expression_p_push (tree expr)
17667 {
17668   bool b;
17669   ++processing_template_decl;
17670   b = type_dependent_expression_p (expr);
17671   --processing_template_decl;
17672   return b;
17673 }
17674
17675 /* Returns TRUE if ARGS contains a type-dependent expression.  */
17676
17677 bool
17678 any_type_dependent_arguments_p (const VEC(tree,gc) *args)
17679 {
17680   unsigned int i;
17681   tree arg;
17682
17683   for (i = 0; VEC_iterate (tree, args, i, arg); ++i)
17684     {
17685       if (type_dependent_expression_p (arg))
17686         return true;
17687     }
17688   return false;
17689 }
17690
17691 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
17692    expressions) contains any value-dependent expressions.  */
17693
17694 bool
17695 any_value_dependent_elements_p (const_tree list)
17696 {
17697   for (; list; list = TREE_CHAIN (list))
17698     if (value_dependent_expression_p (TREE_VALUE (list)))
17699       return true;
17700
17701   return false;
17702 }
17703
17704 /* Returns TRUE if the ARG (a template argument) is dependent.  */
17705
17706 bool
17707 dependent_template_arg_p (tree arg)
17708 {
17709   if (!processing_template_decl)
17710     return false;
17711
17712   if (TREE_CODE (arg) == TEMPLATE_DECL
17713       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
17714     return dependent_template_p (arg);
17715   else if (ARGUMENT_PACK_P (arg))
17716     {
17717       tree args = ARGUMENT_PACK_ARGS (arg);
17718       int i, len = TREE_VEC_LENGTH (args);
17719       for (i = 0; i < len; ++i)
17720         {
17721           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
17722             return true;
17723         }
17724
17725       return false;
17726     }
17727   else if (TYPE_P (arg))
17728     return dependent_type_p (arg);
17729   else
17730     return (type_dependent_expression_p (arg)
17731             || value_dependent_expression_p (arg));
17732 }
17733
17734 /* Returns true if ARGS (a collection of template arguments) contains
17735    any types that require structural equality testing.  */
17736
17737 bool
17738 any_template_arguments_need_structural_equality_p (tree args)
17739 {
17740   int i;
17741   int j;
17742
17743   if (!args)
17744     return false;
17745   if (args == error_mark_node)
17746     return true;
17747
17748   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
17749     {
17750       tree level = TMPL_ARGS_LEVEL (args, i + 1);
17751       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
17752         {
17753           tree arg = TREE_VEC_ELT (level, j);
17754           tree packed_args = NULL_TREE;
17755           int k, len = 1;
17756
17757           if (ARGUMENT_PACK_P (arg))
17758             {
17759               /* Look inside the argument pack.  */
17760               packed_args = ARGUMENT_PACK_ARGS (arg);
17761               len = TREE_VEC_LENGTH (packed_args);
17762             }
17763
17764           for (k = 0; k < len; ++k)
17765             {
17766               if (packed_args)
17767                 arg = TREE_VEC_ELT (packed_args, k);
17768
17769               if (error_operand_p (arg))
17770                 return true;
17771               else if (TREE_CODE (arg) == TEMPLATE_DECL
17772                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
17773                 continue;
17774               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
17775                 return true;
17776               else if (!TYPE_P (arg) && TREE_TYPE (arg)
17777                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
17778                 return true;
17779             }
17780         }
17781     }
17782
17783   return false;
17784 }
17785
17786 /* Returns true if ARGS (a collection of template arguments) contains
17787    any dependent arguments.  */
17788
17789 bool
17790 any_dependent_template_arguments_p (const_tree args)
17791 {
17792   int i;
17793   int j;
17794
17795   if (!args)
17796     return false;
17797   if (args == error_mark_node)
17798     return true;
17799
17800   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
17801     {
17802       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
17803       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
17804         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
17805           return true;
17806     }
17807
17808   return false;
17809 }
17810
17811 /* Returns TRUE if the template TMPL is dependent.  */
17812
17813 bool
17814 dependent_template_p (tree tmpl)
17815 {
17816   if (TREE_CODE (tmpl) == OVERLOAD)
17817     {
17818       while (tmpl)
17819         {
17820           if (dependent_template_p (OVL_FUNCTION (tmpl)))
17821             return true;
17822           tmpl = OVL_CHAIN (tmpl);
17823         }
17824       return false;
17825     }
17826
17827   /* Template template parameters are dependent.  */
17828   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
17829       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
17830     return true;
17831   /* So are names that have not been looked up.  */
17832   if (TREE_CODE (tmpl) == SCOPE_REF
17833       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
17834     return true;
17835   /* So are member templates of dependent classes.  */
17836   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
17837     return dependent_type_p (DECL_CONTEXT (tmpl));
17838   return false;
17839 }
17840
17841 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
17842
17843 bool
17844 dependent_template_id_p (tree tmpl, tree args)
17845 {
17846   return (dependent_template_p (tmpl)
17847           || any_dependent_template_arguments_p (args));
17848 }
17849
17850 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
17851    is dependent.  */
17852
17853 bool
17854 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
17855 {
17856   int i;
17857
17858   if (!processing_template_decl)
17859     return false;
17860
17861   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
17862     {
17863       tree decl = TREE_VEC_ELT (declv, i);
17864       tree init = TREE_VEC_ELT (initv, i);
17865       tree cond = TREE_VEC_ELT (condv, i);
17866       tree incr = TREE_VEC_ELT (incrv, i);
17867
17868       if (type_dependent_expression_p (decl))
17869         return true;
17870
17871       if (init && type_dependent_expression_p (init))
17872         return true;
17873
17874       if (type_dependent_expression_p (cond))
17875         return true;
17876
17877       if (COMPARISON_CLASS_P (cond)
17878           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
17879               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
17880         return true;
17881
17882       if (TREE_CODE (incr) == MODOP_EXPR)
17883         {
17884           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
17885               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
17886             return true;
17887         }
17888       else if (type_dependent_expression_p (incr))
17889         return true;
17890       else if (TREE_CODE (incr) == MODIFY_EXPR)
17891         {
17892           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
17893             return true;
17894           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
17895             {
17896               tree t = TREE_OPERAND (incr, 1);
17897               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
17898                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
17899                 return true;
17900             }
17901         }
17902     }
17903
17904   return false;
17905 }
17906
17907 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
17908    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
17909    no such TYPE can be found.  Note that this function peers inside
17910    uninstantiated templates and therefore should be used only in
17911    extremely limited situations.  ONLY_CURRENT_P restricts this
17912    peering to the currently open classes hierarchy (which is required
17913    when comparing types).  */
17914
17915 tree
17916 resolve_typename_type (tree type, bool only_current_p)
17917 {
17918   tree scope;
17919   tree name;
17920   tree decl;
17921   int quals;
17922   tree pushed_scope;
17923   tree result;
17924
17925   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
17926
17927   scope = TYPE_CONTEXT (type);
17928   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
17929      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
17930      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
17931      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
17932      identifier  of the TYPENAME_TYPE anymore.
17933      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
17934      TYPENAME_TYPE instead, we avoid messing up with a possible
17935      typedef variant case.  */
17936   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
17937
17938   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
17939      it first before we can figure out what NAME refers to.  */
17940   if (TREE_CODE (scope) == TYPENAME_TYPE)
17941     scope = resolve_typename_type (scope, only_current_p);
17942   /* If we don't know what SCOPE refers to, then we cannot resolve the
17943      TYPENAME_TYPE.  */
17944   if (TREE_CODE (scope) == TYPENAME_TYPE)
17945     return type;
17946   /* If the SCOPE is a template type parameter, we have no way of
17947      resolving the name.  */
17948   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
17949     return type;
17950   /* If the SCOPE is not the current instantiation, there's no reason
17951      to look inside it.  */
17952   if (only_current_p && !currently_open_class (scope))
17953     return type;
17954   /* If this is a typedef, we don't want to look inside (c++/11987).  */
17955   if (typedef_variant_p (type))
17956     return type;
17957   /* If SCOPE isn't the template itself, it will not have a valid
17958      TYPE_FIELDS list.  */
17959   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
17960     /* scope is either the template itself or a compatible instantiation
17961        like X<T>, so look up the name in the original template.  */
17962     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
17963   else
17964     /* scope is a partial instantiation, so we can't do the lookup or we
17965        will lose the template arguments.  */
17966     return type;
17967   /* Enter the SCOPE so that name lookup will be resolved as if we
17968      were in the class definition.  In particular, SCOPE will no
17969      longer be considered a dependent type.  */
17970   pushed_scope = push_scope (scope);
17971   /* Look up the declaration.  */
17972   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
17973
17974   result = NULL_TREE;
17975   
17976   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
17977      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
17978   if (!decl)
17979     /*nop*/;
17980   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
17981            && TREE_CODE (decl) == TYPE_DECL)
17982     {
17983       result = TREE_TYPE (decl);
17984       if (result == error_mark_node)
17985         result = NULL_TREE;
17986     }
17987   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
17988            && DECL_CLASS_TEMPLATE_P (decl))
17989     {
17990       tree tmpl;
17991       tree args;
17992       /* Obtain the template and the arguments.  */
17993       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
17994       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
17995       /* Instantiate the template.  */
17996       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
17997                                       /*entering_scope=*/0,
17998                                       tf_error | tf_user);
17999       if (result == error_mark_node)
18000         result = NULL_TREE;
18001     }
18002   
18003   /* Leave the SCOPE.  */
18004   if (pushed_scope)
18005     pop_scope (pushed_scope);
18006
18007   /* If we failed to resolve it, return the original typename.  */
18008   if (!result)
18009     return type;
18010   
18011   /* If lookup found a typename type, resolve that too.  */
18012   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
18013     {
18014       /* Ill-formed programs can cause infinite recursion here, so we
18015          must catch that.  */
18016       TYPENAME_IS_RESOLVING_P (type) = 1;
18017       result = resolve_typename_type (result, only_current_p);
18018       TYPENAME_IS_RESOLVING_P (type) = 0;
18019     }
18020   
18021   /* Qualify the resulting type.  */
18022   quals = cp_type_quals (type);
18023   if (quals)
18024     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
18025
18026   return result;
18027 }
18028
18029 /* EXPR is an expression which is not type-dependent.  Return a proxy
18030    for EXPR that can be used to compute the types of larger
18031    expressions containing EXPR.  */
18032
18033 tree
18034 build_non_dependent_expr (tree expr)
18035 {
18036   tree inner_expr;
18037
18038   /* Preserve null pointer constants so that the type of things like
18039      "p == 0" where "p" is a pointer can be determined.  */
18040   if (null_ptr_cst_p (expr))
18041     return expr;
18042   /* Preserve OVERLOADs; the functions must be available to resolve
18043      types.  */
18044   inner_expr = expr;
18045   if (TREE_CODE (inner_expr) == STMT_EXPR)
18046     inner_expr = stmt_expr_value_expr (inner_expr);
18047   if (TREE_CODE (inner_expr) == ADDR_EXPR)
18048     inner_expr = TREE_OPERAND (inner_expr, 0);
18049   if (TREE_CODE (inner_expr) == COMPONENT_REF)
18050     inner_expr = TREE_OPERAND (inner_expr, 1);
18051   if (is_overloaded_fn (inner_expr)
18052       || TREE_CODE (inner_expr) == OFFSET_REF)
18053     return expr;
18054   /* There is no need to return a proxy for a variable.  */
18055   if (TREE_CODE (expr) == VAR_DECL)
18056     return expr;
18057   /* Preserve string constants; conversions from string constants to
18058      "char *" are allowed, even though normally a "const char *"
18059      cannot be used to initialize a "char *".  */
18060   if (TREE_CODE (expr) == STRING_CST)
18061     return expr;
18062   /* Preserve arithmetic constants, as an optimization -- there is no
18063      reason to create a new node.  */
18064   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
18065     return expr;
18066   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
18067      There is at least one place where we want to know that a
18068      particular expression is a throw-expression: when checking a ?:
18069      expression, there are special rules if the second or third
18070      argument is a throw-expression.  */
18071   if (TREE_CODE (expr) == THROW_EXPR)
18072     return expr;
18073
18074   if (TREE_CODE (expr) == COND_EXPR)
18075     return build3 (COND_EXPR,
18076                    TREE_TYPE (expr),
18077                    TREE_OPERAND (expr, 0),
18078                    (TREE_OPERAND (expr, 1)
18079                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
18080                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
18081                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
18082   if (TREE_CODE (expr) == COMPOUND_EXPR
18083       && !COMPOUND_EXPR_OVERLOADED (expr))
18084     return build2 (COMPOUND_EXPR,
18085                    TREE_TYPE (expr),
18086                    TREE_OPERAND (expr, 0),
18087                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
18088
18089   /* If the type is unknown, it can't really be non-dependent */
18090   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
18091
18092   /* Otherwise, build a NON_DEPENDENT_EXPR.
18093
18094      REFERENCE_TYPEs are not stripped for expressions in templates
18095      because doing so would play havoc with mangling.  Consider, for
18096      example:
18097
18098        template <typename T> void f<T& g>() { g(); }
18099
18100      In the body of "f", the expression for "g" will have
18101      REFERENCE_TYPE, even though the standard says that it should
18102      not.  The reason is that we must preserve the syntactic form of
18103      the expression so that mangling (say) "f<g>" inside the body of
18104      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
18105      stripped here.  */
18106   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
18107 }
18108
18109 /* ARGS is a vector of expressions as arguments to a function call.
18110    Replace the arguments with equivalent non-dependent expressions.
18111    This modifies ARGS in place.  */
18112
18113 void
18114 make_args_non_dependent (VEC(tree,gc) *args)
18115 {
18116   unsigned int ix;
18117   tree arg;
18118
18119   for (ix = 0; VEC_iterate (tree, args, ix, arg); ++ix)
18120     {
18121       tree newarg = build_non_dependent_expr (arg);
18122       if (newarg != arg)
18123         VEC_replace (tree, args, ix, newarg);
18124     }
18125 }
18126
18127 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
18128    with a level one deeper than the actual template parms.  */
18129
18130 tree
18131 make_auto (void)
18132 {
18133   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
18134   TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
18135                                TYPE_DECL, get_identifier ("auto"), au);
18136   TYPE_STUB_DECL (au) = TYPE_NAME (au);
18137   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
18138     (0, processing_template_decl + 1, processing_template_decl + 1,
18139      TYPE_NAME (au), NULL_TREE);
18140   TYPE_CANONICAL (au) = canonical_type_parameter (au);
18141   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
18142   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
18143
18144   return au;
18145 }
18146
18147 /* Given type ARG, return std::initializer_list<ARG>.  */
18148
18149 static tree
18150 listify (tree arg)
18151 {
18152   tree std_init_list = namespace_binding
18153     (get_identifier ("initializer_list"), std_node);
18154   tree argvec;
18155   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
18156     {    
18157       error ("deducing from brace-enclosed initializer list requires "
18158              "#include <initializer_list>");
18159       return error_mark_node;
18160     }
18161   argvec = make_tree_vec (1);
18162   TREE_VEC_ELT (argvec, 0) = arg;
18163   return lookup_template_class (std_init_list, argvec, NULL_TREE,
18164                                 NULL_TREE, 0, tf_warning_or_error);
18165 }
18166
18167 /* Replace auto in TYPE with std::initializer_list<auto>.  */
18168
18169 static tree
18170 listify_autos (tree type, tree auto_node)
18171 {
18172   tree init_auto = listify (auto_node);
18173   tree argvec = make_tree_vec (1);
18174   TREE_VEC_ELT (argvec, 0) = init_auto;
18175   if (processing_template_decl)
18176     argvec = add_to_template_args (current_template_args (), argvec);
18177   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
18178 }
18179
18180 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
18181    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
18182
18183 tree
18184 do_auto_deduction (tree type, tree init, tree auto_node)
18185 {
18186   tree parms, tparms, targs;
18187   tree args[1];
18188   int val;
18189
18190   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
18191      with either a new invented type template parameter U or, if the
18192      initializer is a braced-init-list (8.5.4), with
18193      std::initializer_list<U>.  */
18194   if (BRACE_ENCLOSED_INITIALIZER_P (init))
18195     type = listify_autos (type, auto_node);
18196
18197   parms = build_tree_list (NULL_TREE, type);
18198   args[0] = init;
18199   tparms = make_tree_vec (1);
18200   targs = make_tree_vec (1);
18201   TREE_VEC_ELT (tparms, 0)
18202     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
18203   val = type_unification_real (tparms, targs, parms, args, 1, 0,
18204                                DEDUCE_CALL, LOOKUP_NORMAL);
18205   if (val > 0)
18206     {
18207       error ("unable to deduce %qT from %qE", type, init);
18208       return error_mark_node;
18209     }
18210
18211   /* If the list of declarators contains more than one declarator, the type
18212      of each declared variable is determined as described above. If the
18213      type deduced for the template parameter U is not the same in each
18214      deduction, the program is ill-formed.  */
18215   if (TREE_TYPE (auto_node)
18216       && !same_type_p (TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0)))
18217     {
18218       error ("inconsistent deduction for %qT: %qT and then %qT",
18219              auto_node, TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0));
18220       return error_mark_node;
18221     }
18222   TREE_TYPE (auto_node) = TREE_VEC_ELT (targs, 0);
18223
18224   if (processing_template_decl)
18225     targs = add_to_template_args (current_template_args (), targs);
18226   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
18227 }
18228
18229 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
18230    result.  */
18231
18232 tree
18233 splice_late_return_type (tree type, tree late_return_type)
18234 {
18235   tree argvec;
18236
18237   if (late_return_type == NULL_TREE)
18238     return type;
18239   argvec = make_tree_vec (1);
18240   TREE_VEC_ELT (argvec, 0) = late_return_type;
18241   if (processing_template_decl)
18242     argvec = add_to_template_args (current_template_args (), argvec);
18243   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
18244 }
18245
18246 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
18247
18248 bool
18249 is_auto (const_tree type)
18250 {
18251   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
18252       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
18253     return true;
18254   else
18255     return false;
18256 }
18257
18258 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
18259    appear as a type-specifier for the declaration in question, we don't
18260    have to look through the whole type.  */
18261
18262 tree
18263 type_uses_auto (tree type)
18264 {
18265   enum tree_code code;
18266   if (is_auto (type))
18267     return type;
18268
18269   code = TREE_CODE (type);
18270
18271   if (code == POINTER_TYPE || code == REFERENCE_TYPE
18272       || code == OFFSET_TYPE || code == FUNCTION_TYPE
18273       || code == METHOD_TYPE || code == ARRAY_TYPE)
18274     return type_uses_auto (TREE_TYPE (type));
18275
18276   if (TYPE_PTRMEMFUNC_P (type))
18277     return type_uses_auto (TREE_TYPE (TREE_TYPE
18278                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
18279
18280   return NULL_TREE;
18281 }
18282
18283 /* For a given template T, return the vector of typedefs referenced
18284    in T for which access check is needed at T instantiation time.
18285    T is either  a FUNCTION_DECL or a RECORD_TYPE.
18286    Those typedefs were added to T by the function
18287    append_type_to_template_for_access_check.  */
18288
18289 VEC(qualified_typedef_usage_t,gc)*
18290 get_types_needing_access_check (tree t)
18291 {
18292   tree ti;
18293   VEC(qualified_typedef_usage_t,gc) *result = NULL;
18294
18295   if (!t || t == error_mark_node)
18296     return NULL;
18297
18298   if (!(ti = get_template_info (t)))
18299     return NULL;
18300
18301   if (CLASS_TYPE_P (t)
18302       || TREE_CODE (t) == FUNCTION_DECL)
18303     {
18304       if (!TI_TEMPLATE (ti))
18305         return NULL;
18306
18307       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
18308     }
18309
18310   return result;
18311 }
18312
18313 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
18314    tied to T. That list of typedefs will be access checked at
18315    T instantiation time.
18316    T is either a FUNCTION_DECL or a RECORD_TYPE.
18317    TYPE_DECL is a TYPE_DECL node representing a typedef.
18318    SCOPE is the scope through which TYPE_DECL is accessed.
18319    LOCATION is the location of the usage point of TYPE_DECL.
18320
18321    This function is a subroutine of
18322    append_type_to_template_for_access_check.  */
18323
18324 static void
18325 append_type_to_template_for_access_check_1 (tree t,
18326                                             tree type_decl,
18327                                             tree scope,
18328                                             location_t location)
18329 {
18330   qualified_typedef_usage_t typedef_usage;
18331   tree ti;
18332
18333   if (!t || t == error_mark_node)
18334     return;
18335
18336   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
18337                || CLASS_TYPE_P (t))
18338               && type_decl
18339               && TREE_CODE (type_decl) == TYPE_DECL
18340               && scope);
18341
18342   if (!(ti = get_template_info (t)))
18343     return;
18344
18345   gcc_assert (TI_TEMPLATE (ti));
18346
18347   typedef_usage.typedef_decl = type_decl;
18348   typedef_usage.context = scope;
18349   typedef_usage.locus = location;
18350
18351   VEC_safe_push (qualified_typedef_usage_t, gc,
18352                  TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti),
18353                  &typedef_usage);
18354 }
18355
18356 /* Append TYPE_DECL to the template TEMPL.
18357    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
18358    At TEMPL instanciation time, TYPE_DECL will be checked to see
18359    if it can be accessed through SCOPE.
18360    LOCATION is the location of the usage point of TYPE_DECL.
18361
18362    e.g. consider the following code snippet:
18363
18364      class C
18365      {
18366        typedef int myint;
18367      };
18368
18369      template<class U> struct S
18370      {
18371        C::myint mi; // <-- usage point of the typedef C::myint
18372      };
18373
18374      S<char> s;
18375
18376    At S<char> instantiation time, we need to check the access of C::myint
18377    In other words, we need to check the access of the myint typedef through
18378    the C scope. For that purpose, this function will add the myint typedef
18379    and the scope C through which its being accessed to a list of typedefs
18380    tied to the template S. That list will be walked at template instantiation
18381    time and access check performed on each typedefs it contains.
18382    Note that this particular code snippet should yield an error because
18383    myint is private to C.  */
18384
18385 void
18386 append_type_to_template_for_access_check (tree templ,
18387                                           tree type_decl,
18388                                           tree scope,
18389                                           location_t location)
18390 {
18391   qualified_typedef_usage_t *iter;
18392   int i;
18393
18394   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
18395
18396   /* Make sure we don't append the type to the template twice.  */
18397   for (i = 0;
18398        VEC_iterate (qualified_typedef_usage_t,
18399                     get_types_needing_access_check (templ),
18400                     i, iter);
18401        ++i)
18402     if (iter->typedef_decl == type_decl && scope == iter->context)
18403       return;
18404
18405   append_type_to_template_for_access_check_1 (templ, type_decl,
18406                                               scope, location);
18407 }
18408
18409 /* Set up the hash tables for template instantiations.  */
18410
18411 void
18412 init_template_processing (void)
18413 {
18414   decl_specializations = htab_create_ggc (37,
18415                                           hash_specialization,
18416                                           eq_specializations,
18417                                           ggc_free);
18418   type_specializations = htab_create_ggc (37,
18419                                           hash_specialization,
18420                                           eq_specializations,
18421                                           ggc_free);
18422 }
18423
18424 #include "gt-cp-pt.h"