OSDN Git Service

PR c++/47208
[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, 2010, 2011
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 "tree.h"
34 #include "intl.h"
35 #include "pointer-set.h"
36 #include "flags.h"
37 #include "cp-tree.h"
38 #include "c-family/c-common.h"
39 #include "c-family/c-objc.h"
40 #include "cp-objcp-common.h"
41 #include "tree-inline.h"
42 #include "decl.h"
43 #include "output.h"
44 #include "toplev.h"
45 #include "timevar.h"
46 #include "tree-iterator.h"
47 #include "vecprim.h"
48
49 /* The type of functions taking a tree, and some additional data, and
50    returning an int.  */
51 typedef int (*tree_fn_t) (tree, void*);
52
53 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
54    instantiations have been deferred, either because their definitions
55    were not yet available, or because we were putting off doing the work.  */
56 struct GTY (()) pending_template {
57   struct pending_template *next;
58   struct tinst_level *tinst;
59 };
60
61 static GTY(()) struct pending_template *pending_templates;
62 static GTY(()) struct pending_template *last_pending_template;
63
64 int processing_template_parmlist;
65 static int template_header_count;
66
67 static GTY(()) tree saved_trees;
68 static VEC(int,heap) *inline_parm_levels;
69
70 static GTY(()) struct tinst_level *current_tinst_level;
71
72 static GTY(()) tree saved_access_scope;
73
74 /* Live only within one (recursive) call to tsubst_expr.  We use
75    this to pass the statement expression node from the STMT_EXPR
76    to the EXPR_STMT that is its result.  */
77 static tree cur_stmt_expr;
78
79 /* A map from local variable declarations in the body of the template
80    presently being instantiated to the corresponding instantiated
81    local variables.  */
82 static htab_t local_specializations;
83
84 typedef struct GTY(()) spec_entry
85 {
86   tree tmpl;
87   tree args;
88   tree spec;
89 } spec_entry;
90
91 static GTY ((param_is (spec_entry)))
92   htab_t decl_specializations;
93
94 static GTY ((param_is (spec_entry)))
95   htab_t type_specializations;
96
97 /* Contains canonical template parameter types. The vector is indexed by
98    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
99    TREE_LIST, whose TREE_VALUEs contain the canonical template
100    parameters of various types and levels.  */
101 static GTY(()) VEC(tree,gc) *canonical_template_parms;
102
103 #define UNIFY_ALLOW_NONE 0
104 #define UNIFY_ALLOW_MORE_CV_QUAL 1
105 #define UNIFY_ALLOW_LESS_CV_QUAL 2
106 #define UNIFY_ALLOW_DERIVED 4
107 #define UNIFY_ALLOW_INTEGER 8
108 #define UNIFY_ALLOW_OUTER_LEVEL 16
109 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
110 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
111
112 static void push_access_scope (tree);
113 static void pop_access_scope (tree);
114 static bool resolve_overloaded_unification (tree, tree, tree, tree,
115                                             unification_kind_t, int);
116 static int try_one_overload (tree, tree, tree, tree, tree,
117                              unification_kind_t, int, bool);
118 static int unify (tree, tree, tree, tree, int);
119 static void add_pending_template (tree);
120 static tree reopen_tinst_level (struct tinst_level *);
121 static tree tsubst_initializer_list (tree, tree);
122 static tree get_class_bindings (tree, tree, tree);
123 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
124                                    bool, bool);
125 static void tsubst_enum (tree, tree, tree);
126 static tree add_to_template_args (tree, tree);
127 static tree add_outermost_template_args (tree, tree);
128 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
129 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
130                                              tree);
131 static int type_unification_real (tree, tree, tree, const tree *,
132                                   unsigned int, int, unification_kind_t, int);
133 static void note_template_header (int);
134 static tree convert_nontype_argument_function (tree, tree);
135 static tree convert_nontype_argument (tree, tree, tsubst_flags_t);
136 static tree convert_template_argument (tree, tree, tree,
137                                        tsubst_flags_t, int, tree);
138 static int for_each_template_parm (tree, tree_fn_t, void*,
139                                    struct pointer_set_t*, bool);
140 static tree expand_template_argument_pack (tree);
141 static tree build_template_parm_index (int, int, int, int, tree, tree);
142 static bool inline_needs_template_parms (tree);
143 static void push_inline_template_parms_recursive (tree, int);
144 static tree retrieve_local_specialization (tree);
145 static void register_local_specialization (tree, tree);
146 static hashval_t hash_specialization (const void *p);
147 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
148 static int mark_template_parm (tree, void *);
149 static int template_parm_this_level_p (tree, void *);
150 static tree tsubst_friend_function (tree, tree);
151 static tree tsubst_friend_class (tree, tree);
152 static int can_complete_type_without_circularity (tree);
153 static tree get_bindings (tree, tree, tree, bool);
154 static int template_decl_level (tree);
155 static int check_cv_quals_for_unify (int, tree, tree);
156 static void template_parm_level_and_index (tree, int*, int*);
157 static int unify_pack_expansion (tree, tree, tree, tree, int, bool, bool);
158 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
159 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
160 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
161 static void regenerate_decl_from_template (tree, tree);
162 static tree most_specialized_class (tree, tree, tsubst_flags_t);
163 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
164 static tree tsubst_arg_types (tree, tree, tsubst_flags_t, tree);
165 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
166 static bool check_specialization_scope (void);
167 static tree process_partial_specialization (tree);
168 static void set_current_access_from_decl (tree);
169 static tree get_template_base (tree, tree, tree, tree);
170 static tree try_class_unification (tree, tree, tree, tree);
171 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
172                                            tree, tree);
173 static bool template_template_parm_bindings_ok_p (tree, tree);
174 static int template_args_equal (tree, tree);
175 static void tsubst_default_arguments (tree);
176 static tree for_each_template_parm_r (tree *, int *, void *);
177 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
178 static void copy_default_args_to_explicit_spec (tree);
179 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
180 static int eq_local_specializations (const void *, const void *);
181 static bool dependent_template_arg_p (tree);
182 static bool any_template_arguments_need_structural_equality_p (tree);
183 static bool dependent_type_p_r (tree);
184 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree, bool);
185 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
186 static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
187 static tree tsubst_decl (tree, tree, tsubst_flags_t);
188 static void perform_typedefs_access_check (tree tmpl, tree targs);
189 static void append_type_to_template_for_access_check_1 (tree, tree, tree,
190                                                         location_t);
191 static tree listify (tree);
192 static tree listify_autos (tree, tree);
193 static tree template_parm_to_arg (tree t);
194 static tree current_template_args (void);
195 static tree fixup_template_type_parm_type (tree, int);
196 static tree fixup_template_parm_index (tree, tree, int);
197 static tree tsubst_template_parm (tree, tree, tsubst_flags_t);
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) : CP_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   if (args == NULL_TREE || extra_args == error_mark_node)
499     return extra_args;
500
501   extra_depth = TMPL_ARGS_DEPTH (extra_args);
502   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
503
504   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
505     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
506
507   for (j = 1; j <= extra_depth; ++j, ++i)
508     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
509
510   return new_args;
511 }
512
513 /* Like add_to_template_args, but only the outermost ARGS are added to
514    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
515    (EXTRA_ARGS) levels are added.  This function is used to combine
516    the template arguments from a partial instantiation with the
517    template arguments used to attain the full instantiation from the
518    partial instantiation.  */
519
520 static tree
521 add_outermost_template_args (tree args, tree extra_args)
522 {
523   tree new_args;
524
525   /* If there are more levels of EXTRA_ARGS than there are ARGS,
526      something very fishy is going on.  */
527   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
528
529   /* If *all* the new arguments will be the EXTRA_ARGS, just return
530      them.  */
531   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
532     return extra_args;
533
534   /* For the moment, we make ARGS look like it contains fewer levels.  */
535   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
536
537   new_args = add_to_template_args (args, extra_args);
538
539   /* Now, we restore ARGS to its full dimensions.  */
540   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
541
542   return new_args;
543 }
544
545 /* Return the N levels of innermost template arguments from the ARGS.  */
546
547 tree
548 get_innermost_template_args (tree args, int n)
549 {
550   tree new_args;
551   int extra_levels;
552   int i;
553
554   gcc_assert (n >= 0);
555
556   /* If N is 1, just return the innermost set of template arguments.  */
557   if (n == 1)
558     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
559
560   /* If we're not removing anything, just return the arguments we were
561      given.  */
562   extra_levels = TMPL_ARGS_DEPTH (args) - n;
563   gcc_assert (extra_levels >= 0);
564   if (extra_levels == 0)
565     return args;
566
567   /* Make a new set of arguments, not containing the outer arguments.  */
568   new_args = make_tree_vec (n);
569   for (i = 1; i <= n; ++i)
570     SET_TMPL_ARGS_LEVEL (new_args, i,
571                          TMPL_ARGS_LEVEL (args, i + extra_levels));
572
573   return new_args;
574 }
575
576 /* The inverse of get_innermost_template_args: Return all but the innermost
577    EXTRA_LEVELS levels of template arguments from the ARGS.  */
578
579 static tree
580 strip_innermost_template_args (tree args, int extra_levels)
581 {
582   tree new_args;
583   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
584   int i;
585
586   gcc_assert (n >= 0);
587
588   /* If N is 1, just return the outermost set of template arguments.  */
589   if (n == 1)
590     return TMPL_ARGS_LEVEL (args, 1);
591
592   /* If we're not removing anything, just return the arguments we were
593      given.  */
594   gcc_assert (extra_levels >= 0);
595   if (extra_levels == 0)
596     return args;
597
598   /* Make a new set of arguments, not containing the inner arguments.  */
599   new_args = make_tree_vec (n);
600   for (i = 1; i <= n; ++i)
601     SET_TMPL_ARGS_LEVEL (new_args, i,
602                          TMPL_ARGS_LEVEL (args, i));
603
604   return new_args;
605 }
606
607 /* We've got a template header coming up; push to a new level for storing
608    the parms.  */
609
610 void
611 begin_template_parm_list (void)
612 {
613   /* We use a non-tag-transparent scope here, which causes pushtag to
614      put tags in this scope, rather than in the enclosing class or
615      namespace scope.  This is the right thing, since we want
616      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
617      global template class, push_template_decl handles putting the
618      TEMPLATE_DECL into top-level scope.  For a nested template class,
619      e.g.:
620
621        template <class T> struct S1 {
622          template <class T> struct S2 {};
623        };
624
625      pushtag contains special code to call pushdecl_with_scope on the
626      TEMPLATE_DECL for S2.  */
627   begin_scope (sk_template_parms, NULL);
628   ++processing_template_decl;
629   ++processing_template_parmlist;
630   note_template_header (0);
631 }
632
633 /* This routine is called when a specialization is declared.  If it is
634    invalid to declare a specialization here, an error is reported and
635    false is returned, otherwise this routine will return true.  */
636
637 static bool
638 check_specialization_scope (void)
639 {
640   tree scope = current_scope ();
641
642   /* [temp.expl.spec]
643
644      An explicit specialization shall be declared in the namespace of
645      which the template is a member, or, for member templates, in the
646      namespace of which the enclosing class or enclosing class
647      template is a member.  An explicit specialization of a member
648      function, member class or static data member of a class template
649      shall be declared in the namespace of which the class template
650      is a member.  */
651   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
652     {
653       error ("explicit specialization in non-namespace scope %qD", scope);
654       return false;
655     }
656
657   /* [temp.expl.spec]
658
659      In an explicit specialization declaration for a member of a class
660      template or a member template that appears in namespace scope,
661      the member template and some of its enclosing class templates may
662      remain unspecialized, except that the declaration shall not
663      explicitly specialize a class member template if its enclosing
664      class templates are not explicitly specialized as well.  */
665   if (current_template_parms)
666     {
667       error ("enclosing class templates are not explicitly specialized");
668       return false;
669     }
670
671   return true;
672 }
673
674 /* We've just seen template <>.  */
675
676 bool
677 begin_specialization (void)
678 {
679   begin_scope (sk_template_spec, NULL);
680   note_template_header (1);
681   return check_specialization_scope ();
682 }
683
684 /* Called at then end of processing a declaration preceded by
685    template<>.  */
686
687 void
688 end_specialization (void)
689 {
690   finish_scope ();
691   reset_specialization ();
692 }
693
694 /* Any template <>'s that we have seen thus far are not referring to a
695    function specialization.  */
696
697 void
698 reset_specialization (void)
699 {
700   processing_specialization = 0;
701   template_header_count = 0;
702 }
703
704 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
705    it was of the form template <>.  */
706
707 static void
708 note_template_header (int specialization)
709 {
710   processing_specialization = specialization;
711   template_header_count++;
712 }
713
714 /* We're beginning an explicit instantiation.  */
715
716 void
717 begin_explicit_instantiation (void)
718 {
719   gcc_assert (!processing_explicit_instantiation);
720   processing_explicit_instantiation = true;
721 }
722
723
724 void
725 end_explicit_instantiation (void)
726 {
727   gcc_assert (processing_explicit_instantiation);
728   processing_explicit_instantiation = false;
729 }
730
731 /* An explicit specialization or partial specialization TMPL is being
732    declared.  Check that the namespace in which the specialization is
733    occurring is permissible.  Returns false iff it is invalid to
734    specialize TMPL in the current namespace.  */
735
736 static bool
737 check_specialization_namespace (tree tmpl)
738 {
739   tree tpl_ns = decl_namespace_context (tmpl);
740
741   /* [tmpl.expl.spec]
742
743      An explicit specialization shall be declared in the namespace of
744      which the template is a member, or, for member templates, in the
745      namespace of which the enclosing class or enclosing class
746      template is a member.  An explicit specialization of a member
747      function, member class or static data member of a class template
748      shall be declared in the namespace of which the class template is
749      a member.  */
750   if (current_scope() != DECL_CONTEXT (tmpl)
751       && !at_namespace_scope_p ())
752     {
753       error ("specialization of %qD must appear at namespace scope", tmpl);
754       return false;
755     }
756   if (is_associated_namespace (current_namespace, tpl_ns))
757     /* Same or super-using namespace.  */
758     return true;
759   else
760     {
761       permerror (input_location, "specialization of %qD in different namespace", tmpl);
762       permerror (input_location, "  from definition of %q+#D", tmpl);
763       return false;
764     }
765 }
766
767 /* SPEC is an explicit instantiation.  Check that it is valid to
768    perform this explicit instantiation in the current namespace.  */
769
770 static void
771 check_explicit_instantiation_namespace (tree spec)
772 {
773   tree ns;
774
775   /* DR 275: An explicit instantiation shall appear in an enclosing
776      namespace of its template.  */
777   ns = decl_namespace_context (spec);
778   if (!is_ancestor (current_namespace, ns))
779     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
780                "(which does not enclose namespace %qD)",
781                spec, current_namespace, ns);
782 }
783
784 /* The TYPE is being declared.  If it is a template type, that means it
785    is a partial specialization.  Do appropriate error-checking.  */
786
787 tree
788 maybe_process_partial_specialization (tree type)
789 {
790   tree context;
791
792   if (type == error_mark_node)
793     return error_mark_node;
794
795   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
796     {
797       error ("name of class shadows template template parameter %qD",
798              TYPE_NAME (type));
799       return error_mark_node;
800     }
801
802   context = TYPE_CONTEXT (type);
803
804   if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
805     {
806       /* This is for ordinary explicit specialization and partial
807          specialization of a template class such as:
808
809            template <> class C<int>;
810
811          or:
812
813            template <class T> class C<T*>;
814
815          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
816
817       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
818           && !COMPLETE_TYPE_P (type))
819         {
820           check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
821           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
822           if (processing_template_decl)
823             {
824               if (push_template_decl (TYPE_MAIN_DECL (type))
825                   == error_mark_node)
826                 return error_mark_node;
827             }
828         }
829       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
830         error ("specialization of %qT after instantiation", type);
831     }
832   else if (CLASS_TYPE_P (type)
833            && !CLASSTYPE_USE_TEMPLATE (type)
834            && CLASSTYPE_TEMPLATE_INFO (type)
835            && context && CLASS_TYPE_P (context)
836            && CLASSTYPE_TEMPLATE_INFO (context))
837     {
838       /* This is for an explicit specialization of member class
839          template according to [temp.expl.spec/18]:
840
841            template <> template <class U> class C<int>::D;
842
843          The context `C<int>' must be an implicit instantiation.
844          Otherwise this is just a member class template declared
845          earlier like:
846
847            template <> class C<int> { template <class U> class D; };
848            template <> template <class U> class C<int>::D;
849
850          In the first case, `C<int>::D' is a specialization of `C<T>::D'
851          while in the second case, `C<int>::D' is a primary template
852          and `C<T>::D' may not exist.  */
853
854       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
855           && !COMPLETE_TYPE_P (type))
856         {
857           tree t;
858           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
859
860           if (current_namespace
861               != decl_namespace_context (tmpl))
862             {
863               permerror (input_location, "specializing %q#T in different namespace", type);
864               permerror (input_location, "  from definition of %q+#D", tmpl);
865             }
866
867           /* Check for invalid specialization after instantiation:
868
869                template <> template <> class C<int>::D<int>;
870                template <> template <class U> class C<int>::D;  */
871
872           for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
873                t; t = TREE_CHAIN (t))
874             {
875               tree inst = TREE_VALUE (t);
876               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst))
877                 {
878                   /* We already have a full specialization of this partial
879                      instantiation.  Reassign it to the new member
880                      specialization template.  */
881                   spec_entry elt;
882                   spec_entry **slot;
883
884                   elt.tmpl = most_general_template (tmpl);
885                   elt.args = CLASSTYPE_TI_ARGS (inst);
886                   elt.spec = inst;
887
888                   htab_remove_elt (type_specializations, &elt);
889
890                   elt.tmpl = tmpl;
891                   elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
892
893                   slot = (spec_entry **)
894                     htab_find_slot (type_specializations, &elt, INSERT);
895                   *slot = ggc_alloc_spec_entry ();
896                   **slot = elt;
897                 }
898               else if (COMPLETE_OR_OPEN_TYPE_P (inst))
899                 /* But if we've had an implicit instantiation, that's a
900                    problem ([temp.expl.spec]/6).  */
901                 error ("specialization %qT after instantiation %qT",
902                        type, inst);
903             }
904
905           /* Mark TYPE as a specialization.  And as a result, we only
906              have one level of template argument for the innermost
907              class template.  */
908           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
909           CLASSTYPE_TI_ARGS (type)
910             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
911         }
912     }
913   else if (processing_specialization)
914     {
915        /* Someday C++0x may allow for enum template specialization.  */
916       if (cxx_dialect > cxx98 && TREE_CODE (type) == ENUMERAL_TYPE
917           && CLASS_TYPE_P (context) && CLASSTYPE_USE_TEMPLATE (context))
918         pedwarn (input_location, OPT_pedantic, "template specialization "
919                  "of %qD not allowed by ISO C++", type);
920       else
921         {
922           error ("explicit specialization of non-template %qT", type);
923           return error_mark_node;
924         }
925     }
926
927   return type;
928 }
929
930 /* Returns nonzero if we can optimize the retrieval of specializations
931    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
932    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
933
934 static inline bool
935 optimize_specialization_lookup_p (tree tmpl)
936 {
937   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
938           && DECL_CLASS_SCOPE_P (tmpl)
939           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
940              parameter.  */
941           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
942           /* The optimized lookup depends on the fact that the
943              template arguments for the member function template apply
944              purely to the containing class, which is not true if the
945              containing class is an explicit or partial
946              specialization.  */
947           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
948           && !DECL_MEMBER_TEMPLATE_P (tmpl)
949           && !DECL_CONV_FN_P (tmpl)
950           /* It is possible to have a template that is not a member
951              template and is not a member of a template class:
952
953              template <typename T>
954              struct S { friend A::f(); };
955
956              Here, the friend function is a template, but the context does
957              not have template information.  The optimized lookup relies
958              on having ARGS be the template arguments for both the class
959              and the function template.  */
960           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
961 }
962
963 /* Retrieve the specialization (in the sense of [temp.spec] - a
964    specialization is either an instantiation or an explicit
965    specialization) of TMPL for the given template ARGS.  If there is
966    no such specialization, return NULL_TREE.  The ARGS are a vector of
967    arguments, or a vector of vectors of arguments, in the case of
968    templates with more than one level of parameters.
969
970    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
971    then we search for a partial specialization matching ARGS.  This
972    parameter is ignored if TMPL is not a class template.  */
973
974 static tree
975 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
976 {
977   if (args == error_mark_node)
978     return NULL_TREE;
979
980   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
981
982   /* There should be as many levels of arguments as there are
983      levels of parameters.  */
984   gcc_assert (TMPL_ARGS_DEPTH (args)
985               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
986
987   if (optimize_specialization_lookup_p (tmpl))
988     {
989       tree class_template;
990       tree class_specialization;
991       VEC(tree,gc) *methods;
992       tree fns;
993       int idx;
994
995       /* The template arguments actually apply to the containing
996          class.  Find the class specialization with those
997          arguments.  */
998       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
999       class_specialization
1000         = retrieve_specialization (class_template, args, 0);
1001       if (!class_specialization)
1002         return NULL_TREE;
1003       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
1004          for the specialization.  */
1005       idx = class_method_index_for_fn (class_specialization, tmpl);
1006       if (idx == -1)
1007         return NULL_TREE;
1008       /* Iterate through the methods with the indicated name, looking
1009          for the one that has an instance of TMPL.  */
1010       methods = CLASSTYPE_METHOD_VEC (class_specialization);
1011       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
1012         {
1013           tree fn = OVL_CURRENT (fns);
1014           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl
1015               /* using-declarations can add base methods to the method vec,
1016                  and we don't want those here.  */
1017               && DECL_CONTEXT (fn) == class_specialization)
1018             return fn;
1019         }
1020       return NULL_TREE;
1021     }
1022   else
1023     {
1024       spec_entry *found;
1025       spec_entry elt;
1026       htab_t specializations;
1027
1028       elt.tmpl = tmpl;
1029       elt.args = args;
1030       elt.spec = NULL_TREE;
1031
1032       if (DECL_CLASS_TEMPLATE_P (tmpl))
1033         specializations = type_specializations;
1034       else
1035         specializations = decl_specializations;
1036
1037       if (hash == 0)
1038         hash = hash_specialization (&elt);
1039       found = (spec_entry *) htab_find_with_hash (specializations, &elt, hash);
1040       if (found)
1041         return found->spec;
1042     }
1043
1044   return NULL_TREE;
1045 }
1046
1047 /* Like retrieve_specialization, but for local declarations.  */
1048
1049 static tree
1050 retrieve_local_specialization (tree tmpl)
1051 {
1052   tree spec;
1053
1054   if (local_specializations == NULL)
1055     return NULL_TREE;
1056
1057   spec = (tree) htab_find_with_hash (local_specializations, tmpl,
1058                                      htab_hash_pointer (tmpl));
1059   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
1060 }
1061
1062 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1063
1064 int
1065 is_specialization_of (tree decl, tree tmpl)
1066 {
1067   tree t;
1068
1069   if (TREE_CODE (decl) == FUNCTION_DECL)
1070     {
1071       for (t = decl;
1072            t != NULL_TREE;
1073            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1074         if (t == tmpl)
1075           return 1;
1076     }
1077   else
1078     {
1079       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1080
1081       for (t = TREE_TYPE (decl);
1082            t != NULL_TREE;
1083            t = CLASSTYPE_USE_TEMPLATE (t)
1084              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1085         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1086           return 1;
1087     }
1088
1089   return 0;
1090 }
1091
1092 /* Returns nonzero iff DECL is a specialization of friend declaration
1093    FRIEND_DECL according to [temp.friend].  */
1094
1095 bool
1096 is_specialization_of_friend (tree decl, tree friend_decl)
1097 {
1098   bool need_template = true;
1099   int template_depth;
1100
1101   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1102               || TREE_CODE (decl) == TYPE_DECL);
1103
1104   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1105      of a template class, we want to check if DECL is a specialization
1106      if this.  */
1107   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1108       && DECL_TEMPLATE_INFO (friend_decl)
1109       && !DECL_USE_TEMPLATE (friend_decl))
1110     {
1111       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1112       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1113       need_template = false;
1114     }
1115   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1116            && !PRIMARY_TEMPLATE_P (friend_decl))
1117     need_template = false;
1118
1119   /* There is nothing to do if this is not a template friend.  */
1120   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1121     return false;
1122
1123   if (is_specialization_of (decl, friend_decl))
1124     return true;
1125
1126   /* [temp.friend/6]
1127      A member of a class template may be declared to be a friend of a
1128      non-template class.  In this case, the corresponding member of
1129      every specialization of the class template is a friend of the
1130      class granting friendship.
1131
1132      For example, given a template friend declaration
1133
1134        template <class T> friend void A<T>::f();
1135
1136      the member function below is considered a friend
1137
1138        template <> struct A<int> {
1139          void f();
1140        };
1141
1142      For this type of template friend, TEMPLATE_DEPTH below will be
1143      nonzero.  To determine if DECL is a friend of FRIEND, we first
1144      check if the enclosing class is a specialization of another.  */
1145
1146   template_depth = template_class_depth (CP_DECL_CONTEXT (friend_decl));
1147   if (template_depth
1148       && DECL_CLASS_SCOPE_P (decl)
1149       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1150                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1151     {
1152       /* Next, we check the members themselves.  In order to handle
1153          a few tricky cases, such as when FRIEND_DECL's are
1154
1155            template <class T> friend void A<T>::g(T t);
1156            template <class T> template <T t> friend void A<T>::h();
1157
1158          and DECL's are
1159
1160            void A<int>::g(int);
1161            template <int> void A<int>::h();
1162
1163          we need to figure out ARGS, the template arguments from
1164          the context of DECL.  This is required for template substitution
1165          of `T' in the function parameter of `g' and template parameter
1166          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1167
1168       tree context = DECL_CONTEXT (decl);
1169       tree args = NULL_TREE;
1170       int current_depth = 0;
1171
1172       while (current_depth < template_depth)
1173         {
1174           if (CLASSTYPE_TEMPLATE_INFO (context))
1175             {
1176               if (current_depth == 0)
1177                 args = TYPE_TI_ARGS (context);
1178               else
1179                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1180               current_depth++;
1181             }
1182           context = TYPE_CONTEXT (context);
1183         }
1184
1185       if (TREE_CODE (decl) == FUNCTION_DECL)
1186         {
1187           bool is_template;
1188           tree friend_type;
1189           tree decl_type;
1190           tree friend_args_type;
1191           tree decl_args_type;
1192
1193           /* Make sure that both DECL and FRIEND_DECL are templates or
1194              non-templates.  */
1195           is_template = DECL_TEMPLATE_INFO (decl)
1196                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1197           if (need_template ^ is_template)
1198             return false;
1199           else if (is_template)
1200             {
1201               /* If both are templates, check template parameter list.  */
1202               tree friend_parms
1203                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1204                                          args, tf_none);
1205               if (!comp_template_parms
1206                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1207                       friend_parms))
1208                 return false;
1209
1210               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1211             }
1212           else
1213             decl_type = TREE_TYPE (decl);
1214
1215           friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1216                                               tf_none, NULL_TREE);
1217           if (friend_type == error_mark_node)
1218             return false;
1219
1220           /* Check if return types match.  */
1221           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1222             return false;
1223
1224           /* Check if function parameter types match, ignoring the
1225              `this' parameter.  */
1226           friend_args_type = TYPE_ARG_TYPES (friend_type);
1227           decl_args_type = TYPE_ARG_TYPES (decl_type);
1228           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1229             friend_args_type = TREE_CHAIN (friend_args_type);
1230           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1231             decl_args_type = TREE_CHAIN (decl_args_type);
1232
1233           return compparms (decl_args_type, friend_args_type);
1234         }
1235       else
1236         {
1237           /* DECL is a TYPE_DECL */
1238           bool is_template;
1239           tree decl_type = TREE_TYPE (decl);
1240
1241           /* Make sure that both DECL and FRIEND_DECL are templates or
1242              non-templates.  */
1243           is_template
1244             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1245               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1246
1247           if (need_template ^ is_template)
1248             return false;
1249           else if (is_template)
1250             {
1251               tree friend_parms;
1252               /* If both are templates, check the name of the two
1253                  TEMPLATE_DECL's first because is_friend didn't.  */
1254               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1255                   != DECL_NAME (friend_decl))
1256                 return false;
1257
1258               /* Now check template parameter list.  */
1259               friend_parms
1260                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1261                                          args, tf_none);
1262               return comp_template_parms
1263                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1264                  friend_parms);
1265             }
1266           else
1267             return (DECL_NAME (decl)
1268                     == DECL_NAME (friend_decl));
1269         }
1270     }
1271   return false;
1272 }
1273
1274 /* Register the specialization SPEC as a specialization of TMPL with
1275    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1276    is actually just a friend declaration.  Returns SPEC, or an
1277    equivalent prior declaration, if available.  */
1278
1279 static tree
1280 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1281                          hashval_t hash)
1282 {
1283   tree fn;
1284   spec_entry **slot = NULL;
1285   spec_entry elt;
1286
1287   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec));
1288
1289   if (TREE_CODE (spec) == FUNCTION_DECL
1290       && uses_template_parms (DECL_TI_ARGS (spec)))
1291     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1292        register it; we want the corresponding TEMPLATE_DECL instead.
1293        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1294        the more obvious `uses_template_parms (spec)' to avoid problems
1295        with default function arguments.  In particular, given
1296        something like this:
1297
1298           template <class T> void f(T t1, T t = T())
1299
1300        the default argument expression is not substituted for in an
1301        instantiation unless and until it is actually needed.  */
1302     return spec;
1303
1304   if (optimize_specialization_lookup_p (tmpl))
1305     /* We don't put these specializations in the hash table, but we might
1306        want to give an error about a mismatch.  */
1307     fn = retrieve_specialization (tmpl, args, 0);
1308   else
1309     {
1310       elt.tmpl = tmpl;
1311       elt.args = args;
1312       elt.spec = spec;
1313
1314       if (hash == 0)
1315         hash = hash_specialization (&elt);
1316
1317       slot = (spec_entry **)
1318         htab_find_slot_with_hash (decl_specializations, &elt, hash, INSERT);
1319       if (*slot)
1320         fn = (*slot)->spec;
1321       else
1322         fn = NULL_TREE;
1323     }
1324
1325   /* We can sometimes try to re-register a specialization that we've
1326      already got.  In particular, regenerate_decl_from_template calls
1327      duplicate_decls which will update the specialization list.  But,
1328      we'll still get called again here anyhow.  It's more convenient
1329      to simply allow this than to try to prevent it.  */
1330   if (fn == spec)
1331     return spec;
1332   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1333     {
1334       if (DECL_TEMPLATE_INSTANTIATION (fn))
1335         {
1336           if (DECL_ODR_USED (fn)
1337               || DECL_EXPLICIT_INSTANTIATION (fn))
1338             {
1339               error ("specialization of %qD after instantiation",
1340                      fn);
1341               return error_mark_node;
1342             }
1343           else
1344             {
1345               tree clone;
1346               /* This situation should occur only if the first
1347                  specialization is an implicit instantiation, the
1348                  second is an explicit specialization, and the
1349                  implicit instantiation has not yet been used.  That
1350                  situation can occur if we have implicitly
1351                  instantiated a member function and then specialized
1352                  it later.
1353
1354                  We can also wind up here if a friend declaration that
1355                  looked like an instantiation turns out to be a
1356                  specialization:
1357
1358                    template <class T> void foo(T);
1359                    class S { friend void foo<>(int) };
1360                    template <> void foo(int);
1361
1362                  We transform the existing DECL in place so that any
1363                  pointers to it become pointers to the updated
1364                  declaration.
1365
1366                  If there was a definition for the template, but not
1367                  for the specialization, we want this to look as if
1368                  there were no definition, and vice versa.  */
1369               DECL_INITIAL (fn) = NULL_TREE;
1370               duplicate_decls (spec, fn, is_friend);
1371               /* The call to duplicate_decls will have applied
1372                  [temp.expl.spec]:
1373
1374                    An explicit specialization of a function template
1375                    is inline only if it is explicitly declared to be,
1376                    and independently of whether its function template
1377                    is.
1378
1379                 to the primary function; now copy the inline bits to
1380                 the various clones.  */
1381               FOR_EACH_CLONE (clone, fn)
1382                 {
1383                   DECL_DECLARED_INLINE_P (clone)
1384                     = DECL_DECLARED_INLINE_P (fn);
1385                   DECL_SOURCE_LOCATION (clone)
1386                     = DECL_SOURCE_LOCATION (fn);
1387                 }
1388               check_specialization_namespace (fn);
1389
1390               return fn;
1391             }
1392         }
1393       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1394         {
1395           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1396             /* Dup decl failed, but this is a new definition. Set the
1397                line number so any errors match this new
1398                definition.  */
1399             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1400
1401           return fn;
1402         }
1403     }
1404   else if (fn)
1405     return duplicate_decls (spec, fn, is_friend);
1406
1407   /* A specialization must be declared in the same namespace as the
1408      template it is specializing.  */
1409   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1410       && !check_specialization_namespace (tmpl))
1411     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1412
1413   if (!optimize_specialization_lookup_p (tmpl))
1414     {
1415       gcc_assert (tmpl && args && spec);
1416       *slot = ggc_alloc_spec_entry ();
1417       **slot = elt;
1418       if (TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1419           && PRIMARY_TEMPLATE_P (tmpl)
1420           && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1421         /* TMPL is a forward declaration of a template function; keep a list
1422            of all specializations in case we need to reassign them to a friend
1423            template later in tsubst_friend_function.  */
1424         DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1425           = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1426     }
1427
1428   return spec;
1429 }
1430
1431 /* Returns true iff two spec_entry nodes are equivalent.  Only compares the
1432    TMPL and ARGS members, ignores SPEC.  */
1433
1434 static int
1435 eq_specializations (const void *p1, const void *p2)
1436 {
1437   const spec_entry *e1 = (const spec_entry *)p1;
1438   const spec_entry *e2 = (const spec_entry *)p2;
1439
1440   return (e1->tmpl == e2->tmpl
1441           && comp_template_args (e1->args, e2->args));
1442 }
1443
1444 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1445
1446 static hashval_t
1447 hash_tmpl_and_args (tree tmpl, tree args)
1448 {
1449   hashval_t val = DECL_UID (tmpl);
1450   return iterative_hash_template_arg (args, val);
1451 }
1452
1453 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1454    ignoring SPEC.  */
1455
1456 static hashval_t
1457 hash_specialization (const void *p)
1458 {
1459   const spec_entry *e = (const spec_entry *)p;
1460   return hash_tmpl_and_args (e->tmpl, e->args);
1461 }
1462
1463 /* Recursively calculate a hash value for a template argument ARG, for use
1464    in the hash tables of template specializations.  */
1465
1466 hashval_t
1467 iterative_hash_template_arg (tree arg, hashval_t val)
1468 {
1469   unsigned HOST_WIDE_INT i;
1470   enum tree_code code;
1471   char tclass;
1472
1473   if (arg == NULL_TREE)
1474     return iterative_hash_object (arg, val);
1475
1476   if (!TYPE_P (arg))
1477     STRIP_NOPS (arg);
1478
1479   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
1480     /* We can get one of these when re-hashing a previous entry in the middle
1481        of substituting into a pack expansion.  Just look through it.  */
1482     arg = ARGUMENT_PACK_SELECT_FROM_PACK (arg);
1483
1484   code = TREE_CODE (arg);
1485   tclass = TREE_CODE_CLASS (code);
1486
1487   val = iterative_hash_object (code, val);
1488
1489   switch (code)
1490     {
1491     case ERROR_MARK:
1492       return val;
1493
1494     case IDENTIFIER_NODE:
1495       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1496
1497     case TREE_VEC:
1498       {
1499         int i, len = TREE_VEC_LENGTH (arg);
1500         for (i = 0; i < len; ++i)
1501           val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1502         return val;
1503       }
1504
1505     case TYPE_PACK_EXPANSION:
1506     case EXPR_PACK_EXPANSION:
1507       return iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1508
1509     case TYPE_ARGUMENT_PACK:
1510     case NONTYPE_ARGUMENT_PACK:
1511       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1512
1513     case TREE_LIST:
1514       for (; arg; arg = TREE_CHAIN (arg))
1515         val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1516       return val;
1517
1518     case OVERLOAD:
1519       for (; arg; arg = OVL_CHAIN (arg))
1520         val = iterative_hash_template_arg (OVL_FUNCTION (arg), val);
1521       return val;
1522
1523     case CONSTRUCTOR:
1524       {
1525         tree field, value;
1526         FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1527           {
1528             val = iterative_hash_template_arg (field, val);
1529             val = iterative_hash_template_arg (value, val);
1530           }
1531         return val;
1532       }
1533
1534     case PARM_DECL:
1535       if (!DECL_ARTIFICIAL (arg))
1536         val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1537       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1538
1539     case TARGET_EXPR:
1540       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1541
1542     case PTRMEM_CST:
1543       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1544       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1545
1546     case TEMPLATE_PARM_INDEX:
1547       val = iterative_hash_template_arg
1548         (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1549       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1550       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1551
1552     case TRAIT_EXPR:
1553       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1554       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1555       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1556
1557     case BASELINK:
1558       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1559                                          val);
1560       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1561                                           val);
1562
1563     case MODOP_EXPR:
1564       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1565       code = TREE_CODE (TREE_OPERAND (arg, 1));
1566       val = iterative_hash_object (code, val);
1567       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1568
1569     case ARRAY_TYPE:
1570       /* layout_type sets structural equality for arrays of
1571          incomplete type, so we can't rely on the canonical type
1572          for hashing.  */
1573       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1574       return iterative_hash_template_arg (TYPE_DOMAIN (arg), val);
1575
1576     case LAMBDA_EXPR:
1577       /* A lambda can't appear in a template arg, but don't crash on
1578          erroneous input.  */
1579       gcc_assert (seen_error ());
1580       return val;
1581
1582     case CAST_EXPR:
1583     case STATIC_CAST_EXPR:
1584     case REINTERPRET_CAST_EXPR:
1585     case CONST_CAST_EXPR:
1586     case DYNAMIC_CAST_EXPR:
1587     case NEW_EXPR:
1588       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1589       /* Now hash operands as usual.  */
1590       break;
1591
1592     default:
1593       break;
1594     }
1595
1596   switch (tclass)
1597     {
1598     case tcc_type:
1599       if (TYPE_CANONICAL (arg))
1600         return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1601                                       val);
1602       else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1603         return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1604       /* Otherwise just compare the types during lookup.  */
1605       return val;
1606
1607     case tcc_declaration:
1608     case tcc_constant:
1609       return iterative_hash_expr (arg, val);
1610
1611     default:
1612       gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1613       {
1614         unsigned n = TREE_OPERAND_LENGTH (arg);
1615         for (i = 0; i < n; ++i)
1616           val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1617         return val;
1618       }
1619     }
1620   gcc_unreachable ();
1621   return 0;
1622 }
1623
1624 /* Unregister the specialization SPEC as a specialization of TMPL.
1625    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1626    if the SPEC was listed as a specialization of TMPL.
1627
1628    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1629
1630 bool
1631 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1632 {
1633   spec_entry **slot;
1634   spec_entry elt;
1635
1636   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1637   elt.args = TI_ARGS (tinfo);
1638   elt.spec = NULL_TREE;
1639
1640   slot = (spec_entry **) htab_find_slot (decl_specializations, &elt, INSERT);
1641   if (*slot)
1642     {
1643       gcc_assert ((*slot)->spec == spec || (*slot)->spec == new_spec);
1644       gcc_assert (new_spec != NULL_TREE);
1645       (*slot)->spec = new_spec;
1646       return 1;
1647     }
1648
1649   return 0;
1650 }
1651
1652 /* Compare an entry in the local specializations hash table P1 (which
1653    is really a pointer to a TREE_LIST) with P2 (which is really a
1654    DECL).  */
1655
1656 static int
1657 eq_local_specializations (const void *p1, const void *p2)
1658 {
1659   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1660 }
1661
1662 /* Hash P1, an entry in the local specializations table.  */
1663
1664 static hashval_t
1665 hash_local_specialization (const void* p1)
1666 {
1667   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1668 }
1669
1670 /* Like register_specialization, but for local declarations.  We are
1671    registering SPEC, an instantiation of TMPL.  */
1672
1673 static void
1674 register_local_specialization (tree spec, tree tmpl)
1675 {
1676   void **slot;
1677
1678   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1679                                    htab_hash_pointer (tmpl), INSERT);
1680   *slot = build_tree_list (spec, tmpl);
1681 }
1682
1683 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1684    specialized class.  */
1685
1686 bool
1687 explicit_class_specialization_p (tree type)
1688 {
1689   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1690     return false;
1691   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1692 }
1693
1694 /* Print the list of functions at FNS, going through all the overloads
1695    for each element of the list.  Alternatively, FNS can not be a
1696    TREE_LIST, in which case it will be printed together with all the
1697    overloads.
1698
1699    MORE and *STR should respectively be FALSE and NULL when the function
1700    is called from the outside.  They are used internally on recursive
1701    calls.  print_candidates manages the two parameters and leaves NULL
1702    in *STR when it ends.  */
1703
1704 static void
1705 print_candidates_1 (tree fns, bool more, const char **str)
1706 {
1707   tree fn, fn2;
1708   char *spaces = NULL;
1709
1710   for (fn = fns; fn; fn = OVL_NEXT (fn))
1711     if (TREE_CODE (fn) == TREE_LIST)
1712       {
1713         gcc_assert (!OVL_NEXT (fn) && !is_overloaded_fn (fn));
1714         for (fn2 = fn; fn2 != NULL_TREE; fn2 = TREE_CHAIN (fn2))
1715           print_candidates_1 (TREE_VALUE (fn2),
1716                               TREE_CHAIN (fn2) || more, str);
1717       }
1718     else
1719       {
1720         if (!*str)
1721           {
1722             /* Pick the prefix string.  */
1723             if (!more && !OVL_NEXT (fns))
1724               {
1725                 error ("candidate is: %+#D", OVL_CURRENT (fn));
1726                 continue;
1727               }
1728
1729             *str = _("candidates are:");
1730             spaces = get_spaces (*str);
1731           }
1732         error ("%s %+#D", *str, OVL_CURRENT (fn));
1733         *str = spaces ? spaces : *str;
1734       }
1735
1736   if (!more)
1737     {
1738       free (spaces);
1739       *str = NULL;
1740     }
1741 }
1742
1743 /* Print the list of candidate FNS in an error message.  */
1744
1745 void
1746 print_candidates (tree fns)
1747 {
1748   const char *str = NULL;
1749   print_candidates_1 (fns, false, &str);
1750   gcc_assert (str == NULL);
1751 }
1752
1753 /* Returns the template (one of the functions given by TEMPLATE_ID)
1754    which can be specialized to match the indicated DECL with the
1755    explicit template args given in TEMPLATE_ID.  The DECL may be
1756    NULL_TREE if none is available.  In that case, the functions in
1757    TEMPLATE_ID are non-members.
1758
1759    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1760    specialization of a member template.
1761
1762    The TEMPLATE_COUNT is the number of references to qualifying
1763    template classes that appeared in the name of the function. See
1764    check_explicit_specialization for a more accurate description.
1765
1766    TSK indicates what kind of template declaration (if any) is being
1767    declared.  TSK_TEMPLATE indicates that the declaration given by
1768    DECL, though a FUNCTION_DECL, has template parameters, and is
1769    therefore a template function.
1770
1771    The template args (those explicitly specified and those deduced)
1772    are output in a newly created vector *TARGS_OUT.
1773
1774    If it is impossible to determine the result, an error message is
1775    issued.  The error_mark_node is returned to indicate failure.  */
1776
1777 static tree
1778 determine_specialization (tree template_id,
1779                           tree decl,
1780                           tree* targs_out,
1781                           int need_member_template,
1782                           int template_count,
1783                           tmpl_spec_kind tsk)
1784 {
1785   tree fns;
1786   tree targs;
1787   tree explicit_targs;
1788   tree candidates = NULL_TREE;
1789   /* A TREE_LIST of templates of which DECL may be a specialization.
1790      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1791      corresponding TREE_PURPOSE is the set of template arguments that,
1792      when used to instantiate the template, would produce a function
1793      with the signature of DECL.  */
1794   tree templates = NULL_TREE;
1795   int header_count;
1796   struct cp_binding_level *b;
1797
1798   *targs_out = NULL_TREE;
1799
1800   if (template_id == error_mark_node || decl == error_mark_node)
1801     return error_mark_node;
1802
1803   fns = TREE_OPERAND (template_id, 0);
1804   explicit_targs = TREE_OPERAND (template_id, 1);
1805
1806   if (fns == error_mark_node)
1807     return error_mark_node;
1808
1809   /* Check for baselinks.  */
1810   if (BASELINK_P (fns))
1811     fns = BASELINK_FUNCTIONS (fns);
1812
1813   if (!is_overloaded_fn (fns))
1814     {
1815       error ("%qD is not a function template", fns);
1816       return error_mark_node;
1817     }
1818
1819   /* Count the number of template headers specified for this
1820      specialization.  */
1821   header_count = 0;
1822   for (b = current_binding_level;
1823        b->kind == sk_template_parms;
1824        b = b->level_chain)
1825     ++header_count;
1826
1827   for (; fns; fns = OVL_NEXT (fns))
1828     {
1829       tree fn = OVL_CURRENT (fns);
1830
1831       if (TREE_CODE (fn) == TEMPLATE_DECL)
1832         {
1833           tree decl_arg_types;
1834           tree fn_arg_types;
1835
1836           /* In case of explicit specialization, we need to check if
1837              the number of template headers appearing in the specialization
1838              is correct. This is usually done in check_explicit_specialization,
1839              but the check done there cannot be exhaustive when specializing
1840              member functions. Consider the following code:
1841
1842              template <> void A<int>::f(int);
1843              template <> template <> void A<int>::f(int);
1844
1845              Assuming that A<int> is not itself an explicit specialization
1846              already, the first line specializes "f" which is a non-template
1847              member function, whilst the second line specializes "f" which
1848              is a template member function. So both lines are syntactically
1849              correct, and check_explicit_specialization does not reject
1850              them.
1851
1852              Here, we can do better, as we are matching the specialization
1853              against the declarations. We count the number of template
1854              headers, and we check if they match TEMPLATE_COUNT + 1
1855              (TEMPLATE_COUNT is the number of qualifying template classes,
1856              plus there must be another header for the member template
1857              itself).
1858
1859              Notice that if header_count is zero, this is not a
1860              specialization but rather a template instantiation, so there
1861              is no check we can perform here.  */
1862           if (header_count && header_count != template_count + 1)
1863             continue;
1864
1865           /* Check that the number of template arguments at the
1866              innermost level for DECL is the same as for FN.  */
1867           if (current_binding_level->kind == sk_template_parms
1868               && !current_binding_level->explicit_spec_p
1869               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1870                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1871                                       (current_template_parms))))
1872             continue;
1873
1874           /* DECL might be a specialization of FN.  */
1875           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1876           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1877
1878           /* For a non-static member function, we need to make sure
1879              that the const qualification is the same.  Since
1880              get_bindings does not try to merge the "this" parameter,
1881              we must do the comparison explicitly.  */
1882           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1883               && !same_type_p (TREE_VALUE (fn_arg_types),
1884                                TREE_VALUE (decl_arg_types)))
1885             continue;
1886
1887           /* Skip the "this" parameter and, for constructors of
1888              classes with virtual bases, the VTT parameter.  A
1889              full specialization of a constructor will have a VTT
1890              parameter, but a template never will.  */ 
1891           decl_arg_types 
1892             = skip_artificial_parms_for (decl, decl_arg_types);
1893           fn_arg_types 
1894             = skip_artificial_parms_for (fn, fn_arg_types);
1895
1896           /* Check that the number of function parameters matches.
1897              For example,
1898                template <class T> void f(int i = 0);
1899                template <> void f<int>();
1900              The specialization f<int> is invalid but is not caught
1901              by get_bindings below.  */
1902           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1903             continue;
1904
1905           /* Function templates cannot be specializations; there are
1906              no partial specializations of functions.  Therefore, if
1907              the type of DECL does not match FN, there is no
1908              match.  */
1909           if (tsk == tsk_template)
1910             {
1911               if (compparms (fn_arg_types, decl_arg_types))
1912                 candidates = tree_cons (NULL_TREE, fn, candidates);
1913               continue;
1914             }
1915
1916           /* See whether this function might be a specialization of this
1917              template.  */
1918           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1919
1920           if (!targs)
1921             /* We cannot deduce template arguments that when used to
1922                specialize TMPL will produce DECL.  */
1923             continue;
1924
1925           /* Save this template, and the arguments deduced.  */
1926           templates = tree_cons (targs, fn, templates);
1927         }
1928       else if (need_member_template)
1929         /* FN is an ordinary member function, and we need a
1930            specialization of a member template.  */
1931         ;
1932       else if (TREE_CODE (fn) != FUNCTION_DECL)
1933         /* We can get IDENTIFIER_NODEs here in certain erroneous
1934            cases.  */
1935         ;
1936       else if (!DECL_FUNCTION_MEMBER_P (fn))
1937         /* This is just an ordinary non-member function.  Nothing can
1938            be a specialization of that.  */
1939         ;
1940       else if (DECL_ARTIFICIAL (fn))
1941         /* Cannot specialize functions that are created implicitly.  */
1942         ;
1943       else
1944         {
1945           tree decl_arg_types;
1946
1947           /* This is an ordinary member function.  However, since
1948              we're here, we can assume it's enclosing class is a
1949              template class.  For example,
1950
1951                template <typename T> struct S { void f(); };
1952                template <> void S<int>::f() {}
1953
1954              Here, S<int>::f is a non-template, but S<int> is a
1955              template class.  If FN has the same type as DECL, we
1956              might be in business.  */
1957
1958           if (!DECL_TEMPLATE_INFO (fn))
1959             /* Its enclosing class is an explicit specialization
1960                of a template class.  This is not a candidate.  */
1961             continue;
1962
1963           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1964                             TREE_TYPE (TREE_TYPE (fn))))
1965             /* The return types differ.  */
1966             continue;
1967
1968           /* Adjust the type of DECL in case FN is a static member.  */
1969           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1970           if (DECL_STATIC_FUNCTION_P (fn)
1971               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1972             decl_arg_types = TREE_CHAIN (decl_arg_types);
1973
1974           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1975                          decl_arg_types))
1976             /* They match!  */
1977             candidates = tree_cons (NULL_TREE, fn, candidates);
1978         }
1979     }
1980
1981   if (templates && TREE_CHAIN (templates))
1982     {
1983       /* We have:
1984
1985            [temp.expl.spec]
1986
1987            It is possible for a specialization with a given function
1988            signature to be instantiated from more than one function
1989            template.  In such cases, explicit specification of the
1990            template arguments must be used to uniquely identify the
1991            function template specialization being specialized.
1992
1993          Note that here, there's no suggestion that we're supposed to
1994          determine which of the candidate templates is most
1995          specialized.  However, we, also have:
1996
1997            [temp.func.order]
1998
1999            Partial ordering of overloaded function template
2000            declarations is used in the following contexts to select
2001            the function template to which a function template
2002            specialization refers:
2003
2004            -- when an explicit specialization refers to a function
2005               template.
2006
2007          So, we do use the partial ordering rules, at least for now.
2008          This extension can only serve to make invalid programs valid,
2009          so it's safe.  And, there is strong anecdotal evidence that
2010          the committee intended the partial ordering rules to apply;
2011          the EDG front end has that behavior, and John Spicer claims
2012          that the committee simply forgot to delete the wording in
2013          [temp.expl.spec].  */
2014       tree tmpl = most_specialized_instantiation (templates);
2015       if (tmpl != error_mark_node)
2016         {
2017           templates = tmpl;
2018           TREE_CHAIN (templates) = NULL_TREE;
2019         }
2020     }
2021
2022   if (templates == NULL_TREE && candidates == NULL_TREE)
2023     {
2024       error ("template-id %qD for %q+D does not match any template "
2025              "declaration", template_id, decl);
2026       if (header_count && header_count != template_count + 1)
2027         inform (input_location, "saw %d %<template<>%>, need %d for "
2028                 "specializing a member function template",
2029                 header_count, template_count + 1);
2030       return error_mark_node;
2031     }
2032   else if ((templates && TREE_CHAIN (templates))
2033            || (candidates && TREE_CHAIN (candidates))
2034            || (templates && candidates))
2035     {
2036       error ("ambiguous template specialization %qD for %q+D",
2037              template_id, decl);
2038       candidates = chainon (candidates, templates);
2039       print_candidates (candidates);
2040       return error_mark_node;
2041     }
2042
2043   /* We have one, and exactly one, match.  */
2044   if (candidates)
2045     {
2046       tree fn = TREE_VALUE (candidates);
2047       *targs_out = copy_node (DECL_TI_ARGS (fn));
2048       /* DECL is a re-declaration or partial instantiation of a template
2049          function.  */
2050       if (TREE_CODE (fn) == TEMPLATE_DECL)
2051         return fn;
2052       /* It was a specialization of an ordinary member function in a
2053          template class.  */
2054       return DECL_TI_TEMPLATE (fn);
2055     }
2056
2057   /* It was a specialization of a template.  */
2058   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2059   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2060     {
2061       *targs_out = copy_node (targs);
2062       SET_TMPL_ARGS_LEVEL (*targs_out,
2063                            TMPL_ARGS_DEPTH (*targs_out),
2064                            TREE_PURPOSE (templates));
2065     }
2066   else
2067     *targs_out = TREE_PURPOSE (templates);
2068   return TREE_VALUE (templates);
2069 }
2070
2071 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2072    but with the default argument values filled in from those in the
2073    TMPL_TYPES.  */
2074
2075 static tree
2076 copy_default_args_to_explicit_spec_1 (tree spec_types,
2077                                       tree tmpl_types)
2078 {
2079   tree new_spec_types;
2080
2081   if (!spec_types)
2082     return NULL_TREE;
2083
2084   if (spec_types == void_list_node)
2085     return void_list_node;
2086
2087   /* Substitute into the rest of the list.  */
2088   new_spec_types =
2089     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2090                                           TREE_CHAIN (tmpl_types));
2091
2092   /* Add the default argument for this parameter.  */
2093   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2094                          TREE_VALUE (spec_types),
2095                          new_spec_types);
2096 }
2097
2098 /* DECL is an explicit specialization.  Replicate default arguments
2099    from the template it specializes.  (That way, code like:
2100
2101      template <class T> void f(T = 3);
2102      template <> void f(double);
2103      void g () { f (); }
2104
2105    works, as required.)  An alternative approach would be to look up
2106    the correct default arguments at the call-site, but this approach
2107    is consistent with how implicit instantiations are handled.  */
2108
2109 static void
2110 copy_default_args_to_explicit_spec (tree decl)
2111 {
2112   tree tmpl;
2113   tree spec_types;
2114   tree tmpl_types;
2115   tree new_spec_types;
2116   tree old_type;
2117   tree new_type;
2118   tree t;
2119   tree object_type = NULL_TREE;
2120   tree in_charge = NULL_TREE;
2121   tree vtt = NULL_TREE;
2122
2123   /* See if there's anything we need to do.  */
2124   tmpl = DECL_TI_TEMPLATE (decl);
2125   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2126   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2127     if (TREE_PURPOSE (t))
2128       break;
2129   if (!t)
2130     return;
2131
2132   old_type = TREE_TYPE (decl);
2133   spec_types = TYPE_ARG_TYPES (old_type);
2134
2135   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2136     {
2137       /* Remove the this pointer, but remember the object's type for
2138          CV quals.  */
2139       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2140       spec_types = TREE_CHAIN (spec_types);
2141       tmpl_types = TREE_CHAIN (tmpl_types);
2142
2143       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2144         {
2145           /* DECL may contain more parameters than TMPL due to the extra
2146              in-charge parameter in constructors and destructors.  */
2147           in_charge = spec_types;
2148           spec_types = TREE_CHAIN (spec_types);
2149         }
2150       if (DECL_HAS_VTT_PARM_P (decl))
2151         {
2152           vtt = spec_types;
2153           spec_types = TREE_CHAIN (spec_types);
2154         }
2155     }
2156
2157   /* Compute the merged default arguments.  */
2158   new_spec_types =
2159     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2160
2161   /* Compute the new FUNCTION_TYPE.  */
2162   if (object_type)
2163     {
2164       if (vtt)
2165         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2166                                          TREE_VALUE (vtt),
2167                                          new_spec_types);
2168
2169       if (in_charge)
2170         /* Put the in-charge parameter back.  */
2171         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2172                                          TREE_VALUE (in_charge),
2173                                          new_spec_types);
2174
2175       new_type = build_method_type_directly (object_type,
2176                                              TREE_TYPE (old_type),
2177                                              new_spec_types);
2178     }
2179   else
2180     new_type = build_function_type (TREE_TYPE (old_type),
2181                                     new_spec_types);
2182   new_type = cp_build_type_attribute_variant (new_type,
2183                                               TYPE_ATTRIBUTES (old_type));
2184   new_type = build_exception_variant (new_type,
2185                                       TYPE_RAISES_EXCEPTIONS (old_type));
2186   TREE_TYPE (decl) = new_type;
2187 }
2188
2189 /* Check to see if the function just declared, as indicated in
2190    DECLARATOR, and in DECL, is a specialization of a function
2191    template.  We may also discover that the declaration is an explicit
2192    instantiation at this point.
2193
2194    Returns DECL, or an equivalent declaration that should be used
2195    instead if all goes well.  Issues an error message if something is
2196    amiss.  Returns error_mark_node if the error is not easily
2197    recoverable.
2198
2199    FLAGS is a bitmask consisting of the following flags:
2200
2201    2: The function has a definition.
2202    4: The function is a friend.
2203
2204    The TEMPLATE_COUNT is the number of references to qualifying
2205    template classes that appeared in the name of the function.  For
2206    example, in
2207
2208      template <class T> struct S { void f(); };
2209      void S<int>::f();
2210
2211    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2212    classes are not counted in the TEMPLATE_COUNT, so that in
2213
2214      template <class T> struct S {};
2215      template <> struct S<int> { void f(); }
2216      template <> void S<int>::f();
2217
2218    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2219    invalid; there should be no template <>.)
2220
2221    If the function is a specialization, it is marked as such via
2222    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2223    is set up correctly, and it is added to the list of specializations
2224    for that template.  */
2225
2226 tree
2227 check_explicit_specialization (tree declarator,
2228                                tree decl,
2229                                int template_count,
2230                                int flags)
2231 {
2232   int have_def = flags & 2;
2233   int is_friend = flags & 4;
2234   int specialization = 0;
2235   int explicit_instantiation = 0;
2236   int member_specialization = 0;
2237   tree ctype = DECL_CLASS_CONTEXT (decl);
2238   tree dname = DECL_NAME (decl);
2239   tmpl_spec_kind tsk;
2240
2241   if (is_friend)
2242     {
2243       if (!processing_specialization)
2244         tsk = tsk_none;
2245       else
2246         tsk = tsk_excessive_parms;
2247     }
2248   else
2249     tsk = current_tmpl_spec_kind (template_count);
2250
2251   switch (tsk)
2252     {
2253     case tsk_none:
2254       if (processing_specialization)
2255         {
2256           specialization = 1;
2257           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2258         }
2259       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2260         {
2261           if (is_friend)
2262             /* This could be something like:
2263
2264                template <class T> void f(T);
2265                class S { friend void f<>(int); }  */
2266             specialization = 1;
2267           else
2268             {
2269               /* This case handles bogus declarations like template <>
2270                  template <class T> void f<int>(); */
2271
2272               error ("template-id %qD in declaration of primary template",
2273                      declarator);
2274               return decl;
2275             }
2276         }
2277       break;
2278
2279     case tsk_invalid_member_spec:
2280       /* The error has already been reported in
2281          check_specialization_scope.  */
2282       return error_mark_node;
2283
2284     case tsk_invalid_expl_inst:
2285       error ("template parameter list used in explicit instantiation");
2286
2287       /* Fall through.  */
2288
2289     case tsk_expl_inst:
2290       if (have_def)
2291         error ("definition provided for explicit instantiation");
2292
2293       explicit_instantiation = 1;
2294       break;
2295
2296     case tsk_excessive_parms:
2297     case tsk_insufficient_parms:
2298       if (tsk == tsk_excessive_parms)
2299         error ("too many template parameter lists in declaration of %qD",
2300                decl);
2301       else if (template_header_count)
2302         error("too few template parameter lists in declaration of %qD", decl);
2303       else
2304         error("explicit specialization of %qD must be introduced by "
2305               "%<template <>%>", decl);
2306
2307       /* Fall through.  */
2308     case tsk_expl_spec:
2309       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2310       if (ctype)
2311         member_specialization = 1;
2312       else
2313         specialization = 1;
2314       break;
2315
2316     case tsk_template:
2317       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2318         {
2319           /* This case handles bogus declarations like template <>
2320              template <class T> void f<int>(); */
2321
2322           if (uses_template_parms (declarator))
2323             error ("function template partial specialization %qD "
2324                    "is not allowed", declarator);
2325           else
2326             error ("template-id %qD in declaration of primary template",
2327                    declarator);
2328           return decl;
2329         }
2330
2331       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2332         /* This is a specialization of a member template, without
2333            specialization the containing class.  Something like:
2334
2335              template <class T> struct S {
2336                template <class U> void f (U);
2337              };
2338              template <> template <class U> void S<int>::f(U) {}
2339
2340            That's a specialization -- but of the entire template.  */
2341         specialization = 1;
2342       break;
2343
2344     default:
2345       gcc_unreachable ();
2346     }
2347
2348   if (specialization || member_specialization)
2349     {
2350       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2351       for (; t; t = TREE_CHAIN (t))
2352         if (TREE_PURPOSE (t))
2353           {
2354             permerror (input_location, 
2355                        "default argument specified in explicit specialization");
2356             break;
2357           }
2358     }
2359
2360   if (specialization || member_specialization || explicit_instantiation)
2361     {
2362       tree tmpl = NULL_TREE;
2363       tree targs = NULL_TREE;
2364
2365       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2366       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2367         {
2368           tree fns;
2369
2370           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2371           if (ctype)
2372             fns = dname;
2373           else
2374             {
2375               /* If there is no class context, the explicit instantiation
2376                  must be at namespace scope.  */
2377               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2378
2379               /* Find the namespace binding, using the declaration
2380                  context.  */
2381               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2382                                            false, true);
2383               if (fns == error_mark_node || !is_overloaded_fn (fns))
2384                 {
2385                   error ("%qD is not a template function", dname);
2386                   fns = error_mark_node;
2387                 }
2388               else
2389                 {
2390                   tree fn = OVL_CURRENT (fns);
2391                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2392                                                 CP_DECL_CONTEXT (fn)))
2393                     error ("%qD is not declared in %qD",
2394                            decl, current_namespace);
2395                 }
2396             }
2397
2398           declarator = lookup_template_function (fns, NULL_TREE);
2399         }
2400
2401       if (declarator == error_mark_node)
2402         return error_mark_node;
2403
2404       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2405         {
2406           if (!explicit_instantiation)
2407             /* A specialization in class scope.  This is invalid,
2408                but the error will already have been flagged by
2409                check_specialization_scope.  */
2410             return error_mark_node;
2411           else
2412             {
2413               /* It's not valid to write an explicit instantiation in
2414                  class scope, e.g.:
2415
2416                    class C { template void f(); }
2417
2418                    This case is caught by the parser.  However, on
2419                    something like:
2420
2421                    template class C { void f(); };
2422
2423                    (which is invalid) we can get here.  The error will be
2424                    issued later.  */
2425               ;
2426             }
2427
2428           return decl;
2429         }
2430       else if (ctype != NULL_TREE
2431                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2432                    IDENTIFIER_NODE))
2433         {
2434           /* Find the list of functions in ctype that have the same
2435              name as the declared function.  */
2436           tree name = TREE_OPERAND (declarator, 0);
2437           tree fns = NULL_TREE;
2438           int idx;
2439
2440           if (constructor_name_p (name, ctype))
2441             {
2442               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2443
2444               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2445                   : !CLASSTYPE_DESTRUCTORS (ctype))
2446                 {
2447                   /* From [temp.expl.spec]:
2448
2449                      If such an explicit specialization for the member
2450                      of a class template names an implicitly-declared
2451                      special member function (clause _special_), the
2452                      program is ill-formed.
2453
2454                      Similar language is found in [temp.explicit].  */
2455                   error ("specialization of implicitly-declared special member function");
2456                   return error_mark_node;
2457                 }
2458
2459               name = is_constructor ? ctor_identifier : dtor_identifier;
2460             }
2461
2462           if (!DECL_CONV_FN_P (decl))
2463             {
2464               idx = lookup_fnfields_1 (ctype, name);
2465               if (idx >= 0)
2466                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2467             }
2468           else
2469             {
2470               VEC(tree,gc) *methods;
2471               tree ovl;
2472
2473               /* For a type-conversion operator, we cannot do a
2474                  name-based lookup.  We might be looking for `operator
2475                  int' which will be a specialization of `operator T'.
2476                  So, we find *all* the conversion operators, and then
2477                  select from them.  */
2478               fns = NULL_TREE;
2479
2480               methods = CLASSTYPE_METHOD_VEC (ctype);
2481               if (methods)
2482                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2483                      VEC_iterate (tree, methods, idx, ovl);
2484                      ++idx)
2485                   {
2486                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2487                       /* There are no more conversion functions.  */
2488                       break;
2489
2490                     /* Glue all these conversion functions together
2491                        with those we already have.  */
2492                     for (; ovl; ovl = OVL_NEXT (ovl))
2493                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2494                   }
2495             }
2496
2497           if (fns == NULL_TREE)
2498             {
2499               error ("no member function %qD declared in %qT", name, ctype);
2500               return error_mark_node;
2501             }
2502           else
2503             TREE_OPERAND (declarator, 0) = fns;
2504         }
2505
2506       /* Figure out what exactly is being specialized at this point.
2507          Note that for an explicit instantiation, even one for a
2508          member function, we cannot tell apriori whether the
2509          instantiation is for a member template, or just a member
2510          function of a template class.  Even if a member template is
2511          being instantiated, the member template arguments may be
2512          elided if they can be deduced from the rest of the
2513          declaration.  */
2514       tmpl = determine_specialization (declarator, decl,
2515                                        &targs,
2516                                        member_specialization,
2517                                        template_count,
2518                                        tsk);
2519
2520       if (!tmpl || tmpl == error_mark_node)
2521         /* We couldn't figure out what this declaration was
2522            specializing.  */
2523         return error_mark_node;
2524       else
2525         {
2526           tree gen_tmpl = most_general_template (tmpl);
2527
2528           if (explicit_instantiation)
2529             {
2530               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2531                  is done by do_decl_instantiation later.  */
2532
2533               int arg_depth = TMPL_ARGS_DEPTH (targs);
2534               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2535
2536               if (arg_depth > parm_depth)
2537                 {
2538                   /* If TMPL is not the most general template (for
2539                      example, if TMPL is a friend template that is
2540                      injected into namespace scope), then there will
2541                      be too many levels of TARGS.  Remove some of them
2542                      here.  */
2543                   int i;
2544                   tree new_targs;
2545
2546                   new_targs = make_tree_vec (parm_depth);
2547                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2548                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2549                       = TREE_VEC_ELT (targs, i);
2550                   targs = new_targs;
2551                 }
2552
2553               return instantiate_template (tmpl, targs, tf_error);
2554             }
2555
2556           /* If we thought that the DECL was a member function, but it
2557              turns out to be specializing a static member function,
2558              make DECL a static member function as well.  */
2559           if (DECL_STATIC_FUNCTION_P (tmpl)
2560               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2561             revert_static_member_fn (decl);
2562
2563           /* If this is a specialization of a member template of a
2564              template class, we want to return the TEMPLATE_DECL, not
2565              the specialization of it.  */
2566           if (tsk == tsk_template)
2567             {
2568               tree result = DECL_TEMPLATE_RESULT (tmpl);
2569               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2570               DECL_INITIAL (result) = NULL_TREE;
2571               if (have_def)
2572                 {
2573                   tree parm;
2574                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2575                   DECL_SOURCE_LOCATION (result)
2576                     = DECL_SOURCE_LOCATION (decl);
2577                   /* We want to use the argument list specified in the
2578                      definition, not in the original declaration.  */
2579                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2580                   for (parm = DECL_ARGUMENTS (result); parm;
2581                        parm = DECL_CHAIN (parm))
2582                     DECL_CONTEXT (parm) = result;
2583                 }
2584               return register_specialization (tmpl, gen_tmpl, targs,
2585                                               is_friend, 0);
2586             }
2587
2588           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2589           DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
2590
2591           /* Inherit default function arguments from the template
2592              DECL is specializing.  */
2593           copy_default_args_to_explicit_spec (decl);
2594
2595           /* This specialization has the same protection as the
2596              template it specializes.  */
2597           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2598           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2599
2600           /* 7.1.1-1 [dcl.stc]
2601
2602              A storage-class-specifier shall not be specified in an
2603              explicit specialization...
2604
2605              The parser rejects these, so unless action is taken here,
2606              explicit function specializations will always appear with
2607              global linkage.
2608
2609              The action recommended by the C++ CWG in response to C++
2610              defect report 605 is to make the storage class and linkage
2611              of the explicit specialization match the templated function:
2612
2613              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2614            */
2615           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2616             {
2617               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2618               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2619
2620               /* This specialization has the same linkage and visibility as
2621                  the function template it specializes.  */
2622               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2623               if (! TREE_PUBLIC (decl))
2624                 {
2625                   DECL_INTERFACE_KNOWN (decl) = 1;
2626                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2627                 }
2628               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2629               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2630                 {
2631                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2632                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2633                 }
2634             }
2635
2636           /* If DECL is a friend declaration, declared using an
2637              unqualified name, the namespace associated with DECL may
2638              have been set incorrectly.  For example, in:
2639
2640                template <typename T> void f(T);
2641                namespace N {
2642                  struct S { friend void f<int>(int); }
2643                }
2644
2645              we will have set the DECL_CONTEXT for the friend
2646              declaration to N, rather than to the global namespace.  */
2647           if (DECL_NAMESPACE_SCOPE_P (decl))
2648             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2649
2650           if (is_friend && !have_def)
2651             /* This is not really a declaration of a specialization.
2652                It's just the name of an instantiation.  But, it's not
2653                a request for an instantiation, either.  */
2654             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2655           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2656             /* This is indeed a specialization.  In case of constructors
2657                and destructors, we need in-charge and not-in-charge
2658                versions in V3 ABI.  */
2659             clone_function_decl (decl, /*update_method_vec_p=*/0);
2660
2661           /* Register this specialization so that we can find it
2662              again.  */
2663           decl = register_specialization (decl, gen_tmpl, targs, is_friend, 0);
2664         }
2665     }
2666
2667   return decl;
2668 }
2669
2670 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2671    parameters.  These are represented in the same format used for
2672    DECL_TEMPLATE_PARMS.  */
2673
2674 int
2675 comp_template_parms (const_tree parms1, const_tree parms2)
2676 {
2677   const_tree p1;
2678   const_tree p2;
2679
2680   if (parms1 == parms2)
2681     return 1;
2682
2683   for (p1 = parms1, p2 = parms2;
2684        p1 != NULL_TREE && p2 != NULL_TREE;
2685        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2686     {
2687       tree t1 = TREE_VALUE (p1);
2688       tree t2 = TREE_VALUE (p2);
2689       int i;
2690
2691       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2692       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2693
2694       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2695         return 0;
2696
2697       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2698         {
2699           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2700           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2701
2702           /* If either of the template parameters are invalid, assume
2703              they match for the sake of error recovery. */
2704           if (parm1 == error_mark_node || parm2 == error_mark_node)
2705             return 1;
2706
2707           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2708             return 0;
2709
2710           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2711               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2712                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2713             continue;
2714           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2715             return 0;
2716         }
2717     }
2718
2719   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2720     /* One set of parameters has more parameters lists than the
2721        other.  */
2722     return 0;
2723
2724   return 1;
2725 }
2726
2727 /* Determine whether PARM is a parameter pack.  */
2728
2729 bool 
2730 template_parameter_pack_p (const_tree parm)
2731 {
2732   /* Determine if we have a non-type template parameter pack.  */
2733   if (TREE_CODE (parm) == PARM_DECL)
2734     return (DECL_TEMPLATE_PARM_P (parm) 
2735             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2736
2737   /* If this is a list of template parameters, we could get a
2738      TYPE_DECL or a TEMPLATE_DECL.  */ 
2739   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2740     parm = TREE_TYPE (parm);
2741
2742   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2743            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2744           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2745 }
2746
2747 /* Determine if T is a function parameter pack.  */
2748
2749 bool
2750 function_parameter_pack_p (const_tree t)
2751 {
2752   if (t && TREE_CODE (t) == PARM_DECL)
2753     return FUNCTION_PARAMETER_PACK_P (t);
2754   return false;
2755 }
2756
2757 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
2758    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
2759
2760 tree
2761 get_function_template_decl (const_tree primary_func_tmpl_inst)
2762 {
2763   if (! primary_func_tmpl_inst
2764       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
2765       || ! primary_template_instantiation_p (primary_func_tmpl_inst))
2766     return NULL;
2767
2768   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
2769 }
2770
2771 /* Return true iff the function parameter PARAM_DECL was expanded
2772    from the function parameter pack PACK.  */
2773
2774 bool
2775 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
2776 {
2777   if (DECL_ARTIFICIAL (param_decl)
2778       || !function_parameter_pack_p (pack))
2779     return false;
2780
2781   /* The parameter pack and its pack arguments have the same
2782      DECL_PARM_INDEX.  */
2783   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
2784 }
2785
2786 /* Determine whether ARGS describes a variadic template args list,
2787    i.e., one that is terminated by a template argument pack.  */
2788
2789 static bool 
2790 template_args_variadic_p (tree args)
2791 {
2792   int nargs;
2793   tree last_parm;
2794
2795   if (args == NULL_TREE)
2796     return false;
2797
2798   args = INNERMOST_TEMPLATE_ARGS (args);
2799   nargs = TREE_VEC_LENGTH (args);
2800
2801   if (nargs == 0)
2802     return false;
2803
2804   last_parm = TREE_VEC_ELT (args, nargs - 1);
2805
2806   return ARGUMENT_PACK_P (last_parm);
2807 }
2808
2809 /* Generate a new name for the parameter pack name NAME (an
2810    IDENTIFIER_NODE) that incorporates its */
2811
2812 static tree
2813 make_ith_pack_parameter_name (tree name, int i)
2814 {
2815   /* Munge the name to include the parameter index.  */
2816 #define NUMBUF_LEN 128
2817   char numbuf[NUMBUF_LEN];
2818   char* newname;
2819   int newname_len;
2820
2821   snprintf (numbuf, NUMBUF_LEN, "%i", i);
2822   newname_len = IDENTIFIER_LENGTH (name)
2823                 + strlen (numbuf) + 2;
2824   newname = (char*)alloca (newname_len);
2825   snprintf (newname, newname_len,
2826             "%s#%i", IDENTIFIER_POINTER (name), i);
2827   return get_identifier (newname);
2828 }
2829
2830 /* Return true if T is a primary function
2831    or class template instantiation.  */
2832
2833 bool
2834 primary_template_instantiation_p (const_tree t)
2835 {
2836   if (!t)
2837     return false;
2838
2839   if (TREE_CODE (t) == FUNCTION_DECL)
2840     return DECL_LANG_SPECIFIC (t)
2841            && DECL_TEMPLATE_INSTANTIATION (t)
2842            && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t));
2843   else if (CLASS_TYPE_P (t))
2844     return CLASSTYPE_TEMPLATE_INSTANTIATION (t)
2845            && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t));
2846   return false;
2847 }
2848
2849 /* Return true if PARM is a template template parameter.  */
2850
2851 bool
2852 template_template_parameter_p (const_tree parm)
2853 {
2854   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
2855 }
2856
2857 /* Return the template parameters of T if T is a
2858    primary template instantiation, NULL otherwise.  */
2859
2860 tree
2861 get_primary_template_innermost_parameters (const_tree t)
2862 {
2863   tree parms = NULL, template_info = NULL;
2864
2865   if ((template_info = get_template_info (t))
2866       && primary_template_instantiation_p (t))
2867     parms = INNERMOST_TEMPLATE_PARMS
2868         (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
2869
2870   return parms;
2871 }
2872
2873 /* Return the template parameters of the LEVELth level from the full list
2874    of template parameters PARMS.  */
2875
2876 tree
2877 get_template_parms_at_level (tree parms, int level)
2878 {
2879   tree p;
2880   if (!parms
2881       || TREE_CODE (parms) != TREE_LIST
2882       || level > TMPL_PARMS_DEPTH (parms))
2883     return NULL_TREE;
2884
2885   for (p = parms; p; p = TREE_CHAIN (p))
2886     if (TMPL_PARMS_DEPTH (p) == level)
2887       return p;
2888
2889   return NULL_TREE;
2890 }
2891
2892 /* Returns the template arguments of T if T is a template instantiation,
2893    NULL otherwise.  */
2894
2895 tree
2896 get_template_innermost_arguments (const_tree t)
2897 {
2898   tree args = NULL, template_info = NULL;
2899
2900   if ((template_info = get_template_info (t))
2901       && TI_ARGS (template_info))
2902     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
2903
2904   return args;
2905 }
2906
2907 /* Return the argument pack elements of T if T is a template argument pack,
2908    NULL otherwise.  */
2909
2910 tree
2911 get_template_argument_pack_elems (const_tree t)
2912 {
2913   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
2914       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
2915     return NULL;
2916
2917   return ARGUMENT_PACK_ARGS (t);
2918 }
2919
2920 /* Structure used to track the progress of find_parameter_packs_r.  */
2921 struct find_parameter_pack_data 
2922 {
2923   /* TREE_LIST that will contain all of the parameter packs found by
2924      the traversal.  */
2925   tree* parameter_packs;
2926
2927   /* Set of AST nodes that have been visited by the traversal.  */
2928   struct pointer_set_t *visited;
2929 };
2930
2931 /* Identifies all of the argument packs that occur in a template
2932    argument and appends them to the TREE_LIST inside DATA, which is a
2933    find_parameter_pack_data structure. This is a subroutine of
2934    make_pack_expansion and uses_parameter_packs.  */
2935 static tree
2936 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2937 {
2938   tree t = *tp;
2939   struct find_parameter_pack_data* ppd = 
2940     (struct find_parameter_pack_data*)data;
2941   bool parameter_pack_p = false;
2942
2943   /* Identify whether this is a parameter pack or not.  */
2944   switch (TREE_CODE (t))
2945     {
2946     case TEMPLATE_PARM_INDEX:
2947       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2948         parameter_pack_p = true;
2949       break;
2950
2951     case TEMPLATE_TYPE_PARM:
2952     case TEMPLATE_TEMPLATE_PARM:
2953       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2954         parameter_pack_p = true;
2955       break;
2956
2957     case PARM_DECL:
2958       if (FUNCTION_PARAMETER_PACK_P (t))
2959         {
2960           /* We don't want to walk into the type of a PARM_DECL,
2961              because we don't want to see the type parameter pack.  */
2962           *walk_subtrees = 0;
2963           parameter_pack_p = true;
2964         }
2965       break;
2966
2967     default:
2968       /* Not a parameter pack.  */
2969       break;
2970     }
2971
2972   if (parameter_pack_p)
2973     {
2974       /* Add this parameter pack to the list.  */
2975       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2976     }
2977
2978   if (TYPE_P (t))
2979     cp_walk_tree (&TYPE_CONTEXT (t), 
2980                   &find_parameter_packs_r, ppd, ppd->visited);
2981
2982   /* This switch statement will return immediately if we don't find a
2983      parameter pack.  */
2984   switch (TREE_CODE (t)) 
2985     {
2986     case TEMPLATE_PARM_INDEX:
2987       return NULL_TREE;
2988
2989     case BOUND_TEMPLATE_TEMPLATE_PARM:
2990       /* Check the template itself.  */
2991       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
2992                     &find_parameter_packs_r, ppd, ppd->visited);
2993       /* Check the template arguments.  */
2994       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
2995                     ppd->visited);
2996       *walk_subtrees = 0;
2997       return NULL_TREE;
2998
2999     case TEMPLATE_TYPE_PARM:
3000     case TEMPLATE_TEMPLATE_PARM:
3001       return NULL_TREE;
3002
3003     case PARM_DECL:
3004       return NULL_TREE;
3005
3006     case RECORD_TYPE:
3007       if (TYPE_PTRMEMFUNC_P (t))
3008         return NULL_TREE;
3009       /* Fall through.  */
3010
3011     case UNION_TYPE:
3012     case ENUMERAL_TYPE:
3013       if (TYPE_TEMPLATE_INFO (t))
3014         cp_walk_tree (&TI_ARGS (TYPE_TEMPLATE_INFO (t)),
3015                       &find_parameter_packs_r, ppd, ppd->visited);
3016
3017       *walk_subtrees = 0;
3018       return NULL_TREE;
3019
3020     case TEMPLATE_DECL:
3021       cp_walk_tree (&TREE_TYPE (t),
3022                     &find_parameter_packs_r, ppd, ppd->visited);
3023       return NULL_TREE;
3024  
3025     case TYPENAME_TYPE:
3026       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
3027                    ppd, ppd->visited);
3028       *walk_subtrees = 0;
3029       return NULL_TREE;
3030       
3031     case TYPE_PACK_EXPANSION:
3032     case EXPR_PACK_EXPANSION:
3033       *walk_subtrees = 0;
3034       return NULL_TREE;
3035
3036     case INTEGER_TYPE:
3037       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
3038                     ppd, ppd->visited);
3039       *walk_subtrees = 0;
3040       return NULL_TREE;
3041
3042     case IDENTIFIER_NODE:
3043       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
3044                     ppd->visited);
3045       *walk_subtrees = 0;
3046       return NULL_TREE;
3047
3048     default:
3049       return NULL_TREE;
3050     }
3051
3052   return NULL_TREE;
3053 }
3054
3055 /* Determines if the expression or type T uses any parameter packs.  */
3056 bool
3057 uses_parameter_packs (tree t)
3058 {
3059   tree parameter_packs = NULL_TREE;
3060   struct find_parameter_pack_data ppd;
3061   ppd.parameter_packs = &parameter_packs;
3062   ppd.visited = pointer_set_create ();
3063   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3064   pointer_set_destroy (ppd.visited);
3065   return parameter_packs != NULL_TREE;
3066 }
3067
3068 /* Turn ARG, which may be an expression, type, or a TREE_LIST
3069    representation a base-class initializer into a parameter pack
3070    expansion. If all goes well, the resulting node will be an
3071    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
3072    respectively.  */
3073 tree 
3074 make_pack_expansion (tree arg)
3075 {
3076   tree result;
3077   tree parameter_packs = NULL_TREE;
3078   bool for_types = false;
3079   struct find_parameter_pack_data ppd;
3080
3081   if (!arg || arg == error_mark_node)
3082     return arg;
3083
3084   if (TREE_CODE (arg) == TREE_LIST)
3085     {
3086       /* The only time we will see a TREE_LIST here is for a base
3087          class initializer.  In this case, the TREE_PURPOSE will be a
3088          _TYPE node (representing the base class expansion we're
3089          initializing) and the TREE_VALUE will be a TREE_LIST
3090          containing the initialization arguments. 
3091
3092          The resulting expansion looks somewhat different from most
3093          expansions. Rather than returning just one _EXPANSION, we
3094          return a TREE_LIST whose TREE_PURPOSE is a
3095          TYPE_PACK_EXPANSION containing the bases that will be
3096          initialized.  The TREE_VALUE will be identical to the
3097          original TREE_VALUE, which is a list of arguments that will
3098          be passed to each base.  We do not introduce any new pack
3099          expansion nodes into the TREE_VALUE (although it is possible
3100          that some already exist), because the TREE_PURPOSE and
3101          TREE_VALUE all need to be expanded together with the same
3102          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3103          resulting TREE_PURPOSE will mention the parameter packs in
3104          both the bases and the arguments to the bases.  */
3105       tree purpose;
3106       tree value;
3107       tree parameter_packs = NULL_TREE;
3108
3109       /* Determine which parameter packs will be used by the base
3110          class expansion.  */
3111       ppd.visited = pointer_set_create ();
3112       ppd.parameter_packs = &parameter_packs;
3113       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
3114                     &ppd, ppd.visited);
3115
3116       if (parameter_packs == NULL_TREE)
3117         {
3118           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
3119           pointer_set_destroy (ppd.visited);
3120           return error_mark_node;
3121         }
3122
3123       if (TREE_VALUE (arg) != void_type_node)
3124         {
3125           /* Collect the sets of parameter packs used in each of the
3126              initialization arguments.  */
3127           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3128             {
3129               /* Determine which parameter packs will be expanded in this
3130                  argument.  */
3131               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
3132                             &ppd, ppd.visited);
3133             }
3134         }
3135
3136       pointer_set_destroy (ppd.visited);
3137
3138       /* Create the pack expansion type for the base type.  */
3139       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3140       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3141       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3142
3143       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3144          they will rarely be compared to anything.  */
3145       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3146
3147       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3148     }
3149
3150   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3151     for_types = true;
3152
3153   /* Build the PACK_EXPANSION_* node.  */
3154   result = for_types
3155      ? cxx_make_type (TYPE_PACK_EXPANSION)
3156      : make_node (EXPR_PACK_EXPANSION);
3157   SET_PACK_EXPANSION_PATTERN (result, arg);
3158   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3159     {
3160       /* Propagate type and const-expression information.  */
3161       TREE_TYPE (result) = TREE_TYPE (arg);
3162       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3163     }
3164   else
3165     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3166        they will rarely be compared to anything.  */
3167     SET_TYPE_STRUCTURAL_EQUALITY (result);
3168
3169   /* Determine which parameter packs will be expanded.  */
3170   ppd.parameter_packs = &parameter_packs;
3171   ppd.visited = pointer_set_create ();
3172   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3173   pointer_set_destroy (ppd.visited);
3174
3175   /* Make sure we found some parameter packs.  */
3176   if (parameter_packs == NULL_TREE)
3177     {
3178       if (TYPE_P (arg))
3179         error ("expansion pattern %<%T%> contains no argument packs", arg);
3180       else
3181         error ("expansion pattern %<%E%> contains no argument packs", arg);
3182       return error_mark_node;
3183     }
3184   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
3185
3186   return result;
3187 }
3188
3189 /* Checks T for any "bare" parameter packs, which have not yet been
3190    expanded, and issues an error if any are found. This operation can
3191    only be done on full expressions or types (e.g., an expression
3192    statement, "if" condition, etc.), because we could have expressions like:
3193
3194      foo(f(g(h(args)))...)
3195
3196    where "args" is a parameter pack. check_for_bare_parameter_packs
3197    should not be called for the subexpressions args, h(args),
3198    g(h(args)), or f(g(h(args))), because we would produce erroneous
3199    error messages. 
3200
3201    Returns TRUE and emits an error if there were bare parameter packs,
3202    returns FALSE otherwise.  */
3203 bool 
3204 check_for_bare_parameter_packs (tree t)
3205 {
3206   tree parameter_packs = NULL_TREE;
3207   struct find_parameter_pack_data ppd;
3208
3209   if (!processing_template_decl || !t || t == error_mark_node)
3210     return false;
3211
3212   if (TREE_CODE (t) == TYPE_DECL)
3213     t = TREE_TYPE (t);
3214
3215   ppd.parameter_packs = &parameter_packs;
3216   ppd.visited = pointer_set_create ();
3217   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3218   pointer_set_destroy (ppd.visited);
3219
3220   if (parameter_packs) 
3221     {
3222       error ("parameter packs not expanded with %<...%>:");
3223       while (parameter_packs)
3224         {
3225           tree pack = TREE_VALUE (parameter_packs);
3226           tree name = NULL_TREE;
3227
3228           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
3229               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
3230             name = TYPE_NAME (pack);
3231           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
3232             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
3233           else
3234             name = DECL_NAME (pack);
3235
3236           if (name)
3237             inform (input_location, "        %qD", name);
3238           else
3239             inform (input_location, "        <anonymous>");
3240
3241           parameter_packs = TREE_CHAIN (parameter_packs);
3242         }
3243
3244       return true;
3245     }
3246
3247   return false;
3248 }
3249
3250 /* Expand any parameter packs that occur in the template arguments in
3251    ARGS.  */
3252 tree
3253 expand_template_argument_pack (tree args)
3254 {
3255   tree result_args = NULL_TREE;
3256   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3257   int num_result_args = -1;
3258   int non_default_args_count = -1;
3259
3260   /* First, determine if we need to expand anything, and the number of
3261      slots we'll need.  */
3262   for (in_arg = 0; in_arg < nargs; ++in_arg)
3263     {
3264       tree arg = TREE_VEC_ELT (args, in_arg);
3265       if (arg == NULL_TREE)
3266         return args;
3267       if (ARGUMENT_PACK_P (arg))
3268         {
3269           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3270           if (num_result_args < 0)
3271             num_result_args = in_arg + num_packed;
3272           else
3273             num_result_args += num_packed;
3274         }
3275       else
3276         {
3277           if (num_result_args >= 0)
3278             num_result_args++;
3279         }
3280     }
3281
3282   /* If no expansion is necessary, we're done.  */
3283   if (num_result_args < 0)
3284     return args;
3285
3286   /* Expand arguments.  */
3287   result_args = make_tree_vec (num_result_args);
3288   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
3289     non_default_args_count =
3290       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
3291   for (in_arg = 0; in_arg < nargs; ++in_arg)
3292     {
3293       tree arg = TREE_VEC_ELT (args, in_arg);
3294       if (ARGUMENT_PACK_P (arg))
3295         {
3296           tree packed = ARGUMENT_PACK_ARGS (arg);
3297           int i, num_packed = TREE_VEC_LENGTH (packed);
3298           for (i = 0; i < num_packed; ++i, ++out_arg)
3299             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3300           if (non_default_args_count > 0)
3301             non_default_args_count += num_packed;
3302         }
3303       else
3304         {
3305           TREE_VEC_ELT (result_args, out_arg) = arg;
3306           ++out_arg;
3307         }
3308     }
3309   if (non_default_args_count >= 0)
3310     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
3311   return result_args;
3312 }
3313
3314 /* Checks if DECL shadows a template parameter.
3315
3316    [temp.local]: A template-parameter shall not be redeclared within its
3317    scope (including nested scopes).
3318
3319    Emits an error and returns TRUE if the DECL shadows a parameter,
3320    returns FALSE otherwise.  */
3321
3322 bool
3323 check_template_shadow (tree decl)
3324 {
3325   tree olddecl;
3326
3327   /* If we're not in a template, we can't possibly shadow a template
3328      parameter.  */
3329   if (!current_template_parms)
3330     return true;
3331
3332   /* Figure out what we're shadowing.  */
3333   if (TREE_CODE (decl) == OVERLOAD)
3334     decl = OVL_CURRENT (decl);
3335   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3336
3337   /* If there's no previous binding for this name, we're not shadowing
3338      anything, let alone a template parameter.  */
3339   if (!olddecl)
3340     return true;
3341
3342   /* If we're not shadowing a template parameter, we're done.  Note
3343      that OLDDECL might be an OVERLOAD (or perhaps even an
3344      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3345      node.  */
3346   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3347     return true;
3348
3349   /* We check for decl != olddecl to avoid bogus errors for using a
3350      name inside a class.  We check TPFI to avoid duplicate errors for
3351      inline member templates.  */
3352   if (decl == olddecl
3353       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
3354     return true;
3355
3356   error ("declaration of %q+#D", decl);
3357   error (" shadows template parm %q+#D", olddecl);
3358   return false;
3359 }
3360
3361 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3362    ORIG_LEVEL, DECL, and TYPE.  NUM_SIBLINGS is the total number of
3363    template parameters.  */
3364
3365 static tree
3366 build_template_parm_index (int index,
3367                            int level,
3368                            int orig_level,
3369                            int num_siblings,
3370                            tree decl,
3371                            tree type)
3372 {
3373   tree t = make_node (TEMPLATE_PARM_INDEX);
3374   TEMPLATE_PARM_IDX (t) = index;
3375   TEMPLATE_PARM_LEVEL (t) = level;
3376   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3377   TEMPLATE_PARM_NUM_SIBLINGS (t) = num_siblings;
3378   TEMPLATE_PARM_DECL (t) = decl;
3379   TREE_TYPE (t) = type;
3380   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3381   TREE_READONLY (t) = TREE_READONLY (decl);
3382
3383   return t;
3384 }
3385
3386 /* Find the canonical type parameter for the given template type
3387    parameter.  Returns the canonical type parameter, which may be TYPE
3388    if no such parameter existed.  */
3389
3390 static tree
3391 canonical_type_parameter (tree type)
3392 {
3393   tree list;
3394   int idx = TEMPLATE_TYPE_IDX (type);
3395   if (!canonical_template_parms)
3396     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
3397
3398   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
3399     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
3400
3401   list = VEC_index (tree, canonical_template_parms, idx);
3402   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3403     list = TREE_CHAIN (list);
3404
3405   if (list)
3406     return TREE_VALUE (list);
3407   else
3408     {
3409       VEC_replace(tree, canonical_template_parms, idx,
3410                   tree_cons (NULL_TREE, type, 
3411                              VEC_index (tree, canonical_template_parms, idx)));
3412       return type;
3413     }
3414 }
3415
3416 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3417    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3418    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3419    new one is created.  */
3420
3421 static tree
3422 reduce_template_parm_level (tree index, tree type, int levels, tree args,
3423                             tsubst_flags_t complain)
3424 {
3425   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3426       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3427           != TEMPLATE_PARM_LEVEL (index) - levels)
3428       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
3429     {
3430       tree orig_decl = TEMPLATE_PARM_DECL (index);
3431       tree decl, t;
3432
3433       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3434                          TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3435       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
3436       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
3437       DECL_ARTIFICIAL (decl) = 1;
3438       SET_DECL_TEMPLATE_PARM_P (decl);
3439
3440       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
3441                                      TEMPLATE_PARM_LEVEL (index) - levels,
3442                                      TEMPLATE_PARM_ORIG_LEVEL (index),
3443                                      TEMPLATE_PARM_NUM_SIBLINGS (index),
3444                                      decl, type);
3445       TEMPLATE_PARM_DESCENDANTS (index) = t;
3446       TEMPLATE_PARM_PARAMETER_PACK (t) 
3447         = TEMPLATE_PARM_PARAMETER_PACK (index);
3448
3449         /* Template template parameters need this.  */
3450       if (TREE_CODE (decl) == TEMPLATE_DECL)
3451         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
3452           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
3453            args, complain);
3454     }
3455
3456   return TEMPLATE_PARM_DESCENDANTS (index);
3457 }
3458
3459 /* Process information from new template parameter PARM and append it
3460    to the LIST being built.  This new parameter is a non-type
3461    parameter iff IS_NON_TYPE is true. This new parameter is a
3462    parameter pack iff IS_PARAMETER_PACK is true.  The location of PARM
3463    is in PARM_LOC. NUM_TEMPLATE_PARMS is the size of the template
3464    parameter list PARM belongs to. This is used used to create a
3465    proper canonical type for the type of PARM that is to be created,
3466    iff PARM is a type.  If the size is not known, this parameter shall
3467    be set to 0.  */
3468
3469 tree
3470 process_template_parm (tree list, location_t parm_loc, tree parm,
3471                        bool is_non_type, bool is_parameter_pack,
3472                        unsigned num_template_parms)
3473 {
3474   tree decl = 0;
3475   tree defval;
3476   tree err_parm_list;
3477   int idx = 0;
3478
3479   gcc_assert (TREE_CODE (parm) == TREE_LIST);
3480   defval = TREE_PURPOSE (parm);
3481
3482   if (list)
3483     {
3484       tree p = tree_last (list);
3485
3486       if (p && TREE_VALUE (p) != error_mark_node)
3487         {
3488           p = TREE_VALUE (p);
3489           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3490             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3491           else
3492             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3493         }
3494
3495       ++idx;
3496     }
3497   else
3498     idx = 0;
3499
3500   if (is_non_type)
3501     {
3502       parm = TREE_VALUE (parm);
3503
3504       SET_DECL_TEMPLATE_PARM_P (parm);
3505
3506       if (TREE_TYPE (parm) == error_mark_node)
3507         {
3508           err_parm_list = build_tree_list (defval, parm);
3509           TREE_VALUE (err_parm_list) = error_mark_node;
3510            return chainon (list, err_parm_list);
3511         }
3512       else
3513       {
3514         /* [temp.param]
3515
3516            The top-level cv-qualifiers on the template-parameter are
3517            ignored when determining its type.  */
3518         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3519         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3520           {
3521             err_parm_list = build_tree_list (defval, parm);
3522             TREE_VALUE (err_parm_list) = error_mark_node;
3523              return chainon (list, err_parm_list);
3524           }
3525
3526         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3527           {
3528             /* This template parameter is not a parameter pack, but it
3529                should be. Complain about "bare" parameter packs.  */
3530             check_for_bare_parameter_packs (TREE_TYPE (parm));
3531             
3532             /* Recover by calling this a parameter pack.  */
3533             is_parameter_pack = true;
3534           }
3535       }
3536
3537       /* A template parameter is not modifiable.  */
3538       TREE_CONSTANT (parm) = 1;
3539       TREE_READONLY (parm) = 1;
3540       decl = build_decl (parm_loc,
3541                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3542       TREE_CONSTANT (decl) = 1;
3543       TREE_READONLY (decl) = 1;
3544       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3545         = build_template_parm_index (idx, processing_template_decl,
3546                                      processing_template_decl,
3547                                      num_template_parms,
3548                                      decl, TREE_TYPE (parm));
3549
3550       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3551         = is_parameter_pack;
3552     }
3553   else
3554     {
3555       tree t;
3556       parm = TREE_VALUE (TREE_VALUE (parm));
3557
3558       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3559         {
3560           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3561           /* This is for distinguishing between real templates and template
3562              template parameters */
3563           TREE_TYPE (parm) = t;
3564           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3565           decl = parm;
3566         }
3567       else
3568         {
3569           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3570           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3571           decl = build_decl (parm_loc,
3572                              TYPE_DECL, parm, t);
3573         }
3574
3575       TYPE_NAME (t) = decl;
3576       TYPE_STUB_DECL (t) = decl;
3577       parm = decl;
3578       TEMPLATE_TYPE_PARM_INDEX (t)
3579         = build_template_parm_index (idx, processing_template_decl,
3580                                      processing_template_decl,
3581                                      num_template_parms,
3582                                      decl, TREE_TYPE (parm));
3583       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3584       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3585     }
3586   DECL_ARTIFICIAL (decl) = 1;
3587   SET_DECL_TEMPLATE_PARM_P (decl);
3588   pushdecl (decl);
3589   parm = build_tree_list (defval, parm);
3590   return chainon (list, parm);
3591 }
3592
3593 /* The end of a template parameter list has been reached.  Process the
3594    tree list into a parameter vector, converting each parameter into a more
3595    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3596    as PARM_DECLs.  */
3597
3598 tree
3599 end_template_parm_list (tree parms)
3600 {
3601   int nparms;
3602   tree parm, next;
3603   tree saved_parmlist = make_tree_vec (list_length (parms));
3604
3605   current_template_parms
3606     = tree_cons (size_int (processing_template_decl),
3607                  saved_parmlist, current_template_parms);
3608
3609   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3610     {
3611       next = TREE_CHAIN (parm);
3612       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3613       TREE_CHAIN (parm) = NULL_TREE;
3614     }
3615
3616   --processing_template_parmlist;
3617
3618   return saved_parmlist;
3619 }
3620
3621 /* Create a new type almost identical to TYPE but which has the
3622    following differences:
3623
3624      1/ T has a new TEMPLATE_PARM_INDEX that carries the new number of
3625      template sibling parameters of T.
3626
3627      2/ T has a new canonical type that matches the new number
3628      of sibling parms.
3629
3630      3/ From now on, T is going to be what lookups referring to the
3631      name of TYPE will return. No lookup should return TYPE anymore.
3632
3633    NUM_PARMS is the new number of sibling parms TYPE belongs to.
3634
3635    This is a subroutine of fixup_template_parms.  */
3636
3637 static tree
3638 fixup_template_type_parm_type (tree type, int num_parms)
3639 {
3640   tree orig_idx = TEMPLATE_TYPE_PARM_INDEX (type), idx;
3641   tree t;
3642   /* This is the decl which name is inserted into the symbol table for
3643      the template parm type. So whenever we lookup the type name, this
3644      is the DECL we get.  */
3645   tree decl;
3646
3647   /* Do not fix up the type twice.  */
3648   if (orig_idx && TEMPLATE_PARM_NUM_SIBLINGS (orig_idx) != 0)
3649     return type;
3650
3651   t = copy_type (type);
3652   decl = TYPE_NAME (t);
3653
3654   TYPE_MAIN_VARIANT (t) = t;
3655   TYPE_NEXT_VARIANT (t)= NULL_TREE;
3656   TYPE_POINTER_TO (t) = 0;
3657   TYPE_REFERENCE_TO (t) = 0;
3658
3659   idx = build_template_parm_index (TEMPLATE_PARM_IDX (orig_idx),
3660                                    TEMPLATE_PARM_LEVEL (orig_idx),
3661                                    TEMPLATE_PARM_ORIG_LEVEL (orig_idx),
3662                                    num_parms,
3663                                    decl, t);
3664   TEMPLATE_PARM_DESCENDANTS (idx) = TEMPLATE_PARM_DESCENDANTS (orig_idx);
3665   TEMPLATE_PARM_PARAMETER_PACK (idx) = TEMPLATE_PARM_PARAMETER_PACK (orig_idx);
3666   TEMPLATE_TYPE_PARM_INDEX (t) = idx;
3667
3668   TYPE_STUB_DECL (t) = decl;
3669   TEMPLATE_TYPE_DECL (t) = decl;
3670   if (TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
3671     TREE_TYPE (DECL_TEMPLATE_RESULT  (decl)) = t;
3672
3673   /* Update the type associated to the type name stored in the symbol
3674      table. Now, whenever the type name is looked up, the resulting
3675      type is properly fixed up.  */
3676   TREE_TYPE (decl) = t;
3677
3678   TYPE_CANONICAL (t) = canonical_type_parameter (t);
3679
3680   return t;
3681 }
3682
3683 /* Create and return a new TEMPLATE_PARM_INDEX that is almost
3684    identical to I, but that is fixed up as to:
3685
3686    1/ carry the number of sibling parms (NUM_PARMS) of the template
3687    parm represented by I.
3688
3689    2/ replace all references to template parm types declared before I
3690    (in the same template parm list as I) by references to template
3691    parm types contained in ARGS. ARGS should contain the list of
3692    template parms that have been fixed up so far, in a form suitable
3693    to be passed to tsubst.
3694
3695    This is a subroutine of fixup_template_parms.  */
3696
3697 static tree
3698 fixup_template_parm_index (tree i, tree args, int num_parms)
3699 {
3700   tree index, decl, type;
3701
3702   if (i == NULL_TREE
3703       || TREE_CODE (i) != TEMPLATE_PARM_INDEX
3704       /* Do not fix up the index twice.  */
3705       || (TEMPLATE_PARM_NUM_SIBLINGS (i) != 0))
3706     return i;
3707
3708   decl = TEMPLATE_PARM_DECL (i);
3709   type = TREE_TYPE (decl);
3710
3711   index = build_template_parm_index (TEMPLATE_PARM_IDX (i),
3712                                      TEMPLATE_PARM_LEVEL (i),
3713                                      TEMPLATE_PARM_ORIG_LEVEL (i),
3714                                      num_parms,
3715                                      decl, type);
3716
3717   TEMPLATE_PARM_DESCENDANTS (index) = TEMPLATE_PARM_DESCENDANTS (i);
3718   TEMPLATE_PARM_PARAMETER_PACK (index) = TEMPLATE_PARM_PARAMETER_PACK (i);
3719
3720   type = tsubst (type, args, tf_none, NULL_TREE);
3721   
3722   TREE_TYPE (decl) = type;
3723   TREE_TYPE (index) = type;
3724
3725   return index;
3726 }
3727
3728 /* 
3729    This is a subroutine of fixup_template_parms.
3730
3731    It computes the canonical type of the type of the template
3732    parameter PARM_DESC and update all references to that type so that
3733    they use the newly computed canonical type. No access check is
3734    performed during the fixup. PARM_DESC is a TREE_LIST which
3735    TREE_VALUE is the template parameter and its TREE_PURPOSE is the
3736    default argument of the template parm if any. IDX is the index of
3737    the template parameter, starting at 0. NUM_PARMS is the number of
3738    template parameters in the set PARM_DESC belongs to. ARGLIST is a
3739    TREE_VEC containing the full set of template parameters in a form
3740    suitable to be passed to substs functions as their ARGS
3741    argument. This is what current_template_args returns for a given
3742    template. The innermost vector of args in ARGLIST is the set of
3743    template parms that have been fixed up so far. This function adds
3744    the fixed up parameter into that vector.  */
3745
3746 static void
3747 fixup_template_parm (tree parm_desc,
3748                      int idx,
3749                      int num_parms,
3750                      tree arglist)
3751 {
3752   tree parm = TREE_VALUE (parm_desc);
3753   tree fixedup_args = INNERMOST_TEMPLATE_ARGS (arglist);
3754
3755   push_deferring_access_checks (dk_no_check);
3756
3757   if (TREE_CODE (parm) == TYPE_DECL)
3758     {
3759       /* PARM is a template type parameter. Fix up its type, add
3760          the fixed-up template parm to the vector of fixed-up
3761          template parms so far, and substitute the fixed-up
3762          template parms into the default argument of this
3763          parameter.  */
3764       tree t =
3765         fixup_template_type_parm_type (TREE_TYPE (parm), num_parms);
3766       TREE_TYPE (parm) = t;
3767
3768       TREE_VEC_ELT (fixedup_args, idx) = template_parm_to_arg (parm_desc);
3769     }
3770   else if (TREE_CODE (parm) == TEMPLATE_DECL)
3771     {
3772       /* PARM is a template template parameter. This is going to
3773          be interesting.  */
3774       tree tparms, targs, innermost_args, t;
3775       int j;
3776
3777       /* First, fix up the parms of the template template parm
3778          because the parms are involved in defining the new canonical
3779          type of the template template parm.  */
3780
3781       /* So we need to substitute the template parm types that have
3782          been fixed up so far into the template parms of this template
3783          template parm. E.g, consider this:
3784
3785          template<class T, template<T u> class TT> class S;
3786
3787          In this case we want to substitute T into the
3788          template parameters of TT.
3789
3790          So let's walk the template parms of PARM here, and
3791          tsubst ARGLIST into into each of the template
3792          parms.   */
3793
3794       /* For this substitution we need to build the full set of
3795          template parameters and use that as arguments for the
3796          tsubsting function.  */
3797       tparms = INNERMOST_TEMPLATE_PARMS (DECL_TEMPLATE_PARMS (parm));
3798
3799       /* This will contain the innermost parms of PARM into which
3800          we have substituted so far.  */
3801       innermost_args = make_tree_vec (TREE_VEC_LENGTH (tparms));
3802       targs = add_to_template_args (arglist, innermost_args);
3803       for (j = 0; j < TREE_VEC_LENGTH (tparms); ++j)
3804         {
3805           tree parameter;
3806
3807           parameter = TREE_VEC_ELT (tparms, j);
3808
3809           /* INNERMOST_ARGS needs to have at least the same number
3810              of elements as the index PARAMETER, ortherwise
3811              tsubsting into PARAMETER will result in partially
3812              instantiating it, reducing its tempate parm
3813              level. Let's tactically fill INNERMOST_ARGS for that
3814              purpose.  */
3815           TREE_VEC_ELT (innermost_args, j) =
3816             template_parm_to_arg (parameter);
3817
3818           fixup_template_parm (parameter, j,
3819                                TREE_VEC_LENGTH (tparms),
3820                                targs);
3821         }
3822
3823       /* Now fix up the type of the template template parm.  */
3824
3825       t = fixup_template_type_parm_type (TREE_TYPE (parm), num_parms);
3826       TREE_TYPE (parm) = t;
3827
3828       TREE_VEC_ELT (fixedup_args, idx) =
3829         template_parm_to_arg (parm_desc);
3830     }
3831   else if (TREE_CODE (parm) == PARM_DECL)
3832     {
3833       /* PARM is a non-type template parameter. We need to:
3834
3835        * Fix up its TEMPLATE_PARM_INDEX to make it carry the
3836        proper number of sibling parameters.
3837
3838        * Make lookups of the template parameter return a reference
3839        to the fixed-up index. No lookup should return references
3840        to the former index anymore.
3841
3842        * Substitute the template parms that got fixed up so far
3843
3844        * into the type of PARM.  */
3845
3846       tree index = DECL_INITIAL (parm);
3847
3848       /* PUSHED_DECL is the decl added to the symbol table with
3849          the name of the parameter. E,g:
3850              
3851          template<class T, T u> //#0
3852          auto my_function(T t) -> decltype(u); //#1
3853
3854          Here, when looking up u at //#1, we get the decl of u
3855          resulting from the declaration in #0. This is what
3856          PUSHED_DECL is. We need to replace the reference to the
3857          old TEMPLATE_PARM_INDEX carried by PUSHED_DECL by the
3858          fixed-up TEMPLATE_PARM_INDEX.  */
3859       tree pushed_decl = TEMPLATE_PARM_DECL (index);
3860
3861       /* Let's fix up the TEMPLATE_PARM_INDEX then. Note that we must
3862          fixup the type of PUSHED_DECL as well and luckily
3863          fixup_template_parm_index does it for us too.  */
3864       tree fixed_up_index =
3865         fixup_template_parm_index (index, arglist, num_parms);
3866
3867       DECL_INITIAL (pushed_decl) = DECL_INITIAL (parm) = fixed_up_index;
3868
3869       /* Add this fixed up PARM to the template parms we've fixed
3870          up so far and use that to substitute the fixed-up
3871          template parms into the type of PARM.  */
3872       TREE_VEC_ELT (fixedup_args, idx) =
3873         template_parm_to_arg (parm_desc);
3874       TREE_TYPE (parm) = tsubst (TREE_TYPE (parm), arglist,
3875                                  tf_none, NULL_TREE);
3876     }
3877
3878   TREE_PURPOSE (parm_desc) =
3879     tsubst_template_arg (TREE_PURPOSE (parm_desc),
3880                          arglist, tf_none, parm);
3881
3882   pop_deferring_access_checks ();
3883 }
3884
3885 /* Walk the current template parms and properly compute the canonical
3886    types of the dependent types created during
3887    cp_parser_template_parameter_list.  */
3888
3889 void
3890 fixup_template_parms (void)
3891 {
3892   tree arglist;
3893   tree parameter_vec;
3894   tree fixedup_args;
3895   int i, num_parms;
3896
3897   parameter_vec = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3898   if (parameter_vec == NULL_TREE)
3899     return;
3900
3901   num_parms = TREE_VEC_LENGTH (parameter_vec);
3902
3903   /* This vector contains the current innermost template parms that
3904      have been fixed up so far.  The form of FIXEDUP_ARGS is suitable
3905      to be passed to tsubst* functions as their ARGS argument.  */
3906   fixedup_args = make_tree_vec (num_parms);
3907
3908   /* This vector contains the full set of template parms in a form
3909      suitable to be passed to substs functions as their ARGS
3910      argument.  */
3911   arglist = current_template_args ();
3912   arglist = add_outermost_template_args (arglist, fixedup_args);
3913
3914   /* Let's do the proper fixup now.  */
3915   for (i = 0; i < num_parms; ++i)
3916     fixup_template_parm (TREE_VEC_ELT (parameter_vec, i),
3917                          i, num_parms, arglist);
3918 }
3919
3920 /* end_template_decl is called after a template declaration is seen.  */
3921
3922 void
3923 end_template_decl (void)
3924 {
3925   reset_specialization ();
3926
3927   if (! processing_template_decl)
3928     return;
3929
3930   /* This matches the pushlevel in begin_template_parm_list.  */
3931   finish_scope ();
3932
3933   --processing_template_decl;
3934   current_template_parms = TREE_CHAIN (current_template_parms);
3935 }
3936
3937 /* Takes a TREE_LIST representing a template parameter and convert it
3938    into an argument suitable to be passed to the type substitution
3939    functions.  Note that If the TREE_LIST contains an error_mark
3940    node, the returned argument is error_mark_node.  */
3941
3942 static tree
3943 template_parm_to_arg (tree t)
3944 {
3945
3946   if (t == NULL_TREE
3947       || TREE_CODE (t) != TREE_LIST)
3948     return t;
3949
3950   if (error_operand_p (TREE_VALUE (t)))
3951     return error_mark_node;
3952
3953   t = TREE_VALUE (t);
3954
3955   if (TREE_CODE (t) == TYPE_DECL
3956       || TREE_CODE (t) == TEMPLATE_DECL)
3957     {
3958       t = TREE_TYPE (t);
3959
3960       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3961         {
3962           /* Turn this argument into a TYPE_ARGUMENT_PACK
3963              with a single element, which expands T.  */
3964           tree vec = make_tree_vec (1);
3965 #ifdef ENABLE_CHECKING
3966           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3967             (vec, TREE_VEC_LENGTH (vec));
3968 #endif
3969           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3970
3971           t = cxx_make_type (TYPE_ARGUMENT_PACK);
3972           SET_ARGUMENT_PACK_ARGS (t, vec);
3973         }
3974     }
3975   else
3976     {
3977       t = DECL_INITIAL (t);
3978
3979       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3980         {
3981           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3982              with a single element, which expands T.  */
3983           tree vec = make_tree_vec (1);
3984           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3985 #ifdef ENABLE_CHECKING
3986           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3987             (vec, TREE_VEC_LENGTH (vec));
3988 #endif
3989           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3990
3991           t  = make_node (NONTYPE_ARGUMENT_PACK);
3992           SET_ARGUMENT_PACK_ARGS (t, vec);
3993           TREE_TYPE (t) = type;
3994         }
3995     }
3996   return t;
3997 }
3998
3999 /* Within the declaration of a template, return all levels of template
4000    parameters that apply.  The template parameters are represented as
4001    a TREE_VEC, in the form documented in cp-tree.h for template
4002    arguments.  */
4003
4004 static tree
4005 current_template_args (void)
4006 {
4007   tree header;
4008   tree args = NULL_TREE;
4009   int length = TMPL_PARMS_DEPTH (current_template_parms);
4010   int l = length;
4011
4012   /* If there is only one level of template parameters, we do not
4013      create a TREE_VEC of TREE_VECs.  Instead, we return a single
4014      TREE_VEC containing the arguments.  */
4015   if (length > 1)
4016     args = make_tree_vec (length);
4017
4018   for (header = current_template_parms; header; header = TREE_CHAIN (header))
4019     {
4020       tree a = copy_node (TREE_VALUE (header));
4021       int i;
4022
4023       TREE_TYPE (a) = NULL_TREE;
4024       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
4025         TREE_VEC_ELT (a, i) = template_parm_to_arg (TREE_VEC_ELT (a, i));
4026
4027 #ifdef ENABLE_CHECKING
4028       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
4029 #endif
4030
4031       if (length > 1)
4032         TREE_VEC_ELT (args, --l) = a;
4033       else
4034         args = a;
4035     }
4036
4037     if (length > 1 && TREE_VEC_ELT (args, 0) == NULL_TREE)
4038       /* This can happen for template parms of a template template
4039          parameter, e.g:
4040
4041          template<template<class T, class U> class TT> struct S;
4042
4043          Consider the level of the parms of TT; T and U both have
4044          level 2; TT has no template parm of level 1. So in this case
4045          the first element of full_template_args is NULL_TREE. If we
4046          leave it like this TMPL_ARG_DEPTH on args returns 1 instead
4047          of 2. This will make tsubst wrongly consider that T and U
4048          have level 1. Instead, let's create a dummy vector as the
4049          first element of full_template_args so that TMPL_ARG_DEPTH
4050          returns the correct depth for args.  */
4051       TREE_VEC_ELT (args, 0) = make_tree_vec (1);
4052   return args;
4053 }
4054
4055 /* Update the declared TYPE by doing any lookups which were thought to be
4056    dependent, but are not now that we know the SCOPE of the declarator.  */
4057
4058 tree
4059 maybe_update_decl_type (tree orig_type, tree scope)
4060 {
4061   tree type = orig_type;
4062
4063   if (type == NULL_TREE)
4064     return type;
4065
4066   if (TREE_CODE (orig_type) == TYPE_DECL)
4067     type = TREE_TYPE (type);
4068
4069   if (scope && TYPE_P (scope) && dependent_type_p (scope)
4070       && dependent_type_p (type)
4071       /* Don't bother building up the args in this case.  */
4072       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
4073     {
4074       /* tsubst in the args corresponding to the template parameters,
4075          including auto if present.  Most things will be unchanged, but
4076          make_typename_type and tsubst_qualified_id will resolve
4077          TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
4078       tree args = current_template_args ();
4079       tree auto_node = type_uses_auto (type);
4080       tree pushed;
4081       if (auto_node)
4082         {
4083           tree auto_vec = make_tree_vec (1);
4084           TREE_VEC_ELT (auto_vec, 0) = auto_node;
4085           args = add_to_template_args (args, auto_vec);
4086         }
4087       pushed = push_scope (scope);
4088       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
4089       if (pushed)
4090         pop_scope (scope);
4091     }
4092
4093   if (type == error_mark_node)
4094     return orig_type;
4095
4096   if (TREE_CODE (orig_type) == TYPE_DECL)
4097     {
4098       if (same_type_p (type, TREE_TYPE (orig_type)))
4099         type = orig_type;
4100       else
4101         type = TYPE_NAME (type);
4102     }
4103   return type;
4104 }
4105
4106 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
4107    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
4108    a member template.  Used by push_template_decl below.  */
4109
4110 static tree
4111 build_template_decl (tree decl, tree parms, bool member_template_p)
4112 {
4113   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
4114   DECL_TEMPLATE_PARMS (tmpl) = parms;
4115   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
4116   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
4117
4118   return tmpl;
4119 }
4120
4121 struct template_parm_data
4122 {
4123   /* The level of the template parameters we are currently
4124      processing.  */
4125   int level;
4126
4127   /* The index of the specialization argument we are currently
4128      processing.  */
4129   int current_arg;
4130
4131   /* An array whose size is the number of template parameters.  The
4132      elements are nonzero if the parameter has been used in any one
4133      of the arguments processed so far.  */
4134   int* parms;
4135
4136   /* An array whose size is the number of template arguments.  The
4137      elements are nonzero if the argument makes use of template
4138      parameters of this level.  */
4139   int* arg_uses_template_parms;
4140 };
4141
4142 /* Subroutine of push_template_decl used to see if each template
4143    parameter in a partial specialization is used in the explicit
4144    argument list.  If T is of the LEVEL given in DATA (which is
4145    treated as a template_parm_data*), then DATA->PARMS is marked
4146    appropriately.  */
4147
4148 static int
4149 mark_template_parm (tree t, void* data)
4150 {
4151   int level;
4152   int idx;
4153   struct template_parm_data* tpd = (struct template_parm_data*) data;
4154
4155   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4156     {
4157       level = TEMPLATE_PARM_LEVEL (t);
4158       idx = TEMPLATE_PARM_IDX (t);
4159     }
4160   else
4161     {
4162       level = TEMPLATE_TYPE_LEVEL (t);
4163       idx = TEMPLATE_TYPE_IDX (t);
4164     }
4165
4166   if (level == tpd->level)
4167     {
4168       tpd->parms[idx] = 1;
4169       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
4170     }
4171
4172   /* Return zero so that for_each_template_parm will continue the
4173      traversal of the tree; we want to mark *every* template parm.  */
4174   return 0;
4175 }
4176
4177 /* Process the partial specialization DECL.  */
4178
4179 static tree
4180 process_partial_specialization (tree decl)
4181 {
4182   tree type = TREE_TYPE (decl);
4183   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
4184   tree specargs = CLASSTYPE_TI_ARGS (type);
4185   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
4186   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
4187   tree inner_parms;
4188   tree inst;
4189   int nargs = TREE_VEC_LENGTH (inner_args);
4190   int ntparms;
4191   int  i;
4192   bool did_error_intro = false;
4193   struct template_parm_data tpd;
4194   struct template_parm_data tpd2;
4195
4196   gcc_assert (current_template_parms);
4197
4198   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
4199   ntparms = TREE_VEC_LENGTH (inner_parms);
4200
4201   /* We check that each of the template parameters given in the
4202      partial specialization is used in the argument list to the
4203      specialization.  For example:
4204
4205        template <class T> struct S;
4206        template <class T> struct S<T*>;
4207
4208      The second declaration is OK because `T*' uses the template
4209      parameter T, whereas
4210
4211        template <class T> struct S<int>;
4212
4213      is no good.  Even trickier is:
4214
4215        template <class T>
4216        struct S1
4217        {
4218           template <class U>
4219           struct S2;
4220           template <class U>
4221           struct S2<T>;
4222        };
4223
4224      The S2<T> declaration is actually invalid; it is a
4225      full-specialization.  Of course,
4226
4227           template <class U>
4228           struct S2<T (*)(U)>;
4229
4230      or some such would have been OK.  */
4231   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
4232   tpd.parms = XALLOCAVEC (int, ntparms);
4233   memset (tpd.parms, 0, sizeof (int) * ntparms);
4234
4235   tpd.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4236   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
4237   for (i = 0; i < nargs; ++i)
4238     {
4239       tpd.current_arg = i;
4240       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
4241                               &mark_template_parm,
4242                               &tpd,
4243                               NULL,
4244                               /*include_nondeduced_p=*/false);
4245     }
4246   for (i = 0; i < ntparms; ++i)
4247     if (tpd.parms[i] == 0)
4248       {
4249         /* One of the template parms was not used in the
4250            specialization.  */
4251         if (!did_error_intro)
4252           {
4253             error ("template parameters not used in partial specialization:");
4254             did_error_intro = true;
4255           }
4256
4257         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
4258       }
4259
4260   if (did_error_intro)
4261     return error_mark_node;
4262
4263   /* [temp.class.spec]
4264
4265      The argument list of the specialization shall not be identical to
4266      the implicit argument list of the primary template.  */
4267   if (comp_template_args
4268       (inner_args,
4269        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
4270                                                    (maintmpl)))))
4271     error ("partial specialization %qT does not specialize any template arguments", type);
4272
4273   /* [temp.class.spec]
4274
4275      A partially specialized non-type argument expression shall not
4276      involve template parameters of the partial specialization except
4277      when the argument expression is a simple identifier.
4278
4279      The type of a template parameter corresponding to a specialized
4280      non-type argument shall not be dependent on a parameter of the
4281      specialization. 
4282
4283      Also, we verify that pack expansions only occur at the
4284      end of the argument list.  */
4285   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
4286   tpd2.parms = 0;
4287   for (i = 0; i < nargs; ++i)
4288     {
4289       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
4290       tree arg = TREE_VEC_ELT (inner_args, i);
4291       tree packed_args = NULL_TREE;
4292       int j, len = 1;
4293
4294       if (ARGUMENT_PACK_P (arg))
4295         {
4296           /* Extract the arguments from the argument pack. We'll be
4297              iterating over these in the following loop.  */
4298           packed_args = ARGUMENT_PACK_ARGS (arg);
4299           len = TREE_VEC_LENGTH (packed_args);
4300         }
4301
4302       for (j = 0; j < len; j++)
4303         {
4304           if (packed_args)
4305             /* Get the Jth argument in the parameter pack.  */
4306             arg = TREE_VEC_ELT (packed_args, j);
4307
4308           if (PACK_EXPANSION_P (arg))
4309             {
4310               /* Pack expansions must come at the end of the
4311                  argument list.  */
4312               if ((packed_args && j < len - 1)
4313                   || (!packed_args && i < nargs - 1))
4314                 {
4315                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4316                     error ("parameter pack argument %qE must be at the "
4317                            "end of the template argument list", arg);
4318                   else
4319                     error ("parameter pack argument %qT must be at the "
4320                            "end of the template argument list", arg);
4321                 }
4322             }
4323
4324           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
4325             /* We only care about the pattern.  */
4326             arg = PACK_EXPANSION_PATTERN (arg);
4327
4328           if (/* These first two lines are the `non-type' bit.  */
4329               !TYPE_P (arg)
4330               && TREE_CODE (arg) != TEMPLATE_DECL
4331               /* This next line is the `argument expression is not just a
4332                  simple identifier' condition and also the `specialized
4333                  non-type argument' bit.  */
4334               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
4335             {
4336               if ((!packed_args && tpd.arg_uses_template_parms[i])
4337                   || (packed_args && uses_template_parms (arg)))
4338                 error ("template argument %qE involves template parameter(s)",
4339                        arg);
4340               else 
4341                 {
4342                   /* Look at the corresponding template parameter,
4343                      marking which template parameters its type depends
4344                      upon.  */
4345                   tree type = TREE_TYPE (parm);
4346
4347                   if (!tpd2.parms)
4348                     {
4349                       /* We haven't yet initialized TPD2.  Do so now.  */
4350                       tpd2.arg_uses_template_parms = XALLOCAVEC (int, nargs);
4351                       /* The number of parameters here is the number in the
4352                          main template, which, as checked in the assertion
4353                          above, is NARGS.  */
4354                       tpd2.parms = XALLOCAVEC (int, nargs);
4355                       tpd2.level = 
4356                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
4357                     }
4358
4359                   /* Mark the template parameters.  But this time, we're
4360                      looking for the template parameters of the main
4361                      template, not in the specialization.  */
4362                   tpd2.current_arg = i;
4363                   tpd2.arg_uses_template_parms[i] = 0;
4364                   memset (tpd2.parms, 0, sizeof (int) * nargs);
4365                   for_each_template_parm (type,
4366                                           &mark_template_parm,
4367                                           &tpd2,
4368                                           NULL,
4369                                           /*include_nondeduced_p=*/false);
4370
4371                   if (tpd2.arg_uses_template_parms [i])
4372                     {
4373                       /* The type depended on some template parameters.
4374                          If they are fully specialized in the
4375                          specialization, that's OK.  */
4376                       int j;
4377                       int count = 0;
4378                       for (j = 0; j < nargs; ++j)
4379                         if (tpd2.parms[j] != 0
4380                             && tpd.arg_uses_template_parms [j])
4381                           ++count;
4382                       if (count != 0)
4383                         error_n (input_location, count,
4384                                  "type %qT of template argument %qE depends "
4385                                  "on a template parameter",
4386                                  "type %qT of template argument %qE depends "
4387                                  "on template parameters",
4388                                  type,
4389                                  arg);
4390                     }
4391                 }
4392             }
4393         }
4394     }
4395
4396   /* We should only get here once.  */
4397   gcc_assert (!COMPLETE_TYPE_P (type));
4398
4399   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
4400     = tree_cons (specargs, inner_parms,
4401                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
4402   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
4403
4404   for (inst = DECL_TEMPLATE_INSTANTIATIONS (maintmpl); inst;
4405        inst = TREE_CHAIN (inst))
4406     {
4407       tree inst_type = TREE_VALUE (inst);
4408       if (COMPLETE_TYPE_P (inst_type)
4409           && CLASSTYPE_IMPLICIT_INSTANTIATION (inst_type))
4410         {
4411           tree spec = most_specialized_class (inst_type, maintmpl, tf_none);
4412           if (spec && TREE_TYPE (spec) == type)
4413             permerror (input_location,
4414                        "partial specialization of %qT after instantiation "
4415                        "of %qT", type, inst_type);
4416         }
4417     }
4418
4419   return decl;
4420 }
4421
4422 /* Check that a template declaration's use of default arguments and
4423    parameter packs is not invalid.  Here, PARMS are the template
4424    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
4425    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
4426    specialization.
4427    
4428
4429    IS_FRIEND_DECL is nonzero if DECL is a friend function template
4430    declaration (but not a definition); 1 indicates a declaration, 2
4431    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
4432    emitted for extraneous default arguments.
4433
4434    Returns TRUE if there were no errors found, FALSE otherwise. */
4435
4436 bool
4437 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
4438                          int is_partial, int is_friend_decl)
4439 {
4440   const char *msg;
4441   int last_level_to_check;
4442   tree parm_level;
4443   bool no_errors = true;
4444
4445   /* [temp.param]
4446
4447      A default template-argument shall not be specified in a
4448      function template declaration or a function template definition, nor
4449      in the template-parameter-list of the definition of a member of a
4450      class template.  */
4451
4452   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
4453     /* You can't have a function template declaration in a local
4454        scope, nor you can you define a member of a class template in a
4455        local scope.  */
4456     return true;
4457
4458   if (current_class_type
4459       && !TYPE_BEING_DEFINED (current_class_type)
4460       && DECL_LANG_SPECIFIC (decl)
4461       && DECL_DECLARES_FUNCTION_P (decl)
4462       /* If this is either a friend defined in the scope of the class
4463          or a member function.  */
4464       && (DECL_FUNCTION_MEMBER_P (decl)
4465           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
4466           : DECL_FRIEND_CONTEXT (decl)
4467           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
4468           : false)
4469       /* And, if it was a member function, it really was defined in
4470          the scope of the class.  */
4471       && (!DECL_FUNCTION_MEMBER_P (decl)
4472           || DECL_INITIALIZED_IN_CLASS_P (decl)))
4473     /* We already checked these parameters when the template was
4474        declared, so there's no need to do it again now.  This function
4475        was defined in class scope, but we're processing it's body now
4476        that the class is complete.  */
4477     return true;
4478
4479   /* Core issue 226 (C++0x only): the following only applies to class
4480      templates.  */
4481   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
4482     {
4483       /* [temp.param]
4484
4485          If a template-parameter has a default template-argument, all
4486          subsequent template-parameters shall have a default
4487          template-argument supplied.  */
4488       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
4489         {
4490           tree inner_parms = TREE_VALUE (parm_level);
4491           int ntparms = TREE_VEC_LENGTH (inner_parms);
4492           int seen_def_arg_p = 0;
4493           int i;
4494
4495           for (i = 0; i < ntparms; ++i)
4496             {
4497               tree parm = TREE_VEC_ELT (inner_parms, i);
4498
4499               if (parm == error_mark_node)
4500                 continue;
4501
4502               if (TREE_PURPOSE (parm))
4503                 seen_def_arg_p = 1;
4504               else if (seen_def_arg_p
4505                        && !template_parameter_pack_p (TREE_VALUE (parm)))
4506                 {
4507                   error ("no default argument for %qD", TREE_VALUE (parm));
4508                   /* For better subsequent error-recovery, we indicate that
4509                      there should have been a default argument.  */
4510                   TREE_PURPOSE (parm) = error_mark_node;
4511                   no_errors = false;
4512                 }
4513               else if (is_primary
4514                        && !is_partial
4515                        && !is_friend_decl
4516                        /* Don't complain about an enclosing partial
4517                           specialization.  */
4518                        && parm_level == parms
4519                        && TREE_CODE (decl) == TYPE_DECL
4520                        && i < ntparms - 1
4521                        && template_parameter_pack_p (TREE_VALUE (parm)))
4522                 {
4523                   /* A primary class template can only have one
4524                      parameter pack, at the end of the template
4525                      parameter list.  */
4526
4527                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
4528                     error ("parameter pack %qE must be at the end of the"
4529                            " template parameter list", TREE_VALUE (parm));
4530                   else
4531                     error ("parameter pack %qT must be at the end of the"
4532                            " template parameter list", 
4533                            TREE_TYPE (TREE_VALUE (parm)));
4534
4535                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
4536                     = error_mark_node;
4537                   no_errors = false;
4538                 }
4539             }
4540         }
4541     }
4542
4543   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
4544       || is_partial 
4545       || !is_primary
4546       || is_friend_decl)
4547     /* For an ordinary class template, default template arguments are
4548        allowed at the innermost level, e.g.:
4549          template <class T = int>
4550          struct S {};
4551        but, in a partial specialization, they're not allowed even
4552        there, as we have in [temp.class.spec]:
4553
4554          The template parameter list of a specialization shall not
4555          contain default template argument values.
4556
4557        So, for a partial specialization, or for a function template
4558        (in C++98/C++03), we look at all of them.  */
4559     ;
4560   else
4561     /* But, for a primary class template that is not a partial
4562        specialization we look at all template parameters except the
4563        innermost ones.  */
4564     parms = TREE_CHAIN (parms);
4565
4566   /* Figure out what error message to issue.  */
4567   if (is_friend_decl == 2)
4568     msg = G_("default template arguments may not be used in function template "
4569              "friend re-declaration");
4570   else if (is_friend_decl)
4571     msg = G_("default template arguments may not be used in function template "
4572              "friend declarations");
4573   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
4574     msg = G_("default template arguments may not be used in function templates "
4575              "without -std=c++0x or -std=gnu++0x");
4576   else if (is_partial)
4577     msg = G_("default template arguments may not be used in "
4578              "partial specializations");
4579   else
4580     msg = G_("default argument for template parameter for class enclosing %qD");
4581
4582   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
4583     /* If we're inside a class definition, there's no need to
4584        examine the parameters to the class itself.  On the one
4585        hand, they will be checked when the class is defined, and,
4586        on the other, default arguments are valid in things like:
4587          template <class T = double>
4588          struct S { template <class U> void f(U); };
4589        Here the default argument for `S' has no bearing on the
4590        declaration of `f'.  */
4591     last_level_to_check = template_class_depth (current_class_type) + 1;
4592   else
4593     /* Check everything.  */
4594     last_level_to_check = 0;
4595
4596   for (parm_level = parms;
4597        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
4598        parm_level = TREE_CHAIN (parm_level))
4599     {
4600       tree inner_parms = TREE_VALUE (parm_level);
4601       int i;
4602       int ntparms;
4603
4604       ntparms = TREE_VEC_LENGTH (inner_parms);
4605       for (i = 0; i < ntparms; ++i)
4606         {
4607           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
4608             continue;
4609
4610           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
4611             {
4612               if (msg)
4613                 {
4614                   no_errors = false;
4615                   if (is_friend_decl == 2)
4616                     return no_errors;
4617
4618                   error (msg, decl);
4619                   msg = 0;
4620                 }
4621
4622               /* Clear out the default argument so that we are not
4623                  confused later.  */
4624               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
4625             }
4626         }
4627
4628       /* At this point, if we're still interested in issuing messages,
4629          they must apply to classes surrounding the object declared.  */
4630       if (msg)
4631         msg = G_("default argument for template parameter for class "
4632                  "enclosing %qD");
4633     }
4634
4635   return no_errors;
4636 }
4637
4638 /* Worker for push_template_decl_real, called via
4639    for_each_template_parm.  DATA is really an int, indicating the
4640    level of the parameters we are interested in.  If T is a template
4641    parameter of that level, return nonzero.  */
4642
4643 static int
4644 template_parm_this_level_p (tree t, void* data)
4645 {
4646   int this_level = *(int *)data;
4647   int level;
4648
4649   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4650     level = TEMPLATE_PARM_LEVEL (t);
4651   else
4652     level = TEMPLATE_TYPE_LEVEL (t);
4653   return level == this_level;
4654 }
4655
4656 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
4657    parameters given by current_template_args, or reuses a
4658    previously existing one, if appropriate.  Returns the DECL, or an
4659    equivalent one, if it is replaced via a call to duplicate_decls.
4660
4661    If IS_FRIEND is true, DECL is a friend declaration.  */
4662
4663 tree
4664 push_template_decl_real (tree decl, bool is_friend)
4665 {
4666   tree tmpl;
4667   tree args;
4668   tree info;
4669   tree ctx;
4670   int primary;
4671   int is_partial;
4672   int new_template_p = 0;
4673   /* True if the template is a member template, in the sense of
4674      [temp.mem].  */
4675   bool member_template_p = false;
4676
4677   if (decl == error_mark_node || !current_template_parms)
4678     return error_mark_node;
4679
4680   /* See if this is a partial specialization.  */
4681   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
4682                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
4683                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
4684
4685   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
4686     is_friend = true;
4687
4688   if (is_friend)
4689     /* For a friend, we want the context of the friend function, not
4690        the type of which it is a friend.  */
4691     ctx = CP_DECL_CONTEXT (decl);
4692   else if (CP_DECL_CONTEXT (decl)
4693            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
4694     /* In the case of a virtual function, we want the class in which
4695        it is defined.  */
4696     ctx = CP_DECL_CONTEXT (decl);
4697   else
4698     /* Otherwise, if we're currently defining some class, the DECL
4699        is assumed to be a member of the class.  */
4700     ctx = current_scope ();
4701
4702   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
4703     ctx = NULL_TREE;
4704
4705   if (!DECL_CONTEXT (decl))
4706     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4707
4708   /* See if this is a primary template.  */
4709   if (is_friend && ctx)
4710     /* A friend template that specifies a class context, i.e.
4711          template <typename T> friend void A<T>::f();
4712        is not primary.  */
4713     primary = 0;
4714   else
4715     primary = template_parm_scope_p ();
4716
4717   if (primary)
4718     {
4719       if (DECL_CLASS_SCOPE_P (decl))
4720         member_template_p = true;
4721       if (TREE_CODE (decl) == TYPE_DECL
4722           && ANON_AGGRNAME_P (DECL_NAME (decl)))
4723         {
4724           error ("template class without a name");
4725           return error_mark_node;
4726         }
4727       else if (TREE_CODE (decl) == FUNCTION_DECL)
4728         {
4729           if (DECL_DESTRUCTOR_P (decl))
4730             {
4731               /* [temp.mem]
4732
4733                  A destructor shall not be a member template.  */
4734               error ("destructor %qD declared as member template", decl);
4735               return error_mark_node;
4736             }
4737           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
4738               && (!prototype_p (TREE_TYPE (decl))
4739                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
4740                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
4741                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
4742                       == void_list_node)))
4743             {
4744               /* [basic.stc.dynamic.allocation]
4745
4746                  An allocation function can be a function
4747                  template. ... Template allocation functions shall
4748                  have two or more parameters.  */
4749               error ("invalid template declaration of %qD", decl);
4750               return error_mark_node;
4751             }
4752         }
4753       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4754                && CLASS_TYPE_P (TREE_TYPE (decl)))
4755         /* OK */;
4756       else
4757         {
4758           error ("template declaration of %q#D", decl);
4759           return error_mark_node;
4760         }
4761     }
4762
4763   /* Check to see that the rules regarding the use of default
4764      arguments are not being violated.  */
4765   check_default_tmpl_args (decl, current_template_parms,
4766                            primary, is_partial, /*is_friend_decl=*/0);
4767
4768   /* Ensure that there are no parameter packs in the type of this
4769      declaration that have not been expanded.  */
4770   if (TREE_CODE (decl) == FUNCTION_DECL)
4771     {
4772       /* Check each of the arguments individually to see if there are
4773          any bare parameter packs.  */
4774       tree type = TREE_TYPE (decl);
4775       tree arg = DECL_ARGUMENTS (decl);
4776       tree argtype = TYPE_ARG_TYPES (type);
4777
4778       while (arg && argtype)
4779         {
4780           if (!FUNCTION_PARAMETER_PACK_P (arg)
4781               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
4782             {
4783             /* This is a PARM_DECL that contains unexpanded parameter
4784                packs. We have already complained about this in the
4785                check_for_bare_parameter_packs call, so just replace
4786                these types with ERROR_MARK_NODE.  */
4787               TREE_TYPE (arg) = error_mark_node;
4788               TREE_VALUE (argtype) = error_mark_node;
4789             }
4790
4791           arg = DECL_CHAIN (arg);
4792           argtype = TREE_CHAIN (argtype);
4793         }
4794
4795       /* Check for bare parameter packs in the return type and the
4796          exception specifiers.  */
4797       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
4798         /* Errors were already issued, set return type to int
4799            as the frontend doesn't expect error_mark_node as
4800            the return type.  */
4801         TREE_TYPE (type) = integer_type_node;
4802       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
4803         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
4804     }
4805   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
4806     {
4807       TREE_TYPE (decl) = error_mark_node;
4808       return error_mark_node;
4809     }
4810
4811   if (is_partial)
4812     return process_partial_specialization (decl);
4813
4814   args = current_template_args ();
4815
4816   if (!ctx
4817       || TREE_CODE (ctx) == FUNCTION_DECL
4818       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
4819       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
4820     {
4821       if (DECL_LANG_SPECIFIC (decl)
4822           && DECL_TEMPLATE_INFO (decl)
4823           && DECL_TI_TEMPLATE (decl))
4824         tmpl = DECL_TI_TEMPLATE (decl);
4825       /* If DECL is a TYPE_DECL for a class-template, then there won't
4826          be DECL_LANG_SPECIFIC.  The information equivalent to
4827          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
4828       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4829                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
4830                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
4831         {
4832           /* Since a template declaration already existed for this
4833              class-type, we must be redeclaring it here.  Make sure
4834              that the redeclaration is valid.  */
4835           redeclare_class_template (TREE_TYPE (decl),
4836                                     current_template_parms);
4837           /* We don't need to create a new TEMPLATE_DECL; just use the
4838              one we already had.  */
4839           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
4840         }
4841       else
4842         {
4843           tmpl = build_template_decl (decl, current_template_parms,
4844                                       member_template_p);
4845           new_template_p = 1;
4846
4847           if (DECL_LANG_SPECIFIC (decl)
4848               && DECL_TEMPLATE_SPECIALIZATION (decl))
4849             {
4850               /* A specialization of a member template of a template
4851                  class.  */
4852               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4853               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
4854               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
4855             }
4856         }
4857     }
4858   else
4859     {
4860       tree a, t, current, parms;
4861       int i;
4862       tree tinfo = get_template_info (decl);
4863
4864       if (!tinfo)
4865         {
4866           error ("template definition of non-template %q#D", decl);
4867           return error_mark_node;
4868         }
4869
4870       tmpl = TI_TEMPLATE (tinfo);
4871
4872       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
4873           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
4874           && DECL_TEMPLATE_SPECIALIZATION (decl)
4875           && DECL_MEMBER_TEMPLATE_P (tmpl))
4876         {
4877           tree new_tmpl;
4878
4879           /* The declaration is a specialization of a member
4880              template, declared outside the class.  Therefore, the
4881              innermost template arguments will be NULL, so we
4882              replace them with the arguments determined by the
4883              earlier call to check_explicit_specialization.  */
4884           args = DECL_TI_ARGS (decl);
4885
4886           new_tmpl
4887             = build_template_decl (decl, current_template_parms,
4888                                    member_template_p);
4889           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4890           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4891           DECL_TI_TEMPLATE (decl) = new_tmpl;
4892           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4893           DECL_TEMPLATE_INFO (new_tmpl)
4894             = build_template_info (tmpl, args);
4895
4896           register_specialization (new_tmpl,
4897                                    most_general_template (tmpl),
4898                                    args,
4899                                    is_friend, 0);
4900           return decl;
4901         }
4902
4903       /* Make sure the template headers we got make sense.  */
4904
4905       parms = DECL_TEMPLATE_PARMS (tmpl);
4906       i = TMPL_PARMS_DEPTH (parms);
4907       if (TMPL_ARGS_DEPTH (args) != i)
4908         {
4909           error ("expected %d levels of template parms for %q#D, got %d",
4910                  i, decl, TMPL_ARGS_DEPTH (args));
4911         }
4912       else
4913         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4914           {
4915             a = TMPL_ARGS_LEVEL (args, i);
4916             t = INNERMOST_TEMPLATE_PARMS (parms);
4917
4918             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4919               {
4920                 if (current == decl)
4921                   error ("got %d template parameters for %q#D",
4922                          TREE_VEC_LENGTH (a), decl);
4923                 else
4924                   error ("got %d template parameters for %q#T",
4925                          TREE_VEC_LENGTH (a), current);
4926                 error ("  but %d required", TREE_VEC_LENGTH (t));
4927                 return error_mark_node;
4928               }
4929
4930             if (current == decl)
4931               current = ctx;
4932             else if (current == NULL_TREE)
4933               /* Can happen in erroneous input.  */
4934               break;
4935             else
4936               current = (TYPE_P (current)
4937                          ? TYPE_CONTEXT (current)
4938                          : DECL_CONTEXT (current));
4939           }
4940
4941       /* Check that the parms are used in the appropriate qualifying scopes
4942          in the declarator.  */
4943       if (!comp_template_args
4944           (TI_ARGS (tinfo),
4945            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4946         {
4947           error ("\
4948 template arguments to %qD do not match original template %qD",
4949                  decl, DECL_TEMPLATE_RESULT (tmpl));
4950           if (!uses_template_parms (TI_ARGS (tinfo)))
4951             inform (input_location, "use template<> for an explicit specialization");
4952           /* Avoid crash in import_export_decl.  */
4953           DECL_INTERFACE_KNOWN (decl) = 1;
4954           return error_mark_node;
4955         }
4956     }
4957
4958   DECL_TEMPLATE_RESULT (tmpl) = decl;
4959   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4960
4961   /* Push template declarations for global functions and types.  Note
4962      that we do not try to push a global template friend declared in a
4963      template class; such a thing may well depend on the template
4964      parameters of the class.  */
4965   if (new_template_p && !ctx
4966       && !(is_friend && template_class_depth (current_class_type) > 0))
4967     {
4968       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4969       if (tmpl == error_mark_node)
4970         return error_mark_node;
4971
4972       /* Hide template friend classes that haven't been declared yet.  */
4973       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4974         {
4975           DECL_ANTICIPATED (tmpl) = 1;
4976           DECL_FRIEND_P (tmpl) = 1;
4977         }
4978     }
4979
4980   if (primary)
4981     {
4982       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4983       int i;
4984
4985       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4986       if (DECL_CONV_FN_P (tmpl))
4987         {
4988           int depth = TMPL_PARMS_DEPTH (parms);
4989
4990           /* It is a conversion operator. See if the type converted to
4991              depends on innermost template operands.  */
4992
4993           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4994                                          depth))
4995             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4996         }
4997
4998       /* Give template template parms a DECL_CONTEXT of the template
4999          for which they are a parameter.  */
5000       parms = INNERMOST_TEMPLATE_PARMS (parms);
5001       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
5002         {
5003           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5004           if (TREE_CODE (parm) == TEMPLATE_DECL)
5005             DECL_CONTEXT (parm) = tmpl;
5006         }
5007     }
5008
5009   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
5010      back to its most general template.  If TMPL is a specialization,
5011      ARGS may only have the innermost set of arguments.  Add the missing
5012      argument levels if necessary.  */
5013   if (DECL_TEMPLATE_INFO (tmpl))
5014     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
5015
5016   info = build_template_info (tmpl, args);
5017
5018   if (DECL_IMPLICIT_TYPEDEF_P (decl))
5019     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
5020   else if (DECL_LANG_SPECIFIC (decl))
5021     DECL_TEMPLATE_INFO (decl) = info;
5022
5023   return DECL_TEMPLATE_RESULT (tmpl);
5024 }
5025
5026 tree
5027 push_template_decl (tree decl)
5028 {
5029   return push_template_decl_real (decl, false);
5030 }
5031
5032 /* Called when a class template TYPE is redeclared with the indicated
5033    template PARMS, e.g.:
5034
5035      template <class T> struct S;
5036      template <class T> struct S {};  */
5037
5038 bool
5039 redeclare_class_template (tree type, tree parms)
5040 {
5041   tree tmpl;
5042   tree tmpl_parms;
5043   int i;
5044
5045   if (!TYPE_TEMPLATE_INFO (type))
5046     {
5047       error ("%qT is not a template type", type);
5048       return false;
5049     }
5050
5051   tmpl = TYPE_TI_TEMPLATE (type);
5052   if (!PRIMARY_TEMPLATE_P (tmpl))
5053     /* The type is nested in some template class.  Nothing to worry
5054        about here; there are no new template parameters for the nested
5055        type.  */
5056     return true;
5057
5058   if (!parms)
5059     {
5060       error ("template specifiers not specified in declaration of %qD",
5061              tmpl);
5062       return false;
5063     }
5064
5065   parms = INNERMOST_TEMPLATE_PARMS (parms);
5066   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
5067
5068   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
5069     {
5070       error_n (input_location, TREE_VEC_LENGTH (parms),
5071                "redeclared with %d template parameter",
5072                "redeclared with %d template parameters",
5073                TREE_VEC_LENGTH (parms));
5074       inform_n (input_location, TREE_VEC_LENGTH (tmpl_parms),
5075                 "previous declaration %q+D used %d template parameter",
5076                 "previous declaration %q+D used %d template parameters",
5077                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
5078       return false;
5079     }
5080
5081   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
5082     {
5083       tree tmpl_parm;
5084       tree parm;
5085       tree tmpl_default;
5086       tree parm_default;
5087
5088       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
5089           || TREE_VEC_ELT (parms, i) == error_mark_node)
5090         continue;
5091
5092       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
5093       if (tmpl_parm == error_mark_node)
5094         return false;
5095
5096       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
5097       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
5098       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
5099
5100       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
5101          TEMPLATE_DECL.  */
5102       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
5103           || (TREE_CODE (tmpl_parm) != TYPE_DECL
5104               && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
5105           || (TREE_CODE (tmpl_parm) != PARM_DECL
5106               && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
5107                   != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
5108           || (TREE_CODE (tmpl_parm) == PARM_DECL
5109               && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
5110                   != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
5111         {
5112           error ("template parameter %q+#D", tmpl_parm);
5113           error ("redeclared here as %q#D", parm);
5114           return false;
5115         }
5116
5117       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
5118         {
5119           /* We have in [temp.param]:
5120
5121              A template-parameter may not be given default arguments
5122              by two different declarations in the same scope.  */
5123           error_at (input_location, "redefinition of default argument for %q#D", parm);
5124           inform (DECL_SOURCE_LOCATION (tmpl_parm),
5125                   "original definition appeared here");
5126           return false;
5127         }
5128
5129       if (parm_default != NULL_TREE)
5130         /* Update the previous template parameters (which are the ones
5131            that will really count) with the new default value.  */
5132         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
5133       else if (tmpl_default != NULL_TREE)
5134         /* Update the new parameters, too; they'll be used as the
5135            parameters for any members.  */
5136         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
5137     }
5138
5139     return true;
5140 }
5141
5142 /* Simplify EXPR if it is a non-dependent expression.  Returns the
5143    (possibly simplified) expression.  */
5144
5145 static tree
5146 fold_non_dependent_expr_sfinae (tree expr, tsubst_flags_t complain)
5147 {
5148   if (expr == NULL_TREE)
5149     return NULL_TREE;
5150
5151   /* If we're in a template, but EXPR isn't value dependent, simplify
5152      it.  We're supposed to treat:
5153
5154        template <typename T> void f(T[1 + 1]);
5155        template <typename T> void f(T[2]);
5156
5157      as two declarations of the same function, for example.  */
5158   if (processing_template_decl
5159       && !type_dependent_expression_p (expr)
5160       && potential_constant_expression (expr)
5161       && !value_dependent_expression_p (expr))
5162     {
5163       HOST_WIDE_INT saved_processing_template_decl;
5164
5165       saved_processing_template_decl = processing_template_decl;
5166       processing_template_decl = 0;
5167       expr = tsubst_copy_and_build (expr,
5168                                     /*args=*/NULL_TREE,
5169                                     complain,
5170                                     /*in_decl=*/NULL_TREE,
5171                                     /*function_p=*/false,
5172                                     /*integral_constant_expression_p=*/true);
5173       processing_template_decl = saved_processing_template_decl;
5174     }
5175   return expr;
5176 }
5177
5178 tree
5179 fold_non_dependent_expr (tree expr)
5180 {
5181   return fold_non_dependent_expr_sfinae (expr, tf_error);
5182 }
5183
5184 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
5185    must be a function or a pointer-to-function type, as specified
5186    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
5187    and check that the resulting function has external linkage.  */
5188
5189 static tree
5190 convert_nontype_argument_function (tree type, tree expr)
5191 {
5192   tree fns = expr;
5193   tree fn, fn_no_ptr;
5194
5195   fn = instantiate_type (type, fns, tf_none);
5196   if (fn == error_mark_node)
5197     return error_mark_node;
5198
5199   fn_no_ptr = fn;
5200   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
5201     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
5202   if (TREE_CODE (fn_no_ptr) == BASELINK)
5203     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
5204  
5205   /* [temp.arg.nontype]/1
5206
5207      A template-argument for a non-type, non-template template-parameter
5208      shall be one of:
5209      [...]
5210      -- the address of an object or function with external linkage.  */
5211   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
5212     {
5213       error ("%qE is not a valid template argument for type %qT "
5214              "because function %qD has not external linkage",
5215              expr, type, fn_no_ptr);
5216       return NULL_TREE;
5217     }
5218
5219   return fn;
5220 }
5221
5222 /* Subroutine of convert_nontype_argument.
5223    Check if EXPR of type TYPE is a valid pointer-to-member constant.
5224    Emit an error otherwise.  */
5225
5226 static bool
5227 check_valid_ptrmem_cst_expr (tree type, tree expr,
5228                              tsubst_flags_t complain)
5229 {
5230   STRIP_NOPS (expr);
5231   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
5232     return true;
5233   if (complain & tf_error)
5234     {
5235       error ("%qE is not a valid template argument for type %qT",
5236              expr, type);
5237       error ("it must be a pointer-to-member of the form %<&X::Y%>");
5238     }
5239   return false;
5240 }
5241
5242 /* Returns TRUE iff the address of OP is value-dependent.
5243
5244    14.6.2.4 [temp.dep.temp]:
5245    A non-integral non-type template-argument is dependent if its type is
5246    dependent or it has either of the following forms
5247      qualified-id
5248      & qualified-id
5249    and contains a nested-name-specifier which specifies a class-name that
5250    names a dependent type.
5251
5252    We generalize this to just say that the address of a member of a
5253    dependent class is value-dependent; the above doesn't cover the
5254    address of a static data member named with an unqualified-id.  */
5255
5256 static bool
5257 has_value_dependent_address (tree op)
5258 {
5259   /* We could use get_inner_reference here, but there's no need;
5260      this is only relevant for template non-type arguments, which
5261      can only be expressed as &id-expression.  */
5262   if (DECL_P (op))
5263     {
5264       tree ctx = CP_DECL_CONTEXT (op);
5265       if (TYPE_P (ctx) && dependent_type_p (ctx))
5266         return true;
5267     }
5268
5269   return false;
5270 }
5271
5272 /* Attempt to convert the non-type template parameter EXPR to the
5273    indicated TYPE.  If the conversion is successful, return the
5274    converted value.  If the conversion is unsuccessful, return
5275    NULL_TREE if we issued an error message, or error_mark_node if we
5276    did not.  We issue error messages for out-and-out bad template
5277    parameters, but not simply because the conversion failed, since we
5278    might be just trying to do argument deduction.  Both TYPE and EXPR
5279    must be non-dependent.
5280
5281    The conversion follows the special rules described in
5282    [temp.arg.nontype], and it is much more strict than an implicit
5283    conversion.
5284
5285    This function is called twice for each template argument (see
5286    lookup_template_class for a more accurate description of this
5287    problem). This means that we need to handle expressions which
5288    are not valid in a C++ source, but can be created from the
5289    first call (for instance, casts to perform conversions). These
5290    hacks can go away after we fix the double coercion problem.  */
5291
5292 static tree
5293 convert_nontype_argument (tree type, tree expr, tsubst_flags_t complain)
5294 {
5295   tree expr_type;
5296
5297   /* Detect immediately string literals as invalid non-type argument.
5298      This special-case is not needed for correctness (we would easily
5299      catch this later), but only to provide better diagnostic for this
5300      common user mistake. As suggested by DR 100, we do not mention
5301      linkage issues in the diagnostic as this is not the point.  */
5302   /* FIXME we're making this OK.  */
5303   if (TREE_CODE (expr) == STRING_CST)
5304     {
5305       if (complain & tf_error)
5306         error ("%qE is not a valid template argument for type %qT "
5307                "because string literals can never be used in this context",
5308                expr, type);
5309       return NULL_TREE;
5310     }
5311
5312   /* Add the ADDR_EXPR now for the benefit of
5313      value_dependent_expression_p.  */
5314   if (TYPE_PTROBV_P (type))
5315     expr = decay_conversion (expr);
5316
5317   /* If we are in a template, EXPR may be non-dependent, but still
5318      have a syntactic, rather than semantic, form.  For example, EXPR
5319      might be a SCOPE_REF, rather than the VAR_DECL to which the
5320      SCOPE_REF refers.  Preserving the qualifying scope is necessary
5321      so that access checking can be performed when the template is
5322      instantiated -- but here we need the resolved form so that we can
5323      convert the argument.  */
5324   if (TYPE_REF_OBJ_P (type)
5325       && has_value_dependent_address (expr))
5326     /* If we want the address and it's value-dependent, don't fold.  */;
5327   else if (!type_unknown_p (expr))
5328     expr = fold_non_dependent_expr_sfinae (expr, complain);
5329   if (error_operand_p (expr))
5330     return error_mark_node;
5331   expr_type = TREE_TYPE (expr);
5332   if (TREE_CODE (type) == REFERENCE_TYPE)
5333     expr = mark_lvalue_use (expr);
5334   else
5335     expr = mark_rvalue_use (expr);
5336
5337   /* HACK: Due to double coercion, we can get a
5338      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
5339      which is the tree that we built on the first call (see
5340      below when coercing to reference to object or to reference to
5341      function). We just strip everything and get to the arg.
5342      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
5343      for examples.  */
5344   if (TREE_CODE (expr) == NOP_EXPR)
5345     {
5346       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
5347         {
5348           /* ??? Maybe we could use convert_from_reference here, but we
5349              would need to relax its constraints because the NOP_EXPR
5350              could actually change the type to something more cv-qualified,
5351              and this is not folded by convert_from_reference.  */
5352           tree addr = TREE_OPERAND (expr, 0);
5353           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
5354           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
5355           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
5356           gcc_assert (same_type_ignoring_top_level_qualifiers_p
5357                       (TREE_TYPE (expr_type),
5358                        TREE_TYPE (TREE_TYPE (addr))));
5359
5360           expr = TREE_OPERAND (addr, 0);
5361           expr_type = TREE_TYPE (expr);
5362         }
5363
5364       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
5365          parameter is a pointer to object, through decay and
5366          qualification conversion. Let's strip everything.  */
5367       else if (TYPE_PTROBV_P (type))
5368         {
5369           STRIP_NOPS (expr);
5370           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
5371           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
5372           /* Skip the ADDR_EXPR only if it is part of the decay for
5373              an array. Otherwise, it is part of the original argument
5374              in the source code.  */
5375           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
5376             expr = TREE_OPERAND (expr, 0);
5377           expr_type = TREE_TYPE (expr);
5378         }
5379     }
5380
5381   /* [temp.arg.nontype]/5, bullet 1
5382
5383      For a non-type template-parameter of integral or enumeration type,
5384      integral promotions (_conv.prom_) and integral conversions
5385      (_conv.integral_) are applied.  */
5386   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
5387     {
5388       tree t = build_integral_nontype_arg_conv (type, expr, complain);
5389       t = maybe_constant_value (t);
5390       if (t != error_mark_node)
5391         expr = t;
5392
5393       if (!same_type_ignoring_top_level_qualifiers_p (type, TREE_TYPE (expr)))
5394         return error_mark_node;
5395
5396       /* Notice that there are constant expressions like '4 % 0' which
5397          do not fold into integer constants.  */
5398       if (TREE_CODE (expr) != INTEGER_CST)
5399         {
5400           if (complain & tf_error)
5401             {
5402               error ("%qE is not a valid template argument for type %qT "
5403                      "because it is a non-constant expression", expr, type);
5404               cxx_constant_value (expr);
5405             }
5406           return NULL_TREE;
5407         }
5408     }
5409   /* [temp.arg.nontype]/5, bullet 2
5410
5411      For a non-type template-parameter of type pointer to object,
5412      qualification conversions (_conv.qual_) and the array-to-pointer
5413      conversion (_conv.array_) are applied.  */
5414   else if (TYPE_PTROBV_P (type))
5415     {
5416       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
5417
5418          A template-argument for a non-type, non-template template-parameter
5419          shall be one of: [...]
5420
5421          -- the name of a non-type template-parameter;
5422          -- the address of an object or function with external linkage, [...]
5423             expressed as "& id-expression" where the & is optional if the name
5424             refers to a function or array, or if the corresponding
5425             template-parameter is a reference.
5426
5427         Here, we do not care about functions, as they are invalid anyway
5428         for a parameter of type pointer-to-object.  */
5429
5430       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
5431         /* Non-type template parameters are OK.  */
5432         ;
5433       else if (TREE_CODE (expr) != ADDR_EXPR
5434                && TREE_CODE (expr_type) != ARRAY_TYPE)
5435         {
5436           if (TREE_CODE (expr) == VAR_DECL)
5437             {
5438               error ("%qD is not a valid template argument "
5439                      "because %qD is a variable, not the address of "
5440                      "a variable",
5441                      expr, expr);
5442               return NULL_TREE;
5443             }
5444           /* Other values, like integer constants, might be valid
5445              non-type arguments of some other type.  */
5446           return error_mark_node;
5447         }
5448       else
5449         {
5450           tree decl;
5451
5452           decl = ((TREE_CODE (expr) == ADDR_EXPR)
5453                   ? TREE_OPERAND (expr, 0) : expr);
5454           if (TREE_CODE (decl) != VAR_DECL)
5455             {
5456               error ("%qE is not a valid template argument of type %qT "
5457                      "because %qE is not a variable",
5458                      expr, type, decl);
5459               return NULL_TREE;
5460             }
5461           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
5462             {
5463               error ("%qE is not a valid template argument of type %qT "
5464                      "because %qD does not have external linkage",
5465                      expr, type, decl);
5466               return NULL_TREE;
5467             }
5468         }
5469
5470       expr = decay_conversion (expr);
5471       if (expr == error_mark_node)
5472         return error_mark_node;
5473
5474       expr = perform_qualification_conversions (type, expr);
5475       if (expr == error_mark_node)
5476         return error_mark_node;
5477     }
5478   /* [temp.arg.nontype]/5, bullet 3
5479
5480      For a non-type template-parameter of type reference to object, no
5481      conversions apply. The type referred to by the reference may be more
5482      cv-qualified than the (otherwise identical) type of the
5483      template-argument. The template-parameter is bound directly to the
5484      template-argument, which must be an lvalue.  */
5485   else if (TYPE_REF_OBJ_P (type))
5486     {
5487       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
5488                                                       expr_type))
5489         return error_mark_node;
5490
5491       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
5492         {
5493           error ("%qE is not a valid template argument for type %qT "
5494                  "because of conflicts in cv-qualification", expr, type);
5495           return NULL_TREE;
5496         }
5497
5498       if (!real_lvalue_p (expr))
5499         {
5500           error ("%qE is not a valid template argument for type %qT "
5501                  "because it is not an lvalue", expr, type);
5502           return NULL_TREE;
5503         }
5504
5505       /* [temp.arg.nontype]/1
5506
5507          A template-argument for a non-type, non-template template-parameter
5508          shall be one of: [...]
5509
5510          -- the address of an object or function with external linkage.  */
5511       if (TREE_CODE (expr) == INDIRECT_REF
5512           && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
5513         {
5514           expr = TREE_OPERAND (expr, 0);
5515           if (DECL_P (expr))
5516             {
5517               error ("%q#D is not a valid template argument for type %qT "
5518                      "because a reference variable does not have a constant "
5519                      "address", expr, type);
5520               return NULL_TREE;
5521             }
5522         }
5523
5524       if (!DECL_P (expr))
5525         {
5526           error ("%qE is not a valid template argument for type %qT "
5527                  "because it is not an object with external linkage",
5528                  expr, type);
5529           return NULL_TREE;
5530         }
5531
5532       if (!DECL_EXTERNAL_LINKAGE_P (expr))
5533         {
5534           error ("%qE is not a valid template argument for type %qT "
5535                  "because object %qD has not external linkage",
5536                  expr, type, expr);
5537           return NULL_TREE;
5538         }
5539
5540       expr = build_nop (type, build_address (expr));
5541     }
5542   /* [temp.arg.nontype]/5, bullet 4
5543
5544      For a non-type template-parameter of type pointer to function, only
5545      the function-to-pointer conversion (_conv.func_) is applied. If the
5546      template-argument represents a set of overloaded functions (or a
5547      pointer to such), the matching function is selected from the set
5548      (_over.over_).  */
5549   else if (TYPE_PTRFN_P (type))
5550     {
5551       /* If the argument is a template-id, we might not have enough
5552          context information to decay the pointer.  */
5553       if (!type_unknown_p (expr_type))
5554         {
5555           expr = decay_conversion (expr);
5556           if (expr == error_mark_node)
5557             return error_mark_node;
5558         }
5559
5560       expr = convert_nontype_argument_function (type, expr);
5561       if (!expr || expr == error_mark_node)
5562         return expr;
5563
5564       if (TREE_CODE (expr) != ADDR_EXPR)
5565         {
5566           error ("%qE is not a valid template argument for type %qT", expr, type);
5567           error ("it must be the address of a function with external linkage");
5568           return NULL_TREE;
5569         }
5570     }
5571   /* [temp.arg.nontype]/5, bullet 5
5572
5573      For a non-type template-parameter of type reference to function, no
5574      conversions apply. If the template-argument represents a set of
5575      overloaded functions, the matching function is selected from the set
5576      (_over.over_).  */
5577   else if (TYPE_REFFN_P (type))
5578     {
5579       if (TREE_CODE (expr) == ADDR_EXPR)
5580         {
5581           error ("%qE is not a valid template argument for type %qT "
5582                  "because it is a pointer", expr, type);
5583           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
5584           return NULL_TREE;
5585         }
5586
5587       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
5588       if (!expr || expr == error_mark_node)
5589         return expr;
5590
5591       expr = build_nop (type, build_address (expr));
5592     }
5593   /* [temp.arg.nontype]/5, bullet 6
5594
5595      For a non-type template-parameter of type pointer to member function,
5596      no conversions apply. If the template-argument represents a set of
5597      overloaded member functions, the matching member function is selected
5598      from the set (_over.over_).  */
5599   else if (TYPE_PTRMEMFUNC_P (type))
5600     {
5601       expr = instantiate_type (type, expr, tf_none);
5602       if (expr == error_mark_node)
5603         return error_mark_node;
5604
5605       /* [temp.arg.nontype] bullet 1 says the pointer to member
5606          expression must be a pointer-to-member constant.  */
5607       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
5608         return error_mark_node;
5609
5610       /* There is no way to disable standard conversions in
5611          resolve_address_of_overloaded_function (called by
5612          instantiate_type). It is possible that the call succeeded by
5613          converting &B::I to &D::I (where B is a base of D), so we need
5614          to reject this conversion here.
5615
5616          Actually, even if there was a way to disable standard conversions,
5617          it would still be better to reject them here so that we can
5618          provide a superior diagnostic.  */
5619       if (!same_type_p (TREE_TYPE (expr), type))
5620         {
5621           error ("%qE is not a valid template argument for type %qT "
5622                  "because it is of type %qT", expr, type,
5623                  TREE_TYPE (expr));
5624           /* If we are just one standard conversion off, explain.  */
5625           if (can_convert (type, TREE_TYPE (expr)))
5626             inform (input_location,
5627                     "standard conversions are not allowed in this context");
5628           return NULL_TREE;
5629         }
5630     }
5631   /* [temp.arg.nontype]/5, bullet 7
5632
5633      For a non-type template-parameter of type pointer to data member,
5634      qualification conversions (_conv.qual_) are applied.  */
5635   else if (TYPE_PTRMEM_P (type))
5636     {
5637       /* [temp.arg.nontype] bullet 1 says the pointer to member
5638          expression must be a pointer-to-member constant.  */
5639       if (!check_valid_ptrmem_cst_expr (type, expr, complain))
5640         return error_mark_node;
5641
5642       expr = perform_qualification_conversions (type, expr);
5643       if (expr == error_mark_node)
5644         return expr;
5645     }
5646   /* A template non-type parameter must be one of the above.  */
5647   else
5648     gcc_unreachable ();
5649
5650   /* Sanity check: did we actually convert the argument to the
5651      right type?  */
5652   gcc_assert (same_type_ignoring_top_level_qualifiers_p
5653               (type, TREE_TYPE (expr)));
5654   return expr;
5655 }
5656
5657 /* Subroutine of coerce_template_template_parms, which returns 1 if
5658    PARM_PARM and ARG_PARM match using the rule for the template
5659    parameters of template template parameters. Both PARM and ARG are
5660    template parameters; the rest of the arguments are the same as for
5661    coerce_template_template_parms.
5662  */
5663 static int
5664 coerce_template_template_parm (tree parm,
5665                               tree arg,
5666                               tsubst_flags_t complain,
5667                               tree in_decl,
5668                               tree outer_args)
5669 {
5670   if (arg == NULL_TREE || arg == error_mark_node
5671       || parm == NULL_TREE || parm == error_mark_node)
5672     return 0;
5673   
5674   if (TREE_CODE (arg) != TREE_CODE (parm))
5675     return 0;
5676   
5677   switch (TREE_CODE (parm))
5678     {
5679     case TEMPLATE_DECL:
5680       /* We encounter instantiations of templates like
5681          template <template <template <class> class> class TT>
5682          class C;  */
5683       {
5684         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5685         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5686         
5687         if (!coerce_template_template_parms
5688             (parmparm, argparm, complain, in_decl, outer_args))
5689           return 0;
5690       }
5691       /* Fall through.  */
5692       
5693     case TYPE_DECL:
5694       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
5695           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5696         /* Argument is a parameter pack but parameter is not.  */
5697         return 0;
5698       break;
5699       
5700     case PARM_DECL:
5701       /* The tsubst call is used to handle cases such as
5702          
5703            template <int> class C {};
5704            template <class T, template <T> class TT> class D {};
5705            D<int, C> d;
5706
5707          i.e. the parameter list of TT depends on earlier parameters.  */
5708       if (!uses_template_parms (TREE_TYPE (arg))
5709           && !same_type_p
5710                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
5711                  TREE_TYPE (arg)))
5712         return 0;
5713       
5714       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
5715           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5716         /* Argument is a parameter pack but parameter is not.  */
5717         return 0;
5718       
5719       break;
5720
5721     default:
5722       gcc_unreachable ();
5723     }
5724
5725   return 1;
5726 }
5727
5728
5729 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
5730    template template parameters.  Both PARM_PARMS and ARG_PARMS are
5731    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
5732    or PARM_DECL.
5733
5734    Consider the example:
5735      template <class T> class A;
5736      template<template <class U> class TT> class B;
5737
5738    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
5739    the parameters to A, and OUTER_ARGS contains A.  */
5740
5741 static int
5742 coerce_template_template_parms (tree parm_parms,
5743                                 tree arg_parms,
5744                                 tsubst_flags_t complain,
5745                                 tree in_decl,
5746                                 tree outer_args)
5747 {
5748   int nparms, nargs, i;
5749   tree parm, arg;
5750   int variadic_p = 0;
5751
5752   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
5753   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
5754
5755   nparms = TREE_VEC_LENGTH (parm_parms);
5756   nargs = TREE_VEC_LENGTH (arg_parms);
5757
5758   /* Determine whether we have a parameter pack at the end of the
5759      template template parameter's template parameter list.  */
5760   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
5761     {
5762       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
5763       
5764       if (parm == error_mark_node)
5765         return 0;
5766
5767       switch (TREE_CODE (parm))
5768         {
5769         case TEMPLATE_DECL:
5770         case TYPE_DECL:
5771           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5772             variadic_p = 1;
5773           break;
5774           
5775         case PARM_DECL:
5776           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5777             variadic_p = 1;
5778           break;
5779           
5780         default:
5781           gcc_unreachable ();
5782         }
5783     }
5784  
5785   if (nargs != nparms
5786       && !(variadic_p && nargs >= nparms - 1))
5787     return 0;
5788
5789   /* Check all of the template parameters except the parameter pack at
5790      the end (if any).  */
5791   for (i = 0; i < nparms - variadic_p; ++i)
5792     {
5793       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
5794           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5795         continue;
5796
5797       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5798       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5799
5800       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5801                                           outer_args))
5802         return 0;
5803
5804     }
5805
5806   if (variadic_p)
5807     {
5808       /* Check each of the template parameters in the template
5809          argument against the template parameter pack at the end of
5810          the template template parameter.  */
5811       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
5812         return 0;
5813
5814       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5815
5816       for (; i < nargs; ++i)
5817         {
5818           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5819             continue;
5820  
5821           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5822  
5823           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5824                                               outer_args))
5825             return 0;
5826         }
5827     }
5828
5829   return 1;
5830 }
5831
5832 /* Verifies that the deduced template arguments (in TARGS) for the
5833    template template parameters (in TPARMS) represent valid bindings,
5834    by comparing the template parameter list of each template argument
5835    to the template parameter list of its corresponding template
5836    template parameter, in accordance with DR150. This
5837    routine can only be called after all template arguments have been
5838    deduced. It will return TRUE if all of the template template
5839    parameter bindings are okay, FALSE otherwise.  */
5840 bool 
5841 template_template_parm_bindings_ok_p (tree tparms, tree targs)
5842 {
5843   int i, ntparms = TREE_VEC_LENGTH (tparms);
5844   bool ret = true;
5845
5846   /* We're dealing with template parms in this process.  */
5847   ++processing_template_decl;
5848
5849   targs = INNERMOST_TEMPLATE_ARGS (targs);
5850
5851   for (i = 0; i < ntparms; ++i)
5852     {
5853       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
5854       tree targ = TREE_VEC_ELT (targs, i);
5855
5856       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
5857         {
5858           tree packed_args = NULL_TREE;
5859           int idx, len = 1;
5860
5861           if (ARGUMENT_PACK_P (targ))
5862             {
5863               /* Look inside the argument pack.  */
5864               packed_args = ARGUMENT_PACK_ARGS (targ);
5865               len = TREE_VEC_LENGTH (packed_args);
5866             }
5867
5868           for (idx = 0; idx < len; ++idx)
5869             {
5870               tree targ_parms = NULL_TREE;
5871
5872               if (packed_args)
5873                 /* Extract the next argument from the argument
5874                    pack.  */
5875                 targ = TREE_VEC_ELT (packed_args, idx);
5876
5877               if (PACK_EXPANSION_P (targ))
5878                 /* Look at the pattern of the pack expansion.  */
5879                 targ = PACK_EXPANSION_PATTERN (targ);
5880
5881               /* Extract the template parameters from the template
5882                  argument.  */
5883               if (TREE_CODE (targ) == TEMPLATE_DECL)
5884                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
5885               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
5886                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
5887
5888               /* Verify that we can coerce the template template
5889                  parameters from the template argument to the template
5890                  parameter.  This requires an exact match.  */
5891               if (targ_parms
5892                   && !coerce_template_template_parms
5893                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
5894                         targ_parms,
5895                         tf_none,
5896                         tparm,
5897                         targs))
5898                 {
5899                   ret = false;
5900                   goto out;
5901                 }
5902             }
5903         }
5904     }
5905
5906  out:
5907
5908   --processing_template_decl;
5909   return ret;
5910 }
5911
5912 /* Convert the indicated template ARG as necessary to match the
5913    indicated template PARM.  Returns the converted ARG, or
5914    error_mark_node if the conversion was unsuccessful.  Error and
5915    warning messages are issued under control of COMPLAIN.  This
5916    conversion is for the Ith parameter in the parameter list.  ARGS is
5917    the full set of template arguments deduced so far.  */
5918
5919 static tree
5920 convert_template_argument (tree parm,
5921                            tree arg,
5922                            tree args,
5923                            tsubst_flags_t complain,
5924                            int i,
5925                            tree in_decl)
5926 {
5927   tree orig_arg;
5928   tree val;
5929   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
5930
5931   if (TREE_CODE (arg) == TREE_LIST
5932       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
5933     {
5934       /* The template argument was the name of some
5935          member function.  That's usually
5936          invalid, but static members are OK.  In any
5937          case, grab the underlying fields/functions
5938          and issue an error later if required.  */
5939       orig_arg = TREE_VALUE (arg);
5940       TREE_TYPE (arg) = unknown_type_node;
5941     }
5942
5943   orig_arg = arg;
5944
5945   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
5946   requires_type = (TREE_CODE (parm) == TYPE_DECL
5947                    || requires_tmpl_type);
5948
5949   /* When determining whether an argument pack expansion is a template,
5950      look at the pattern.  */
5951   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
5952     arg = PACK_EXPANSION_PATTERN (arg);
5953
5954   /* Deal with an injected-class-name used as a template template arg.  */
5955   if (requires_tmpl_type && CLASS_TYPE_P (arg))
5956     {
5957       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
5958       if (TREE_CODE (t) == TEMPLATE_DECL)
5959         {
5960           if (complain & tf_warning_or_error)
5961             pedwarn (input_location, OPT_pedantic, "injected-class-name %qD"
5962                      " used as template template argument", TYPE_NAME (arg));
5963           else if (flag_pedantic_errors)
5964             t = arg;
5965
5966           arg = t;
5967         }
5968     }
5969
5970   is_tmpl_type = 
5971     ((TREE_CODE (arg) == TEMPLATE_DECL
5972       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
5973      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5974      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
5975
5976   if (is_tmpl_type
5977       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5978           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
5979     arg = TYPE_STUB_DECL (arg);
5980
5981   is_type = TYPE_P (arg) || is_tmpl_type;
5982
5983   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
5984       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
5985     {
5986       permerror (input_location, "to refer to a type member of a template parameter, "
5987                  "use %<typename %E%>", orig_arg);
5988
5989       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
5990                                      TREE_OPERAND (arg, 1),
5991                                      typename_type,
5992                                      complain & tf_error);
5993       arg = orig_arg;
5994       is_type = 1;
5995     }
5996   if (is_type != requires_type)
5997     {
5998       if (in_decl)
5999         {
6000           if (complain & tf_error)
6001             {
6002               error ("type/value mismatch at argument %d in template "
6003                      "parameter list for %qD",
6004                      i + 1, in_decl);
6005               if (is_type)
6006                 error ("  expected a constant of type %qT, got %qT",
6007                        TREE_TYPE (parm),
6008                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
6009               else if (requires_tmpl_type)
6010                 error ("  expected a class template, got %qE", orig_arg);
6011               else
6012                 error ("  expected a type, got %qE", orig_arg);
6013             }
6014         }
6015       return error_mark_node;
6016     }
6017   if (is_tmpl_type ^ requires_tmpl_type)
6018     {
6019       if (in_decl && (complain & tf_error))
6020         {
6021           error ("type/value mismatch at argument %d in template "
6022                  "parameter list for %qD",
6023                  i + 1, in_decl);
6024           if (is_tmpl_type)
6025             error ("  expected a type, got %qT", DECL_NAME (arg));
6026           else
6027             error ("  expected a class template, got %qT", orig_arg);
6028         }
6029       return error_mark_node;
6030     }
6031
6032   if (is_type)
6033     {
6034       if (requires_tmpl_type)
6035         {
6036           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
6037             /* The number of argument required is not known yet.
6038                Just accept it for now.  */
6039             val = TREE_TYPE (arg);
6040           else
6041             {
6042               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
6043               tree argparm;
6044
6045               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
6046
6047               if (coerce_template_template_parms (parmparm, argparm,
6048                                                   complain, in_decl,
6049                                                   args))
6050                 {
6051                   val = arg;
6052
6053                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
6054                      TEMPLATE_DECL.  */
6055                   if (val != error_mark_node)
6056                     {
6057                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
6058                         val = TREE_TYPE (val);
6059                       if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
6060                         val = make_pack_expansion (val);
6061                     }
6062                 }
6063               else
6064                 {
6065                   if (in_decl && (complain & tf_error))
6066                     {
6067                       error ("type/value mismatch at argument %d in "
6068                              "template parameter list for %qD",
6069                              i + 1, in_decl);
6070                       error ("  expected a template of type %qD, got %qT",
6071                              parm, orig_arg);
6072                     }
6073
6074                   val = error_mark_node;
6075                 }
6076             }
6077         }
6078       else
6079         val = orig_arg;
6080       /* We only form one instance of each template specialization.
6081          Therefore, if we use a non-canonical variant (i.e., a
6082          typedef), any future messages referring to the type will use
6083          the typedef, which is confusing if those future uses do not
6084          themselves also use the typedef.  */
6085       if (TYPE_P (val))
6086         val = strip_typedefs (val);
6087     }
6088   else
6089     {
6090       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
6091
6092       if (invalid_nontype_parm_type_p (t, complain))
6093         return error_mark_node;
6094
6095       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
6096         {
6097           if (same_type_p (t, TREE_TYPE (orig_arg)))
6098             val = orig_arg;
6099           else
6100             {
6101               /* Not sure if this is reachable, but it doesn't hurt
6102                  to be robust.  */
6103               error ("type mismatch in nontype parameter pack");
6104               val = error_mark_node;
6105             }
6106         }
6107       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
6108         /* We used to call digest_init here.  However, digest_init
6109            will report errors, which we don't want when complain
6110            is zero.  More importantly, digest_init will try too
6111            hard to convert things: for example, `0' should not be
6112            converted to pointer type at this point according to
6113            the standard.  Accepting this is not merely an
6114            extension, since deciding whether or not these
6115            conversions can occur is part of determining which
6116            function template to call, or whether a given explicit
6117            argument specification is valid.  */
6118         val = convert_nontype_argument (t, orig_arg, complain);
6119       else
6120         val = orig_arg;
6121
6122       if (val == NULL_TREE)
6123         val = error_mark_node;
6124       else if (val == error_mark_node && (complain & tf_error))
6125         error ("could not convert template argument %qE to %qT",  orig_arg, t);
6126
6127       if (TREE_CODE (val) == SCOPE_REF)
6128         {
6129           /* Strip typedefs from the SCOPE_REF.  */
6130           tree type = strip_typedefs (TREE_TYPE (val));
6131           tree scope = strip_typedefs (TREE_OPERAND (val, 0));
6132           val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
6133                                       QUALIFIED_NAME_IS_TEMPLATE (val));
6134         }
6135     }
6136
6137   return val;
6138 }
6139
6140 /* Coerces the remaining template arguments in INNER_ARGS (from
6141    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
6142    Returns the coerced argument pack. PARM_IDX is the position of this
6143    parameter in the template parameter list. ARGS is the original
6144    template argument list.  */
6145 static tree
6146 coerce_template_parameter_pack (tree parms,
6147                                 int parm_idx,
6148                                 tree args,
6149                                 tree inner_args,
6150                                 int arg_idx,
6151                                 tree new_args,
6152                                 int* lost,
6153                                 tree in_decl,
6154                                 tsubst_flags_t complain)
6155 {
6156   tree parm = TREE_VEC_ELT (parms, parm_idx);
6157   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
6158   tree packed_args;
6159   tree argument_pack;
6160   tree packed_types = NULL_TREE;
6161
6162   if (arg_idx > nargs)
6163     arg_idx = nargs;
6164
6165   packed_args = make_tree_vec (nargs - arg_idx);
6166
6167   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
6168       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
6169     {
6170       /* When the template parameter is a non-type template
6171          parameter pack whose type uses parameter packs, we need
6172          to look at each of the template arguments
6173          separately. Build a vector of the types for these
6174          non-type template parameters in PACKED_TYPES.  */
6175       tree expansion 
6176         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
6177       packed_types = tsubst_pack_expansion (expansion, args,
6178                                             complain, in_decl);
6179
6180       if (packed_types == error_mark_node)
6181         return error_mark_node;
6182
6183       /* Check that we have the right number of arguments.  */
6184       if (arg_idx < nargs
6185           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
6186           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
6187         {
6188           int needed_parms 
6189             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
6190           error ("wrong number of template arguments (%d, should be %d)",
6191                  nargs, needed_parms);
6192           return error_mark_node;
6193         }
6194
6195       /* If we aren't able to check the actual arguments now
6196          (because they haven't been expanded yet), we can at least
6197          verify that all of the types used for the non-type
6198          template parameter pack are, in fact, valid for non-type
6199          template parameters.  */
6200       if (arg_idx < nargs 
6201           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
6202         {
6203           int j, len = TREE_VEC_LENGTH (packed_types);
6204           for (j = 0; j < len; ++j)
6205             {
6206               tree t = TREE_VEC_ELT (packed_types, j);
6207               if (invalid_nontype_parm_type_p (t, complain))
6208                 return error_mark_node;
6209             }
6210         }
6211     }
6212
6213   /* Convert the remaining arguments, which will be a part of the
6214      parameter pack "parm".  */
6215   for (; arg_idx < nargs; ++arg_idx)
6216     {
6217       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
6218       tree actual_parm = TREE_VALUE (parm);
6219
6220       if (packed_types && !PACK_EXPANSION_P (arg))
6221         {
6222           /* When we have a vector of types (corresponding to the
6223              non-type template parameter pack that uses parameter
6224              packs in its type, as mention above), and the
6225              argument is not an expansion (which expands to a
6226              currently unknown number of arguments), clone the
6227              parm and give it the next type in PACKED_TYPES.  */
6228           actual_parm = copy_node (actual_parm);
6229           TREE_TYPE (actual_parm) = 
6230             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
6231         }
6232
6233       if (arg != error_mark_node)
6234         arg = convert_template_argument (actual_parm, 
6235                                          arg, new_args, complain, parm_idx,
6236                                          in_decl);
6237       if (arg == error_mark_node)
6238         (*lost)++;
6239       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
6240     }
6241
6242   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
6243       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
6244     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
6245   else
6246     {
6247       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
6248       TREE_TYPE (argument_pack) 
6249         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
6250       TREE_CONSTANT (argument_pack) = 1;
6251     }
6252
6253   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
6254 #ifdef ENABLE_CHECKING
6255   SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
6256                                        TREE_VEC_LENGTH (packed_args));
6257 #endif
6258   return argument_pack;
6259 }
6260
6261 /* Convert all template arguments to their appropriate types, and
6262    return a vector containing the innermost resulting template
6263    arguments.  If any error occurs, return error_mark_node. Error and
6264    warning messages are issued under control of COMPLAIN.
6265
6266    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
6267    for arguments not specified in ARGS.  Otherwise, if
6268    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
6269    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
6270    USE_DEFAULT_ARGS is false, then all arguments must be specified in
6271    ARGS.  */
6272
6273 static tree
6274 coerce_template_parms (tree parms,
6275                        tree args,
6276                        tree in_decl,
6277                        tsubst_flags_t complain,
6278                        bool require_all_args,
6279                        bool use_default_args)
6280 {
6281   int nparms, nargs, parm_idx, arg_idx, lost = 0;
6282   tree inner_args;
6283   tree new_args;
6284   tree new_inner_args;
6285   int saved_unevaluated_operand;
6286   int saved_inhibit_evaluation_warnings;
6287
6288   /* When used as a boolean value, indicates whether this is a
6289      variadic template parameter list. Since it's an int, we can also
6290      subtract it from nparms to get the number of non-variadic
6291      parameters.  */
6292   int variadic_p = 0;
6293
6294   if (args == error_mark_node)
6295     return error_mark_node;
6296
6297   nparms = TREE_VEC_LENGTH (parms);
6298
6299   /* Determine if there are any parameter packs.  */
6300   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
6301     {
6302       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
6303       if (template_parameter_pack_p (tparm))
6304         ++variadic_p;
6305     }
6306
6307   inner_args = INNERMOST_TEMPLATE_ARGS (args);
6308   /* If there are 0 or 1 parameter packs, we need to expand any argument
6309      packs so that we can deduce a parameter pack from some non-packed args
6310      followed by an argument pack, as in variadic85.C.  If there are more
6311      than that, we need to leave argument packs intact so the arguments are
6312      assigned to the right parameter packs.  This should only happen when
6313      dealing with a nested class inside a partial specialization of a class
6314      template, as in variadic92.C.  */
6315   if (variadic_p <= 1)
6316     inner_args = expand_template_argument_pack (inner_args);
6317
6318   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
6319   if ((nargs > nparms && !variadic_p)
6320       || (nargs < nparms - variadic_p
6321           && require_all_args
6322           && (!use_default_args
6323               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
6324                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
6325     {
6326       if (complain & tf_error)
6327         {
6328           if (variadic_p)
6329             {
6330               --nparms;
6331               error ("wrong number of template arguments "
6332                      "(%d, should be %d or more)", nargs, nparms);
6333             }
6334           else
6335              error ("wrong number of template arguments "
6336                     "(%d, should be %d)", nargs, nparms);
6337
6338           if (in_decl)
6339             error ("provided for %q+D", in_decl);
6340         }
6341
6342       return error_mark_node;
6343     }
6344
6345   /* We need to evaluate the template arguments, even though this
6346      template-id may be nested within a "sizeof".  */
6347   saved_unevaluated_operand = cp_unevaluated_operand;
6348   cp_unevaluated_operand = 0;
6349   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
6350   c_inhibit_evaluation_warnings = 0;
6351   new_inner_args = make_tree_vec (nparms);
6352   new_args = add_outermost_template_args (args, new_inner_args);
6353   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
6354     {
6355       tree arg;
6356       tree parm;
6357
6358       /* Get the Ith template parameter.  */
6359       parm = TREE_VEC_ELT (parms, parm_idx);
6360  
6361       if (parm == error_mark_node)
6362       {
6363         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
6364         continue;
6365       }
6366
6367       /* Calculate the next argument.  */
6368       if (arg_idx < nargs)
6369         arg = TREE_VEC_ELT (inner_args, arg_idx);
6370       else
6371         arg = NULL_TREE;
6372
6373       if (template_parameter_pack_p (TREE_VALUE (parm))
6374           && !(arg && ARGUMENT_PACK_P (arg)))
6375         {
6376           /* All remaining arguments will be placed in the
6377              template parameter pack PARM.  */
6378           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
6379                                                 inner_args, arg_idx,
6380                                                 new_args, &lost,
6381                                                 in_decl, complain);
6382
6383           /* Store this argument.  */
6384           if (arg == error_mark_node)
6385             lost++;
6386           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
6387
6388           /* We are done with all of the arguments.  */
6389           arg_idx = nargs;
6390           
6391           continue;
6392         }
6393       else if (arg)
6394         {
6395           if (PACK_EXPANSION_P (arg))
6396             {
6397               if (complain & tf_error)
6398                 {
6399                   /* FIXME this restriction was removed by N2555; see
6400                      bug 35722.  */
6401                   /* If ARG is a pack expansion, but PARM is not a
6402                      template parameter pack (if it were, we would have
6403                      handled it above), we're trying to expand into a
6404                      fixed-length argument list.  */
6405                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
6406                     sorry ("cannot expand %<%E%> into a fixed-length "
6407                            "argument list", arg);
6408                   else
6409                     sorry ("cannot expand %<%T%> into a fixed-length "
6410                            "argument list", arg);
6411                 }
6412               ++lost;
6413             }
6414         }
6415       else if (require_all_args)
6416         {
6417           /* There must be a default arg in this case.  */
6418           arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
6419                                      complain, in_decl);
6420           /* The position of the first default template argument,
6421              is also the number of non-defaulted arguments in NEW_INNER_ARGS.
6422              Record that.  */
6423           if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6424             SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args, arg_idx);
6425         }
6426       else
6427         break;
6428
6429       if (arg == error_mark_node)
6430         {
6431           if (complain & tf_error)
6432             error ("template argument %d is invalid", arg_idx + 1);
6433         }
6434       else if (!arg)
6435         /* This only occurs if there was an error in the template
6436            parameter list itself (which we would already have
6437            reported) that we are trying to recover from, e.g., a class
6438            template with a parameter list such as
6439            template<typename..., typename>.  */
6440         ++lost;
6441       else
6442         arg = convert_template_argument (TREE_VALUE (parm),
6443                                          arg, new_args, complain, 
6444                                          parm_idx, in_decl);
6445
6446       if (arg == error_mark_node)
6447         lost++;
6448       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
6449     }
6450   cp_unevaluated_operand = saved_unevaluated_operand;
6451   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
6452
6453   if (lost)
6454     return error_mark_node;
6455
6456 #ifdef ENABLE_CHECKING
6457   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6458     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
6459                                          TREE_VEC_LENGTH (new_inner_args));
6460 #endif
6461
6462   return new_inner_args;
6463 }
6464
6465 /* Returns 1 if template args OT and NT are equivalent.  */
6466
6467 static int
6468 template_args_equal (tree ot, tree nt)
6469 {
6470   if (nt == ot)
6471     return 1;
6472
6473   if (TREE_CODE (nt) == TREE_VEC)
6474     /* For member templates */
6475     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
6476   else if (PACK_EXPANSION_P (ot))
6477     return PACK_EXPANSION_P (nt) 
6478       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
6479                               PACK_EXPANSION_PATTERN (nt));
6480   else if (ARGUMENT_PACK_P (ot))
6481     {
6482       int i, len;
6483       tree opack, npack;
6484
6485       if (!ARGUMENT_PACK_P (nt))
6486         return 0;
6487
6488       opack = ARGUMENT_PACK_ARGS (ot);
6489       npack = ARGUMENT_PACK_ARGS (nt);
6490       len = TREE_VEC_LENGTH (opack);
6491       if (TREE_VEC_LENGTH (npack) != len)
6492         return 0;
6493       for (i = 0; i < len; ++i)
6494         if (!template_args_equal (TREE_VEC_ELT (opack, i),
6495                                   TREE_VEC_ELT (npack, i)))
6496           return 0;
6497       return 1;
6498     }
6499   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
6500     {
6501       /* We get here probably because we are in the middle of substituting
6502          into the pattern of a pack expansion. In that case the
6503          ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
6504          interested in. So we want to use the initial pack argument for
6505          the comparison.  */
6506       ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
6507       if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
6508         nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
6509       return template_args_equal (ot, nt);
6510     }
6511   else if (TYPE_P (nt))
6512     return TYPE_P (ot) && same_type_p (ot, nt);
6513   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
6514     return 0;
6515   else
6516     return cp_tree_equal (ot, nt);
6517 }
6518
6519 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
6520    of template arguments.  Returns 0 otherwise.  */
6521
6522 int
6523 comp_template_args (tree oldargs, tree newargs)
6524 {
6525   int i;
6526
6527   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
6528     return 0;
6529
6530   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
6531     {
6532       tree nt = TREE_VEC_ELT (newargs, i);
6533       tree ot = TREE_VEC_ELT (oldargs, i);
6534
6535       if (! template_args_equal (ot, nt))
6536         return 0;
6537     }
6538   return 1;
6539 }
6540
6541 static void
6542 add_pending_template (tree d)
6543 {
6544   tree ti = (TYPE_P (d)
6545              ? CLASSTYPE_TEMPLATE_INFO (d)
6546              : DECL_TEMPLATE_INFO (d));
6547   struct pending_template *pt;
6548   int level;
6549
6550   if (TI_PENDING_TEMPLATE_FLAG (ti))
6551     return;
6552
6553   /* We are called both from instantiate_decl, where we've already had a
6554      tinst_level pushed, and instantiate_template, where we haven't.
6555      Compensate.  */
6556   level = !current_tinst_level || current_tinst_level->decl != d;
6557
6558   if (level)
6559     push_tinst_level (d);
6560
6561   pt = ggc_alloc_pending_template ();
6562   pt->next = NULL;
6563   pt->tinst = current_tinst_level;
6564   if (last_pending_template)
6565     last_pending_template->next = pt;
6566   else
6567     pending_templates = pt;
6568
6569   last_pending_template = pt;
6570
6571   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
6572
6573   if (level)
6574     pop_tinst_level ();
6575 }
6576
6577
6578 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
6579    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
6580    documentation for TEMPLATE_ID_EXPR.  */
6581
6582 tree
6583 lookup_template_function (tree fns, tree arglist)
6584 {
6585   tree type;
6586
6587   if (fns == error_mark_node || arglist == error_mark_node)
6588     return error_mark_node;
6589
6590   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
6591   gcc_assert (fns && (is_overloaded_fn (fns)
6592                       || TREE_CODE (fns) == IDENTIFIER_NODE));
6593
6594   if (BASELINK_P (fns))
6595     {
6596       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
6597                                          unknown_type_node,
6598                                          BASELINK_FUNCTIONS (fns),
6599                                          arglist);
6600       return fns;
6601     }
6602
6603   type = TREE_TYPE (fns);
6604   if (TREE_CODE (fns) == OVERLOAD || !type)
6605     type = unknown_type_node;
6606
6607   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
6608 }
6609
6610 /* Within the scope of a template class S<T>, the name S gets bound
6611    (in build_self_reference) to a TYPE_DECL for the class, not a
6612    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
6613    or one of its enclosing classes, and that type is a template,
6614    return the associated TEMPLATE_DECL.  Otherwise, the original
6615    DECL is returned.
6616
6617    Also handle the case when DECL is a TREE_LIST of ambiguous
6618    injected-class-names from different bases.  */
6619
6620 tree
6621 maybe_get_template_decl_from_type_decl (tree decl)
6622 {
6623   if (decl == NULL_TREE)
6624     return decl;
6625
6626   /* DR 176: A lookup that finds an injected-class-name (10.2
6627      [class.member.lookup]) can result in an ambiguity in certain cases
6628      (for example, if it is found in more than one base class). If all of
6629      the injected-class-names that are found refer to specializations of
6630      the same class template, and if the name is followed by a
6631      template-argument-list, the reference refers to the class template
6632      itself and not a specialization thereof, and is not ambiguous.  */
6633   if (TREE_CODE (decl) == TREE_LIST)
6634     {
6635       tree t, tmpl = NULL_TREE;
6636       for (t = decl; t; t = TREE_CHAIN (t))
6637         {
6638           tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
6639           if (!tmpl)
6640             tmpl = elt;
6641           else if (tmpl != elt)
6642             break;
6643         }
6644       if (tmpl && t == NULL_TREE)
6645         return tmpl;
6646       else
6647         return decl;
6648     }
6649
6650   return (decl != NULL_TREE
6651           && DECL_SELF_REFERENCE_P (decl)
6652           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
6653     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
6654 }
6655
6656 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
6657    parameters, find the desired type.
6658
6659    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
6660
6661    IN_DECL, if non-NULL, is the template declaration we are trying to
6662    instantiate.
6663
6664    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
6665    the class we are looking up.
6666
6667    Issue error and warning messages under control of COMPLAIN.
6668
6669    If the template class is really a local class in a template
6670    function, then the FUNCTION_CONTEXT is the function in which it is
6671    being instantiated.
6672
6673    ??? Note that this function is currently called *twice* for each
6674    template-id: the first time from the parser, while creating the
6675    incomplete type (finish_template_type), and the second type during the
6676    real instantiation (instantiate_template_class). This is surely something
6677    that we want to avoid. It also causes some problems with argument
6678    coercion (see convert_nontype_argument for more information on this).  */
6679
6680 tree
6681 lookup_template_class (tree d1,
6682                        tree arglist,
6683                        tree in_decl,
6684                        tree context,
6685                        int entering_scope,
6686                        tsubst_flags_t complain)
6687 {
6688   tree templ = NULL_TREE, parmlist;
6689   tree t;
6690   spec_entry **slot;
6691   spec_entry *entry;
6692   spec_entry elt;
6693   hashval_t hash;
6694
6695   timevar_push (TV_NAME_LOOKUP);
6696
6697   if (TREE_CODE (d1) == IDENTIFIER_NODE)
6698     {
6699       tree value = innermost_non_namespace_value (d1);
6700       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
6701         templ = value;
6702       else
6703         {
6704           if (context)
6705             push_decl_namespace (context);
6706           templ = lookup_name (d1);
6707           templ = maybe_get_template_decl_from_type_decl (templ);
6708           if (context)
6709             pop_decl_namespace ();
6710         }
6711       if (templ)
6712         context = DECL_CONTEXT (templ);
6713     }
6714   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
6715     {
6716       tree type = TREE_TYPE (d1);
6717
6718       /* If we are declaring a constructor, say A<T>::A<T>, we will get
6719          an implicit typename for the second A.  Deal with it.  */
6720       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
6721         type = TREE_TYPE (type);
6722
6723       if (CLASSTYPE_TEMPLATE_INFO (type))
6724         {
6725           templ = CLASSTYPE_TI_TEMPLATE (type);
6726           d1 = DECL_NAME (templ);
6727         }
6728     }
6729   else if (TREE_CODE (d1) == ENUMERAL_TYPE
6730            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
6731     {
6732       templ = TYPE_TI_TEMPLATE (d1);
6733       d1 = DECL_NAME (templ);
6734     }
6735   else if (TREE_CODE (d1) == TEMPLATE_DECL
6736            && DECL_TEMPLATE_RESULT (d1)
6737            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
6738     {
6739       templ = d1;
6740       d1 = DECL_NAME (templ);
6741       context = DECL_CONTEXT (templ);
6742     }
6743
6744   /* Issue an error message if we didn't find a template.  */
6745   if (! templ)
6746     {
6747       if (complain & tf_error)
6748         error ("%qT is not a template", d1);
6749       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6750     }
6751
6752   if (TREE_CODE (templ) != TEMPLATE_DECL
6753          /* Make sure it's a user visible template, if it was named by
6754             the user.  */
6755       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
6756           && !PRIMARY_TEMPLATE_P (templ)))
6757     {
6758       if (complain & tf_error)
6759         {
6760           error ("non-template type %qT used as a template", d1);
6761           if (in_decl)
6762             error ("for template declaration %q+D", in_decl);
6763         }
6764       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6765     }
6766
6767   complain &= ~tf_user;
6768
6769   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
6770     {
6771       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
6772          template arguments */
6773
6774       tree parm;
6775       tree arglist2;
6776       tree outer;
6777
6778       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
6779
6780       /* Consider an example where a template template parameter declared as
6781
6782            template <class T, class U = std::allocator<T> > class TT
6783
6784          The template parameter level of T and U are one level larger than
6785          of TT.  To proper process the default argument of U, say when an
6786          instantiation `TT<int>' is seen, we need to build the full
6787          arguments containing {int} as the innermost level.  Outer levels,
6788          available when not appearing as default template argument, can be
6789          obtained from the arguments of the enclosing template.
6790
6791          Suppose that TT is later substituted with std::vector.  The above
6792          instantiation is `TT<int, std::allocator<T> >' with TT at
6793          level 1, and T at level 2, while the template arguments at level 1
6794          becomes {std::vector} and the inner level 2 is {int}.  */
6795
6796       outer = DECL_CONTEXT (templ);
6797       if (outer)
6798         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
6799       else if (current_template_parms)
6800         /* This is an argument of the current template, so we haven't set
6801            DECL_CONTEXT yet.  */
6802         outer = current_template_args ();
6803
6804       if (outer)
6805         arglist = add_to_template_args (outer, arglist);
6806
6807       arglist2 = coerce_template_parms (parmlist, arglist, templ,
6808                                         complain,
6809                                         /*require_all_args=*/true,
6810                                         /*use_default_args=*/true);
6811       if (arglist2 == error_mark_node
6812           || (!uses_template_parms (arglist2)
6813               && check_instantiated_args (templ, arglist2, complain)))
6814         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6815
6816       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
6817       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
6818     }
6819   else
6820     {
6821       tree template_type = TREE_TYPE (templ);
6822       tree gen_tmpl;
6823       tree type_decl;
6824       tree found = NULL_TREE;
6825       int arg_depth;
6826       int parm_depth;
6827       int is_dependent_type;
6828       int use_partial_inst_tmpl = false;
6829
6830       gen_tmpl = most_general_template (templ);
6831       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
6832       parm_depth = TMPL_PARMS_DEPTH (parmlist);
6833       arg_depth = TMPL_ARGS_DEPTH (arglist);
6834
6835       if (arg_depth == 1 && parm_depth > 1)
6836         {
6837           /* We've been given an incomplete set of template arguments.
6838              For example, given:
6839
6840                template <class T> struct S1 {
6841                  template <class U> struct S2 {};
6842                  template <class U> struct S2<U*> {};
6843                 };
6844
6845              we will be called with an ARGLIST of `U*', but the
6846              TEMPLATE will be `template <class T> template
6847              <class U> struct S1<T>::S2'.  We must fill in the missing
6848              arguments.  */
6849           arglist
6850             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
6851                                            arglist);
6852           arg_depth = TMPL_ARGS_DEPTH (arglist);
6853         }
6854
6855       /* Now we should have enough arguments.  */
6856       gcc_assert (parm_depth == arg_depth);
6857
6858       /* From here on, we're only interested in the most general
6859          template.  */
6860
6861       /* Calculate the BOUND_ARGS.  These will be the args that are
6862          actually tsubst'd into the definition to create the
6863          instantiation.  */
6864       if (parm_depth > 1)
6865         {
6866           /* We have multiple levels of arguments to coerce, at once.  */
6867           int i;
6868           int saved_depth = TMPL_ARGS_DEPTH (arglist);
6869
6870           tree bound_args = make_tree_vec (parm_depth);
6871
6872           for (i = saved_depth,
6873                  t = DECL_TEMPLATE_PARMS (gen_tmpl);
6874                i > 0 && t != NULL_TREE;
6875                --i, t = TREE_CHAIN (t))
6876             {
6877               tree a;
6878               if (i == saved_depth)
6879                 a = coerce_template_parms (TREE_VALUE (t),
6880                                            arglist, gen_tmpl,
6881                                            complain,
6882                                            /*require_all_args=*/true,
6883                                            /*use_default_args=*/true);
6884               else
6885                 /* Outer levels should have already been coerced.  */
6886                 a = TMPL_ARGS_LEVEL (arglist, i);
6887
6888               /* Don't process further if one of the levels fails.  */
6889               if (a == error_mark_node)
6890                 {
6891                   /* Restore the ARGLIST to its full size.  */
6892                   TREE_VEC_LENGTH (arglist) = saved_depth;
6893                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6894                 }
6895
6896               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
6897
6898               /* We temporarily reduce the length of the ARGLIST so
6899                  that coerce_template_parms will see only the arguments
6900                  corresponding to the template parameters it is
6901                  examining.  */
6902               TREE_VEC_LENGTH (arglist)--;
6903             }
6904
6905           /* Restore the ARGLIST to its full size.  */
6906           TREE_VEC_LENGTH (arglist) = saved_depth;
6907
6908           arglist = bound_args;
6909         }
6910       else
6911         arglist
6912           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
6913                                    INNERMOST_TEMPLATE_ARGS (arglist),
6914                                    gen_tmpl,
6915                                    complain,
6916                                    /*require_all_args=*/true,
6917                                    /*use_default_args=*/true);
6918
6919       if (arglist == error_mark_node)
6920         /* We were unable to bind the arguments.  */
6921         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6922
6923       /* In the scope of a template class, explicit references to the
6924          template class refer to the type of the template, not any
6925          instantiation of it.  For example, in:
6926
6927            template <class T> class C { void f(C<T>); }
6928
6929          the `C<T>' is just the same as `C'.  Outside of the
6930          class, however, such a reference is an instantiation.  */
6931       if ((entering_scope
6932            || !PRIMARY_TEMPLATE_P (gen_tmpl)
6933            || currently_open_class (template_type))
6934           /* comp_template_args is expensive, check it last.  */
6935           && comp_template_args (TYPE_TI_ARGS (template_type),
6936                                  arglist))
6937         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, template_type);
6938
6939       /* If we already have this specialization, return it.  */
6940       elt.tmpl = gen_tmpl;
6941       elt.args = arglist;
6942       hash = hash_specialization (&elt);
6943       entry = (spec_entry *) htab_find_with_hash (type_specializations,
6944                                                   &elt, hash);
6945
6946       if (entry)
6947         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, entry->spec);
6948
6949       is_dependent_type = uses_template_parms (arglist);
6950
6951       /* If the deduced arguments are invalid, then the binding
6952          failed.  */
6953       if (!is_dependent_type
6954           && check_instantiated_args (gen_tmpl,
6955                                       INNERMOST_TEMPLATE_ARGS (arglist),
6956                                       complain))
6957         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6958
6959       if (!is_dependent_type
6960           && !PRIMARY_TEMPLATE_P (gen_tmpl)
6961           && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
6962           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
6963         {
6964           found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
6965                                       DECL_NAME (gen_tmpl),
6966                                       /*tag_scope=*/ts_global);
6967           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
6968         }
6969
6970       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
6971                         complain, in_decl);
6972       if (!context)
6973         context = global_namespace;
6974
6975       /* Create the type.  */
6976       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
6977         {
6978           if (!is_dependent_type)
6979             {
6980               set_current_access_from_decl (TYPE_NAME (template_type));
6981               t = start_enum (TYPE_IDENTIFIER (template_type), NULL_TREE,
6982                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
6983                                       arglist, complain, in_decl),
6984                               SCOPED_ENUM_P (template_type), NULL);
6985             }
6986           else
6987             {
6988               /* We don't want to call start_enum for this type, since
6989                  the values for the enumeration constants may involve
6990                  template parameters.  And, no one should be interested
6991                  in the enumeration constants for such a type.  */
6992               t = cxx_make_type (ENUMERAL_TYPE);
6993               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
6994             }
6995           SET_OPAQUE_ENUM_P (t, OPAQUE_ENUM_P (template_type));
6996           ENUM_FIXED_UNDERLYING_TYPE_P (t)
6997             = ENUM_FIXED_UNDERLYING_TYPE_P (template_type);
6998         }
6999       else
7000         {
7001           t = make_class_type (TREE_CODE (template_type));
7002           CLASSTYPE_DECLARED_CLASS (t)
7003             = CLASSTYPE_DECLARED_CLASS (template_type);
7004           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
7005           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
7006
7007           /* A local class.  Make sure the decl gets registered properly.  */
7008           if (context == current_function_decl)
7009             pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
7010
7011           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
7012             /* This instantiation is another name for the primary
7013                template type. Set the TYPE_CANONICAL field
7014                appropriately. */
7015             TYPE_CANONICAL (t) = template_type;
7016           else if (any_template_arguments_need_structural_equality_p (arglist))
7017             /* Some of the template arguments require structural
7018                equality testing, so this template class requires
7019                structural equality testing. */
7020             SET_TYPE_STRUCTURAL_EQUALITY (t);
7021         }
7022
7023       /* If we called start_enum or pushtag above, this information
7024          will already be set up.  */
7025       if (!TYPE_NAME (t))
7026         {
7027           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
7028
7029           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
7030           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
7031           DECL_SOURCE_LOCATION (type_decl)
7032             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
7033         }
7034       else
7035         type_decl = TYPE_NAME (t);
7036
7037       TREE_PRIVATE (type_decl)
7038         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
7039       TREE_PROTECTED (type_decl)
7040         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
7041       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
7042         {
7043           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
7044           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
7045         }
7046
7047       /* Let's consider the explicit specialization of a member
7048          of a class template specialization that is implicitely instantiated,
7049          e.g.:
7050              template<class T>
7051              struct S
7052              {
7053                template<class U> struct M {}; //#0
7054              };
7055
7056              template<>
7057              template<>
7058              struct S<int>::M<char> //#1
7059              {
7060                int i;
7061              };
7062         [temp.expl.spec]/4 says this is valid.
7063
7064         In this case, when we write:
7065         S<int>::M<char> m;
7066
7067         M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
7068         the one of #0.
7069
7070         When we encounter #1, we want to store the partial instantiation
7071         of M (template<class T> S<int>::M<T>) in it's CLASSTYPE_TI_TEMPLATE.
7072
7073         For all cases other than this "explicit specialization of member of a
7074         class template", we just want to store the most general template into
7075         the CLASSTYPE_TI_TEMPLATE of M.
7076
7077         This case of "explicit specialization of member of a class template"
7078         only happens when:
7079         1/ the enclosing class is an instantiation of, and therefore not
7080         the same as, the context of the most general template, and
7081         2/ we aren't looking at the partial instantiation itself, i.e.
7082         the innermost arguments are not the same as the innermost parms of
7083         the most general template.
7084
7085         So it's only when 1/ and 2/ happens that we want to use the partial
7086         instantiation of the member template in lieu of its most general
7087         template.  */
7088
7089       if (PRIMARY_TEMPLATE_P (gen_tmpl)
7090           && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
7091           /* the enclosing class must be an instantiation...  */
7092           && CLASS_TYPE_P (context)
7093           && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
7094         {
7095           tree partial_inst_args;
7096           TREE_VEC_LENGTH (arglist)--;
7097           ++processing_template_decl;
7098           partial_inst_args =
7099             tsubst (INNERMOST_TEMPLATE_ARGS
7100                         (CLASSTYPE_TI_ARGS (TREE_TYPE (gen_tmpl))),
7101                     arglist, complain, NULL_TREE);
7102           --processing_template_decl;
7103           TREE_VEC_LENGTH (arglist)++;
7104           use_partial_inst_tmpl =
7105             /*...and we must not be looking at the partial instantiation
7106              itself. */
7107             !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
7108                                  partial_inst_args);
7109         }
7110
7111       if (!use_partial_inst_tmpl)
7112         /* This case is easy; there are no member templates involved.  */
7113         found = gen_tmpl;
7114       else
7115         {
7116           /* This is a full instantiation of a member template.  Find
7117              the partial instantiation of which this is an instance.  */
7118
7119           /* Temporarily reduce by one the number of levels in the ARGLIST
7120              so as to avoid comparing the last set of arguments.  */
7121           TREE_VEC_LENGTH (arglist)--;
7122           found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
7123           TREE_VEC_LENGTH (arglist)++;
7124           found = CLASSTYPE_TI_TEMPLATE (found);
7125         }
7126
7127       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
7128
7129       elt.spec = t;
7130       slot = (spec_entry **) htab_find_slot_with_hash (type_specializations,
7131                                                        &elt, hash, INSERT);
7132       *slot = ggc_alloc_spec_entry ();
7133       **slot = elt;
7134
7135       /* Note this use of the partial instantiation so we can check it
7136          later in maybe_process_partial_specialization.  */
7137       DECL_TEMPLATE_INSTANTIATIONS (templ)
7138         = tree_cons (arglist, t,
7139                      DECL_TEMPLATE_INSTANTIATIONS (templ));
7140
7141       if (TREE_CODE (t) == ENUMERAL_TYPE && !is_dependent_type)
7142         /* Now that the type has been registered on the instantiations
7143            list, we set up the enumerators.  Because the enumeration
7144            constants may involve the enumeration type itself, we make
7145            sure to register the type first, and then create the
7146            constants.  That way, doing tsubst_expr for the enumeration
7147            constants won't result in recursive calls here; we'll find
7148            the instantiation and exit above.  */
7149         tsubst_enum (template_type, t, arglist);
7150
7151       if (is_dependent_type)
7152         /* If the type makes use of template parameters, the
7153            code that generates debugging information will crash.  */
7154         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
7155
7156       /* Possibly limit visibility based on template args.  */
7157       TREE_PUBLIC (type_decl) = 1;
7158       determine_visibility (type_decl);
7159
7160       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
7161     }
7162   timevar_pop (TV_NAME_LOOKUP);
7163 }
7164 \f
7165 struct pair_fn_data
7166 {
7167   tree_fn_t fn;
7168   void *data;
7169   /* True when we should also visit template parameters that occur in
7170      non-deduced contexts.  */
7171   bool include_nondeduced_p;
7172   struct pointer_set_t *visited;
7173 };
7174
7175 /* Called from for_each_template_parm via walk_tree.  */
7176
7177 static tree
7178 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
7179 {
7180   tree t = *tp;
7181   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
7182   tree_fn_t fn = pfd->fn;
7183   void *data = pfd->data;
7184
7185   if (TYPE_P (t)
7186       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
7187       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
7188                                  pfd->include_nondeduced_p))
7189     return error_mark_node;
7190
7191   switch (TREE_CODE (t))
7192     {
7193     case RECORD_TYPE:
7194       if (TYPE_PTRMEMFUNC_P (t))
7195         break;
7196       /* Fall through.  */
7197
7198     case UNION_TYPE:
7199     case ENUMERAL_TYPE:
7200       if (!TYPE_TEMPLATE_INFO (t))
7201         *walk_subtrees = 0;
7202       else if (for_each_template_parm (TI_ARGS (TYPE_TEMPLATE_INFO (t)),
7203                                        fn, data, pfd->visited, 
7204                                        pfd->include_nondeduced_p))
7205         return error_mark_node;
7206       break;
7207
7208     case INTEGER_TYPE:
7209       if (for_each_template_parm (TYPE_MIN_VALUE (t),
7210                                   fn, data, pfd->visited, 
7211                                   pfd->include_nondeduced_p)
7212           || for_each_template_parm (TYPE_MAX_VALUE (t),
7213                                      fn, data, pfd->visited,
7214                                      pfd->include_nondeduced_p))
7215         return error_mark_node;
7216       break;
7217
7218     case METHOD_TYPE:
7219       /* Since we're not going to walk subtrees, we have to do this
7220          explicitly here.  */
7221       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
7222                                   pfd->visited, pfd->include_nondeduced_p))
7223         return error_mark_node;
7224       /* Fall through.  */
7225
7226     case FUNCTION_TYPE:
7227       /* Check the return type.  */
7228       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
7229                                   pfd->include_nondeduced_p))
7230         return error_mark_node;
7231
7232       /* Check the parameter types.  Since default arguments are not
7233          instantiated until they are needed, the TYPE_ARG_TYPES may
7234          contain expressions that involve template parameters.  But,
7235          no-one should be looking at them yet.  And, once they're
7236          instantiated, they don't contain template parameters, so
7237          there's no point in looking at them then, either.  */
7238       {
7239         tree parm;
7240
7241         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
7242           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
7243                                       pfd->visited, pfd->include_nondeduced_p))
7244             return error_mark_node;
7245
7246         /* Since we've already handled the TYPE_ARG_TYPES, we don't
7247            want walk_tree walking into them itself.  */
7248         *walk_subtrees = 0;
7249       }
7250       break;
7251
7252     case TYPEOF_TYPE:
7253       if (pfd->include_nondeduced_p
7254           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
7255                                      pfd->visited, 
7256                                      pfd->include_nondeduced_p))
7257         return error_mark_node;
7258       break;
7259
7260     case FUNCTION_DECL:
7261     case VAR_DECL:
7262       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
7263           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
7264                                      pfd->visited, pfd->include_nondeduced_p))
7265         return error_mark_node;
7266       /* Fall through.  */
7267
7268     case PARM_DECL:
7269     case CONST_DECL:
7270       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
7271           && for_each_template_parm (DECL_INITIAL (t), fn, data,
7272                                      pfd->visited, pfd->include_nondeduced_p))
7273         return error_mark_node;
7274       if (DECL_CONTEXT (t)
7275           && pfd->include_nondeduced_p
7276           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
7277                                      pfd->visited, pfd->include_nondeduced_p))
7278         return error_mark_node;
7279       break;
7280
7281     case BOUND_TEMPLATE_TEMPLATE_PARM:
7282       /* Record template parameters such as `T' inside `TT<T>'.  */
7283       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
7284                                   pfd->include_nondeduced_p))
7285         return error_mark_node;
7286       /* Fall through.  */
7287
7288     case TEMPLATE_TEMPLATE_PARM:
7289     case TEMPLATE_TYPE_PARM:
7290     case TEMPLATE_PARM_INDEX:
7291       if (fn && (*fn)(t, data))
7292         return error_mark_node;
7293       else if (!fn)
7294         return error_mark_node;
7295       break;
7296
7297     case TEMPLATE_DECL:
7298       /* A template template parameter is encountered.  */
7299       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
7300           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
7301                                      pfd->include_nondeduced_p))
7302         return error_mark_node;
7303
7304       /* Already substituted template template parameter */
7305       *walk_subtrees = 0;
7306       break;
7307
7308     case TYPENAME_TYPE:
7309       if (!fn
7310           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
7311                                      data, pfd->visited, 
7312                                      pfd->include_nondeduced_p))
7313         return error_mark_node;
7314       break;
7315
7316     case CONSTRUCTOR:
7317       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
7318           && pfd->include_nondeduced_p
7319           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
7320                                      (TREE_TYPE (t)), fn, data,
7321                                      pfd->visited, pfd->include_nondeduced_p))
7322         return error_mark_node;
7323       break;
7324
7325     case INDIRECT_REF:
7326     case COMPONENT_REF:
7327       /* If there's no type, then this thing must be some expression
7328          involving template parameters.  */
7329       if (!fn && !TREE_TYPE (t))
7330         return error_mark_node;
7331       break;
7332
7333     case MODOP_EXPR:
7334     case CAST_EXPR:
7335     case REINTERPRET_CAST_EXPR:
7336     case CONST_CAST_EXPR:
7337     case STATIC_CAST_EXPR:
7338     case DYNAMIC_CAST_EXPR:
7339     case ARROW_EXPR:
7340     case DOTSTAR_EXPR:
7341     case TYPEID_EXPR:
7342     case PSEUDO_DTOR_EXPR:
7343       if (!fn)
7344         return error_mark_node;
7345       break;
7346
7347     default:
7348       break;
7349     }
7350
7351   /* We didn't find any template parameters we liked.  */
7352   return NULL_TREE;
7353 }
7354
7355 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
7356    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
7357    call FN with the parameter and the DATA.
7358    If FN returns nonzero, the iteration is terminated, and
7359    for_each_template_parm returns 1.  Otherwise, the iteration
7360    continues.  If FN never returns a nonzero value, the value
7361    returned by for_each_template_parm is 0.  If FN is NULL, it is
7362    considered to be the function which always returns 1.
7363
7364    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
7365    parameters that occur in non-deduced contexts.  When false, only
7366    visits those template parameters that can be deduced.  */
7367
7368 static int
7369 for_each_template_parm (tree t, tree_fn_t fn, void* data,
7370                         struct pointer_set_t *visited,
7371                         bool include_nondeduced_p)
7372 {
7373   struct pair_fn_data pfd;
7374   int result;
7375
7376   /* Set up.  */
7377   pfd.fn = fn;
7378   pfd.data = data;
7379   pfd.include_nondeduced_p = include_nondeduced_p;
7380
7381   /* Walk the tree.  (Conceptually, we would like to walk without
7382      duplicates, but for_each_template_parm_r recursively calls
7383      for_each_template_parm, so we would need to reorganize a fair
7384      bit to use walk_tree_without_duplicates, so we keep our own
7385      visited list.)  */
7386   if (visited)
7387     pfd.visited = visited;
7388   else
7389     pfd.visited = pointer_set_create ();
7390   result = cp_walk_tree (&t,
7391                          for_each_template_parm_r,
7392                          &pfd,
7393                          pfd.visited) != NULL_TREE;
7394
7395   /* Clean up.  */
7396   if (!visited)
7397     {
7398       pointer_set_destroy (pfd.visited);
7399       pfd.visited = 0;
7400     }
7401
7402   return result;
7403 }
7404
7405 /* Returns true if T depends on any template parameter.  */
7406
7407 int
7408 uses_template_parms (tree t)
7409 {
7410   bool dependent_p;
7411   int saved_processing_template_decl;
7412
7413   saved_processing_template_decl = processing_template_decl;
7414   if (!saved_processing_template_decl)
7415     processing_template_decl = 1;
7416   if (TYPE_P (t))
7417     dependent_p = dependent_type_p (t);
7418   else if (TREE_CODE (t) == TREE_VEC)
7419     dependent_p = any_dependent_template_arguments_p (t);
7420   else if (TREE_CODE (t) == TREE_LIST)
7421     dependent_p = (uses_template_parms (TREE_VALUE (t))
7422                    || uses_template_parms (TREE_CHAIN (t)));
7423   else if (TREE_CODE (t) == TYPE_DECL)
7424     dependent_p = dependent_type_p (TREE_TYPE (t));
7425   else if (DECL_P (t)
7426            || EXPR_P (t)
7427            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
7428            || TREE_CODE (t) == OVERLOAD
7429            || TREE_CODE (t) == BASELINK
7430            || TREE_CODE (t) == IDENTIFIER_NODE
7431            || TREE_CODE (t) == TRAIT_EXPR
7432            || TREE_CODE (t) == CONSTRUCTOR
7433            || CONSTANT_CLASS_P (t))
7434     dependent_p = (type_dependent_expression_p (t)
7435                    || value_dependent_expression_p (t));
7436   else
7437     {
7438       gcc_assert (t == error_mark_node);
7439       dependent_p = false;
7440     }
7441
7442   processing_template_decl = saved_processing_template_decl;
7443
7444   return dependent_p;
7445 }
7446
7447 /* Returns true if T depends on any template parameter with level LEVEL.  */
7448
7449 int
7450 uses_template_parms_level (tree t, int level)
7451 {
7452   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
7453                                  /*include_nondeduced_p=*/true);
7454 }
7455
7456 static int tinst_depth;
7457 extern int max_tinst_depth;
7458 #ifdef GATHER_STATISTICS
7459 int depth_reached;
7460 #endif
7461 static int tinst_level_tick;
7462 static int last_template_error_tick;
7463
7464 /* We're starting to instantiate D; record the template instantiation context
7465    for diagnostics and to restore it later.  */
7466
7467 int
7468 push_tinst_level (tree d)
7469 {
7470   struct tinst_level *new_level;
7471
7472   if (tinst_depth >= max_tinst_depth)
7473     {
7474       /* If the instantiation in question still has unbound template parms,
7475          we don't really care if we can't instantiate it, so just return.
7476          This happens with base instantiation for implicit `typename'.  */
7477       if (uses_template_parms (d))
7478         return 0;
7479
7480       last_template_error_tick = tinst_level_tick;
7481       error ("template instantiation depth exceeds maximum of %d (use "
7482              "-ftemplate-depth= to increase the maximum) instantiating %qD",
7483              max_tinst_depth, d);
7484
7485       print_instantiation_context ();
7486
7487       return 0;
7488     }
7489
7490   new_level = ggc_alloc_tinst_level ();
7491   new_level->decl = d;
7492   new_level->locus = input_location;
7493   new_level->in_system_header_p = in_system_header;
7494   new_level->next = current_tinst_level;
7495   current_tinst_level = new_level;
7496
7497   ++tinst_depth;
7498 #ifdef GATHER_STATISTICS
7499   if (tinst_depth > depth_reached)
7500     depth_reached = tinst_depth;
7501 #endif
7502
7503   ++tinst_level_tick;
7504   return 1;
7505 }
7506
7507 /* We're done instantiating this template; return to the instantiation
7508    context.  */
7509
7510 void
7511 pop_tinst_level (void)
7512 {
7513   /* Restore the filename and line number stashed away when we started
7514      this instantiation.  */
7515   input_location = current_tinst_level->locus;
7516   current_tinst_level = current_tinst_level->next;
7517   --tinst_depth;
7518   ++tinst_level_tick;
7519 }
7520
7521 /* We're instantiating a deferred template; restore the template
7522    instantiation context in which the instantiation was requested, which
7523    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
7524
7525 static tree
7526 reopen_tinst_level (struct tinst_level *level)
7527 {
7528   struct tinst_level *t;
7529
7530   tinst_depth = 0;
7531   for (t = level; t; t = t->next)
7532     ++tinst_depth;
7533
7534   current_tinst_level = level;
7535   pop_tinst_level ();
7536   return level->decl;
7537 }
7538
7539 /* Returns the TINST_LEVEL which gives the original instantiation
7540    context.  */
7541
7542 struct tinst_level *
7543 outermost_tinst_level (void)
7544 {
7545   struct tinst_level *level = current_tinst_level;
7546   if (level)
7547     while (level->next)
7548       level = level->next;
7549   return level;
7550 }
7551
7552 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
7553
7554 bool
7555 parameter_of_template_p (tree parm, tree templ)
7556 {
7557   tree parms;
7558   int i;
7559
7560   if (!parm || !templ)
7561     return false;
7562
7563   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
7564   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7565
7566   parms = DECL_TEMPLATE_PARMS (templ);
7567   parms = INNERMOST_TEMPLATE_PARMS (parms);
7568
7569   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
7570     if (parm == TREE_VALUE (TREE_VEC_ELT (parms, i)))
7571       return true;
7572
7573   return false;
7574 }
7575
7576 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
7577    vector of template arguments, as for tsubst.
7578
7579    Returns an appropriate tsubst'd friend declaration.  */
7580
7581 static tree
7582 tsubst_friend_function (tree decl, tree args)
7583 {
7584   tree new_friend;
7585
7586   if (TREE_CODE (decl) == FUNCTION_DECL
7587       && DECL_TEMPLATE_INSTANTIATION (decl)
7588       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
7589     /* This was a friend declared with an explicit template
7590        argument list, e.g.:
7591
7592        friend void f<>(T);
7593
7594        to indicate that f was a template instantiation, not a new
7595        function declaration.  Now, we have to figure out what
7596        instantiation of what template.  */
7597     {
7598       tree template_id, arglist, fns;
7599       tree new_args;
7600       tree tmpl;
7601       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
7602
7603       /* Friend functions are looked up in the containing namespace scope.
7604          We must enter that scope, to avoid finding member functions of the
7605          current class with same name.  */
7606       push_nested_namespace (ns);
7607       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
7608                          tf_warning_or_error, NULL_TREE,
7609                          /*integral_constant_expression_p=*/false);
7610       pop_nested_namespace (ns);
7611       arglist = tsubst (DECL_TI_ARGS (decl), args,
7612                         tf_warning_or_error, NULL_TREE);
7613       template_id = lookup_template_function (fns, arglist);
7614
7615       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7616       tmpl = determine_specialization (template_id, new_friend,
7617                                        &new_args,
7618                                        /*need_member_template=*/0,
7619                                        TREE_VEC_LENGTH (args),
7620                                        tsk_none);
7621       return instantiate_template (tmpl, new_args, tf_error);
7622     }
7623
7624   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7625
7626   /* The NEW_FRIEND will look like an instantiation, to the
7627      compiler, but is not an instantiation from the point of view of
7628      the language.  For example, we might have had:
7629
7630      template <class T> struct S {
7631        template <class U> friend void f(T, U);
7632      };
7633
7634      Then, in S<int>, template <class U> void f(int, U) is not an
7635      instantiation of anything.  */
7636   if (new_friend == error_mark_node)
7637     return error_mark_node;
7638
7639   DECL_USE_TEMPLATE (new_friend) = 0;
7640   if (TREE_CODE (decl) == TEMPLATE_DECL)
7641     {
7642       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
7643       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
7644         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
7645     }
7646
7647   /* The mangled name for the NEW_FRIEND is incorrect.  The function
7648      is not a template instantiation and should not be mangled like
7649      one.  Therefore, we forget the mangling here; we'll recompute it
7650      later if we need it.  */
7651   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
7652     {
7653       SET_DECL_RTL (new_friend, NULL);
7654       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
7655     }
7656
7657   if (DECL_NAMESPACE_SCOPE_P (new_friend))
7658     {
7659       tree old_decl;
7660       tree new_friend_template_info;
7661       tree new_friend_result_template_info;
7662       tree ns;
7663       int  new_friend_is_defn;
7664
7665       /* We must save some information from NEW_FRIEND before calling
7666          duplicate decls since that function will free NEW_FRIEND if
7667          possible.  */
7668       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
7669       new_friend_is_defn =
7670             (DECL_INITIAL (DECL_TEMPLATE_RESULT
7671                            (template_for_substitution (new_friend)))
7672              != NULL_TREE);
7673       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
7674         {
7675           /* This declaration is a `primary' template.  */
7676           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
7677
7678           new_friend_result_template_info
7679             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
7680         }
7681       else
7682         new_friend_result_template_info = NULL_TREE;
7683
7684       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
7685       if (new_friend_is_defn)
7686         DECL_INITIAL (new_friend) = error_mark_node;
7687
7688       /* Inside pushdecl_namespace_level, we will push into the
7689          current namespace. However, the friend function should go
7690          into the namespace of the template.  */
7691       ns = decl_namespace_context (new_friend);
7692       push_nested_namespace (ns);
7693       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
7694       pop_nested_namespace (ns);
7695
7696       if (old_decl == error_mark_node)
7697         return error_mark_node;
7698
7699       if (old_decl != new_friend)
7700         {
7701           /* This new friend declaration matched an existing
7702              declaration.  For example, given:
7703
7704                template <class T> void f(T);
7705                template <class U> class C {
7706                  template <class T> friend void f(T) {}
7707                };
7708
7709              the friend declaration actually provides the definition
7710              of `f', once C has been instantiated for some type.  So,
7711              old_decl will be the out-of-class template declaration,
7712              while new_friend is the in-class definition.
7713
7714              But, if `f' was called before this point, the
7715              instantiation of `f' will have DECL_TI_ARGS corresponding
7716              to `T' but not to `U', references to which might appear
7717              in the definition of `f'.  Previously, the most general
7718              template for an instantiation of `f' was the out-of-class
7719              version; now it is the in-class version.  Therefore, we
7720              run through all specialization of `f', adding to their
7721              DECL_TI_ARGS appropriately.  In particular, they need a
7722              new set of outer arguments, corresponding to the
7723              arguments for this class instantiation.
7724
7725              The same situation can arise with something like this:
7726
7727                friend void f(int);
7728                template <class T> class C {
7729                  friend void f(T) {}
7730                };
7731
7732              when `C<int>' is instantiated.  Now, `f(int)' is defined
7733              in the class.  */
7734
7735           if (!new_friend_is_defn)
7736             /* On the other hand, if the in-class declaration does
7737                *not* provide a definition, then we don't want to alter
7738                existing definitions.  We can just leave everything
7739                alone.  */
7740             ;
7741           else
7742             {
7743               tree new_template = TI_TEMPLATE (new_friend_template_info);
7744               tree new_args = TI_ARGS (new_friend_template_info);
7745
7746               /* Overwrite whatever template info was there before, if
7747                  any, with the new template information pertaining to
7748                  the declaration.  */
7749               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
7750
7751               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
7752                 {
7753                   /* We should have called reregister_specialization in
7754                      duplicate_decls.  */
7755                   gcc_assert (retrieve_specialization (new_template,
7756                                                        new_args, 0)
7757                               == old_decl);
7758
7759                   /* Instantiate it if the global has already been used.  */
7760                   if (DECL_ODR_USED (old_decl))
7761                     instantiate_decl (old_decl, /*defer_ok=*/true,
7762                                       /*expl_inst_class_mem_p=*/false);
7763                 }
7764               else
7765                 {
7766                   tree t;
7767
7768                   /* Indicate that the old function template is a partial
7769                      instantiation.  */
7770                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
7771                     = new_friend_result_template_info;
7772
7773                   gcc_assert (new_template
7774                               == most_general_template (new_template));
7775                   gcc_assert (new_template != old_decl);
7776
7777                   /* Reassign any specializations already in the hash table
7778                      to the new more general template, and add the
7779                      additional template args.  */
7780                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
7781                        t != NULL_TREE;
7782                        t = TREE_CHAIN (t))
7783                     {
7784                       tree spec = TREE_VALUE (t);
7785                       spec_entry elt;
7786
7787                       elt.tmpl = old_decl;
7788                       elt.args = DECL_TI_ARGS (spec);
7789                       elt.spec = NULL_TREE;
7790
7791                       htab_remove_elt (decl_specializations, &elt);
7792
7793                       DECL_TI_ARGS (spec)
7794                         = add_outermost_template_args (new_args,
7795                                                        DECL_TI_ARGS (spec));
7796
7797                       register_specialization
7798                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
7799
7800                     }
7801                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
7802                 }
7803             }
7804
7805           /* The information from NEW_FRIEND has been merged into OLD_DECL
7806              by duplicate_decls.  */
7807           new_friend = old_decl;
7808         }
7809     }
7810   else
7811     {
7812       tree context = DECL_CONTEXT (new_friend);
7813       bool dependent_p;
7814
7815       /* In the code
7816            template <class T> class C {
7817              template <class U> friend void C1<U>::f (); // case 1
7818              friend void C2<T>::f ();                    // case 2
7819            };
7820          we only need to make sure CONTEXT is a complete type for
7821          case 2.  To distinguish between the two cases, we note that
7822          CONTEXT of case 1 remains dependent type after tsubst while
7823          this isn't true for case 2.  */
7824       ++processing_template_decl;
7825       dependent_p = dependent_type_p (context);
7826       --processing_template_decl;
7827
7828       if (!dependent_p
7829           && !complete_type_or_else (context, NULL_TREE))
7830         return error_mark_node;
7831
7832       if (COMPLETE_TYPE_P (context))
7833         {
7834           /* Check to see that the declaration is really present, and,
7835              possibly obtain an improved declaration.  */
7836           tree fn = check_classfn (context,
7837                                    new_friend, NULL_TREE);
7838
7839           if (fn)
7840             new_friend = fn;
7841         }
7842     }
7843
7844   return new_friend;
7845 }
7846
7847 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
7848    template arguments, as for tsubst.
7849
7850    Returns an appropriate tsubst'd friend type or error_mark_node on
7851    failure.  */
7852
7853 static tree
7854 tsubst_friend_class (tree friend_tmpl, tree args)
7855 {
7856   tree friend_type;
7857   tree tmpl;
7858   tree context;
7859
7860   context = CP_DECL_CONTEXT (friend_tmpl);
7861
7862   if (context != global_namespace)
7863     {
7864       if (TREE_CODE (context) == NAMESPACE_DECL)
7865         push_nested_namespace (context);
7866       else
7867         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
7868     }
7869
7870   /* Look for a class template declaration.  We look for hidden names
7871      because two friend declarations of the same template are the
7872      same.  For example, in:
7873
7874        struct A { 
7875          template <typename> friend class F;
7876        };
7877        template <typename> struct B { 
7878          template <typename> friend class F;
7879        };
7880
7881      both F templates are the same.  */
7882   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
7883                            /*block_p=*/true, 0, 
7884                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
7885
7886   /* But, if we don't find one, it might be because we're in a
7887      situation like this:
7888
7889        template <class T>
7890        struct S {
7891          template <class U>
7892          friend struct S;
7893        };
7894
7895      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
7896      for `S<int>', not the TEMPLATE_DECL.  */
7897   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
7898     {
7899       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
7900       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
7901     }
7902
7903   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
7904     {
7905       /* The friend template has already been declared.  Just
7906          check to see that the declarations match, and install any new
7907          default parameters.  We must tsubst the default parameters,
7908          of course.  We only need the innermost template parameters
7909          because that is all that redeclare_class_template will look
7910          at.  */
7911       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
7912           > TMPL_ARGS_DEPTH (args))
7913         {
7914           tree parms;
7915           location_t saved_input_location;
7916           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
7917                                          args, tf_warning_or_error);
7918
7919           saved_input_location = input_location;
7920           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
7921           redeclare_class_template (TREE_TYPE (tmpl), parms);
7922           input_location = saved_input_location;
7923           
7924         }
7925
7926       friend_type = TREE_TYPE (tmpl);
7927     }
7928   else
7929     {
7930       /* The friend template has not already been declared.  In this
7931          case, the instantiation of the template class will cause the
7932          injection of this template into the global scope.  */
7933       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
7934       if (tmpl == error_mark_node)
7935         return error_mark_node;
7936
7937       /* The new TMPL is not an instantiation of anything, so we
7938          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
7939          the new type because that is supposed to be the corresponding
7940          template decl, i.e., TMPL.  */
7941       DECL_USE_TEMPLATE (tmpl) = 0;
7942       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
7943       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
7944       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
7945         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
7946
7947       /* Inject this template into the global scope.  */
7948       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
7949     }
7950
7951   if (context != global_namespace)
7952     {
7953       if (TREE_CODE (context) == NAMESPACE_DECL)
7954         pop_nested_namespace (context);
7955       else
7956         pop_nested_class ();
7957     }
7958
7959   return friend_type;
7960 }
7961
7962 /* Returns zero if TYPE cannot be completed later due to circularity.
7963    Otherwise returns one.  */
7964
7965 static int
7966 can_complete_type_without_circularity (tree type)
7967 {
7968   if (type == NULL_TREE || type == error_mark_node)
7969     return 0;
7970   else if (COMPLETE_TYPE_P (type))
7971     return 1;
7972   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
7973     return can_complete_type_without_circularity (TREE_TYPE (type));
7974   else if (CLASS_TYPE_P (type)
7975            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
7976     return 0;
7977   else
7978     return 1;
7979 }
7980
7981 /* Apply any attributes which had to be deferred until instantiation
7982    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
7983    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
7984
7985 static void
7986 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
7987                                 tree args, tsubst_flags_t complain, tree in_decl)
7988 {
7989   tree last_dep = NULL_TREE;
7990   tree t;
7991   tree *p;
7992
7993   for (t = attributes; t; t = TREE_CHAIN (t))
7994     if (ATTR_IS_DEPENDENT (t))
7995       {
7996         last_dep = t;
7997         attributes = copy_list (attributes);
7998         break;
7999       }
8000
8001   if (DECL_P (*decl_p))
8002     {
8003       if (TREE_TYPE (*decl_p) == error_mark_node)
8004         return;
8005       p = &DECL_ATTRIBUTES (*decl_p);
8006     }
8007   else
8008     p = &TYPE_ATTRIBUTES (*decl_p);
8009
8010   if (last_dep)
8011     {
8012       tree late_attrs = NULL_TREE;
8013       tree *q = &late_attrs;
8014
8015       for (*p = attributes; *p; )
8016         {
8017           t = *p;
8018           if (ATTR_IS_DEPENDENT (t))
8019             {
8020               *p = TREE_CHAIN (t);
8021               TREE_CHAIN (t) = NULL_TREE;
8022               /* If the first attribute argument is an identifier, don't
8023                  pass it through tsubst.  Attributes like mode, format,
8024                  cleanup and several target specific attributes expect it
8025                  unmodified.  */
8026               if (TREE_VALUE (t)
8027                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
8028                   && TREE_VALUE (TREE_VALUE (t))
8029                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
8030                       == IDENTIFIER_NODE))
8031                 {
8032                   tree chain
8033                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
8034                                    in_decl,
8035                                    /*integral_constant_expression_p=*/false);
8036                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
8037                     TREE_VALUE (t)
8038                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
8039                                    chain);
8040                 }
8041               else
8042                 TREE_VALUE (t)
8043                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
8044                                  /*integral_constant_expression_p=*/false);
8045               *q = t;
8046               q = &TREE_CHAIN (t);
8047             }
8048           else
8049             p = &TREE_CHAIN (t);
8050         }
8051
8052       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
8053     }
8054 }
8055
8056 /* Perform (or defer) access check for typedefs that were referenced
8057    from within the template TMPL code.
8058    This is a subroutine of instantiate_template and instantiate_class_template.
8059    TMPL is the template to consider and TARGS is the list of arguments of
8060    that template.  */
8061
8062 static void
8063 perform_typedefs_access_check (tree tmpl, tree targs)
8064 {
8065   location_t saved_location;
8066   int i;
8067   qualified_typedef_usage_t *iter;
8068
8069   if (!tmpl
8070       || (!CLASS_TYPE_P (tmpl)
8071           && TREE_CODE (tmpl) != FUNCTION_DECL))
8072     return;
8073
8074   saved_location = input_location;
8075   FOR_EACH_VEC_ELT (qualified_typedef_usage_t,
8076                     get_types_needing_access_check (tmpl),
8077                     i, iter)
8078     {
8079       tree type_decl = iter->typedef_decl;
8080       tree type_scope = iter->context;
8081
8082       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
8083         continue;
8084
8085       if (uses_template_parms (type_decl))
8086         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
8087       if (uses_template_parms (type_scope))
8088         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
8089
8090       /* Make access check error messages point to the location
8091          of the use of the typedef.  */
8092       input_location = iter->locus;
8093       perform_or_defer_access_check (TYPE_BINFO (type_scope),
8094                                      type_decl, type_decl);
8095     }
8096     input_location = saved_location;
8097 }
8098
8099 tree
8100 instantiate_class_template (tree type)
8101 {
8102   tree templ, args, pattern, t, member;
8103   tree typedecl;
8104   tree pbinfo;
8105   tree base_list;
8106   unsigned int saved_maximum_field_alignment;
8107
8108   if (type == error_mark_node)
8109     return error_mark_node;
8110
8111   if (COMPLETE_OR_OPEN_TYPE_P (type)
8112       || uses_template_parms (type))
8113     return type;
8114
8115   /* Figure out which template is being instantiated.  */
8116   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
8117   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
8118
8119   /* Determine what specialization of the original template to
8120      instantiate.  */
8121   t = most_specialized_class (type, templ, tf_warning_or_error);
8122   if (t == error_mark_node)
8123     {
8124       TYPE_BEING_DEFINED (type) = 1;
8125       return error_mark_node;
8126     }
8127   else if (t)
8128     {
8129       /* This TYPE is actually an instantiation of a partial
8130          specialization.  We replace the innermost set of ARGS with
8131          the arguments appropriate for substitution.  For example,
8132          given:
8133
8134            template <class T> struct S {};
8135            template <class T> struct S<T*> {};
8136
8137          and supposing that we are instantiating S<int*>, ARGS will
8138          presently be {int*} -- but we need {int}.  */
8139       pattern = TREE_TYPE (t);
8140       args = TREE_PURPOSE (t);
8141     }
8142   else
8143     {
8144       pattern = TREE_TYPE (templ);
8145       args = CLASSTYPE_TI_ARGS (type);
8146     }
8147
8148   /* If the template we're instantiating is incomplete, then clearly
8149      there's nothing we can do.  */
8150   if (!COMPLETE_TYPE_P (pattern))
8151     return type;
8152
8153   /* If we've recursively instantiated too many templates, stop.  */
8154   if (! push_tinst_level (type))
8155     return type;
8156
8157   /* Now we're really doing the instantiation.  Mark the type as in
8158      the process of being defined.  */
8159   TYPE_BEING_DEFINED (type) = 1;
8160
8161   /* We may be in the middle of deferred access check.  Disable
8162      it now.  */
8163   push_deferring_access_checks (dk_no_deferred);
8164
8165   push_to_top_level ();
8166   /* Use #pragma pack from the template context.  */
8167   saved_maximum_field_alignment = maximum_field_alignment;
8168   maximum_field_alignment = TYPE_PRECISION (pattern);
8169
8170   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
8171
8172   /* Set the input location to the most specialized template definition.
8173      This is needed if tsubsting causes an error.  */
8174   typedecl = TYPE_MAIN_DECL (pattern);
8175   input_location = DECL_SOURCE_LOCATION (TYPE_NAME (type)) =
8176     DECL_SOURCE_LOCATION (typedecl);
8177
8178   TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
8179   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
8180   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
8181   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
8182   TYPE_HAS_COPY_ASSIGN (type) = TYPE_HAS_COPY_ASSIGN (pattern);
8183   TYPE_HAS_CONST_COPY_ASSIGN (type) = TYPE_HAS_CONST_COPY_ASSIGN (pattern);
8184   TYPE_HAS_COPY_CTOR (type) = TYPE_HAS_COPY_CTOR (pattern);
8185   TYPE_HAS_CONST_COPY_CTOR (type) = TYPE_HAS_CONST_COPY_CTOR (pattern);
8186   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
8187   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
8188   TYPE_PACKED (type) = TYPE_PACKED (pattern);
8189   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
8190   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
8191   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
8192   if (ANON_AGGR_TYPE_P (pattern))
8193     SET_ANON_AGGR_TYPE_P (type);
8194   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
8195     {
8196       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
8197       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
8198     }
8199
8200   pbinfo = TYPE_BINFO (pattern);
8201
8202   /* We should never instantiate a nested class before its enclosing
8203      class; we need to look up the nested class by name before we can
8204      instantiate it, and that lookup should instantiate the enclosing
8205      class.  */
8206   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
8207               || COMPLETE_OR_OPEN_TYPE_P (TYPE_CONTEXT (type)));
8208
8209   base_list = NULL_TREE;
8210   if (BINFO_N_BASE_BINFOS (pbinfo))
8211     {
8212       tree pbase_binfo;
8213       tree pushed_scope;
8214       int i;
8215
8216       /* We must enter the scope containing the type, as that is where
8217          the accessibility of types named in dependent bases are
8218          looked up from.  */
8219       pushed_scope = push_scope (CP_TYPE_CONTEXT (type));
8220
8221       /* Substitute into each of the bases to determine the actual
8222          basetypes.  */
8223       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
8224         {
8225           tree base;
8226           tree access = BINFO_BASE_ACCESS (pbinfo, i);
8227           tree expanded_bases = NULL_TREE;
8228           int idx, len = 1;
8229
8230           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
8231             {
8232               expanded_bases = 
8233                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
8234                                        args, tf_error, NULL_TREE);
8235               if (expanded_bases == error_mark_node)
8236                 continue;
8237
8238               len = TREE_VEC_LENGTH (expanded_bases);
8239             }
8240
8241           for (idx = 0; idx < len; idx++)
8242             {
8243               if (expanded_bases)
8244                 /* Extract the already-expanded base class.  */
8245                 base = TREE_VEC_ELT (expanded_bases, idx);
8246               else
8247                 /* Substitute to figure out the base class.  */
8248                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
8249                                NULL_TREE);
8250
8251               if (base == error_mark_node)
8252                 continue;
8253
8254               base_list = tree_cons (access, base, base_list);
8255               if (BINFO_VIRTUAL_P (pbase_binfo))
8256                 TREE_TYPE (base_list) = integer_type_node;
8257             }
8258         }
8259
8260       /* The list is now in reverse order; correct that.  */
8261       base_list = nreverse (base_list);
8262
8263       if (pushed_scope)
8264         pop_scope (pushed_scope);
8265     }
8266   /* Now call xref_basetypes to set up all the base-class
8267      information.  */
8268   xref_basetypes (type, base_list);
8269
8270   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
8271                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
8272                                   args, tf_error, NULL_TREE);
8273   fixup_attribute_variants (type);
8274
8275   /* Now that our base classes are set up, enter the scope of the
8276      class, so that name lookups into base classes, etc. will work
8277      correctly.  This is precisely analogous to what we do in
8278      begin_class_definition when defining an ordinary non-template
8279      class, except we also need to push the enclosing classes.  */
8280   push_nested_class (type);
8281
8282   /* Now members are processed in the order of declaration.  */
8283   for (member = CLASSTYPE_DECL_LIST (pattern);
8284        member; member = TREE_CHAIN (member))
8285     {
8286       tree t = TREE_VALUE (member);
8287
8288       if (TREE_PURPOSE (member))
8289         {
8290           if (TYPE_P (t))
8291             {
8292               /* Build new CLASSTYPE_NESTED_UTDS.  */
8293
8294               tree newtag;
8295               bool class_template_p;
8296
8297               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
8298                                   && TYPE_LANG_SPECIFIC (t)
8299                                   && CLASSTYPE_IS_TEMPLATE (t));
8300               /* If the member is a class template, then -- even after
8301                  substitution -- there may be dependent types in the
8302                  template argument list for the class.  We increment
8303                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
8304                  that function will assume that no types are dependent
8305                  when outside of a template.  */
8306               if (class_template_p)
8307                 ++processing_template_decl;
8308               newtag = tsubst (t, args, tf_error, NULL_TREE);
8309               if (class_template_p)
8310                 --processing_template_decl;
8311               if (newtag == error_mark_node)
8312                 continue;
8313
8314               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
8315                 {
8316                   tree name = TYPE_IDENTIFIER (t);
8317
8318                   if (class_template_p)
8319                     /* Unfortunately, lookup_template_class sets
8320                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
8321                        instantiation (i.e., for the type of a member
8322                        template class nested within a template class.)
8323                        This behavior is required for
8324                        maybe_process_partial_specialization to work
8325                        correctly, but is not accurate in this case;
8326                        the TAG is not an instantiation of anything.
8327                        (The corresponding TEMPLATE_DECL is an
8328                        instantiation, but the TYPE is not.) */
8329                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
8330
8331                   /* Now, we call pushtag to put this NEWTAG into the scope of
8332                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
8333                      pushtag calling push_template_decl.  We don't have to do
8334                      this for enums because it will already have been done in
8335                      tsubst_enum.  */
8336                   if (name)
8337                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
8338                   pushtag (name, newtag, /*tag_scope=*/ts_current);
8339                 }
8340             }
8341           else if (TREE_CODE (t) == FUNCTION_DECL
8342                    || DECL_FUNCTION_TEMPLATE_P (t))
8343             {
8344               /* Build new TYPE_METHODS.  */
8345               tree r;
8346
8347               if (TREE_CODE (t) == TEMPLATE_DECL)
8348                 ++processing_template_decl;
8349               r = tsubst (t, args, tf_error, NULL_TREE);
8350               if (TREE_CODE (t) == TEMPLATE_DECL)
8351                 --processing_template_decl;
8352               set_current_access_from_decl (r);
8353               finish_member_declaration (r);
8354             }
8355           else
8356             {
8357               /* Build new TYPE_FIELDS.  */
8358               if (TREE_CODE (t) == STATIC_ASSERT)
8359                 {
8360                   tree condition = 
8361                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
8362                                  tf_warning_or_error, NULL_TREE,
8363                                  /*integral_constant_expression_p=*/true);
8364                   finish_static_assert (condition,
8365                                         STATIC_ASSERT_MESSAGE (t), 
8366                                         STATIC_ASSERT_SOURCE_LOCATION (t),
8367                                         /*member_p=*/true);
8368                 }
8369               else if (TREE_CODE (t) != CONST_DECL)
8370                 {
8371                   tree r;
8372
8373                   /* The file and line for this declaration, to
8374                      assist in error message reporting.  Since we
8375                      called push_tinst_level above, we don't need to
8376                      restore these.  */
8377                   input_location = DECL_SOURCE_LOCATION (t);
8378
8379                   if (TREE_CODE (t) == TEMPLATE_DECL)
8380                     ++processing_template_decl;
8381                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
8382                   if (TREE_CODE (t) == TEMPLATE_DECL)
8383                     --processing_template_decl;
8384                   if (TREE_CODE (r) == VAR_DECL)
8385                     {
8386                       /* In [temp.inst]:
8387
8388                            [t]he initialization (and any associated
8389                            side-effects) of a static data member does
8390                            not occur unless the static data member is
8391                            itself used in a way that requires the
8392                            definition of the static data member to
8393                            exist.
8394
8395                          Therefore, we do not substitute into the
8396                          initialized for the static data member here.  */
8397                       finish_static_data_member_decl
8398                         (r,
8399                          /*init=*/NULL_TREE,
8400                          /*init_const_expr_p=*/false,
8401                          /*asmspec_tree=*/NULL_TREE,
8402                          /*flags=*/0);
8403                       if (DECL_INITIALIZED_IN_CLASS_P (r))
8404                         check_static_variable_definition (r, TREE_TYPE (r));
8405                     }
8406                   else if (TREE_CODE (r) == FIELD_DECL)
8407                     {
8408                       /* Determine whether R has a valid type and can be
8409                          completed later.  If R is invalid, then it is
8410                          replaced by error_mark_node so that it will not be
8411                          added to TYPE_FIELDS.  */
8412                       tree rtype = TREE_TYPE (r);
8413                       if (can_complete_type_without_circularity (rtype))
8414                         complete_type (rtype);
8415
8416                       if (!COMPLETE_TYPE_P (rtype))
8417                         {
8418                           cxx_incomplete_type_error (r, rtype);
8419                           r = error_mark_node;
8420                         }
8421                     }
8422
8423                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
8424                      such a thing will already have been added to the field
8425                      list by tsubst_enum in finish_member_declaration in the
8426                      CLASSTYPE_NESTED_UTDS case above.  */
8427                   if (!(TREE_CODE (r) == TYPE_DECL
8428                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
8429                         && DECL_ARTIFICIAL (r)))
8430                     {
8431                       set_current_access_from_decl (r);
8432                       finish_member_declaration (r);
8433                     }
8434                 }
8435             }
8436         }
8437       else
8438         {
8439           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
8440             {
8441               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
8442
8443               tree friend_type = t;
8444               bool adjust_processing_template_decl = false;
8445
8446               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8447                 {
8448                   /* template <class T> friend class C;  */
8449                   friend_type = tsubst_friend_class (friend_type, args);
8450                   adjust_processing_template_decl = true;
8451                 }
8452               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
8453                 {
8454                   /* template <class T> friend class C::D;  */
8455                   friend_type = tsubst (friend_type, args,
8456                                         tf_warning_or_error, NULL_TREE);
8457                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8458                     friend_type = TREE_TYPE (friend_type);
8459                   adjust_processing_template_decl = true;
8460                 }
8461               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
8462                 {
8463                   /* This could be either
8464
8465                        friend class T::C;
8466
8467                      when dependent_type_p is false or
8468
8469                        template <class U> friend class T::C;
8470
8471                      otherwise.  */
8472                   friend_type = tsubst (friend_type, args,
8473                                         tf_warning_or_error, NULL_TREE);
8474                   /* Bump processing_template_decl for correct
8475                      dependent_type_p calculation.  */
8476                   ++processing_template_decl;
8477                   if (dependent_type_p (friend_type))
8478                     adjust_processing_template_decl = true;
8479                   --processing_template_decl;
8480                 }
8481               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
8482                        && hidden_name_p (TYPE_NAME (friend_type)))
8483                 {
8484                   /* friend class C;
8485
8486                      where C hasn't been declared yet.  Let's lookup name
8487                      from namespace scope directly, bypassing any name that
8488                      come from dependent base class.  */
8489                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
8490
8491                   /* The call to xref_tag_from_type does injection for friend
8492                      classes.  */
8493                   push_nested_namespace (ns);
8494                   friend_type =
8495                     xref_tag_from_type (friend_type, NULL_TREE,
8496                                         /*tag_scope=*/ts_current);
8497                   pop_nested_namespace (ns);
8498                 }
8499               else if (uses_template_parms (friend_type))
8500                 /* friend class C<T>;  */
8501                 friend_type = tsubst (friend_type, args,
8502                                       tf_warning_or_error, NULL_TREE);
8503               /* Otherwise it's
8504
8505                    friend class C;
8506
8507                  where C is already declared or
8508
8509                    friend class C<int>;
8510
8511                  We don't have to do anything in these cases.  */
8512
8513               if (adjust_processing_template_decl)
8514                 /* Trick make_friend_class into realizing that the friend
8515                    we're adding is a template, not an ordinary class.  It's
8516                    important that we use make_friend_class since it will
8517                    perform some error-checking and output cross-reference
8518                    information.  */
8519                 ++processing_template_decl;
8520
8521               if (friend_type != error_mark_node)
8522                 make_friend_class (type, friend_type, /*complain=*/false);
8523
8524               if (adjust_processing_template_decl)
8525                 --processing_template_decl;
8526             }
8527           else
8528             {
8529               /* Build new DECL_FRIENDLIST.  */
8530               tree r;
8531
8532               /* The file and line for this declaration, to
8533                  assist in error message reporting.  Since we
8534                  called push_tinst_level above, we don't need to
8535                  restore these.  */
8536               input_location = DECL_SOURCE_LOCATION (t);
8537
8538               if (TREE_CODE (t) == TEMPLATE_DECL)
8539                 {
8540                   ++processing_template_decl;
8541                   push_deferring_access_checks (dk_no_check);
8542                 }
8543
8544               r = tsubst_friend_function (t, args);
8545               add_friend (type, r, /*complain=*/false);
8546               if (TREE_CODE (t) == TEMPLATE_DECL)
8547                 {
8548                   pop_deferring_access_checks ();
8549                   --processing_template_decl;
8550                 }
8551             }
8552         }
8553     }
8554
8555   /* Set the file and line number information to whatever is given for
8556      the class itself.  This puts error messages involving generated
8557      implicit functions at a predictable point, and the same point
8558      that would be used for non-template classes.  */
8559   input_location = DECL_SOURCE_LOCATION (typedecl);
8560
8561   unreverse_member_declarations (type);
8562   finish_struct_1 (type);
8563   TYPE_BEING_DEFINED (type) = 0;
8564
8565   /* We don't instantiate default arguments for member functions.  14.7.1:
8566
8567      The implicit instantiation of a class template specialization causes
8568      the implicit instantiation of the declarations, but not of the
8569      definitions or default arguments, of the class member functions,
8570      member classes, static data members and member templates....  */
8571
8572   /* Some typedefs referenced from within the template code need to be access
8573      checked at template instantiation time, i.e now. These types were
8574      added to the template at parsing time. Let's get those and perform
8575      the access checks then.  */
8576   perform_typedefs_access_check (pattern, args);
8577   perform_deferred_access_checks ();
8578   pop_nested_class ();
8579   maximum_field_alignment = saved_maximum_field_alignment;
8580   pop_from_top_level ();
8581   pop_deferring_access_checks ();
8582   pop_tinst_level ();
8583
8584   /* The vtable for a template class can be emitted in any translation
8585      unit in which the class is instantiated.  When there is no key
8586      method, however, finish_struct_1 will already have added TYPE to
8587      the keyed_classes list.  */
8588   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
8589     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
8590
8591   return type;
8592 }
8593
8594 static tree
8595 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8596 {
8597   tree r;
8598
8599   if (!t)
8600     r = t;
8601   else if (TYPE_P (t))
8602     r = tsubst (t, args, complain, in_decl);
8603   else
8604     {
8605       if (!(complain & tf_warning))
8606         ++c_inhibit_evaluation_warnings;
8607       r = tsubst_expr (t, args, complain, in_decl,
8608                        /*integral_constant_expression_p=*/true);
8609       if (!(complain & tf_warning))
8610         --c_inhibit_evaluation_warnings;
8611     }
8612   return r;
8613 }
8614
8615 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
8616    NONTYPE_ARGUMENT_PACK.  */
8617
8618 static tree
8619 make_fnparm_pack (tree spec_parm)
8620 {
8621   /* Collect all of the extra "packed" parameters into an
8622      argument pack.  */
8623   tree parmvec;
8624   tree parmtypevec;
8625   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
8626   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
8627   int i, len = list_length (spec_parm);
8628
8629   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
8630   parmvec = make_tree_vec (len);
8631   parmtypevec = make_tree_vec (len);
8632   for (i = 0; i < len; i++, spec_parm = DECL_CHAIN (spec_parm))
8633     {
8634       TREE_VEC_ELT (parmvec, i) = spec_parm;
8635       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
8636     }
8637
8638   /* Build the argument packs.  */
8639   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
8640   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
8641   TREE_TYPE (argpack) = argtypepack;
8642
8643   return argpack;
8644 }        
8645
8646 /* Substitute ARGS into T, which is an pack expansion
8647    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
8648    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
8649    (if only a partial substitution could be performed) or
8650    ERROR_MARK_NODE if there was an error.  */
8651 tree
8652 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
8653                        tree in_decl)
8654 {
8655   tree pattern;
8656   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
8657   int i, len = -1;
8658   tree result;
8659   int incomplete = 0;
8660   htab_t saved_local_specializations = NULL;
8661
8662   gcc_assert (PACK_EXPANSION_P (t));
8663   pattern = PACK_EXPANSION_PATTERN (t);
8664
8665   /* Determine the argument packs that will instantiate the parameter
8666      packs used in the expansion expression. While we're at it,
8667      compute the number of arguments to be expanded and make sure it
8668      is consistent.  */
8669   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
8670        pack = TREE_CHAIN (pack))
8671     {
8672       tree parm_pack = TREE_VALUE (pack);
8673       tree arg_pack = NULL_TREE;
8674       tree orig_arg = NULL_TREE;
8675
8676       if (TREE_CODE (parm_pack) == PARM_DECL)
8677         {
8678           if (!cp_unevaluated_operand)
8679             arg_pack = retrieve_local_specialization (parm_pack);
8680           else
8681             {
8682               /* We can't rely on local_specializations for a parameter
8683                  name used later in a function declaration (such as in a
8684                  late-specified return type).  Even if it exists, it might
8685                  have the wrong value for a recursive call.  Just make a
8686                  dummy decl, since it's only used for its type.  */
8687               arg_pack = tsubst_decl (parm_pack, args, complain);
8688               arg_pack = make_fnparm_pack (arg_pack);
8689             }
8690         }
8691       else
8692         {
8693           int level, idx, levels;
8694           template_parm_level_and_index (parm_pack, &level, &idx);
8695
8696           levels = TMPL_ARGS_DEPTH (args);
8697           if (level <= levels)
8698             arg_pack = TMPL_ARG (args, level, idx);
8699         }
8700
8701       orig_arg = arg_pack;
8702       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
8703         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
8704       
8705       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
8706         /* This can only happen if we forget to expand an argument
8707            pack somewhere else. Just return an error, silently.  */
8708         {
8709           result = make_tree_vec (1);
8710           TREE_VEC_ELT (result, 0) = error_mark_node;
8711           return result;
8712         }
8713
8714       if (arg_pack
8715           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
8716           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
8717         {
8718           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
8719           tree pattern = PACK_EXPANSION_PATTERN (expansion);
8720           if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
8721               || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
8722             /* The argument pack that the parameter maps to is just an
8723                expansion of the parameter itself, such as one would
8724                find in the implicit typedef of a class inside the
8725                class itself.  Consider this parameter "unsubstituted",
8726                so that we will maintain the outer pack expansion.  */
8727             arg_pack = NULL_TREE;
8728         }
8729           
8730       if (arg_pack)
8731         {
8732           int my_len = 
8733             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
8734
8735           /* It's all-or-nothing with incomplete argument packs.  */
8736           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8737             return error_mark_node;
8738           
8739           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8740             incomplete = 1;
8741
8742           if (len < 0)
8743             len = my_len;
8744           else if (len != my_len)
8745             {
8746               if (incomplete)
8747                 /* We got explicit args for some packs but not others;
8748                    do nothing now and try again after deduction.  */
8749                 return t;
8750               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
8751                 error ("mismatched argument pack lengths while expanding "
8752                        "%<%T%>",
8753                        pattern);
8754               else
8755                 error ("mismatched argument pack lengths while expanding "
8756                        "%<%E%>",
8757                        pattern);
8758               return error_mark_node;
8759             }
8760
8761           /* Keep track of the parameter packs and their corresponding
8762              argument packs.  */
8763           packs = tree_cons (parm_pack, arg_pack, packs);
8764           TREE_TYPE (packs) = orig_arg;
8765         }
8766       else
8767         /* We can't substitute for this parameter pack.  */
8768         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
8769                                          TREE_VALUE (pack),
8770                                          unsubstituted_packs);
8771     }
8772
8773   /* We cannot expand this expansion expression, because we don't have
8774      all of the argument packs we need. Substitute into the pattern
8775      and return a PACK_EXPANSION_*. The caller will need to deal with
8776      that.  */
8777   if (unsubstituted_packs)
8778     {
8779       tree new_pat;
8780       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8781         new_pat = tsubst_expr (pattern, args, complain, in_decl,
8782                                /*integral_constant_expression_p=*/false);
8783       else
8784         new_pat = tsubst (pattern, args, complain, in_decl);
8785       return make_pack_expansion (new_pat);
8786     }
8787
8788   /* We could not find any argument packs that work.  */
8789   if (len < 0)
8790     return error_mark_node;
8791
8792   if (cp_unevaluated_operand)
8793     {
8794       /* We're in a late-specified return type, so create our own local
8795          specializations table; the current table is either NULL or (in the
8796          case of recursive unification) might have bindings that we don't
8797          want to use or alter.  */
8798       saved_local_specializations = local_specializations;
8799       local_specializations = htab_create (37,
8800                                            hash_local_specialization,
8801                                            eq_local_specializations,
8802                                            NULL);
8803     }
8804
8805   /* For each argument in each argument pack, substitute into the
8806      pattern.  */
8807   result = make_tree_vec (len + incomplete);
8808   for (i = 0; i < len + incomplete; ++i)
8809     {
8810       /* For parameter pack, change the substitution of the parameter
8811          pack to the ith argument in its argument pack, then expand
8812          the pattern.  */
8813       for (pack = packs; pack; pack = TREE_CHAIN (pack))
8814         {
8815           tree parm = TREE_PURPOSE (pack);
8816
8817           if (TREE_CODE (parm) == PARM_DECL)
8818             {
8819               /* Select the Ith argument from the pack.  */
8820               tree arg = make_node (ARGUMENT_PACK_SELECT);
8821               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
8822               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
8823               mark_used (parm);
8824               register_local_specialization (arg, parm);
8825             }
8826           else
8827             {
8828               tree value = parm;
8829               int idx, level;
8830               template_parm_level_and_index (parm, &level, &idx);
8831               
8832               if (i < len) 
8833                 {
8834                   /* Select the Ith argument from the pack. */
8835                   value = make_node (ARGUMENT_PACK_SELECT);
8836                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
8837                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
8838                 }
8839
8840               /* Update the corresponding argument.  */
8841               TMPL_ARG (args, level, idx) = value;
8842             }
8843         }
8844
8845       /* Substitute into the PATTERN with the altered arguments.  */
8846       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8847         TREE_VEC_ELT (result, i) = 
8848           tsubst_expr (pattern, args, complain, in_decl,
8849                        /*integral_constant_expression_p=*/false);
8850       else
8851         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
8852
8853       if (i == len)
8854         /* When we have incomplete argument packs, the last "expanded"
8855            result is itself a pack expansion, which allows us
8856            to deduce more arguments.  */
8857         TREE_VEC_ELT (result, i) = 
8858           make_pack_expansion (TREE_VEC_ELT (result, i));
8859
8860       if (TREE_VEC_ELT (result, i) == error_mark_node)
8861         {
8862           result = error_mark_node;
8863           break;
8864         }
8865     }
8866
8867   /* Update ARGS to restore the substitution from parameter packs to
8868      their argument packs.  */
8869   for (pack = packs; pack; pack = TREE_CHAIN (pack))
8870     {
8871       tree parm = TREE_PURPOSE (pack);
8872
8873       if (TREE_CODE (parm) == PARM_DECL)
8874         register_local_specialization (TREE_TYPE (pack), parm);
8875       else
8876         {
8877           int idx, level;
8878           template_parm_level_and_index (parm, &level, &idx);
8879           
8880           /* Update the corresponding argument.  */
8881           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
8882             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
8883               TREE_TYPE (pack);
8884           else
8885             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
8886         }
8887     }
8888
8889   if (saved_local_specializations)
8890     {
8891       htab_delete (local_specializations);
8892       local_specializations = saved_local_specializations;
8893     }
8894   
8895   return result;
8896 }
8897
8898 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
8899    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
8900    parameter packs; all parms generated from a function parameter pack will
8901    have the same DECL_PARM_INDEX.  */
8902
8903 tree
8904 get_pattern_parm (tree parm, tree tmpl)
8905 {
8906   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
8907   tree patparm;
8908
8909   if (DECL_ARTIFICIAL (parm))
8910     {
8911       for (patparm = DECL_ARGUMENTS (pattern);
8912            patparm; patparm = DECL_CHAIN (patparm))
8913         if (DECL_ARTIFICIAL (patparm)
8914             && DECL_NAME (parm) == DECL_NAME (patparm))
8915           break;
8916     }
8917   else
8918     {
8919       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
8920       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
8921       gcc_assert (DECL_PARM_INDEX (patparm)
8922                   == DECL_PARM_INDEX (parm));
8923     }
8924
8925   return patparm;
8926 }
8927
8928 /* Substitute ARGS into the vector or list of template arguments T.  */
8929
8930 static tree
8931 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8932 {
8933   tree orig_t = t;
8934   int len = TREE_VEC_LENGTH (t);
8935   int need_new = 0, i, expanded_len_adjust = 0, out;
8936   tree *elts = XALLOCAVEC (tree, len);
8937
8938   for (i = 0; i < len; i++)
8939     {
8940       tree orig_arg = TREE_VEC_ELT (t, i);
8941       tree new_arg;
8942
8943       if (TREE_CODE (orig_arg) == TREE_VEC)
8944         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
8945       else if (PACK_EXPANSION_P (orig_arg))
8946         {
8947           /* Substitute into an expansion expression.  */
8948           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
8949
8950           if (TREE_CODE (new_arg) == TREE_VEC)
8951             /* Add to the expanded length adjustment the number of
8952                expanded arguments. We subtract one from this
8953                measurement, because the argument pack expression
8954                itself is already counted as 1 in
8955                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
8956                the argument pack is empty.  */
8957             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
8958         }
8959       else if (ARGUMENT_PACK_P (orig_arg))
8960         {
8961           /* Substitute into each of the arguments.  */
8962           new_arg = TYPE_P (orig_arg)
8963             ? cxx_make_type (TREE_CODE (orig_arg))
8964             : make_node (TREE_CODE (orig_arg));
8965           
8966           SET_ARGUMENT_PACK_ARGS (
8967             new_arg,
8968             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
8969                                   args, complain, in_decl));
8970
8971           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
8972             new_arg = error_mark_node;
8973
8974           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
8975             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
8976                                           complain, in_decl);
8977             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
8978
8979             if (TREE_TYPE (new_arg) == error_mark_node)
8980               new_arg = error_mark_node;
8981           }
8982         }
8983       else
8984         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
8985
8986       if (new_arg == error_mark_node)
8987         return error_mark_node;
8988
8989       elts[i] = new_arg;
8990       if (new_arg != orig_arg)
8991         need_new = 1;
8992     }
8993
8994   if (!need_new)
8995     return t;
8996
8997   /* Make space for the expanded arguments coming from template
8998      argument packs.  */
8999   t = make_tree_vec (len + expanded_len_adjust);
9000   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
9001      arguments for a member template.
9002      In that case each TREE_VEC in ORIG_T represents a level of template
9003      arguments, and ORIG_T won't carry any non defaulted argument count.
9004      It will rather be the nested TREE_VECs that will carry one.
9005      In other words, ORIG_T carries a non defaulted argument count only
9006      if it doesn't contain any nested TREE_VEC.  */
9007   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
9008     {
9009       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
9010       count += expanded_len_adjust;
9011       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
9012     }
9013   for (i = 0, out = 0; i < len; i++)
9014     {
9015       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
9016            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
9017           && TREE_CODE (elts[i]) == TREE_VEC)
9018         {
9019           int idx;
9020
9021           /* Now expand the template argument pack "in place".  */
9022           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
9023             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
9024         }
9025       else
9026         {
9027           TREE_VEC_ELT (t, out) = elts[i];
9028           out++;
9029         }
9030     }
9031
9032   return t;
9033 }
9034
9035 /* Return the result of substituting ARGS into the template parameters
9036    given by PARMS.  If there are m levels of ARGS and m + n levels of
9037    PARMS, then the result will contain n levels of PARMS.  For
9038    example, if PARMS is `template <class T> template <class U>
9039    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
9040    result will be `template <int*, double, class V>'.  */
9041
9042 static tree
9043 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
9044 {
9045   tree r = NULL_TREE;
9046   tree* new_parms;
9047
9048   /* When substituting into a template, we must set
9049      PROCESSING_TEMPLATE_DECL as the template parameters may be
9050      dependent if they are based on one-another, and the dependency
9051      predicates are short-circuit outside of templates.  */
9052   ++processing_template_decl;
9053
9054   for (new_parms = &r;
9055        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
9056        new_parms = &(TREE_CHAIN (*new_parms)),
9057          parms = TREE_CHAIN (parms))
9058     {
9059       tree new_vec =
9060         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
9061       int i;
9062
9063       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
9064         {
9065           tree tuple;
9066
9067           if (parms == error_mark_node)
9068             continue;
9069
9070           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
9071
9072           if (tuple == error_mark_node)
9073             continue;
9074
9075           TREE_VEC_ELT (new_vec, i) =
9076             tsubst_template_parm (tuple, args, complain);
9077         }
9078
9079       *new_parms =
9080         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
9081                              - TMPL_ARGS_DEPTH (args)),
9082                    new_vec, NULL_TREE);
9083     }
9084
9085   --processing_template_decl;
9086
9087   return r;
9088 }
9089
9090 /* Return the result of substituting ARGS into one template parameter
9091    given by T. T Must be a TREE_LIST which TREE_VALUE is the template
9092    parameter and which TREE_PURPOSE is the default argument of the
9093    template parameter.  */
9094
9095 static tree
9096 tsubst_template_parm (tree t, tree args, tsubst_flags_t complain)
9097 {
9098   tree default_value, parm_decl;
9099
9100   if (args == NULL_TREE
9101       || t == NULL_TREE
9102       || t == error_mark_node)
9103     return t;
9104
9105   gcc_assert (TREE_CODE (t) == TREE_LIST);
9106
9107   default_value = TREE_PURPOSE (t);
9108   parm_decl = TREE_VALUE (t);
9109
9110   parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
9111   if (TREE_CODE (parm_decl) == PARM_DECL
9112       && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
9113     parm_decl = error_mark_node;
9114   default_value = tsubst_template_arg (default_value, args,
9115                                        complain, NULL_TREE);
9116
9117   return build_tree_list (default_value, parm_decl);
9118 }
9119
9120 /* Substitute the ARGS into the indicated aggregate (or enumeration)
9121    type T.  If T is not an aggregate or enumeration type, it is
9122    handled as if by tsubst.  IN_DECL is as for tsubst.  If
9123    ENTERING_SCOPE is nonzero, T is the context for a template which
9124    we are presently tsubst'ing.  Return the substituted value.  */
9125
9126 static tree
9127 tsubst_aggr_type (tree t,
9128                   tree args,
9129                   tsubst_flags_t complain,
9130                   tree in_decl,
9131                   int entering_scope)
9132 {
9133   if (t == NULL_TREE)
9134     return NULL_TREE;
9135
9136   switch (TREE_CODE (t))
9137     {
9138     case RECORD_TYPE:
9139       if (TYPE_PTRMEMFUNC_P (t))
9140         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
9141
9142       /* Else fall through.  */
9143     case ENUMERAL_TYPE:
9144     case UNION_TYPE:
9145       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
9146         {
9147           tree argvec;
9148           tree context;
9149           tree r;
9150           int saved_unevaluated_operand;
9151           int saved_inhibit_evaluation_warnings;
9152
9153           /* In "sizeof(X<I>)" we need to evaluate "I".  */
9154           saved_unevaluated_operand = cp_unevaluated_operand;
9155           cp_unevaluated_operand = 0;
9156           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
9157           c_inhibit_evaluation_warnings = 0;
9158
9159           /* First, determine the context for the type we are looking
9160              up.  */
9161           context = TYPE_CONTEXT (t);
9162           if (context)
9163             {
9164               context = tsubst_aggr_type (context, args, complain,
9165                                           in_decl, /*entering_scope=*/1);
9166               /* If context is a nested class inside a class template,
9167                  it may still need to be instantiated (c++/33959).  */
9168               if (TYPE_P (context))
9169                 context = complete_type (context);
9170             }
9171
9172           /* Then, figure out what arguments are appropriate for the
9173              type we are trying to find.  For example, given:
9174
9175                template <class T> struct S;
9176                template <class T, class U> void f(T, U) { S<U> su; }
9177
9178              and supposing that we are instantiating f<int, double>,
9179              then our ARGS will be {int, double}, but, when looking up
9180              S we only want {double}.  */
9181           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
9182                                          complain, in_decl);
9183           if (argvec == error_mark_node)
9184             r = error_mark_node;
9185           else
9186             {
9187               r = lookup_template_class (t, argvec, in_decl, context,
9188                                          entering_scope, complain);
9189               r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
9190             }
9191
9192           cp_unevaluated_operand = saved_unevaluated_operand;
9193           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
9194
9195           return r;
9196         }
9197       else
9198         /* This is not a template type, so there's nothing to do.  */
9199         return t;
9200
9201     default:
9202       return tsubst (t, args, complain, in_decl);
9203     }
9204 }
9205
9206 /* Substitute into the default argument ARG (a default argument for
9207    FN), which has the indicated TYPE.  */
9208
9209 tree
9210 tsubst_default_argument (tree fn, tree type, tree arg)
9211 {
9212   tree saved_class_ptr = NULL_TREE;
9213   tree saved_class_ref = NULL_TREE;
9214
9215   /* This can happen in invalid code.  */
9216   if (TREE_CODE (arg) == DEFAULT_ARG)
9217     return arg;
9218
9219   /* This default argument came from a template.  Instantiate the
9220      default argument here, not in tsubst.  In the case of
9221      something like:
9222
9223        template <class T>
9224        struct S {
9225          static T t();
9226          void f(T = t());
9227        };
9228
9229      we must be careful to do name lookup in the scope of S<T>,
9230      rather than in the current class.  */
9231   push_access_scope (fn);
9232   /* The "this" pointer is not valid in a default argument.  */
9233   if (cfun)
9234     {
9235       saved_class_ptr = current_class_ptr;
9236       cp_function_chain->x_current_class_ptr = NULL_TREE;
9237       saved_class_ref = current_class_ref;
9238       cp_function_chain->x_current_class_ref = NULL_TREE;
9239     }
9240
9241   push_deferring_access_checks(dk_no_deferred);
9242   /* The default argument expression may cause implicitly defined
9243      member functions to be synthesized, which will result in garbage
9244      collection.  We must treat this situation as if we were within
9245      the body of function so as to avoid collecting live data on the
9246      stack.  */
9247   ++function_depth;
9248   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
9249                      tf_warning_or_error, NULL_TREE,
9250                      /*integral_constant_expression_p=*/false);
9251   --function_depth;
9252   pop_deferring_access_checks();
9253
9254   /* Restore the "this" pointer.  */
9255   if (cfun)
9256     {
9257       cp_function_chain->x_current_class_ptr = saved_class_ptr;
9258       cp_function_chain->x_current_class_ref = saved_class_ref;
9259     }
9260
9261   /* Make sure the default argument is reasonable.  */
9262   arg = check_default_argument (type, arg);
9263
9264   pop_access_scope (fn);
9265
9266   return arg;
9267 }
9268
9269 /* Substitute into all the default arguments for FN.  */
9270
9271 static void
9272 tsubst_default_arguments (tree fn)
9273 {
9274   tree arg;
9275   tree tmpl_args;
9276
9277   tmpl_args = DECL_TI_ARGS (fn);
9278
9279   /* If this function is not yet instantiated, we certainly don't need
9280      its default arguments.  */
9281   if (uses_template_parms (tmpl_args))
9282     return;
9283   /* Don't do this again for clones.  */
9284   if (DECL_CLONED_FUNCTION_P (fn))
9285     return;
9286
9287   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
9288        arg;
9289        arg = TREE_CHAIN (arg))
9290     if (TREE_PURPOSE (arg))
9291       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
9292                                                     TREE_VALUE (arg),
9293                                                     TREE_PURPOSE (arg));
9294 }
9295
9296 /* Substitute the ARGS into the T, which is a _DECL.  Return the
9297    result of the substitution.  Issue error and warning messages under
9298    control of COMPLAIN.  */
9299
9300 static tree
9301 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
9302 {
9303 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
9304   location_t saved_loc;
9305   tree r = NULL_TREE;
9306   tree in_decl = t;
9307   hashval_t hash = 0;
9308
9309   /* Set the filename and linenumber to improve error-reporting.  */
9310   saved_loc = input_location;
9311   input_location = DECL_SOURCE_LOCATION (t);
9312
9313   switch (TREE_CODE (t))
9314     {
9315     case TEMPLATE_DECL:
9316       {
9317         /* We can get here when processing a member function template,
9318            member class template, or template template parameter.  */
9319         tree decl = DECL_TEMPLATE_RESULT (t);
9320         tree spec;
9321         tree tmpl_args;
9322         tree full_args;
9323
9324         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
9325           {
9326             /* Template template parameter is treated here.  */
9327             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9328             if (new_type == error_mark_node)
9329               RETURN (error_mark_node);
9330
9331             r = copy_decl (t);
9332             DECL_CHAIN (r) = NULL_TREE;
9333             TREE_TYPE (r) = new_type;
9334             DECL_TEMPLATE_RESULT (r)
9335               = build_decl (DECL_SOURCE_LOCATION (decl),
9336                             TYPE_DECL, DECL_NAME (decl), new_type);
9337             DECL_TEMPLATE_PARMS (r)
9338               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
9339                                        complain);
9340             TYPE_NAME (new_type) = r;
9341             break;
9342           }
9343
9344         /* We might already have an instance of this template.
9345            The ARGS are for the surrounding class type, so the
9346            full args contain the tsubst'd args for the context,
9347            plus the innermost args from the template decl.  */
9348         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
9349           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
9350           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
9351         /* Because this is a template, the arguments will still be
9352            dependent, even after substitution.  If
9353            PROCESSING_TEMPLATE_DECL is not set, the dependency
9354            predicates will short-circuit.  */
9355         ++processing_template_decl;
9356         full_args = tsubst_template_args (tmpl_args, args,
9357                                           complain, in_decl);
9358         --processing_template_decl;
9359         if (full_args == error_mark_node)
9360           RETURN (error_mark_node);
9361
9362         /* If this is a default template template argument,
9363            tsubst might not have changed anything.  */
9364         if (full_args == tmpl_args)
9365           RETURN (t);
9366
9367         hash = hash_tmpl_and_args (t, full_args);
9368         spec = retrieve_specialization (t, full_args, hash);
9369         if (spec != NULL_TREE)
9370           {
9371             r = spec;
9372             break;
9373           }
9374
9375         /* Make a new template decl.  It will be similar to the
9376            original, but will record the current template arguments.
9377            We also create a new function declaration, which is just
9378            like the old one, but points to this new template, rather
9379            than the old one.  */
9380         r = copy_decl (t);
9381         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
9382         DECL_CHAIN (r) = NULL_TREE;
9383
9384         DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
9385
9386         if (TREE_CODE (decl) == TYPE_DECL)
9387           {
9388             tree new_type;
9389             ++processing_template_decl;
9390             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9391             --processing_template_decl;
9392             if (new_type == error_mark_node)
9393               RETURN (error_mark_node);
9394
9395             TREE_TYPE (r) = new_type;
9396             CLASSTYPE_TI_TEMPLATE (new_type) = r;
9397             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
9398             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
9399             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
9400           }
9401         else
9402           {
9403             tree new_decl;
9404             ++processing_template_decl;
9405             new_decl = tsubst (decl, args, complain, in_decl);
9406             --processing_template_decl;
9407             if (new_decl == error_mark_node)
9408               RETURN (error_mark_node);
9409
9410             DECL_TEMPLATE_RESULT (r) = new_decl;
9411             DECL_TI_TEMPLATE (new_decl) = r;
9412             TREE_TYPE (r) = TREE_TYPE (new_decl);
9413             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
9414             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
9415           }
9416
9417         SET_DECL_IMPLICIT_INSTANTIATION (r);
9418         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
9419         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
9420
9421         /* The template parameters for this new template are all the
9422            template parameters for the old template, except the
9423            outermost level of parameters.  */
9424         DECL_TEMPLATE_PARMS (r)
9425           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
9426                                    complain);
9427
9428         if (PRIMARY_TEMPLATE_P (t))
9429           DECL_PRIMARY_TEMPLATE (r) = r;
9430
9431         if (TREE_CODE (decl) != TYPE_DECL)
9432           /* Record this non-type partial instantiation.  */
9433           register_specialization (r, t,
9434                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
9435                                    false, hash);
9436       }
9437       break;
9438
9439     case FUNCTION_DECL:
9440       {
9441         tree ctx;
9442         tree argvec = NULL_TREE;
9443         tree *friends;
9444         tree gen_tmpl;
9445         tree type;
9446         int member;
9447         int args_depth;
9448         int parms_depth;
9449
9450         /* Nobody should be tsubst'ing into non-template functions.  */
9451         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
9452
9453         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
9454           {
9455             tree spec;
9456             bool dependent_p;
9457
9458             /* If T is not dependent, just return it.  We have to
9459                increment PROCESSING_TEMPLATE_DECL because
9460                value_dependent_expression_p assumes that nothing is
9461                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
9462             ++processing_template_decl;
9463             dependent_p = value_dependent_expression_p (t);
9464             --processing_template_decl;
9465             if (!dependent_p)
9466               RETURN (t);
9467
9468             /* Calculate the most general template of which R is a
9469                specialization, and the complete set of arguments used to
9470                specialize R.  */
9471             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
9472             argvec = tsubst_template_args (DECL_TI_ARGS
9473                                           (DECL_TEMPLATE_RESULT
9474                                                  (DECL_TI_TEMPLATE (t))),
9475                                            args, complain, in_decl);
9476
9477             /* Check to see if we already have this specialization.  */
9478             hash = hash_tmpl_and_args (gen_tmpl, argvec);
9479             spec = retrieve_specialization (gen_tmpl, argvec, hash);
9480
9481             if (spec)
9482               {
9483                 r = spec;
9484                 break;
9485               }
9486
9487             /* We can see more levels of arguments than parameters if
9488                there was a specialization of a member template, like
9489                this:
9490
9491                  template <class T> struct S { template <class U> void f(); }
9492                  template <> template <class U> void S<int>::f(U);
9493
9494                Here, we'll be substituting into the specialization,
9495                because that's where we can find the code we actually
9496                want to generate, but we'll have enough arguments for
9497                the most general template.
9498
9499                We also deal with the peculiar case:
9500
9501                  template <class T> struct S {
9502                    template <class U> friend void f();
9503                  };
9504                  template <class U> void f() {}
9505                  template S<int>;
9506                  template void f<double>();
9507
9508                Here, the ARGS for the instantiation of will be {int,
9509                double}.  But, we only need as many ARGS as there are
9510                levels of template parameters in CODE_PATTERN.  We are
9511                careful not to get fooled into reducing the ARGS in
9512                situations like:
9513
9514                  template <class T> struct S { template <class U> void f(U); }
9515                  template <class T> template <> void S<T>::f(int) {}
9516
9517                which we can spot because the pattern will be a
9518                specialization in this case.  */
9519             args_depth = TMPL_ARGS_DEPTH (args);
9520             parms_depth =
9521               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
9522             if (args_depth > parms_depth
9523                 && !DECL_TEMPLATE_SPECIALIZATION (t))
9524               args = get_innermost_template_args (args, parms_depth);
9525           }
9526         else
9527           {
9528             /* This special case arises when we have something like this:
9529
9530                  template <class T> struct S {
9531                    friend void f<int>(int, double);
9532                  };
9533
9534                Here, the DECL_TI_TEMPLATE for the friend declaration
9535                will be an IDENTIFIER_NODE.  We are being called from
9536                tsubst_friend_function, and we want only to create a
9537                new decl (R) with appropriate types so that we can call
9538                determine_specialization.  */
9539             gen_tmpl = NULL_TREE;
9540           }
9541
9542         if (DECL_CLASS_SCOPE_P (t))
9543           {
9544             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
9545               member = 2;
9546             else
9547               member = 1;
9548             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
9549                                     complain, t, /*entering_scope=*/1);
9550           }
9551         else
9552           {
9553             member = 0;
9554             ctx = DECL_CONTEXT (t);
9555           }
9556         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9557         if (type == error_mark_node)
9558           RETURN (error_mark_node);
9559
9560         /* We do NOT check for matching decls pushed separately at this
9561            point, as they may not represent instantiations of this
9562            template, and in any case are considered separate under the
9563            discrete model.  */
9564         r = copy_decl (t);
9565         DECL_USE_TEMPLATE (r) = 0;
9566         TREE_TYPE (r) = type;
9567         /* Clear out the mangled name and RTL for the instantiation.  */
9568         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9569         SET_DECL_RTL (r, NULL);
9570         /* Leave DECL_INITIAL set on deleted instantiations.  */
9571         if (!DECL_DELETED_FN (r))
9572           DECL_INITIAL (r) = NULL_TREE;
9573         DECL_CONTEXT (r) = ctx;
9574
9575         if (member && DECL_CONV_FN_P (r))
9576           /* Type-conversion operator.  Reconstruct the name, in
9577              case it's the name of one of the template's parameters.  */
9578           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
9579
9580         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
9581                                      complain, t);
9582         DECL_RESULT (r) = NULL_TREE;
9583
9584         TREE_STATIC (r) = 0;
9585         TREE_PUBLIC (r) = TREE_PUBLIC (t);
9586         DECL_EXTERNAL (r) = 1;
9587         /* If this is an instantiation of a function with internal
9588            linkage, we already know what object file linkage will be
9589            assigned to the instantiation.  */
9590         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
9591         DECL_DEFER_OUTPUT (r) = 0;
9592         DECL_CHAIN (r) = NULL_TREE;
9593         DECL_PENDING_INLINE_INFO (r) = 0;
9594         DECL_PENDING_INLINE_P (r) = 0;
9595         DECL_SAVED_TREE (r) = NULL_TREE;
9596         DECL_STRUCT_FUNCTION (r) = NULL;
9597         TREE_USED (r) = 0;
9598         /* We'll re-clone as appropriate in instantiate_template.  */
9599         DECL_CLONED_FUNCTION (r) = NULL_TREE;
9600
9601         /* If we aren't complaining now, return on error before we register
9602            the specialization so that we'll complain eventually.  */
9603         if ((complain & tf_error) == 0
9604             && IDENTIFIER_OPNAME_P (DECL_NAME (r))
9605             && !grok_op_properties (r, /*complain=*/false))
9606           RETURN (error_mark_node);
9607
9608         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
9609            this in the special friend case mentioned above where
9610            GEN_TMPL is NULL.  */
9611         if (gen_tmpl)
9612           {
9613             DECL_TEMPLATE_INFO (r)
9614               = build_template_info (gen_tmpl, argvec);
9615             SET_DECL_IMPLICIT_INSTANTIATION (r);
9616             register_specialization (r, gen_tmpl, argvec, false, hash);
9617
9618             /* We're not supposed to instantiate default arguments
9619                until they are called, for a template.  But, for a
9620                declaration like:
9621
9622                  template <class T> void f ()
9623                  { extern void g(int i = T()); }
9624
9625                we should do the substitution when the template is
9626                instantiated.  We handle the member function case in
9627                instantiate_class_template since the default arguments
9628                might refer to other members of the class.  */
9629             if (!member
9630                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
9631                 && !uses_template_parms (argvec))
9632               tsubst_default_arguments (r);
9633           }
9634         else
9635           DECL_TEMPLATE_INFO (r) = NULL_TREE;
9636
9637         /* Copy the list of befriending classes.  */
9638         for (friends = &DECL_BEFRIENDING_CLASSES (r);
9639              *friends;
9640              friends = &TREE_CHAIN (*friends))
9641           {
9642             *friends = copy_node (*friends);
9643             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
9644                                             args, complain,
9645                                             in_decl);
9646           }
9647
9648         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
9649           {
9650             maybe_retrofit_in_chrg (r);
9651             if (DECL_CONSTRUCTOR_P (r))
9652               grok_ctor_properties (ctx, r);
9653             /* If this is an instantiation of a member template, clone it.
9654                If it isn't, that'll be handled by
9655                clone_constructors_and_destructors.  */
9656             if (PRIMARY_TEMPLATE_P (gen_tmpl))
9657               clone_function_decl (r, /*update_method_vec_p=*/0);
9658           }
9659         else if ((complain & tf_error) != 0
9660                  && IDENTIFIER_OPNAME_P (DECL_NAME (r))
9661                  && !grok_op_properties (r, /*complain=*/true))
9662           RETURN (error_mark_node);
9663
9664         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
9665           SET_DECL_FRIEND_CONTEXT (r,
9666                                    tsubst (DECL_FRIEND_CONTEXT (t),
9667                                             args, complain, in_decl));
9668
9669         /* Possibly limit visibility based on template args.  */
9670         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
9671         if (DECL_VISIBILITY_SPECIFIED (t))
9672           {
9673             DECL_VISIBILITY_SPECIFIED (r) = 0;
9674             DECL_ATTRIBUTES (r)
9675               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
9676           }
9677         determine_visibility (r);
9678         if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
9679             && !processing_template_decl)
9680           defaulted_late_check (r);
9681
9682         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9683                                         args, complain, in_decl);
9684       }
9685       break;
9686
9687     case PARM_DECL:
9688       {
9689         tree type = NULL_TREE;
9690         int i, len = 1;
9691         tree expanded_types = NULL_TREE;
9692         tree prev_r = NULL_TREE;
9693         tree first_r = NULL_TREE;
9694
9695         if (FUNCTION_PARAMETER_PACK_P (t))
9696           {
9697             /* If there is a local specialization that isn't a
9698                parameter pack, it means that we're doing a "simple"
9699                substitution from inside tsubst_pack_expansion. Just
9700                return the local specialization (which will be a single
9701                parm).  */
9702             tree spec = retrieve_local_specialization (t);
9703             if (spec 
9704                 && TREE_CODE (spec) == PARM_DECL
9705                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
9706               RETURN (spec);
9707
9708             /* Expand the TYPE_PACK_EXPANSION that provides the types for
9709                the parameters in this function parameter pack.  */
9710             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
9711                                                     complain, in_decl);
9712             if (TREE_CODE (expanded_types) == TREE_VEC)
9713               {
9714                 len = TREE_VEC_LENGTH (expanded_types);
9715
9716                 /* Zero-length parameter packs are boring. Just substitute
9717                    into the chain.  */
9718                 if (len == 0)
9719                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
9720                                   TREE_CHAIN (t)));
9721               }
9722             else
9723               {
9724                 /* All we did was update the type. Make a note of that.  */
9725                 type = expanded_types;
9726                 expanded_types = NULL_TREE;
9727               }
9728           }
9729
9730         /* Loop through all of the parameter's we'll build. When T is
9731            a function parameter pack, LEN is the number of expanded
9732            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
9733         r = NULL_TREE;
9734         for (i = 0; i < len; ++i)
9735           {
9736             prev_r = r;
9737             r = copy_node (t);
9738             if (DECL_TEMPLATE_PARM_P (t))
9739               SET_DECL_TEMPLATE_PARM_P (r);
9740
9741             /* An argument of a function parameter pack is not a parameter
9742                pack.  */
9743             FUNCTION_PARAMETER_PACK_P (r) = false;
9744
9745             if (expanded_types)
9746               /* We're on the Ith parameter of the function parameter
9747                  pack.  */
9748               {
9749                 /* Get the Ith type.  */
9750                 type = TREE_VEC_ELT (expanded_types, i);
9751
9752                 if (DECL_NAME (r))
9753                   /* Rename the parameter to include the index.  */
9754                   DECL_NAME (r) =
9755                     make_ith_pack_parameter_name (DECL_NAME (r), i);
9756               }
9757             else if (!type)
9758               /* We're dealing with a normal parameter.  */
9759               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9760
9761             type = type_decays_to (type);
9762             TREE_TYPE (r) = type;
9763             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9764
9765             if (DECL_INITIAL (r))
9766               {
9767                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
9768                   DECL_INITIAL (r) = TREE_TYPE (r);
9769                 else
9770                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
9771                                              complain, in_decl);
9772               }
9773
9774             DECL_CONTEXT (r) = NULL_TREE;
9775
9776             if (!DECL_TEMPLATE_PARM_P (r))
9777               DECL_ARG_TYPE (r) = type_passed_as (type);
9778
9779             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9780                                             args, complain, in_decl);
9781
9782             /* Keep track of the first new parameter we
9783                generate. That's what will be returned to the
9784                caller.  */
9785             if (!first_r)
9786               first_r = r;
9787
9788             /* Build a proper chain of parameters when substituting
9789                into a function parameter pack.  */
9790             if (prev_r)
9791               DECL_CHAIN (prev_r) = r;
9792           }
9793
9794         if (DECL_CHAIN (t))
9795           DECL_CHAIN (r) = tsubst (DECL_CHAIN (t), args,
9796                                    complain, DECL_CHAIN (t));
9797
9798         /* FIRST_R contains the start of the chain we've built.  */
9799         r = first_r;
9800       }
9801       break;
9802
9803     case FIELD_DECL:
9804       {
9805         tree type;
9806
9807         r = copy_decl (t);
9808         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9809         if (type == error_mark_node)
9810           RETURN (error_mark_node);
9811         TREE_TYPE (r) = type;
9812         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9813
9814         /* DECL_INITIAL gives the number of bits in a bit-field.  */
9815         DECL_INITIAL (r)
9816           = tsubst_expr (DECL_INITIAL (t), args,
9817                          complain, in_decl,
9818                          /*integral_constant_expression_p=*/true);
9819         /* We don't have to set DECL_CONTEXT here; it is set by
9820            finish_member_declaration.  */
9821         DECL_CHAIN (r) = NULL_TREE;
9822         if (VOID_TYPE_P (type))
9823           error ("instantiation of %q+D as type %qT", r, type);
9824
9825         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9826                                         args, complain, in_decl);
9827       }
9828       break;
9829
9830     case USING_DECL:
9831       /* We reach here only for member using decls.  */
9832       if (DECL_DEPENDENT_P (t))
9833         {
9834           r = do_class_using_decl
9835             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
9836              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
9837           if (!r)
9838             r = error_mark_node;
9839           else
9840             {
9841               TREE_PROTECTED (r) = TREE_PROTECTED (t);
9842               TREE_PRIVATE (r) = TREE_PRIVATE (t);
9843             }
9844         }
9845       else
9846         {
9847           r = copy_node (t);
9848           DECL_CHAIN (r) = NULL_TREE;
9849         }
9850       break;
9851
9852     case TYPE_DECL:
9853     case VAR_DECL:
9854       {
9855         tree argvec = NULL_TREE;
9856         tree gen_tmpl = NULL_TREE;
9857         tree spec;
9858         tree tmpl = NULL_TREE;
9859         tree ctx;
9860         tree type = NULL_TREE;
9861         bool local_p;
9862
9863         if (TREE_CODE (t) == TYPE_DECL
9864             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
9865           {
9866             /* If this is the canonical decl, we don't have to
9867                mess with instantiations, and often we can't (for
9868                typename, template type parms and such).  Note that
9869                TYPE_NAME is not correct for the above test if
9870                we've copied the type for a typedef.  */
9871             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9872             if (type == error_mark_node)
9873               RETURN (error_mark_node);
9874             r = TYPE_NAME (type);
9875             break;
9876           }
9877
9878         /* Check to see if we already have the specialization we
9879            need.  */
9880         spec = NULL_TREE;
9881         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
9882           {
9883             /* T is a static data member or namespace-scope entity.
9884                We have to substitute into namespace-scope variables
9885                (even though such entities are never templates) because
9886                of cases like:
9887                
9888                  template <class T> void f() { extern T t; }
9889
9890                where the entity referenced is not known until
9891                instantiation time.  */
9892             local_p = false;
9893             ctx = DECL_CONTEXT (t);
9894             if (DECL_CLASS_SCOPE_P (t))
9895               {
9896                 ctx = tsubst_aggr_type (ctx, args,
9897                                         complain,
9898                                         in_decl, /*entering_scope=*/1);
9899                 /* If CTX is unchanged, then T is in fact the
9900                    specialization we want.  That situation occurs when
9901                    referencing a static data member within in its own
9902                    class.  We can use pointer equality, rather than
9903                    same_type_p, because DECL_CONTEXT is always
9904                    canonical.  */
9905                 if (ctx == DECL_CONTEXT (t))
9906                   spec = t;
9907               }
9908
9909             if (!spec)
9910               {
9911                 tmpl = DECL_TI_TEMPLATE (t);
9912                 gen_tmpl = most_general_template (tmpl);
9913                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
9914                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
9915                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
9916               }
9917           }
9918         else
9919           {
9920             /* A local variable.  */
9921             local_p = true;
9922             /* Subsequent calls to pushdecl will fill this in.  */
9923             ctx = NULL_TREE;
9924             spec = retrieve_local_specialization (t);
9925           }
9926         /* If we already have the specialization we need, there is
9927            nothing more to do.  */ 
9928         if (spec)
9929           {
9930             r = spec;
9931             break;
9932           }
9933
9934         /* Create a new node for the specialization we need.  */
9935         r = copy_decl (t);
9936         if (type == NULL_TREE)
9937           {
9938             if (is_typedef_decl (t))
9939               type = DECL_ORIGINAL_TYPE (t);
9940             else
9941               type = TREE_TYPE (t);
9942             if (TREE_CODE (t) == VAR_DECL && VAR_HAD_UNKNOWN_BOUND (t))
9943               type = strip_array_domain (type);
9944             type = tsubst (type, args, complain, in_decl);
9945           }
9946         if (TREE_CODE (r) == VAR_DECL)
9947           {
9948             /* Even if the original location is out of scope, the
9949                newly substituted one is not.  */
9950             DECL_DEAD_FOR_LOCAL (r) = 0;
9951             DECL_INITIALIZED_P (r) = 0;
9952             DECL_TEMPLATE_INSTANTIATED (r) = 0;
9953             if (type == error_mark_node)
9954               RETURN (error_mark_node);
9955             if (TREE_CODE (type) == FUNCTION_TYPE)
9956               {
9957                 /* It may seem that this case cannot occur, since:
9958
9959                      typedef void f();
9960                      void g() { f x; }
9961
9962                    declares a function, not a variable.  However:
9963       
9964                      typedef void f();
9965                      template <typename T> void g() { T t; }
9966                      template void g<f>();
9967
9968                    is an attempt to declare a variable with function
9969                    type.  */
9970                 error ("variable %qD has function type",
9971                        /* R is not yet sufficiently initialized, so we
9972                           just use its name.  */
9973                        DECL_NAME (r));
9974                 RETURN (error_mark_node);
9975               }
9976             type = complete_type (type);
9977             /* Wait until cp_finish_decl to set this again, to handle
9978                circular dependency (template/instantiate6.C). */
9979             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r) = 0;
9980             type = check_var_type (DECL_NAME (r), type);
9981
9982             if (DECL_HAS_VALUE_EXPR_P (t))
9983               {
9984                 tree ve = DECL_VALUE_EXPR (t);
9985                 ve = tsubst_expr (ve, args, complain, in_decl,
9986                                   /*constant_expression_p=*/false);
9987                 SET_DECL_VALUE_EXPR (r, ve);
9988               }
9989           }
9990         else if (DECL_SELF_REFERENCE_P (t))
9991           SET_DECL_SELF_REFERENCE_P (r);
9992         TREE_TYPE (r) = type;
9993         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9994         DECL_CONTEXT (r) = ctx;
9995         /* Clear out the mangled name and RTL for the instantiation.  */
9996         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9997         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9998           SET_DECL_RTL (r, NULL);
9999         /* The initializer must not be expanded until it is required;
10000            see [temp.inst].  */
10001         DECL_INITIAL (r) = NULL_TREE;
10002         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
10003           SET_DECL_RTL (r, NULL);
10004         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
10005         if (TREE_CODE (r) == VAR_DECL)
10006           {
10007             /* Possibly limit visibility based on template args.  */
10008             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
10009             if (DECL_VISIBILITY_SPECIFIED (t))
10010               {
10011                 DECL_VISIBILITY_SPECIFIED (r) = 0;
10012                 DECL_ATTRIBUTES (r)
10013                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
10014               }
10015             determine_visibility (r);
10016           }
10017
10018         if (!local_p)
10019           {
10020             /* A static data member declaration is always marked
10021                external when it is declared in-class, even if an
10022                initializer is present.  We mimic the non-template
10023                processing here.  */
10024             DECL_EXTERNAL (r) = 1;
10025
10026             register_specialization (r, gen_tmpl, argvec, false, hash);
10027             DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
10028             SET_DECL_IMPLICIT_INSTANTIATION (r);
10029           }
10030         else if (cp_unevaluated_operand)
10031           {
10032             /* We're substituting this var in a decltype outside of its
10033                scope, such as for a lambda return type.  Don't add it to
10034                local_specializations, do perform auto deduction.  */
10035             tree auto_node = type_uses_auto (type);
10036             tree init
10037               = tsubst_expr (DECL_INITIAL (t), args, complain, in_decl,
10038                              /*constant_expression_p=*/false);
10039
10040             if (auto_node && init)
10041               {
10042                 init = resolve_nondeduced_context (init);
10043                 if (describable_type (init))
10044                   {
10045                     type = do_auto_deduction (type, init, auto_node);
10046                     TREE_TYPE (r) = type;
10047                   }
10048               }
10049           }
10050         else
10051           register_local_specialization (r, t);
10052
10053         DECL_CHAIN (r) = NULL_TREE;
10054
10055         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
10056                                         /*flags=*/0,
10057                                         args, complain, in_decl);
10058
10059         /* Preserve a typedef that names a type.  */
10060         if (is_typedef_decl (r))
10061           {
10062             DECL_ORIGINAL_TYPE (r) = NULL_TREE;
10063             set_underlying_type (r);
10064           }
10065
10066         layout_decl (r, 0);
10067       }
10068       break;
10069
10070     default:
10071       gcc_unreachable ();
10072     }
10073 #undef RETURN
10074
10075  out:
10076   /* Restore the file and line information.  */
10077   input_location = saved_loc;
10078
10079   return r;
10080 }
10081
10082 /* Substitute into the ARG_TYPES of a function type.  */
10083
10084 static tree
10085 tsubst_arg_types (tree arg_types,
10086                   tree args,
10087                   tsubst_flags_t complain,
10088                   tree in_decl)
10089 {
10090   tree remaining_arg_types;
10091   tree type = NULL_TREE;
10092   int i = 1;
10093   tree expanded_args = NULL_TREE;
10094   tree default_arg;
10095
10096   if (!arg_types || arg_types == void_list_node)
10097     return arg_types;
10098
10099   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
10100                                           args, complain, in_decl);
10101   if (remaining_arg_types == error_mark_node)
10102     return error_mark_node;
10103
10104   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
10105     {
10106       /* For a pack expansion, perform substitution on the
10107          entire expression. Later on, we'll handle the arguments
10108          one-by-one.  */
10109       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
10110                                             args, complain, in_decl);
10111
10112       if (TREE_CODE (expanded_args) == TREE_VEC)
10113         /* So that we'll spin through the parameters, one by one.  */
10114         i = TREE_VEC_LENGTH (expanded_args);
10115       else
10116         {
10117           /* We only partially substituted into the parameter
10118              pack. Our type is TYPE_PACK_EXPANSION.  */
10119           type = expanded_args;
10120           expanded_args = NULL_TREE;
10121         }
10122     }
10123
10124   while (i > 0) {
10125     --i;
10126     
10127     if (expanded_args)
10128       type = TREE_VEC_ELT (expanded_args, i);
10129     else if (!type)
10130       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
10131
10132     if (type == error_mark_node)
10133       return error_mark_node;
10134     if (VOID_TYPE_P (type))
10135       {
10136         if (complain & tf_error)
10137           {
10138             error ("invalid parameter type %qT", type);
10139             if (in_decl)
10140               error ("in declaration %q+D", in_decl);
10141           }
10142         return error_mark_node;
10143     }
10144     
10145     /* Do array-to-pointer, function-to-pointer conversion, and ignore
10146        top-level qualifiers as required.  */
10147     type = TYPE_MAIN_VARIANT (type_decays_to (type));
10148
10149     /* We do not substitute into default arguments here.  The standard
10150        mandates that they be instantiated only when needed, which is
10151        done in build_over_call.  */
10152     default_arg = TREE_PURPOSE (arg_types);
10153
10154     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
10155       {
10156         /* We've instantiated a template before its default arguments
10157            have been parsed.  This can happen for a nested template
10158            class, and is not an error unless we require the default
10159            argument in a call of this function.  */
10160         remaining_arg_types = 
10161           tree_cons (default_arg, type, remaining_arg_types);
10162         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
10163                        remaining_arg_types);
10164       }
10165     else
10166       remaining_arg_types = 
10167         hash_tree_cons (default_arg, type, remaining_arg_types);
10168   }
10169         
10170   return remaining_arg_types;
10171 }
10172
10173 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
10174    *not* handle the exception-specification for FNTYPE, because the
10175    initial substitution of explicitly provided template parameters
10176    during argument deduction forbids substitution into the
10177    exception-specification:
10178
10179      [temp.deduct]
10180
10181      All references in the function type of the function template to  the
10182      corresponding template parameters are replaced by the specified tem-
10183      plate argument values.  If a substitution in a template parameter or
10184      in  the function type of the function template results in an invalid
10185      type, type deduction fails.  [Note: The equivalent  substitution  in
10186      exception specifications is done only when the function is instanti-
10187      ated, at which point a program is  ill-formed  if  the  substitution
10188      results in an invalid type.]  */
10189
10190 static tree
10191 tsubst_function_type (tree t,
10192                       tree args,
10193                       tsubst_flags_t complain,
10194                       tree in_decl)
10195 {
10196   tree return_type;
10197   tree arg_types;
10198   tree fntype;
10199
10200   /* The TYPE_CONTEXT is not used for function/method types.  */
10201   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
10202
10203   /* Substitute the return type.  */
10204   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
10205   if (return_type == error_mark_node)
10206     return error_mark_node;
10207   /* The standard does not presently indicate that creation of a
10208      function type with an invalid return type is a deduction failure.
10209      However, that is clearly analogous to creating an array of "void"
10210      or a reference to a reference.  This is core issue #486.  */
10211   if (TREE_CODE (return_type) == ARRAY_TYPE
10212       || TREE_CODE (return_type) == FUNCTION_TYPE)
10213     {
10214       if (complain & tf_error)
10215         {
10216           if (TREE_CODE (return_type) == ARRAY_TYPE)
10217             error ("function returning an array");
10218           else
10219             error ("function returning a function");
10220         }
10221       return error_mark_node;
10222     }
10223
10224   /* Substitute the argument types.  */
10225   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
10226                                 complain, in_decl);
10227   if (arg_types == error_mark_node)
10228     return error_mark_node;
10229
10230   /* Construct a new type node and return it.  */
10231   if (TREE_CODE (t) == FUNCTION_TYPE)
10232     {
10233       fntype = build_function_type (return_type, arg_types);
10234       fntype = apply_memfn_quals (fntype, type_memfn_quals (t));
10235     }
10236   else
10237     {
10238       tree r = TREE_TYPE (TREE_VALUE (arg_types));
10239       if (! 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 function of non-class type %qT",
10250                       r);
10251           return error_mark_node;
10252         }
10253
10254       fntype = build_method_type_directly (r, return_type,
10255                                            TREE_CHAIN (arg_types));
10256     }
10257   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
10258
10259   return fntype;
10260 }
10261
10262 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
10263    ARGS into that specification, and return the substituted
10264    specification.  If there is no specification, return NULL_TREE.  */
10265
10266 static tree
10267 tsubst_exception_specification (tree fntype,
10268                                 tree args,
10269                                 tsubst_flags_t complain,
10270                                 tree in_decl)
10271 {
10272   tree specs;
10273   tree new_specs;
10274
10275   specs = TYPE_RAISES_EXCEPTIONS (fntype);
10276   new_specs = NULL_TREE;
10277   if (specs && TREE_PURPOSE (specs))
10278     {
10279       /* A noexcept-specifier.  */
10280       new_specs = tsubst_copy_and_build
10281         (TREE_PURPOSE (specs), args, complain, in_decl, /*function_p=*/false,
10282          /*integral_constant_expression_p=*/true);
10283       new_specs = build_noexcept_spec (new_specs, complain);
10284     }
10285   else if (specs)
10286     {
10287       if (! TREE_VALUE (specs))
10288         new_specs = specs;
10289       else
10290         while (specs)
10291           {
10292             tree spec;
10293             int i, len = 1;
10294             tree expanded_specs = NULL_TREE;
10295
10296             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
10297               {
10298                 /* Expand the pack expansion type.  */
10299                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
10300                                                        args, complain,
10301                                                        in_decl);
10302
10303                 if (expanded_specs == error_mark_node)
10304                   return error_mark_node;
10305                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
10306                   len = TREE_VEC_LENGTH (expanded_specs);
10307                 else
10308                   {
10309                     /* We're substituting into a member template, so
10310                        we got a TYPE_PACK_EXPANSION back.  Add that
10311                        expansion and move on.  */
10312                     gcc_assert (TREE_CODE (expanded_specs) 
10313                                 == TYPE_PACK_EXPANSION);
10314                     new_specs = add_exception_specifier (new_specs,
10315                                                          expanded_specs,
10316                                                          complain);
10317                     specs = TREE_CHAIN (specs);
10318                     continue;
10319                   }
10320               }
10321
10322             for (i = 0; i < len; ++i)
10323               {
10324                 if (expanded_specs)
10325                   spec = TREE_VEC_ELT (expanded_specs, i);
10326                 else
10327                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
10328                 if (spec == error_mark_node)
10329                   return spec;
10330                 new_specs = add_exception_specifier (new_specs, spec, 
10331                                                      complain);
10332               }
10333
10334             specs = TREE_CHAIN (specs);
10335           }
10336     }
10337   return new_specs;
10338 }
10339
10340 /* Take the tree structure T and replace template parameters used
10341    therein with the argument vector ARGS.  IN_DECL is an associated
10342    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
10343    Issue error and warning messages under control of COMPLAIN.  Note
10344    that we must be relatively non-tolerant of extensions here, in
10345    order to preserve conformance; if we allow substitutions that
10346    should not be allowed, we may allow argument deductions that should
10347    not succeed, and therefore report ambiguous overload situations
10348    where there are none.  In theory, we could allow the substitution,
10349    but indicate that it should have failed, and allow our caller to
10350    make sure that the right thing happens, but we don't try to do this
10351    yet.
10352
10353    This function is used for dealing with types, decls and the like;
10354    for expressions, use tsubst_expr or tsubst_copy.  */
10355
10356 tree
10357 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10358 {
10359   enum tree_code code;
10360   tree type, r;
10361
10362   if (t == NULL_TREE || t == error_mark_node
10363       || t == integer_type_node
10364       || t == void_type_node
10365       || t == char_type_node
10366       || t == unknown_type_node
10367       || TREE_CODE (t) == NAMESPACE_DECL
10368       || TREE_CODE (t) == TRANSLATION_UNIT_DECL)
10369     return t;
10370
10371   if (DECL_P (t))
10372     return tsubst_decl (t, args, complain);
10373
10374   if (args == NULL_TREE)
10375     return t;
10376
10377   code = TREE_CODE (t);
10378
10379   if (code == IDENTIFIER_NODE)
10380     type = IDENTIFIER_TYPE_VALUE (t);
10381   else
10382     type = TREE_TYPE (t);
10383
10384   gcc_assert (type != unknown_type_node);
10385
10386   /* Reuse typedefs.  We need to do this to handle dependent attributes,
10387      such as attribute aligned.  */
10388   if (TYPE_P (t)
10389       && typedef_variant_p (t))
10390     {
10391       tree decl = TYPE_NAME (t);
10392       
10393       if (DECL_CLASS_SCOPE_P (decl)
10394           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
10395           && uses_template_parms (DECL_CONTEXT (decl)))
10396         {
10397           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
10398           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
10399           r = retrieve_specialization (tmpl, gen_args, 0);
10400         }
10401       else if (DECL_FUNCTION_SCOPE_P (decl)
10402                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
10403                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
10404         r = retrieve_local_specialization (decl);
10405       else
10406         /* The typedef is from a non-template context.  */
10407         return t;
10408
10409       if (r)
10410         {
10411           r = TREE_TYPE (r);
10412           r = cp_build_qualified_type_real
10413             (r, cp_type_quals (t) | cp_type_quals (r),
10414              complain | tf_ignore_bad_quals);
10415           return r;
10416         }
10417       /* Else we must be instantiating the typedef, so fall through.  */
10418     }
10419
10420   if (type
10421       && code != TYPENAME_TYPE
10422       && code != TEMPLATE_TYPE_PARM
10423       && code != IDENTIFIER_NODE
10424       && code != FUNCTION_TYPE
10425       && code != METHOD_TYPE)
10426     type = tsubst (type, args, complain, in_decl);
10427   if (type == error_mark_node)
10428     return error_mark_node;
10429
10430   switch (code)
10431     {
10432     case RECORD_TYPE:
10433     case UNION_TYPE:
10434     case ENUMERAL_TYPE:
10435       return tsubst_aggr_type (t, args, complain, in_decl,
10436                                /*entering_scope=*/0);
10437
10438     case ERROR_MARK:
10439     case IDENTIFIER_NODE:
10440     case VOID_TYPE:
10441     case REAL_TYPE:
10442     case COMPLEX_TYPE:
10443     case VECTOR_TYPE:
10444     case BOOLEAN_TYPE:
10445     case NULLPTR_TYPE:
10446     case LANG_TYPE:
10447       return t;
10448
10449     case INTEGER_TYPE:
10450       if (t == integer_type_node)
10451         return t;
10452
10453       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
10454           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
10455         return t;
10456
10457       {
10458         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
10459
10460         max = tsubst_expr (omax, args, complain, in_decl,
10461                            /*integral_constant_expression_p=*/false);
10462
10463         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
10464            needed.  */
10465         if (TREE_CODE (max) == NOP_EXPR
10466             && TREE_SIDE_EFFECTS (omax)
10467             && !TREE_TYPE (max))
10468           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
10469
10470         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
10471            with TREE_SIDE_EFFECTS that indicates this is not an integral
10472            constant expression.  */
10473         if (processing_template_decl
10474             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
10475           {
10476             gcc_assert (TREE_CODE (max) == NOP_EXPR);
10477             TREE_SIDE_EFFECTS (max) = 1;
10478           }
10479
10480         return compute_array_index_type (NULL_TREE, max, complain);
10481       }
10482
10483     case TEMPLATE_TYPE_PARM:
10484     case TEMPLATE_TEMPLATE_PARM:
10485     case BOUND_TEMPLATE_TEMPLATE_PARM:
10486     case TEMPLATE_PARM_INDEX:
10487       {
10488         int idx;
10489         int level;
10490         int levels;
10491         tree arg = NULL_TREE;
10492
10493         r = NULL_TREE;
10494
10495         gcc_assert (TREE_VEC_LENGTH (args) > 0);
10496         template_parm_level_and_index (t, &level, &idx); 
10497
10498         levels = TMPL_ARGS_DEPTH (args);
10499         if (level <= levels)
10500           {
10501             arg = TMPL_ARG (args, level, idx);
10502
10503             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
10504               /* See through ARGUMENT_PACK_SELECT arguments. */
10505               arg = ARGUMENT_PACK_SELECT_ARG (arg);
10506           }
10507
10508         if (arg == error_mark_node)
10509           return error_mark_node;
10510         else if (arg != NULL_TREE)
10511           {
10512             if (ARGUMENT_PACK_P (arg))
10513               /* If ARG is an argument pack, we don't actually want to
10514                  perform a substitution here, because substitutions
10515                  for argument packs are only done
10516                  element-by-element. We can get to this point when
10517                  substituting the type of a non-type template
10518                  parameter pack, when that type actually contains
10519                  template parameter packs from an outer template, e.g.,
10520
10521                  template<typename... Types> struct A {
10522                    template<Types... Values> struct B { };
10523                  };  */
10524               return t;
10525
10526             if (code == TEMPLATE_TYPE_PARM)
10527               {
10528                 int quals;
10529                 gcc_assert (TYPE_P (arg));
10530
10531                 quals = cp_type_quals (arg) | cp_type_quals (t);
10532                   
10533                 return cp_build_qualified_type_real
10534                   (arg, quals, complain | tf_ignore_bad_quals);
10535               }
10536             else if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
10537               {
10538                 /* We are processing a type constructed from a
10539                    template template parameter.  */
10540                 tree argvec = tsubst (TYPE_TI_ARGS (t),
10541                                       args, complain, in_decl);
10542                 if (argvec == error_mark_node)
10543                   return error_mark_node;
10544
10545                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
10546                    are resolving nested-types in the signature of a
10547                    member function templates.  Otherwise ARG is a
10548                    TEMPLATE_DECL and is the real template to be
10549                    instantiated.  */
10550                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
10551                   arg = TYPE_NAME (arg);
10552
10553                 r = lookup_template_class (arg,
10554                                            argvec, in_decl,
10555                                            DECL_CONTEXT (arg),
10556                                             /*entering_scope=*/0,
10557                                            complain);
10558                 return cp_build_qualified_type_real
10559                   (r, cp_type_quals (t), complain);
10560               }
10561             else
10562               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
10563               return unshare_expr (arg);
10564           }
10565
10566         if (level == 1)
10567           /* This can happen during the attempted tsubst'ing in
10568              unify.  This means that we don't yet have any information
10569              about the template parameter in question.  */
10570           return t;
10571
10572         /* If we get here, we must have been looking at a parm for a
10573            more deeply nested template.  Make a new version of this
10574            template parameter, but with a lower level.  */
10575         switch (code)
10576           {
10577           case TEMPLATE_TYPE_PARM:
10578           case TEMPLATE_TEMPLATE_PARM:
10579           case BOUND_TEMPLATE_TEMPLATE_PARM:
10580             if (cp_type_quals (t))
10581               {
10582                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
10583                 r = cp_build_qualified_type_real
10584                   (r, cp_type_quals (t),
10585                    complain | (code == TEMPLATE_TYPE_PARM
10586                                ? tf_ignore_bad_quals : 0));
10587               }
10588             else
10589               {
10590                 r = copy_type (t);
10591                 TEMPLATE_TYPE_PARM_INDEX (r)
10592                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
10593                                                 r, levels, args, complain);
10594                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
10595                 TYPE_MAIN_VARIANT (r) = r;
10596                 TYPE_POINTER_TO (r) = NULL_TREE;
10597                 TYPE_REFERENCE_TO (r) = NULL_TREE;
10598
10599                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
10600                   /* We have reduced the level of the template
10601                      template parameter, but not the levels of its
10602                      template parameters, so canonical_type_parameter
10603                      will not be able to find the canonical template
10604                      template parameter for this level. Thus, we
10605                      require structural equality checking to compare
10606                      TEMPLATE_TEMPLATE_PARMs. */
10607                   SET_TYPE_STRUCTURAL_EQUALITY (r);
10608                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
10609                   SET_TYPE_STRUCTURAL_EQUALITY (r);
10610                 else
10611                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
10612
10613                 if (code == BOUND_TEMPLATE_TEMPLATE_PARM)
10614                   {
10615                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
10616                                           complain, in_decl);
10617                     if (argvec == error_mark_node)
10618                       return error_mark_node;
10619
10620                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
10621                       = build_template_info (TYPE_TI_TEMPLATE (t), argvec);
10622                   }
10623               }
10624             break;
10625
10626           case TEMPLATE_PARM_INDEX:
10627             r = reduce_template_parm_level (t, type, levels, args, complain);
10628             break;
10629
10630           default:
10631             gcc_unreachable ();
10632           }
10633
10634         return r;
10635       }
10636
10637     case TREE_LIST:
10638       {
10639         tree purpose, value, chain;
10640
10641         if (t == void_list_node)
10642           return t;
10643
10644         purpose = TREE_PURPOSE (t);
10645         if (purpose)
10646           {
10647             purpose = tsubst (purpose, args, complain, in_decl);
10648             if (purpose == error_mark_node)
10649               return error_mark_node;
10650           }
10651         value = TREE_VALUE (t);
10652         if (value)
10653           {
10654             value = tsubst (value, args, complain, in_decl);
10655             if (value == error_mark_node)
10656               return error_mark_node;
10657           }
10658         chain = TREE_CHAIN (t);
10659         if (chain && chain != void_type_node)
10660           {
10661             chain = tsubst (chain, args, complain, in_decl);
10662             if (chain == error_mark_node)
10663               return error_mark_node;
10664           }
10665         if (purpose == TREE_PURPOSE (t)
10666             && value == TREE_VALUE (t)
10667             && chain == TREE_CHAIN (t))
10668           return t;
10669         return hash_tree_cons (purpose, value, chain);
10670       }
10671
10672     case TREE_BINFO:
10673       /* We should never be tsubsting a binfo.  */
10674       gcc_unreachable ();
10675
10676     case TREE_VEC:
10677       /* A vector of template arguments.  */
10678       gcc_assert (!type);
10679       return tsubst_template_args (t, args, complain, in_decl);
10680
10681     case POINTER_TYPE:
10682     case REFERENCE_TYPE:
10683       {
10684         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
10685           return t;
10686
10687         /* [temp.deduct]
10688
10689            Type deduction may fail for any of the following
10690            reasons:
10691
10692            -- Attempting to create a pointer to reference type.
10693            -- Attempting to create a reference to a reference type or
10694               a reference to void.
10695
10696           Core issue 106 says that creating a reference to a reference
10697           during instantiation is no longer a cause for failure. We
10698           only enforce this check in strict C++98 mode.  */
10699         if ((TREE_CODE (type) == REFERENCE_TYPE
10700              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
10701             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
10702           {
10703             static location_t last_loc;
10704
10705             /* We keep track of the last time we issued this error
10706                message to avoid spewing a ton of messages during a
10707                single bad template instantiation.  */
10708             if (complain & tf_error
10709                 && last_loc != input_location)
10710               {
10711                 if (TREE_CODE (type) == VOID_TYPE)
10712                   error ("forming reference to void");
10713                else if (code == POINTER_TYPE)
10714                  error ("forming pointer to reference type %qT", type);
10715                else
10716                   error ("forming reference to reference type %qT", type);
10717                 last_loc = input_location;
10718               }
10719
10720             return error_mark_node;
10721           }
10722         else if (code == POINTER_TYPE)
10723           {
10724             r = build_pointer_type (type);
10725             if (TREE_CODE (type) == METHOD_TYPE)
10726               r = build_ptrmemfunc_type (r);
10727           }
10728         else if (TREE_CODE (type) == REFERENCE_TYPE)
10729           /* In C++0x, during template argument substitution, when there is an
10730              attempt to create a reference to a reference type, reference
10731              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
10732
10733              "If a template-argument for a template-parameter T names a type
10734              that is a reference to a type A, an attempt to create the type
10735              'lvalue reference to cv T' creates the type 'lvalue reference to
10736              A,' while an attempt to create the type type rvalue reference to
10737              cv T' creates the type T"
10738           */
10739           r = cp_build_reference_type
10740               (TREE_TYPE (type),
10741                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
10742         else
10743           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
10744         r = cp_build_qualified_type_real (r, cp_type_quals (t), complain);
10745
10746         if (r != error_mark_node)
10747           /* Will this ever be needed for TYPE_..._TO values?  */
10748           layout_type (r);
10749
10750         return r;
10751       }
10752     case OFFSET_TYPE:
10753       {
10754         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
10755         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
10756           {
10757             /* [temp.deduct]
10758
10759                Type deduction may fail for any of the following
10760                reasons:
10761
10762                -- Attempting to create "pointer to member of T" when T
10763                   is not a class type.  */
10764             if (complain & tf_error)
10765               error ("creating pointer to member of non-class type %qT", r);
10766             return error_mark_node;
10767           }
10768         if (TREE_CODE (type) == REFERENCE_TYPE)
10769           {
10770             if (complain & tf_error)
10771               error ("creating pointer to member reference type %qT", type);
10772             return error_mark_node;
10773           }
10774         if (TREE_CODE (type) == VOID_TYPE)
10775           {
10776             if (complain & tf_error)
10777               error ("creating pointer to member of type void");
10778             return error_mark_node;
10779           }
10780         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
10781         if (TREE_CODE (type) == FUNCTION_TYPE)
10782           {
10783             /* The type of the implicit object parameter gets its
10784                cv-qualifiers from the FUNCTION_TYPE. */
10785             tree memptr;
10786             tree method_type = build_memfn_type (type, r, type_memfn_quals (type));
10787             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
10788             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
10789                                                  complain);
10790           }
10791         else
10792           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
10793                                                cp_type_quals (t),
10794                                                complain);
10795       }
10796     case FUNCTION_TYPE:
10797     case METHOD_TYPE:
10798       {
10799         tree fntype;
10800         tree specs;
10801         fntype = tsubst_function_type (t, args, complain, in_decl);
10802         if (fntype == error_mark_node)
10803           return error_mark_node;
10804
10805         /* Substitute the exception specification.  */
10806         specs = tsubst_exception_specification (t, args, complain,
10807                                                 in_decl);
10808         if (specs == error_mark_node)
10809           return error_mark_node;
10810         if (specs)
10811           fntype = build_exception_variant (fntype, specs);
10812         return fntype;
10813       }
10814     case ARRAY_TYPE:
10815       {
10816         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
10817         if (domain == error_mark_node)
10818           return error_mark_node;
10819
10820         /* As an optimization, we avoid regenerating the array type if
10821            it will obviously be the same as T.  */
10822         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
10823           return t;
10824
10825         /* These checks should match the ones in grokdeclarator.
10826
10827            [temp.deduct]
10828
10829            The deduction may fail for any of the following reasons:
10830
10831            -- Attempting to create an array with an element type that
10832               is void, a function type, or a reference type, or [DR337]
10833               an abstract class type.  */
10834         if (TREE_CODE (type) == VOID_TYPE
10835             || TREE_CODE (type) == FUNCTION_TYPE
10836             || TREE_CODE (type) == REFERENCE_TYPE)
10837           {
10838             if (complain & tf_error)
10839               error ("creating array of %qT", type);
10840             return error_mark_node;
10841           }
10842         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
10843           {
10844             if (complain & tf_error)
10845               error ("creating array of %qT, which is an abstract class type",
10846                      type);
10847             return error_mark_node;
10848           }
10849
10850         r = build_cplus_array_type (type, domain);
10851
10852         if (TYPE_USER_ALIGN (t))
10853           {
10854             TYPE_ALIGN (r) = TYPE_ALIGN (t);
10855             TYPE_USER_ALIGN (r) = 1;
10856           }
10857
10858         return r;
10859       }
10860
10861     case TYPENAME_TYPE:
10862       {
10863         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10864                                      in_decl, /*entering_scope=*/1);
10865         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
10866                               complain, in_decl);
10867
10868         if (ctx == error_mark_node || f == error_mark_node)
10869           return error_mark_node;
10870
10871         if (!MAYBE_CLASS_TYPE_P (ctx))
10872           {
10873             if (complain & tf_error)
10874               error ("%qT is not a class, struct, or union type", ctx);
10875             return error_mark_node;
10876           }
10877         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
10878           {
10879             /* Normally, make_typename_type does not require that the CTX
10880                have complete type in order to allow things like:
10881
10882                  template <class T> struct S { typename S<T>::X Y; };
10883
10884                But, such constructs have already been resolved by this
10885                point, so here CTX really should have complete type, unless
10886                it's a partial instantiation.  */
10887             ctx = complete_type (ctx);
10888             if (!COMPLETE_TYPE_P (ctx))
10889               {
10890                 if (complain & tf_error)
10891                   cxx_incomplete_type_error (NULL_TREE, ctx);
10892                 return error_mark_node;
10893               }
10894           }
10895
10896         f = make_typename_type (ctx, f, typename_type,
10897                                 (complain & tf_error) | tf_keep_type_decl);
10898         if (f == error_mark_node)
10899           return f;
10900         if (TREE_CODE (f) == TYPE_DECL)
10901           {
10902             complain |= tf_ignore_bad_quals;
10903             f = TREE_TYPE (f);
10904           }
10905
10906         if (TREE_CODE (f) != TYPENAME_TYPE)
10907           {
10908             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
10909               error ("%qT resolves to %qT, which is not an enumeration type",
10910                      t, f);
10911             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
10912               error ("%qT resolves to %qT, which is is not a class type",
10913                      t, f);
10914           }
10915
10916         return cp_build_qualified_type_real
10917           (f, cp_type_quals (f) | cp_type_quals (t), complain);
10918       }
10919
10920     case UNBOUND_CLASS_TEMPLATE:
10921       {
10922         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10923                                      in_decl, /*entering_scope=*/1);
10924         tree name = TYPE_IDENTIFIER (t);
10925         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
10926
10927         if (ctx == error_mark_node || name == error_mark_node)
10928           return error_mark_node;
10929
10930         if (parm_list)
10931           parm_list = tsubst_template_parms (parm_list, args, complain);
10932         return make_unbound_class_template (ctx, name, parm_list, complain);
10933       }
10934
10935     case TYPEOF_TYPE:
10936       {
10937         tree type;
10938
10939         ++cp_unevaluated_operand;
10940         ++c_inhibit_evaluation_warnings;
10941
10942         type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
10943                             complain, in_decl,
10944                             /*integral_constant_expression_p=*/false);
10945
10946         --cp_unevaluated_operand;
10947         --c_inhibit_evaluation_warnings;
10948
10949         type = finish_typeof (type);
10950         return cp_build_qualified_type_real (type,
10951                                              cp_type_quals (t)
10952                                              | cp_type_quals (type),
10953                                              complain);
10954       }
10955
10956     case DECLTYPE_TYPE:
10957       {
10958         tree type;
10959
10960         ++cp_unevaluated_operand;
10961         ++c_inhibit_evaluation_warnings;
10962
10963         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
10964                             complain, in_decl,
10965                             /*integral_constant_expression_p=*/false);
10966
10967         --cp_unevaluated_operand;
10968         --c_inhibit_evaluation_warnings;
10969
10970         if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
10971           type = lambda_capture_field_type (type);
10972         else if (DECLTYPE_FOR_LAMBDA_RETURN (t))
10973           type = lambda_return_type (type);
10974         else
10975           type = finish_decltype_type
10976             (type, DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
10977         return cp_build_qualified_type_real (type,
10978                                              cp_type_quals (t)
10979                                              | cp_type_quals (type),
10980                                              complain);
10981       }
10982
10983     case TYPE_ARGUMENT_PACK:
10984     case NONTYPE_ARGUMENT_PACK:
10985       {
10986         tree r = TYPE_P (t) ? cxx_make_type (code) : make_node (code);
10987         tree packed_out = 
10988           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
10989                                 args,
10990                                 complain,
10991                                 in_decl);
10992         SET_ARGUMENT_PACK_ARGS (r, packed_out);
10993
10994         /* For template nontype argument packs, also substitute into
10995            the type.  */
10996         if (code == NONTYPE_ARGUMENT_PACK)
10997           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
10998
10999         return r;
11000       }
11001       break;
11002
11003     case INTEGER_CST:
11004     case REAL_CST:
11005     case STRING_CST:
11006     case PLUS_EXPR:
11007     case MINUS_EXPR:
11008     case NEGATE_EXPR:
11009     case NOP_EXPR:
11010     case INDIRECT_REF:
11011     case ADDR_EXPR:
11012     case CALL_EXPR:
11013     case ARRAY_REF:
11014     case SCOPE_REF:
11015       /* We should use one of the expression tsubsts for these codes.  */
11016       gcc_unreachable ();
11017
11018     default:
11019       sorry ("use of %qs in template", tree_code_name [(int) code]);
11020       return error_mark_node;
11021     }
11022 }
11023
11024 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
11025    type of the expression on the left-hand side of the "." or "->"
11026    operator.  */
11027
11028 static tree
11029 tsubst_baselink (tree baselink, tree object_type,
11030                  tree args, tsubst_flags_t complain, tree in_decl)
11031 {
11032     tree name;
11033     tree qualifying_scope;
11034     tree fns;
11035     tree optype;
11036     tree template_args = 0;
11037     bool template_id_p = false;
11038
11039     /* A baselink indicates a function from a base class.  Both the
11040        BASELINK_ACCESS_BINFO and the base class referenced may
11041        indicate bases of the template class, rather than the
11042        instantiated class.  In addition, lookups that were not
11043        ambiguous before may be ambiguous now.  Therefore, we perform
11044        the lookup again.  */
11045     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
11046     qualifying_scope = tsubst (qualifying_scope, args,
11047                                complain, in_decl);
11048     fns = BASELINK_FUNCTIONS (baselink);
11049     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
11050     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
11051       {
11052         template_id_p = true;
11053         template_args = TREE_OPERAND (fns, 1);
11054         fns = TREE_OPERAND (fns, 0);
11055         if (template_args)
11056           template_args = tsubst_template_args (template_args, args,
11057                                                 complain, in_decl);
11058       }
11059     name = DECL_NAME (get_first_fn (fns));
11060     if (IDENTIFIER_TYPENAME_P (name))
11061       name = mangle_conv_op_name_for_type (optype);
11062     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
11063     if (!baselink)
11064       return error_mark_node;
11065
11066     /* If lookup found a single function, mark it as used at this
11067        point.  (If it lookup found multiple functions the one selected
11068        later by overload resolution will be marked as used at that
11069        point.)  */
11070     if (BASELINK_P (baselink))
11071       fns = BASELINK_FUNCTIONS (baselink);
11072     if (!template_id_p && !really_overloaded_fn (fns))
11073       mark_used (OVL_CURRENT (fns));
11074
11075     /* Add back the template arguments, if present.  */
11076     if (BASELINK_P (baselink) && template_id_p)
11077       BASELINK_FUNCTIONS (baselink)
11078         = build_nt (TEMPLATE_ID_EXPR,
11079                     BASELINK_FUNCTIONS (baselink),
11080                     template_args);
11081     /* Update the conversion operator type.  */
11082     BASELINK_OPTYPE (baselink) = optype;
11083
11084     if (!object_type)
11085       object_type = current_class_type;
11086     return adjust_result_of_qualified_name_lookup (baselink,
11087                                                    qualifying_scope,
11088                                                    object_type);
11089 }
11090
11091 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
11092    true if the qualified-id will be a postfix-expression in-and-of
11093    itself; false if more of the postfix-expression follows the
11094    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
11095    of "&".  */
11096
11097 static tree
11098 tsubst_qualified_id (tree qualified_id, tree args,
11099                      tsubst_flags_t complain, tree in_decl,
11100                      bool done, bool address_p)
11101 {
11102   tree expr;
11103   tree scope;
11104   tree name;
11105   bool is_template;
11106   tree template_args;
11107
11108   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
11109
11110   /* Figure out what name to look up.  */
11111   name = TREE_OPERAND (qualified_id, 1);
11112   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
11113     {
11114       is_template = true;
11115       template_args = TREE_OPERAND (name, 1);
11116       if (template_args)
11117         template_args = tsubst_template_args (template_args, args,
11118                                               complain, in_decl);
11119       name = TREE_OPERAND (name, 0);
11120     }
11121   else
11122     {
11123       is_template = false;
11124       template_args = NULL_TREE;
11125     }
11126
11127   /* Substitute into the qualifying scope.  When there are no ARGS, we
11128      are just trying to simplify a non-dependent expression.  In that
11129      case the qualifying scope may be dependent, and, in any case,
11130      substituting will not help.  */
11131   scope = TREE_OPERAND (qualified_id, 0);
11132   if (args)
11133     {
11134       scope = tsubst (scope, args, complain, in_decl);
11135       expr = tsubst_copy (name, args, complain, in_decl);
11136     }
11137   else
11138     expr = name;
11139
11140   if (dependent_scope_p (scope))
11141     return build_qualified_name (NULL_TREE, scope, expr,
11142                                  QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
11143
11144   if (!BASELINK_P (name) && !DECL_P (expr))
11145     {
11146       if (TREE_CODE (expr) == BIT_NOT_EXPR)
11147         {
11148           /* A BIT_NOT_EXPR is used to represent a destructor.  */
11149           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
11150             {
11151               error ("qualifying type %qT does not match destructor name ~%qT",
11152                      scope, TREE_OPERAND (expr, 0));
11153               expr = error_mark_node;
11154             }
11155           else
11156             expr = lookup_qualified_name (scope, complete_dtor_identifier,
11157                                           /*is_type_p=*/0, false);
11158         }
11159       else
11160         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
11161       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
11162                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
11163         {
11164           if (complain & tf_error)
11165             {
11166               error ("dependent-name %qE is parsed as a non-type, but "
11167                      "instantiation yields a type", qualified_id);
11168               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
11169             }
11170           return error_mark_node;
11171         }
11172     }
11173
11174   if (DECL_P (expr))
11175     {
11176       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
11177                                            scope);
11178       /* Remember that there was a reference to this entity.  */
11179       mark_used (expr);
11180     }
11181
11182   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
11183     {
11184       if (complain & tf_error)
11185         qualified_name_lookup_error (scope,
11186                                      TREE_OPERAND (qualified_id, 1),
11187                                      expr, input_location);
11188       return error_mark_node;
11189     }
11190
11191   if (is_template)
11192     expr = lookup_template_function (expr, template_args);
11193
11194   if (expr == error_mark_node && complain & tf_error)
11195     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
11196                                  expr, input_location);
11197   else if (TYPE_P (scope))
11198     {
11199       expr = (adjust_result_of_qualified_name_lookup
11200               (expr, scope, current_class_type));
11201       expr = (finish_qualified_id_expr
11202               (scope, expr, done, address_p,
11203                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
11204                /*template_arg_p=*/false));
11205     }
11206
11207   /* Expressions do not generally have reference type.  */
11208   if (TREE_CODE (expr) != SCOPE_REF
11209       /* However, if we're about to form a pointer-to-member, we just
11210          want the referenced member referenced.  */
11211       && TREE_CODE (expr) != OFFSET_REF)
11212     expr = convert_from_reference (expr);
11213
11214   return expr;
11215 }
11216
11217 /* Like tsubst, but deals with expressions.  This function just replaces
11218    template parms; to finish processing the resultant expression, use
11219    tsubst_expr.  */
11220
11221 static tree
11222 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
11223 {
11224   enum tree_code code;
11225   tree r;
11226
11227   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
11228     return t;
11229
11230   code = TREE_CODE (t);
11231
11232   switch (code)
11233     {
11234     case PARM_DECL:
11235       r = retrieve_local_specialization (t);
11236
11237       if (r == NULL)
11238         {
11239           tree c;
11240           /* This can happen for a parameter name used later in a function
11241              declaration (such as in a late-specified return type).  Just
11242              make a dummy decl, since it's only used for its type.  */
11243           gcc_assert (cp_unevaluated_operand != 0);
11244           /* We copy T because want to tsubst the PARM_DECL only,
11245              not the following PARM_DECLs that are chained to T.  */
11246           c = copy_node (t);
11247           r = tsubst_decl (c, args, complain);
11248           /* Give it the template pattern as its context; its true context
11249              hasn't been instantiated yet and this is good enough for
11250              mangling.  */
11251           DECL_CONTEXT (r) = DECL_CONTEXT (t);
11252         }
11253       
11254       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
11255         r = ARGUMENT_PACK_SELECT_ARG (r);
11256       mark_used (r);
11257       return r;
11258
11259     case CONST_DECL:
11260       {
11261         tree enum_type;
11262         tree v;
11263
11264         if (DECL_TEMPLATE_PARM_P (t))
11265           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
11266         /* There is no need to substitute into namespace-scope
11267            enumerators.  */
11268         if (DECL_NAMESPACE_SCOPE_P (t))
11269           return t;
11270         /* If ARGS is NULL, then T is known to be non-dependent.  */
11271         if (args == NULL_TREE)
11272           return integral_constant_value (t);
11273
11274         /* Unfortunately, we cannot just call lookup_name here.
11275            Consider:
11276
11277              template <int I> int f() {
11278              enum E { a = I };
11279              struct S { void g() { E e = a; } };
11280              };
11281
11282            When we instantiate f<7>::S::g(), say, lookup_name is not
11283            clever enough to find f<7>::a.  */
11284         enum_type
11285           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
11286                               /*entering_scope=*/0);
11287
11288         for (v = TYPE_VALUES (enum_type);
11289              v != NULL_TREE;
11290              v = TREE_CHAIN (v))
11291           if (TREE_PURPOSE (v) == DECL_NAME (t))
11292             return TREE_VALUE (v);
11293
11294           /* We didn't find the name.  That should never happen; if
11295              name-lookup found it during preliminary parsing, we
11296              should find it again here during instantiation.  */
11297         gcc_unreachable ();
11298       }
11299       return t;
11300
11301     case FIELD_DECL:
11302       if (DECL_CONTEXT (t))
11303         {
11304           tree ctx;
11305
11306           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
11307                                   /*entering_scope=*/1);
11308           if (ctx != DECL_CONTEXT (t))
11309             {
11310               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
11311               if (!r)
11312                 {
11313                   if (complain & tf_error)
11314                     error ("using invalid field %qD", t);
11315                   return error_mark_node;
11316                 }
11317               return r;
11318             }
11319         }
11320
11321       return t;
11322
11323     case VAR_DECL:
11324     case FUNCTION_DECL:
11325       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
11326           || local_variable_p (t))
11327         t = tsubst (t, args, complain, in_decl);
11328       mark_used (t);
11329       return t;
11330
11331     case OVERLOAD:
11332       /* An OVERLOAD will always be a non-dependent overload set; an
11333          overload set from function scope will just be represented with an
11334          IDENTIFIER_NODE, and from class scope with a BASELINK.  */
11335       gcc_assert (!uses_template_parms (t));
11336       return t;
11337
11338     case BASELINK:
11339       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
11340
11341     case TEMPLATE_DECL:
11342       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
11343         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
11344                        args, complain, in_decl);
11345       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
11346         return tsubst (t, args, complain, in_decl);
11347       else if (DECL_CLASS_SCOPE_P (t)
11348                && uses_template_parms (DECL_CONTEXT (t)))
11349         {
11350           /* Template template argument like the following example need
11351              special treatment:
11352
11353                template <template <class> class TT> struct C {};
11354                template <class T> struct D {
11355                  template <class U> struct E {};
11356                  C<E> c;                                // #1
11357                };
11358                D<int> d;                                // #2
11359
11360              We are processing the template argument `E' in #1 for
11361              the template instantiation #2.  Originally, `E' is a
11362              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
11363              have to substitute this with one having context `D<int>'.  */
11364
11365           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
11366           return lookup_field (context, DECL_NAME(t), 0, false);
11367         }
11368       else
11369         /* Ordinary template template argument.  */
11370         return t;
11371
11372     case CAST_EXPR:
11373     case REINTERPRET_CAST_EXPR:
11374     case CONST_CAST_EXPR:
11375     case STATIC_CAST_EXPR:
11376     case DYNAMIC_CAST_EXPR:
11377     case NOP_EXPR:
11378       return build1
11379         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11380          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11381
11382     case SIZEOF_EXPR:
11383       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11384         {
11385
11386           tree expanded;
11387           int len = 0;
11388
11389           ++cp_unevaluated_operand;
11390           ++c_inhibit_evaluation_warnings;
11391           /* We only want to compute the number of arguments.  */
11392           expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
11393                                             complain, in_decl);
11394           --cp_unevaluated_operand;
11395           --c_inhibit_evaluation_warnings;
11396
11397           if (TREE_CODE (expanded) == TREE_VEC)
11398             len = TREE_VEC_LENGTH (expanded);
11399
11400           if (expanded == error_mark_node)
11401             return error_mark_node;
11402           else if (PACK_EXPANSION_P (expanded)
11403                    || (TREE_CODE (expanded) == TREE_VEC
11404                        && len > 0
11405                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
11406             {
11407               if (TREE_CODE (expanded) == TREE_VEC)
11408                 expanded = TREE_VEC_ELT (expanded, len - 1);
11409
11410               if (TYPE_P (expanded))
11411                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
11412                                                    complain & tf_error);
11413               else
11414                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
11415                                                    complain & tf_error);
11416             }
11417           else
11418             return build_int_cst (size_type_node, len);
11419         }
11420       /* Fall through */
11421
11422     case INDIRECT_REF:
11423     case NEGATE_EXPR:
11424     case TRUTH_NOT_EXPR:
11425     case BIT_NOT_EXPR:
11426     case ADDR_EXPR:
11427     case UNARY_PLUS_EXPR:      /* Unary + */
11428     case ALIGNOF_EXPR:
11429     case AT_ENCODE_EXPR:
11430     case ARROW_EXPR:
11431     case THROW_EXPR:
11432     case TYPEID_EXPR:
11433     case REALPART_EXPR:
11434     case IMAGPART_EXPR:
11435       return build1
11436         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11437          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11438
11439     case COMPONENT_REF:
11440       {
11441         tree object;
11442         tree name;
11443
11444         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
11445         name = TREE_OPERAND (t, 1);
11446         if (TREE_CODE (name) == BIT_NOT_EXPR)
11447           {
11448             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11449                                 complain, in_decl);
11450             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11451           }
11452         else if (TREE_CODE (name) == SCOPE_REF
11453                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
11454           {
11455             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
11456                                      complain, in_decl);
11457             name = TREE_OPERAND (name, 1);
11458             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11459                                 complain, in_decl);
11460             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11461             name = build_qualified_name (/*type=*/NULL_TREE,
11462                                          base, name,
11463                                          /*template_p=*/false);
11464           }
11465         else if (TREE_CODE (name) == BASELINK)
11466           name = tsubst_baselink (name,
11467                                   non_reference (TREE_TYPE (object)),
11468                                   args, complain,
11469                                   in_decl);
11470         else
11471           name = tsubst_copy (name, args, complain, in_decl);
11472         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
11473       }
11474
11475     case PLUS_EXPR:
11476     case MINUS_EXPR:
11477     case MULT_EXPR:
11478     case TRUNC_DIV_EXPR:
11479     case CEIL_DIV_EXPR:
11480     case FLOOR_DIV_EXPR:
11481     case ROUND_DIV_EXPR:
11482     case EXACT_DIV_EXPR:
11483     case BIT_AND_EXPR:
11484     case BIT_IOR_EXPR:
11485     case BIT_XOR_EXPR:
11486     case TRUNC_MOD_EXPR:
11487     case FLOOR_MOD_EXPR:
11488     case TRUTH_ANDIF_EXPR:
11489     case TRUTH_ORIF_EXPR:
11490     case TRUTH_AND_EXPR:
11491     case TRUTH_OR_EXPR:
11492     case RSHIFT_EXPR:
11493     case LSHIFT_EXPR:
11494     case RROTATE_EXPR:
11495     case LROTATE_EXPR:
11496     case EQ_EXPR:
11497     case NE_EXPR:
11498     case MAX_EXPR:
11499     case MIN_EXPR:
11500     case LE_EXPR:
11501     case GE_EXPR:
11502     case LT_EXPR:
11503     case GT_EXPR:
11504     case COMPOUND_EXPR:
11505     case DOTSTAR_EXPR:
11506     case MEMBER_REF:
11507     case PREDECREMENT_EXPR:
11508     case PREINCREMENT_EXPR:
11509     case POSTDECREMENT_EXPR:
11510     case POSTINCREMENT_EXPR:
11511       return build_nt
11512         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11513          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11514
11515     case SCOPE_REF:
11516       return build_qualified_name (/*type=*/NULL_TREE,
11517                                    tsubst_copy (TREE_OPERAND (t, 0),
11518                                                 args, complain, in_decl),
11519                                    tsubst_copy (TREE_OPERAND (t, 1),
11520                                                 args, complain, in_decl),
11521                                    QUALIFIED_NAME_IS_TEMPLATE (t));
11522
11523     case ARRAY_REF:
11524       return build_nt
11525         (ARRAY_REF,
11526          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11527          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11528          NULL_TREE, NULL_TREE);
11529
11530     case CALL_EXPR:
11531       {
11532         int n = VL_EXP_OPERAND_LENGTH (t);
11533         tree result = build_vl_exp (CALL_EXPR, n);
11534         int i;
11535         for (i = 0; i < n; i++)
11536           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
11537                                              complain, in_decl);
11538         return result;
11539       }
11540
11541     case COND_EXPR:
11542     case MODOP_EXPR:
11543     case PSEUDO_DTOR_EXPR:
11544       {
11545         r = build_nt
11546           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11547            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11548            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
11549         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
11550         return r;
11551       }
11552
11553     case NEW_EXPR:
11554       {
11555         r = build_nt
11556         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11557          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11558          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
11559         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
11560         return r;
11561       }
11562
11563     case DELETE_EXPR:
11564       {
11565         r = build_nt
11566         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11567          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11568         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
11569         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
11570         return r;
11571       }
11572
11573     case TEMPLATE_ID_EXPR:
11574       {
11575         /* Substituted template arguments */
11576         tree fn = TREE_OPERAND (t, 0);
11577         tree targs = TREE_OPERAND (t, 1);
11578
11579         fn = tsubst_copy (fn, args, complain, in_decl);
11580         if (targs)
11581           targs = tsubst_template_args (targs, args, complain, in_decl);
11582
11583         return lookup_template_function (fn, targs);
11584       }
11585
11586     case TREE_LIST:
11587       {
11588         tree purpose, value, chain;
11589
11590         if (t == void_list_node)
11591           return t;
11592
11593         purpose = TREE_PURPOSE (t);
11594         if (purpose)
11595           purpose = tsubst_copy (purpose, args, complain, in_decl);
11596         value = TREE_VALUE (t);
11597         if (value)
11598           value = tsubst_copy (value, args, complain, in_decl);
11599         chain = TREE_CHAIN (t);
11600         if (chain && chain != void_type_node)
11601           chain = tsubst_copy (chain, args, complain, in_decl);
11602         if (purpose == TREE_PURPOSE (t)
11603             && value == TREE_VALUE (t)
11604             && chain == TREE_CHAIN (t))
11605           return t;
11606         return tree_cons (purpose, value, chain);
11607       }
11608
11609     case RECORD_TYPE:
11610     case UNION_TYPE:
11611     case ENUMERAL_TYPE:
11612     case INTEGER_TYPE:
11613     case TEMPLATE_TYPE_PARM:
11614     case TEMPLATE_TEMPLATE_PARM:
11615     case BOUND_TEMPLATE_TEMPLATE_PARM:
11616     case TEMPLATE_PARM_INDEX:
11617     case POINTER_TYPE:
11618     case REFERENCE_TYPE:
11619     case OFFSET_TYPE:
11620     case FUNCTION_TYPE:
11621     case METHOD_TYPE:
11622     case ARRAY_TYPE:
11623     case TYPENAME_TYPE:
11624     case UNBOUND_CLASS_TEMPLATE:
11625     case TYPEOF_TYPE:
11626     case DECLTYPE_TYPE:
11627     case TYPE_DECL:
11628       return tsubst (t, args, complain, in_decl);
11629
11630     case IDENTIFIER_NODE:
11631       if (IDENTIFIER_TYPENAME_P (t))
11632         {
11633           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11634           return mangle_conv_op_name_for_type (new_type);
11635         }
11636       else
11637         return t;
11638
11639     case CONSTRUCTOR:
11640       /* This is handled by tsubst_copy_and_build.  */
11641       gcc_unreachable ();
11642
11643     case VA_ARG_EXPR:
11644       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
11645                                           in_decl),
11646                              tsubst (TREE_TYPE (t), args, complain, in_decl));
11647
11648     case CLEANUP_POINT_EXPR:
11649       /* We shouldn't have built any of these during initial template
11650          generation.  Instead, they should be built during instantiation
11651          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
11652       gcc_unreachable ();
11653
11654     case OFFSET_REF:
11655       r = build2
11656         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11657          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11658          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11659       PTRMEM_OK_P (r) = PTRMEM_OK_P (t);
11660       mark_used (TREE_OPERAND (r, 1));
11661       return r;
11662
11663     case EXPR_PACK_EXPANSION:
11664       error ("invalid use of pack expansion expression");
11665       return error_mark_node;
11666
11667     case NONTYPE_ARGUMENT_PACK:
11668       error ("use %<...%> to expand argument pack");
11669       return error_mark_node;
11670
11671     case INTEGER_CST:
11672     case REAL_CST:
11673     case STRING_CST:
11674     case COMPLEX_CST:
11675       {
11676         /* Instantiate any typedefs in the type.  */
11677         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11678         r = fold_convert (type, t);
11679         gcc_assert (TREE_CODE (r) == code);
11680         return r;
11681       }
11682
11683     case PTRMEM_CST:
11684       /* These can sometimes show up in a partial instantiation, but never
11685          involve template parms.  */
11686       gcc_assert (!uses_template_parms (t));
11687       return t;
11688
11689     default:
11690       gcc_unreachable ();
11691     }
11692 }
11693
11694 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
11695
11696 static tree
11697 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
11698                     tree in_decl)
11699 {
11700   tree new_clauses = NULL, nc, oc;
11701
11702   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
11703     {
11704       nc = copy_node (oc);
11705       OMP_CLAUSE_CHAIN (nc) = new_clauses;
11706       new_clauses = nc;
11707
11708       switch (OMP_CLAUSE_CODE (nc))
11709         {
11710         case OMP_CLAUSE_LASTPRIVATE:
11711           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
11712             {
11713               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
11714               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
11715                            in_decl, /*integral_constant_expression_p=*/false);
11716               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
11717                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
11718             }
11719           /* FALLTHRU */
11720         case OMP_CLAUSE_PRIVATE:
11721         case OMP_CLAUSE_SHARED:
11722         case OMP_CLAUSE_FIRSTPRIVATE:
11723         case OMP_CLAUSE_REDUCTION:
11724         case OMP_CLAUSE_COPYIN:
11725         case OMP_CLAUSE_COPYPRIVATE:
11726         case OMP_CLAUSE_IF:
11727         case OMP_CLAUSE_NUM_THREADS:
11728         case OMP_CLAUSE_SCHEDULE:
11729         case OMP_CLAUSE_COLLAPSE:
11730           OMP_CLAUSE_OPERAND (nc, 0)
11731             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
11732                            in_decl, /*integral_constant_expression_p=*/false);
11733           break;
11734         case OMP_CLAUSE_NOWAIT:
11735         case OMP_CLAUSE_ORDERED:
11736         case OMP_CLAUSE_DEFAULT:
11737         case OMP_CLAUSE_UNTIED:
11738           break;
11739         default:
11740           gcc_unreachable ();
11741         }
11742     }
11743
11744   return finish_omp_clauses (nreverse (new_clauses));
11745 }
11746
11747 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
11748
11749 static tree
11750 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
11751                           tree in_decl)
11752 {
11753 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
11754
11755   tree purpose, value, chain;
11756
11757   if (t == NULL)
11758     return t;
11759
11760   if (TREE_CODE (t) != TREE_LIST)
11761     return tsubst_copy_and_build (t, args, complain, in_decl,
11762                                   /*function_p=*/false,
11763                                   /*integral_constant_expression_p=*/false);
11764
11765   if (t == void_list_node)
11766     return t;
11767
11768   purpose = TREE_PURPOSE (t);
11769   if (purpose)
11770     purpose = RECUR (purpose);
11771   value = TREE_VALUE (t);
11772   if (value && TREE_CODE (value) != LABEL_DECL)
11773     value = RECUR (value);
11774   chain = TREE_CHAIN (t);
11775   if (chain && chain != void_type_node)
11776     chain = RECUR (chain);
11777   return tree_cons (purpose, value, chain);
11778 #undef RECUR
11779 }
11780
11781 /* Substitute one OMP_FOR iterator.  */
11782
11783 static void
11784 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
11785                          tree condv, tree incrv, tree *clauses,
11786                          tree args, tsubst_flags_t complain, tree in_decl,
11787                          bool integral_constant_expression_p)
11788 {
11789 #define RECUR(NODE)                             \
11790   tsubst_expr ((NODE), args, complain, in_decl, \
11791                integral_constant_expression_p)
11792   tree decl, init, cond, incr, auto_node;
11793
11794   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
11795   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
11796   decl = RECUR (TREE_OPERAND (init, 0));
11797   init = TREE_OPERAND (init, 1);
11798   auto_node = type_uses_auto (TREE_TYPE (decl));
11799   if (auto_node && init)
11800     {
11801       tree init_expr = init;
11802       if (TREE_CODE (init_expr) == DECL_EXPR)
11803         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
11804       init_expr = RECUR (init_expr);
11805       TREE_TYPE (decl)
11806         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
11807     }
11808   gcc_assert (!type_dependent_expression_p (decl));
11809
11810   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
11811     {
11812       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
11813       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11814       if (TREE_CODE (incr) == MODIFY_EXPR)
11815         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
11816                                     RECUR (TREE_OPERAND (incr, 1)),
11817                                     complain);
11818       else
11819         incr = RECUR (incr);
11820       TREE_VEC_ELT (declv, i) = decl;
11821       TREE_VEC_ELT (initv, i) = init;
11822       TREE_VEC_ELT (condv, i) = cond;
11823       TREE_VEC_ELT (incrv, i) = incr;
11824       return;
11825     }
11826
11827   if (init && TREE_CODE (init) != DECL_EXPR)
11828     {
11829       tree c;
11830       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
11831         {
11832           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
11833                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
11834               && OMP_CLAUSE_DECL (c) == decl)
11835             break;
11836           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
11837                    && OMP_CLAUSE_DECL (c) == decl)
11838             error ("iteration variable %qD should not be firstprivate", decl);
11839           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
11840                    && OMP_CLAUSE_DECL (c) == decl)
11841             error ("iteration variable %qD should not be reduction", decl);
11842         }
11843       if (c == NULL)
11844         {
11845           c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
11846           OMP_CLAUSE_DECL (c) = decl;
11847           c = finish_omp_clauses (c);
11848           if (c)
11849             {
11850               OMP_CLAUSE_CHAIN (c) = *clauses;
11851               *clauses = c;
11852             }
11853         }
11854     }
11855   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
11856   if (COMPARISON_CLASS_P (cond))
11857     cond = build2 (TREE_CODE (cond), boolean_type_node,
11858                    RECUR (TREE_OPERAND (cond, 0)),
11859                    RECUR (TREE_OPERAND (cond, 1)));
11860   else
11861     cond = RECUR (cond);
11862   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11863   switch (TREE_CODE (incr))
11864     {
11865     case PREINCREMENT_EXPR:
11866     case PREDECREMENT_EXPR:
11867     case POSTINCREMENT_EXPR:
11868     case POSTDECREMENT_EXPR:
11869       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
11870                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
11871       break;
11872     case MODIFY_EXPR:
11873       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11874           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11875         {
11876           tree rhs = TREE_OPERAND (incr, 1);
11877           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11878                          RECUR (TREE_OPERAND (incr, 0)),
11879                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11880                                  RECUR (TREE_OPERAND (rhs, 0)),
11881                                  RECUR (TREE_OPERAND (rhs, 1))));
11882         }
11883       else
11884         incr = RECUR (incr);
11885       break;
11886     case MODOP_EXPR:
11887       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11888           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11889         {
11890           tree lhs = RECUR (TREE_OPERAND (incr, 0));
11891           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
11892                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
11893                                  TREE_TYPE (decl), lhs,
11894                                  RECUR (TREE_OPERAND (incr, 2))));
11895         }
11896       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
11897                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
11898                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
11899         {
11900           tree rhs = TREE_OPERAND (incr, 2);
11901           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11902                          RECUR (TREE_OPERAND (incr, 0)),
11903                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11904                                  RECUR (TREE_OPERAND (rhs, 0)),
11905                                  RECUR (TREE_OPERAND (rhs, 1))));
11906         }
11907       else
11908         incr = RECUR (incr);
11909       break;
11910     default:
11911       incr = RECUR (incr);
11912       break;
11913     }
11914
11915   TREE_VEC_ELT (declv, i) = decl;
11916   TREE_VEC_ELT (initv, i) = init;
11917   TREE_VEC_ELT (condv, i) = cond;
11918   TREE_VEC_ELT (incrv, i) = incr;
11919 #undef RECUR
11920 }
11921
11922 /* Like tsubst_copy for expressions, etc. but also does semantic
11923    processing.  */
11924
11925 static tree
11926 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
11927              bool integral_constant_expression_p)
11928 {
11929 #define RECUR(NODE)                             \
11930   tsubst_expr ((NODE), args, complain, in_decl, \
11931                integral_constant_expression_p)
11932
11933   tree stmt, tmp;
11934
11935   if (t == NULL_TREE || t == error_mark_node)
11936     return t;
11937
11938   if (EXPR_HAS_LOCATION (t))
11939     input_location = EXPR_LOCATION (t);
11940   if (STATEMENT_CODE_P (TREE_CODE (t)))
11941     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
11942
11943   switch (TREE_CODE (t))
11944     {
11945     case STATEMENT_LIST:
11946       {
11947         tree_stmt_iterator i;
11948         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
11949           RECUR (tsi_stmt (i));
11950         break;
11951       }
11952
11953     case CTOR_INITIALIZER:
11954       finish_mem_initializers (tsubst_initializer_list
11955                                (TREE_OPERAND (t, 0), args));
11956       break;
11957
11958     case RETURN_EXPR:
11959       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
11960       break;
11961
11962     case EXPR_STMT:
11963       tmp = RECUR (EXPR_STMT_EXPR (t));
11964       if (EXPR_STMT_STMT_EXPR_RESULT (t))
11965         finish_stmt_expr_expr (tmp, cur_stmt_expr);
11966       else
11967         finish_expr_stmt (tmp);
11968       break;
11969
11970     case USING_STMT:
11971       do_using_directive (USING_STMT_NAMESPACE (t));
11972       break;
11973
11974     case DECL_EXPR:
11975       {
11976         tree decl, pattern_decl;
11977         tree init;
11978
11979         pattern_decl = decl = DECL_EXPR_DECL (t);
11980         if (TREE_CODE (decl) == LABEL_DECL)
11981           finish_label_decl (DECL_NAME (decl));
11982         else if (TREE_CODE (decl) == USING_DECL)
11983           {
11984             tree scope = USING_DECL_SCOPE (decl);
11985             tree name = DECL_NAME (decl);
11986             tree decl;
11987
11988             scope = tsubst (scope, args, complain, in_decl);
11989             decl = lookup_qualified_name (scope, name,
11990                                           /*is_type_p=*/false,
11991                                           /*complain=*/false);
11992             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
11993               qualified_name_lookup_error (scope, name, decl, input_location);
11994             else
11995               do_local_using_decl (decl, scope, name);
11996           }
11997         else
11998           {
11999             init = DECL_INITIAL (decl);
12000             decl = tsubst (decl, args, complain, in_decl);
12001             if (decl != error_mark_node)
12002               {
12003                 /* By marking the declaration as instantiated, we avoid
12004                    trying to instantiate it.  Since instantiate_decl can't
12005                    handle local variables, and since we've already done
12006                    all that needs to be done, that's the right thing to
12007                    do.  */
12008                 if (TREE_CODE (decl) == VAR_DECL)
12009                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
12010                 if (TREE_CODE (decl) == VAR_DECL
12011                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
12012                   /* Anonymous aggregates are a special case.  */
12013                   finish_anon_union (decl);
12014                 else
12015                   {
12016                     int const_init = false;
12017                     maybe_push_decl (decl);
12018                     if (TREE_CODE (decl) == VAR_DECL
12019                         && DECL_PRETTY_FUNCTION_P (decl))
12020                       {
12021                         /* For __PRETTY_FUNCTION__ we have to adjust the
12022                            initializer.  */
12023                         const char *const name
12024                           = cxx_printable_name (current_function_decl, 2);
12025                         init = cp_fname_init (name, &TREE_TYPE (decl));
12026                       }
12027                     else
12028                       {
12029                         tree t = RECUR (init);
12030
12031                         if (init && !t)
12032                           {
12033                             /* If we had an initializer but it
12034                                instantiated to nothing,
12035                                value-initialize the object.  This will
12036                                only occur when the initializer was a
12037                                pack expansion where the parameter packs
12038                                used in that expansion were of length
12039                                zero.  */
12040                             init = build_value_init (TREE_TYPE (decl),
12041                                                      complain);
12042                             if (TREE_CODE (init) == AGGR_INIT_EXPR)
12043                               init = get_target_expr (init);
12044                           }
12045                         else
12046                           init = t;
12047                       }
12048
12049                     if (TREE_CODE (decl) == VAR_DECL)
12050                       const_init = (DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P
12051                                     (pattern_decl));
12052                     cp_finish_decl (decl, init, const_init, NULL_TREE, 0);
12053                   }
12054               }
12055           }
12056
12057         /* A DECL_EXPR can also be used as an expression, in the condition
12058            clause of an if/for/while construct.  */
12059         return decl;
12060       }
12061
12062     case FOR_STMT:
12063       stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
12064       RECUR (FOR_INIT_STMT (t));
12065       finish_for_init_stmt (stmt);
12066       tmp = RECUR (FOR_COND (t));
12067       finish_for_cond (tmp, stmt);
12068       tmp = RECUR (FOR_EXPR (t));
12069       finish_for_expr (tmp, stmt);
12070       RECUR (FOR_BODY (t));
12071       finish_for_stmt (stmt);
12072       break;
12073
12074     case RANGE_FOR_STMT:
12075       {
12076         tree decl, expr;
12077         stmt = begin_for_stmt (NULL_TREE, NULL_TREE);
12078         decl = RANGE_FOR_DECL (t);
12079         decl = tsubst (decl, args, complain, in_decl);
12080         maybe_push_decl (decl);
12081         expr = RECUR (RANGE_FOR_EXPR (t));
12082         stmt = cp_convert_range_for (stmt, decl, expr);
12083         RECUR (RANGE_FOR_BODY (t));
12084         finish_for_stmt (stmt);
12085       }
12086       break;
12087
12088     case WHILE_STMT:
12089       stmt = begin_while_stmt ();
12090       tmp = RECUR (WHILE_COND (t));
12091       finish_while_stmt_cond (tmp, stmt);
12092       RECUR (WHILE_BODY (t));
12093       finish_while_stmt (stmt);
12094       break;
12095
12096     case DO_STMT:
12097       stmt = begin_do_stmt ();
12098       RECUR (DO_BODY (t));
12099       finish_do_body (stmt);
12100       tmp = RECUR (DO_COND (t));
12101       finish_do_stmt (tmp, stmt);
12102       break;
12103
12104     case IF_STMT:
12105       stmt = begin_if_stmt ();
12106       tmp = RECUR (IF_COND (t));
12107       finish_if_stmt_cond (tmp, stmt);
12108       RECUR (THEN_CLAUSE (t));
12109       finish_then_clause (stmt);
12110
12111       if (ELSE_CLAUSE (t))
12112         {
12113           begin_else_clause (stmt);
12114           RECUR (ELSE_CLAUSE (t));
12115           finish_else_clause (stmt);
12116         }
12117
12118       finish_if_stmt (stmt);
12119       break;
12120
12121     case BIND_EXPR:
12122       if (BIND_EXPR_BODY_BLOCK (t))
12123         stmt = begin_function_body ();
12124       else
12125         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
12126                                     ? BCS_TRY_BLOCK : 0);
12127
12128       RECUR (BIND_EXPR_BODY (t));
12129
12130       if (BIND_EXPR_BODY_BLOCK (t))
12131         finish_function_body (stmt);
12132       else
12133         finish_compound_stmt (stmt);
12134       break;
12135
12136     case BREAK_STMT:
12137       finish_break_stmt ();
12138       break;
12139
12140     case CONTINUE_STMT:
12141       finish_continue_stmt ();
12142       break;
12143
12144     case SWITCH_STMT:
12145       stmt = begin_switch_stmt ();
12146       tmp = RECUR (SWITCH_STMT_COND (t));
12147       finish_switch_cond (tmp, stmt);
12148       RECUR (SWITCH_STMT_BODY (t));
12149       finish_switch_stmt (stmt);
12150       break;
12151
12152     case CASE_LABEL_EXPR:
12153       finish_case_label (EXPR_LOCATION (t),
12154                          RECUR (CASE_LOW (t)),
12155                          RECUR (CASE_HIGH (t)));
12156       break;
12157
12158     case LABEL_EXPR:
12159       {
12160         tree decl = LABEL_EXPR_LABEL (t);
12161         tree label;
12162
12163         label = finish_label_stmt (DECL_NAME (decl));
12164         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
12165           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
12166       }
12167       break;
12168
12169     case GOTO_EXPR:
12170       tmp = GOTO_DESTINATION (t);
12171       if (TREE_CODE (tmp) != LABEL_DECL)
12172         /* Computed goto's must be tsubst'd into.  On the other hand,
12173            non-computed gotos must not be; the identifier in question
12174            will have no binding.  */
12175         tmp = RECUR (tmp);
12176       else
12177         tmp = DECL_NAME (tmp);
12178       finish_goto_stmt (tmp);
12179       break;
12180
12181     case ASM_EXPR:
12182       tmp = finish_asm_stmt
12183         (ASM_VOLATILE_P (t),
12184          RECUR (ASM_STRING (t)),
12185          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
12186          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
12187          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl),
12188          tsubst_copy_asm_operands (ASM_LABELS (t), args, complain, in_decl));
12189       {
12190         tree asm_expr = tmp;
12191         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
12192           asm_expr = TREE_OPERAND (asm_expr, 0);
12193         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
12194       }
12195       break;
12196
12197     case TRY_BLOCK:
12198       if (CLEANUP_P (t))
12199         {
12200           stmt = begin_try_block ();
12201           RECUR (TRY_STMTS (t));
12202           finish_cleanup_try_block (stmt);
12203           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
12204         }
12205       else
12206         {
12207           tree compound_stmt = NULL_TREE;
12208
12209           if (FN_TRY_BLOCK_P (t))
12210             stmt = begin_function_try_block (&compound_stmt);
12211           else
12212             stmt = begin_try_block ();
12213
12214           RECUR (TRY_STMTS (t));
12215
12216           if (FN_TRY_BLOCK_P (t))
12217             finish_function_try_block (stmt);
12218           else
12219             finish_try_block (stmt);
12220
12221           RECUR (TRY_HANDLERS (t));
12222           if (FN_TRY_BLOCK_P (t))
12223             finish_function_handler_sequence (stmt, compound_stmt);
12224           else
12225             finish_handler_sequence (stmt);
12226         }
12227       break;
12228
12229     case HANDLER:
12230       {
12231         tree decl = HANDLER_PARMS (t);
12232
12233         if (decl)
12234           {
12235             decl = tsubst (decl, args, complain, in_decl);
12236             /* Prevent instantiate_decl from trying to instantiate
12237                this variable.  We've already done all that needs to be
12238                done.  */
12239             if (decl != error_mark_node)
12240               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
12241           }
12242         stmt = begin_handler ();
12243         finish_handler_parms (decl, stmt);
12244         RECUR (HANDLER_BODY (t));
12245         finish_handler (stmt);
12246       }
12247       break;
12248
12249     case TAG_DEFN:
12250       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
12251       break;
12252
12253     case STATIC_ASSERT:
12254       {
12255         tree condition = 
12256           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
12257                        args,
12258                        complain, in_decl,
12259                        /*integral_constant_expression_p=*/true);
12260         finish_static_assert (condition,
12261                               STATIC_ASSERT_MESSAGE (t),
12262                               STATIC_ASSERT_SOURCE_LOCATION (t),
12263                               /*member_p=*/false);
12264       }
12265       break;
12266
12267     case OMP_PARALLEL:
12268       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
12269                                 args, complain, in_decl);
12270       stmt = begin_omp_parallel ();
12271       RECUR (OMP_PARALLEL_BODY (t));
12272       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
12273         = OMP_PARALLEL_COMBINED (t);
12274       break;
12275
12276     case OMP_TASK:
12277       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
12278                                 args, complain, in_decl);
12279       stmt = begin_omp_task ();
12280       RECUR (OMP_TASK_BODY (t));
12281       finish_omp_task (tmp, stmt);
12282       break;
12283
12284     case OMP_FOR:
12285       {
12286         tree clauses, body, pre_body;
12287         tree declv, initv, condv, incrv;
12288         int i;
12289
12290         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
12291                                       args, complain, in_decl);
12292         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12293         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12294         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12295         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
12296
12297         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
12298           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
12299                                    &clauses, args, complain, in_decl,
12300                                    integral_constant_expression_p);
12301
12302         stmt = begin_omp_structured_block ();
12303
12304         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
12305           if (TREE_VEC_ELT (initv, i) == NULL
12306               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
12307             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
12308           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
12309             {
12310               tree init = RECUR (TREE_VEC_ELT (initv, i));
12311               gcc_assert (init == TREE_VEC_ELT (declv, i));
12312               TREE_VEC_ELT (initv, i) = NULL_TREE;
12313             }
12314           else
12315             {
12316               tree decl_expr = TREE_VEC_ELT (initv, i);
12317               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
12318               gcc_assert (init != NULL);
12319               TREE_VEC_ELT (initv, i) = RECUR (init);
12320               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
12321               RECUR (decl_expr);
12322               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
12323             }
12324
12325         pre_body = push_stmt_list ();
12326         RECUR (OMP_FOR_PRE_BODY (t));
12327         pre_body = pop_stmt_list (pre_body);
12328
12329         body = push_stmt_list ();
12330         RECUR (OMP_FOR_BODY (t));
12331         body = pop_stmt_list (body);
12332
12333         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
12334                             body, pre_body, clauses);
12335
12336         add_stmt (finish_omp_structured_block (stmt));
12337       }
12338       break;
12339
12340     case OMP_SECTIONS:
12341     case OMP_SINGLE:
12342       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
12343       stmt = push_stmt_list ();
12344       RECUR (OMP_BODY (t));
12345       stmt = pop_stmt_list (stmt);
12346
12347       t = copy_node (t);
12348       OMP_BODY (t) = stmt;
12349       OMP_CLAUSES (t) = tmp;
12350       add_stmt (t);
12351       break;
12352
12353     case OMP_SECTION:
12354     case OMP_CRITICAL:
12355     case OMP_MASTER:
12356     case OMP_ORDERED:
12357       stmt = push_stmt_list ();
12358       RECUR (OMP_BODY (t));
12359       stmt = pop_stmt_list (stmt);
12360
12361       t = copy_node (t);
12362       OMP_BODY (t) = stmt;
12363       add_stmt (t);
12364       break;
12365
12366     case OMP_ATOMIC:
12367       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
12368       {
12369         tree op1 = TREE_OPERAND (t, 1);
12370         tree lhs = RECUR (TREE_OPERAND (op1, 0));
12371         tree rhs = RECUR (TREE_OPERAND (op1, 1));
12372         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
12373       }
12374       break;
12375
12376     case EXPR_PACK_EXPANSION:
12377       error ("invalid use of pack expansion expression");
12378       return error_mark_node;
12379
12380     case NONTYPE_ARGUMENT_PACK:
12381       error ("use %<...%> to expand argument pack");
12382       return error_mark_node;
12383
12384     default:
12385       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
12386
12387       return tsubst_copy_and_build (t, args, complain, in_decl,
12388                                     /*function_p=*/false,
12389                                     integral_constant_expression_p);
12390     }
12391
12392   return NULL_TREE;
12393 #undef RECUR
12394 }
12395
12396 /* T is a postfix-expression that is not being used in a function
12397    call.  Return the substituted version of T.  */
12398
12399 static tree
12400 tsubst_non_call_postfix_expression (tree t, tree args,
12401                                     tsubst_flags_t complain,
12402                                     tree in_decl)
12403 {
12404   if (TREE_CODE (t) == SCOPE_REF)
12405     t = tsubst_qualified_id (t, args, complain, in_decl,
12406                              /*done=*/false, /*address_p=*/false);
12407   else
12408     t = tsubst_copy_and_build (t, args, complain, in_decl,
12409                                /*function_p=*/false,
12410                                /*integral_constant_expression_p=*/false);
12411
12412   return t;
12413 }
12414
12415 /* Like tsubst but deals with expressions and performs semantic
12416    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
12417
12418 tree
12419 tsubst_copy_and_build (tree t,
12420                        tree args,
12421                        tsubst_flags_t complain,
12422                        tree in_decl,
12423                        bool function_p,
12424                        bool integral_constant_expression_p)
12425 {
12426 #define RECUR(NODE)                                             \
12427   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
12428                          /*function_p=*/false,                  \
12429                          integral_constant_expression_p)
12430
12431   tree op1;
12432
12433   if (t == NULL_TREE || t == error_mark_node)
12434     return t;
12435
12436   switch (TREE_CODE (t))
12437     {
12438     case USING_DECL:
12439       t = DECL_NAME (t);
12440       /* Fall through.  */
12441     case IDENTIFIER_NODE:
12442       {
12443         tree decl;
12444         cp_id_kind idk;
12445         bool non_integral_constant_expression_p;
12446         const char *error_msg;
12447
12448         if (IDENTIFIER_TYPENAME_P (t))
12449           {
12450             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12451             t = mangle_conv_op_name_for_type (new_type);
12452           }
12453
12454         /* Look up the name.  */
12455         decl = lookup_name (t);
12456
12457         /* By convention, expressions use ERROR_MARK_NODE to indicate
12458            failure, not NULL_TREE.  */
12459         if (decl == NULL_TREE)
12460           decl = error_mark_node;
12461
12462         decl = finish_id_expression (t, decl, NULL_TREE,
12463                                      &idk,
12464                                      integral_constant_expression_p,
12465                                      /*allow_non_integral_constant_expression_p=*/false,
12466                                      &non_integral_constant_expression_p,
12467                                      /*template_p=*/false,
12468                                      /*done=*/true,
12469                                      /*address_p=*/false,
12470                                      /*template_arg_p=*/false,
12471                                      &error_msg,
12472                                      input_location);
12473         if (error_msg)
12474           error (error_msg);
12475         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
12476           decl = unqualified_name_lookup_error (decl);
12477         return decl;
12478       }
12479
12480     case TEMPLATE_ID_EXPR:
12481       {
12482         tree object;
12483         tree templ = RECUR (TREE_OPERAND (t, 0));
12484         tree targs = TREE_OPERAND (t, 1);
12485
12486         if (targs)
12487           targs = tsubst_template_args (targs, args, complain, in_decl);
12488
12489         if (TREE_CODE (templ) == COMPONENT_REF)
12490           {
12491             object = TREE_OPERAND (templ, 0);
12492             templ = TREE_OPERAND (templ, 1);
12493           }
12494         else
12495           object = NULL_TREE;
12496         templ = lookup_template_function (templ, targs);
12497
12498         if (object)
12499           return build3 (COMPONENT_REF, TREE_TYPE (templ),
12500                          object, templ, NULL_TREE);
12501         else
12502           return baselink_for_fns (templ);
12503       }
12504
12505     case INDIRECT_REF:
12506       {
12507         tree r = RECUR (TREE_OPERAND (t, 0));
12508
12509         if (REFERENCE_REF_P (t))
12510           {
12511             /* A type conversion to reference type will be enclosed in
12512                such an indirect ref, but the substitution of the cast
12513                will have also added such an indirect ref.  */
12514             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
12515               r = convert_from_reference (r);
12516           }
12517         else
12518           r = build_x_indirect_ref (r, RO_UNARY_STAR, complain);
12519         return r;
12520       }
12521
12522     case NOP_EXPR:
12523       return build_nop
12524         (tsubst (TREE_TYPE (t), args, complain, in_decl),
12525          RECUR (TREE_OPERAND (t, 0)));
12526
12527     case CAST_EXPR:
12528     case REINTERPRET_CAST_EXPR:
12529     case CONST_CAST_EXPR:
12530     case DYNAMIC_CAST_EXPR:
12531     case STATIC_CAST_EXPR:
12532       {
12533         tree type;
12534         tree op;
12535
12536         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12537         if (integral_constant_expression_p
12538             && !cast_valid_in_integral_constant_expression_p (type))
12539           {
12540             if (complain & tf_error)
12541               error ("a cast to a type other than an integral or "
12542                      "enumeration type cannot appear in a constant-expression");
12543             return error_mark_node; 
12544           }
12545
12546         op = RECUR (TREE_OPERAND (t, 0));
12547
12548         switch (TREE_CODE (t))
12549           {
12550           case CAST_EXPR:
12551             return build_functional_cast (type, op, complain);
12552           case REINTERPRET_CAST_EXPR:
12553             return build_reinterpret_cast (type, op, complain);
12554           case CONST_CAST_EXPR:
12555             return build_const_cast (type, op, complain);
12556           case DYNAMIC_CAST_EXPR:
12557             return build_dynamic_cast (type, op, complain);
12558           case STATIC_CAST_EXPR:
12559             return build_static_cast (type, op, complain);
12560           default:
12561             gcc_unreachable ();
12562           }
12563       }
12564
12565     case POSTDECREMENT_EXPR:
12566     case POSTINCREMENT_EXPR:
12567       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12568                                                 args, complain, in_decl);
12569       return build_x_unary_op (TREE_CODE (t), op1, complain);
12570
12571     case PREDECREMENT_EXPR:
12572     case PREINCREMENT_EXPR:
12573     case NEGATE_EXPR:
12574     case BIT_NOT_EXPR:
12575     case ABS_EXPR:
12576     case TRUTH_NOT_EXPR:
12577     case UNARY_PLUS_EXPR:  /* Unary + */
12578     case REALPART_EXPR:
12579     case IMAGPART_EXPR:
12580       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
12581                                complain);
12582
12583     case ADDR_EXPR:
12584       op1 = TREE_OPERAND (t, 0);
12585       if (TREE_CODE (op1) == LABEL_DECL)
12586         return finish_label_address_expr (DECL_NAME (op1),
12587                                           EXPR_LOCATION (op1));
12588       if (TREE_CODE (op1) == SCOPE_REF)
12589         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
12590                                    /*done=*/true, /*address_p=*/true);
12591       else
12592         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
12593                                                   in_decl);
12594       return build_x_unary_op (ADDR_EXPR, op1, complain);
12595
12596     case PLUS_EXPR:
12597     case MINUS_EXPR:
12598     case MULT_EXPR:
12599     case TRUNC_DIV_EXPR:
12600     case CEIL_DIV_EXPR:
12601     case FLOOR_DIV_EXPR:
12602     case ROUND_DIV_EXPR:
12603     case EXACT_DIV_EXPR:
12604     case BIT_AND_EXPR:
12605     case BIT_IOR_EXPR:
12606     case BIT_XOR_EXPR:
12607     case TRUNC_MOD_EXPR:
12608     case FLOOR_MOD_EXPR:
12609     case TRUTH_ANDIF_EXPR:
12610     case TRUTH_ORIF_EXPR:
12611     case TRUTH_AND_EXPR:
12612     case TRUTH_OR_EXPR:
12613     case RSHIFT_EXPR:
12614     case LSHIFT_EXPR:
12615     case RROTATE_EXPR:
12616     case LROTATE_EXPR:
12617     case EQ_EXPR:
12618     case NE_EXPR:
12619     case MAX_EXPR:
12620     case MIN_EXPR:
12621     case LE_EXPR:
12622     case GE_EXPR:
12623     case LT_EXPR:
12624     case GT_EXPR:
12625     case MEMBER_REF:
12626     case DOTSTAR_EXPR:
12627       return build_x_binary_op
12628         (TREE_CODE (t),
12629          RECUR (TREE_OPERAND (t, 0)),
12630          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
12631           ? ERROR_MARK
12632           : TREE_CODE (TREE_OPERAND (t, 0))),
12633          RECUR (TREE_OPERAND (t, 1)),
12634          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
12635           ? ERROR_MARK
12636           : TREE_CODE (TREE_OPERAND (t, 1))),
12637          /*overloaded_p=*/NULL,
12638          complain);
12639
12640     case SCOPE_REF:
12641       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
12642                                   /*address_p=*/false);
12643     case ARRAY_REF:
12644       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12645                                                 args, complain, in_decl);
12646       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
12647
12648     case SIZEOF_EXPR:
12649       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
12650         return tsubst_copy (t, args, complain, in_decl);
12651       /* Fall through */
12652       
12653     case ALIGNOF_EXPR:
12654       op1 = TREE_OPERAND (t, 0);
12655       if (!args)
12656         {
12657           /* When there are no ARGS, we are trying to evaluate a
12658              non-dependent expression from the parser.  Trying to do
12659              the substitutions may not work.  */
12660           if (!TYPE_P (op1))
12661             op1 = TREE_TYPE (op1);
12662         }
12663       else
12664         {
12665           ++cp_unevaluated_operand;
12666           ++c_inhibit_evaluation_warnings;
12667           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
12668                                        /*function_p=*/false,
12669                                        /*integral_constant_expression_p=*/false);
12670           --cp_unevaluated_operand;
12671           --c_inhibit_evaluation_warnings;
12672         }
12673       if (TYPE_P (op1))
12674         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
12675                                            complain & tf_error);
12676       else
12677         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
12678                                            complain & tf_error);
12679
12680     case AT_ENCODE_EXPR:
12681       {
12682         op1 = TREE_OPERAND (t, 0);
12683         ++cp_unevaluated_operand;
12684         ++c_inhibit_evaluation_warnings;
12685         op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
12686                                      /*function_p=*/false,
12687                                      /*integral_constant_expression_p=*/false);
12688         --cp_unevaluated_operand;
12689         --c_inhibit_evaluation_warnings;
12690         return objc_build_encode_expr (op1);
12691       }
12692
12693     case NOEXCEPT_EXPR:
12694       op1 = TREE_OPERAND (t, 0);
12695       ++cp_unevaluated_operand;
12696       ++c_inhibit_evaluation_warnings;
12697       op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
12698                                    /*function_p=*/false,
12699                                    /*integral_constant_expression_p=*/false);
12700       --cp_unevaluated_operand;
12701       --c_inhibit_evaluation_warnings;
12702       return finish_noexcept_expr (op1, complain);
12703
12704     case MODOP_EXPR:
12705       {
12706         tree r = build_x_modify_expr
12707           (RECUR (TREE_OPERAND (t, 0)),
12708            TREE_CODE (TREE_OPERAND (t, 1)),
12709            RECUR (TREE_OPERAND (t, 2)),
12710            complain);
12711         /* TREE_NO_WARNING must be set if either the expression was
12712            parenthesized or it uses an operator such as >>= rather
12713            than plain assignment.  In the former case, it was already
12714            set and must be copied.  In the latter case,
12715            build_x_modify_expr sets it and it must not be reset
12716            here.  */
12717         if (TREE_NO_WARNING (t))
12718           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
12719         return r;
12720       }
12721
12722     case ARROW_EXPR:
12723       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12724                                                 args, complain, in_decl);
12725       /* Remember that there was a reference to this entity.  */
12726       if (DECL_P (op1))
12727         mark_used (op1);
12728       return build_x_arrow (op1);
12729
12730     case NEW_EXPR:
12731       {
12732         tree placement = RECUR (TREE_OPERAND (t, 0));
12733         tree init = RECUR (TREE_OPERAND (t, 3));
12734         VEC(tree,gc) *placement_vec;
12735         VEC(tree,gc) *init_vec;
12736         tree ret;
12737
12738         if (placement == NULL_TREE)
12739           placement_vec = NULL;
12740         else
12741           {
12742             placement_vec = make_tree_vector ();
12743             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
12744               VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
12745           }
12746
12747         /* If there was an initializer in the original tree, but it
12748            instantiated to an empty list, then we should pass a
12749            non-NULL empty vector to tell build_new that it was an
12750            empty initializer() rather than no initializer.  This can
12751            only happen when the initializer is a pack expansion whose
12752            parameter packs are of length zero.  */
12753         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
12754           init_vec = NULL;
12755         else
12756           {
12757             init_vec = make_tree_vector ();
12758             if (init == void_zero_node)
12759               gcc_assert (init_vec != NULL);
12760             else
12761               {
12762                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
12763                   VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
12764               }
12765           }
12766
12767         ret = build_new (&placement_vec,
12768                          tsubst (TREE_OPERAND (t, 1), args, complain, in_decl),
12769                          RECUR (TREE_OPERAND (t, 2)),
12770                          &init_vec,
12771                          NEW_EXPR_USE_GLOBAL (t),
12772                          complain);
12773
12774         if (placement_vec != NULL)
12775           release_tree_vector (placement_vec);
12776         if (init_vec != NULL)
12777           release_tree_vector (init_vec);
12778
12779         return ret;
12780       }
12781
12782     case DELETE_EXPR:
12783      return delete_sanity
12784        (RECUR (TREE_OPERAND (t, 0)),
12785         RECUR (TREE_OPERAND (t, 1)),
12786         DELETE_EXPR_USE_VEC (t),
12787         DELETE_EXPR_USE_GLOBAL (t));
12788
12789     case COMPOUND_EXPR:
12790       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
12791                                     RECUR (TREE_OPERAND (t, 1)),
12792                                     complain);
12793
12794     case CALL_EXPR:
12795       {
12796         tree function;
12797         VEC(tree,gc) *call_args;
12798         unsigned int nargs, i;
12799         bool qualified_p;
12800         bool koenig_p;
12801         tree ret;
12802
12803         function = CALL_EXPR_FN (t);
12804         /* When we parsed the expression,  we determined whether or
12805            not Koenig lookup should be performed.  */
12806         koenig_p = KOENIG_LOOKUP_P (t);
12807         if (TREE_CODE (function) == SCOPE_REF)
12808           {
12809             qualified_p = true;
12810             function = tsubst_qualified_id (function, args, complain, in_decl,
12811                                             /*done=*/false,
12812                                             /*address_p=*/false);
12813           }
12814         else
12815           {
12816             if (TREE_CODE (function) == COMPONENT_REF)
12817               {
12818                 tree op = TREE_OPERAND (function, 1);
12819
12820                 qualified_p = (TREE_CODE (op) == SCOPE_REF
12821                                || (BASELINK_P (op)
12822                                    && BASELINK_QUALIFIED_P (op)));
12823               }
12824             else
12825               qualified_p = false;
12826
12827             function = tsubst_copy_and_build (function, args, complain,
12828                                               in_decl,
12829                                               !qualified_p,
12830                                               integral_constant_expression_p);
12831
12832             if (BASELINK_P (function))
12833               qualified_p = true;
12834           }
12835
12836         nargs = call_expr_nargs (t);
12837         call_args = make_tree_vector ();
12838         for (i = 0; i < nargs; ++i)
12839           {
12840             tree arg = CALL_EXPR_ARG (t, i);
12841
12842             if (!PACK_EXPANSION_P (arg))
12843               VEC_safe_push (tree, gc, call_args,
12844                              RECUR (CALL_EXPR_ARG (t, i)));
12845             else
12846               {
12847                 /* Expand the pack expansion and push each entry onto
12848                    CALL_ARGS.  */
12849                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
12850                 if (TREE_CODE (arg) == TREE_VEC)
12851                   {
12852                     unsigned int len, j;
12853
12854                     len = TREE_VEC_LENGTH (arg);
12855                     for (j = 0; j < len; ++j)
12856                       {
12857                         tree value = TREE_VEC_ELT (arg, j);
12858                         if (value != NULL_TREE)
12859                           value = convert_from_reference (value);
12860                         VEC_safe_push (tree, gc, call_args, value);
12861                       }
12862                   }
12863                 else
12864                   {
12865                     /* A partial substitution.  Add one entry.  */
12866                     VEC_safe_push (tree, gc, call_args, arg);
12867                   }
12868               }
12869           }
12870
12871         /* We do not perform argument-dependent lookup if normal
12872            lookup finds a non-function, in accordance with the
12873            expected resolution of DR 218.  */
12874         if (koenig_p
12875             && ((is_overloaded_fn (function)
12876                  /* If lookup found a member function, the Koenig lookup is
12877                     not appropriate, even if an unqualified-name was used
12878                     to denote the function.  */
12879                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
12880                 || TREE_CODE (function) == IDENTIFIER_NODE)
12881             /* Only do this when substitution turns a dependent call
12882                into a non-dependent call.  */
12883             && type_dependent_expression_p_push (t)
12884             && !any_type_dependent_arguments_p (call_args))
12885           function = perform_koenig_lookup (function, call_args, false);
12886
12887         if (TREE_CODE (function) == IDENTIFIER_NODE)
12888           {
12889             unqualified_name_lookup_error (function);
12890             release_tree_vector (call_args);
12891             return error_mark_node;
12892           }
12893
12894         /* Remember that there was a reference to this entity.  */
12895         if (DECL_P (function))
12896           mark_used (function);
12897
12898         if (TREE_CODE (function) == OFFSET_REF)
12899           ret = build_offset_ref_call_from_tree (function, &call_args);
12900         else if (TREE_CODE (function) == COMPONENT_REF)
12901           {
12902             tree instance = TREE_OPERAND (function, 0);
12903             tree fn = TREE_OPERAND (function, 1);
12904
12905             if (processing_template_decl
12906                 && (type_dependent_expression_p (instance)
12907                     || (!BASELINK_P (fn)
12908                         && TREE_CODE (fn) != FIELD_DECL)
12909                     || type_dependent_expression_p (fn)
12910                     || any_type_dependent_arguments_p (call_args)))
12911               ret = build_nt_call_vec (function, call_args);
12912             else if (!BASELINK_P (fn))
12913               ret = finish_call_expr (function, &call_args,
12914                                        /*disallow_virtual=*/false,
12915                                        /*koenig_p=*/false,
12916                                        complain);
12917             else
12918               ret = (build_new_method_call
12919                       (instance, fn,
12920                        &call_args, NULL_TREE,
12921                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
12922                        /*fn_p=*/NULL,
12923                        complain));
12924           }
12925         else
12926           ret = finish_call_expr (function, &call_args,
12927                                   /*disallow_virtual=*/qualified_p,
12928                                   koenig_p,
12929                                   complain);
12930
12931         release_tree_vector (call_args);
12932
12933         return ret;
12934       }
12935
12936     case COND_EXPR:
12937       return build_x_conditional_expr
12938         (RECUR (TREE_OPERAND (t, 0)),
12939          RECUR (TREE_OPERAND (t, 1)),
12940          RECUR (TREE_OPERAND (t, 2)),
12941          complain);
12942
12943     case PSEUDO_DTOR_EXPR:
12944       return finish_pseudo_destructor_expr
12945         (RECUR (TREE_OPERAND (t, 0)),
12946          RECUR (TREE_OPERAND (t, 1)),
12947          RECUR (TREE_OPERAND (t, 2)));
12948
12949     case TREE_LIST:
12950       {
12951         tree purpose, value, chain;
12952
12953         if (t == void_list_node)
12954           return t;
12955
12956         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
12957             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
12958           {
12959             /* We have pack expansions, so expand those and
12960                create a new list out of it.  */
12961             tree purposevec = NULL_TREE;
12962             tree valuevec = NULL_TREE;
12963             tree chain;
12964             int i, len = -1;
12965
12966             /* Expand the argument expressions.  */
12967             if (TREE_PURPOSE (t))
12968               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
12969                                                  complain, in_decl);
12970             if (TREE_VALUE (t))
12971               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
12972                                                complain, in_decl);
12973
12974             /* Build the rest of the list.  */
12975             chain = TREE_CHAIN (t);
12976             if (chain && chain != void_type_node)
12977               chain = RECUR (chain);
12978
12979             /* Determine the number of arguments.  */
12980             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
12981               {
12982                 len = TREE_VEC_LENGTH (purposevec);
12983                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
12984               }
12985             else if (TREE_CODE (valuevec) == TREE_VEC)
12986               len = TREE_VEC_LENGTH (valuevec);
12987             else
12988               {
12989                 /* Since we only performed a partial substitution into
12990                    the argument pack, we only return a single list
12991                    node.  */
12992                 if (purposevec == TREE_PURPOSE (t)
12993                     && valuevec == TREE_VALUE (t)
12994                     && chain == TREE_CHAIN (t))
12995                   return t;
12996
12997                 return tree_cons (purposevec, valuevec, chain);
12998               }
12999             
13000             /* Convert the argument vectors into a TREE_LIST */
13001             i = len;
13002             while (i > 0)
13003               {
13004                 /* Grab the Ith values.  */
13005                 i--;
13006                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
13007                                      : NULL_TREE;
13008                 value 
13009                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
13010                              : NULL_TREE;
13011
13012                 /* Build the list (backwards).  */
13013                 chain = tree_cons (purpose, value, chain);
13014               }
13015
13016             return chain;
13017           }
13018
13019         purpose = TREE_PURPOSE (t);
13020         if (purpose)
13021           purpose = RECUR (purpose);
13022         value = TREE_VALUE (t);
13023         if (value)
13024           value = RECUR (value);
13025         chain = TREE_CHAIN (t);
13026         if (chain && chain != void_type_node)
13027           chain = RECUR (chain);
13028         if (purpose == TREE_PURPOSE (t)
13029             && value == TREE_VALUE (t)
13030             && chain == TREE_CHAIN (t))
13031           return t;
13032         return tree_cons (purpose, value, chain);
13033       }
13034
13035     case COMPONENT_REF:
13036       {
13037         tree object;
13038         tree object_type;
13039         tree member;
13040
13041         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
13042                                                      args, complain, in_decl);
13043         /* Remember that there was a reference to this entity.  */
13044         if (DECL_P (object))
13045           mark_used (object);
13046         object_type = TREE_TYPE (object);
13047
13048         member = TREE_OPERAND (t, 1);
13049         if (BASELINK_P (member))
13050           member = tsubst_baselink (member,
13051                                     non_reference (TREE_TYPE (object)),
13052                                     args, complain, in_decl);
13053         else
13054           member = tsubst_copy (member, args, complain, in_decl);
13055         if (member == error_mark_node)
13056           return error_mark_node;
13057
13058         if (object_type && !CLASS_TYPE_P (object_type))
13059           {
13060             if (SCALAR_TYPE_P (object_type))
13061               {
13062                 tree s = NULL_TREE;
13063                 tree dtor = member;
13064
13065                 if (TREE_CODE (dtor) == SCOPE_REF)
13066                   {
13067                     s = TREE_OPERAND (dtor, 0);
13068                     dtor = TREE_OPERAND (dtor, 1);
13069                   }
13070                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
13071                   {
13072                     dtor = TREE_OPERAND (dtor, 0);
13073                     if (TYPE_P (dtor))
13074                       return finish_pseudo_destructor_expr (object, s, dtor);
13075                   }
13076               }
13077           }
13078         else if (TREE_CODE (member) == SCOPE_REF
13079                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
13080           {
13081             tree tmpl;
13082             tree args;
13083
13084             /* Lookup the template functions now that we know what the
13085                scope is.  */
13086             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
13087             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
13088             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
13089                                             /*is_type_p=*/false,
13090                                             /*complain=*/false);
13091             if (BASELINK_P (member))
13092               {
13093                 BASELINK_FUNCTIONS (member)
13094                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
13095                               args);
13096                 member = (adjust_result_of_qualified_name_lookup
13097                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
13098                            object_type));
13099               }
13100             else
13101               {
13102                 qualified_name_lookup_error (object_type, tmpl, member,
13103                                              input_location);
13104                 return error_mark_node;
13105               }
13106           }
13107         else if (TREE_CODE (member) == SCOPE_REF
13108                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
13109                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
13110           {
13111             if (complain & tf_error)
13112               {
13113                 if (TYPE_P (TREE_OPERAND (member, 0)))
13114                   error ("%qT is not a class or namespace",
13115                          TREE_OPERAND (member, 0));
13116                 else
13117                   error ("%qD is not a class or namespace",
13118                          TREE_OPERAND (member, 0));
13119               }
13120             return error_mark_node;
13121           }
13122         else if (TREE_CODE (member) == FIELD_DECL)
13123           return finish_non_static_data_member (member, object, NULL_TREE);
13124
13125         return finish_class_member_access_expr (object, member,
13126                                                 /*template_p=*/false,
13127                                                 complain);
13128       }
13129
13130     case THROW_EXPR:
13131       return build_throw
13132         (RECUR (TREE_OPERAND (t, 0)));
13133
13134     case CONSTRUCTOR:
13135       {
13136         VEC(constructor_elt,gc) *n;
13137         constructor_elt *ce;
13138         unsigned HOST_WIDE_INT idx;
13139         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
13140         bool process_index_p;
13141         int newlen;
13142         bool need_copy_p = false;
13143         tree r;
13144
13145         if (type == error_mark_node)
13146           return error_mark_node;
13147
13148         /* digest_init will do the wrong thing if we let it.  */
13149         if (type && TYPE_PTRMEMFUNC_P (type))
13150           return t;
13151
13152         /* We do not want to process the index of aggregate
13153            initializers as they are identifier nodes which will be
13154            looked up by digest_init.  */
13155         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
13156
13157         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
13158         newlen = VEC_length (constructor_elt, n);
13159         FOR_EACH_VEC_ELT (constructor_elt, n, idx, ce)
13160           {
13161             if (ce->index && process_index_p)
13162               ce->index = RECUR (ce->index);
13163
13164             if (PACK_EXPANSION_P (ce->value))
13165               {
13166                 /* Substitute into the pack expansion.  */
13167                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
13168                                                   in_decl);
13169
13170                 if (ce->value == error_mark_node)
13171                   ;
13172                 else if (TREE_VEC_LENGTH (ce->value) == 1)
13173                   /* Just move the argument into place.  */
13174                   ce->value = TREE_VEC_ELT (ce->value, 0);
13175                 else
13176                   {
13177                     /* Update the length of the final CONSTRUCTOR
13178                        arguments vector, and note that we will need to
13179                        copy.*/
13180                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
13181                     need_copy_p = true;
13182                   }
13183               }
13184             else
13185               ce->value = RECUR (ce->value);
13186           }
13187
13188         if (need_copy_p)
13189           {
13190             VEC(constructor_elt,gc) *old_n = n;
13191
13192             n = VEC_alloc (constructor_elt, gc, newlen);
13193             FOR_EACH_VEC_ELT (constructor_elt, old_n, idx, ce)
13194               {
13195                 if (TREE_CODE (ce->value) == TREE_VEC)
13196                   {
13197                     int i, len = TREE_VEC_LENGTH (ce->value);
13198                     for (i = 0; i < len; ++i)
13199                       CONSTRUCTOR_APPEND_ELT (n, 0,
13200                                               TREE_VEC_ELT (ce->value, i));
13201                   }
13202                 else
13203                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
13204               }
13205           }
13206
13207         r = build_constructor (init_list_type_node, n);
13208         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
13209
13210         if (TREE_HAS_CONSTRUCTOR (t))
13211           return finish_compound_literal (type, r);
13212
13213         TREE_TYPE (r) = type;
13214         return r;
13215       }
13216
13217     case TYPEID_EXPR:
13218       {
13219         tree operand_0 = TREE_OPERAND (t, 0);
13220         if (TYPE_P (operand_0))
13221           {
13222             operand_0 = tsubst (operand_0, args, complain, in_decl);
13223             return get_typeid (operand_0);
13224           }
13225         else
13226           {
13227             operand_0 = RECUR (operand_0);
13228             return build_typeid (operand_0);
13229           }
13230       }
13231
13232     case VAR_DECL:
13233       if (!args)
13234         return t;
13235       /* Fall through */
13236
13237     case PARM_DECL:
13238       {
13239         tree r = tsubst_copy (t, args, complain, in_decl);
13240
13241         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
13242           /* If the original type was a reference, we'll be wrapped in
13243              the appropriate INDIRECT_REF.  */
13244           r = convert_from_reference (r);
13245         return r;
13246       }
13247
13248     case VA_ARG_EXPR:
13249       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
13250                              tsubst (TREE_TYPE (t), args, complain, in_decl));
13251
13252     case OFFSETOF_EXPR:
13253       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
13254
13255     case TRAIT_EXPR:
13256       {
13257         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
13258                                   complain, in_decl);
13259
13260         tree type2 = TRAIT_EXPR_TYPE2 (t);
13261         if (type2)
13262           type2 = tsubst_copy (type2, args, complain, in_decl);
13263         
13264         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
13265       }
13266
13267     case STMT_EXPR:
13268       {
13269         tree old_stmt_expr = cur_stmt_expr;
13270         tree stmt_expr = begin_stmt_expr ();
13271
13272         cur_stmt_expr = stmt_expr;
13273         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
13274                      integral_constant_expression_p);
13275         stmt_expr = finish_stmt_expr (stmt_expr, false);
13276         cur_stmt_expr = old_stmt_expr;
13277
13278         /* If the resulting list of expression statement is empty,
13279            fold it further into void_zero_node.  */
13280         if (empty_expr_stmt_p (stmt_expr))
13281           stmt_expr = void_zero_node;
13282
13283         return stmt_expr;
13284       }
13285
13286     case CONST_DECL:
13287       t = tsubst_copy (t, args, complain, in_decl);
13288       /* As in finish_id_expression, we resolve enumeration constants
13289          to their underlying values.  */
13290       if (TREE_CODE (t) == CONST_DECL)
13291         {
13292           used_types_insert (TREE_TYPE (t));
13293           return DECL_INITIAL (t);
13294         }
13295       return t;
13296
13297     case LAMBDA_EXPR:
13298       {
13299         tree r = build_lambda_expr ();
13300
13301         tree type = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
13302         TREE_TYPE (r) = type;
13303         CLASSTYPE_LAMBDA_EXPR (type) = r;
13304
13305         LAMBDA_EXPR_LOCATION (r)
13306           = LAMBDA_EXPR_LOCATION (t);
13307         LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
13308           = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
13309         LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
13310         LAMBDA_EXPR_DISCRIMINATOR (r)
13311           = (LAMBDA_EXPR_DISCRIMINATOR (t));
13312         LAMBDA_EXPR_CAPTURE_LIST (r)
13313           = RECUR (LAMBDA_EXPR_CAPTURE_LIST (t));
13314         LAMBDA_EXPR_THIS_CAPTURE (r)
13315           = RECUR (LAMBDA_EXPR_THIS_CAPTURE (t));
13316         LAMBDA_EXPR_EXTRA_SCOPE (r)
13317           = RECUR (LAMBDA_EXPR_EXTRA_SCOPE (t));
13318
13319         /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
13320         determine_visibility (TYPE_NAME (type));
13321         /* Now that we know visibility, instantiate the type so we have a
13322            declaration of the op() for later calls to lambda_function.  */
13323         complete_type (type);
13324
13325         type = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
13326         if (type)
13327           apply_lambda_return_type (r, type);
13328
13329         return build_lambda_object (r);
13330       }
13331
13332     case TARGET_EXPR:
13333       /* We can get here for a constant initializer of non-dependent type.
13334          FIXME stop folding in cp_parser_initializer_clause.  */
13335       gcc_assert (TREE_CONSTANT (t));
13336       return get_target_expr (RECUR (TARGET_EXPR_INITIAL (t)));
13337
13338     default:
13339       /* Handle Objective-C++ constructs, if appropriate.  */
13340       {
13341         tree subst
13342           = objcp_tsubst_copy_and_build (t, args, complain,
13343                                          in_decl, /*function_p=*/false);
13344         if (subst)
13345           return subst;
13346       }
13347       return tsubst_copy (t, args, complain, in_decl);
13348     }
13349
13350 #undef RECUR
13351 }
13352
13353 /* Verify that the instantiated ARGS are valid. For type arguments,
13354    make sure that the type's linkage is ok. For non-type arguments,
13355    make sure they are constants if they are integral or enumerations.
13356    Emit an error under control of COMPLAIN, and return TRUE on error.  */
13357
13358 static bool
13359 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
13360 {
13361   if (ARGUMENT_PACK_P (t))
13362     {
13363       tree vec = ARGUMENT_PACK_ARGS (t);
13364       int len = TREE_VEC_LENGTH (vec);
13365       bool result = false;
13366       int i;
13367
13368       for (i = 0; i < len; ++i)
13369         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
13370           result = true;
13371       return result;
13372     }
13373   else if (TYPE_P (t))
13374     {
13375       /* [basic.link]: A name with no linkage (notably, the name
13376          of a class or enumeration declared in a local scope)
13377          shall not be used to declare an entity with linkage.
13378          This implies that names with no linkage cannot be used as
13379          template arguments
13380
13381          DR 757 relaxes this restriction for C++0x.  */
13382       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
13383                  : no_linkage_check (t, /*relaxed_p=*/false));
13384
13385       if (nt)
13386         {
13387           /* DR 488 makes use of a type with no linkage cause
13388              type deduction to fail.  */
13389           if (complain & tf_error)
13390             {
13391               if (TYPE_ANONYMOUS_P (nt))
13392                 error ("%qT is/uses anonymous type", t);
13393               else
13394                 error ("template argument for %qD uses local type %qT",
13395                        tmpl, t);
13396             }
13397           return true;
13398         }
13399       /* In order to avoid all sorts of complications, we do not
13400          allow variably-modified types as template arguments.  */
13401       else if (variably_modified_type_p (t, NULL_TREE))
13402         {
13403           if (complain & tf_error)
13404             error ("%qT is a variably modified type", t);
13405           return true;
13406         }
13407     }
13408   /* A non-type argument of integral or enumerated type must be a
13409      constant.  */
13410   else if (TREE_TYPE (t)
13411            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
13412            && !TREE_CONSTANT (t))
13413     {
13414       if (complain & tf_error)
13415         error ("integral expression %qE is not constant", t);
13416       return true;
13417     }
13418   return false;
13419 }
13420
13421 static bool
13422 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
13423 {
13424   int ix, len = DECL_NTPARMS (tmpl);
13425   bool result = false;
13426
13427   for (ix = 0; ix != len; ix++)
13428     {
13429       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
13430         result = true;
13431     }
13432   if (result && (complain & tf_error))
13433     error ("  trying to instantiate %qD", tmpl);
13434   return result;
13435 }
13436
13437 /* Instantiate the indicated variable or function template TMPL with
13438    the template arguments in TARG_PTR.  */
13439
13440 tree
13441 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
13442 {
13443   tree targ_ptr = orig_args;
13444   tree fndecl;
13445   tree gen_tmpl;
13446   tree spec;
13447   HOST_WIDE_INT saved_processing_template_decl;
13448
13449   if (tmpl == error_mark_node)
13450     return error_mark_node;
13451
13452   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
13453
13454   /* If this function is a clone, handle it specially.  */
13455   if (DECL_CLONED_FUNCTION_P (tmpl))
13456     {
13457       tree spec;
13458       tree clone;
13459
13460       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
13461          DECL_CLONED_FUNCTION.  */
13462       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
13463                                    targ_ptr, complain);
13464       if (spec == error_mark_node)
13465         return error_mark_node;
13466
13467       /* Look for the clone.  */
13468       FOR_EACH_CLONE (clone, spec)
13469         if (DECL_NAME (clone) == DECL_NAME (tmpl))
13470           return clone;
13471       /* We should always have found the clone by now.  */
13472       gcc_unreachable ();
13473       return NULL_TREE;
13474     }
13475
13476   /* Check to see if we already have this specialization.  */
13477   gen_tmpl = most_general_template (tmpl);
13478   if (tmpl != gen_tmpl)
13479     /* The TMPL is a partial instantiation.  To get a full set of
13480        arguments we must add the arguments used to perform the
13481        partial instantiation.  */
13482     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
13483                                             targ_ptr);
13484
13485   /* It would be nice to avoid hashing here and then again in tsubst_decl,
13486      but it doesn't seem to be on the hot path.  */
13487   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
13488
13489   gcc_assert (tmpl == gen_tmpl
13490               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
13491                   == spec)
13492               || fndecl == NULL_TREE);
13493
13494   if (spec != NULL_TREE)
13495     return spec;
13496
13497   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
13498                                complain))
13499     return error_mark_node;
13500
13501   /* We are building a FUNCTION_DECL, during which the access of its
13502      parameters and return types have to be checked.  However this
13503      FUNCTION_DECL which is the desired context for access checking
13504      is not built yet.  We solve this chicken-and-egg problem by
13505      deferring all checks until we have the FUNCTION_DECL.  */
13506   push_deferring_access_checks (dk_deferred);
13507
13508   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
13509      (because, for example, we have encountered a non-dependent
13510      function call in the body of a template function and must now
13511      determine which of several overloaded functions will be called),
13512      within the instantiation itself we are not processing a
13513      template.  */  
13514   saved_processing_template_decl = processing_template_decl;
13515   processing_template_decl = 0;
13516   /* Substitute template parameters to obtain the specialization.  */
13517   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
13518                    targ_ptr, complain, gen_tmpl);
13519   processing_template_decl = saved_processing_template_decl;
13520   if (fndecl == error_mark_node)
13521     return error_mark_node;
13522
13523   /* Now we know the specialization, compute access previously
13524      deferred.  */
13525   push_access_scope (fndecl);
13526
13527   /* Some typedefs referenced from within the template code need to be access
13528      checked at template instantiation time, i.e now. These types were
13529      added to the template at parsing time. Let's get those and perfom
13530      the acces checks then.  */
13531   perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
13532   perform_deferred_access_checks ();
13533   pop_access_scope (fndecl);
13534   pop_deferring_access_checks ();
13535
13536   /* The DECL_TI_TEMPLATE should always be the immediate parent
13537      template, not the most general template.  */
13538   DECL_TI_TEMPLATE (fndecl) = tmpl;
13539
13540   /* If we've just instantiated the main entry point for a function,
13541      instantiate all the alternate entry points as well.  We do this
13542      by cloning the instantiation of the main entry point, not by
13543      instantiating the template clones.  */
13544   if (DECL_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (DECL_CHAIN (gen_tmpl)))
13545     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
13546
13547   return fndecl;
13548 }
13549
13550 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
13551    NARGS elements of the arguments that are being used when calling
13552    it.  TARGS is a vector into which the deduced template arguments
13553    are placed.
13554
13555    Return zero for success, 2 for an incomplete match that doesn't resolve
13556    all the types, and 1 for complete failure.  An error message will be
13557    printed only for an incomplete match.
13558
13559    If FN is a conversion operator, or we are trying to produce a specific
13560    specialization, RETURN_TYPE is the return type desired.
13561
13562    The EXPLICIT_TARGS are explicit template arguments provided via a
13563    template-id.
13564
13565    The parameter STRICT is one of:
13566
13567    DEDUCE_CALL:
13568      We are deducing arguments for a function call, as in
13569      [temp.deduct.call].
13570
13571    DEDUCE_CONV:
13572      We are deducing arguments for a conversion function, as in
13573      [temp.deduct.conv].
13574
13575    DEDUCE_EXACT:
13576      We are deducing arguments when doing an explicit instantiation
13577      as in [temp.explicit], when determining an explicit specialization
13578      as in [temp.expl.spec], or when taking the address of a function
13579      template, as in [temp.deduct.funcaddr].  */
13580
13581 int
13582 fn_type_unification (tree fn,
13583                      tree explicit_targs,
13584                      tree targs,
13585                      const tree *args,
13586                      unsigned int nargs,
13587                      tree return_type,
13588                      unification_kind_t strict,
13589                      int flags)
13590 {
13591   tree parms;
13592   tree fntype;
13593   int result;
13594   bool incomplete_argument_packs_p = false;
13595
13596   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
13597
13598   fntype = TREE_TYPE (fn);
13599   if (explicit_targs)
13600     {
13601       /* [temp.deduct]
13602
13603          The specified template arguments must match the template
13604          parameters in kind (i.e., type, nontype, template), and there
13605          must not be more arguments than there are parameters;
13606          otherwise type deduction fails.
13607
13608          Nontype arguments must match the types of the corresponding
13609          nontype template parameters, or must be convertible to the
13610          types of the corresponding nontype parameters as specified in
13611          _temp.arg.nontype_, otherwise type deduction fails.
13612
13613          All references in the function type of the function template
13614          to the corresponding template parameters are replaced by the
13615          specified template argument values.  If a substitution in a
13616          template parameter or in the function type of the function
13617          template results in an invalid type, type deduction fails.  */
13618       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
13619       int i, len = TREE_VEC_LENGTH (tparms);
13620       tree converted_args;
13621       bool incomplete = false;
13622
13623       if (explicit_targs == error_mark_node)
13624         return 1;
13625
13626       converted_args
13627         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
13628                                   /*require_all_args=*/false,
13629                                   /*use_default_args=*/false));
13630       if (converted_args == error_mark_node)
13631         return 1;
13632
13633       /* Substitute the explicit args into the function type.  This is
13634          necessary so that, for instance, explicitly declared function
13635          arguments can match null pointed constants.  If we were given
13636          an incomplete set of explicit args, we must not do semantic
13637          processing during substitution as we could create partial
13638          instantiations.  */
13639       for (i = 0; i < len; i++)
13640         {
13641           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13642           bool parameter_pack = false;
13643
13644           /* Dig out the actual parm.  */
13645           if (TREE_CODE (parm) == TYPE_DECL
13646               || TREE_CODE (parm) == TEMPLATE_DECL)
13647             {
13648               parm = TREE_TYPE (parm);
13649               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
13650             }
13651           else if (TREE_CODE (parm) == PARM_DECL)
13652             {
13653               parm = DECL_INITIAL (parm);
13654               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
13655             }
13656
13657           if (parameter_pack)
13658             {
13659               int level, idx;
13660               tree targ;
13661               template_parm_level_and_index (parm, &level, &idx);
13662
13663               /* Mark the argument pack as "incomplete". We could
13664                  still deduce more arguments during unification.  */
13665               targ = TMPL_ARG (converted_args, level, idx);
13666               if (targ)
13667                 {
13668                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
13669                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
13670                     = ARGUMENT_PACK_ARGS (targ);
13671                 }
13672
13673               /* We have some incomplete argument packs.  */
13674               incomplete_argument_packs_p = true;
13675             }
13676         }
13677
13678       if (incomplete_argument_packs_p)
13679         /* Any substitution is guaranteed to be incomplete if there
13680            are incomplete argument packs, because we can still deduce
13681            more arguments.  */
13682         incomplete = 1;
13683       else
13684         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
13685
13686       processing_template_decl += incomplete;
13687       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
13688       processing_template_decl -= incomplete;
13689
13690       if (fntype == error_mark_node)
13691         return 1;
13692
13693       /* Place the explicitly specified arguments in TARGS.  */
13694       for (i = NUM_TMPL_ARGS (converted_args); i--;)
13695         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
13696     }
13697
13698   /* Never do unification on the 'this' parameter.  */
13699   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
13700
13701   if (return_type)
13702     {
13703       tree *new_args;
13704
13705       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
13706       new_args = XALLOCAVEC (tree, nargs + 1);
13707       new_args[0] = return_type;
13708       memcpy (new_args + 1, args, nargs * sizeof (tree));
13709       args = new_args;
13710       ++nargs;
13711     }
13712
13713   /* We allow incomplete unification without an error message here
13714      because the standard doesn't seem to explicitly prohibit it.  Our
13715      callers must be ready to deal with unification failures in any
13716      event.  */
13717   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
13718                                   targs, parms, args, nargs, /*subr=*/0,
13719                                   strict, flags);
13720
13721   if (result == 0 && incomplete_argument_packs_p)
13722     {
13723       int i, len = NUM_TMPL_ARGS (targs);
13724
13725       /* Clear the "incomplete" flags on all argument packs.  */
13726       for (i = 0; i < len; i++)
13727         {
13728           tree arg = TREE_VEC_ELT (targs, i);
13729           if (ARGUMENT_PACK_P (arg))
13730             {
13731               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
13732               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
13733             }
13734         }
13735     }
13736
13737   /* Now that we have bindings for all of the template arguments,
13738      ensure that the arguments deduced for the template template
13739      parameters have compatible template parameter lists.  We cannot
13740      check this property before we have deduced all template
13741      arguments, because the template parameter types of a template
13742      template parameter might depend on prior template parameters
13743      deduced after the template template parameter.  The following
13744      ill-formed example illustrates this issue:
13745
13746        template<typename T, template<T> class C> void f(C<5>, T);
13747
13748        template<int N> struct X {};
13749
13750        void g() {
13751          f(X<5>(), 5l); // error: template argument deduction fails
13752        }
13753
13754      The template parameter list of 'C' depends on the template type
13755      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
13756      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
13757      time that we deduce 'C'.  */
13758   if (result == 0
13759       && !template_template_parm_bindings_ok_p 
13760            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
13761     return 1;
13762
13763   if (result == 0)
13764     /* All is well so far.  Now, check:
13765
13766        [temp.deduct]
13767
13768        When all template arguments have been deduced, all uses of
13769        template parameters in nondeduced contexts are replaced with
13770        the corresponding deduced argument values.  If the
13771        substitution results in an invalid type, as described above,
13772        type deduction fails.  */
13773     {
13774       tree substed = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
13775       if (substed == error_mark_node)
13776         return 1;
13777
13778       /* If we're looking for an exact match, check that what we got
13779          is indeed an exact match.  It might not be if some template
13780          parameters are used in non-deduced contexts.  */
13781       if (strict == DEDUCE_EXACT)
13782         {
13783           unsigned int i;
13784
13785           tree sarg
13786             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
13787           if (return_type)
13788             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
13789           for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
13790             if (!same_type_p (args[i], TREE_VALUE (sarg)))
13791               return 1;
13792         }
13793     }
13794
13795   return result;
13796 }
13797
13798 /* Adjust types before performing type deduction, as described in
13799    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
13800    sections are symmetric.  PARM is the type of a function parameter
13801    or the return type of the conversion function.  ARG is the type of
13802    the argument passed to the call, or the type of the value
13803    initialized with the result of the conversion function.
13804    ARG_EXPR is the original argument expression, which may be null.  */
13805
13806 static int
13807 maybe_adjust_types_for_deduction (unification_kind_t strict,
13808                                   tree* parm,
13809                                   tree* arg,
13810                                   tree arg_expr)
13811 {
13812   int result = 0;
13813
13814   switch (strict)
13815     {
13816     case DEDUCE_CALL:
13817       break;
13818
13819     case DEDUCE_CONV:
13820       {
13821         /* Swap PARM and ARG throughout the remainder of this
13822            function; the handling is precisely symmetric since PARM
13823            will initialize ARG rather than vice versa.  */
13824         tree* temp = parm;
13825         parm = arg;
13826         arg = temp;
13827         break;
13828       }
13829
13830     case DEDUCE_EXACT:
13831       /* Core issue #873: Do the DR606 thing (see below) for these cases,
13832          too, but here handle it by stripping the reference from PARM
13833          rather than by adding it to ARG.  */
13834       if (TREE_CODE (*parm) == REFERENCE_TYPE
13835           && TYPE_REF_IS_RVALUE (*parm)
13836           && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13837           && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13838           && TREE_CODE (*arg) == REFERENCE_TYPE
13839           && !TYPE_REF_IS_RVALUE (*arg))
13840         *parm = TREE_TYPE (*parm);
13841       /* Nothing else to do in this case.  */
13842       return 0;
13843
13844     default:
13845       gcc_unreachable ();
13846     }
13847
13848   if (TREE_CODE (*parm) != REFERENCE_TYPE)
13849     {
13850       /* [temp.deduct.call]
13851
13852          If P is not a reference type:
13853
13854          --If A is an array type, the pointer type produced by the
13855          array-to-pointer standard conversion (_conv.array_) is
13856          used in place of A for type deduction; otherwise,
13857
13858          --If A is a function type, the pointer type produced by
13859          the function-to-pointer standard conversion
13860          (_conv.func_) is used in place of A for type deduction;
13861          otherwise,
13862
13863          --If A is a cv-qualified type, the top level
13864          cv-qualifiers of A's type are ignored for type
13865          deduction.  */
13866       if (TREE_CODE (*arg) == ARRAY_TYPE)
13867         *arg = build_pointer_type (TREE_TYPE (*arg));
13868       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
13869         *arg = build_pointer_type (*arg);
13870       else
13871         *arg = TYPE_MAIN_VARIANT (*arg);
13872     }
13873
13874   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
13875      of the form T&&, where T is a template parameter, and the argument
13876      is an lvalue, T is deduced as A& */
13877   if (TREE_CODE (*parm) == REFERENCE_TYPE
13878       && TYPE_REF_IS_RVALUE (*parm)
13879       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13880       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13881       && arg_expr && real_lvalue_p (arg_expr))
13882     *arg = build_reference_type (*arg);
13883
13884   /* [temp.deduct.call]
13885
13886      If P is a cv-qualified type, the top level cv-qualifiers
13887      of P's type are ignored for type deduction.  If P is a
13888      reference type, the type referred to by P is used for
13889      type deduction.  */
13890   *parm = TYPE_MAIN_VARIANT (*parm);
13891   if (TREE_CODE (*parm) == REFERENCE_TYPE)
13892     {
13893       *parm = TREE_TYPE (*parm);
13894       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
13895     }
13896
13897   /* DR 322. For conversion deduction, remove a reference type on parm
13898      too (which has been swapped into ARG).  */
13899   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
13900     *arg = TREE_TYPE (*arg);
13901
13902   return result;
13903 }
13904
13905 /* Most parms like fn_type_unification.
13906
13907    If SUBR is 1, we're being called recursively (to unify the
13908    arguments of a function or method parameter of a function
13909    template). */
13910
13911 static int
13912 type_unification_real (tree tparms,
13913                        tree targs,
13914                        tree xparms,
13915                        const tree *xargs,
13916                        unsigned int xnargs,
13917                        int subr,
13918                        unification_kind_t strict,
13919                        int flags)
13920 {
13921   tree parm, arg, arg_expr;
13922   int i;
13923   int ntparms = TREE_VEC_LENGTH (tparms);
13924   int sub_strict;
13925   int saw_undeduced = 0;
13926   tree parms;
13927   const tree *args;
13928   unsigned int nargs;
13929   unsigned int ia;
13930
13931   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
13932   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
13933   gcc_assert (ntparms > 0);
13934
13935   /* Reset the number of non-defaulted template arguments contained
13936      in in TARGS.  */
13937   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
13938
13939   switch (strict)
13940     {
13941     case DEDUCE_CALL:
13942       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
13943                     | UNIFY_ALLOW_DERIVED);
13944       break;
13945
13946     case DEDUCE_CONV:
13947       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
13948       break;
13949
13950     case DEDUCE_EXACT:
13951       sub_strict = UNIFY_ALLOW_NONE;
13952       break;
13953
13954     default:
13955       gcc_unreachable ();
13956     }
13957
13958  again:
13959   parms = xparms;
13960   args = xargs;
13961   nargs = xnargs;
13962
13963   ia = 0;
13964   while (parms && parms != void_list_node
13965          && ia < nargs)
13966     {
13967       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13968         break;
13969
13970       parm = TREE_VALUE (parms);
13971       parms = TREE_CHAIN (parms);
13972       arg = args[ia];
13973       ++ia;
13974       arg_expr = NULL;
13975
13976       if (arg == error_mark_node)
13977         return 1;
13978       if (arg == unknown_type_node)
13979         /* We can't deduce anything from this, but we might get all the
13980            template args from other function args.  */
13981         continue;
13982
13983       /* Conversions will be performed on a function argument that
13984          corresponds with a function parameter that contains only
13985          non-deducible template parameters and explicitly specified
13986          template parameters.  */
13987       if (!uses_template_parms (parm))
13988         {
13989           tree type;
13990
13991           if (!TYPE_P (arg))
13992             type = TREE_TYPE (arg);
13993           else
13994             type = arg;
13995
13996           if (same_type_p (parm, type))
13997             continue;
13998           if (strict != DEDUCE_EXACT
13999               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
14000                                   flags))
14001             continue;
14002
14003           return 1;
14004         }
14005
14006       if (!TYPE_P (arg))
14007         {
14008           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
14009           if (type_unknown_p (arg))
14010             {
14011               /* [temp.deduct.type] 
14012
14013                  A template-argument can be deduced from a pointer to
14014                  function or pointer to member function argument if
14015                  the set of overloaded functions does not contain
14016                  function templates and at most one of a set of
14017                  overloaded functions provides a unique match.  */
14018               if (resolve_overloaded_unification
14019                   (tparms, targs, parm, arg, strict, sub_strict))
14020                 continue;
14021
14022               return 1;
14023             }
14024           arg_expr = arg;
14025           arg = unlowered_expr_type (arg);
14026           if (arg == error_mark_node)
14027             return 1;
14028         }
14029
14030       {
14031         int arg_strict = sub_strict;
14032
14033         if (!subr)
14034           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
14035                                                           arg_expr);
14036
14037         if (arg == init_list_type_node && arg_expr)
14038           arg = arg_expr;
14039         if (unify (tparms, targs, parm, arg, arg_strict))
14040           return 1;
14041       }
14042     }
14043
14044
14045   if (parms 
14046       && parms != void_list_node
14047       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
14048     {
14049       /* Unify the remaining arguments with the pack expansion type.  */
14050       tree argvec;
14051       tree parmvec = make_tree_vec (1);
14052
14053       /* Allocate a TREE_VEC and copy in all of the arguments */ 
14054       argvec = make_tree_vec (nargs - ia);
14055       for (i = 0; ia < nargs; ++ia, ++i)
14056         TREE_VEC_ELT (argvec, i) = args[ia];
14057
14058       /* Copy the parameter into parmvec.  */
14059       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
14060       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
14061                                 /*call_args_p=*/true, /*subr=*/subr))
14062         return 1;
14063
14064       /* Advance to the end of the list of parameters.  */
14065       parms = TREE_CHAIN (parms);
14066     }
14067
14068   /* Fail if we've reached the end of the parm list, and more args
14069      are present, and the parm list isn't variadic.  */
14070   if (ia < nargs && parms == void_list_node)
14071     return 1;
14072   /* Fail if parms are left and they don't have default values.  */
14073   if (parms && parms != void_list_node
14074       && TREE_PURPOSE (parms) == NULL_TREE)
14075     return 1;
14076
14077   if (!subr)
14078     for (i = 0; i < ntparms; i++)
14079       if (!TREE_VEC_ELT (targs, i))
14080         {
14081           tree tparm;
14082
14083           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
14084             continue;
14085
14086           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
14087
14088           /* If this is an undeduced nontype parameter that depends on
14089              a type parameter, try another pass; its type may have been
14090              deduced from a later argument than the one from which
14091              this parameter can be deduced.  */
14092           if (TREE_CODE (tparm) == PARM_DECL
14093               && uses_template_parms (TREE_TYPE (tparm))
14094               && !saw_undeduced++)
14095             goto again;
14096
14097           /* Core issue #226 (C++0x) [temp.deduct]:
14098
14099                If a template argument has not been deduced, its
14100                default template argument, if any, is used. 
14101
14102              When we are in C++98 mode, TREE_PURPOSE will either
14103              be NULL_TREE or ERROR_MARK_NODE, so we do not need
14104              to explicitly check cxx_dialect here.  */
14105           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
14106             {
14107               tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
14108               tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
14109               arg = tsubst_template_arg (arg, targs, tf_none, NULL_TREE);
14110               arg = convert_template_argument (parm, arg, targs, tf_none,
14111                                                i, NULL_TREE);
14112               if (arg == error_mark_node)
14113                 return 1;
14114               else
14115                 {
14116                   TREE_VEC_ELT (targs, i) = arg;
14117                   /* The position of the first default template argument,
14118                      is also the number of non-defaulted arguments in TARGS.
14119                      Record that.  */
14120                   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
14121                     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
14122                   continue;
14123                 }
14124             }
14125
14126           /* If the type parameter is a parameter pack, then it will
14127              be deduced to an empty parameter pack.  */
14128           if (template_parameter_pack_p (tparm))
14129             {
14130               tree arg;
14131
14132               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
14133                 {
14134                   arg = make_node (NONTYPE_ARGUMENT_PACK);
14135                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
14136                   TREE_CONSTANT (arg) = 1;
14137                 }
14138               else
14139                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
14140
14141               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
14142
14143               TREE_VEC_ELT (targs, i) = arg;
14144               continue;
14145             }
14146
14147           return 2;
14148         }
14149 #ifdef ENABLE_CHECKING
14150   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
14151     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
14152 #endif
14153
14154   return 0;
14155 }
14156
14157 /* Subroutine of type_unification_real.  Args are like the variables
14158    at the call site.  ARG is an overloaded function (or template-id);
14159    we try deducing template args from each of the overloads, and if
14160    only one succeeds, we go with that.  Modifies TARGS and returns
14161    true on success.  */
14162
14163 static bool
14164 resolve_overloaded_unification (tree tparms,
14165                                 tree targs,
14166                                 tree parm,
14167                                 tree arg,
14168                                 unification_kind_t strict,
14169                                 int sub_strict)
14170 {
14171   tree tempargs = copy_node (targs);
14172   int good = 0;
14173   tree goodfn = NULL_TREE;
14174   bool addr_p;
14175
14176   if (TREE_CODE (arg) == ADDR_EXPR)
14177     {
14178       arg = TREE_OPERAND (arg, 0);
14179       addr_p = true;
14180     }
14181   else
14182     addr_p = false;
14183
14184   if (TREE_CODE (arg) == COMPONENT_REF)
14185     /* Handle `&x' where `x' is some static or non-static member
14186        function name.  */
14187     arg = TREE_OPERAND (arg, 1);
14188
14189   if (TREE_CODE (arg) == OFFSET_REF)
14190     arg = TREE_OPERAND (arg, 1);
14191
14192   /* Strip baselink information.  */
14193   if (BASELINK_P (arg))
14194     arg = BASELINK_FUNCTIONS (arg);
14195
14196   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
14197     {
14198       /* If we got some explicit template args, we need to plug them into
14199          the affected templates before we try to unify, in case the
14200          explicit args will completely resolve the templates in question.  */
14201
14202       tree expl_subargs = TREE_OPERAND (arg, 1);
14203       arg = TREE_OPERAND (arg, 0);
14204
14205       for (; arg; arg = OVL_NEXT (arg))
14206         {
14207           tree fn = OVL_CURRENT (arg);
14208           tree subargs, elem;
14209
14210           if (TREE_CODE (fn) != TEMPLATE_DECL)
14211             continue;
14212
14213           ++processing_template_decl;
14214           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
14215                                   expl_subargs, /*check_ret=*/false);
14216           if (subargs)
14217             {
14218               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
14219               if (try_one_overload (tparms, targs, tempargs, parm,
14220                                     elem, strict, sub_strict, addr_p)
14221                   && (!goodfn || !decls_match (goodfn, elem)))
14222                 {
14223                   goodfn = elem;
14224                   ++good;
14225                 }
14226             }
14227           --processing_template_decl;
14228         }
14229     }
14230   else if (TREE_CODE (arg) != OVERLOAD
14231            && TREE_CODE (arg) != FUNCTION_DECL)
14232     /* If ARG is, for example, "(0, &f)" then its type will be unknown
14233        -- but the deduction does not succeed because the expression is
14234        not just the function on its own.  */
14235     return false;
14236   else
14237     for (; arg; arg = OVL_NEXT (arg))
14238       if (try_one_overload (tparms, targs, tempargs, parm,
14239                             TREE_TYPE (OVL_CURRENT (arg)),
14240                             strict, sub_strict, addr_p)
14241           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
14242         {
14243           goodfn = OVL_CURRENT (arg);
14244           ++good;
14245         }
14246
14247   /* [temp.deduct.type] A template-argument can be deduced from a pointer
14248      to function or pointer to member function argument if the set of
14249      overloaded functions does not contain function templates and at most
14250      one of a set of overloaded functions provides a unique match.
14251
14252      So if we found multiple possibilities, we return success but don't
14253      deduce anything.  */
14254
14255   if (good == 1)
14256     {
14257       int i = TREE_VEC_LENGTH (targs);
14258       for (; i--; )
14259         if (TREE_VEC_ELT (tempargs, i))
14260           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
14261     }
14262   if (good)
14263     return true;
14264
14265   return false;
14266 }
14267
14268 /* Core DR 115: In contexts where deduction is done and fails, or in
14269    contexts where deduction is not done, if a template argument list is
14270    specified and it, along with any default template arguments, identifies
14271    a single function template specialization, then the template-id is an
14272    lvalue for the function template specialization.  */
14273
14274 tree
14275 resolve_nondeduced_context (tree orig_expr)
14276 {
14277   tree expr, offset, baselink;
14278   bool addr;
14279
14280   if (!type_unknown_p (orig_expr))
14281     return orig_expr;
14282
14283   expr = orig_expr;
14284   addr = false;
14285   offset = NULL_TREE;
14286   baselink = NULL_TREE;
14287
14288   if (TREE_CODE (expr) == ADDR_EXPR)
14289     {
14290       expr = TREE_OPERAND (expr, 0);
14291       addr = true;
14292     }
14293   if (TREE_CODE (expr) == OFFSET_REF)
14294     {
14295       offset = expr;
14296       expr = TREE_OPERAND (expr, 1);
14297     }
14298   if (TREE_CODE (expr) == BASELINK)
14299     {
14300       baselink = expr;
14301       expr = BASELINK_FUNCTIONS (expr);
14302     }
14303
14304   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
14305     {
14306       int good = 0;
14307       tree goodfn = NULL_TREE;
14308
14309       /* If we got some explicit template args, we need to plug them into
14310          the affected templates before we try to unify, in case the
14311          explicit args will completely resolve the templates in question.  */
14312
14313       tree expl_subargs = TREE_OPERAND (expr, 1);
14314       tree arg = TREE_OPERAND (expr, 0);
14315       tree badfn = NULL_TREE;
14316       tree badargs = NULL_TREE;
14317
14318       for (; arg; arg = OVL_NEXT (arg))
14319         {
14320           tree fn = OVL_CURRENT (arg);
14321           tree subargs, elem;
14322
14323           if (TREE_CODE (fn) != TEMPLATE_DECL)
14324             continue;
14325
14326           ++processing_template_decl;
14327           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
14328                                   expl_subargs, /*check_ret=*/false);
14329           if (subargs && !any_dependent_template_arguments_p (subargs))
14330             {
14331               elem = instantiate_template (fn, subargs, tf_none);
14332               if (elem == error_mark_node)
14333                 {
14334                   badfn = fn;
14335                   badargs = subargs;
14336                 }
14337               else if (elem && (!goodfn || !decls_match (goodfn, elem)))
14338                 {
14339                   goodfn = elem;
14340                   ++good;
14341                 }
14342             }
14343           --processing_template_decl;
14344         }
14345       if (good == 1)
14346         {
14347           expr = goodfn;
14348           if (baselink)
14349             expr = build_baselink (BASELINK_BINFO (baselink),
14350                                    BASELINK_ACCESS_BINFO (baselink),
14351                                    expr, BASELINK_OPTYPE (baselink));
14352           if (offset)
14353             {
14354               tree base
14355                 = TYPE_MAIN_VARIANT (TREE_TYPE (TREE_OPERAND (offset, 0)));
14356               expr = build_offset_ref (base, expr, addr);
14357             }
14358           if (addr)
14359             expr = cp_build_addr_expr (expr, tf_warning_or_error);
14360           return expr;
14361         }
14362       else if (good == 0 && badargs)
14363         /* There were no good options and at least one bad one, so let the
14364            user know what the problem is.  */
14365         instantiate_template (badfn, badargs, tf_warning_or_error);
14366     }
14367   return orig_expr;
14368 }
14369
14370 /* Subroutine of resolve_overloaded_unification; does deduction for a single
14371    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
14372    different overloads deduce different arguments for a given parm.
14373    ADDR_P is true if the expression for which deduction is being
14374    performed was of the form "& fn" rather than simply "fn".
14375
14376    Returns 1 on success.  */
14377
14378 static int
14379 try_one_overload (tree tparms,
14380                   tree orig_targs,
14381                   tree targs,
14382                   tree parm,
14383                   tree arg,
14384                   unification_kind_t strict,
14385                   int sub_strict,
14386                   bool addr_p)
14387 {
14388   int nargs;
14389   tree tempargs;
14390   int i;
14391
14392   /* [temp.deduct.type] A template-argument can be deduced from a pointer
14393      to function or pointer to member function argument if the set of
14394      overloaded functions does not contain function templates and at most
14395      one of a set of overloaded functions provides a unique match.
14396
14397      So if this is a template, just return success.  */
14398
14399   if (uses_template_parms (arg))
14400     return 1;
14401
14402   if (TREE_CODE (arg) == METHOD_TYPE)
14403     arg = build_ptrmemfunc_type (build_pointer_type (arg));
14404   else if (addr_p)
14405     arg = build_pointer_type (arg);
14406
14407   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
14408
14409   /* We don't copy orig_targs for this because if we have already deduced
14410      some template args from previous args, unify would complain when we
14411      try to deduce a template parameter for the same argument, even though
14412      there isn't really a conflict.  */
14413   nargs = TREE_VEC_LENGTH (targs);
14414   tempargs = make_tree_vec (nargs);
14415
14416   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
14417     return 0;
14418
14419   /* First make sure we didn't deduce anything that conflicts with
14420      explicitly specified args.  */
14421   for (i = nargs; i--; )
14422     {
14423       tree elt = TREE_VEC_ELT (tempargs, i);
14424       tree oldelt = TREE_VEC_ELT (orig_targs, i);
14425
14426       if (!elt)
14427         /*NOP*/;
14428       else if (uses_template_parms (elt))
14429         /* Since we're unifying against ourselves, we will fill in
14430            template args used in the function parm list with our own
14431            template parms.  Discard them.  */
14432         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
14433       else if (oldelt && !template_args_equal (oldelt, elt))
14434         return 0;
14435     }
14436
14437   for (i = nargs; i--; )
14438     {
14439       tree elt = TREE_VEC_ELT (tempargs, i);
14440
14441       if (elt)
14442         TREE_VEC_ELT (targs, i) = elt;
14443     }
14444
14445   return 1;
14446 }
14447
14448 /* PARM is a template class (perhaps with unbound template
14449    parameters).  ARG is a fully instantiated type.  If ARG can be
14450    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
14451    TARGS are as for unify.  */
14452
14453 static tree
14454 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
14455 {
14456   tree copy_of_targs;
14457
14458   if (!CLASSTYPE_TEMPLATE_INFO (arg)
14459       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
14460           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
14461     return NULL_TREE;
14462
14463   /* We need to make a new template argument vector for the call to
14464      unify.  If we used TARGS, we'd clutter it up with the result of
14465      the attempted unification, even if this class didn't work out.
14466      We also don't want to commit ourselves to all the unifications
14467      we've already done, since unification is supposed to be done on
14468      an argument-by-argument basis.  In other words, consider the
14469      following pathological case:
14470
14471        template <int I, int J, int K>
14472        struct S {};
14473
14474        template <int I, int J>
14475        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
14476
14477        template <int I, int J, int K>
14478        void f(S<I, J, K>, S<I, I, I>);
14479
14480        void g() {
14481          S<0, 0, 0> s0;
14482          S<0, 1, 2> s2;
14483
14484          f(s0, s2);
14485        }
14486
14487      Now, by the time we consider the unification involving `s2', we
14488      already know that we must have `f<0, 0, 0>'.  But, even though
14489      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
14490      because there are two ways to unify base classes of S<0, 1, 2>
14491      with S<I, I, I>.  If we kept the already deduced knowledge, we
14492      would reject the possibility I=1.  */
14493   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
14494
14495   /* If unification failed, we're done.  */
14496   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
14497              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
14498     return NULL_TREE;
14499
14500   return arg;
14501 }
14502
14503 /* Given a template type PARM and a class type ARG, find the unique
14504    base type in ARG that is an instance of PARM.  We do not examine
14505    ARG itself; only its base-classes.  If there is not exactly one
14506    appropriate base class, return NULL_TREE.  PARM may be the type of
14507    a partial specialization, as well as a plain template type.  Used
14508    by unify.  */
14509
14510 static tree
14511 get_template_base (tree tparms, tree targs, tree parm, tree arg)
14512 {
14513   tree rval = NULL_TREE;
14514   tree binfo;
14515
14516   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
14517
14518   binfo = TYPE_BINFO (complete_type (arg));
14519   if (!binfo)
14520     /* The type could not be completed.  */
14521     return NULL_TREE;
14522
14523   /* Walk in inheritance graph order.  The search order is not
14524      important, and this avoids multiple walks of virtual bases.  */
14525   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
14526     {
14527       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
14528
14529       if (r)
14530         {
14531           /* If there is more than one satisfactory baseclass, then:
14532
14533                [temp.deduct.call]
14534
14535               If they yield more than one possible deduced A, the type
14536               deduction fails.
14537
14538              applies.  */
14539           if (rval && !same_type_p (r, rval))
14540             return NULL_TREE;
14541
14542           rval = r;
14543         }
14544     }
14545
14546   return rval;
14547 }
14548
14549 /* Returns the level of DECL, which declares a template parameter.  */
14550
14551 static int
14552 template_decl_level (tree decl)
14553 {
14554   switch (TREE_CODE (decl))
14555     {
14556     case TYPE_DECL:
14557     case TEMPLATE_DECL:
14558       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
14559
14560     case PARM_DECL:
14561       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
14562
14563     default:
14564       gcc_unreachable ();
14565     }
14566   return 0;
14567 }
14568
14569 /* Decide whether ARG can be unified with PARM, considering only the
14570    cv-qualifiers of each type, given STRICT as documented for unify.
14571    Returns nonzero iff the unification is OK on that basis.  */
14572
14573 static int
14574 check_cv_quals_for_unify (int strict, tree arg, tree parm)
14575 {
14576   int arg_quals = cp_type_quals (arg);
14577   int parm_quals = cp_type_quals (parm);
14578
14579   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14580       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
14581     {
14582       /*  Although a CVR qualifier is ignored when being applied to a
14583           substituted template parameter ([8.3.2]/1 for example), that
14584           does not allow us to unify "const T" with "int&" because both
14585           types are not of the form "cv-list T" [14.8.2.5 temp.deduct.type].
14586           It is ok when we're allowing additional CV qualifiers
14587           at the outer level [14.8.2.1]/3,1st bullet.  */
14588       if ((TREE_CODE (arg) == REFERENCE_TYPE
14589            || TREE_CODE (arg) == FUNCTION_TYPE
14590            || TREE_CODE (arg) == METHOD_TYPE)
14591           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
14592         return 0;
14593
14594       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
14595           && (parm_quals & TYPE_QUAL_RESTRICT))
14596         return 0;
14597     }
14598
14599   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
14600       && (arg_quals & parm_quals) != parm_quals)
14601     return 0;
14602
14603   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
14604       && (parm_quals & arg_quals) != arg_quals)
14605     return 0;
14606
14607   return 1;
14608 }
14609
14610 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
14611 void 
14612 template_parm_level_and_index (tree parm, int* level, int* index)
14613 {
14614   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14615       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14616       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14617     {
14618       *index = TEMPLATE_TYPE_IDX (parm);
14619       *level = TEMPLATE_TYPE_LEVEL (parm);
14620     }
14621   else
14622     {
14623       *index = TEMPLATE_PARM_IDX (parm);
14624       *level = TEMPLATE_PARM_LEVEL (parm);
14625     }
14626 }
14627
14628 /* Unifies the remaining arguments in PACKED_ARGS with the pack
14629    expansion at the end of PACKED_PARMS. Returns 0 if the type
14630    deduction succeeds, 1 otherwise. STRICT is the same as in
14631    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
14632    call argument list. We'll need to adjust the arguments to make them
14633    types. SUBR tells us if this is from a recursive call to
14634    type_unification_real.  */
14635 int
14636 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
14637                       tree packed_args, int strict, bool call_args_p,
14638                       bool subr)
14639 {
14640   tree parm 
14641     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
14642   tree pattern = PACK_EXPANSION_PATTERN (parm);
14643   tree pack, packs = NULL_TREE;
14644   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
14645   int len = TREE_VEC_LENGTH (packed_args);
14646
14647   /* Determine the parameter packs we will be deducing from the
14648      pattern, and record their current deductions.  */
14649   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
14650        pack; pack = TREE_CHAIN (pack))
14651     {
14652       tree parm_pack = TREE_VALUE (pack);
14653       int idx, level;
14654
14655       /* Determine the index and level of this parameter pack.  */
14656       template_parm_level_and_index (parm_pack, &level, &idx);
14657
14658       /* Keep track of the parameter packs and their corresponding
14659          argument packs.  */
14660       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
14661       TREE_TYPE (packs) = make_tree_vec (len - start);
14662     }
14663   
14664   /* Loop through all of the arguments that have not yet been
14665      unified and unify each with the pattern.  */
14666   for (i = start; i < len; i++)
14667     {
14668       tree parm = pattern;
14669
14670       /* For each parameter pack, clear out the deduced value so that
14671          we can deduce it again.  */
14672       for (pack = packs; pack; pack = TREE_CHAIN (pack))
14673         {
14674           int idx, level;
14675           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14676
14677           TMPL_ARG (targs, level, idx) = NULL_TREE;
14678         }
14679
14680       /* Unify the pattern with the current argument.  */
14681       {
14682         tree arg = TREE_VEC_ELT (packed_args, i);
14683         tree arg_expr = NULL_TREE;
14684         int arg_strict = strict;
14685         bool skip_arg_p = false;
14686
14687         if (call_args_p)
14688           {
14689             int sub_strict;
14690
14691             /* This mirrors what we do in type_unification_real.  */
14692             switch (strict)
14693               {
14694               case DEDUCE_CALL:
14695                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
14696                               | UNIFY_ALLOW_MORE_CV_QUAL
14697                               | UNIFY_ALLOW_DERIVED);
14698                 break;
14699                 
14700               case DEDUCE_CONV:
14701                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
14702                 break;
14703                 
14704               case DEDUCE_EXACT:
14705                 sub_strict = UNIFY_ALLOW_NONE;
14706                 break;
14707                 
14708               default:
14709                 gcc_unreachable ();
14710               }
14711
14712             if (!TYPE_P (arg))
14713               {
14714                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
14715                 if (type_unknown_p (arg))
14716                   {
14717                     /* [temp.deduct.type] A template-argument can be
14718                        deduced from a pointer to function or pointer
14719                        to member function argument if the set of
14720                        overloaded functions does not contain function
14721                        templates and at most one of a set of
14722                        overloaded functions provides a unique
14723                        match.  */
14724
14725                     if (resolve_overloaded_unification
14726                         (tparms, targs, parm, arg,
14727                          (unification_kind_t) strict,
14728                          sub_strict)
14729                         != 0)
14730                       return 1;
14731                     skip_arg_p = true;
14732                   }
14733
14734                 if (!skip_arg_p)
14735                   {
14736                     arg_expr = arg;
14737                     arg = unlowered_expr_type (arg);
14738                     if (arg == error_mark_node)
14739                       return 1;
14740                   }
14741               }
14742       
14743             arg_strict = sub_strict;
14744
14745             if (!subr)
14746               arg_strict |= 
14747                 maybe_adjust_types_for_deduction ((unification_kind_t) strict,
14748                                                   &parm, &arg, arg_expr);
14749           }
14750
14751         if (!skip_arg_p)
14752           {
14753             /* For deduction from an init-list we need the actual list.  */
14754             if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
14755               arg = arg_expr;
14756             if (unify (tparms, targs, parm, arg, arg_strict))
14757               return 1;
14758           }
14759       }
14760
14761       /* For each parameter pack, collect the deduced value.  */
14762       for (pack = packs; pack; pack = TREE_CHAIN (pack))
14763         {
14764           int idx, level;
14765           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14766
14767           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
14768             TMPL_ARG (targs, level, idx);
14769         }
14770     }
14771
14772   /* Verify that the results of unification with the parameter packs
14773      produce results consistent with what we've seen before, and make
14774      the deduced argument packs available.  */
14775   for (pack = packs; pack; pack = TREE_CHAIN (pack))
14776     {
14777       tree old_pack = TREE_VALUE (pack);
14778       tree new_args = TREE_TYPE (pack);
14779       int i, len = TREE_VEC_LENGTH (new_args);
14780       int idx, level;
14781       bool nondeduced_p = false;
14782
14783       /* By default keep the original deduced argument pack.
14784          If necessary, more specific code is going to update the
14785          resulting deduced argument later down in this function.  */
14786       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14787       TMPL_ARG (targs, level, idx) = old_pack;
14788
14789       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
14790          actually deduce anything.  */
14791       for (i = 0; i < len && !nondeduced_p; ++i)
14792         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
14793           nondeduced_p = true;
14794       if (nondeduced_p)
14795         continue;
14796
14797       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
14798         {
14799           /* Prepend the explicit arguments onto NEW_ARGS.  */
14800           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14801           tree old_args = new_args;
14802           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
14803           int len = explicit_len + TREE_VEC_LENGTH (old_args);
14804
14805           /* Copy the explicit arguments.  */
14806           new_args = make_tree_vec (len);
14807           for (i = 0; i < explicit_len; i++)
14808             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
14809
14810           /* Copy the deduced arguments.  */
14811           for (; i < len; i++)
14812             TREE_VEC_ELT (new_args, i) =
14813               TREE_VEC_ELT (old_args, i - explicit_len);
14814         }
14815
14816       if (!old_pack)
14817         {
14818           tree result;
14819           /* Build the deduced *_ARGUMENT_PACK.  */
14820           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
14821             {
14822               result = make_node (NONTYPE_ARGUMENT_PACK);
14823               TREE_TYPE (result) = 
14824                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
14825               TREE_CONSTANT (result) = 1;
14826             }
14827           else
14828             result = cxx_make_type (TYPE_ARGUMENT_PACK);
14829
14830           SET_ARGUMENT_PACK_ARGS (result, new_args);
14831
14832           /* Note the deduced argument packs for this parameter
14833              pack.  */
14834           TMPL_ARG (targs, level, idx) = result;
14835         }
14836       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
14837                && (ARGUMENT_PACK_ARGS (old_pack) 
14838                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
14839         {
14840           /* We only had the explicitly-provided arguments before, but
14841              now we have a complete set of arguments.  */
14842           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14843
14844           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
14845           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
14846           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
14847         }
14848       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
14849                                     new_args))
14850         /* Inconsistent unification of this parameter pack.  */
14851         return 1;
14852     }
14853
14854   return 0;
14855 }
14856
14857 /* Deduce the value of template parameters.  TPARMS is the (innermost)
14858    set of template parameters to a template.  TARGS is the bindings
14859    for those template parameters, as determined thus far; TARGS may
14860    include template arguments for outer levels of template parameters
14861    as well.  PARM is a parameter to a template function, or a
14862    subcomponent of that parameter; ARG is the corresponding argument.
14863    This function attempts to match PARM with ARG in a manner
14864    consistent with the existing assignments in TARGS.  If more values
14865    are deduced, then TARGS is updated.
14866
14867    Returns 0 if the type deduction succeeds, 1 otherwise.  The
14868    parameter STRICT is a bitwise or of the following flags:
14869
14870      UNIFY_ALLOW_NONE:
14871        Require an exact match between PARM and ARG.
14872      UNIFY_ALLOW_MORE_CV_QUAL:
14873        Allow the deduced ARG to be more cv-qualified (by qualification
14874        conversion) than ARG.
14875      UNIFY_ALLOW_LESS_CV_QUAL:
14876        Allow the deduced ARG to be less cv-qualified than ARG.
14877      UNIFY_ALLOW_DERIVED:
14878        Allow the deduced ARG to be a template base class of ARG,
14879        or a pointer to a template base class of the type pointed to by
14880        ARG.
14881      UNIFY_ALLOW_INTEGER:
14882        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
14883        case for more information.
14884      UNIFY_ALLOW_OUTER_LEVEL:
14885        This is the outermost level of a deduction. Used to determine validity
14886        of qualification conversions. A valid qualification conversion must
14887        have const qualified pointers leading up to the inner type which
14888        requires additional CV quals, except at the outer level, where const
14889        is not required [conv.qual]. It would be normal to set this flag in
14890        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
14891      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
14892        This is the outermost level of a deduction, and PARM can be more CV
14893        qualified at this point.
14894      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
14895        This is the outermost level of a deduction, and PARM can be less CV
14896        qualified at this point.  */
14897
14898 static int
14899 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
14900 {
14901   int idx;
14902   tree targ;
14903   tree tparm;
14904   int strict_in = strict;
14905
14906   /* I don't think this will do the right thing with respect to types.
14907      But the only case I've seen it in so far has been array bounds, where
14908      signedness is the only information lost, and I think that will be
14909      okay.  */
14910   while (TREE_CODE (parm) == NOP_EXPR)
14911     parm = TREE_OPERAND (parm, 0);
14912
14913   if (arg == error_mark_node)
14914     return 1;
14915   if (arg == unknown_type_node
14916       || arg == init_list_type_node)
14917     /* We can't deduce anything from this, but we might get all the
14918        template args from other function args.  */
14919     return 0;
14920
14921   /* If PARM uses template parameters, then we can't bail out here,
14922      even if ARG == PARM, since we won't record unifications for the
14923      template parameters.  We might need them if we're trying to
14924      figure out which of two things is more specialized.  */
14925   if (arg == parm && !uses_template_parms (parm))
14926     return 0;
14927
14928   /* Handle init lists early, so the rest of the function can assume
14929      we're dealing with a type. */
14930   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
14931     {
14932       tree elt, elttype;
14933       unsigned i;
14934       tree orig_parm = parm;
14935
14936       /* Replace T with std::initializer_list<T> for deduction.  */
14937       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14938           && flag_deduce_init_list)
14939         parm = listify (parm);
14940
14941       if (!is_std_init_list (parm))
14942         /* We can only deduce from an initializer list argument if the
14943            parameter is std::initializer_list; otherwise this is a
14944            non-deduced context. */
14945         return 0;
14946
14947       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
14948
14949       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
14950         {
14951           int elt_strict = strict;
14952
14953           if (elt == error_mark_node)
14954             return 1;
14955
14956           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
14957             {
14958               tree type = TREE_TYPE (elt);
14959               /* It should only be possible to get here for a call.  */
14960               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
14961               elt_strict |= maybe_adjust_types_for_deduction
14962                 (DEDUCE_CALL, &elttype, &type, elt);
14963               elt = type;
14964             }
14965
14966           if (unify (tparms, targs, elttype, elt, elt_strict))
14967             return 1;
14968         }
14969
14970       /* If the std::initializer_list<T> deduction worked, replace the
14971          deduced A with std::initializer_list<A>.  */
14972       if (orig_parm != parm)
14973         {
14974           idx = TEMPLATE_TYPE_IDX (orig_parm);
14975           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14976           targ = listify (targ);
14977           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
14978         }
14979       return 0;
14980     }
14981
14982   /* Immediately reject some pairs that won't unify because of
14983      cv-qualification mismatches.  */
14984   if (TREE_CODE (arg) == TREE_CODE (parm)
14985       && TYPE_P (arg)
14986       /* It is the elements of the array which hold the cv quals of an array
14987          type, and the elements might be template type parms. We'll check
14988          when we recurse.  */
14989       && TREE_CODE (arg) != ARRAY_TYPE
14990       /* We check the cv-qualifiers when unifying with template type
14991          parameters below.  We want to allow ARG `const T' to unify with
14992          PARM `T' for example, when computing which of two templates
14993          is more specialized, for example.  */
14994       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
14995       && !check_cv_quals_for_unify (strict_in, arg, parm))
14996     return 1;
14997
14998   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
14999       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
15000     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
15001   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
15002   strict &= ~UNIFY_ALLOW_DERIVED;
15003   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
15004   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
15005
15006   switch (TREE_CODE (parm))
15007     {
15008     case TYPENAME_TYPE:
15009     case SCOPE_REF:
15010     case UNBOUND_CLASS_TEMPLATE:
15011       /* In a type which contains a nested-name-specifier, template
15012          argument values cannot be deduced for template parameters used
15013          within the nested-name-specifier.  */
15014       return 0;
15015
15016     case TEMPLATE_TYPE_PARM:
15017     case TEMPLATE_TEMPLATE_PARM:
15018     case BOUND_TEMPLATE_TEMPLATE_PARM:
15019       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
15020       if (tparm == error_mark_node)
15021         return 1;
15022
15023       if (TEMPLATE_TYPE_LEVEL (parm)
15024           != template_decl_level (tparm))
15025         /* The PARM is not one we're trying to unify.  Just check
15026            to see if it matches ARG.  */
15027         return (TREE_CODE (arg) == TREE_CODE (parm)
15028                 && same_type_p (parm, arg)) ? 0 : 1;
15029       idx = TEMPLATE_TYPE_IDX (parm);
15030       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
15031       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
15032
15033       /* Check for mixed types and values.  */
15034       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
15035            && TREE_CODE (tparm) != TYPE_DECL)
15036           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
15037               && TREE_CODE (tparm) != TEMPLATE_DECL))
15038         return 1;
15039
15040       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
15041         {
15042           /* ARG must be constructed from a template class or a template
15043              template parameter.  */
15044           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
15045               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
15046             return 1;
15047
15048           {
15049             tree parmvec = TYPE_TI_ARGS (parm);
15050             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
15051             tree full_argvec = add_to_template_args (targs, argvec);
15052             tree parm_parms 
15053               = DECL_INNERMOST_TEMPLATE_PARMS
15054                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
15055             int i, len;
15056             int parm_variadic_p = 0;
15057
15058             /* The resolution to DR150 makes clear that default
15059                arguments for an N-argument may not be used to bind T
15060                to a template template parameter with fewer than N
15061                parameters.  It is not safe to permit the binding of
15062                default arguments as an extension, as that may change
15063                the meaning of a conforming program.  Consider:
15064
15065                   struct Dense { static const unsigned int dim = 1; };
15066
15067                   template <template <typename> class View,
15068                             typename Block>
15069                   void operator+(float, View<Block> const&);
15070
15071                   template <typename Block,
15072                             unsigned int Dim = Block::dim>
15073                   struct Lvalue_proxy { operator float() const; };
15074
15075                   void
15076                   test_1d (void) {
15077                     Lvalue_proxy<Dense> p;
15078                     float b;
15079                     b + p;
15080                   }
15081
15082               Here, if Lvalue_proxy is permitted to bind to View, then
15083               the global operator+ will be used; if they are not, the
15084               Lvalue_proxy will be converted to float.  */
15085             if (coerce_template_parms (parm_parms,
15086                                        full_argvec,
15087                                        TYPE_TI_TEMPLATE (parm),
15088                                        tf_none,
15089                                        /*require_all_args=*/true,
15090                                        /*use_default_args=*/false)
15091                 == error_mark_node)
15092               return 1;
15093
15094             /* Deduce arguments T, i from TT<T> or TT<i>.
15095                We check each element of PARMVEC and ARGVEC individually
15096                rather than the whole TREE_VEC since they can have
15097                different number of elements.  */
15098
15099             parmvec = expand_template_argument_pack (parmvec);
15100             argvec = expand_template_argument_pack (argvec);
15101
15102             len = TREE_VEC_LENGTH (parmvec);
15103
15104             /* Check if the parameters end in a pack, making them
15105                variadic.  */
15106             if (len > 0
15107                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
15108               parm_variadic_p = 1;
15109             
15110             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
15111               return 1;
15112
15113              for (i = 0; i < len - parm_variadic_p; ++i)
15114               {
15115                 if (unify (tparms, targs,
15116                            TREE_VEC_ELT (parmvec, i),
15117                            TREE_VEC_ELT (argvec, i),
15118                            UNIFY_ALLOW_NONE))
15119                   return 1;
15120               }
15121
15122             if (parm_variadic_p
15123                 && unify_pack_expansion (tparms, targs,
15124                                          parmvec, argvec,
15125                                          UNIFY_ALLOW_NONE,
15126                                          /*call_args_p=*/false,
15127                                          /*subr=*/false))
15128               return 1;
15129           }
15130           arg = TYPE_TI_TEMPLATE (arg);
15131
15132           /* Fall through to deduce template name.  */
15133         }
15134
15135       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
15136           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
15137         {
15138           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
15139
15140           /* Simple cases: Value already set, does match or doesn't.  */
15141           if (targ != NULL_TREE && template_args_equal (targ, arg))
15142             return 0;
15143           else if (targ)
15144             return 1;
15145         }
15146       else
15147         {
15148           /* If PARM is `const T' and ARG is only `int', we don't have
15149              a match unless we are allowing additional qualification.
15150              If ARG is `const int' and PARM is just `T' that's OK;
15151              that binds `const int' to `T'.  */
15152           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
15153                                          arg, parm))
15154             return 1;
15155
15156           /* Consider the case where ARG is `const volatile int' and
15157              PARM is `const T'.  Then, T should be `volatile int'.  */
15158           arg = cp_build_qualified_type_real
15159             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
15160           if (arg == error_mark_node)
15161             return 1;
15162
15163           /* Simple cases: Value already set, does match or doesn't.  */
15164           if (targ != NULL_TREE && same_type_p (targ, arg))
15165             return 0;
15166           else if (targ)
15167             return 1;
15168
15169           /* Make sure that ARG is not a variable-sized array.  (Note
15170              that were talking about variable-sized arrays (like
15171              `int[n]'), rather than arrays of unknown size (like
15172              `int[]').)  We'll get very confused by such a type since
15173              the bound of the array will not be computable in an
15174              instantiation.  Besides, such types are not allowed in
15175              ISO C++, so we can do as we please here.  */
15176           if (variably_modified_type_p (arg, NULL_TREE))
15177             return 1;
15178
15179           /* Strip typedefs as in convert_template_argument.  */
15180           arg = strip_typedefs (arg);
15181         }
15182
15183       /* If ARG is a parameter pack or an expansion, we cannot unify
15184          against it unless PARM is also a parameter pack.  */
15185       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
15186           && !template_parameter_pack_p (parm))
15187         return 1;
15188
15189       /* If the argument deduction results is a METHOD_TYPE,
15190          then there is a problem.
15191          METHOD_TYPE doesn't map to any real C++ type the result of
15192          the deduction can not be of that type.  */
15193       if (TREE_CODE (arg) == METHOD_TYPE)
15194         return 1;
15195
15196       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
15197       return 0;
15198
15199     case TEMPLATE_PARM_INDEX:
15200       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
15201       if (tparm == error_mark_node)
15202         return 1;
15203
15204       if (TEMPLATE_PARM_LEVEL (parm)
15205           != template_decl_level (tparm))
15206         /* The PARM is not one we're trying to unify.  Just check
15207            to see if it matches ARG.  */
15208         return !(TREE_CODE (arg) == TREE_CODE (parm)
15209                  && cp_tree_equal (parm, arg));
15210
15211       idx = TEMPLATE_PARM_IDX (parm);
15212       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
15213
15214       if (targ)
15215         return !cp_tree_equal (targ, arg);
15216
15217       /* [temp.deduct.type] If, in the declaration of a function template
15218          with a non-type template-parameter, the non-type
15219          template-parameter is used in an expression in the function
15220          parameter-list and, if the corresponding template-argument is
15221          deduced, the template-argument type shall match the type of the
15222          template-parameter exactly, except that a template-argument
15223          deduced from an array bound may be of any integral type.
15224          The non-type parameter might use already deduced type parameters.  */
15225       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
15226       if (!TREE_TYPE (arg))
15227         /* Template-parameter dependent expression.  Just accept it for now.
15228            It will later be processed in convert_template_argument.  */
15229         ;
15230       else if (same_type_p (TREE_TYPE (arg), tparm))
15231         /* OK */;
15232       else if ((strict & UNIFY_ALLOW_INTEGER)
15233                && (TREE_CODE (tparm) == INTEGER_TYPE
15234                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
15235         /* Convert the ARG to the type of PARM; the deduced non-type
15236            template argument must exactly match the types of the
15237            corresponding parameter.  */
15238         arg = fold (build_nop (tparm, arg));
15239       else if (uses_template_parms (tparm))
15240         /* We haven't deduced the type of this parameter yet.  Try again
15241            later.  */
15242         return 0;
15243       else
15244         return 1;
15245
15246       /* If ARG is a parameter pack or an expansion, we cannot unify
15247          against it unless PARM is also a parameter pack.  */
15248       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
15249           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
15250         return 1;
15251
15252       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
15253       return 0;
15254
15255     case PTRMEM_CST:
15256      {
15257         /* A pointer-to-member constant can be unified only with
15258          another constant.  */
15259       if (TREE_CODE (arg) != PTRMEM_CST)
15260         return 1;
15261
15262       /* Just unify the class member. It would be useless (and possibly
15263          wrong, depending on the strict flags) to unify also
15264          PTRMEM_CST_CLASS, because we want to be sure that both parm and
15265          arg refer to the same variable, even if through different
15266          classes. For instance:
15267
15268          struct A { int x; };
15269          struct B : A { };
15270
15271          Unification of &A::x and &B::x must succeed.  */
15272       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
15273                     PTRMEM_CST_MEMBER (arg), strict);
15274      }
15275
15276     case POINTER_TYPE:
15277       {
15278         if (TREE_CODE (arg) != POINTER_TYPE)
15279           return 1;
15280
15281         /* [temp.deduct.call]
15282
15283            A can be another pointer or pointer to member type that can
15284            be converted to the deduced A via a qualification
15285            conversion (_conv.qual_).
15286
15287            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
15288            This will allow for additional cv-qualification of the
15289            pointed-to types if appropriate.  */
15290
15291         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
15292           /* The derived-to-base conversion only persists through one
15293              level of pointers.  */
15294           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
15295
15296         return unify (tparms, targs, TREE_TYPE (parm),
15297                       TREE_TYPE (arg), strict);
15298       }
15299
15300     case REFERENCE_TYPE:
15301       if (TREE_CODE (arg) != REFERENCE_TYPE)
15302         return 1;
15303       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
15304                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
15305
15306     case ARRAY_TYPE:
15307       if (TREE_CODE (arg) != ARRAY_TYPE)
15308         return 1;
15309       if ((TYPE_DOMAIN (parm) == NULL_TREE)
15310           != (TYPE_DOMAIN (arg) == NULL_TREE))
15311         return 1;
15312       if (TYPE_DOMAIN (parm) != NULL_TREE)
15313         {
15314           tree parm_max;
15315           tree arg_max;
15316           bool parm_cst;
15317           bool arg_cst;
15318
15319           /* Our representation of array types uses "N - 1" as the
15320              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
15321              not an integer constant.  We cannot unify arbitrarily
15322              complex expressions, so we eliminate the MINUS_EXPRs
15323              here.  */
15324           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
15325           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
15326           if (!parm_cst)
15327             {
15328               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
15329               parm_max = TREE_OPERAND (parm_max, 0);
15330             }
15331           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
15332           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
15333           if (!arg_cst)
15334             {
15335               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
15336                  trying to unify the type of a variable with the type
15337                  of a template parameter.  For example:
15338
15339                    template <unsigned int N>
15340                    void f (char (&) [N]);
15341                    int g(); 
15342                    void h(int i) {
15343                      char a[g(i)];
15344                      f(a); 
15345                    }
15346
15347                 Here, the type of the ARG will be "int [g(i)]", and
15348                 may be a SAVE_EXPR, etc.  */
15349               if (TREE_CODE (arg_max) != MINUS_EXPR)
15350                 return 1;
15351               arg_max = TREE_OPERAND (arg_max, 0);
15352             }
15353
15354           /* If only one of the bounds used a MINUS_EXPR, compensate
15355              by adding one to the other bound.  */
15356           if (parm_cst && !arg_cst)
15357             parm_max = fold_build2_loc (input_location, PLUS_EXPR,
15358                                     integer_type_node,
15359                                     parm_max,
15360                                     integer_one_node);
15361           else if (arg_cst && !parm_cst)
15362             arg_max = fold_build2_loc (input_location, PLUS_EXPR,
15363                                    integer_type_node,
15364                                    arg_max,
15365                                    integer_one_node);
15366
15367           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
15368             return 1;
15369         }
15370       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
15371                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
15372
15373     case REAL_TYPE:
15374     case COMPLEX_TYPE:
15375     case VECTOR_TYPE:
15376     case INTEGER_TYPE:
15377     case BOOLEAN_TYPE:
15378     case ENUMERAL_TYPE:
15379     case VOID_TYPE:
15380       if (TREE_CODE (arg) != TREE_CODE (parm))
15381         return 1;
15382
15383       /* We have already checked cv-qualification at the top of the
15384          function.  */
15385       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
15386         return 1;
15387
15388       /* As far as unification is concerned, this wins.  Later checks
15389          will invalidate it if necessary.  */
15390       return 0;
15391
15392       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
15393       /* Type INTEGER_CST can come from ordinary constant template args.  */
15394     case INTEGER_CST:
15395       while (TREE_CODE (arg) == NOP_EXPR)
15396         arg = TREE_OPERAND (arg, 0);
15397
15398       if (TREE_CODE (arg) != INTEGER_CST)
15399         return 1;
15400       return !tree_int_cst_equal (parm, arg);
15401
15402     case TREE_VEC:
15403       {
15404         int i;
15405         if (TREE_CODE (arg) != TREE_VEC)
15406           return 1;
15407         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
15408           return 1;
15409         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
15410           if (unify (tparms, targs,
15411                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
15412                      UNIFY_ALLOW_NONE))
15413             return 1;
15414         return 0;
15415       }
15416
15417     case RECORD_TYPE:
15418     case UNION_TYPE:
15419       if (TREE_CODE (arg) != TREE_CODE (parm))
15420         return 1;
15421
15422       if (TYPE_PTRMEMFUNC_P (parm))
15423         {
15424           if (!TYPE_PTRMEMFUNC_P (arg))
15425             return 1;
15426
15427           return unify (tparms, targs,
15428                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
15429                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
15430                         strict);
15431         }
15432
15433       if (CLASSTYPE_TEMPLATE_INFO (parm))
15434         {
15435           tree t = NULL_TREE;
15436
15437           if (strict_in & UNIFY_ALLOW_DERIVED)
15438             {
15439               /* First, we try to unify the PARM and ARG directly.  */
15440               t = try_class_unification (tparms, targs,
15441                                          parm, arg);
15442
15443               if (!t)
15444                 {
15445                   /* Fallback to the special case allowed in
15446                      [temp.deduct.call]:
15447
15448                        If P is a class, and P has the form
15449                        template-id, then A can be a derived class of
15450                        the deduced A.  Likewise, if P is a pointer to
15451                        a class of the form template-id, A can be a
15452                        pointer to a derived class pointed to by the
15453                        deduced A.  */
15454                   t = get_template_base (tparms, targs, parm, arg);
15455
15456                   if (!t)
15457                     return 1;
15458                 }
15459             }
15460           else if (CLASSTYPE_TEMPLATE_INFO (arg)
15461                    && (CLASSTYPE_TI_TEMPLATE (parm)
15462                        == CLASSTYPE_TI_TEMPLATE (arg)))
15463             /* Perhaps PARM is something like S<U> and ARG is S<int>.
15464                Then, we should unify `int' and `U'.  */
15465             t = arg;
15466           else
15467             /* There's no chance of unification succeeding.  */
15468             return 1;
15469
15470           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
15471                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
15472         }
15473       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
15474         return 1;
15475       return 0;
15476
15477     case METHOD_TYPE:
15478     case FUNCTION_TYPE:
15479       {
15480         unsigned int nargs;
15481         tree *args;
15482         tree a;
15483         unsigned int i;
15484
15485         if (TREE_CODE (arg) != TREE_CODE (parm))
15486           return 1;
15487
15488         /* CV qualifications for methods can never be deduced, they must
15489            match exactly.  We need to check them explicitly here,
15490            because type_unification_real treats them as any other
15491            cv-qualified parameter.  */
15492         if (TREE_CODE (parm) == METHOD_TYPE
15493             && (!check_cv_quals_for_unify
15494                 (UNIFY_ALLOW_NONE,
15495                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
15496                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
15497           return 1;
15498
15499         if (unify (tparms, targs, TREE_TYPE (parm),
15500                    TREE_TYPE (arg), UNIFY_ALLOW_NONE))
15501           return 1;
15502
15503         nargs = list_length (TYPE_ARG_TYPES (arg));
15504         args = XALLOCAVEC (tree, nargs);
15505         for (a = TYPE_ARG_TYPES (arg), i = 0;
15506              a != NULL_TREE && a != void_list_node;
15507              a = TREE_CHAIN (a), ++i)
15508           args[i] = TREE_VALUE (a);
15509         nargs = i;
15510
15511         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
15512                                       args, nargs, 1, DEDUCE_EXACT,
15513                                       LOOKUP_NORMAL);
15514       }
15515
15516     case OFFSET_TYPE:
15517       /* Unify a pointer to member with a pointer to member function, which
15518          deduces the type of the member as a function type. */
15519       if (TYPE_PTRMEMFUNC_P (arg))
15520         {
15521           tree method_type;
15522           tree fntype;
15523
15524           /* Check top-level cv qualifiers */
15525           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
15526             return 1;
15527
15528           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
15529                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
15530             return 1;
15531
15532           /* Determine the type of the function we are unifying against. */
15533           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
15534           fntype =
15535             build_function_type (TREE_TYPE (method_type),
15536                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
15537
15538           /* Extract the cv-qualifiers of the member function from the
15539              implicit object parameter and place them on the function
15540              type to be restored later. */
15541           fntype = apply_memfn_quals (fntype, type_memfn_quals (method_type));
15542           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
15543         }
15544
15545       if (TREE_CODE (arg) != OFFSET_TYPE)
15546         return 1;
15547       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
15548                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
15549         return 1;
15550       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
15551                     strict);
15552
15553     case CONST_DECL:
15554       if (DECL_TEMPLATE_PARM_P (parm))
15555         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
15556       if (arg != integral_constant_value (parm))
15557         return 1;
15558       return 0;
15559
15560     case FIELD_DECL:
15561     case TEMPLATE_DECL:
15562       /* Matched cases are handled by the ARG == PARM test above.  */
15563       return 1;
15564
15565     case VAR_DECL:
15566       /* A non-type template parameter that is a variable should be a
15567          an integral constant, in which case, it whould have been
15568          folded into its (constant) value. So we should not be getting
15569          a variable here.  */
15570       gcc_unreachable ();
15571
15572     case TYPE_ARGUMENT_PACK:
15573     case NONTYPE_ARGUMENT_PACK:
15574       {
15575         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
15576         tree packed_args = ARGUMENT_PACK_ARGS (arg);
15577         int i, len = TREE_VEC_LENGTH (packed_parms);
15578         int argslen = TREE_VEC_LENGTH (packed_args);
15579         int parm_variadic_p = 0;
15580
15581         for (i = 0; i < len; ++i)
15582           {
15583             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
15584               {
15585                 if (i == len - 1)
15586                   /* We can unify against something with a trailing
15587                      parameter pack.  */
15588                   parm_variadic_p = 1;
15589                 else
15590                   /* Since there is something following the pack
15591                      expansion, we cannot unify this template argument
15592                      list.  */
15593                   return 0;
15594               }
15595           }
15596           
15597
15598         /* If we don't have enough arguments to satisfy the parameters
15599            (not counting the pack expression at the end), or we have
15600            too many arguments for a parameter list that doesn't end in
15601            a pack expression, we can't unify.  */
15602         if (argslen < (len - parm_variadic_p)
15603             || (argslen > len && !parm_variadic_p))
15604           return 1;
15605
15606         /* Unify all of the parameters that precede the (optional)
15607            pack expression.  */
15608         for (i = 0; i < len - parm_variadic_p; ++i)
15609           {
15610             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
15611                        TREE_VEC_ELT (packed_args, i), strict))
15612               return 1;
15613           }
15614
15615         if (parm_variadic_p)
15616           return unify_pack_expansion (tparms, targs, 
15617                                        packed_parms, packed_args,
15618                                        strict, /*call_args_p=*/false,
15619                                        /*subr=*/false);
15620         return 0;
15621       }
15622
15623       break;
15624
15625     case TYPEOF_TYPE:
15626     case DECLTYPE_TYPE:
15627       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
15628          nodes.  */
15629       return 0;
15630
15631     case ERROR_MARK:
15632       /* Unification fails if we hit an error node.  */
15633       return 1;
15634
15635     default:
15636       gcc_assert (EXPR_P (parm));
15637
15638       /* We must be looking at an expression.  This can happen with
15639          something like:
15640
15641            template <int I>
15642            void foo(S<I>, S<I + 2>);
15643
15644          This is a "nondeduced context":
15645
15646            [deduct.type]
15647
15648            The nondeduced contexts are:
15649
15650            --A type that is a template-id in which one or more of
15651              the template-arguments is an expression that references
15652              a template-parameter.
15653
15654          In these cases, we assume deduction succeeded, but don't
15655          actually infer any unifications.  */
15656
15657       if (!uses_template_parms (parm)
15658           && !template_args_equal (parm, arg))
15659         return 1;
15660       else
15661         return 0;
15662     }
15663 }
15664 \f
15665 /* Note that DECL can be defined in this translation unit, if
15666    required.  */
15667
15668 static void
15669 mark_definable (tree decl)
15670 {
15671   tree clone;
15672   DECL_NOT_REALLY_EXTERN (decl) = 1;
15673   FOR_EACH_CLONE (clone, decl)
15674     DECL_NOT_REALLY_EXTERN (clone) = 1;
15675 }
15676
15677 /* Called if RESULT is explicitly instantiated, or is a member of an
15678    explicitly instantiated class.  */
15679
15680 void
15681 mark_decl_instantiated (tree result, int extern_p)
15682 {
15683   SET_DECL_EXPLICIT_INSTANTIATION (result);
15684
15685   /* If this entity has already been written out, it's too late to
15686      make any modifications.  */
15687   if (TREE_ASM_WRITTEN (result))
15688     return;
15689
15690   if (TREE_CODE (result) != FUNCTION_DECL)
15691     /* The TREE_PUBLIC flag for function declarations will have been
15692        set correctly by tsubst.  */
15693     TREE_PUBLIC (result) = 1;
15694
15695   /* This might have been set by an earlier implicit instantiation.  */
15696   DECL_COMDAT (result) = 0;
15697
15698   if (extern_p)
15699     DECL_NOT_REALLY_EXTERN (result) = 0;
15700   else
15701     {
15702       mark_definable (result);
15703       /* Always make artificials weak.  */
15704       if (DECL_ARTIFICIAL (result) && flag_weak)
15705         comdat_linkage (result);
15706       /* For WIN32 we also want to put explicit instantiations in
15707          linkonce sections.  */
15708       else if (TREE_PUBLIC (result))
15709         maybe_make_one_only (result);
15710     }
15711
15712   /* If EXTERN_P, then this function will not be emitted -- unless
15713      followed by an explicit instantiation, at which point its linkage
15714      will be adjusted.  If !EXTERN_P, then this function will be
15715      emitted here.  In neither circumstance do we want
15716      import_export_decl to adjust the linkage.  */
15717   DECL_INTERFACE_KNOWN (result) = 1;
15718 }
15719
15720 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
15721    important template arguments.  If any are missing, we check whether
15722    they're important by using error_mark_node for substituting into any
15723    args that were used for partial ordering (the ones between ARGS and END)
15724    and seeing if it bubbles up.  */
15725
15726 static bool
15727 check_undeduced_parms (tree targs, tree args, tree end)
15728 {
15729   bool found = false;
15730   int i;
15731   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
15732     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
15733       {
15734         found = true;
15735         TREE_VEC_ELT (targs, i) = error_mark_node;
15736       }
15737   if (found)
15738     {
15739       for (; args != end; args = TREE_CHAIN (args))
15740         {
15741           tree substed = tsubst (TREE_VALUE (args), targs, tf_none, NULL_TREE);
15742           if (substed == error_mark_node)
15743             return true;
15744         }
15745     }
15746   return false;
15747 }
15748
15749 /* Given two function templates PAT1 and PAT2, return:
15750
15751    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
15752    -1 if PAT2 is more specialized than PAT1.
15753    0 if neither is more specialized.
15754
15755    LEN indicates the number of parameters we should consider
15756    (defaulted parameters should not be considered).
15757
15758    The 1998 std underspecified function template partial ordering, and
15759    DR214 addresses the issue.  We take pairs of arguments, one from
15760    each of the templates, and deduce them against each other.  One of
15761    the templates will be more specialized if all the *other*
15762    template's arguments deduce against its arguments and at least one
15763    of its arguments *does* *not* deduce against the other template's
15764    corresponding argument.  Deduction is done as for class templates.
15765    The arguments used in deduction have reference and top level cv
15766    qualifiers removed.  Iff both arguments were originally reference
15767    types *and* deduction succeeds in both directions, the template
15768    with the more cv-qualified argument wins for that pairing (if
15769    neither is more cv-qualified, they both are equal).  Unlike regular
15770    deduction, after all the arguments have been deduced in this way,
15771    we do *not* verify the deduced template argument values can be
15772    substituted into non-deduced contexts.
15773
15774    The logic can be a bit confusing here, because we look at deduce1 and
15775    targs1 to see if pat2 is at least as specialized, and vice versa; if we
15776    can find template arguments for pat1 to make arg1 look like arg2, that
15777    means that arg2 is at least as specialized as arg1.  */
15778
15779 int
15780 more_specialized_fn (tree pat1, tree pat2, int len)
15781 {
15782   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
15783   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
15784   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
15785   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
15786   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
15787   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
15788   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
15789   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
15790   tree origs1, origs2;
15791   bool lose1 = false;
15792   bool lose2 = false;
15793
15794   /* Remove the this parameter from non-static member functions.  If
15795      one is a non-static member function and the other is not a static
15796      member function, remove the first parameter from that function
15797      also.  This situation occurs for operator functions where we
15798      locate both a member function (with this pointer) and non-member
15799      operator (with explicit first operand).  */
15800   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
15801     {
15802       len--; /* LEN is the number of significant arguments for DECL1 */
15803       args1 = TREE_CHAIN (args1);
15804       if (!DECL_STATIC_FUNCTION_P (decl2))
15805         args2 = TREE_CHAIN (args2);
15806     }
15807   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
15808     {
15809       args2 = TREE_CHAIN (args2);
15810       if (!DECL_STATIC_FUNCTION_P (decl1))
15811         {
15812           len--;
15813           args1 = TREE_CHAIN (args1);
15814         }
15815     }
15816
15817   /* If only one is a conversion operator, they are unordered.  */
15818   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
15819     return 0;
15820
15821   /* Consider the return type for a conversion function */
15822   if (DECL_CONV_FN_P (decl1))
15823     {
15824       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
15825       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
15826       len++;
15827     }
15828
15829   processing_template_decl++;
15830
15831   origs1 = args1;
15832   origs2 = args2;
15833
15834   while (len--
15835          /* Stop when an ellipsis is seen.  */
15836          && args1 != NULL_TREE && args2 != NULL_TREE)
15837     {
15838       tree arg1 = TREE_VALUE (args1);
15839       tree arg2 = TREE_VALUE (args2);
15840       int deduce1, deduce2;
15841       int quals1 = -1;
15842       int quals2 = -1;
15843
15844       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15845           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15846         {
15847           /* When both arguments are pack expansions, we need only
15848              unify the patterns themselves.  */
15849           arg1 = PACK_EXPANSION_PATTERN (arg1);
15850           arg2 = PACK_EXPANSION_PATTERN (arg2);
15851
15852           /* This is the last comparison we need to do.  */
15853           len = 0;
15854         }
15855
15856       if (TREE_CODE (arg1) == REFERENCE_TYPE)
15857         {
15858           arg1 = TREE_TYPE (arg1);
15859           quals1 = cp_type_quals (arg1);
15860         }
15861
15862       if (TREE_CODE (arg2) == REFERENCE_TYPE)
15863         {
15864           arg2 = TREE_TYPE (arg2);
15865           quals2 = cp_type_quals (arg2);
15866         }
15867
15868       if ((quals1 < 0) != (quals2 < 0))
15869         {
15870           /* Only of the args is a reference, see if we should apply
15871              array/function pointer decay to it.  This is not part of
15872              DR214, but is, IMHO, consistent with the deduction rules
15873              for the function call itself, and with our earlier
15874              implementation of the underspecified partial ordering
15875              rules.  (nathan).  */
15876           if (quals1 >= 0)
15877             {
15878               switch (TREE_CODE (arg1))
15879                 {
15880                 case ARRAY_TYPE:
15881                   arg1 = TREE_TYPE (arg1);
15882                   /* FALLTHROUGH. */
15883                 case FUNCTION_TYPE:
15884                   arg1 = build_pointer_type (arg1);
15885                   break;
15886
15887                 default:
15888                   break;
15889                 }
15890             }
15891           else
15892             {
15893               switch (TREE_CODE (arg2))
15894                 {
15895                 case ARRAY_TYPE:
15896                   arg2 = TREE_TYPE (arg2);
15897                   /* FALLTHROUGH. */
15898                 case FUNCTION_TYPE:
15899                   arg2 = build_pointer_type (arg2);
15900                   break;
15901
15902                 default:
15903                   break;
15904                 }
15905             }
15906         }
15907
15908       arg1 = TYPE_MAIN_VARIANT (arg1);
15909       arg2 = TYPE_MAIN_VARIANT (arg2);
15910
15911       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
15912         {
15913           int i, len2 = list_length (args2);
15914           tree parmvec = make_tree_vec (1);
15915           tree argvec = make_tree_vec (len2);
15916           tree ta = args2;
15917
15918           /* Setup the parameter vector, which contains only ARG1.  */
15919           TREE_VEC_ELT (parmvec, 0) = arg1;
15920
15921           /* Setup the argument vector, which contains the remaining
15922              arguments.  */
15923           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
15924             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15925
15926           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
15927                                            argvec, UNIFY_ALLOW_NONE, 
15928                                            /*call_args_p=*/false, 
15929                                            /*subr=*/0);
15930
15931           /* We cannot deduce in the other direction, because ARG1 is
15932              a pack expansion but ARG2 is not.  */
15933           deduce2 = 0;
15934         }
15935       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15936         {
15937           int i, len1 = list_length (args1);
15938           tree parmvec = make_tree_vec (1);
15939           tree argvec = make_tree_vec (len1);
15940           tree ta = args1;
15941
15942           /* Setup the parameter vector, which contains only ARG1.  */
15943           TREE_VEC_ELT (parmvec, 0) = arg2;
15944
15945           /* Setup the argument vector, which contains the remaining
15946              arguments.  */
15947           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
15948             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15949
15950           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
15951                                            argvec, UNIFY_ALLOW_NONE, 
15952                                            /*call_args_p=*/false, 
15953                                            /*subr=*/0);
15954
15955           /* We cannot deduce in the other direction, because ARG2 is
15956              a pack expansion but ARG1 is not.*/
15957           deduce1 = 0;
15958         }
15959
15960       else
15961         {
15962           /* The normal case, where neither argument is a pack
15963              expansion.  */
15964           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
15965           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
15966         }
15967
15968       /* If we couldn't deduce arguments for tparms1 to make arg1 match
15969          arg2, then arg2 is not as specialized as arg1.  */
15970       if (!deduce1)
15971         lose2 = true;
15972       if (!deduce2)
15973         lose1 = true;
15974
15975       /* "If, for a given type, deduction succeeds in both directions
15976          (i.e., the types are identical after the transformations above)
15977          and if the type from the argument template is more cv-qualified
15978          than the type from the parameter template (as described above)
15979          that type is considered to be more specialized than the other. If
15980          neither type is more cv-qualified than the other then neither type
15981          is more specialized than the other."  */
15982
15983       if (deduce1 && deduce2
15984           && quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
15985         {
15986           if ((quals1 & quals2) == quals2)
15987             lose2 = true;
15988           if ((quals1 & quals2) == quals1)
15989             lose1 = true;
15990         }
15991
15992       if (lose1 && lose2)
15993         /* We've failed to deduce something in either direction.
15994            These must be unordered.  */
15995         break;
15996
15997       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15998           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15999         /* We have already processed all of the arguments in our
16000            handing of the pack expansion type.  */
16001         len = 0;
16002
16003       args1 = TREE_CHAIN (args1);
16004       args2 = TREE_CHAIN (args2);
16005     }
16006
16007   /* "In most cases, all template parameters must have values in order for
16008      deduction to succeed, but for partial ordering purposes a template
16009      parameter may remain without a value provided it is not used in the
16010      types being used for partial ordering."
16011
16012      Thus, if we are missing any of the targs1 we need to substitute into
16013      origs1, then pat2 is not as specialized as pat1.  This can happen when
16014      there is a nondeduced context.  */
16015   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
16016     lose2 = true;
16017   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
16018     lose1 = true;
16019
16020   processing_template_decl--;
16021
16022   /* All things being equal, if the next argument is a pack expansion
16023      for one function but not for the other, prefer the
16024      non-variadic function.  FIXME this is bogus; see c++/41958.  */
16025   if (lose1 == lose2
16026       && args1 && TREE_VALUE (args1)
16027       && args2 && TREE_VALUE (args2))
16028     {
16029       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
16030       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
16031     }
16032
16033   if (lose1 == lose2)
16034     return 0;
16035   else if (!lose1)
16036     return 1;
16037   else
16038     return -1;
16039 }
16040
16041 /* Determine which of two partial specializations is more specialized.
16042
16043    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
16044    to the first partial specialization.  The TREE_VALUE is the
16045    innermost set of template parameters for the partial
16046    specialization.  PAT2 is similar, but for the second template.
16047
16048    Return 1 if the first partial specialization is more specialized;
16049    -1 if the second is more specialized; 0 if neither is more
16050    specialized.
16051
16052    See [temp.class.order] for information about determining which of
16053    two templates is more specialized.  */
16054
16055 static int
16056 more_specialized_class (tree pat1, tree pat2)
16057 {
16058   tree targs;
16059   tree tmpl1, tmpl2;
16060   int winner = 0;
16061   bool any_deductions = false;
16062
16063   tmpl1 = TREE_TYPE (pat1);
16064   tmpl2 = TREE_TYPE (pat2);
16065
16066   /* Just like what happens for functions, if we are ordering between
16067      different class template specializations, we may encounter dependent
16068      types in the arguments, and we need our dependency check functions
16069      to behave correctly.  */
16070   ++processing_template_decl;
16071   targs = get_class_bindings (TREE_VALUE (pat1),
16072                               CLASSTYPE_TI_ARGS (tmpl1),
16073                               CLASSTYPE_TI_ARGS (tmpl2));
16074   if (targs)
16075     {
16076       --winner;
16077       any_deductions = true;
16078     }
16079
16080   targs = get_class_bindings (TREE_VALUE (pat2),
16081                               CLASSTYPE_TI_ARGS (tmpl2),
16082                               CLASSTYPE_TI_ARGS (tmpl1));
16083   if (targs)
16084     {
16085       ++winner;
16086       any_deductions = true;
16087     }
16088   --processing_template_decl;
16089
16090   /* In the case of a tie where at least one of the class templates
16091      has a parameter pack at the end, the template with the most
16092      non-packed parameters wins.  */
16093   if (winner == 0
16094       && any_deductions
16095       && (template_args_variadic_p (TREE_PURPOSE (pat1))
16096           || template_args_variadic_p (TREE_PURPOSE (pat2))))
16097     {
16098       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
16099       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
16100       int len1 = TREE_VEC_LENGTH (args1);
16101       int len2 = TREE_VEC_LENGTH (args2);
16102
16103       /* We don't count the pack expansion at the end.  */
16104       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
16105         --len1;
16106       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
16107         --len2;
16108
16109       if (len1 > len2)
16110         return 1;
16111       else if (len1 < len2)
16112         return -1;
16113     }
16114
16115   return winner;
16116 }
16117
16118 /* Return the template arguments that will produce the function signature
16119    DECL from the function template FN, with the explicit template
16120    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
16121    also match.  Return NULL_TREE if no satisfactory arguments could be
16122    found.  */
16123
16124 static tree
16125 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
16126 {
16127   int ntparms = DECL_NTPARMS (fn);
16128   tree targs = make_tree_vec (ntparms);
16129   tree decl_type;
16130   tree decl_arg_types;
16131   tree *args;
16132   unsigned int nargs, ix;
16133   tree arg;
16134
16135   /* Substitute the explicit template arguments into the type of DECL.
16136      The call to fn_type_unification will handle substitution into the
16137      FN.  */
16138   decl_type = TREE_TYPE (decl);
16139   if (explicit_args && uses_template_parms (decl_type))
16140     {
16141       tree tmpl;
16142       tree converted_args;
16143
16144       if (DECL_TEMPLATE_INFO (decl))
16145         tmpl = DECL_TI_TEMPLATE (decl);
16146       else
16147         /* We can get here for some invalid specializations.  */
16148         return NULL_TREE;
16149
16150       converted_args
16151         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
16152                                  explicit_args, NULL_TREE,
16153                                  tf_none,
16154                                  /*require_all_args=*/false,
16155                                  /*use_default_args=*/false);
16156       if (converted_args == error_mark_node)
16157         return NULL_TREE;
16158
16159       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
16160       if (decl_type == error_mark_node)
16161         return NULL_TREE;
16162     }
16163
16164   /* Never do unification on the 'this' parameter.  */
16165   decl_arg_types = skip_artificial_parms_for (decl, 
16166                                               TYPE_ARG_TYPES (decl_type));
16167
16168   nargs = list_length (decl_arg_types);
16169   args = XALLOCAVEC (tree, nargs);
16170   for (arg = decl_arg_types, ix = 0;
16171        arg != NULL_TREE && arg != void_list_node;
16172        arg = TREE_CHAIN (arg), ++ix)
16173     args[ix] = TREE_VALUE (arg);
16174
16175   if (fn_type_unification (fn, explicit_args, targs,
16176                            args, ix,
16177                            (check_rettype || DECL_CONV_FN_P (fn)
16178                             ? TREE_TYPE (decl_type) : NULL_TREE),
16179                            DEDUCE_EXACT, LOOKUP_NORMAL))
16180     return NULL_TREE;
16181
16182   return targs;
16183 }
16184
16185 /* Return the innermost template arguments that, when applied to a
16186    template specialization whose innermost template parameters are
16187    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
16188    ARGS.
16189
16190    For example, suppose we have:
16191
16192      template <class T, class U> struct S {};
16193      template <class T> struct S<T*, int> {};
16194
16195    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
16196    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
16197    int}.  The resulting vector will be {double}, indicating that `T'
16198    is bound to `double'.  */
16199
16200 static tree
16201 get_class_bindings (tree tparms, tree spec_args, tree args)
16202 {
16203   int i, ntparms = TREE_VEC_LENGTH (tparms);
16204   tree deduced_args;
16205   tree innermost_deduced_args;
16206
16207   innermost_deduced_args = make_tree_vec (ntparms);
16208   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
16209     {
16210       deduced_args = copy_node (args);
16211       SET_TMPL_ARGS_LEVEL (deduced_args,
16212                            TMPL_ARGS_DEPTH (deduced_args),
16213                            innermost_deduced_args);
16214     }
16215   else
16216     deduced_args = innermost_deduced_args;
16217
16218   if (unify (tparms, deduced_args,
16219              INNERMOST_TEMPLATE_ARGS (spec_args),
16220              INNERMOST_TEMPLATE_ARGS (args),
16221              UNIFY_ALLOW_NONE))
16222     return NULL_TREE;
16223
16224   for (i =  0; i < ntparms; ++i)
16225     if (! TREE_VEC_ELT (innermost_deduced_args, i))
16226       return NULL_TREE;
16227
16228   /* Verify that nondeduced template arguments agree with the type
16229      obtained from argument deduction.
16230
16231      For example:
16232
16233        struct A { typedef int X; };
16234        template <class T, class U> struct C {};
16235        template <class T> struct C<T, typename T::X> {};
16236
16237      Then with the instantiation `C<A, int>', we can deduce that
16238      `T' is `A' but unify () does not check whether `typename T::X'
16239      is `int'.  */
16240   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
16241   if (spec_args == error_mark_node
16242       /* We only need to check the innermost arguments; the other
16243          arguments will always agree.  */
16244       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
16245                               INNERMOST_TEMPLATE_ARGS (args)))
16246     return NULL_TREE;
16247
16248   /* Now that we have bindings for all of the template arguments,
16249      ensure that the arguments deduced for the template template
16250      parameters have compatible template parameter lists.  See the use
16251      of template_template_parm_bindings_ok_p in fn_type_unification
16252      for more information.  */
16253   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
16254     return NULL_TREE;
16255
16256   return deduced_args;
16257 }
16258
16259 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
16260    Return the TREE_LIST node with the most specialized template, if
16261    any.  If there is no most specialized template, the error_mark_node
16262    is returned.
16263
16264    Note that this function does not look at, or modify, the
16265    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
16266    returned is one of the elements of INSTANTIATIONS, callers may
16267    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
16268    and retrieve it from the value returned.  */
16269
16270 tree
16271 most_specialized_instantiation (tree templates)
16272 {
16273   tree fn, champ;
16274
16275   ++processing_template_decl;
16276
16277   champ = templates;
16278   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
16279     {
16280       int fate = 0;
16281
16282       if (get_bindings (TREE_VALUE (champ),
16283                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
16284                         NULL_TREE, /*check_ret=*/false))
16285         fate--;
16286
16287       if (get_bindings (TREE_VALUE (fn),
16288                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
16289                         NULL_TREE, /*check_ret=*/false))
16290         fate++;
16291
16292       if (fate == -1)
16293         champ = fn;
16294       else if (!fate)
16295         {
16296           /* Equally specialized, move to next function.  If there
16297              is no next function, nothing's most specialized.  */
16298           fn = TREE_CHAIN (fn);
16299           champ = fn;
16300           if (!fn)
16301             break;
16302         }
16303     }
16304
16305   if (champ)
16306     /* Now verify that champ is better than everything earlier in the
16307        instantiation list.  */
16308     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
16309       if (get_bindings (TREE_VALUE (champ),
16310                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
16311                         NULL_TREE, /*check_ret=*/false)
16312           || !get_bindings (TREE_VALUE (fn),
16313                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
16314                             NULL_TREE, /*check_ret=*/false))
16315         {
16316           champ = NULL_TREE;
16317           break;
16318         }
16319
16320   processing_template_decl--;
16321
16322   if (!champ)
16323     return error_mark_node;
16324
16325   return champ;
16326 }
16327
16328 /* If DECL is a specialization of some template, return the most
16329    general such template.  Otherwise, returns NULL_TREE.
16330
16331    For example, given:
16332
16333      template <class T> struct S { template <class U> void f(U); };
16334
16335    if TMPL is `template <class U> void S<int>::f(U)' this will return
16336    the full template.  This function will not trace past partial
16337    specializations, however.  For example, given in addition:
16338
16339      template <class T> struct S<T*> { template <class U> void f(U); };
16340
16341    if TMPL is `template <class U> void S<int*>::f(U)' this will return
16342    `template <class T> template <class U> S<T*>::f(U)'.  */
16343
16344 tree
16345 most_general_template (tree decl)
16346 {
16347   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
16348      an immediate specialization.  */
16349   if (TREE_CODE (decl) == FUNCTION_DECL)
16350     {
16351       if (DECL_TEMPLATE_INFO (decl)) {
16352         decl = DECL_TI_TEMPLATE (decl);
16353
16354         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
16355            template friend.  */
16356         if (TREE_CODE (decl) != TEMPLATE_DECL)
16357           return NULL_TREE;
16358       } else
16359         return NULL_TREE;
16360     }
16361
16362   /* Look for more and more general templates.  */
16363   while (DECL_TEMPLATE_INFO (decl))
16364     {
16365       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
16366          (See cp-tree.h for details.)  */
16367       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
16368         break;
16369
16370       if (CLASS_TYPE_P (TREE_TYPE (decl))
16371           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
16372         break;
16373
16374       /* Stop if we run into an explicitly specialized class template.  */
16375       if (!DECL_NAMESPACE_SCOPE_P (decl)
16376           && DECL_CONTEXT (decl)
16377           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
16378         break;
16379
16380       decl = DECL_TI_TEMPLATE (decl);
16381     }
16382
16383   return decl;
16384 }
16385
16386 /* Return the most specialized of the class template partial
16387    specializations of TMPL which can produce TYPE, a specialization of
16388    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
16389    a _TYPE node corresponding to the partial specialization, while the
16390    TREE_PURPOSE is the set of template arguments that must be
16391    substituted into the TREE_TYPE in order to generate TYPE.
16392
16393    If the choice of partial specialization is ambiguous, a diagnostic
16394    is issued, and the error_mark_node is returned.  If there are no
16395    partial specializations of TMPL matching TYPE, then NULL_TREE is
16396    returned.  */
16397
16398 static tree
16399 most_specialized_class (tree type, tree tmpl, tsubst_flags_t complain)
16400 {
16401   tree list = NULL_TREE;
16402   tree t;
16403   tree champ;
16404   int fate;
16405   bool ambiguous_p;
16406   tree args;
16407   tree outer_args = NULL_TREE;
16408
16409   tmpl = most_general_template (tmpl);
16410   args = CLASSTYPE_TI_ARGS (type);
16411
16412   /* For determining which partial specialization to use, only the
16413      innermost args are interesting.  */
16414   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
16415     {
16416       outer_args = strip_innermost_template_args (args, 1);
16417       args = INNERMOST_TEMPLATE_ARGS (args);
16418     }
16419
16420   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
16421     {
16422       tree partial_spec_args;
16423       tree spec_args;
16424       tree parms = TREE_VALUE (t);
16425
16426       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
16427
16428       ++processing_template_decl;
16429
16430       if (outer_args)
16431         {
16432           int i;
16433
16434           /* Discard the outer levels of args, and then substitute in the
16435              template args from the enclosing class.  */
16436           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
16437           partial_spec_args = tsubst_template_args
16438             (partial_spec_args, outer_args, tf_none, NULL_TREE);
16439
16440           /* PARMS already refers to just the innermost parms, but the
16441              template parms in partial_spec_args had their levels lowered
16442              by tsubst, so we need to do the same for the parm list.  We
16443              can't just tsubst the TREE_VEC itself, as tsubst wants to
16444              treat a TREE_VEC as an argument vector.  */
16445           parms = copy_node (parms);
16446           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
16447             TREE_VEC_ELT (parms, i) =
16448               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
16449
16450         }
16451
16452       partial_spec_args =
16453           coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
16454                                  add_to_template_args (outer_args,
16455                                                        partial_spec_args),
16456                                  tmpl, tf_none,
16457                                  /*require_all_args=*/true,
16458                                  /*use_default_args=*/true);
16459
16460       --processing_template_decl;
16461
16462       if (partial_spec_args == error_mark_node)
16463         return error_mark_node;
16464
16465       spec_args = get_class_bindings (parms,
16466                                       partial_spec_args,
16467                                       args);
16468       if (spec_args)
16469         {
16470           if (outer_args)
16471             spec_args = add_to_template_args (outer_args, spec_args);
16472           list = tree_cons (spec_args, TREE_VALUE (t), list);
16473           TREE_TYPE (list) = TREE_TYPE (t);
16474         }
16475     }
16476
16477   if (! list)
16478     return NULL_TREE;
16479
16480   ambiguous_p = false;
16481   t = list;
16482   champ = t;
16483   t = TREE_CHAIN (t);
16484   for (; t; t = TREE_CHAIN (t))
16485     {
16486       fate = more_specialized_class (champ, t);
16487       if (fate == 1)
16488         ;
16489       else
16490         {
16491           if (fate == 0)
16492             {
16493               t = TREE_CHAIN (t);
16494               if (! t)
16495                 {
16496                   ambiguous_p = true;
16497                   break;
16498                 }
16499             }
16500           champ = t;
16501         }
16502     }
16503
16504   if (!ambiguous_p)
16505     for (t = list; t && t != champ; t = TREE_CHAIN (t))
16506       {
16507         fate = more_specialized_class (champ, t);
16508         if (fate != 1)
16509           {
16510             ambiguous_p = true;
16511             break;
16512           }
16513       }
16514
16515   if (ambiguous_p)
16516     {
16517       const char *str;
16518       char *spaces = NULL;
16519       if (!(complain & tf_error))
16520         return error_mark_node;
16521       error ("ambiguous class template instantiation for %q#T", type);
16522       str = ngettext ("candidate is:", "candidates are:", list_length (list));
16523       for (t = list; t; t = TREE_CHAIN (t))
16524         {
16525           error ("%s %+#T", spaces ? spaces : str, TREE_TYPE (t));
16526           spaces = spaces ? spaces : get_spaces (str);
16527         }
16528       free (spaces);
16529       return error_mark_node;
16530     }
16531
16532   return champ;
16533 }
16534
16535 /* Explicitly instantiate DECL.  */
16536
16537 void
16538 do_decl_instantiation (tree decl, tree storage)
16539 {
16540   tree result = NULL_TREE;
16541   int extern_p = 0;
16542
16543   if (!decl || decl == error_mark_node)
16544     /* An error occurred, for which grokdeclarator has already issued
16545        an appropriate message.  */
16546     return;
16547   else if (! DECL_LANG_SPECIFIC (decl))
16548     {
16549       error ("explicit instantiation of non-template %q#D", decl);
16550       return;
16551     }
16552   else if (TREE_CODE (decl) == VAR_DECL)
16553     {
16554       /* There is an asymmetry here in the way VAR_DECLs and
16555          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
16556          the latter, the DECL we get back will be marked as a
16557          template instantiation, and the appropriate
16558          DECL_TEMPLATE_INFO will be set up.  This does not happen for
16559          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
16560          should handle VAR_DECLs as it currently handles
16561          FUNCTION_DECLs.  */
16562       if (!DECL_CLASS_SCOPE_P (decl))
16563         {
16564           error ("%qD is not a static data member of a class template", decl);
16565           return;
16566         }
16567       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
16568       if (!result || TREE_CODE (result) != VAR_DECL)
16569         {
16570           error ("no matching template for %qD found", decl);
16571           return;
16572         }
16573       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
16574         {
16575           error ("type %qT for explicit instantiation %qD does not match "
16576                  "declared type %qT", TREE_TYPE (result), decl,
16577                  TREE_TYPE (decl));
16578           return;
16579         }
16580     }
16581   else if (TREE_CODE (decl) != FUNCTION_DECL)
16582     {
16583       error ("explicit instantiation of %q#D", decl);
16584       return;
16585     }
16586   else
16587     result = decl;
16588
16589   /* Check for various error cases.  Note that if the explicit
16590      instantiation is valid the RESULT will currently be marked as an
16591      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
16592      until we get here.  */
16593
16594   if (DECL_TEMPLATE_SPECIALIZATION (result))
16595     {
16596       /* DR 259 [temp.spec].
16597
16598          Both an explicit instantiation and a declaration of an explicit
16599          specialization shall not appear in a program unless the explicit
16600          instantiation follows a declaration of the explicit specialization.
16601
16602          For a given set of template parameters, if an explicit
16603          instantiation of a template appears after a declaration of an
16604          explicit specialization for that template, the explicit
16605          instantiation has no effect.  */
16606       return;
16607     }
16608   else if (DECL_EXPLICIT_INSTANTIATION (result))
16609     {
16610       /* [temp.spec]
16611
16612          No program shall explicitly instantiate any template more
16613          than once.
16614
16615          We check DECL_NOT_REALLY_EXTERN so as not to complain when
16616          the first instantiation was `extern' and the second is not,
16617          and EXTERN_P for the opposite case.  */
16618       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
16619         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
16620       /* If an "extern" explicit instantiation follows an ordinary
16621          explicit instantiation, the template is instantiated.  */
16622       if (extern_p)
16623         return;
16624     }
16625   else if (!DECL_IMPLICIT_INSTANTIATION (result))
16626     {
16627       error ("no matching template for %qD found", result);
16628       return;
16629     }
16630   else if (!DECL_TEMPLATE_INFO (result))
16631     {
16632       permerror (input_location, "explicit instantiation of non-template %q#D", result);
16633       return;
16634     }
16635
16636   if (storage == NULL_TREE)
16637     ;
16638   else if (storage == ridpointers[(int) RID_EXTERN])
16639     {
16640       if (!in_system_header && (cxx_dialect == cxx98))
16641         pedwarn (input_location, OPT_pedantic, 
16642                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
16643                  "instantiations");
16644       extern_p = 1;
16645     }
16646   else
16647     error ("storage class %qD applied to template instantiation", storage);
16648
16649   check_explicit_instantiation_namespace (result);
16650   mark_decl_instantiated (result, extern_p);
16651   if (! extern_p)
16652     instantiate_decl (result, /*defer_ok=*/1,
16653                       /*expl_inst_class_mem_p=*/false);
16654 }
16655
16656 static void
16657 mark_class_instantiated (tree t, int extern_p)
16658 {
16659   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
16660   SET_CLASSTYPE_INTERFACE_KNOWN (t);
16661   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
16662   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
16663   if (! extern_p)
16664     {
16665       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
16666       rest_of_type_compilation (t, 1);
16667     }
16668 }
16669
16670 /* Called from do_type_instantiation through binding_table_foreach to
16671    do recursive instantiation for the type bound in ENTRY.  */
16672 static void
16673 bt_instantiate_type_proc (binding_entry entry, void *data)
16674 {
16675   tree storage = *(tree *) data;
16676
16677   if (MAYBE_CLASS_TYPE_P (entry->type)
16678       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
16679     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
16680 }
16681
16682 /* Called from do_type_instantiation to instantiate a member
16683    (a member function or a static member variable) of an
16684    explicitly instantiated class template.  */
16685 static void
16686 instantiate_class_member (tree decl, int extern_p)
16687 {
16688   mark_decl_instantiated (decl, extern_p);
16689   if (! extern_p)
16690     instantiate_decl (decl, /*defer_ok=*/1,
16691                       /*expl_inst_class_mem_p=*/true);
16692 }
16693
16694 /* Perform an explicit instantiation of template class T.  STORAGE, if
16695    non-null, is the RID for extern, inline or static.  COMPLAIN is
16696    nonzero if this is called from the parser, zero if called recursively,
16697    since the standard is unclear (as detailed below).  */
16698
16699 void
16700 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
16701 {
16702   int extern_p = 0;
16703   int nomem_p = 0;
16704   int static_p = 0;
16705   int previous_instantiation_extern_p = 0;
16706
16707   if (TREE_CODE (t) == TYPE_DECL)
16708     t = TREE_TYPE (t);
16709
16710   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
16711     {
16712       error ("explicit instantiation of non-template type %qT", t);
16713       return;
16714     }
16715
16716   complete_type (t);
16717
16718   if (!COMPLETE_TYPE_P (t))
16719     {
16720       if (complain & tf_error)
16721         error ("explicit instantiation of %q#T before definition of template",
16722                t);
16723       return;
16724     }
16725
16726   if (storage != NULL_TREE)
16727     {
16728       if (!in_system_header)
16729         {
16730           if (storage == ridpointers[(int) RID_EXTERN])
16731             {
16732               if (cxx_dialect == cxx98)
16733                 pedwarn (input_location, OPT_pedantic, 
16734                          "ISO C++ 1998 forbids the use of %<extern%> on "
16735                          "explicit instantiations");
16736             }
16737           else
16738             pedwarn (input_location, OPT_pedantic, 
16739                      "ISO C++ forbids the use of %qE"
16740                      " on explicit instantiations", storage);
16741         }
16742
16743       if (storage == ridpointers[(int) RID_INLINE])
16744         nomem_p = 1;
16745       else if (storage == ridpointers[(int) RID_EXTERN])
16746         extern_p = 1;
16747       else if (storage == ridpointers[(int) RID_STATIC])
16748         static_p = 1;
16749       else
16750         {
16751           error ("storage class %qD applied to template instantiation",
16752                  storage);
16753           extern_p = 0;
16754         }
16755     }
16756
16757   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
16758     {
16759       /* DR 259 [temp.spec].
16760
16761          Both an explicit instantiation and a declaration of an explicit
16762          specialization shall not appear in a program unless the explicit
16763          instantiation follows a declaration of the explicit specialization.
16764
16765          For a given set of template parameters, if an explicit
16766          instantiation of a template appears after a declaration of an
16767          explicit specialization for that template, the explicit
16768          instantiation has no effect.  */
16769       return;
16770     }
16771   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
16772     {
16773       /* [temp.spec]
16774
16775          No program shall explicitly instantiate any template more
16776          than once.
16777
16778          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
16779          instantiation was `extern'.  If EXTERN_P then the second is.
16780          These cases are OK.  */
16781       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
16782
16783       if (!previous_instantiation_extern_p && !extern_p
16784           && (complain & tf_error))
16785         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
16786
16787       /* If we've already instantiated the template, just return now.  */
16788       if (!CLASSTYPE_INTERFACE_ONLY (t))
16789         return;
16790     }
16791
16792   check_explicit_instantiation_namespace (TYPE_NAME (t));
16793   mark_class_instantiated (t, extern_p);
16794
16795   if (nomem_p)
16796     return;
16797
16798   {
16799     tree tmp;
16800
16801     /* In contrast to implicit instantiation, where only the
16802        declarations, and not the definitions, of members are
16803        instantiated, we have here:
16804
16805          [temp.explicit]
16806
16807          The explicit instantiation of a class template specialization
16808          implies the instantiation of all of its members not
16809          previously explicitly specialized in the translation unit
16810          containing the explicit instantiation.
16811
16812        Of course, we can't instantiate member template classes, since
16813        we don't have any arguments for them.  Note that the standard
16814        is unclear on whether the instantiation of the members are
16815        *explicit* instantiations or not.  However, the most natural
16816        interpretation is that it should be an explicit instantiation.  */
16817
16818     if (! static_p)
16819       for (tmp = TYPE_METHODS (t); tmp; tmp = DECL_CHAIN (tmp))
16820         if (TREE_CODE (tmp) == FUNCTION_DECL
16821             && DECL_TEMPLATE_INSTANTIATION (tmp))
16822           instantiate_class_member (tmp, extern_p);
16823
16824     for (tmp = TYPE_FIELDS (t); tmp; tmp = DECL_CHAIN (tmp))
16825       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
16826         instantiate_class_member (tmp, extern_p);
16827
16828     if (CLASSTYPE_NESTED_UTDS (t))
16829       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
16830                              bt_instantiate_type_proc, &storage);
16831   }
16832 }
16833
16834 /* Given a function DECL, which is a specialization of TMPL, modify
16835    DECL to be a re-instantiation of TMPL with the same template
16836    arguments.  TMPL should be the template into which tsubst'ing
16837    should occur for DECL, not the most general template.
16838
16839    One reason for doing this is a scenario like this:
16840
16841      template <class T>
16842      void f(const T&, int i);
16843
16844      void g() { f(3, 7); }
16845
16846      template <class T>
16847      void f(const T& t, const int i) { }
16848
16849    Note that when the template is first instantiated, with
16850    instantiate_template, the resulting DECL will have no name for the
16851    first parameter, and the wrong type for the second.  So, when we go
16852    to instantiate the DECL, we regenerate it.  */
16853
16854 static void
16855 regenerate_decl_from_template (tree decl, tree tmpl)
16856 {
16857   /* The arguments used to instantiate DECL, from the most general
16858      template.  */
16859   tree args;
16860   tree code_pattern;
16861
16862   args = DECL_TI_ARGS (decl);
16863   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
16864
16865   /* Make sure that we can see identifiers, and compute access
16866      correctly.  */
16867   push_access_scope (decl);
16868
16869   if (TREE_CODE (decl) == FUNCTION_DECL)
16870     {
16871       tree decl_parm;
16872       tree pattern_parm;
16873       tree specs;
16874       int args_depth;
16875       int parms_depth;
16876
16877       args_depth = TMPL_ARGS_DEPTH (args);
16878       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
16879       if (args_depth > parms_depth)
16880         args = get_innermost_template_args (args, parms_depth);
16881
16882       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
16883                                               args, tf_error, NULL_TREE);
16884       if (specs)
16885         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
16886                                                     specs);
16887
16888       /* Merge parameter declarations.  */
16889       decl_parm = skip_artificial_parms_for (decl,
16890                                              DECL_ARGUMENTS (decl));
16891       pattern_parm
16892         = skip_artificial_parms_for (code_pattern,
16893                                      DECL_ARGUMENTS (code_pattern));
16894       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
16895         {
16896           tree parm_type;
16897           tree attributes;
16898           
16899           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16900             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
16901           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
16902                               NULL_TREE);
16903           parm_type = type_decays_to (parm_type);
16904           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16905             TREE_TYPE (decl_parm) = parm_type;
16906           attributes = DECL_ATTRIBUTES (pattern_parm);
16907           if (DECL_ATTRIBUTES (decl_parm) != attributes)
16908             {
16909               DECL_ATTRIBUTES (decl_parm) = attributes;
16910               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16911             }
16912           decl_parm = DECL_CHAIN (decl_parm);
16913           pattern_parm = DECL_CHAIN (pattern_parm);
16914         }
16915       /* Merge any parameters that match with the function parameter
16916          pack.  */
16917       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
16918         {
16919           int i, len;
16920           tree expanded_types;
16921           /* Expand the TYPE_PACK_EXPANSION that provides the types for
16922              the parameters in this function parameter pack.  */
16923           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
16924                                                  args, tf_error, NULL_TREE);
16925           len = TREE_VEC_LENGTH (expanded_types);
16926           for (i = 0; i < len; i++)
16927             {
16928               tree parm_type;
16929               tree attributes;
16930           
16931               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16932                 /* Rename the parameter to include the index.  */
16933                 DECL_NAME (decl_parm) = 
16934                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
16935               parm_type = TREE_VEC_ELT (expanded_types, i);
16936               parm_type = type_decays_to (parm_type);
16937               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16938                 TREE_TYPE (decl_parm) = parm_type;
16939               attributes = DECL_ATTRIBUTES (pattern_parm);
16940               if (DECL_ATTRIBUTES (decl_parm) != attributes)
16941                 {
16942                   DECL_ATTRIBUTES (decl_parm) = attributes;
16943                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16944                 }
16945               decl_parm = DECL_CHAIN (decl_parm);
16946             }
16947         }
16948       /* Merge additional specifiers from the CODE_PATTERN.  */
16949       if (DECL_DECLARED_INLINE_P (code_pattern)
16950           && !DECL_DECLARED_INLINE_P (decl))
16951         DECL_DECLARED_INLINE_P (decl) = 1;
16952     }
16953   else if (TREE_CODE (decl) == VAR_DECL)
16954     {
16955       DECL_INITIAL (decl) =
16956         tsubst_expr (DECL_INITIAL (code_pattern), args,
16957                      tf_error, DECL_TI_TEMPLATE (decl),
16958                      /*integral_constant_expression_p=*/false);
16959       if (VAR_HAD_UNKNOWN_BOUND (decl))
16960         TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
16961                                    tf_error, DECL_TI_TEMPLATE (decl));
16962     }
16963   else
16964     gcc_unreachable ();
16965
16966   pop_access_scope (decl);
16967 }
16968
16969 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
16970    substituted to get DECL.  */
16971
16972 tree
16973 template_for_substitution (tree decl)
16974 {
16975   tree tmpl = DECL_TI_TEMPLATE (decl);
16976
16977   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
16978      for the instantiation.  This is not always the most general
16979      template.  Consider, for example:
16980
16981         template <class T>
16982         struct S { template <class U> void f();
16983                    template <> void f<int>(); };
16984
16985      and an instantiation of S<double>::f<int>.  We want TD to be the
16986      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
16987   while (/* An instantiation cannot have a definition, so we need a
16988             more general template.  */
16989          DECL_TEMPLATE_INSTANTIATION (tmpl)
16990            /* We must also deal with friend templates.  Given:
16991
16992                 template <class T> struct S {
16993                   template <class U> friend void f() {};
16994                 };
16995
16996               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
16997               so far as the language is concerned, but that's still
16998               where we get the pattern for the instantiation from.  On
16999               other hand, if the definition comes outside the class, say:
17000
17001                 template <class T> struct S {
17002                   template <class U> friend void f();
17003                 };
17004                 template <class U> friend void f() {}
17005
17006               we don't need to look any further.  That's what the check for
17007               DECL_INITIAL is for.  */
17008           || (TREE_CODE (decl) == FUNCTION_DECL
17009               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
17010               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
17011     {
17012       /* The present template, TD, should not be a definition.  If it
17013          were a definition, we should be using it!  Note that we
17014          cannot restructure the loop to just keep going until we find
17015          a template with a definition, since that might go too far if
17016          a specialization was declared, but not defined.  */
17017       gcc_assert (TREE_CODE (decl) != VAR_DECL
17018                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
17019
17020       /* Fetch the more general template.  */
17021       tmpl = DECL_TI_TEMPLATE (tmpl);
17022     }
17023
17024   return tmpl;
17025 }
17026
17027 /* Returns true if we need to instantiate this template instance even if we
17028    know we aren't going to emit it..  */
17029
17030 bool
17031 always_instantiate_p (tree decl)
17032 {
17033   /* We always instantiate inline functions so that we can inline them.  An
17034      explicit instantiation declaration prohibits implicit instantiation of
17035      non-inline functions.  With high levels of optimization, we would
17036      normally inline non-inline functions -- but we're not allowed to do
17037      that for "extern template" functions.  Therefore, we check
17038      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
17039   return ((TREE_CODE (decl) == FUNCTION_DECL
17040            && DECL_DECLARED_INLINE_P (decl))
17041           /* And we need to instantiate static data members so that
17042              their initializers are available in integral constant
17043              expressions.  */
17044           || (TREE_CODE (decl) == VAR_DECL
17045               && decl_maybe_constant_var_p (decl)));
17046 }
17047
17048 /* Produce the definition of D, a _DECL generated from a template.  If
17049    DEFER_OK is nonzero, then we don't have to actually do the
17050    instantiation now; we just have to do it sometime.  Normally it is
17051    an error if this is an explicit instantiation but D is undefined.
17052    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
17053    explicitly instantiated class template.  */
17054
17055 tree
17056 instantiate_decl (tree d, int defer_ok,
17057                   bool expl_inst_class_mem_p)
17058 {
17059   tree tmpl = DECL_TI_TEMPLATE (d);
17060   tree gen_args;
17061   tree args;
17062   tree td;
17063   tree code_pattern;
17064   tree spec;
17065   tree gen_tmpl;
17066   bool pattern_defined;
17067   int need_push;
17068   location_t saved_loc = input_location;
17069   bool external_p;
17070
17071   /* This function should only be used to instantiate templates for
17072      functions and static member variables.  */
17073   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
17074               || TREE_CODE (d) == VAR_DECL);
17075
17076   /* Variables are never deferred; if instantiation is required, they
17077      are instantiated right away.  That allows for better code in the
17078      case that an expression refers to the value of the variable --
17079      if the variable has a constant value the referring expression can
17080      take advantage of that fact.  */
17081   if (TREE_CODE (d) == VAR_DECL
17082       || DECL_DECLARED_CONSTEXPR_P (d))
17083     defer_ok = 0;
17084
17085   /* Don't instantiate cloned functions.  Instead, instantiate the
17086      functions they cloned.  */
17087   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
17088     d = DECL_CLONED_FUNCTION (d);
17089
17090   if (DECL_TEMPLATE_INSTANTIATED (d)
17091       || DECL_TEMPLATE_SPECIALIZATION (d))
17092     /* D has already been instantiated or explicitly specialized, so
17093        there's nothing for us to do here.
17094
17095        It might seem reasonable to check whether or not D is an explicit
17096        instantiation, and, if so, stop here.  But when an explicit
17097        instantiation is deferred until the end of the compilation,
17098        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
17099        the instantiation.  */
17100     return d;
17101
17102   /* Check to see whether we know that this template will be
17103      instantiated in some other file, as with "extern template"
17104      extension.  */
17105   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
17106
17107   /* In general, we do not instantiate such templates.  */
17108   if (external_p && !always_instantiate_p (d))
17109     return d;
17110
17111   gen_tmpl = most_general_template (tmpl);
17112   gen_args = DECL_TI_ARGS (d);
17113
17114   if (tmpl != gen_tmpl)
17115     /* We should already have the extra args.  */
17116     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
17117                 == TMPL_ARGS_DEPTH (gen_args));
17118   /* And what's in the hash table should match D.  */
17119   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
17120               || spec == NULL_TREE);
17121
17122   /* This needs to happen before any tsubsting.  */
17123   if (! push_tinst_level (d))
17124     return d;
17125
17126   timevar_push (TV_PARSE);
17127
17128   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
17129      for the instantiation.  */
17130   td = template_for_substitution (d);
17131   code_pattern = DECL_TEMPLATE_RESULT (td);
17132
17133   /* We should never be trying to instantiate a member of a class
17134      template or partial specialization.  */
17135   gcc_assert (d != code_pattern);
17136
17137   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
17138       || DECL_TEMPLATE_SPECIALIZATION (td))
17139     /* In the case of a friend template whose definition is provided
17140        outside the class, we may have too many arguments.  Drop the
17141        ones we don't need.  The same is true for specializations.  */
17142     args = get_innermost_template_args
17143       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
17144   else
17145     args = gen_args;
17146
17147   if (TREE_CODE (d) == FUNCTION_DECL)
17148     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
17149   else
17150     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
17151
17152   /* We may be in the middle of deferred access check.  Disable it now.  */
17153   push_deferring_access_checks (dk_no_deferred);
17154
17155   /* Unless an explicit instantiation directive has already determined
17156      the linkage of D, remember that a definition is available for
17157      this entity.  */
17158   if (pattern_defined
17159       && !DECL_INTERFACE_KNOWN (d)
17160       && !DECL_NOT_REALLY_EXTERN (d))
17161     mark_definable (d);
17162
17163   DECL_SOURCE_LOCATION (td) = DECL_SOURCE_LOCATION (code_pattern);
17164   DECL_SOURCE_LOCATION (d) = DECL_SOURCE_LOCATION (code_pattern);
17165   input_location = DECL_SOURCE_LOCATION (d);
17166
17167   /* If D is a member of an explicitly instantiated class template,
17168      and no definition is available, treat it like an implicit
17169      instantiation.  */
17170   if (!pattern_defined && expl_inst_class_mem_p
17171       && DECL_EXPLICIT_INSTANTIATION (d))
17172     {
17173       DECL_NOT_REALLY_EXTERN (d) = 0;
17174       DECL_INTERFACE_KNOWN (d) = 0;
17175       SET_DECL_IMPLICIT_INSTANTIATION (d);
17176     }
17177
17178   /* Recheck the substitutions to obtain any warning messages
17179      about ignoring cv qualifiers.  Don't do this for artificial decls,
17180      as it breaks the context-sensitive substitution for lambda op(). */
17181   if (!defer_ok && !DECL_ARTIFICIAL (d))
17182     {
17183       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
17184       tree type = TREE_TYPE (gen);
17185
17186       /* Make sure that we can see identifiers, and compute access
17187          correctly.  D is already the target FUNCTION_DECL with the
17188          right context.  */
17189       push_access_scope (d);
17190
17191       if (TREE_CODE (gen) == FUNCTION_DECL)
17192         {
17193           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
17194           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
17195                                           d);
17196           /* Don't simply tsubst the function type, as that will give
17197              duplicate warnings about poor parameter qualifications.
17198              The function arguments are the same as the decl_arguments
17199              without the top level cv qualifiers.  */
17200           type = TREE_TYPE (type);
17201         }
17202       tsubst (type, gen_args, tf_warning_or_error, d);
17203
17204       pop_access_scope (d);
17205     }
17206
17207   /* Defer all other templates, unless we have been explicitly
17208      forbidden from doing so.  */
17209   if (/* If there is no definition, we cannot instantiate the
17210          template.  */
17211       ! pattern_defined
17212       /* If it's OK to postpone instantiation, do so.  */
17213       || defer_ok
17214       /* If this is a static data member that will be defined
17215          elsewhere, we don't want to instantiate the entire data
17216          member, but we do want to instantiate the initializer so that
17217          we can substitute that elsewhere.  */
17218       || (external_p && TREE_CODE (d) == VAR_DECL))
17219     {
17220       /* The definition of the static data member is now required so
17221          we must substitute the initializer.  */
17222       if (TREE_CODE (d) == VAR_DECL
17223           && !DECL_INITIAL (d)
17224           && DECL_INITIAL (code_pattern))
17225         {
17226           tree ns;
17227           tree init;
17228           bool const_init = false;
17229
17230           ns = decl_namespace_context (d);
17231           push_nested_namespace (ns);
17232           push_nested_class (DECL_CONTEXT (d));
17233           init = tsubst_expr (DECL_INITIAL (code_pattern),
17234                               args,
17235                               tf_warning_or_error, NULL_TREE,
17236                               /*integral_constant_expression_p=*/false);
17237           /* Make sure the initializer is still constant, in case of
17238              circular dependency (template/instantiate6.C). */
17239           const_init
17240             = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
17241           cp_finish_decl (d, init, /*init_const_expr_p=*/const_init,
17242                           /*asmspec_tree=*/NULL_TREE,
17243                           LOOKUP_ONLYCONVERTING);
17244           pop_nested_class ();
17245           pop_nested_namespace (ns);
17246         }
17247
17248       /* We restore the source position here because it's used by
17249          add_pending_template.  */
17250       input_location = saved_loc;
17251
17252       if (at_eof && !pattern_defined
17253           && DECL_EXPLICIT_INSTANTIATION (d)
17254           && DECL_NOT_REALLY_EXTERN (d))
17255         /* [temp.explicit]
17256
17257            The definition of a non-exported function template, a
17258            non-exported member function template, or a non-exported
17259            member function or static data member of a class template
17260            shall be present in every translation unit in which it is
17261            explicitly instantiated.  */
17262         permerror (input_location,  "explicit instantiation of %qD "
17263                    "but no definition available", d);
17264
17265       /* If we're in unevaluated context, we just wanted to get the
17266          constant value; this isn't an odr use, so don't queue
17267          a full instantiation.  */
17268       if (cp_unevaluated_operand != 0)
17269         goto out;
17270       /* ??? Historically, we have instantiated inline functions, even
17271          when marked as "extern template".  */
17272       if (!(external_p && TREE_CODE (d) == VAR_DECL))
17273         add_pending_template (d);
17274       goto out;
17275     }
17276   /* Tell the repository that D is available in this translation unit
17277      -- and see if it is supposed to be instantiated here.  */
17278   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
17279     {
17280       /* In a PCH file, despite the fact that the repository hasn't
17281          requested instantiation in the PCH it is still possible that
17282          an instantiation will be required in a file that includes the
17283          PCH.  */
17284       if (pch_file)
17285         add_pending_template (d);
17286       /* Instantiate inline functions so that the inliner can do its
17287          job, even though we'll not be emitting a copy of this
17288          function.  */
17289       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
17290         goto out;
17291     }
17292
17293   need_push = !cfun || !global_bindings_p ();
17294   if (need_push)
17295     push_to_top_level ();
17296
17297   /* Mark D as instantiated so that recursive calls to
17298      instantiate_decl do not try to instantiate it again.  */
17299   DECL_TEMPLATE_INSTANTIATED (d) = 1;
17300
17301   /* Regenerate the declaration in case the template has been modified
17302      by a subsequent redeclaration.  */
17303   regenerate_decl_from_template (d, td);
17304
17305   /* We already set the file and line above.  Reset them now in case
17306      they changed as a result of calling regenerate_decl_from_template.  */
17307   input_location = DECL_SOURCE_LOCATION (d);
17308
17309   if (TREE_CODE (d) == VAR_DECL)
17310     {
17311       tree init;
17312       bool const_init = false;
17313
17314       /* Clear out DECL_RTL; whatever was there before may not be right
17315          since we've reset the type of the declaration.  */
17316       SET_DECL_RTL (d, NULL);
17317       DECL_IN_AGGR_P (d) = 0;
17318
17319       /* The initializer is placed in DECL_INITIAL by
17320          regenerate_decl_from_template so we don't need to
17321          push/pop_access_scope again here.  Pull it out so that
17322          cp_finish_decl can process it.  */
17323       init = DECL_INITIAL (d);
17324       DECL_INITIAL (d) = NULL_TREE;
17325       DECL_INITIALIZED_P (d) = 0;
17326
17327       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
17328          initializer.  That function will defer actual emission until
17329          we have a chance to determine linkage.  */
17330       DECL_EXTERNAL (d) = 0;
17331
17332       /* Enter the scope of D so that access-checking works correctly.  */
17333       push_nested_class (DECL_CONTEXT (d));
17334       const_init = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (code_pattern);
17335       cp_finish_decl (d, init, const_init, NULL_TREE, 0);
17336       pop_nested_class ();
17337     }
17338   else if (TREE_CODE (d) == FUNCTION_DECL)
17339     {
17340       htab_t saved_local_specializations;
17341       tree subst_decl;
17342       tree tmpl_parm;
17343       tree spec_parm;
17344
17345       /* Save away the current list, in case we are instantiating one
17346          template from within the body of another.  */
17347       saved_local_specializations = local_specializations;
17348
17349       /* Set up the list of local specializations.  */
17350       local_specializations = htab_create (37,
17351                                            hash_local_specialization,
17352                                            eq_local_specializations,
17353                                            NULL);
17354
17355       /* Set up context.  */
17356       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
17357
17358       /* Create substitution entries for the parameters.  */
17359       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
17360       tmpl_parm = DECL_ARGUMENTS (subst_decl);
17361       spec_parm = DECL_ARGUMENTS (d);
17362       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
17363         {
17364           register_local_specialization (spec_parm, tmpl_parm);
17365           spec_parm = skip_artificial_parms_for (d, spec_parm);
17366           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
17367         }
17368       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
17369         {
17370           register_local_specialization (spec_parm, tmpl_parm);
17371           tmpl_parm = DECL_CHAIN (tmpl_parm);
17372           spec_parm = DECL_CHAIN (spec_parm);
17373         }
17374       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
17375         {
17376           /* Register the (value) argument pack as a specialization of
17377              TMPL_PARM, then move on.  */
17378           tree argpack = make_fnparm_pack (spec_parm);
17379           register_local_specialization (argpack, tmpl_parm);
17380           tmpl_parm = DECL_CHAIN (tmpl_parm);
17381           spec_parm = NULL_TREE;
17382         }
17383       gcc_assert (!spec_parm);
17384
17385       /* Substitute into the body of the function.  */
17386       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
17387                    tf_warning_or_error, tmpl,
17388                    /*integral_constant_expression_p=*/false);
17389
17390       /* Set the current input_location to the end of the function
17391          so that finish_function knows where we are.  */
17392       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
17393
17394       /* We don't need the local specializations any more.  */
17395       htab_delete (local_specializations);
17396       local_specializations = saved_local_specializations;
17397
17398       /* Finish the function.  */
17399       d = finish_function (0);
17400       expand_or_defer_fn (d);
17401     }
17402
17403   /* We're not deferring instantiation any more.  */
17404   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
17405
17406   if (need_push)
17407     pop_from_top_level ();
17408
17409 out:
17410   input_location = saved_loc;
17411   pop_deferring_access_checks ();
17412   pop_tinst_level ();
17413
17414   timevar_pop (TV_PARSE);
17415
17416   return d;
17417 }
17418
17419 /* Run through the list of templates that we wish we could
17420    instantiate, and instantiate any we can.  RETRIES is the
17421    number of times we retry pending template instantiation.  */
17422
17423 void
17424 instantiate_pending_templates (int retries)
17425 {
17426   int reconsider;
17427   location_t saved_loc = input_location;
17428
17429   /* Instantiating templates may trigger vtable generation.  This in turn
17430      may require further template instantiations.  We place a limit here
17431      to avoid infinite loop.  */
17432   if (pending_templates && retries >= max_tinst_depth)
17433     {
17434       tree decl = pending_templates->tinst->decl;
17435
17436       error ("template instantiation depth exceeds maximum of %d"
17437              " instantiating %q+D, possibly from virtual table generation"
17438              " (use -ftemplate-depth= to increase the maximum)",
17439              max_tinst_depth, decl);
17440       if (TREE_CODE (decl) == FUNCTION_DECL)
17441         /* Pretend that we defined it.  */
17442         DECL_INITIAL (decl) = error_mark_node;
17443       return;
17444     }
17445
17446   do
17447     {
17448       struct pending_template **t = &pending_templates;
17449       struct pending_template *last = NULL;
17450       reconsider = 0;
17451       while (*t)
17452         {
17453           tree instantiation = reopen_tinst_level ((*t)->tinst);
17454           bool complete = false;
17455
17456           if (TYPE_P (instantiation))
17457             {
17458               tree fn;
17459
17460               if (!COMPLETE_TYPE_P (instantiation))
17461                 {
17462                   instantiate_class_template (instantiation);
17463                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
17464                     for (fn = TYPE_METHODS (instantiation);
17465                          fn;
17466                          fn = TREE_CHAIN (fn))
17467                       if (! DECL_ARTIFICIAL (fn))
17468                         instantiate_decl (fn,
17469                                           /*defer_ok=*/0,
17470                                           /*expl_inst_class_mem_p=*/false);
17471                   if (COMPLETE_TYPE_P (instantiation))
17472                     reconsider = 1;
17473                 }
17474
17475               complete = COMPLETE_TYPE_P (instantiation);
17476             }
17477           else
17478             {
17479               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
17480                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
17481                 {
17482                   instantiation
17483                     = instantiate_decl (instantiation,
17484                                         /*defer_ok=*/0,
17485                                         /*expl_inst_class_mem_p=*/false);
17486                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
17487                     reconsider = 1;
17488                 }
17489
17490               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
17491                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
17492             }
17493
17494           if (complete)
17495             /* If INSTANTIATION has been instantiated, then we don't
17496                need to consider it again in the future.  */
17497             *t = (*t)->next;
17498           else
17499             {
17500               last = *t;
17501               t = &(*t)->next;
17502             }
17503           tinst_depth = 0;
17504           current_tinst_level = NULL;
17505         }
17506       last_pending_template = last;
17507     }
17508   while (reconsider);
17509
17510   input_location = saved_loc;
17511 }
17512
17513 /* Substitute ARGVEC into T, which is a list of initializers for
17514    either base class or a non-static data member.  The TREE_PURPOSEs
17515    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
17516    instantiate_decl.  */
17517
17518 static tree
17519 tsubst_initializer_list (tree t, tree argvec)
17520 {
17521   tree inits = NULL_TREE;
17522
17523   for (; t; t = TREE_CHAIN (t))
17524     {
17525       tree decl;
17526       tree init;
17527       tree expanded_bases = NULL_TREE;
17528       tree expanded_arguments = NULL_TREE;
17529       int i, len = 1;
17530
17531       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
17532         {
17533           tree expr;
17534           tree arg;
17535
17536           /* Expand the base class expansion type into separate base
17537              classes.  */
17538           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
17539                                                  tf_warning_or_error,
17540                                                  NULL_TREE);
17541           if (expanded_bases == error_mark_node)
17542             continue;
17543           
17544           /* We'll be building separate TREE_LISTs of arguments for
17545              each base.  */
17546           len = TREE_VEC_LENGTH (expanded_bases);
17547           expanded_arguments = make_tree_vec (len);
17548           for (i = 0; i < len; i++)
17549             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
17550
17551           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
17552              expand each argument in the TREE_VALUE of t.  */
17553           expr = make_node (EXPR_PACK_EXPANSION);
17554           PACK_EXPANSION_PARAMETER_PACKS (expr) =
17555             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
17556
17557           if (TREE_VALUE (t) == void_type_node)
17558             /* VOID_TYPE_NODE is used to indicate
17559                value-initialization.  */
17560             {
17561               for (i = 0; i < len; i++)
17562                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
17563             }
17564           else
17565             {
17566               /* Substitute parameter packs into each argument in the
17567                  TREE_LIST.  */
17568               in_base_initializer = 1;
17569               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
17570                 {
17571                   tree expanded_exprs;
17572
17573                   /* Expand the argument.  */
17574                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
17575                   expanded_exprs 
17576                     = tsubst_pack_expansion (expr, argvec,
17577                                              tf_warning_or_error,
17578                                              NULL_TREE);
17579                   if (expanded_exprs == error_mark_node)
17580                     continue;
17581
17582                   /* Prepend each of the expanded expressions to the
17583                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
17584                   for (i = 0; i < len; i++)
17585                     {
17586                       TREE_VEC_ELT (expanded_arguments, i) = 
17587                         tree_cons (NULL_TREE, 
17588                                    TREE_VEC_ELT (expanded_exprs, i),
17589                                    TREE_VEC_ELT (expanded_arguments, i));
17590                     }
17591                 }
17592               in_base_initializer = 0;
17593
17594               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
17595                  since we built them backwards.  */
17596               for (i = 0; i < len; i++)
17597                 {
17598                   TREE_VEC_ELT (expanded_arguments, i) = 
17599                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
17600                 }
17601             }
17602         }
17603
17604       for (i = 0; i < len; ++i)
17605         {
17606           if (expanded_bases)
17607             {
17608               decl = TREE_VEC_ELT (expanded_bases, i);
17609               decl = expand_member_init (decl);
17610               init = TREE_VEC_ELT (expanded_arguments, i);
17611             }
17612           else
17613             {
17614               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
17615                                   tf_warning_or_error, NULL_TREE);
17616
17617               decl = expand_member_init (decl);
17618               if (decl && !DECL_P (decl))
17619                 in_base_initializer = 1;
17620
17621               init = TREE_VALUE (t);
17622               if (init != void_type_node)
17623                 init = tsubst_expr (init, argvec,
17624                                     tf_warning_or_error, NULL_TREE,
17625                                     /*integral_constant_expression_p=*/false);
17626               in_base_initializer = 0;
17627             }
17628
17629           if (decl)
17630             {
17631               init = build_tree_list (decl, init);
17632               TREE_CHAIN (init) = inits;
17633               inits = init;
17634             }
17635         }
17636     }
17637   return inits;
17638 }
17639
17640 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
17641
17642 static void
17643 set_current_access_from_decl (tree decl)
17644 {
17645   if (TREE_PRIVATE (decl))
17646     current_access_specifier = access_private_node;
17647   else if (TREE_PROTECTED (decl))
17648     current_access_specifier = access_protected_node;
17649   else
17650     current_access_specifier = access_public_node;
17651 }
17652
17653 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
17654    is the instantiation (which should have been created with
17655    start_enum) and ARGS are the template arguments to use.  */
17656
17657 static void
17658 tsubst_enum (tree tag, tree newtag, tree args)
17659 {
17660   tree e;
17661
17662   if (SCOPED_ENUM_P (newtag))
17663     begin_scope (sk_scoped_enum, newtag);
17664
17665   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
17666     {
17667       tree value;
17668       tree decl;
17669
17670       decl = TREE_VALUE (e);
17671       /* Note that in a template enum, the TREE_VALUE is the
17672          CONST_DECL, not the corresponding INTEGER_CST.  */
17673       value = tsubst_expr (DECL_INITIAL (decl),
17674                            args, tf_warning_or_error, NULL_TREE,
17675                            /*integral_constant_expression_p=*/true);
17676
17677       /* Give this enumeration constant the correct access.  */
17678       set_current_access_from_decl (decl);
17679
17680       /* Actually build the enumerator itself.  */
17681       build_enumerator
17682         (DECL_NAME (decl), value, newtag, DECL_SOURCE_LOCATION (decl));
17683     }
17684
17685   if (SCOPED_ENUM_P (newtag))
17686     finish_scope ();
17687
17688   finish_enum_value_list (newtag);
17689   finish_enum (newtag);
17690
17691   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
17692     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
17693 }
17694
17695 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
17696    its type -- but without substituting the innermost set of template
17697    arguments.  So, innermost set of template parameters will appear in
17698    the type.  */
17699
17700 tree
17701 get_mostly_instantiated_function_type (tree decl)
17702 {
17703   tree fn_type;
17704   tree tmpl;
17705   tree targs;
17706   tree tparms;
17707   int parm_depth;
17708
17709   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
17710   targs = DECL_TI_ARGS (decl);
17711   tparms = DECL_TEMPLATE_PARMS (tmpl);
17712   parm_depth = TMPL_PARMS_DEPTH (tparms);
17713
17714   /* There should be as many levels of arguments as there are levels
17715      of parameters.  */
17716   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
17717
17718   fn_type = TREE_TYPE (tmpl);
17719
17720   if (parm_depth == 1)
17721     /* No substitution is necessary.  */
17722     ;
17723   else
17724     {
17725       int i, save_access_control;
17726       tree partial_args;
17727
17728       /* Replace the innermost level of the TARGS with NULL_TREEs to
17729          let tsubst know not to substitute for those parameters.  */
17730       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
17731       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
17732         SET_TMPL_ARGS_LEVEL (partial_args, i,
17733                              TMPL_ARGS_LEVEL (targs, i));
17734       SET_TMPL_ARGS_LEVEL (partial_args,
17735                            TMPL_ARGS_DEPTH (targs),
17736                            make_tree_vec (DECL_NTPARMS (tmpl)));
17737
17738       /* Disable access control as this function is used only during
17739          name-mangling.  */
17740       save_access_control = flag_access_control;
17741       flag_access_control = 0;
17742
17743       ++processing_template_decl;
17744       /* Now, do the (partial) substitution to figure out the
17745          appropriate function type.  */
17746       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
17747       --processing_template_decl;
17748
17749       /* Substitute into the template parameters to obtain the real
17750          innermost set of parameters.  This step is important if the
17751          innermost set of template parameters contains value
17752          parameters whose types depend on outer template parameters.  */
17753       TREE_VEC_LENGTH (partial_args)--;
17754       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
17755
17756       flag_access_control = save_access_control;
17757     }
17758
17759   return fn_type;
17760 }
17761
17762 /* Return truthvalue if we're processing a template different from
17763    the last one involved in diagnostics.  */
17764 int
17765 problematic_instantiation_changed (void)
17766 {
17767   return last_template_error_tick != tinst_level_tick;
17768 }
17769
17770 /* Remember current template involved in diagnostics.  */
17771 void
17772 record_last_problematic_instantiation (void)
17773 {
17774   last_template_error_tick = tinst_level_tick;
17775 }
17776
17777 struct tinst_level *
17778 current_instantiation (void)
17779 {
17780   return current_tinst_level;
17781 }
17782
17783 /* [temp.param] Check that template non-type parm TYPE is of an allowable
17784    type. Return zero for ok, nonzero for disallowed. Issue error and
17785    warning messages under control of COMPLAIN.  */
17786
17787 static int
17788 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
17789 {
17790   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
17791     return 0;
17792   else if (POINTER_TYPE_P (type))
17793     return 0;
17794   else if (TYPE_PTR_TO_MEMBER_P (type))
17795     return 0;
17796   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
17797     return 0;
17798   else if (TREE_CODE (type) == TYPENAME_TYPE)
17799     return 0;
17800
17801   if (complain & tf_error)
17802     error ("%q#T is not a valid type for a template constant parameter", type);
17803   return 1;
17804 }
17805
17806 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
17807    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
17808
17809 static bool
17810 dependent_type_p_r (tree type)
17811 {
17812   tree scope;
17813
17814   /* [temp.dep.type]
17815
17816      A type is dependent if it is:
17817
17818      -- a template parameter. Template template parameters are types
17819         for us (since TYPE_P holds true for them) so we handle
17820         them here.  */
17821   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
17822       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
17823     return true;
17824   /* -- a qualified-id with a nested-name-specifier which contains a
17825         class-name that names a dependent type or whose unqualified-id
17826         names a dependent type.  */
17827   if (TREE_CODE (type) == TYPENAME_TYPE)
17828     return true;
17829   /* -- a cv-qualified type where the cv-unqualified type is
17830         dependent.  */
17831   type = TYPE_MAIN_VARIANT (type);
17832   /* -- a compound type constructed from any dependent type.  */
17833   if (TYPE_PTR_TO_MEMBER_P (type))
17834     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
17835             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
17836                                            (type)));
17837   else if (TREE_CODE (type) == POINTER_TYPE
17838            || TREE_CODE (type) == REFERENCE_TYPE)
17839     return dependent_type_p (TREE_TYPE (type));
17840   else if (TREE_CODE (type) == FUNCTION_TYPE
17841            || TREE_CODE (type) == METHOD_TYPE)
17842     {
17843       tree arg_type;
17844
17845       if (dependent_type_p (TREE_TYPE (type)))
17846         return true;
17847       for (arg_type = TYPE_ARG_TYPES (type);
17848            arg_type;
17849            arg_type = TREE_CHAIN (arg_type))
17850         if (dependent_type_p (TREE_VALUE (arg_type)))
17851           return true;
17852       return false;
17853     }
17854   /* -- an array type constructed from any dependent type or whose
17855         size is specified by a constant expression that is
17856         value-dependent.
17857
17858         We checked for type- and value-dependence of the bounds in
17859         compute_array_index_type, so TYPE_DEPENDENT_P is already set.  */
17860   if (TREE_CODE (type) == ARRAY_TYPE)
17861     {
17862       if (TYPE_DOMAIN (type)
17863           && dependent_type_p (TYPE_DOMAIN (type)))
17864         return true;
17865       return dependent_type_p (TREE_TYPE (type));
17866     }
17867
17868   /* -- a template-id in which either the template name is a template
17869      parameter ...  */
17870   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
17871     return true;
17872   /* ... or any of the template arguments is a dependent type or
17873         an expression that is type-dependent or value-dependent.  */
17874   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
17875            && (any_dependent_template_arguments_p
17876                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
17877     return true;
17878
17879   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
17880      argument of the `typeof' expression is not type-dependent, then
17881      it should already been have resolved.  */
17882   if (TREE_CODE (type) == TYPEOF_TYPE
17883       || TREE_CODE (type) == DECLTYPE_TYPE)
17884     return true;
17885
17886   /* A template argument pack is dependent if any of its packed
17887      arguments are.  */
17888   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
17889     {
17890       tree args = ARGUMENT_PACK_ARGS (type);
17891       int i, len = TREE_VEC_LENGTH (args);
17892       for (i = 0; i < len; ++i)
17893         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
17894           return true;
17895     }
17896
17897   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
17898      be template parameters.  */
17899   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
17900     return true;
17901
17902   /* The standard does not specifically mention types that are local
17903      to template functions or local classes, but they should be
17904      considered dependent too.  For example:
17905
17906        template <int I> void f() {
17907          enum E { a = I };
17908          S<sizeof (E)> s;
17909        }
17910
17911      The size of `E' cannot be known until the value of `I' has been
17912      determined.  Therefore, `E' must be considered dependent.  */
17913   scope = TYPE_CONTEXT (type);
17914   if (scope && TYPE_P (scope))
17915     return dependent_type_p (scope);
17916   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
17917     return type_dependent_expression_p (scope);
17918
17919   /* Other types are non-dependent.  */
17920   return false;
17921 }
17922
17923 /* Returns TRUE if TYPE is dependent, in the sense of
17924    [temp.dep.type].  Note that a NULL type is considered dependent.  */
17925
17926 bool
17927 dependent_type_p (tree type)
17928 {
17929   /* If there are no template parameters in scope, then there can't be
17930      any dependent types.  */
17931   if (!processing_template_decl)
17932     {
17933       /* If we are not processing a template, then nobody should be
17934          providing us with a dependent type.  */
17935       gcc_assert (type);
17936       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
17937       return false;
17938     }
17939
17940   /* If the type is NULL, we have not computed a type for the entity
17941      in question; in that case, the type is dependent.  */
17942   if (!type)
17943     return true;
17944
17945   /* Erroneous types can be considered non-dependent.  */
17946   if (type == error_mark_node)
17947     return false;
17948
17949   /* If we have not already computed the appropriate value for TYPE,
17950      do so now.  */
17951   if (!TYPE_DEPENDENT_P_VALID (type))
17952     {
17953       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
17954       TYPE_DEPENDENT_P_VALID (type) = 1;
17955     }
17956
17957   return TYPE_DEPENDENT_P (type);
17958 }
17959
17960 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
17961    lookup.  In other words, a dependent type that is not the current
17962    instantiation.  */
17963
17964 bool
17965 dependent_scope_p (tree scope)
17966 {
17967   return (scope && TYPE_P (scope) && dependent_type_p (scope)
17968           && !currently_open_class (scope));
17969 }
17970
17971 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
17972    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
17973    expression.  */
17974
17975 /* Note that this predicate is not appropriate for general expressions;
17976    only constant expressions (that satisfy potential_constant_expression)
17977    can be tested for value dependence.
17978
17979    We should really also have a predicate for "instantiation-dependent".
17980
17981    fold_non_dependent_expr: fold if constant and not type-dependent and not value-dependent.
17982      (what about instantiation-dependent constant-expressions?)
17983    is_late_template_attribute: defer if instantiation-dependent.
17984    compute_array_index_type: proceed if constant and not t- or v-dependent
17985      if instantiation-dependent, need to remember full expression
17986    uses_template_parms: FIXME - need to audit callers
17987    tsubst_decl [function_decl]: Why is this using value_dependent_expression_p?
17988    dependent_type_p [array_type]: dependent if index type is dependent
17989      (or non-constant?)
17990    static_assert - instantiation-dependent */
17991
17992 bool
17993 value_dependent_expression_p (tree expression)
17994 {
17995   if (!processing_template_decl)
17996     return false;
17997
17998   /* A name declared with a dependent type.  */
17999   if (DECL_P (expression) && type_dependent_expression_p (expression))
18000     return true;
18001
18002   switch (TREE_CODE (expression))
18003     {
18004     case IDENTIFIER_NODE:
18005       /* A name that has not been looked up -- must be dependent.  */
18006       return true;
18007
18008     case TEMPLATE_PARM_INDEX:
18009       /* A non-type template parm.  */
18010       return true;
18011
18012     case CONST_DECL:
18013       /* A non-type template parm.  */
18014       if (DECL_TEMPLATE_PARM_P (expression))
18015         return true;
18016       return value_dependent_expression_p (DECL_INITIAL (expression));
18017
18018     case VAR_DECL:
18019        /* A constant with integral or enumeration type and is initialized
18020           with an expression that is value-dependent.  */
18021       if (DECL_INITIAL (expression)
18022           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
18023           && value_dependent_expression_p (DECL_INITIAL (expression)))
18024         return true;
18025       return false;
18026
18027     case DYNAMIC_CAST_EXPR:
18028     case STATIC_CAST_EXPR:
18029     case CONST_CAST_EXPR:
18030     case REINTERPRET_CAST_EXPR:
18031     case CAST_EXPR:
18032       /* These expressions are value-dependent if the type to which
18033          the cast occurs is dependent or the expression being casted
18034          is value-dependent.  */
18035       {
18036         tree type = TREE_TYPE (expression);
18037
18038         if (dependent_type_p (type))
18039           return true;
18040
18041         /* A functional cast has a list of operands.  */
18042         expression = TREE_OPERAND (expression, 0);
18043         if (!expression)
18044           {
18045             /* If there are no operands, it must be an expression such
18046                as "int()". This should not happen for aggregate types
18047                because it would form non-constant expressions.  */
18048             gcc_assert (cxx_dialect >= cxx0x
18049                         || INTEGRAL_OR_ENUMERATION_TYPE_P (type));
18050
18051             return false;
18052           }
18053
18054         if (TREE_CODE (expression) == TREE_LIST)
18055           return any_value_dependent_elements_p (expression);
18056
18057         return value_dependent_expression_p (expression);
18058       }
18059
18060     case SIZEOF_EXPR:
18061     case ALIGNOF_EXPR:
18062       /* A `sizeof' expression is value-dependent if the operand is
18063          type-dependent or is a pack expansion.  */
18064       expression = TREE_OPERAND (expression, 0);
18065       if (PACK_EXPANSION_P (expression))
18066         return true;
18067       else if (TYPE_P (expression))
18068         return dependent_type_p (expression);
18069       return type_dependent_expression_p (expression);
18070
18071     case AT_ENCODE_EXPR:
18072       /* An 'encode' expression is value-dependent if the operand is
18073          type-dependent.  */
18074       expression = TREE_OPERAND (expression, 0);
18075       return dependent_type_p (expression);
18076
18077     case NOEXCEPT_EXPR:
18078       expression = TREE_OPERAND (expression, 0);
18079       /* FIXME why check value-dependency?  */
18080       return (type_dependent_expression_p (expression)
18081               || value_dependent_expression_p (expression));
18082
18083     case SCOPE_REF:
18084       {
18085         tree name = TREE_OPERAND (expression, 1);
18086         return value_dependent_expression_p (name);
18087       }
18088
18089     case COMPONENT_REF:
18090       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
18091               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
18092
18093     case NONTYPE_ARGUMENT_PACK:
18094       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
18095          is value-dependent.  */
18096       {
18097         tree values = ARGUMENT_PACK_ARGS (expression);
18098         int i, len = TREE_VEC_LENGTH (values);
18099         
18100         for (i = 0; i < len; ++i)
18101           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
18102             return true;
18103         
18104         return false;
18105       }
18106
18107     case TRAIT_EXPR:
18108       {
18109         tree type2 = TRAIT_EXPR_TYPE2 (expression);
18110         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
18111                 || (type2 ? dependent_type_p (type2) : false));
18112       }
18113
18114     case MODOP_EXPR:
18115       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
18116               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
18117
18118     case ARRAY_REF:
18119       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
18120               || (value_dependent_expression_p (TREE_OPERAND (expression, 1))));
18121
18122     case ADDR_EXPR:
18123       {
18124         tree op = TREE_OPERAND (expression, 0);
18125         return (value_dependent_expression_p (op)
18126                 || has_value_dependent_address (op));
18127       }
18128
18129     case CALL_EXPR:
18130       {
18131         tree fn = get_callee_fndecl (expression);
18132         int i, nargs;
18133         if (!fn && value_dependent_expression_p (CALL_EXPR_FN (expression)))
18134           return true;
18135         nargs = call_expr_nargs (expression);
18136         for (i = 0; i < nargs; ++i)
18137           {
18138             tree op = CALL_EXPR_ARG (expression, i);
18139             /* In a call to a constexpr member function, look through the
18140                implicit ADDR_EXPR on the object argument so that it doesn't
18141                cause the call to be considered value-dependent.  We also
18142                look through it in potential_constant_expression.  */
18143             if (i == 0 && fn && DECL_DECLARED_CONSTEXPR_P (fn)
18144                 && DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
18145                 && TREE_CODE (op) == ADDR_EXPR)
18146               op = TREE_OPERAND (op, 0);
18147             if (value_dependent_expression_p (op))
18148               return true;
18149           }
18150         return false;
18151       }
18152
18153     default:
18154       /* A constant expression is value-dependent if any subexpression is
18155          value-dependent.  */
18156       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
18157         {
18158         case tcc_reference:
18159         case tcc_unary:
18160           return (value_dependent_expression_p
18161                   (TREE_OPERAND (expression, 0)));
18162
18163         case tcc_comparison:
18164         case tcc_binary:
18165           return ((value_dependent_expression_p
18166                    (TREE_OPERAND (expression, 0)))
18167                   || (value_dependent_expression_p
18168                       (TREE_OPERAND (expression, 1))));
18169
18170         case tcc_expression:
18171         case tcc_vl_exp:
18172           {
18173             int i;
18174             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
18175               /* In some cases, some of the operands may be missing.
18176                  (For example, in the case of PREDECREMENT_EXPR, the
18177                  amount to increment by may be missing.)  That doesn't
18178                  make the expression dependent.  */
18179               if (TREE_OPERAND (expression, i)
18180                   && (value_dependent_expression_p
18181                       (TREE_OPERAND (expression, i))))
18182                 return true;
18183             return false;
18184           }
18185
18186         default:
18187           break;
18188         }
18189     }
18190
18191   /* The expression is not value-dependent.  */
18192   return false;
18193 }
18194
18195 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
18196    [temp.dep.expr].  Note that an expression with no type is
18197    considered dependent.  Other parts of the compiler arrange for an
18198    expression with type-dependent subexpressions to have no type, so
18199    this function doesn't have to be fully recursive.  */
18200
18201 bool
18202 type_dependent_expression_p (tree expression)
18203 {
18204   if (!processing_template_decl)
18205     return false;
18206
18207   if (expression == error_mark_node)
18208     return false;
18209
18210   /* An unresolved name is always dependent.  */
18211   if (TREE_CODE (expression) == IDENTIFIER_NODE
18212       || TREE_CODE (expression) == USING_DECL)
18213     return true;
18214
18215   /* Some expression forms are never type-dependent.  */
18216   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
18217       || TREE_CODE (expression) == SIZEOF_EXPR
18218       || TREE_CODE (expression) == ALIGNOF_EXPR
18219       || TREE_CODE (expression) == AT_ENCODE_EXPR
18220       || TREE_CODE (expression) == NOEXCEPT_EXPR
18221       || TREE_CODE (expression) == TRAIT_EXPR
18222       || TREE_CODE (expression) == TYPEID_EXPR
18223       || TREE_CODE (expression) == DELETE_EXPR
18224       || TREE_CODE (expression) == VEC_DELETE_EXPR
18225       || TREE_CODE (expression) == THROW_EXPR)
18226     return false;
18227
18228   /* The types of these expressions depends only on the type to which
18229      the cast occurs.  */
18230   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
18231       || TREE_CODE (expression) == STATIC_CAST_EXPR
18232       || TREE_CODE (expression) == CONST_CAST_EXPR
18233       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
18234       || TREE_CODE (expression) == CAST_EXPR)
18235     return dependent_type_p (TREE_TYPE (expression));
18236
18237   /* The types of these expressions depends only on the type created
18238      by the expression.  */
18239   if (TREE_CODE (expression) == NEW_EXPR
18240       || TREE_CODE (expression) == VEC_NEW_EXPR)
18241     {
18242       /* For NEW_EXPR tree nodes created inside a template, either
18243          the object type itself or a TREE_LIST may appear as the
18244          operand 1.  */
18245       tree type = TREE_OPERAND (expression, 1);
18246       if (TREE_CODE (type) == TREE_LIST)
18247         /* This is an array type.  We need to check array dimensions
18248            as well.  */
18249         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
18250                || value_dependent_expression_p
18251                     (TREE_OPERAND (TREE_VALUE (type), 1));
18252       else
18253         return dependent_type_p (type);
18254     }
18255
18256   if (TREE_CODE (expression) == SCOPE_REF)
18257     {
18258       tree scope = TREE_OPERAND (expression, 0);
18259       tree name = TREE_OPERAND (expression, 1);
18260
18261       /* 14.6.2.2 [temp.dep.expr]: An id-expression is type-dependent if it
18262          contains an identifier associated by name lookup with one or more
18263          declarations declared with a dependent type, or...a
18264          nested-name-specifier or qualified-id that names a member of an
18265          unknown specialization.  */
18266       return (type_dependent_expression_p (name)
18267               || dependent_scope_p (scope));
18268     }
18269
18270   if (TREE_CODE (expression) == FUNCTION_DECL
18271       && DECL_LANG_SPECIFIC (expression)
18272       && DECL_TEMPLATE_INFO (expression)
18273       && (any_dependent_template_arguments_p
18274           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
18275     return true;
18276
18277   if (TREE_CODE (expression) == TEMPLATE_DECL
18278       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
18279     return false;
18280
18281   if (TREE_CODE (expression) == STMT_EXPR)
18282     expression = stmt_expr_value_expr (expression);
18283
18284   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
18285     {
18286       tree elt;
18287       unsigned i;
18288
18289       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
18290         {
18291           if (type_dependent_expression_p (elt))
18292             return true;
18293         }
18294       return false;
18295     }
18296
18297   /* A static data member of the current instantiation with incomplete
18298      array type is type-dependent, as the definition and specializations
18299      can have different bounds.  */
18300   if (TREE_CODE (expression) == VAR_DECL
18301       && DECL_CLASS_SCOPE_P (expression)
18302       && dependent_type_p (DECL_CONTEXT (expression))
18303       && VAR_HAD_UNKNOWN_BOUND (expression))
18304     return true;
18305
18306   if (TREE_TYPE (expression) == unknown_type_node)
18307     {
18308       if (TREE_CODE (expression) == ADDR_EXPR)
18309         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
18310       if (TREE_CODE (expression) == COMPONENT_REF
18311           || TREE_CODE (expression) == OFFSET_REF)
18312         {
18313           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
18314             return true;
18315           expression = TREE_OPERAND (expression, 1);
18316           if (TREE_CODE (expression) == IDENTIFIER_NODE)
18317             return false;
18318         }
18319       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
18320       if (TREE_CODE (expression) == SCOPE_REF)
18321         return false;
18322
18323       if (TREE_CODE (expression) == BASELINK)
18324         expression = BASELINK_FUNCTIONS (expression);
18325
18326       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
18327         {
18328           if (any_dependent_template_arguments_p
18329               (TREE_OPERAND (expression, 1)))
18330             return true;
18331           expression = TREE_OPERAND (expression, 0);
18332         }
18333       gcc_assert (TREE_CODE (expression) == OVERLOAD
18334                   || TREE_CODE (expression) == FUNCTION_DECL);
18335
18336       while (expression)
18337         {
18338           if (type_dependent_expression_p (OVL_CURRENT (expression)))
18339             return true;
18340           expression = OVL_NEXT (expression);
18341         }
18342       return false;
18343     }
18344
18345   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
18346
18347   return (dependent_type_p (TREE_TYPE (expression)));
18348 }
18349
18350 /* Like type_dependent_expression_p, but it also works while not processing
18351    a template definition, i.e. during substitution or mangling.  */
18352
18353 bool
18354 type_dependent_expression_p_push (tree expr)
18355 {
18356   bool b;
18357   ++processing_template_decl;
18358   b = type_dependent_expression_p (expr);
18359   --processing_template_decl;
18360   return b;
18361 }
18362
18363 /* Returns TRUE if ARGS contains a type-dependent expression.  */
18364
18365 bool
18366 any_type_dependent_arguments_p (const VEC(tree,gc) *args)
18367 {
18368   unsigned int i;
18369   tree arg;
18370
18371   FOR_EACH_VEC_ELT (tree, args, i, arg)
18372     {
18373       if (type_dependent_expression_p (arg))
18374         return true;
18375     }
18376   return false;
18377 }
18378
18379 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
18380    expressions) contains any value-dependent expressions.  */
18381
18382 bool
18383 any_value_dependent_elements_p (const_tree list)
18384 {
18385   for (; list; list = TREE_CHAIN (list))
18386     if (value_dependent_expression_p (TREE_VALUE (list)))
18387       return true;
18388
18389   return false;
18390 }
18391
18392 /* Returns TRUE if the ARG (a template argument) is dependent.  */
18393
18394 bool
18395 dependent_template_arg_p (tree arg)
18396 {
18397   if (!processing_template_decl)
18398     return false;
18399
18400   /* Assume a template argument that was wrongly written by the user
18401      is dependent. This is consistent with what
18402      any_dependent_template_arguments_p [that calls this function]
18403      does.  */
18404   if (arg == error_mark_node)
18405     return true;
18406
18407   if (TREE_CODE (arg) == TEMPLATE_DECL
18408       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
18409     return dependent_template_p (arg);
18410   else if (ARGUMENT_PACK_P (arg))
18411     {
18412       tree args = ARGUMENT_PACK_ARGS (arg);
18413       int i, len = TREE_VEC_LENGTH (args);
18414       for (i = 0; i < len; ++i)
18415         {
18416           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
18417             return true;
18418         }
18419
18420       return false;
18421     }
18422   else if (TYPE_P (arg))
18423     return dependent_type_p (arg);
18424   else
18425     return (type_dependent_expression_p (arg)
18426             || value_dependent_expression_p (arg));
18427 }
18428
18429 /* Returns true if ARGS (a collection of template arguments) contains
18430    any types that require structural equality testing.  */
18431
18432 bool
18433 any_template_arguments_need_structural_equality_p (tree args)
18434 {
18435   int i;
18436   int j;
18437
18438   if (!args)
18439     return false;
18440   if (args == error_mark_node)
18441     return true;
18442
18443   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
18444     {
18445       tree level = TMPL_ARGS_LEVEL (args, i + 1);
18446       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
18447         {
18448           tree arg = TREE_VEC_ELT (level, j);
18449           tree packed_args = NULL_TREE;
18450           int k, len = 1;
18451
18452           if (ARGUMENT_PACK_P (arg))
18453             {
18454               /* Look inside the argument pack.  */
18455               packed_args = ARGUMENT_PACK_ARGS (arg);
18456               len = TREE_VEC_LENGTH (packed_args);
18457             }
18458
18459           for (k = 0; k < len; ++k)
18460             {
18461               if (packed_args)
18462                 arg = TREE_VEC_ELT (packed_args, k);
18463
18464               if (error_operand_p (arg))
18465                 return true;
18466               else if (TREE_CODE (arg) == TEMPLATE_DECL
18467                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
18468                 continue;
18469               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
18470                 return true;
18471               else if (!TYPE_P (arg) && TREE_TYPE (arg)
18472                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
18473                 return true;
18474             }
18475         }
18476     }
18477
18478   return false;
18479 }
18480
18481 /* Returns true if ARGS (a collection of template arguments) contains
18482    any dependent arguments.  */
18483
18484 bool
18485 any_dependent_template_arguments_p (const_tree args)
18486 {
18487   int i;
18488   int j;
18489
18490   if (!args)
18491     return false;
18492   if (args == error_mark_node)
18493     return true;
18494
18495   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
18496     {
18497       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
18498       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
18499         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
18500           return true;
18501     }
18502
18503   return false;
18504 }
18505
18506 /* Returns TRUE if the template TMPL is dependent.  */
18507
18508 bool
18509 dependent_template_p (tree tmpl)
18510 {
18511   if (TREE_CODE (tmpl) == OVERLOAD)
18512     {
18513       while (tmpl)
18514         {
18515           if (dependent_template_p (OVL_FUNCTION (tmpl)))
18516             return true;
18517           tmpl = OVL_CHAIN (tmpl);
18518         }
18519       return false;
18520     }
18521
18522   /* Template template parameters are dependent.  */
18523   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
18524       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
18525     return true;
18526   /* So are names that have not been looked up.  */
18527   if (TREE_CODE (tmpl) == SCOPE_REF
18528       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
18529     return true;
18530   /* So are member templates of dependent classes.  */
18531   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
18532     return dependent_type_p (DECL_CONTEXT (tmpl));
18533   return false;
18534 }
18535
18536 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
18537
18538 bool
18539 dependent_template_id_p (tree tmpl, tree args)
18540 {
18541   return (dependent_template_p (tmpl)
18542           || any_dependent_template_arguments_p (args));
18543 }
18544
18545 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
18546    is dependent.  */
18547
18548 bool
18549 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
18550 {
18551   int i;
18552
18553   if (!processing_template_decl)
18554     return false;
18555
18556   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
18557     {
18558       tree decl = TREE_VEC_ELT (declv, i);
18559       tree init = TREE_VEC_ELT (initv, i);
18560       tree cond = TREE_VEC_ELT (condv, i);
18561       tree incr = TREE_VEC_ELT (incrv, i);
18562
18563       if (type_dependent_expression_p (decl))
18564         return true;
18565
18566       if (init && type_dependent_expression_p (init))
18567         return true;
18568
18569       if (type_dependent_expression_p (cond))
18570         return true;
18571
18572       if (COMPARISON_CLASS_P (cond)
18573           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
18574               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
18575         return true;
18576
18577       if (TREE_CODE (incr) == MODOP_EXPR)
18578         {
18579           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
18580               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
18581             return true;
18582         }
18583       else if (type_dependent_expression_p (incr))
18584         return true;
18585       else if (TREE_CODE (incr) == MODIFY_EXPR)
18586         {
18587           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
18588             return true;
18589           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
18590             {
18591               tree t = TREE_OPERAND (incr, 1);
18592               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
18593                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
18594                 return true;
18595             }
18596         }
18597     }
18598
18599   return false;
18600 }
18601
18602 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
18603    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
18604    no such TYPE can be found.  Note that this function peers inside
18605    uninstantiated templates and therefore should be used only in
18606    extremely limited situations.  ONLY_CURRENT_P restricts this
18607    peering to the currently open classes hierarchy (which is required
18608    when comparing types).  */
18609
18610 tree
18611 resolve_typename_type (tree type, bool only_current_p)
18612 {
18613   tree scope;
18614   tree name;
18615   tree decl;
18616   int quals;
18617   tree pushed_scope;
18618   tree result;
18619
18620   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
18621
18622   scope = TYPE_CONTEXT (type);
18623   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
18624      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
18625      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
18626      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
18627      identifier  of the TYPENAME_TYPE anymore.
18628      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
18629      TYPENAME_TYPE instead, we avoid messing up with a possible
18630      typedef variant case.  */
18631   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
18632
18633   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
18634      it first before we can figure out what NAME refers to.  */
18635   if (TREE_CODE (scope) == TYPENAME_TYPE)
18636     scope = resolve_typename_type (scope, only_current_p);
18637   /* If we don't know what SCOPE refers to, then we cannot resolve the
18638      TYPENAME_TYPE.  */
18639   if (TREE_CODE (scope) == TYPENAME_TYPE)
18640     return type;
18641   /* If the SCOPE is a template type parameter, we have no way of
18642      resolving the name.  */
18643   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
18644     return type;
18645   /* If the SCOPE is not the current instantiation, there's no reason
18646      to look inside it.  */
18647   if (only_current_p && !currently_open_class (scope))
18648     return type;
18649   /* If this is a typedef, we don't want to look inside (c++/11987).  */
18650   if (typedef_variant_p (type))
18651     return type;
18652   /* If SCOPE isn't the template itself, it will not have a valid
18653      TYPE_FIELDS list.  */
18654   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
18655     /* scope is either the template itself or a compatible instantiation
18656        like X<T>, so look up the name in the original template.  */
18657     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
18658   else
18659     /* scope is a partial instantiation, so we can't do the lookup or we
18660        will lose the template arguments.  */
18661     return type;
18662   /* Enter the SCOPE so that name lookup will be resolved as if we
18663      were in the class definition.  In particular, SCOPE will no
18664      longer be considered a dependent type.  */
18665   pushed_scope = push_scope (scope);
18666   /* Look up the declaration.  */
18667   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
18668
18669   result = NULL_TREE;
18670   
18671   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
18672      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
18673   if (!decl)
18674     /*nop*/;
18675   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
18676            && TREE_CODE (decl) == TYPE_DECL)
18677     {
18678       result = TREE_TYPE (decl);
18679       if (result == error_mark_node)
18680         result = NULL_TREE;
18681     }
18682   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
18683            && DECL_CLASS_TEMPLATE_P (decl))
18684     {
18685       tree tmpl;
18686       tree args;
18687       /* Obtain the template and the arguments.  */
18688       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
18689       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
18690       /* Instantiate the template.  */
18691       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
18692                                       /*entering_scope=*/0,
18693                                       tf_error | tf_user);
18694       if (result == error_mark_node)
18695         result = NULL_TREE;
18696     }
18697   
18698   /* Leave the SCOPE.  */
18699   if (pushed_scope)
18700     pop_scope (pushed_scope);
18701
18702   /* If we failed to resolve it, return the original typename.  */
18703   if (!result)
18704     return type;
18705   
18706   /* If lookup found a typename type, resolve that too.  */
18707   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
18708     {
18709       /* Ill-formed programs can cause infinite recursion here, so we
18710          must catch that.  */
18711       TYPENAME_IS_RESOLVING_P (type) = 1;
18712       result = resolve_typename_type (result, only_current_p);
18713       TYPENAME_IS_RESOLVING_P (type) = 0;
18714     }
18715   
18716   /* Qualify the resulting type.  */
18717   quals = cp_type_quals (type);
18718   if (quals)
18719     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
18720
18721   return result;
18722 }
18723
18724 /* EXPR is an expression which is not type-dependent.  Return a proxy
18725    for EXPR that can be used to compute the types of larger
18726    expressions containing EXPR.  */
18727
18728 tree
18729 build_non_dependent_expr (tree expr)
18730 {
18731   tree inner_expr;
18732
18733   /* Preserve null pointer constants so that the type of things like
18734      "p == 0" where "p" is a pointer can be determined.  */
18735   if (null_ptr_cst_p (expr))
18736     return expr;
18737   /* Preserve OVERLOADs; the functions must be available to resolve
18738      types.  */
18739   inner_expr = expr;
18740   if (TREE_CODE (inner_expr) == STMT_EXPR)
18741     inner_expr = stmt_expr_value_expr (inner_expr);
18742   if (TREE_CODE (inner_expr) == ADDR_EXPR)
18743     inner_expr = TREE_OPERAND (inner_expr, 0);
18744   if (TREE_CODE (inner_expr) == COMPONENT_REF)
18745     inner_expr = TREE_OPERAND (inner_expr, 1);
18746   if (is_overloaded_fn (inner_expr)
18747       || TREE_CODE (inner_expr) == OFFSET_REF)
18748     return expr;
18749   /* There is no need to return a proxy for a variable.  */
18750   if (TREE_CODE (expr) == VAR_DECL)
18751     return expr;
18752   /* Preserve string constants; conversions from string constants to
18753      "char *" are allowed, even though normally a "const char *"
18754      cannot be used to initialize a "char *".  */
18755   if (TREE_CODE (expr) == STRING_CST)
18756     return expr;
18757   /* Preserve arithmetic constants, as an optimization -- there is no
18758      reason to create a new node.  */
18759   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
18760     return expr;
18761   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
18762      There is at least one place where we want to know that a
18763      particular expression is a throw-expression: when checking a ?:
18764      expression, there are special rules if the second or third
18765      argument is a throw-expression.  */
18766   if (TREE_CODE (expr) == THROW_EXPR)
18767     return expr;
18768
18769   if (TREE_CODE (expr) == COND_EXPR)
18770     return build3 (COND_EXPR,
18771                    TREE_TYPE (expr),
18772                    TREE_OPERAND (expr, 0),
18773                    (TREE_OPERAND (expr, 1)
18774                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
18775                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
18776                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
18777   if (TREE_CODE (expr) == COMPOUND_EXPR
18778       && !COMPOUND_EXPR_OVERLOADED (expr))
18779     return build2 (COMPOUND_EXPR,
18780                    TREE_TYPE (expr),
18781                    TREE_OPERAND (expr, 0),
18782                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
18783
18784   /* If the type is unknown, it can't really be non-dependent */
18785   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
18786
18787   /* Otherwise, build a NON_DEPENDENT_EXPR.
18788
18789      REFERENCE_TYPEs are not stripped for expressions in templates
18790      because doing so would play havoc with mangling.  Consider, for
18791      example:
18792
18793        template <typename T> void f<T& g>() { g(); }
18794
18795      In the body of "f", the expression for "g" will have
18796      REFERENCE_TYPE, even though the standard says that it should
18797      not.  The reason is that we must preserve the syntactic form of
18798      the expression so that mangling (say) "f<g>" inside the body of
18799      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
18800      stripped here.  */
18801   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
18802 }
18803
18804 /* ARGS is a vector of expressions as arguments to a function call.
18805    Replace the arguments with equivalent non-dependent expressions.
18806    This modifies ARGS in place.  */
18807
18808 void
18809 make_args_non_dependent (VEC(tree,gc) *args)
18810 {
18811   unsigned int ix;
18812   tree arg;
18813
18814   FOR_EACH_VEC_ELT (tree, args, ix, arg)
18815     {
18816       tree newarg = build_non_dependent_expr (arg);
18817       if (newarg != arg)
18818         VEC_replace (tree, args, ix, newarg);
18819     }
18820 }
18821
18822 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
18823    with a level one deeper than the actual template parms.  */
18824
18825 tree
18826 make_auto (void)
18827 {
18828   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
18829   TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
18830                                TYPE_DECL, get_identifier ("auto"), au);
18831   TYPE_STUB_DECL (au) = TYPE_NAME (au);
18832   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
18833     (0, processing_template_decl + 1, processing_template_decl + 1,
18834      0, TYPE_NAME (au), NULL_TREE);
18835   TYPE_CANONICAL (au) = canonical_type_parameter (au);
18836   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
18837   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
18838
18839   return au;
18840 }
18841
18842 /* Given type ARG, return std::initializer_list<ARG>.  */
18843
18844 static tree
18845 listify (tree arg)
18846 {
18847   tree std_init_list = namespace_binding
18848     (get_identifier ("initializer_list"), std_node);
18849   tree argvec;
18850   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
18851     {    
18852       error ("deducing from brace-enclosed initializer list requires "
18853              "#include <initializer_list>");
18854       return error_mark_node;
18855     }
18856   argvec = make_tree_vec (1);
18857   TREE_VEC_ELT (argvec, 0) = arg;
18858   return lookup_template_class (std_init_list, argvec, NULL_TREE,
18859                                 NULL_TREE, 0, tf_warning_or_error);
18860 }
18861
18862 /* Replace auto in TYPE with std::initializer_list<auto>.  */
18863
18864 static tree
18865 listify_autos (tree type, tree auto_node)
18866 {
18867   tree init_auto = listify (auto_node);
18868   tree argvec = make_tree_vec (1);
18869   TREE_VEC_ELT (argvec, 0) = init_auto;
18870   if (processing_template_decl)
18871     argvec = add_to_template_args (current_template_args (), argvec);
18872   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
18873 }
18874
18875 /* walk_tree helper for do_auto_deduction.  */
18876
18877 static tree
18878 contains_auto_r (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
18879                  void *type)
18880 {
18881   /* Is this a variable with the type we're looking for?  */
18882   if (DECL_P (*tp)
18883       && TREE_TYPE (*tp) == type)
18884     return *tp;
18885   else
18886     return NULL_TREE;
18887 }
18888
18889 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
18890    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
18891
18892 tree
18893 do_auto_deduction (tree type, tree init, tree auto_node)
18894 {
18895   tree parms, tparms, targs;
18896   tree args[1];
18897   tree decl;
18898   int val;
18899
18900   /* The name of the object being declared shall not appear in the
18901      initializer expression.  */
18902   decl = cp_walk_tree_without_duplicates (&init, contains_auto_r, type);
18903   if (decl)
18904     {
18905       error ("variable %q#D with %<auto%> type used in its own "
18906              "initializer", decl);
18907       return error_mark_node;
18908     }
18909
18910   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
18911      with either a new invented type template parameter U or, if the
18912      initializer is a braced-init-list (8.5.4), with
18913      std::initializer_list<U>.  */
18914   if (BRACE_ENCLOSED_INITIALIZER_P (init))
18915     type = listify_autos (type, auto_node);
18916
18917   init = resolve_nondeduced_context (init);
18918
18919   parms = build_tree_list (NULL_TREE, type);
18920   args[0] = init;
18921   tparms = make_tree_vec (1);
18922   targs = make_tree_vec (1);
18923   TREE_VEC_ELT (tparms, 0)
18924     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
18925   val = type_unification_real (tparms, targs, parms, args, 1, 0,
18926                                DEDUCE_CALL, LOOKUP_NORMAL);
18927   if (val > 0)
18928     {
18929       if (type && type != error_mark_node)
18930         /* If type is error_mark_node a diagnostic must have been
18931            emitted by now.  Also, having a mention to '<type error>'
18932            in the diagnostic is not really useful to the user.  */
18933         error ("unable to deduce %qT from %qE", type, init);
18934       return error_mark_node;
18935     }
18936
18937   /* If the list of declarators contains more than one declarator, the type
18938      of each declared variable is determined as described above. If the
18939      type deduced for the template parameter U is not the same in each
18940      deduction, the program is ill-formed.  */
18941   if (TREE_TYPE (auto_node)
18942       && !same_type_p (TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0)))
18943     {
18944       error ("inconsistent deduction for %qT: %qT and then %qT",
18945              auto_node, TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0));
18946       return error_mark_node;
18947     }
18948   TREE_TYPE (auto_node) = TREE_VEC_ELT (targs, 0);
18949
18950   if (processing_template_decl)
18951     targs = add_to_template_args (current_template_args (), targs);
18952   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
18953 }
18954
18955 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
18956    result.  */
18957
18958 tree
18959 splice_late_return_type (tree type, tree late_return_type)
18960 {
18961   tree argvec;
18962
18963   if (late_return_type == NULL_TREE)
18964     return type;
18965   argvec = make_tree_vec (1);
18966   TREE_VEC_ELT (argvec, 0) = late_return_type;
18967   if (processing_template_decl)
18968     argvec = add_to_template_args (current_template_args (), argvec);
18969   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
18970 }
18971
18972 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
18973
18974 bool
18975 is_auto (const_tree type)
18976 {
18977   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
18978       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
18979     return true;
18980   else
18981     return false;
18982 }
18983
18984 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
18985    appear as a type-specifier for the declaration in question, we don't
18986    have to look through the whole type.  */
18987
18988 tree
18989 type_uses_auto (tree type)
18990 {
18991   enum tree_code code;
18992   if (is_auto (type))
18993     return type;
18994
18995   code = TREE_CODE (type);
18996
18997   if (code == POINTER_TYPE || code == REFERENCE_TYPE
18998       || code == OFFSET_TYPE || code == FUNCTION_TYPE
18999       || code == METHOD_TYPE || code == ARRAY_TYPE)
19000     return type_uses_auto (TREE_TYPE (type));
19001
19002   if (TYPE_PTRMEMFUNC_P (type))
19003     return type_uses_auto (TREE_TYPE (TREE_TYPE
19004                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
19005
19006   return NULL_TREE;
19007 }
19008
19009 /* For a given template T, return the vector of typedefs referenced
19010    in T for which access check is needed at T instantiation time.
19011    T is either  a FUNCTION_DECL or a RECORD_TYPE.
19012    Those typedefs were added to T by the function
19013    append_type_to_template_for_access_check.  */
19014
19015 VEC(qualified_typedef_usage_t,gc)*
19016 get_types_needing_access_check (tree t)
19017 {
19018   tree ti;
19019   VEC(qualified_typedef_usage_t,gc) *result = NULL;
19020
19021   if (!t || t == error_mark_node)
19022     return NULL;
19023
19024   if (!(ti = get_template_info (t)))
19025     return NULL;
19026
19027   if (CLASS_TYPE_P (t)
19028       || TREE_CODE (t) == FUNCTION_DECL)
19029     {
19030       if (!TI_TEMPLATE (ti))
19031         return NULL;
19032
19033       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
19034     }
19035
19036   return result;
19037 }
19038
19039 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
19040    tied to T. That list of typedefs will be access checked at
19041    T instantiation time.
19042    T is either a FUNCTION_DECL or a RECORD_TYPE.
19043    TYPE_DECL is a TYPE_DECL node representing a typedef.
19044    SCOPE is the scope through which TYPE_DECL is accessed.
19045    LOCATION is the location of the usage point of TYPE_DECL.
19046
19047    This function is a subroutine of
19048    append_type_to_template_for_access_check.  */
19049
19050 static void
19051 append_type_to_template_for_access_check_1 (tree t,
19052                                             tree type_decl,
19053                                             tree scope,
19054                                             location_t location)
19055 {
19056   qualified_typedef_usage_t typedef_usage;
19057   tree ti;
19058
19059   if (!t || t == error_mark_node)
19060     return;
19061
19062   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
19063                || CLASS_TYPE_P (t))
19064               && type_decl
19065               && TREE_CODE (type_decl) == TYPE_DECL
19066               && scope);
19067
19068   if (!(ti = get_template_info (t)))
19069     return;
19070
19071   gcc_assert (TI_TEMPLATE (ti));
19072
19073   typedef_usage.typedef_decl = type_decl;
19074   typedef_usage.context = scope;
19075   typedef_usage.locus = location;
19076
19077   VEC_safe_push (qualified_typedef_usage_t, gc,
19078                  TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti),
19079                  &typedef_usage);
19080 }
19081
19082 /* Append TYPE_DECL to the template TEMPL.
19083    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
19084    At TEMPL instanciation time, TYPE_DECL will be checked to see
19085    if it can be accessed through SCOPE.
19086    LOCATION is the location of the usage point of TYPE_DECL.
19087
19088    e.g. consider the following code snippet:
19089
19090      class C
19091      {
19092        typedef int myint;
19093      };
19094
19095      template<class U> struct S
19096      {
19097        C::myint mi; // <-- usage point of the typedef C::myint
19098      };
19099
19100      S<char> s;
19101
19102    At S<char> instantiation time, we need to check the access of C::myint
19103    In other words, we need to check the access of the myint typedef through
19104    the C scope. For that purpose, this function will add the myint typedef
19105    and the scope C through which its being accessed to a list of typedefs
19106    tied to the template S. That list will be walked at template instantiation
19107    time and access check performed on each typedefs it contains.
19108    Note that this particular code snippet should yield an error because
19109    myint is private to C.  */
19110
19111 void
19112 append_type_to_template_for_access_check (tree templ,
19113                                           tree type_decl,
19114                                           tree scope,
19115                                           location_t location)
19116 {
19117   qualified_typedef_usage_t *iter;
19118   int i;
19119
19120   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
19121
19122   /* Make sure we don't append the type to the template twice.  */
19123   FOR_EACH_VEC_ELT (qualified_typedef_usage_t,
19124                     get_types_needing_access_check (templ),
19125                     i, iter)
19126     if (iter->typedef_decl == type_decl && scope == iter->context)
19127       return;
19128
19129   append_type_to_template_for_access_check_1 (templ, type_decl,
19130                                               scope, location);
19131 }
19132
19133 /* Set up the hash tables for template instantiations.  */
19134
19135 void
19136 init_template_processing (void)
19137 {
19138   decl_specializations = htab_create_ggc (37,
19139                                           hash_specialization,
19140                                           eq_specializations,
19141                                           ggc_free);
19142   type_specializations = htab_create_ggc (37,
19143                                           hash_specialization,
19144                                           eq_specializations,
19145                                           ggc_free);
19146 }
19147
19148 /* Print stats about the template hash tables for -fstats.  */
19149
19150 void
19151 print_template_statistics (void)
19152 {
19153   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
19154            "%f collisions\n", (long) htab_size (decl_specializations),
19155            (long) htab_elements (decl_specializations),
19156            htab_collisions (decl_specializations));
19157   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
19158            "%f collisions\n", (long) htab_size (type_specializations),
19159            (long) htab_elements (type_specializations),
19160            htab_collisions (type_specializations));
19161 }
19162
19163 #include "gt-cp-pt.h"