OSDN Git Service

* c-opts.c (c_common_parse_file): If start_end_main_source_file,
[pf3gnuchains/gcc-fork.git] / gcc / cp / pt.c
1 /* Handle parameterized types (templates) for GNU C++.
2    Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
3    2001, 2002, 2003, 2004, 2005, 2007, 2008, 2009
4    Free Software Foundation, Inc.
5    Written by Ken Raeburn (raeburn@cygnus.com) while at Watchmaker Computing.
6    Rewritten by Jason Merrill (jason@cygnus.com).
7
8 This file is part of GCC.
9
10 GCC is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 3, or (at your option)
13 any later version.
14
15 GCC is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 GNU General Public License for more details.
19
20 You should have received a copy of the GNU General Public License
21 along with GCC; see the file COPYING3.  If not see
22 <http://www.gnu.org/licenses/>.  */
23
24 /* Known bugs or deficiencies include:
25
26      all methods must be provided in header files; can't use a source
27      file that contains only the method templates and "just win".  */
28
29 #include "config.h"
30 #include "system.h"
31 #include "coretypes.h"
32 #include "tm.h"
33 #include "obstack.h"
34 #include "tree.h"
35 #include "intl.h"
36 #include "pointer-set.h"
37 #include "flags.h"
38 #include "c-common.h"
39 #include "cp-tree.h"
40 #include "cp-objcp-common.h"
41 #include "tree-inline.h"
42 #include "decl.h"
43 #include "output.h"
44 #include "except.h"
45 #include "toplev.h"
46 #include "rtl.h"
47 #include "timevar.h"
48 #include "tree-iterator.h"
49 #include "vecprim.h"
50
51 /* The type of functions taking a tree, and some additional data, and
52    returning an int.  */
53 typedef int (*tree_fn_t) (tree, void*);
54
55 /* The PENDING_TEMPLATES is a TREE_LIST of templates whose
56    instantiations have been deferred, either because their definitions
57    were not yet available, or because we were putting off doing the work.  */
58 struct GTY (()) pending_template {
59   struct pending_template *next;
60   struct tinst_level *tinst;
61 };
62
63 static GTY(()) struct pending_template *pending_templates;
64 static GTY(()) struct pending_template *last_pending_template;
65
66 int processing_template_parmlist;
67 static int template_header_count;
68
69 static GTY(()) tree saved_trees;
70 static VEC(int,heap) *inline_parm_levels;
71
72 static GTY(()) struct tinst_level *current_tinst_level;
73
74 static GTY(()) tree saved_access_scope;
75
76 /* Live only within one (recursive) call to tsubst_expr.  We use
77    this to pass the statement expression node from the STMT_EXPR
78    to the EXPR_STMT that is its result.  */
79 static tree cur_stmt_expr;
80
81 /* A map from local variable declarations in the body of the template
82    presently being instantiated to the corresponding instantiated
83    local variables.  */
84 static htab_t local_specializations;
85
86 typedef struct GTY(()) spec_entry
87 {
88   tree tmpl;
89   tree args;
90   tree spec;
91 } spec_entry;
92
93 static GTY ((param_is (spec_entry)))
94   htab_t decl_specializations;
95
96 static GTY ((param_is (spec_entry)))
97   htab_t type_specializations;
98
99 /* Contains canonical template parameter types. The vector is indexed by
100    the TEMPLATE_TYPE_IDX of the template parameter. Each element is a
101    TREE_LIST, whose TREE_VALUEs contain the canonical template
102    parameters of various types and levels.  */
103 static GTY(()) VEC(tree,gc) *canonical_template_parms;
104
105 #define UNIFY_ALLOW_NONE 0
106 #define UNIFY_ALLOW_MORE_CV_QUAL 1
107 #define UNIFY_ALLOW_LESS_CV_QUAL 2
108 #define UNIFY_ALLOW_DERIVED 4
109 #define UNIFY_ALLOW_INTEGER 8
110 #define UNIFY_ALLOW_OUTER_LEVEL 16
111 #define UNIFY_ALLOW_OUTER_MORE_CV_QUAL 32
112 #define UNIFY_ALLOW_OUTER_LESS_CV_QUAL 64
113
114 static void push_access_scope (tree);
115 static void pop_access_scope (tree);
116 static bool resolve_overloaded_unification (tree, tree, tree, tree,
117                                             unification_kind_t, int);
118 static int try_one_overload (tree, tree, tree, tree, tree,
119                              unification_kind_t, int, bool);
120 static int unify (tree, tree, tree, tree, int);
121 static void add_pending_template (tree);
122 static tree reopen_tinst_level (struct tinst_level *);
123 static tree tsubst_initializer_list (tree, tree);
124 static tree get_class_bindings (tree, tree, tree);
125 static tree coerce_template_parms (tree, tree, tree, tsubst_flags_t,
126                                    bool, bool);
127 static void tsubst_enum (tree, tree, tree);
128 static tree add_to_template_args (tree, tree);
129 static tree add_outermost_template_args (tree, tree);
130 static bool check_instantiated_args (tree, tree, tsubst_flags_t);
131 static int maybe_adjust_types_for_deduction (unification_kind_t, tree*, tree*,
132                                              tree);
133 static int type_unification_real (tree, tree, tree, const tree *,
134                                   unsigned int, int, unification_kind_t, int);
135 static void note_template_header (int);
136 static tree convert_nontype_argument_function (tree, tree);
137 static tree convert_nontype_argument (tree, tree);
138 static tree convert_template_argument (tree, tree, tree,
139                                        tsubst_flags_t, int, tree);
140 static int for_each_template_parm (tree, tree_fn_t, void*,
141                                    struct pointer_set_t*, bool);
142 static tree expand_template_argument_pack (tree);
143 static tree build_template_parm_index (int, int, int, tree, tree);
144 static bool inline_needs_template_parms (tree);
145 static void push_inline_template_parms_recursive (tree, int);
146 static tree retrieve_local_specialization (tree);
147 static void register_local_specialization (tree, tree);
148 static hashval_t hash_specialization (const void *p);
149 static tree reduce_template_parm_level (tree, tree, int, tree, tsubst_flags_t);
150 static int mark_template_parm (tree, void *);
151 static int template_parm_this_level_p (tree, void *);
152 static tree tsubst_friend_function (tree, tree);
153 static tree tsubst_friend_class (tree, tree);
154 static int can_complete_type_without_circularity (tree);
155 static tree get_bindings (tree, tree, tree, bool);
156 static int template_decl_level (tree);
157 static int check_cv_quals_for_unify (int, tree, tree);
158 static void template_parm_level_and_index (tree, int*, int*);
159 static int unify_pack_expansion (tree, tree, tree, tree, int, bool, bool);
160 static tree tsubst_template_arg (tree, tree, tsubst_flags_t, tree);
161 static tree tsubst_template_args (tree, tree, tsubst_flags_t, tree);
162 static tree tsubst_template_parms (tree, tree, tsubst_flags_t);
163 static void regenerate_decl_from_template (tree, tree);
164 static tree most_specialized_class (tree, tree);
165 static tree tsubst_aggr_type (tree, tree, tsubst_flags_t, tree, int);
166 static tree tsubst_arg_types (tree, tree, tsubst_flags_t, tree);
167 static tree tsubst_function_type (tree, tree, tsubst_flags_t, tree);
168 static bool check_specialization_scope (void);
169 static tree process_partial_specialization (tree);
170 static void set_current_access_from_decl (tree);
171 static tree get_template_base (tree, tree, tree, tree);
172 static tree try_class_unification (tree, tree, tree, tree);
173 static int coerce_template_template_parms (tree, tree, tsubst_flags_t,
174                                            tree, tree);
175 static bool template_template_parm_bindings_ok_p (tree, tree);
176 static int template_args_equal (tree, tree);
177 static void tsubst_default_arguments (tree);
178 static tree for_each_template_parm_r (tree *, int *, void *);
179 static tree copy_default_args_to_explicit_spec_1 (tree, tree);
180 static void copy_default_args_to_explicit_spec (tree);
181 static int invalid_nontype_parm_type_p (tree, tsubst_flags_t);
182 static int eq_local_specializations (const void *, const void *);
183 static bool dependent_template_arg_p (tree);
184 static bool any_template_arguments_need_structural_equality_p (tree);
185 static bool dependent_type_p_r (tree);
186 static tree tsubst_expr (tree, tree, tsubst_flags_t, tree, bool);
187 static tree tsubst_copy (tree, tree, tsubst_flags_t, tree);
188 static tree tsubst_pack_expansion (tree, tree, tsubst_flags_t, tree);
189 static tree tsubst_decl (tree, tree, tsubst_flags_t);
190 static void perform_typedefs_access_check (tree tmpl, tree targs);
191 static void append_type_to_template_for_access_check_1 (tree, tree, tree,
192                                                         location_t);
193 static hashval_t iterative_hash_template_arg (tree arg, hashval_t val);
194 static tree listify (tree);
195 static tree listify_autos (tree, tree);
196
197 /* Make the current scope suitable for access checking when we are
198    processing T.  T can be FUNCTION_DECL for instantiated function
199    template, or VAR_DECL for static member variable (need by
200    instantiate_decl).  */
201
202 static void
203 push_access_scope (tree t)
204 {
205   gcc_assert (TREE_CODE (t) == FUNCTION_DECL
206               || TREE_CODE (t) == VAR_DECL);
207
208   if (DECL_FRIEND_CONTEXT (t))
209     push_nested_class (DECL_FRIEND_CONTEXT (t));
210   else if (DECL_CLASS_SCOPE_P (t))
211     push_nested_class (DECL_CONTEXT (t));
212   else
213     push_to_top_level ();
214
215   if (TREE_CODE (t) == FUNCTION_DECL)
216     {
217       saved_access_scope = tree_cons
218         (NULL_TREE, current_function_decl, saved_access_scope);
219       current_function_decl = t;
220     }
221 }
222
223 /* Restore the scope set up by push_access_scope.  T is the node we
224    are processing.  */
225
226 static void
227 pop_access_scope (tree t)
228 {
229   if (TREE_CODE (t) == FUNCTION_DECL)
230     {
231       current_function_decl = TREE_VALUE (saved_access_scope);
232       saved_access_scope = TREE_CHAIN (saved_access_scope);
233     }
234
235   if (DECL_FRIEND_CONTEXT (t) || DECL_CLASS_SCOPE_P (t))
236     pop_nested_class ();
237   else
238     pop_from_top_level ();
239 }
240
241 /* Do any processing required when DECL (a member template
242    declaration) is finished.  Returns the TEMPLATE_DECL corresponding
243    to DECL, unless it is a specialization, in which case the DECL
244    itself is returned.  */
245
246 tree
247 finish_member_template_decl (tree decl)
248 {
249   if (decl == error_mark_node)
250     return error_mark_node;
251
252   gcc_assert (DECL_P (decl));
253
254   if (TREE_CODE (decl) == TYPE_DECL)
255     {
256       tree type;
257
258       type = TREE_TYPE (decl);
259       if (type == error_mark_node)
260         return error_mark_node;
261       if (MAYBE_CLASS_TYPE_P (type)
262           && CLASSTYPE_TEMPLATE_INFO (type)
263           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
264         {
265           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
266           check_member_template (tmpl);
267           return tmpl;
268         }
269       return NULL_TREE;
270     }
271   else if (TREE_CODE (decl) == FIELD_DECL)
272     error ("data member %qD cannot be a member template", decl);
273   else if (DECL_TEMPLATE_INFO (decl))
274     {
275       if (!DECL_TEMPLATE_SPECIALIZATION (decl))
276         {
277           check_member_template (DECL_TI_TEMPLATE (decl));
278           return DECL_TI_TEMPLATE (decl);
279         }
280       else
281         return decl;
282     }
283   else
284     error ("invalid member template declaration %qD", decl);
285
286   return error_mark_node;
287 }
288
289 /* Create a template info node.  */
290
291 tree
292 build_template_info (tree template_decl, tree template_args)
293 {
294   tree result = make_node (TEMPLATE_INFO);
295   TI_TEMPLATE (result) = template_decl;
296   TI_ARGS (result) = template_args;
297   return result;
298 }
299
300 /* Return the template info node corresponding to T, whatever T is.  */
301
302 tree
303 get_template_info (const_tree t)
304 {
305   tree tinfo = NULL_TREE;
306
307   if (!t || t == error_mark_node)
308     return NULL;
309
310   if (DECL_P (t) && DECL_LANG_SPECIFIC (t))
311     tinfo = DECL_TEMPLATE_INFO (t);
312
313   if (!tinfo && DECL_IMPLICIT_TYPEDEF_P (t))
314     t = TREE_TYPE (t);
315
316   if (TAGGED_TYPE_P (t))
317     tinfo = TYPE_TEMPLATE_INFO (t);
318   else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
319     tinfo = TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (t);
320
321   return tinfo;
322 }
323
324 /* Returns the template nesting level of the indicated class TYPE.
325
326    For example, in:
327      template <class T>
328      struct A
329      {
330        template <class U>
331        struct B {};
332      };
333
334    A<T>::B<U> has depth two, while A<T> has depth one.
335    Both A<T>::B<int> and A<int>::B<U> have depth one, if
336    they are instantiations, not specializations.
337
338    This function is guaranteed to return 0 if passed NULL_TREE so
339    that, for example, `template_class_depth (current_class_type)' is
340    always safe.  */
341
342 int
343 template_class_depth (tree type)
344 {
345   int depth;
346
347   for (depth = 0;
348        type && TREE_CODE (type) != NAMESPACE_DECL;
349        type = (TREE_CODE (type) == FUNCTION_DECL)
350          ? CP_DECL_CONTEXT (type) : TYPE_CONTEXT (type))
351     {
352       tree tinfo = get_template_info (type);
353
354       if (tinfo && PRIMARY_TEMPLATE_P (TI_TEMPLATE (tinfo))
355           && uses_template_parms (INNERMOST_TEMPLATE_ARGS (TI_ARGS (tinfo))))
356         ++depth;
357     }
358
359   return depth;
360 }
361
362 /* Subroutine of maybe_begin_member_template_processing.
363    Returns true if processing DECL needs us to push template parms.  */
364
365 static bool
366 inline_needs_template_parms (tree decl)
367 {
368   if (! DECL_TEMPLATE_INFO (decl))
369     return false;
370
371   return (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (most_general_template (decl)))
372           > (processing_template_decl + DECL_TEMPLATE_SPECIALIZATION (decl)));
373 }
374
375 /* Subroutine of maybe_begin_member_template_processing.
376    Push the template parms in PARMS, starting from LEVELS steps into the
377    chain, and ending at the beginning, since template parms are listed
378    innermost first.  */
379
380 static void
381 push_inline_template_parms_recursive (tree parmlist, int levels)
382 {
383   tree parms = TREE_VALUE (parmlist);
384   int i;
385
386   if (levels > 1)
387     push_inline_template_parms_recursive (TREE_CHAIN (parmlist), levels - 1);
388
389   ++processing_template_decl;
390   current_template_parms
391     = tree_cons (size_int (processing_template_decl),
392                  parms, current_template_parms);
393   TEMPLATE_PARMS_FOR_INLINE (current_template_parms) = 1;
394
395   begin_scope (TREE_VEC_LENGTH (parms) ? sk_template_parms : sk_template_spec,
396                NULL);
397   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
398     {
399       tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
400
401       if (parm == error_mark_node)
402         continue;
403
404       gcc_assert (DECL_P (parm));
405
406       switch (TREE_CODE (parm))
407         {
408         case TYPE_DECL:
409         case TEMPLATE_DECL:
410           pushdecl (parm);
411           break;
412
413         case PARM_DECL:
414           {
415             /* Make a CONST_DECL as is done in process_template_parm.
416                It is ugly that we recreate this here; the original
417                version built in process_template_parm is no longer
418                available.  */
419             tree decl = build_decl (DECL_SOURCE_LOCATION (parm),
420                                     CONST_DECL, DECL_NAME (parm),
421                                     TREE_TYPE (parm));
422             DECL_ARTIFICIAL (decl) = 1;
423             TREE_CONSTANT (decl) = 1;
424             TREE_READONLY (decl) = 1;
425             DECL_INITIAL (decl) = DECL_INITIAL (parm);
426             SET_DECL_TEMPLATE_PARM_P (decl);
427             pushdecl (decl);
428           }
429           break;
430
431         default:
432           gcc_unreachable ();
433         }
434     }
435 }
436
437 /* Restore the template parameter context for a member template or
438    a friend template defined in a class definition.  */
439
440 void
441 maybe_begin_member_template_processing (tree decl)
442 {
443   tree parms;
444   int levels = 0;
445
446   if (inline_needs_template_parms (decl))
447     {
448       parms = DECL_TEMPLATE_PARMS (most_general_template (decl));
449       levels = TMPL_PARMS_DEPTH (parms) - processing_template_decl;
450
451       if (DECL_TEMPLATE_SPECIALIZATION (decl))
452         {
453           --levels;
454           parms = TREE_CHAIN (parms);
455         }
456
457       push_inline_template_parms_recursive (parms, levels);
458     }
459
460   /* Remember how many levels of template parameters we pushed so that
461      we can pop them later.  */
462   VEC_safe_push (int, heap, inline_parm_levels, levels);
463 }
464
465 /* Undo the effects of maybe_begin_member_template_processing.  */
466
467 void
468 maybe_end_member_template_processing (void)
469 {
470   int i;
471   int last;
472
473   if (VEC_length (int, inline_parm_levels) == 0)
474     return;
475
476   last = VEC_pop (int, inline_parm_levels);
477   for (i = 0; i < last; ++i)
478     {
479       --processing_template_decl;
480       current_template_parms = TREE_CHAIN (current_template_parms);
481       poplevel (0, 0, 0);
482     }
483 }
484
485 /* Return a new template argument vector which contains all of ARGS,
486    but has as its innermost set of arguments the EXTRA_ARGS.  */
487
488 static tree
489 add_to_template_args (tree args, tree extra_args)
490 {
491   tree new_args;
492   int extra_depth;
493   int i;
494   int j;
495
496   if (args == NULL_TREE)
497     return extra_args;
498
499   extra_depth = TMPL_ARGS_DEPTH (extra_args);
500   new_args = make_tree_vec (TMPL_ARGS_DEPTH (args) + extra_depth);
501
502   for (i = 1; i <= TMPL_ARGS_DEPTH (args); ++i)
503     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (args, i));
504
505   for (j = 1; j <= extra_depth; ++j, ++i)
506     SET_TMPL_ARGS_LEVEL (new_args, i, TMPL_ARGS_LEVEL (extra_args, j));
507
508   return new_args;
509 }
510
511 /* Like add_to_template_args, but only the outermost ARGS are added to
512    the EXTRA_ARGS.  In particular, all but TMPL_ARGS_DEPTH
513    (EXTRA_ARGS) levels are added.  This function is used to combine
514    the template arguments from a partial instantiation with the
515    template arguments used to attain the full instantiation from the
516    partial instantiation.  */
517
518 static tree
519 add_outermost_template_args (tree args, tree extra_args)
520 {
521   tree new_args;
522
523   /* If there are more levels of EXTRA_ARGS than there are ARGS,
524      something very fishy is going on.  */
525   gcc_assert (TMPL_ARGS_DEPTH (args) >= TMPL_ARGS_DEPTH (extra_args));
526
527   /* If *all* the new arguments will be the EXTRA_ARGS, just return
528      them.  */
529   if (TMPL_ARGS_DEPTH (args) == TMPL_ARGS_DEPTH (extra_args))
530     return extra_args;
531
532   /* For the moment, we make ARGS look like it contains fewer levels.  */
533   TREE_VEC_LENGTH (args) -= TMPL_ARGS_DEPTH (extra_args);
534
535   new_args = add_to_template_args (args, extra_args);
536
537   /* Now, we restore ARGS to its full dimensions.  */
538   TREE_VEC_LENGTH (args) += TMPL_ARGS_DEPTH (extra_args);
539
540   return new_args;
541 }
542
543 /* Return the N levels of innermost template arguments from the ARGS.  */
544
545 tree
546 get_innermost_template_args (tree args, int n)
547 {
548   tree new_args;
549   int extra_levels;
550   int i;
551
552   gcc_assert (n >= 0);
553
554   /* If N is 1, just return the innermost set of template arguments.  */
555   if (n == 1)
556     return TMPL_ARGS_LEVEL (args, TMPL_ARGS_DEPTH (args));
557
558   /* If we're not removing anything, just return the arguments we were
559      given.  */
560   extra_levels = TMPL_ARGS_DEPTH (args) - n;
561   gcc_assert (extra_levels >= 0);
562   if (extra_levels == 0)
563     return args;
564
565   /* Make a new set of arguments, not containing the outer arguments.  */
566   new_args = make_tree_vec (n);
567   for (i = 1; i <= n; ++i)
568     SET_TMPL_ARGS_LEVEL (new_args, i,
569                          TMPL_ARGS_LEVEL (args, i + extra_levels));
570
571   return new_args;
572 }
573
574 /* The inverse of get_innermost_template_args: Return all but the innermost
575    EXTRA_LEVELS levels of template arguments from the ARGS.  */
576
577 static tree
578 strip_innermost_template_args (tree args, int extra_levels)
579 {
580   tree new_args;
581   int n = TMPL_ARGS_DEPTH (args) - extra_levels;
582   int i;
583
584   gcc_assert (n >= 0);
585
586   /* If N is 1, just return the outermost set of template arguments.  */
587   if (n == 1)
588     return TMPL_ARGS_LEVEL (args, 1);
589
590   /* If we're not removing anything, just return the arguments we were
591      given.  */
592   gcc_assert (extra_levels >= 0);
593   if (extra_levels == 0)
594     return args;
595
596   /* Make a new set of arguments, not containing the inner arguments.  */
597   new_args = make_tree_vec (n);
598   for (i = 1; i <= n; ++i)
599     SET_TMPL_ARGS_LEVEL (new_args, i,
600                          TMPL_ARGS_LEVEL (args, i));
601
602   return new_args;
603 }
604
605 /* We've got a template header coming up; push to a new level for storing
606    the parms.  */
607
608 void
609 begin_template_parm_list (void)
610 {
611   /* We use a non-tag-transparent scope here, which causes pushtag to
612      put tags in this scope, rather than in the enclosing class or
613      namespace scope.  This is the right thing, since we want
614      TEMPLATE_DECLS, and not TYPE_DECLS for template classes.  For a
615      global template class, push_template_decl handles putting the
616      TEMPLATE_DECL into top-level scope.  For a nested template class,
617      e.g.:
618
619        template <class T> struct S1 {
620          template <class T> struct S2 {};
621        };
622
623      pushtag contains special code to call pushdecl_with_scope on the
624      TEMPLATE_DECL for S2.  */
625   begin_scope (sk_template_parms, NULL);
626   ++processing_template_decl;
627   ++processing_template_parmlist;
628   note_template_header (0);
629 }
630
631 /* This routine is called when a specialization is declared.  If it is
632    invalid to declare a specialization here, an error is reported and
633    false is returned, otherwise this routine will return true.  */
634
635 static bool
636 check_specialization_scope (void)
637 {
638   tree scope = current_scope ();
639
640   /* [temp.expl.spec]
641
642      An explicit specialization shall be declared in the namespace of
643      which the template is a member, or, for member templates, in the
644      namespace of which the enclosing class or enclosing class
645      template is a member.  An explicit specialization of a member
646      function, member class or static data member of a class template
647      shall be declared in the namespace of which the class template
648      is a member.  */
649   if (scope && TREE_CODE (scope) != NAMESPACE_DECL)
650     {
651       error ("explicit specialization in non-namespace scope %qD", scope);
652       return false;
653     }
654
655   /* [temp.expl.spec]
656
657      In an explicit specialization declaration for a member of a class
658      template or a member template that appears in namespace scope,
659      the member template and some of its enclosing class templates may
660      remain unspecialized, except that the declaration shall not
661      explicitly specialize a class member template if its enclosing
662      class templates are not explicitly specialized as well.  */
663   if (current_template_parms)
664     {
665       error ("enclosing class templates are not explicitly specialized");
666       return false;
667     }
668
669   return true;
670 }
671
672 /* We've just seen template <>.  */
673
674 bool
675 begin_specialization (void)
676 {
677   begin_scope (sk_template_spec, NULL);
678   note_template_header (1);
679   return check_specialization_scope ();
680 }
681
682 /* Called at then end of processing a declaration preceded by
683    template<>.  */
684
685 void
686 end_specialization (void)
687 {
688   finish_scope ();
689   reset_specialization ();
690 }
691
692 /* Any template <>'s that we have seen thus far are not referring to a
693    function specialization.  */
694
695 void
696 reset_specialization (void)
697 {
698   processing_specialization = 0;
699   template_header_count = 0;
700 }
701
702 /* We've just seen a template header.  If SPECIALIZATION is nonzero,
703    it was of the form template <>.  */
704
705 static void
706 note_template_header (int specialization)
707 {
708   processing_specialization = specialization;
709   template_header_count++;
710 }
711
712 /* We're beginning an explicit instantiation.  */
713
714 void
715 begin_explicit_instantiation (void)
716 {
717   gcc_assert (!processing_explicit_instantiation);
718   processing_explicit_instantiation = true;
719 }
720
721
722 void
723 end_explicit_instantiation (void)
724 {
725   gcc_assert (processing_explicit_instantiation);
726   processing_explicit_instantiation = false;
727 }
728
729 /* An explicit specialization or partial specialization TMPL is being
730    declared.  Check that the namespace in which the specialization is
731    occurring is permissible.  Returns false iff it is invalid to
732    specialize TMPL in the current namespace.  */
733
734 static bool
735 check_specialization_namespace (tree tmpl)
736 {
737   tree tpl_ns = decl_namespace_context (tmpl);
738
739   /* [tmpl.expl.spec]
740
741      An explicit specialization shall be declared in the namespace of
742      which the template is a member, or, for member templates, in the
743      namespace of which the enclosing class or enclosing class
744      template is a member.  An explicit specialization of a member
745      function, member class or static data member of a class template
746      shall be declared in the namespace of which the class template is
747      a member.  */
748   if (current_scope() != DECL_CONTEXT (tmpl)
749       && !at_namespace_scope_p ())
750     {
751       error ("specialization of %qD must appear at namespace scope", tmpl);
752       return false;
753     }
754   if (is_associated_namespace (current_namespace, tpl_ns))
755     /* Same or super-using namespace.  */
756     return true;
757   else
758     {
759       permerror (input_location, "specialization of %qD in different namespace", tmpl);
760       permerror (input_location, "  from definition of %q+#D", tmpl);
761       return false;
762     }
763 }
764
765 /* SPEC is an explicit instantiation.  Check that it is valid to
766    perform this explicit instantiation in the current namespace.  */
767
768 static void
769 check_explicit_instantiation_namespace (tree spec)
770 {
771   tree ns;
772
773   /* DR 275: An explicit instantiation shall appear in an enclosing
774      namespace of its template.  */
775   ns = decl_namespace_context (spec);
776   if (!is_ancestor (current_namespace, ns))
777     permerror (input_location, "explicit instantiation of %qD in namespace %qD "
778                "(which does not enclose namespace %qD)",
779                spec, current_namespace, ns);
780 }
781
782 /* The TYPE is being declared.  If it is a template type, that means it
783    is a partial specialization.  Do appropriate error-checking.  */
784
785 tree
786 maybe_process_partial_specialization (tree type)
787 {
788   tree context;
789
790   if (type == error_mark_node)
791     return error_mark_node;
792
793   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
794     {
795       error ("name of class shadows template template parameter %qD",
796              TYPE_NAME (type));
797       return error_mark_node;
798     }
799
800   context = TYPE_CONTEXT (type);
801
802   if (CLASS_TYPE_P (type) && CLASSTYPE_USE_TEMPLATE (type))
803     {
804       /* This is for ordinary explicit specialization and partial
805          specialization of a template class such as:
806
807            template <> class C<int>;
808
809          or:
810
811            template <class T> class C<T*>;
812
813          Make sure that `C<int>' and `C<T*>' are implicit instantiations.  */
814
815       if (CLASSTYPE_IMPLICIT_INSTANTIATION (type)
816           && !COMPLETE_TYPE_P (type))
817         {
818           check_specialization_namespace (CLASSTYPE_TI_TEMPLATE (type));
819           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
820           if (processing_template_decl)
821             {
822               if (push_template_decl (TYPE_MAIN_DECL (type))
823                   == error_mark_node)
824                 return error_mark_node;
825             }
826         }
827       else if (CLASSTYPE_TEMPLATE_INSTANTIATION (type))
828         error ("specialization of %qT after instantiation", type);
829     }
830   else if (CLASS_TYPE_P (type)
831            && !CLASSTYPE_USE_TEMPLATE (type)
832            && CLASSTYPE_TEMPLATE_INFO (type)
833            && context && CLASS_TYPE_P (context)
834            && CLASSTYPE_TEMPLATE_INFO (context))
835     {
836       /* This is for an explicit specialization of member class
837          template according to [temp.expl.spec/18]:
838
839            template <> template <class U> class C<int>::D;
840
841          The context `C<int>' must be an implicit instantiation.
842          Otherwise this is just a member class template declared
843          earlier like:
844
845            template <> class C<int> { template <class U> class D; };
846            template <> template <class U> class C<int>::D;
847
848          In the first case, `C<int>::D' is a specialization of `C<T>::D'
849          while in the second case, `C<int>::D' is a primary template
850          and `C<T>::D' may not exist.  */
851
852       if (CLASSTYPE_IMPLICIT_INSTANTIATION (context)
853           && !COMPLETE_TYPE_P (type))
854         {
855           tree t;
856           tree tmpl = CLASSTYPE_TI_TEMPLATE (type);
857
858           if (current_namespace
859               != decl_namespace_context (tmpl))
860             {
861               permerror (input_location, "specializing %q#T in different namespace", type);
862               permerror (input_location, "  from definition of %q+#D", tmpl);
863             }
864
865           /* Check for invalid specialization after instantiation:
866
867                template <> template <> class C<int>::D<int>;
868                template <> template <class U> class C<int>::D;  */
869
870           for (t = DECL_TEMPLATE_INSTANTIATIONS (tmpl);
871                t; t = TREE_CHAIN (t))
872             {
873               tree inst = TREE_VALUE (t);
874               if (CLASSTYPE_TEMPLATE_SPECIALIZATION (inst))
875                 {
876                   /* We already have a full specialization of this partial
877                      instantiation.  Reassign it to the new member
878                      specialization template.  */
879                   spec_entry elt;
880                   spec_entry **slot;
881
882                   elt.tmpl = most_general_template (tmpl);
883                   elt.args = CLASSTYPE_TI_ARGS (inst);
884                   elt.spec = inst;
885
886                   htab_remove_elt (type_specializations, &elt);
887
888                   elt.tmpl = tmpl;
889                   elt.args = INNERMOST_TEMPLATE_ARGS (elt.args);
890
891                   slot = (spec_entry **)
892                     htab_find_slot (type_specializations, &elt, INSERT);
893                   *slot = GGC_NEW (spec_entry);
894                   **slot = elt;
895                 }
896               else if (COMPLETE_TYPE_P (inst) || TYPE_BEING_DEFINED (inst))
897                 /* But if we've had an implicit instantiation, that's a
898                    problem ([temp.expl.spec]/6).  */
899                 error ("specialization %qT after instantiation %qT",
900                        type, inst);
901             }
902
903           /* Mark TYPE as a specialization.  And as a result, we only
904              have one level of template argument for the innermost
905              class template.  */
906           SET_CLASSTYPE_TEMPLATE_SPECIALIZATION (type);
907           CLASSTYPE_TI_ARGS (type)
908             = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type));
909         }
910     }
911   else if (processing_specialization)
912     {
913       error ("explicit specialization of non-template %qT", type);
914       return error_mark_node;
915     }
916
917   return type;
918 }
919
920 /* Returns nonzero if we can optimize the retrieval of specializations
921    for TMPL, a TEMPLATE_DECL.  In particular, for such a template, we
922    do not use DECL_TEMPLATE_SPECIALIZATIONS at all.  */
923
924 static inline bool
925 optimize_specialization_lookup_p (tree tmpl)
926 {
927   return (DECL_FUNCTION_TEMPLATE_P (tmpl)
928           && DECL_CLASS_SCOPE_P (tmpl)
929           /* DECL_CLASS_SCOPE_P holds of T::f even if T is a template
930              parameter.  */
931           && CLASS_TYPE_P (DECL_CONTEXT (tmpl))
932           /* The optimized lookup depends on the fact that the
933              template arguments for the member function template apply
934              purely to the containing class, which is not true if the
935              containing class is an explicit or partial
936              specialization.  */
937           && !CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (tmpl))
938           && !DECL_MEMBER_TEMPLATE_P (tmpl)
939           && !DECL_CONV_FN_P (tmpl)
940           /* It is possible to have a template that is not a member
941              template and is not a member of a template class:
942
943              template <typename T>
944              struct S { friend A::f(); };
945
946              Here, the friend function is a template, but the context does
947              not have template information.  The optimized lookup relies
948              on having ARGS be the template arguments for both the class
949              and the function template.  */
950           && !DECL_FRIEND_P (DECL_TEMPLATE_RESULT (tmpl)));
951 }
952
953 /* Retrieve the specialization (in the sense of [temp.spec] - a
954    specialization is either an instantiation or an explicit
955    specialization) of TMPL for the given template ARGS.  If there is
956    no such specialization, return NULL_TREE.  The ARGS are a vector of
957    arguments, or a vector of vectors of arguments, in the case of
958    templates with more than one level of parameters.
959
960    If TMPL is a type template and CLASS_SPECIALIZATIONS_P is true,
961    then we search for a partial specialization matching ARGS.  This
962    parameter is ignored if TMPL is not a class template.  */
963
964 static tree
965 retrieve_specialization (tree tmpl, tree args, hashval_t hash)
966 {
967   if (args == error_mark_node)
968     return NULL_TREE;
969
970   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
971
972   /* There should be as many levels of arguments as there are
973      levels of parameters.  */
974   gcc_assert (TMPL_ARGS_DEPTH (args)
975               == TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl)));
976
977   if (optimize_specialization_lookup_p (tmpl))
978     {
979       tree class_template;
980       tree class_specialization;
981       VEC(tree,gc) *methods;
982       tree fns;
983       int idx;
984
985       /* The template arguments actually apply to the containing
986          class.  Find the class specialization with those
987          arguments.  */
988       class_template = CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (tmpl));
989       class_specialization
990         = retrieve_specialization (class_template, args, 0);
991       if (!class_specialization)
992         return NULL_TREE;
993       /* Now, find the appropriate entry in the CLASSTYPE_METHOD_VEC
994          for the specialization.  */
995       idx = class_method_index_for_fn (class_specialization, tmpl);
996       if (idx == -1)
997         return NULL_TREE;
998       /* Iterate through the methods with the indicated name, looking
999          for the one that has an instance of TMPL.  */
1000       methods = CLASSTYPE_METHOD_VEC (class_specialization);
1001       for (fns = VEC_index (tree, methods, idx); fns; fns = OVL_NEXT (fns))
1002         {
1003           tree fn = OVL_CURRENT (fns);
1004           if (DECL_TEMPLATE_INFO (fn) && DECL_TI_TEMPLATE (fn) == tmpl
1005               /* using-declarations can add base methods to the method vec,
1006                  and we don't want those here.  */
1007               && DECL_CONTEXT (fn) == class_specialization)
1008             return fn;
1009         }
1010       return NULL_TREE;
1011     }
1012   else
1013     {
1014       spec_entry *found;
1015       spec_entry elt;
1016       htab_t specializations;
1017
1018       elt.tmpl = tmpl;
1019       elt.args = args;
1020       elt.spec = NULL_TREE;
1021
1022       if (DECL_CLASS_TEMPLATE_P (tmpl))
1023         specializations = type_specializations;
1024       else
1025         specializations = decl_specializations;
1026
1027       if (hash == 0)
1028         hash = hash_specialization (&elt);
1029       found = (spec_entry *) htab_find_with_hash (specializations, &elt, hash);
1030       if (found)
1031         return found->spec;
1032     }
1033
1034   return NULL_TREE;
1035 }
1036
1037 /* Like retrieve_specialization, but for local declarations.  */
1038
1039 static tree
1040 retrieve_local_specialization (tree tmpl)
1041 {
1042   tree spec;
1043
1044   if (local_specializations == NULL)
1045     return NULL_TREE;
1046
1047   spec = (tree) htab_find_with_hash (local_specializations, tmpl,
1048                                      htab_hash_pointer (tmpl));
1049   return spec ? TREE_PURPOSE (spec) : NULL_TREE;
1050 }
1051
1052 /* Returns nonzero iff DECL is a specialization of TMPL.  */
1053
1054 int
1055 is_specialization_of (tree decl, tree tmpl)
1056 {
1057   tree t;
1058
1059   if (TREE_CODE (decl) == FUNCTION_DECL)
1060     {
1061       for (t = decl;
1062            t != NULL_TREE;
1063            t = DECL_TEMPLATE_INFO (t) ? DECL_TI_TEMPLATE (t) : NULL_TREE)
1064         if (t == tmpl)
1065           return 1;
1066     }
1067   else
1068     {
1069       gcc_assert (TREE_CODE (decl) == TYPE_DECL);
1070
1071       for (t = TREE_TYPE (decl);
1072            t != NULL_TREE;
1073            t = CLASSTYPE_USE_TEMPLATE (t)
1074              ? TREE_TYPE (CLASSTYPE_TI_TEMPLATE (t)) : NULL_TREE)
1075         if (same_type_ignoring_top_level_qualifiers_p (t, TREE_TYPE (tmpl)))
1076           return 1;
1077     }
1078
1079   return 0;
1080 }
1081
1082 /* Returns nonzero iff DECL is a specialization of friend declaration
1083    FRIEND_DECL according to [temp.friend].  */
1084
1085 bool
1086 is_specialization_of_friend (tree decl, tree friend_decl)
1087 {
1088   bool need_template = true;
1089   int template_depth;
1090
1091   gcc_assert (TREE_CODE (decl) == FUNCTION_DECL
1092               || TREE_CODE (decl) == TYPE_DECL);
1093
1094   /* For [temp.friend/6] when FRIEND_DECL is an ordinary member function
1095      of a template class, we want to check if DECL is a specialization
1096      if this.  */
1097   if (TREE_CODE (friend_decl) == FUNCTION_DECL
1098       && DECL_TEMPLATE_INFO (friend_decl)
1099       && !DECL_USE_TEMPLATE (friend_decl))
1100     {
1101       /* We want a TEMPLATE_DECL for `is_specialization_of'.  */
1102       friend_decl = DECL_TI_TEMPLATE (friend_decl);
1103       need_template = false;
1104     }
1105   else if (TREE_CODE (friend_decl) == TEMPLATE_DECL
1106            && !PRIMARY_TEMPLATE_P (friend_decl))
1107     need_template = false;
1108
1109   /* There is nothing to do if this is not a template friend.  */
1110   if (TREE_CODE (friend_decl) != TEMPLATE_DECL)
1111     return false;
1112
1113   if (is_specialization_of (decl, friend_decl))
1114     return true;
1115
1116   /* [temp.friend/6]
1117      A member of a class template may be declared to be a friend of a
1118      non-template class.  In this case, the corresponding member of
1119      every specialization of the class template is a friend of the
1120      class granting friendship.
1121
1122      For example, given a template friend declaration
1123
1124        template <class T> friend void A<T>::f();
1125
1126      the member function below is considered a friend
1127
1128        template <> struct A<int> {
1129          void f();
1130        };
1131
1132      For this type of template friend, TEMPLATE_DEPTH below will be
1133      nonzero.  To determine if DECL is a friend of FRIEND, we first
1134      check if the enclosing class is a specialization of another.  */
1135
1136   template_depth = template_class_depth (DECL_CONTEXT (friend_decl));
1137   if (template_depth
1138       && DECL_CLASS_SCOPE_P (decl)
1139       && is_specialization_of (TYPE_NAME (DECL_CONTEXT (decl)),
1140                                CLASSTYPE_TI_TEMPLATE (DECL_CONTEXT (friend_decl))))
1141     {
1142       /* Next, we check the members themselves.  In order to handle
1143          a few tricky cases, such as when FRIEND_DECL's are
1144
1145            template <class T> friend void A<T>::g(T t);
1146            template <class T> template <T t> friend void A<T>::h();
1147
1148          and DECL's are
1149
1150            void A<int>::g(int);
1151            template <int> void A<int>::h();
1152
1153          we need to figure out ARGS, the template arguments from
1154          the context of DECL.  This is required for template substitution
1155          of `T' in the function parameter of `g' and template parameter
1156          of `h' in the above examples.  Here ARGS corresponds to `int'.  */
1157
1158       tree context = DECL_CONTEXT (decl);
1159       tree args = NULL_TREE;
1160       int current_depth = 0;
1161
1162       while (current_depth < template_depth)
1163         {
1164           if (CLASSTYPE_TEMPLATE_INFO (context))
1165             {
1166               if (current_depth == 0)
1167                 args = TYPE_TI_ARGS (context);
1168               else
1169                 args = add_to_template_args (TYPE_TI_ARGS (context), args);
1170               current_depth++;
1171             }
1172           context = TYPE_CONTEXT (context);
1173         }
1174
1175       if (TREE_CODE (decl) == FUNCTION_DECL)
1176         {
1177           bool is_template;
1178           tree friend_type;
1179           tree decl_type;
1180           tree friend_args_type;
1181           tree decl_args_type;
1182
1183           /* Make sure that both DECL and FRIEND_DECL are templates or
1184              non-templates.  */
1185           is_template = DECL_TEMPLATE_INFO (decl)
1186                         && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (decl));
1187           if (need_template ^ is_template)
1188             return false;
1189           else if (is_template)
1190             {
1191               /* If both are templates, check template parameter list.  */
1192               tree friend_parms
1193                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1194                                          args, tf_none);
1195               if (!comp_template_parms
1196                      (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (decl)),
1197                       friend_parms))
1198                 return false;
1199
1200               decl_type = TREE_TYPE (DECL_TI_TEMPLATE (decl));
1201             }
1202           else
1203             decl_type = TREE_TYPE (decl);
1204
1205           friend_type = tsubst_function_type (TREE_TYPE (friend_decl), args,
1206                                               tf_none, NULL_TREE);
1207           if (friend_type == error_mark_node)
1208             return false;
1209
1210           /* Check if return types match.  */
1211           if (!same_type_p (TREE_TYPE (decl_type), TREE_TYPE (friend_type)))
1212             return false;
1213
1214           /* Check if function parameter types match, ignoring the
1215              `this' parameter.  */
1216           friend_args_type = TYPE_ARG_TYPES (friend_type);
1217           decl_args_type = TYPE_ARG_TYPES (decl_type);
1218           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (friend_decl))
1219             friend_args_type = TREE_CHAIN (friend_args_type);
1220           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1221             decl_args_type = TREE_CHAIN (decl_args_type);
1222
1223           return compparms (decl_args_type, friend_args_type);
1224         }
1225       else
1226         {
1227           /* DECL is a TYPE_DECL */
1228           bool is_template;
1229           tree decl_type = TREE_TYPE (decl);
1230
1231           /* Make sure that both DECL and FRIEND_DECL are templates or
1232              non-templates.  */
1233           is_template
1234             = CLASSTYPE_TEMPLATE_INFO (decl_type)
1235               && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (decl_type));
1236
1237           if (need_template ^ is_template)
1238             return false;
1239           else if (is_template)
1240             {
1241               tree friend_parms;
1242               /* If both are templates, check the name of the two
1243                  TEMPLATE_DECL's first because is_friend didn't.  */
1244               if (DECL_NAME (CLASSTYPE_TI_TEMPLATE (decl_type))
1245                   != DECL_NAME (friend_decl))
1246                 return false;
1247
1248               /* Now check template parameter list.  */
1249               friend_parms
1250                 = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_decl),
1251                                          args, tf_none);
1252               return comp_template_parms
1253                 (DECL_TEMPLATE_PARMS (CLASSTYPE_TI_TEMPLATE (decl_type)),
1254                  friend_parms);
1255             }
1256           else
1257             return (DECL_NAME (decl)
1258                     == DECL_NAME (friend_decl));
1259         }
1260     }
1261   return false;
1262 }
1263
1264 /* Register the specialization SPEC as a specialization of TMPL with
1265    the indicated ARGS.  IS_FRIEND indicates whether the specialization
1266    is actually just a friend declaration.  Returns SPEC, or an
1267    equivalent prior declaration, if available.  */
1268
1269 static tree
1270 register_specialization (tree spec, tree tmpl, tree args, bool is_friend,
1271                          hashval_t hash)
1272 {
1273   tree fn;
1274   spec_entry **slot = NULL;
1275   spec_entry elt;
1276
1277   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL && DECL_P (spec));
1278
1279   if (TREE_CODE (spec) == FUNCTION_DECL
1280       && uses_template_parms (DECL_TI_ARGS (spec)))
1281     /* This is the FUNCTION_DECL for a partial instantiation.  Don't
1282        register it; we want the corresponding TEMPLATE_DECL instead.
1283        We use `uses_template_parms (DECL_TI_ARGS (spec))' rather than
1284        the more obvious `uses_template_parms (spec)' to avoid problems
1285        with default function arguments.  In particular, given
1286        something like this:
1287
1288           template <class T> void f(T t1, T t = T())
1289
1290        the default argument expression is not substituted for in an
1291        instantiation unless and until it is actually needed.  */
1292     return spec;
1293
1294   if (optimize_specialization_lookup_p (tmpl))
1295     /* We don't put these specializations in the hash table, but we might
1296        want to give an error about a mismatch.  */
1297     fn = retrieve_specialization (tmpl, args, 0);
1298   else
1299     {
1300       elt.tmpl = tmpl;
1301       elt.args = args;
1302       elt.spec = spec;
1303
1304       if (hash == 0)
1305         hash = hash_specialization (&elt);
1306
1307       slot = (spec_entry **)
1308         htab_find_slot_with_hash (decl_specializations, &elt, hash, INSERT);
1309       if (*slot)
1310         fn = (*slot)->spec;
1311       else
1312         fn = NULL_TREE;
1313     }
1314
1315   /* We can sometimes try to re-register a specialization that we've
1316      already got.  In particular, regenerate_decl_from_template calls
1317      duplicate_decls which will update the specialization list.  But,
1318      we'll still get called again here anyhow.  It's more convenient
1319      to simply allow this than to try to prevent it.  */
1320   if (fn == spec)
1321     return spec;
1322   else if (fn && DECL_TEMPLATE_SPECIALIZATION (spec))
1323     {
1324       if (DECL_TEMPLATE_INSTANTIATION (fn))
1325         {
1326           if (DECL_ODR_USED (fn)
1327               || DECL_EXPLICIT_INSTANTIATION (fn))
1328             {
1329               error ("specialization of %qD after instantiation",
1330                      fn);
1331               return error_mark_node;
1332             }
1333           else
1334             {
1335               tree clone;
1336               /* This situation should occur only if the first
1337                  specialization is an implicit instantiation, the
1338                  second is an explicit specialization, and the
1339                  implicit instantiation has not yet been used.  That
1340                  situation can occur if we have implicitly
1341                  instantiated a member function and then specialized
1342                  it later.
1343
1344                  We can also wind up here if a friend declaration that
1345                  looked like an instantiation turns out to be a
1346                  specialization:
1347
1348                    template <class T> void foo(T);
1349                    class S { friend void foo<>(int) };
1350                    template <> void foo(int);
1351
1352                  We transform the existing DECL in place so that any
1353                  pointers to it become pointers to the updated
1354                  declaration.
1355
1356                  If there was a definition for the template, but not
1357                  for the specialization, we want this to look as if
1358                  there were no definition, and vice versa.  */
1359               DECL_INITIAL (fn) = NULL_TREE;
1360               duplicate_decls (spec, fn, is_friend);
1361               /* The call to duplicate_decls will have applied
1362                  [temp.expl.spec]:
1363
1364                    An explicit specialization of a function template
1365                    is inline only if it is explicitly declared to be,
1366                    and independently of whether its function template
1367                    is.
1368
1369                 to the primary function; now copy the inline bits to
1370                 the various clones.  */
1371               FOR_EACH_CLONE (clone, fn)
1372                 {
1373                   DECL_DECLARED_INLINE_P (clone)
1374                     = DECL_DECLARED_INLINE_P (fn);
1375                   DECL_SOURCE_LOCATION (clone)
1376                     = DECL_SOURCE_LOCATION (fn);
1377                 }
1378               check_specialization_namespace (fn);
1379
1380               return fn;
1381             }
1382         }
1383       else if (DECL_TEMPLATE_SPECIALIZATION (fn))
1384         {
1385           if (!duplicate_decls (spec, fn, is_friend) && DECL_INITIAL (spec))
1386             /* Dup decl failed, but this is a new definition. Set the
1387                line number so any errors match this new
1388                definition.  */
1389             DECL_SOURCE_LOCATION (fn) = DECL_SOURCE_LOCATION (spec);
1390
1391           return fn;
1392         }
1393     }
1394   else if (fn)
1395     return duplicate_decls (spec, fn, is_friend);
1396
1397   /* A specialization must be declared in the same namespace as the
1398      template it is specializing.  */
1399   if (DECL_TEMPLATE_SPECIALIZATION (spec)
1400       && !check_specialization_namespace (tmpl))
1401     DECL_CONTEXT (spec) = DECL_CONTEXT (tmpl);
1402
1403   if (!optimize_specialization_lookup_p (tmpl))
1404     {
1405       gcc_assert (tmpl && args && spec);
1406       *slot = GGC_NEW (spec_entry);
1407       **slot = elt;
1408       if (TREE_CODE (spec) == FUNCTION_DECL && DECL_NAMESPACE_SCOPE_P (spec)
1409           && PRIMARY_TEMPLATE_P (tmpl)
1410           && DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (tmpl)) == NULL_TREE)
1411         /* TMPL is a forward declaration of a template function; keep a list
1412            of all specializations in case we need to reassign them to a friend
1413            template later in tsubst_friend_function.  */
1414         DECL_TEMPLATE_INSTANTIATIONS (tmpl)
1415           = tree_cons (args, spec, DECL_TEMPLATE_INSTANTIATIONS (tmpl));
1416     }
1417
1418   return spec;
1419 }
1420
1421 /* Returns true iff two spec_entry nodes are equivalent.  Only compares the
1422    TMPL and ARGS members, ignores SPEC.  */
1423
1424 static int
1425 eq_specializations (const void *p1, const void *p2)
1426 {
1427   const spec_entry *e1 = (const spec_entry *)p1;
1428   const spec_entry *e2 = (const spec_entry *)p2;
1429
1430   return (e1->tmpl == e2->tmpl
1431           && comp_template_args (e1->args, e2->args));
1432 }
1433
1434 /* Returns a hash for a template TMPL and template arguments ARGS.  */
1435
1436 static hashval_t
1437 hash_tmpl_and_args (tree tmpl, tree args)
1438 {
1439   hashval_t val = DECL_UID (tmpl);
1440   return iterative_hash_template_arg (args, val);
1441 }
1442
1443 /* Returns a hash for a spec_entry node based on the TMPL and ARGS members,
1444    ignoring SPEC.  */
1445
1446 static hashval_t
1447 hash_specialization (const void *p)
1448 {
1449   const spec_entry *e = (const spec_entry *)p;
1450   return hash_tmpl_and_args (e->tmpl, e->args);
1451 }
1452
1453 /* Recursively calculate a hash value for a template argument ARG, for use
1454    in the hash tables of template specializations.  */
1455
1456 static hashval_t
1457 iterative_hash_template_arg (tree arg, hashval_t val)
1458 {
1459   unsigned HOST_WIDE_INT i;
1460   enum tree_code code;
1461   char tclass;
1462
1463   if (arg == NULL_TREE)
1464     return iterative_hash_object (arg, val);
1465
1466   if (!TYPE_P (arg))
1467     STRIP_NOPS (arg);
1468
1469   if (TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
1470     /* We can get one of these when re-hashing a previous entry in the middle
1471        of substituting into a pack expansion.  Just look through it.  */
1472     arg = ARGUMENT_PACK_SELECT_FROM_PACK (arg);
1473
1474   code = TREE_CODE (arg);
1475   tclass = TREE_CODE_CLASS (code);
1476
1477   val = iterative_hash_object (code, val);
1478
1479   switch (code)
1480     {
1481     case ERROR_MARK:
1482       return val;
1483
1484     case IDENTIFIER_NODE:
1485       return iterative_hash_object (IDENTIFIER_HASH_VALUE (arg), val);
1486
1487     case TREE_VEC:
1488       {
1489         int i, len = TREE_VEC_LENGTH (arg);
1490         for (i = 0; i < len; ++i)
1491           val = iterative_hash_template_arg (TREE_VEC_ELT (arg, i), val);
1492         return val;
1493       }
1494
1495     case TYPE_PACK_EXPANSION:
1496     case EXPR_PACK_EXPANSION:
1497       return iterative_hash_template_arg (PACK_EXPANSION_PATTERN (arg), val);
1498
1499     case TYPE_ARGUMENT_PACK:
1500     case NONTYPE_ARGUMENT_PACK:
1501       return iterative_hash_template_arg (ARGUMENT_PACK_ARGS (arg), val);
1502
1503     case TREE_LIST:
1504       for (; arg; arg = TREE_CHAIN (arg))
1505         val = iterative_hash_template_arg (TREE_VALUE (arg), val);
1506       return val;
1507
1508     case OVERLOAD:
1509       for (; arg; arg = OVL_CHAIN (arg))
1510         val = iterative_hash_template_arg (OVL_FUNCTION (arg), val);
1511       return val;
1512
1513     case CONSTRUCTOR:
1514       {
1515         tree field, value;
1516         FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (arg), i, field, value)
1517           {
1518             val = iterative_hash_template_arg (field, val);
1519             val = iterative_hash_template_arg (value, val);
1520           }
1521         return val;
1522       }
1523
1524     case PARM_DECL:
1525       if (!DECL_ARTIFICIAL (arg))
1526         val = iterative_hash_object (DECL_PARM_INDEX (arg), val);
1527       return iterative_hash_template_arg (TREE_TYPE (arg), val);
1528
1529     case TARGET_EXPR:
1530       return iterative_hash_template_arg (TARGET_EXPR_INITIAL (arg), val);
1531
1532     case PTRMEM_CST:
1533       val = iterative_hash_template_arg (PTRMEM_CST_CLASS (arg), val);
1534       return iterative_hash_template_arg (PTRMEM_CST_MEMBER (arg), val);
1535
1536     case TEMPLATE_PARM_INDEX:
1537       val = iterative_hash_template_arg
1538         (TREE_TYPE (TEMPLATE_PARM_DECL (arg)), val);
1539       val = iterative_hash_object (TEMPLATE_PARM_LEVEL (arg), val);
1540       return iterative_hash_object (TEMPLATE_PARM_IDX (arg), val);
1541
1542     case TRAIT_EXPR:
1543       val = iterative_hash_object (TRAIT_EXPR_KIND (arg), val);
1544       val = iterative_hash_template_arg (TRAIT_EXPR_TYPE1 (arg), val);
1545       return iterative_hash_template_arg (TRAIT_EXPR_TYPE2 (arg), val);
1546
1547     case BASELINK:
1548       val = iterative_hash_template_arg (BINFO_TYPE (BASELINK_BINFO (arg)),
1549                                          val);
1550       return iterative_hash_template_arg (DECL_NAME (get_first_fn (arg)),
1551                                           val);
1552
1553     case MODOP_EXPR:
1554       val = iterative_hash_template_arg (TREE_OPERAND (arg, 0), val);
1555       code = TREE_CODE (TREE_OPERAND (arg, 1));
1556       val = iterative_hash_object (code, val);
1557       return iterative_hash_template_arg (TREE_OPERAND (arg, 2), val);
1558
1559     case ARRAY_TYPE:
1560       /* layout_type sets structural equality for arrays of
1561          incomplete type, so we can't rely on the canonical type
1562          for hashing.  */
1563       val = iterative_hash_template_arg (TREE_TYPE (arg), val);
1564       return iterative_hash_template_arg (TYPE_DOMAIN (arg), val);
1565
1566     case LAMBDA_EXPR:
1567       /* A lambda can't appear in a template arg, but don't crash on
1568          erroneous input.  */
1569       gcc_assert (errorcount > 0);
1570       return val;
1571
1572     default:
1573       switch (tclass)
1574         {
1575         case tcc_type:
1576           if (TYPE_CANONICAL (arg))
1577             return iterative_hash_object (TYPE_HASH (TYPE_CANONICAL (arg)),
1578                                           val);
1579           else if (TREE_CODE (arg) == DECLTYPE_TYPE)
1580             return iterative_hash_template_arg (DECLTYPE_TYPE_EXPR (arg), val);
1581           /* Otherwise just compare the types during lookup.  */
1582           return val;
1583
1584         case tcc_declaration:
1585         case tcc_constant:
1586           return iterative_hash_expr (arg, val);
1587
1588         default:
1589           gcc_assert (IS_EXPR_CODE_CLASS (tclass));
1590           {
1591             unsigned n = TREE_OPERAND_LENGTH (arg);
1592             for (i = 0; i < n; ++i)
1593               val = iterative_hash_template_arg (TREE_OPERAND (arg, i), val);
1594             return val;
1595           }
1596         }
1597     }
1598   gcc_unreachable ();
1599   return 0;
1600 }
1601
1602 /* Unregister the specialization SPEC as a specialization of TMPL.
1603    Replace it with NEW_SPEC, if NEW_SPEC is non-NULL.  Returns true
1604    if the SPEC was listed as a specialization of TMPL.
1605
1606    Note that SPEC has been ggc_freed, so we can't look inside it.  */
1607
1608 bool
1609 reregister_specialization (tree spec, tree tinfo, tree new_spec)
1610 {
1611   spec_entry **slot;
1612   spec_entry elt;
1613
1614   elt.tmpl = most_general_template (TI_TEMPLATE (tinfo));
1615   elt.args = TI_ARGS (tinfo);
1616   elt.spec = NULL_TREE;
1617
1618   slot = (spec_entry **) htab_find_slot (decl_specializations, &elt, INSERT);
1619   if (*slot)
1620     {
1621       gcc_assert ((*slot)->spec == spec || (*slot)->spec == new_spec);
1622       gcc_assert (new_spec != NULL_TREE);
1623       (*slot)->spec = new_spec;
1624       return 1;
1625     }
1626
1627   return 0;
1628 }
1629
1630 /* Compare an entry in the local specializations hash table P1 (which
1631    is really a pointer to a TREE_LIST) with P2 (which is really a
1632    DECL).  */
1633
1634 static int
1635 eq_local_specializations (const void *p1, const void *p2)
1636 {
1637   return TREE_VALUE ((const_tree) p1) == (const_tree) p2;
1638 }
1639
1640 /* Hash P1, an entry in the local specializations table.  */
1641
1642 static hashval_t
1643 hash_local_specialization (const void* p1)
1644 {
1645   return htab_hash_pointer (TREE_VALUE ((const_tree) p1));
1646 }
1647
1648 /* Like register_specialization, but for local declarations.  We are
1649    registering SPEC, an instantiation of TMPL.  */
1650
1651 static void
1652 register_local_specialization (tree spec, tree tmpl)
1653 {
1654   void **slot;
1655
1656   slot = htab_find_slot_with_hash (local_specializations, tmpl,
1657                                    htab_hash_pointer (tmpl), INSERT);
1658   *slot = build_tree_list (spec, tmpl);
1659 }
1660
1661 /* TYPE is a class type.  Returns true if TYPE is an explicitly
1662    specialized class.  */
1663
1664 bool
1665 explicit_class_specialization_p (tree type)
1666 {
1667   if (!CLASSTYPE_TEMPLATE_SPECIALIZATION (type))
1668     return false;
1669   return !uses_template_parms (CLASSTYPE_TI_ARGS (type));
1670 }
1671
1672 /* Print the list of functions at FNS, going through all the overloads
1673    for each element of the list.  Alternatively, FNS can not be a
1674    TREE_LIST, in which case it will be printed together with all the
1675    overloads.
1676
1677    MORE and *STR should respectively be FALSE and NULL when the function
1678    is called from the outside.  They are used internally on recursive
1679    calls.  print_candidates manages the two parameters and leaves NULL
1680    in *STR when it ends.  */
1681
1682 static void
1683 print_candidates_1 (tree fns, bool more, const char **str)
1684 {
1685   tree fn, fn2;
1686   char *spaces = NULL;
1687
1688   for (fn = fns; fn; fn = OVL_NEXT (fn))
1689     if (TREE_CODE (fn) == TREE_LIST)
1690       {
1691         gcc_assert (!OVL_NEXT (fn) && !is_overloaded_fn (fn));
1692         for (fn2 = fn; fn2 != NULL_TREE; fn2 = TREE_CHAIN (fn2))
1693           print_candidates_1 (TREE_VALUE (fn2),
1694                               TREE_CHAIN (fn2) || more, str);
1695       }
1696     else
1697       {
1698         if (!*str)
1699           {
1700             /* Pick the prefix string.  */
1701             if (!more && !OVL_NEXT (fns))
1702               {
1703                 error ("candidate is: %+#D", OVL_CURRENT (fn));
1704                 continue;
1705               }
1706
1707             *str = _("candidates are:");
1708             spaces = get_spaces (*str);
1709           }
1710         error ("%s %+#D", *str, OVL_CURRENT (fn));
1711         *str = spaces ? spaces : *str;
1712       }
1713
1714   if (!more)
1715     {
1716       free (spaces);
1717       *str = NULL;
1718     }
1719 }
1720
1721 /* Print the list of candidate FNS in an error message.  */
1722
1723 void
1724 print_candidates (tree fns)
1725 {
1726   const char *str = NULL;
1727   print_candidates_1 (fns, false, &str);
1728   gcc_assert (str == NULL);
1729 }
1730
1731 /* Returns the template (one of the functions given by TEMPLATE_ID)
1732    which can be specialized to match the indicated DECL with the
1733    explicit template args given in TEMPLATE_ID.  The DECL may be
1734    NULL_TREE if none is available.  In that case, the functions in
1735    TEMPLATE_ID are non-members.
1736
1737    If NEED_MEMBER_TEMPLATE is nonzero the function is known to be a
1738    specialization of a member template.
1739
1740    The TEMPLATE_COUNT is the number of references to qualifying
1741    template classes that appeared in the name of the function. See
1742    check_explicit_specialization for a more accurate description.
1743
1744    TSK indicates what kind of template declaration (if any) is being
1745    declared.  TSK_TEMPLATE indicates that the declaration given by
1746    DECL, though a FUNCTION_DECL, has template parameters, and is
1747    therefore a template function.
1748
1749    The template args (those explicitly specified and those deduced)
1750    are output in a newly created vector *TARGS_OUT.
1751
1752    If it is impossible to determine the result, an error message is
1753    issued.  The error_mark_node is returned to indicate failure.  */
1754
1755 static tree
1756 determine_specialization (tree template_id,
1757                           tree decl,
1758                           tree* targs_out,
1759                           int need_member_template,
1760                           int template_count,
1761                           tmpl_spec_kind tsk)
1762 {
1763   tree fns;
1764   tree targs;
1765   tree explicit_targs;
1766   tree candidates = NULL_TREE;
1767   /* A TREE_LIST of templates of which DECL may be a specialization.
1768      The TREE_VALUE of each node is a TEMPLATE_DECL.  The
1769      corresponding TREE_PURPOSE is the set of template arguments that,
1770      when used to instantiate the template, would produce a function
1771      with the signature of DECL.  */
1772   tree templates = NULL_TREE;
1773   int header_count;
1774   struct cp_binding_level *b;
1775
1776   *targs_out = NULL_TREE;
1777
1778   if (template_id == error_mark_node || decl == error_mark_node)
1779     return error_mark_node;
1780
1781   fns = TREE_OPERAND (template_id, 0);
1782   explicit_targs = TREE_OPERAND (template_id, 1);
1783
1784   if (fns == error_mark_node)
1785     return error_mark_node;
1786
1787   /* Check for baselinks.  */
1788   if (BASELINK_P (fns))
1789     fns = BASELINK_FUNCTIONS (fns);
1790
1791   if (!is_overloaded_fn (fns))
1792     {
1793       error ("%qD is not a function template", fns);
1794       return error_mark_node;
1795     }
1796
1797   /* Count the number of template headers specified for this
1798      specialization.  */
1799   header_count = 0;
1800   for (b = current_binding_level;
1801        b->kind == sk_template_parms;
1802        b = b->level_chain)
1803     ++header_count;
1804
1805   for (; fns; fns = OVL_NEXT (fns))
1806     {
1807       tree fn = OVL_CURRENT (fns);
1808
1809       if (TREE_CODE (fn) == TEMPLATE_DECL)
1810         {
1811           tree decl_arg_types;
1812           tree fn_arg_types;
1813
1814           /* In case of explicit specialization, we need to check if
1815              the number of template headers appearing in the specialization
1816              is correct. This is usually done in check_explicit_specialization,
1817              but the check done there cannot be exhaustive when specializing
1818              member functions. Consider the following code:
1819
1820              template <> void A<int>::f(int);
1821              template <> template <> void A<int>::f(int);
1822
1823              Assuming that A<int> is not itself an explicit specialization
1824              already, the first line specializes "f" which is a non-template
1825              member function, whilst the second line specializes "f" which
1826              is a template member function. So both lines are syntactically
1827              correct, and check_explicit_specialization does not reject
1828              them.
1829
1830              Here, we can do better, as we are matching the specialization
1831              against the declarations. We count the number of template
1832              headers, and we check if they match TEMPLATE_COUNT + 1
1833              (TEMPLATE_COUNT is the number of qualifying template classes,
1834              plus there must be another header for the member template
1835              itself).
1836
1837              Notice that if header_count is zero, this is not a
1838              specialization but rather a template instantiation, so there
1839              is no check we can perform here.  */
1840           if (header_count && header_count != template_count + 1)
1841             continue;
1842
1843           /* Check that the number of template arguments at the
1844              innermost level for DECL is the same as for FN.  */
1845           if (current_binding_level->kind == sk_template_parms
1846               && !current_binding_level->explicit_spec_p
1847               && (TREE_VEC_LENGTH (DECL_INNERMOST_TEMPLATE_PARMS (fn))
1848                   != TREE_VEC_LENGTH (INNERMOST_TEMPLATE_PARMS
1849                                       (current_template_parms))))
1850             continue;
1851
1852           /* DECL might be a specialization of FN.  */
1853           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1854           fn_arg_types = TYPE_ARG_TYPES (TREE_TYPE (fn));
1855
1856           /* For a non-static member function, we need to make sure
1857              that the const qualification is the same.  Since
1858              get_bindings does not try to merge the "this" parameter,
1859              we must do the comparison explicitly.  */
1860           if (DECL_NONSTATIC_MEMBER_FUNCTION_P (fn)
1861               && !same_type_p (TREE_VALUE (fn_arg_types),
1862                                TREE_VALUE (decl_arg_types)))
1863             continue;
1864
1865           /* Skip the "this" parameter and, for constructors of
1866              classes with virtual bases, the VTT parameter.  A
1867              full specialization of a constructor will have a VTT
1868              parameter, but a template never will.  */ 
1869           decl_arg_types 
1870             = skip_artificial_parms_for (decl, decl_arg_types);
1871           fn_arg_types 
1872             = skip_artificial_parms_for (fn, fn_arg_types);
1873
1874           /* Check that the number of function parameters matches.
1875              For example,
1876                template <class T> void f(int i = 0);
1877                template <> void f<int>();
1878              The specialization f<int> is invalid but is not caught
1879              by get_bindings below.  */
1880           if (list_length (fn_arg_types) != list_length (decl_arg_types))
1881             continue;
1882
1883           /* Function templates cannot be specializations; there are
1884              no partial specializations of functions.  Therefore, if
1885              the type of DECL does not match FN, there is no
1886              match.  */
1887           if (tsk == tsk_template)
1888             {
1889               if (compparms (fn_arg_types, decl_arg_types))
1890                 candidates = tree_cons (NULL_TREE, fn, candidates);
1891               continue;
1892             }
1893
1894           /* See whether this function might be a specialization of this
1895              template.  */
1896           targs = get_bindings (fn, decl, explicit_targs, /*check_ret=*/true);
1897
1898           if (!targs)
1899             /* We cannot deduce template arguments that when used to
1900                specialize TMPL will produce DECL.  */
1901             continue;
1902
1903           /* Save this template, and the arguments deduced.  */
1904           templates = tree_cons (targs, fn, templates);
1905         }
1906       else if (need_member_template)
1907         /* FN is an ordinary member function, and we need a
1908            specialization of a member template.  */
1909         ;
1910       else if (TREE_CODE (fn) != FUNCTION_DECL)
1911         /* We can get IDENTIFIER_NODEs here in certain erroneous
1912            cases.  */
1913         ;
1914       else if (!DECL_FUNCTION_MEMBER_P (fn))
1915         /* This is just an ordinary non-member function.  Nothing can
1916            be a specialization of that.  */
1917         ;
1918       else if (DECL_ARTIFICIAL (fn))
1919         /* Cannot specialize functions that are created implicitly.  */
1920         ;
1921       else
1922         {
1923           tree decl_arg_types;
1924
1925           /* This is an ordinary member function.  However, since
1926              we're here, we can assume it's enclosing class is a
1927              template class.  For example,
1928
1929                template <typename T> struct S { void f(); };
1930                template <> void S<int>::f() {}
1931
1932              Here, S<int>::f is a non-template, but S<int> is a
1933              template class.  If FN has the same type as DECL, we
1934              might be in business.  */
1935
1936           if (!DECL_TEMPLATE_INFO (fn))
1937             /* Its enclosing class is an explicit specialization
1938                of a template class.  This is not a candidate.  */
1939             continue;
1940
1941           if (!same_type_p (TREE_TYPE (TREE_TYPE (decl)),
1942                             TREE_TYPE (TREE_TYPE (fn))))
1943             /* The return types differ.  */
1944             continue;
1945
1946           /* Adjust the type of DECL in case FN is a static member.  */
1947           decl_arg_types = TYPE_ARG_TYPES (TREE_TYPE (decl));
1948           if (DECL_STATIC_FUNCTION_P (fn)
1949               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
1950             decl_arg_types = TREE_CHAIN (decl_arg_types);
1951
1952           if (compparms (TYPE_ARG_TYPES (TREE_TYPE (fn)),
1953                          decl_arg_types))
1954             /* They match!  */
1955             candidates = tree_cons (NULL_TREE, fn, candidates);
1956         }
1957     }
1958
1959   if (templates && TREE_CHAIN (templates))
1960     {
1961       /* We have:
1962
1963            [temp.expl.spec]
1964
1965            It is possible for a specialization with a given function
1966            signature to be instantiated from more than one function
1967            template.  In such cases, explicit specification of the
1968            template arguments must be used to uniquely identify the
1969            function template specialization being specialized.
1970
1971          Note that here, there's no suggestion that we're supposed to
1972          determine which of the candidate templates is most
1973          specialized.  However, we, also have:
1974
1975            [temp.func.order]
1976
1977            Partial ordering of overloaded function template
1978            declarations is used in the following contexts to select
1979            the function template to which a function template
1980            specialization refers:
1981
1982            -- when an explicit specialization refers to a function
1983               template.
1984
1985          So, we do use the partial ordering rules, at least for now.
1986          This extension can only serve to make invalid programs valid,
1987          so it's safe.  And, there is strong anecdotal evidence that
1988          the committee intended the partial ordering rules to apply;
1989          the EDG front end has that behavior, and John Spicer claims
1990          that the committee simply forgot to delete the wording in
1991          [temp.expl.spec].  */
1992       tree tmpl = most_specialized_instantiation (templates);
1993       if (tmpl != error_mark_node)
1994         {
1995           templates = tmpl;
1996           TREE_CHAIN (templates) = NULL_TREE;
1997         }
1998     }
1999
2000   if (templates == NULL_TREE && candidates == NULL_TREE)
2001     {
2002       error ("template-id %qD for %q+D does not match any template "
2003              "declaration", template_id, decl);
2004       if (header_count && header_count != template_count + 1)
2005         inform (input_location, "saw %d %<template<>%>, need %d for "
2006                 "specializing a member function template",
2007                 header_count, template_count + 1);
2008       return error_mark_node;
2009     }
2010   else if ((templates && TREE_CHAIN (templates))
2011            || (candidates && TREE_CHAIN (candidates))
2012            || (templates && candidates))
2013     {
2014       error ("ambiguous template specialization %qD for %q+D",
2015              template_id, decl);
2016       candidates = chainon (candidates, templates);
2017       print_candidates (candidates);
2018       return error_mark_node;
2019     }
2020
2021   /* We have one, and exactly one, match.  */
2022   if (candidates)
2023     {
2024       tree fn = TREE_VALUE (candidates);
2025       *targs_out = copy_node (DECL_TI_ARGS (fn));
2026       /* DECL is a re-declaration or partial instantiation of a template
2027          function.  */
2028       if (TREE_CODE (fn) == TEMPLATE_DECL)
2029         return fn;
2030       /* It was a specialization of an ordinary member function in a
2031          template class.  */
2032       return DECL_TI_TEMPLATE (fn);
2033     }
2034
2035   /* It was a specialization of a template.  */
2036   targs = DECL_TI_ARGS (DECL_TEMPLATE_RESULT (TREE_VALUE (templates)));
2037   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (targs))
2038     {
2039       *targs_out = copy_node (targs);
2040       SET_TMPL_ARGS_LEVEL (*targs_out,
2041                            TMPL_ARGS_DEPTH (*targs_out),
2042                            TREE_PURPOSE (templates));
2043     }
2044   else
2045     *targs_out = TREE_PURPOSE (templates);
2046   return TREE_VALUE (templates);
2047 }
2048
2049 /* Returns a chain of parameter types, exactly like the SPEC_TYPES,
2050    but with the default argument values filled in from those in the
2051    TMPL_TYPES.  */
2052
2053 static tree
2054 copy_default_args_to_explicit_spec_1 (tree spec_types,
2055                                       tree tmpl_types)
2056 {
2057   tree new_spec_types;
2058
2059   if (!spec_types)
2060     return NULL_TREE;
2061
2062   if (spec_types == void_list_node)
2063     return void_list_node;
2064
2065   /* Substitute into the rest of the list.  */
2066   new_spec_types =
2067     copy_default_args_to_explicit_spec_1 (TREE_CHAIN (spec_types),
2068                                           TREE_CHAIN (tmpl_types));
2069
2070   /* Add the default argument for this parameter.  */
2071   return hash_tree_cons (TREE_PURPOSE (tmpl_types),
2072                          TREE_VALUE (spec_types),
2073                          new_spec_types);
2074 }
2075
2076 /* DECL is an explicit specialization.  Replicate default arguments
2077    from the template it specializes.  (That way, code like:
2078
2079      template <class T> void f(T = 3);
2080      template <> void f(double);
2081      void g () { f (); }
2082
2083    works, as required.)  An alternative approach would be to look up
2084    the correct default arguments at the call-site, but this approach
2085    is consistent with how implicit instantiations are handled.  */
2086
2087 static void
2088 copy_default_args_to_explicit_spec (tree decl)
2089 {
2090   tree tmpl;
2091   tree spec_types;
2092   tree tmpl_types;
2093   tree new_spec_types;
2094   tree old_type;
2095   tree new_type;
2096   tree t;
2097   tree object_type = NULL_TREE;
2098   tree in_charge = NULL_TREE;
2099   tree vtt = NULL_TREE;
2100
2101   /* See if there's anything we need to do.  */
2102   tmpl = DECL_TI_TEMPLATE (decl);
2103   tmpl_types = TYPE_ARG_TYPES (TREE_TYPE (DECL_TEMPLATE_RESULT (tmpl)));
2104   for (t = tmpl_types; t; t = TREE_CHAIN (t))
2105     if (TREE_PURPOSE (t))
2106       break;
2107   if (!t)
2108     return;
2109
2110   old_type = TREE_TYPE (decl);
2111   spec_types = TYPE_ARG_TYPES (old_type);
2112
2113   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2114     {
2115       /* Remove the this pointer, but remember the object's type for
2116          CV quals.  */
2117       object_type = TREE_TYPE (TREE_VALUE (spec_types));
2118       spec_types = TREE_CHAIN (spec_types);
2119       tmpl_types = TREE_CHAIN (tmpl_types);
2120
2121       if (DECL_HAS_IN_CHARGE_PARM_P (decl))
2122         {
2123           /* DECL may contain more parameters than TMPL due to the extra
2124              in-charge parameter in constructors and destructors.  */
2125           in_charge = spec_types;
2126           spec_types = TREE_CHAIN (spec_types);
2127         }
2128       if (DECL_HAS_VTT_PARM_P (decl))
2129         {
2130           vtt = spec_types;
2131           spec_types = TREE_CHAIN (spec_types);
2132         }
2133     }
2134
2135   /* Compute the merged default arguments.  */
2136   new_spec_types =
2137     copy_default_args_to_explicit_spec_1 (spec_types, tmpl_types);
2138
2139   /* Compute the new FUNCTION_TYPE.  */
2140   if (object_type)
2141     {
2142       if (vtt)
2143         new_spec_types = hash_tree_cons (TREE_PURPOSE (vtt),
2144                                          TREE_VALUE (vtt),
2145                                          new_spec_types);
2146
2147       if (in_charge)
2148         /* Put the in-charge parameter back.  */
2149         new_spec_types = hash_tree_cons (TREE_PURPOSE (in_charge),
2150                                          TREE_VALUE (in_charge),
2151                                          new_spec_types);
2152
2153       new_type = build_method_type_directly (object_type,
2154                                              TREE_TYPE (old_type),
2155                                              new_spec_types);
2156     }
2157   else
2158     new_type = build_function_type (TREE_TYPE (old_type),
2159                                     new_spec_types);
2160   new_type = cp_build_type_attribute_variant (new_type,
2161                                               TYPE_ATTRIBUTES (old_type));
2162   new_type = build_exception_variant (new_type,
2163                                       TYPE_RAISES_EXCEPTIONS (old_type));
2164   TREE_TYPE (decl) = new_type;
2165 }
2166
2167 /* Check to see if the function just declared, as indicated in
2168    DECLARATOR, and in DECL, is a specialization of a function
2169    template.  We may also discover that the declaration is an explicit
2170    instantiation at this point.
2171
2172    Returns DECL, or an equivalent declaration that should be used
2173    instead if all goes well.  Issues an error message if something is
2174    amiss.  Returns error_mark_node if the error is not easily
2175    recoverable.
2176
2177    FLAGS is a bitmask consisting of the following flags:
2178
2179    2: The function has a definition.
2180    4: The function is a friend.
2181
2182    The TEMPLATE_COUNT is the number of references to qualifying
2183    template classes that appeared in the name of the function.  For
2184    example, in
2185
2186      template <class T> struct S { void f(); };
2187      void S<int>::f();
2188
2189    the TEMPLATE_COUNT would be 1.  However, explicitly specialized
2190    classes are not counted in the TEMPLATE_COUNT, so that in
2191
2192      template <class T> struct S {};
2193      template <> struct S<int> { void f(); }
2194      template <> void S<int>::f();
2195
2196    the TEMPLATE_COUNT would be 0.  (Note that this declaration is
2197    invalid; there should be no template <>.)
2198
2199    If the function is a specialization, it is marked as such via
2200    DECL_TEMPLATE_SPECIALIZATION.  Furthermore, its DECL_TEMPLATE_INFO
2201    is set up correctly, and it is added to the list of specializations
2202    for that template.  */
2203
2204 tree
2205 check_explicit_specialization (tree declarator,
2206                                tree decl,
2207                                int template_count,
2208                                int flags)
2209 {
2210   int have_def = flags & 2;
2211   int is_friend = flags & 4;
2212   int specialization = 0;
2213   int explicit_instantiation = 0;
2214   int member_specialization = 0;
2215   tree ctype = DECL_CLASS_CONTEXT (decl);
2216   tree dname = DECL_NAME (decl);
2217   tmpl_spec_kind tsk;
2218
2219   if (is_friend)
2220     {
2221       if (!processing_specialization)
2222         tsk = tsk_none;
2223       else
2224         tsk = tsk_excessive_parms;
2225     }
2226   else
2227     tsk = current_tmpl_spec_kind (template_count);
2228
2229   switch (tsk)
2230     {
2231     case tsk_none:
2232       if (processing_specialization)
2233         {
2234           specialization = 1;
2235           SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2236         }
2237       else if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2238         {
2239           if (is_friend)
2240             /* This could be something like:
2241
2242                template <class T> void f(T);
2243                class S { friend void f<>(int); }  */
2244             specialization = 1;
2245           else
2246             {
2247               /* This case handles bogus declarations like template <>
2248                  template <class T> void f<int>(); */
2249
2250               error ("template-id %qD in declaration of primary template",
2251                      declarator);
2252               return decl;
2253             }
2254         }
2255       break;
2256
2257     case tsk_invalid_member_spec:
2258       /* The error has already been reported in
2259          check_specialization_scope.  */
2260       return error_mark_node;
2261
2262     case tsk_invalid_expl_inst:
2263       error ("template parameter list used in explicit instantiation");
2264
2265       /* Fall through.  */
2266
2267     case tsk_expl_inst:
2268       if (have_def)
2269         error ("definition provided for explicit instantiation");
2270
2271       explicit_instantiation = 1;
2272       break;
2273
2274     case tsk_excessive_parms:
2275     case tsk_insufficient_parms:
2276       if (tsk == tsk_excessive_parms)
2277         error ("too many template parameter lists in declaration of %qD",
2278                decl);
2279       else if (template_header_count)
2280         error("too few template parameter lists in declaration of %qD", decl);
2281       else
2282         error("explicit specialization of %qD must be introduced by "
2283               "%<template <>%>", decl);
2284
2285       /* Fall through.  */
2286     case tsk_expl_spec:
2287       SET_DECL_TEMPLATE_SPECIALIZATION (decl);
2288       if (ctype)
2289         member_specialization = 1;
2290       else
2291         specialization = 1;
2292       break;
2293
2294     case tsk_template:
2295       if (TREE_CODE (declarator) == TEMPLATE_ID_EXPR)
2296         {
2297           /* This case handles bogus declarations like template <>
2298              template <class T> void f<int>(); */
2299
2300           if (uses_template_parms (declarator))
2301             error ("function template partial specialization %qD "
2302                    "is not allowed", declarator);
2303           else
2304             error ("template-id %qD in declaration of primary template",
2305                    declarator);
2306           return decl;
2307         }
2308
2309       if (ctype && CLASSTYPE_TEMPLATE_INSTANTIATION (ctype))
2310         /* This is a specialization of a member template, without
2311            specialization the containing class.  Something like:
2312
2313              template <class T> struct S {
2314                template <class U> void f (U);
2315              };
2316              template <> template <class U> void S<int>::f(U) {}
2317
2318            That's a specialization -- but of the entire template.  */
2319         specialization = 1;
2320       break;
2321
2322     default:
2323       gcc_unreachable ();
2324     }
2325
2326   if (specialization || member_specialization)
2327     {
2328       tree t = TYPE_ARG_TYPES (TREE_TYPE (decl));
2329       for (; t; t = TREE_CHAIN (t))
2330         if (TREE_PURPOSE (t))
2331           {
2332             permerror (input_location, 
2333                        "default argument specified in explicit specialization");
2334             break;
2335           }
2336     }
2337
2338   if (specialization || member_specialization || explicit_instantiation)
2339     {
2340       tree tmpl = NULL_TREE;
2341       tree targs = NULL_TREE;
2342
2343       /* Make sure that the declarator is a TEMPLATE_ID_EXPR.  */
2344       if (TREE_CODE (declarator) != TEMPLATE_ID_EXPR)
2345         {
2346           tree fns;
2347
2348           gcc_assert (TREE_CODE (declarator) == IDENTIFIER_NODE);
2349           if (ctype)
2350             fns = dname;
2351           else
2352             {
2353               /* If there is no class context, the explicit instantiation
2354                  must be at namespace scope.  */
2355               gcc_assert (DECL_NAMESPACE_SCOPE_P (decl));
2356
2357               /* Find the namespace binding, using the declaration
2358                  context.  */
2359               fns = lookup_qualified_name (CP_DECL_CONTEXT (decl), dname,
2360                                            false, true);
2361               if (fns == error_mark_node || !is_overloaded_fn (fns))
2362                 {
2363                   error ("%qD is not a template function", dname);
2364                   fns = error_mark_node;
2365                 }
2366               else
2367                 {
2368                   tree fn = OVL_CURRENT (fns);
2369                   if (!is_associated_namespace (CP_DECL_CONTEXT (decl),
2370                                                 CP_DECL_CONTEXT (fn)))
2371                     error ("%qD is not declared in %qD",
2372                            decl, current_namespace);
2373                 }
2374             }
2375
2376           declarator = lookup_template_function (fns, NULL_TREE);
2377         }
2378
2379       if (declarator == error_mark_node)
2380         return error_mark_node;
2381
2382       if (ctype != NULL_TREE && TYPE_BEING_DEFINED (ctype))
2383         {
2384           if (!explicit_instantiation)
2385             /* A specialization in class scope.  This is invalid,
2386                but the error will already have been flagged by
2387                check_specialization_scope.  */
2388             return error_mark_node;
2389           else
2390             {
2391               /* It's not valid to write an explicit instantiation in
2392                  class scope, e.g.:
2393
2394                    class C { template void f(); }
2395
2396                    This case is caught by the parser.  However, on
2397                    something like:
2398
2399                    template class C { void f(); };
2400
2401                    (which is invalid) we can get here.  The error will be
2402                    issued later.  */
2403               ;
2404             }
2405
2406           return decl;
2407         }
2408       else if (ctype != NULL_TREE
2409                && (TREE_CODE (TREE_OPERAND (declarator, 0)) ==
2410                    IDENTIFIER_NODE))
2411         {
2412           /* Find the list of functions in ctype that have the same
2413              name as the declared function.  */
2414           tree name = TREE_OPERAND (declarator, 0);
2415           tree fns = NULL_TREE;
2416           int idx;
2417
2418           if (constructor_name_p (name, ctype))
2419             {
2420               int is_constructor = DECL_CONSTRUCTOR_P (decl);
2421
2422               if (is_constructor ? !TYPE_HAS_USER_CONSTRUCTOR (ctype)
2423                   : !CLASSTYPE_DESTRUCTORS (ctype))
2424                 {
2425                   /* From [temp.expl.spec]:
2426
2427                      If such an explicit specialization for the member
2428                      of a class template names an implicitly-declared
2429                      special member function (clause _special_), the
2430                      program is ill-formed.
2431
2432                      Similar language is found in [temp.explicit].  */
2433                   error ("specialization of implicitly-declared special member function");
2434                   return error_mark_node;
2435                 }
2436
2437               name = is_constructor ? ctor_identifier : dtor_identifier;
2438             }
2439
2440           if (!DECL_CONV_FN_P (decl))
2441             {
2442               idx = lookup_fnfields_1 (ctype, name);
2443               if (idx >= 0)
2444                 fns = VEC_index (tree, CLASSTYPE_METHOD_VEC (ctype), idx);
2445             }
2446           else
2447             {
2448               VEC(tree,gc) *methods;
2449               tree ovl;
2450
2451               /* For a type-conversion operator, we cannot do a
2452                  name-based lookup.  We might be looking for `operator
2453                  int' which will be a specialization of `operator T'.
2454                  So, we find *all* the conversion operators, and then
2455                  select from them.  */
2456               fns = NULL_TREE;
2457
2458               methods = CLASSTYPE_METHOD_VEC (ctype);
2459               if (methods)
2460                 for (idx = CLASSTYPE_FIRST_CONVERSION_SLOT;
2461                      VEC_iterate (tree, methods, idx, ovl);
2462                      ++idx)
2463                   {
2464                     if (!DECL_CONV_FN_P (OVL_CURRENT (ovl)))
2465                       /* There are no more conversion functions.  */
2466                       break;
2467
2468                     /* Glue all these conversion functions together
2469                        with those we already have.  */
2470                     for (; ovl; ovl = OVL_NEXT (ovl))
2471                       fns = ovl_cons (OVL_CURRENT (ovl), fns);
2472                   }
2473             }
2474
2475           if (fns == NULL_TREE)
2476             {
2477               error ("no member function %qD declared in %qT", name, ctype);
2478               return error_mark_node;
2479             }
2480           else
2481             TREE_OPERAND (declarator, 0) = fns;
2482         }
2483
2484       /* Figure out what exactly is being specialized at this point.
2485          Note that for an explicit instantiation, even one for a
2486          member function, we cannot tell apriori whether the
2487          instantiation is for a member template, or just a member
2488          function of a template class.  Even if a member template is
2489          being instantiated, the member template arguments may be
2490          elided if they can be deduced from the rest of the
2491          declaration.  */
2492       tmpl = determine_specialization (declarator, decl,
2493                                        &targs,
2494                                        member_specialization,
2495                                        template_count,
2496                                        tsk);
2497
2498       if (!tmpl || tmpl == error_mark_node)
2499         /* We couldn't figure out what this declaration was
2500            specializing.  */
2501         return error_mark_node;
2502       else
2503         {
2504           tree gen_tmpl = most_general_template (tmpl);
2505
2506           if (explicit_instantiation)
2507             {
2508               /* We don't set DECL_EXPLICIT_INSTANTIATION here; that
2509                  is done by do_decl_instantiation later.  */
2510
2511               int arg_depth = TMPL_ARGS_DEPTH (targs);
2512               int parm_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
2513
2514               if (arg_depth > parm_depth)
2515                 {
2516                   /* If TMPL is not the most general template (for
2517                      example, if TMPL is a friend template that is
2518                      injected into namespace scope), then there will
2519                      be too many levels of TARGS.  Remove some of them
2520                      here.  */
2521                   int i;
2522                   tree new_targs;
2523
2524                   new_targs = make_tree_vec (parm_depth);
2525                   for (i = arg_depth - parm_depth; i < arg_depth; ++i)
2526                     TREE_VEC_ELT (new_targs, i - (arg_depth - parm_depth))
2527                       = TREE_VEC_ELT (targs, i);
2528                   targs = new_targs;
2529                 }
2530
2531               return instantiate_template (tmpl, targs, tf_error);
2532             }
2533
2534           /* If we thought that the DECL was a member function, but it
2535              turns out to be specializing a static member function,
2536              make DECL a static member function as well.  */
2537           if (DECL_STATIC_FUNCTION_P (tmpl)
2538               && DECL_NONSTATIC_MEMBER_FUNCTION_P (decl))
2539             revert_static_member_fn (decl);
2540
2541           /* If this is a specialization of a member template of a
2542              template class, we want to return the TEMPLATE_DECL, not
2543              the specialization of it.  */
2544           if (tsk == tsk_template)
2545             {
2546               tree result = DECL_TEMPLATE_RESULT (tmpl);
2547               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
2548               DECL_INITIAL (result) = NULL_TREE;
2549               if (have_def)
2550                 {
2551                   tree parm;
2552                   DECL_SOURCE_LOCATION (tmpl) = DECL_SOURCE_LOCATION (decl);
2553                   DECL_SOURCE_LOCATION (result)
2554                     = DECL_SOURCE_LOCATION (decl);
2555                   /* We want to use the argument list specified in the
2556                      definition, not in the original declaration.  */
2557                   DECL_ARGUMENTS (result) = DECL_ARGUMENTS (decl);
2558                   for (parm = DECL_ARGUMENTS (result); parm;
2559                        parm = TREE_CHAIN (parm))
2560                     DECL_CONTEXT (parm) = result;
2561                 }
2562               return register_specialization (tmpl, gen_tmpl, targs,
2563                                               is_friend, 0);
2564             }
2565
2566           /* Set up the DECL_TEMPLATE_INFO for DECL.  */
2567           DECL_TEMPLATE_INFO (decl) = build_template_info (tmpl, targs);
2568
2569           /* Inherit default function arguments from the template
2570              DECL is specializing.  */
2571           copy_default_args_to_explicit_spec (decl);
2572
2573           /* This specialization has the same protection as the
2574              template it specializes.  */
2575           TREE_PRIVATE (decl) = TREE_PRIVATE (gen_tmpl);
2576           TREE_PROTECTED (decl) = TREE_PROTECTED (gen_tmpl);
2577
2578           /* 7.1.1-1 [dcl.stc]
2579
2580              A storage-class-specifier shall not be specified in an
2581              explicit specialization...
2582
2583              The parser rejects these, so unless action is taken here,
2584              explicit function specializations will always appear with
2585              global linkage.
2586
2587              The action recommended by the C++ CWG in response to C++
2588              defect report 605 is to make the storage class and linkage
2589              of the explicit specialization match the templated function:
2590
2591              http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#605
2592            */
2593           if (tsk == tsk_expl_spec && DECL_FUNCTION_TEMPLATE_P (gen_tmpl))
2594             {
2595               tree tmpl_func = DECL_TEMPLATE_RESULT (gen_tmpl);
2596               gcc_assert (TREE_CODE (tmpl_func) == FUNCTION_DECL);
2597
2598               /* This specialization has the same linkage and visibility as
2599                  the function template it specializes.  */
2600               TREE_PUBLIC (decl) = TREE_PUBLIC (tmpl_func);
2601               if (! TREE_PUBLIC (decl))
2602                 {
2603                   DECL_INTERFACE_KNOWN (decl) = 1;
2604                   DECL_NOT_REALLY_EXTERN (decl) = 1;
2605                 }
2606               DECL_THIS_STATIC (decl) = DECL_THIS_STATIC (tmpl_func);
2607               if (DECL_VISIBILITY_SPECIFIED (tmpl_func))
2608                 {
2609                   DECL_VISIBILITY_SPECIFIED (decl) = 1;
2610                   DECL_VISIBILITY (decl) = DECL_VISIBILITY (tmpl_func);
2611                 }
2612             }
2613
2614           /* If DECL is a friend declaration, declared using an
2615              unqualified name, the namespace associated with DECL may
2616              have been set incorrectly.  For example, in:
2617
2618                template <typename T> void f(T);
2619                namespace N {
2620                  struct S { friend void f<int>(int); }
2621                }
2622
2623              we will have set the DECL_CONTEXT for the friend
2624              declaration to N, rather than to the global namespace.  */
2625           if (DECL_NAMESPACE_SCOPE_P (decl))
2626             DECL_CONTEXT (decl) = DECL_CONTEXT (tmpl);
2627
2628           if (is_friend && !have_def)
2629             /* This is not really a declaration of a specialization.
2630                It's just the name of an instantiation.  But, it's not
2631                a request for an instantiation, either.  */
2632             SET_DECL_IMPLICIT_INSTANTIATION (decl);
2633           else if (DECL_CONSTRUCTOR_P (decl) || DECL_DESTRUCTOR_P (decl))
2634             /* This is indeed a specialization.  In case of constructors
2635                and destructors, we need in-charge and not-in-charge
2636                versions in V3 ABI.  */
2637             clone_function_decl (decl, /*update_method_vec_p=*/0);
2638
2639           /* Register this specialization so that we can find it
2640              again.  */
2641           decl = register_specialization (decl, gen_tmpl, targs, is_friend, 0);
2642         }
2643     }
2644
2645   return decl;
2646 }
2647
2648 /* Returns 1 iff PARMS1 and PARMS2 are identical sets of template
2649    parameters.  These are represented in the same format used for
2650    DECL_TEMPLATE_PARMS.  */
2651
2652 int
2653 comp_template_parms (const_tree parms1, const_tree parms2)
2654 {
2655   const_tree p1;
2656   const_tree p2;
2657
2658   if (parms1 == parms2)
2659     return 1;
2660
2661   for (p1 = parms1, p2 = parms2;
2662        p1 != NULL_TREE && p2 != NULL_TREE;
2663        p1 = TREE_CHAIN (p1), p2 = TREE_CHAIN (p2))
2664     {
2665       tree t1 = TREE_VALUE (p1);
2666       tree t2 = TREE_VALUE (p2);
2667       int i;
2668
2669       gcc_assert (TREE_CODE (t1) == TREE_VEC);
2670       gcc_assert (TREE_CODE (t2) == TREE_VEC);
2671
2672       if (TREE_VEC_LENGTH (t1) != TREE_VEC_LENGTH (t2))
2673         return 0;
2674
2675       for (i = 0; i < TREE_VEC_LENGTH (t2); ++i)
2676         {
2677           tree parm1 = TREE_VALUE (TREE_VEC_ELT (t1, i));
2678           tree parm2 = TREE_VALUE (TREE_VEC_ELT (t2, i));
2679
2680           /* If either of the template parameters are invalid, assume
2681              they match for the sake of error recovery. */
2682           if (parm1 == error_mark_node || parm2 == error_mark_node)
2683             return 1;
2684
2685           if (TREE_CODE (parm1) != TREE_CODE (parm2))
2686             return 0;
2687
2688           if (TREE_CODE (parm1) == TEMPLATE_TYPE_PARM
2689               && (TEMPLATE_TYPE_PARAMETER_PACK (parm1)
2690                   == TEMPLATE_TYPE_PARAMETER_PACK (parm2)))
2691             continue;
2692           else if (!same_type_p (TREE_TYPE (parm1), TREE_TYPE (parm2)))
2693             return 0;
2694         }
2695     }
2696
2697   if ((p1 != NULL_TREE) != (p2 != NULL_TREE))
2698     /* One set of parameters has more parameters lists than the
2699        other.  */
2700     return 0;
2701
2702   return 1;
2703 }
2704
2705 /* Determine whether PARM is a parameter pack.  */
2706
2707 bool 
2708 template_parameter_pack_p (const_tree parm)
2709 {
2710   /* Determine if we have a non-type template parameter pack.  */
2711   if (TREE_CODE (parm) == PARM_DECL)
2712     return (DECL_TEMPLATE_PARM_P (parm) 
2713             && TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)));
2714
2715   /* If this is a list of template parameters, we could get a
2716      TYPE_DECL or a TEMPLATE_DECL.  */ 
2717   if (TREE_CODE (parm) == TYPE_DECL || TREE_CODE (parm) == TEMPLATE_DECL)
2718     parm = TREE_TYPE (parm);
2719
2720   return ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
2721            || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM)
2722           && TEMPLATE_TYPE_PARAMETER_PACK (parm));
2723 }
2724
2725 /* Determine if T is a function parameter pack.  */
2726
2727 bool
2728 function_parameter_pack_p (const_tree t)
2729 {
2730   if (t && TREE_CODE (t) == PARM_DECL)
2731     return FUNCTION_PARAMETER_PACK_P (t);
2732   return false;
2733 }
2734
2735 /* Return the function template declaration of PRIMARY_FUNC_TMPL_INST.
2736    PRIMARY_FUNC_TMPL_INST is a primary function template instantiation.  */
2737
2738 tree
2739 get_function_template_decl (const_tree primary_func_tmpl_inst)
2740 {
2741   if (! primary_func_tmpl_inst
2742       || TREE_CODE (primary_func_tmpl_inst) != FUNCTION_DECL
2743       || ! primary_template_instantiation_p (primary_func_tmpl_inst))
2744     return NULL;
2745
2746   return DECL_TEMPLATE_RESULT (DECL_TI_TEMPLATE (primary_func_tmpl_inst));
2747 }
2748
2749 /* Return true iff the function parameter PARAM_DECL was expanded
2750    from the function parameter pack PACK.  */
2751
2752 bool
2753 function_parameter_expanded_from_pack_p (tree param_decl, tree pack)
2754 {
2755   if (DECL_ARTIFICIAL (param_decl)
2756       || !function_parameter_pack_p (pack))
2757     return false;
2758
2759   /* The parameter pack and its pack arguments have the same
2760      DECL_PARM_INDEX.  */
2761   return DECL_PARM_INDEX (pack) == DECL_PARM_INDEX (param_decl);
2762 }
2763
2764 /* Determine whether ARGS describes a variadic template args list,
2765    i.e., one that is terminated by a template argument pack.  */
2766
2767 static bool 
2768 template_args_variadic_p (tree args)
2769 {
2770   int nargs;
2771   tree last_parm;
2772
2773   if (args == NULL_TREE)
2774     return false;
2775
2776   args = INNERMOST_TEMPLATE_ARGS (args);
2777   nargs = TREE_VEC_LENGTH (args);
2778
2779   if (nargs == 0)
2780     return false;
2781
2782   last_parm = TREE_VEC_ELT (args, nargs - 1);
2783
2784   return ARGUMENT_PACK_P (last_parm);
2785 }
2786
2787 /* Generate a new name for the parameter pack name NAME (an
2788    IDENTIFIER_NODE) that incorporates its */
2789
2790 static tree
2791 make_ith_pack_parameter_name (tree name, int i)
2792 {
2793   /* Munge the name to include the parameter index.  */
2794 #define NUMBUF_LEN 128
2795   char numbuf[NUMBUF_LEN];
2796   char* newname;
2797   int newname_len;
2798
2799   snprintf (numbuf, NUMBUF_LEN, "%i", i);
2800   newname_len = IDENTIFIER_LENGTH (name)
2801                 + strlen (numbuf) + 2;
2802   newname = (char*)alloca (newname_len);
2803   snprintf (newname, newname_len,
2804             "%s#%i", IDENTIFIER_POINTER (name), i);
2805   return get_identifier (newname);
2806 }
2807
2808 /* Return true if T is a primary function
2809    or class template instantiation.  */
2810
2811 bool
2812 primary_template_instantiation_p (const_tree t)
2813 {
2814   if (!t)
2815     return false;
2816
2817   if (TREE_CODE (t) == FUNCTION_DECL)
2818     return DECL_LANG_SPECIFIC (t)
2819            && DECL_TEMPLATE_INSTANTIATION (t)
2820            && PRIMARY_TEMPLATE_P (DECL_TI_TEMPLATE (t));
2821   else if (CLASS_TYPE_P (t))
2822     return CLASSTYPE_TEMPLATE_INSTANTIATION (t)
2823            && PRIMARY_TEMPLATE_P (CLASSTYPE_TI_TEMPLATE (t));
2824   return false;
2825 }
2826
2827 /* Return true if PARM is a template template parameter.  */
2828
2829 bool
2830 template_template_parameter_p (const_tree parm)
2831 {
2832   return DECL_TEMPLATE_TEMPLATE_PARM_P (parm);
2833 }
2834
2835 /* Return the template parameters of T if T is a
2836    primary template instantiation, NULL otherwise.  */
2837
2838 tree
2839 get_primary_template_innermost_parameters (const_tree t)
2840 {
2841   tree parms = NULL, template_info = NULL;
2842
2843   if ((template_info = get_template_info (t))
2844       && primary_template_instantiation_p (t))
2845     parms = INNERMOST_TEMPLATE_PARMS
2846         (DECL_TEMPLATE_PARMS (TI_TEMPLATE (template_info)));
2847
2848   return parms;
2849 }
2850
2851 /* Return the template parameters of the LEVELth level from the full list
2852    of template parameters PARMS.  */
2853
2854 tree
2855 get_template_parms_at_level (tree parms, int level)
2856 {
2857   tree p;
2858   if (!parms
2859       || TREE_CODE (parms) != TREE_LIST
2860       || level > TMPL_PARMS_DEPTH (parms))
2861     return NULL_TREE;
2862
2863   for (p = parms; p; p = TREE_CHAIN (p))
2864     if (TMPL_PARMS_DEPTH (p) == level)
2865       return p;
2866
2867   return NULL_TREE;
2868 }
2869
2870 /* Returns the template arguments of T if T is a template instantiation,
2871    NULL otherwise.  */
2872
2873 tree
2874 get_template_innermost_arguments (const_tree t)
2875 {
2876   tree args = NULL, template_info = NULL;
2877
2878   if ((template_info = get_template_info (t))
2879       && TI_ARGS (template_info))
2880     args = INNERMOST_TEMPLATE_ARGS (TI_ARGS (template_info));
2881
2882   return args;
2883 }
2884
2885 /* Return the argument pack elements of T if T is a template argument pack,
2886    NULL otherwise.  */
2887
2888 tree
2889 get_template_argument_pack_elems (const_tree t)
2890 {
2891   if (TREE_CODE (t) != TYPE_ARGUMENT_PACK
2892       && TREE_CODE (t) != NONTYPE_ARGUMENT_PACK)
2893     return NULL;
2894
2895   return ARGUMENT_PACK_ARGS (t);
2896 }
2897
2898 /* Structure used to track the progress of find_parameter_packs_r.  */
2899 struct find_parameter_pack_data 
2900 {
2901   /* TREE_LIST that will contain all of the parameter packs found by
2902      the traversal.  */
2903   tree* parameter_packs;
2904
2905   /* Set of AST nodes that have been visited by the traversal.  */
2906   struct pointer_set_t *visited;
2907 };
2908
2909 /* Identifies all of the argument packs that occur in a template
2910    argument and appends them to the TREE_LIST inside DATA, which is a
2911    find_parameter_pack_data structure. This is a subroutine of
2912    make_pack_expansion and uses_parameter_packs.  */
2913 static tree
2914 find_parameter_packs_r (tree *tp, int *walk_subtrees, void* data)
2915 {
2916   tree t = *tp;
2917   struct find_parameter_pack_data* ppd = 
2918     (struct find_parameter_pack_data*)data;
2919   bool parameter_pack_p = false;
2920
2921   /* Identify whether this is a parameter pack or not.  */
2922   switch (TREE_CODE (t))
2923     {
2924     case TEMPLATE_PARM_INDEX:
2925       if (TEMPLATE_PARM_PARAMETER_PACK (t))
2926         parameter_pack_p = true;
2927       break;
2928
2929     case TEMPLATE_TYPE_PARM:
2930     case TEMPLATE_TEMPLATE_PARM:
2931       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
2932         parameter_pack_p = true;
2933       break;
2934
2935     case PARM_DECL:
2936       if (FUNCTION_PARAMETER_PACK_P (t))
2937         {
2938           /* We don't want to walk into the type of a PARM_DECL,
2939              because we don't want to see the type parameter pack.  */
2940           *walk_subtrees = 0;
2941           parameter_pack_p = true;
2942         }
2943       break;
2944
2945     default:
2946       /* Not a parameter pack.  */
2947       break;
2948     }
2949
2950   if (parameter_pack_p)
2951     {
2952       /* Add this parameter pack to the list.  */
2953       *ppd->parameter_packs = tree_cons (NULL_TREE, t, *ppd->parameter_packs);
2954     }
2955
2956   if (TYPE_P (t))
2957     cp_walk_tree (&TYPE_CONTEXT (t), 
2958                   &find_parameter_packs_r, ppd, ppd->visited);
2959
2960   /* This switch statement will return immediately if we don't find a
2961      parameter pack.  */
2962   switch (TREE_CODE (t)) 
2963     {
2964     case TEMPLATE_PARM_INDEX:
2965       return NULL_TREE;
2966
2967     case BOUND_TEMPLATE_TEMPLATE_PARM:
2968       /* Check the template itself.  */
2969       cp_walk_tree (&TREE_TYPE (TYPE_TI_TEMPLATE (t)), 
2970                     &find_parameter_packs_r, ppd, ppd->visited);
2971       /* Check the template arguments.  */
2972       cp_walk_tree (&TYPE_TI_ARGS (t), &find_parameter_packs_r, ppd, 
2973                     ppd->visited);
2974       *walk_subtrees = 0;
2975       return NULL_TREE;
2976
2977     case TEMPLATE_TYPE_PARM:
2978     case TEMPLATE_TEMPLATE_PARM:
2979       return NULL_TREE;
2980
2981     case PARM_DECL:
2982       return NULL_TREE;
2983
2984     case RECORD_TYPE:
2985       if (TYPE_PTRMEMFUNC_P (t))
2986         return NULL_TREE;
2987       /* Fall through.  */
2988
2989     case UNION_TYPE:
2990     case ENUMERAL_TYPE:
2991       if (TYPE_TEMPLATE_INFO (t))
2992         cp_walk_tree (&TI_ARGS (TYPE_TEMPLATE_INFO (t)),
2993                       &find_parameter_packs_r, ppd, ppd->visited);
2994
2995       *walk_subtrees = 0;
2996       return NULL_TREE;
2997
2998     case TEMPLATE_DECL:
2999       cp_walk_tree (&TREE_TYPE (t),
3000                     &find_parameter_packs_r, ppd, ppd->visited);
3001       return NULL_TREE;
3002  
3003     case TYPENAME_TYPE:
3004       cp_walk_tree (&TYPENAME_TYPE_FULLNAME (t), &find_parameter_packs_r,
3005                    ppd, ppd->visited);
3006       *walk_subtrees = 0;
3007       return NULL_TREE;
3008       
3009     case TYPE_PACK_EXPANSION:
3010     case EXPR_PACK_EXPANSION:
3011       *walk_subtrees = 0;
3012       return NULL_TREE;
3013
3014     case INTEGER_TYPE:
3015       cp_walk_tree (&TYPE_MAX_VALUE (t), &find_parameter_packs_r, 
3016                     ppd, ppd->visited);
3017       *walk_subtrees = 0;
3018       return NULL_TREE;
3019
3020     case IDENTIFIER_NODE:
3021       cp_walk_tree (&TREE_TYPE (t), &find_parameter_packs_r, ppd, 
3022                     ppd->visited);
3023       *walk_subtrees = 0;
3024       return NULL_TREE;
3025
3026     default:
3027       return NULL_TREE;
3028     }
3029
3030   return NULL_TREE;
3031 }
3032
3033 /* Determines if the expression or type T uses any parameter packs.  */
3034 bool
3035 uses_parameter_packs (tree t)
3036 {
3037   tree parameter_packs = NULL_TREE;
3038   struct find_parameter_pack_data ppd;
3039   ppd.parameter_packs = &parameter_packs;
3040   ppd.visited = pointer_set_create ();
3041   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3042   pointer_set_destroy (ppd.visited);
3043   return parameter_packs != NULL_TREE;
3044 }
3045
3046 /* Turn ARG, which may be an expression, type, or a TREE_LIST
3047    representation a base-class initializer into a parameter pack
3048    expansion. If all goes well, the resulting node will be an
3049    EXPR_PACK_EXPANSION, TYPE_PACK_EXPANSION, or TREE_LIST,
3050    respectively.  */
3051 tree 
3052 make_pack_expansion (tree arg)
3053 {
3054   tree result;
3055   tree parameter_packs = NULL_TREE;
3056   bool for_types = false;
3057   struct find_parameter_pack_data ppd;
3058
3059   if (!arg || arg == error_mark_node)
3060     return arg;
3061
3062   if (TREE_CODE (arg) == TREE_LIST)
3063     {
3064       /* The only time we will see a TREE_LIST here is for a base
3065          class initializer.  In this case, the TREE_PURPOSE will be a
3066          _TYPE node (representing the base class expansion we're
3067          initializing) and the TREE_VALUE will be a TREE_LIST
3068          containing the initialization arguments. 
3069
3070          The resulting expansion looks somewhat different from most
3071          expansions. Rather than returning just one _EXPANSION, we
3072          return a TREE_LIST whose TREE_PURPOSE is a
3073          TYPE_PACK_EXPANSION containing the bases that will be
3074          initialized.  The TREE_VALUE will be identical to the
3075          original TREE_VALUE, which is a list of arguments that will
3076          be passed to each base.  We do not introduce any new pack
3077          expansion nodes into the TREE_VALUE (although it is possible
3078          that some already exist), because the TREE_PURPOSE and
3079          TREE_VALUE all need to be expanded together with the same
3080          _EXPANSION node.  Note that the TYPE_PACK_EXPANSION in the
3081          resulting TREE_PURPOSE will mention the parameter packs in
3082          both the bases and the arguments to the bases.  */
3083       tree purpose;
3084       tree value;
3085       tree parameter_packs = NULL_TREE;
3086
3087       /* Determine which parameter packs will be used by the base
3088          class expansion.  */
3089       ppd.visited = pointer_set_create ();
3090       ppd.parameter_packs = &parameter_packs;
3091       cp_walk_tree (&TREE_PURPOSE (arg), &find_parameter_packs_r, 
3092                     &ppd, ppd.visited);
3093
3094       if (parameter_packs == NULL_TREE)
3095         {
3096           error ("base initializer expansion %<%T%> contains no parameter packs", arg);
3097           pointer_set_destroy (ppd.visited);
3098           return error_mark_node;
3099         }
3100
3101       if (TREE_VALUE (arg) != void_type_node)
3102         {
3103           /* Collect the sets of parameter packs used in each of the
3104              initialization arguments.  */
3105           for (value = TREE_VALUE (arg); value; value = TREE_CHAIN (value))
3106             {
3107               /* Determine which parameter packs will be expanded in this
3108                  argument.  */
3109               cp_walk_tree (&TREE_VALUE (value), &find_parameter_packs_r, 
3110                             &ppd, ppd.visited);
3111             }
3112         }
3113
3114       pointer_set_destroy (ppd.visited);
3115
3116       /* Create the pack expansion type for the base type.  */
3117       purpose = cxx_make_type (TYPE_PACK_EXPANSION);
3118       SET_PACK_EXPANSION_PATTERN (purpose, TREE_PURPOSE (arg));
3119       PACK_EXPANSION_PARAMETER_PACKS (purpose) = parameter_packs;
3120
3121       /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3122          they will rarely be compared to anything.  */
3123       SET_TYPE_STRUCTURAL_EQUALITY (purpose);
3124
3125       return tree_cons (purpose, TREE_VALUE (arg), NULL_TREE);
3126     }
3127
3128   if (TYPE_P (arg) || TREE_CODE (arg) == TEMPLATE_DECL)
3129     for_types = true;
3130
3131   /* Build the PACK_EXPANSION_* node.  */
3132   result = for_types
3133      ? cxx_make_type (TYPE_PACK_EXPANSION)
3134      : make_node (EXPR_PACK_EXPANSION);
3135   SET_PACK_EXPANSION_PATTERN (result, arg);
3136   if (TREE_CODE (result) == EXPR_PACK_EXPANSION)
3137     {
3138       /* Propagate type and const-expression information.  */
3139       TREE_TYPE (result) = TREE_TYPE (arg);
3140       TREE_CONSTANT (result) = TREE_CONSTANT (arg);
3141     }
3142   else
3143     /* Just use structural equality for these TYPE_PACK_EXPANSIONS;
3144        they will rarely be compared to anything.  */
3145     SET_TYPE_STRUCTURAL_EQUALITY (result);
3146
3147   /* Determine which parameter packs will be expanded.  */
3148   ppd.parameter_packs = &parameter_packs;
3149   ppd.visited = pointer_set_create ();
3150   cp_walk_tree (&arg, &find_parameter_packs_r, &ppd, ppd.visited);
3151   pointer_set_destroy (ppd.visited);
3152
3153   /* Make sure we found some parameter packs.  */
3154   if (parameter_packs == NULL_TREE)
3155     {
3156       if (TYPE_P (arg))
3157         error ("expansion pattern %<%T%> contains no argument packs", arg);
3158       else
3159         error ("expansion pattern %<%E%> contains no argument packs", arg);
3160       return error_mark_node;
3161     }
3162   PACK_EXPANSION_PARAMETER_PACKS (result) = parameter_packs;
3163
3164   return result;
3165 }
3166
3167 /* Checks T for any "bare" parameter packs, which have not yet been
3168    expanded, and issues an error if any are found. This operation can
3169    only be done on full expressions or types (e.g., an expression
3170    statement, "if" condition, etc.), because we could have expressions like:
3171
3172      foo(f(g(h(args)))...)
3173
3174    where "args" is a parameter pack. check_for_bare_parameter_packs
3175    should not be called for the subexpressions args, h(args),
3176    g(h(args)), or f(g(h(args))), because we would produce erroneous
3177    error messages. 
3178
3179    Returns TRUE and emits an error if there were bare parameter packs,
3180    returns FALSE otherwise.  */
3181 bool 
3182 check_for_bare_parameter_packs (tree t)
3183 {
3184   tree parameter_packs = NULL_TREE;
3185   struct find_parameter_pack_data ppd;
3186
3187   if (!processing_template_decl || !t || t == error_mark_node)
3188     return false;
3189
3190   if (TREE_CODE (t) == TYPE_DECL)
3191     t = TREE_TYPE (t);
3192
3193   ppd.parameter_packs = &parameter_packs;
3194   ppd.visited = pointer_set_create ();
3195   cp_walk_tree (&t, &find_parameter_packs_r, &ppd, ppd.visited);
3196   pointer_set_destroy (ppd.visited);
3197
3198   if (parameter_packs) 
3199     {
3200       error ("parameter packs not expanded with %<...%>:");
3201       while (parameter_packs)
3202         {
3203           tree pack = TREE_VALUE (parameter_packs);
3204           tree name = NULL_TREE;
3205
3206           if (TREE_CODE (pack) == TEMPLATE_TYPE_PARM
3207               || TREE_CODE (pack) == TEMPLATE_TEMPLATE_PARM)
3208             name = TYPE_NAME (pack);
3209           else if (TREE_CODE (pack) == TEMPLATE_PARM_INDEX)
3210             name = DECL_NAME (TEMPLATE_PARM_DECL (pack));
3211           else
3212             name = DECL_NAME (pack);
3213
3214           if (name)
3215             inform (input_location, "        %qD", name);
3216           else
3217             inform (input_location, "        <anonymous>");
3218
3219           parameter_packs = TREE_CHAIN (parameter_packs);
3220         }
3221
3222       return true;
3223     }
3224
3225   return false;
3226 }
3227
3228 /* Expand any parameter packs that occur in the template arguments in
3229    ARGS.  */
3230 tree
3231 expand_template_argument_pack (tree args)
3232 {
3233   tree result_args = NULL_TREE;
3234   int in_arg, out_arg = 0, nargs = args ? TREE_VEC_LENGTH (args) : 0;
3235   int num_result_args = -1;
3236   int non_default_args_count = -1;
3237
3238   /* First, determine if we need to expand anything, and the number of
3239      slots we'll need.  */
3240   for (in_arg = 0; in_arg < nargs; ++in_arg)
3241     {
3242       tree arg = TREE_VEC_ELT (args, in_arg);
3243       if (arg == NULL_TREE)
3244         return args;
3245       if (ARGUMENT_PACK_P (arg))
3246         {
3247           int num_packed = TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg));
3248           if (num_result_args < 0)
3249             num_result_args = in_arg + num_packed;
3250           else
3251             num_result_args += num_packed;
3252         }
3253       else
3254         {
3255           if (num_result_args >= 0)
3256             num_result_args++;
3257         }
3258     }
3259
3260   /* If no expansion is necessary, we're done.  */
3261   if (num_result_args < 0)
3262     return args;
3263
3264   /* Expand arguments.  */
3265   result_args = make_tree_vec (num_result_args);
3266   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (args))
3267     non_default_args_count =
3268       GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (args);
3269   for (in_arg = 0; in_arg < nargs; ++in_arg)
3270     {
3271       tree arg = TREE_VEC_ELT (args, in_arg);
3272       if (ARGUMENT_PACK_P (arg))
3273         {
3274           tree packed = ARGUMENT_PACK_ARGS (arg);
3275           int i, num_packed = TREE_VEC_LENGTH (packed);
3276           for (i = 0; i < num_packed; ++i, ++out_arg)
3277             TREE_VEC_ELT (result_args, out_arg) = TREE_VEC_ELT(packed, i);
3278           if (non_default_args_count > 0)
3279             non_default_args_count += num_packed;
3280         }
3281       else
3282         {
3283           TREE_VEC_ELT (result_args, out_arg) = arg;
3284           ++out_arg;
3285         }
3286     }
3287   if (non_default_args_count >= 0)
3288     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (result_args, non_default_args_count);
3289   return result_args;
3290 }
3291
3292 /* Checks if DECL shadows a template parameter.
3293
3294    [temp.local]: A template-parameter shall not be redeclared within its
3295    scope (including nested scopes).
3296
3297    Emits an error and returns TRUE if the DECL shadows a parameter,
3298    returns FALSE otherwise.  */
3299
3300 bool
3301 check_template_shadow (tree decl)
3302 {
3303   tree olddecl;
3304
3305   /* If we're not in a template, we can't possibly shadow a template
3306      parameter.  */
3307   if (!current_template_parms)
3308     return true;
3309
3310   /* Figure out what we're shadowing.  */
3311   if (TREE_CODE (decl) == OVERLOAD)
3312     decl = OVL_CURRENT (decl);
3313   olddecl = innermost_non_namespace_value (DECL_NAME (decl));
3314
3315   /* If there's no previous binding for this name, we're not shadowing
3316      anything, let alone a template parameter.  */
3317   if (!olddecl)
3318     return true;
3319
3320   /* If we're not shadowing a template parameter, we're done.  Note
3321      that OLDDECL might be an OVERLOAD (or perhaps even an
3322      ERROR_MARK), so we can't just blithely assume it to be a _DECL
3323      node.  */
3324   if (!DECL_P (olddecl) || !DECL_TEMPLATE_PARM_P (olddecl))
3325     return true;
3326
3327   /* We check for decl != olddecl to avoid bogus errors for using a
3328      name inside a class.  We check TPFI to avoid duplicate errors for
3329      inline member templates.  */
3330   if (decl == olddecl
3331       || TEMPLATE_PARMS_FOR_INLINE (current_template_parms))
3332     return true;
3333
3334   error ("declaration of %q+#D", decl);
3335   error (" shadows template parm %q+#D", olddecl);
3336   return false;
3337 }
3338
3339 /* Return a new TEMPLATE_PARM_INDEX with the indicated INDEX, LEVEL,
3340    ORIG_LEVEL, DECL, and TYPE.  */
3341
3342 static tree
3343 build_template_parm_index (int index,
3344                            int level,
3345                            int orig_level,
3346                            tree decl,
3347                            tree type)
3348 {
3349   tree t = make_node (TEMPLATE_PARM_INDEX);
3350   TEMPLATE_PARM_IDX (t) = index;
3351   TEMPLATE_PARM_LEVEL (t) = level;
3352   TEMPLATE_PARM_ORIG_LEVEL (t) = orig_level;
3353   TEMPLATE_PARM_DECL (t) = decl;
3354   TREE_TYPE (t) = type;
3355   TREE_CONSTANT (t) = TREE_CONSTANT (decl);
3356   TREE_READONLY (t) = TREE_READONLY (decl);
3357
3358   return t;
3359 }
3360
3361 /* Find the canonical type parameter for the given template type
3362    parameter.  Returns the canonical type parameter, which may be TYPE
3363    if no such parameter existed.  */
3364 static tree
3365 canonical_type_parameter (tree type)
3366 {
3367   tree list;
3368   int idx = TEMPLATE_TYPE_IDX (type);
3369   if (!canonical_template_parms)
3370     canonical_template_parms = VEC_alloc (tree, gc, idx+1);
3371
3372   while (VEC_length (tree, canonical_template_parms) <= (unsigned)idx)
3373     VEC_safe_push (tree, gc, canonical_template_parms, NULL_TREE);
3374
3375   list = VEC_index (tree, canonical_template_parms, idx);
3376   while (list && !comptypes (type, TREE_VALUE (list), COMPARE_STRUCTURAL))
3377     list = TREE_CHAIN (list);
3378
3379   if (list)
3380     return TREE_VALUE (list);
3381   else
3382     {
3383       VEC_replace(tree, canonical_template_parms, idx,
3384                   tree_cons (NULL_TREE, type, 
3385                              VEC_index (tree, canonical_template_parms, idx)));
3386       return type;
3387     }
3388 }
3389
3390 /* Return a TEMPLATE_PARM_INDEX, similar to INDEX, but whose
3391    TEMPLATE_PARM_LEVEL has been decreased by LEVELS.  If such a
3392    TEMPLATE_PARM_INDEX already exists, it is returned; otherwise, a
3393    new one is created.  */
3394
3395 static tree
3396 reduce_template_parm_level (tree index, tree type, int levels, tree args,
3397                             tsubst_flags_t complain)
3398 {
3399   if (TEMPLATE_PARM_DESCENDANTS (index) == NULL_TREE
3400       || (TEMPLATE_PARM_LEVEL (TEMPLATE_PARM_DESCENDANTS (index))
3401           != TEMPLATE_PARM_LEVEL (index) - levels)
3402       || !same_type_p (type, TREE_TYPE (TEMPLATE_PARM_DESCENDANTS (index))))
3403     {
3404       tree orig_decl = TEMPLATE_PARM_DECL (index);
3405       tree decl, t;
3406
3407       decl = build_decl (DECL_SOURCE_LOCATION (orig_decl),
3408                          TREE_CODE (orig_decl), DECL_NAME (orig_decl), type);
3409       TREE_CONSTANT (decl) = TREE_CONSTANT (orig_decl);
3410       TREE_READONLY (decl) = TREE_READONLY (orig_decl);
3411       DECL_ARTIFICIAL (decl) = 1;
3412       SET_DECL_TEMPLATE_PARM_P (decl);
3413
3414       t = build_template_parm_index (TEMPLATE_PARM_IDX (index),
3415                                      TEMPLATE_PARM_LEVEL (index) - levels,
3416                                      TEMPLATE_PARM_ORIG_LEVEL (index),
3417                                      decl, type);
3418       TEMPLATE_PARM_DESCENDANTS (index) = t;
3419       TEMPLATE_PARM_PARAMETER_PACK (t) 
3420         = TEMPLATE_PARM_PARAMETER_PACK (index);
3421
3422         /* Template template parameters need this.  */
3423       if (TREE_CODE (decl) == TEMPLATE_DECL)
3424         DECL_TEMPLATE_PARMS (decl) = tsubst_template_parms
3425           (DECL_TEMPLATE_PARMS (TEMPLATE_PARM_DECL (index)),
3426            args, complain);
3427     }
3428
3429   return TEMPLATE_PARM_DESCENDANTS (index);
3430 }
3431
3432 /* Process information from new template parameter PARM and append it to the
3433    LIST being built.  This new parameter is a non-type parameter iff
3434    IS_NON_TYPE is true. This new parameter is a parameter
3435    pack iff IS_PARAMETER_PACK is true.  The location of PARM is in 
3436    PARM_LOC.  */
3437
3438 tree
3439 process_template_parm (tree list, location_t parm_loc, tree parm, bool is_non_type, 
3440                        bool is_parameter_pack)
3441 {
3442   tree decl = 0;
3443   tree defval;
3444   tree err_parm_list;
3445   int idx = 0;
3446
3447   gcc_assert (TREE_CODE (parm) == TREE_LIST);
3448   defval = TREE_PURPOSE (parm);
3449
3450   if (list)
3451     {
3452       tree p = tree_last (list);
3453
3454       if (p && TREE_VALUE (p) != error_mark_node)
3455         {
3456           p = TREE_VALUE (p);
3457           if (TREE_CODE (p) == TYPE_DECL || TREE_CODE (p) == TEMPLATE_DECL)
3458             idx = TEMPLATE_TYPE_IDX (TREE_TYPE (p));
3459           else
3460             idx = TEMPLATE_PARM_IDX (DECL_INITIAL (p));
3461         }
3462
3463       ++idx;
3464     }
3465   else
3466     idx = 0;
3467
3468   if (is_non_type)
3469     {
3470       parm = TREE_VALUE (parm);
3471
3472       SET_DECL_TEMPLATE_PARM_P (parm);
3473
3474       if (TREE_TYPE (parm) == error_mark_node)
3475         {
3476           err_parm_list = build_tree_list (defval, parm);
3477           TREE_VALUE (err_parm_list) = error_mark_node;
3478            return chainon (list, err_parm_list);
3479         }
3480       else
3481       {
3482         /* [temp.param]
3483
3484            The top-level cv-qualifiers on the template-parameter are
3485            ignored when determining its type.  */
3486         TREE_TYPE (parm) = TYPE_MAIN_VARIANT (TREE_TYPE (parm));
3487         if (invalid_nontype_parm_type_p (TREE_TYPE (parm), 1))
3488           {
3489             err_parm_list = build_tree_list (defval, parm);
3490             TREE_VALUE (err_parm_list) = error_mark_node;
3491              return chainon (list, err_parm_list);
3492           }
3493
3494         if (uses_parameter_packs (TREE_TYPE (parm)) && !is_parameter_pack)
3495           {
3496             /* This template parameter is not a parameter pack, but it
3497                should be. Complain about "bare" parameter packs.  */
3498             check_for_bare_parameter_packs (TREE_TYPE (parm));
3499             
3500             /* Recover by calling this a parameter pack.  */
3501             is_parameter_pack = true;
3502           }
3503       }
3504
3505       /* A template parameter is not modifiable.  */
3506       TREE_CONSTANT (parm) = 1;
3507       TREE_READONLY (parm) = 1;
3508       decl = build_decl (parm_loc,
3509                          CONST_DECL, DECL_NAME (parm), TREE_TYPE (parm));
3510       TREE_CONSTANT (decl) = 1;
3511       TREE_READONLY (decl) = 1;
3512       DECL_INITIAL (parm) = DECL_INITIAL (decl)
3513         = build_template_parm_index (idx, processing_template_decl,
3514                                      processing_template_decl,
3515                                      decl, TREE_TYPE (parm));
3516
3517       TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)) 
3518         = is_parameter_pack;
3519     }
3520   else
3521     {
3522       tree t;
3523       parm = TREE_VALUE (TREE_VALUE (parm));
3524
3525       if (parm && TREE_CODE (parm) == TEMPLATE_DECL)
3526         {
3527           t = cxx_make_type (TEMPLATE_TEMPLATE_PARM);
3528           /* This is for distinguishing between real templates and template
3529              template parameters */
3530           TREE_TYPE (parm) = t;
3531           TREE_TYPE (DECL_TEMPLATE_RESULT (parm)) = t;
3532           decl = parm;
3533         }
3534       else
3535         {
3536           t = cxx_make_type (TEMPLATE_TYPE_PARM);
3537           /* parm is either IDENTIFIER_NODE or NULL_TREE.  */
3538           decl = build_decl (parm_loc,
3539                              TYPE_DECL, parm, t);
3540         }
3541
3542       TYPE_NAME (t) = decl;
3543       TYPE_STUB_DECL (t) = decl;
3544       parm = decl;
3545       TEMPLATE_TYPE_PARM_INDEX (t)
3546         = build_template_parm_index (idx, processing_template_decl,
3547                                      processing_template_decl,
3548                                      decl, TREE_TYPE (parm));
3549       TEMPLATE_TYPE_PARAMETER_PACK (t) = is_parameter_pack;
3550       TYPE_CANONICAL (t) = canonical_type_parameter (t);
3551     }
3552   DECL_ARTIFICIAL (decl) = 1;
3553   SET_DECL_TEMPLATE_PARM_P (decl);
3554   pushdecl (decl);
3555   parm = build_tree_list (defval, parm);
3556   return chainon (list, parm);
3557 }
3558
3559 /* The end of a template parameter list has been reached.  Process the
3560    tree list into a parameter vector, converting each parameter into a more
3561    useful form.  Type parameters are saved as IDENTIFIER_NODEs, and others
3562    as PARM_DECLs.  */
3563
3564 tree
3565 end_template_parm_list (tree parms)
3566 {
3567   int nparms;
3568   tree parm, next;
3569   tree saved_parmlist = make_tree_vec (list_length (parms));
3570
3571   current_template_parms
3572     = tree_cons (size_int (processing_template_decl),
3573                  saved_parmlist, current_template_parms);
3574
3575   for (parm = parms, nparms = 0; parm; parm = next, nparms++)
3576     {
3577       next = TREE_CHAIN (parm);
3578       TREE_VEC_ELT (saved_parmlist, nparms) = parm;
3579       TREE_CHAIN (parm) = NULL_TREE;
3580       if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL)
3581         TEMPLATE_TYPE_PARM_SIBLING_PARMS (TREE_TYPE (TREE_VALUE (parm))) =
3582               current_template_parms;
3583     }
3584
3585   --processing_template_parmlist;
3586
3587   return saved_parmlist;
3588 }
3589
3590 /* end_template_decl is called after a template declaration is seen.  */
3591
3592 void
3593 end_template_decl (void)
3594 {
3595   reset_specialization ();
3596
3597   if (! processing_template_decl)
3598     return;
3599
3600   /* This matches the pushlevel in begin_template_parm_list.  */
3601   finish_scope ();
3602
3603   --processing_template_decl;
3604   current_template_parms = TREE_CHAIN (current_template_parms);
3605 }
3606
3607 /* Within the declaration of a template, return all levels of template
3608    parameters that apply.  The template parameters are represented as
3609    a TREE_VEC, in the form documented in cp-tree.h for template
3610    arguments.  */
3611
3612 static tree
3613 current_template_args (void)
3614 {
3615   tree header;
3616   tree args = NULL_TREE;
3617   int length = TMPL_PARMS_DEPTH (current_template_parms);
3618   int l = length;
3619
3620   /* If there is only one level of template parameters, we do not
3621      create a TREE_VEC of TREE_VECs.  Instead, we return a single
3622      TREE_VEC containing the arguments.  */
3623   if (length > 1)
3624     args = make_tree_vec (length);
3625
3626   for (header = current_template_parms; header; header = TREE_CHAIN (header))
3627     {
3628       tree a = copy_node (TREE_VALUE (header));
3629       int i;
3630
3631       TREE_TYPE (a) = NULL_TREE;
3632       for (i = TREE_VEC_LENGTH (a) - 1; i >= 0; --i)
3633         {
3634           tree t = TREE_VEC_ELT (a, i);
3635
3636           /* T will be a list if we are called from within a
3637              begin/end_template_parm_list pair, but a vector directly
3638              if within a begin/end_member_template_processing pair.  */
3639           if (TREE_CODE (t) == TREE_LIST)
3640             {
3641               t = TREE_VALUE (t);
3642
3643               if (!error_operand_p (t))
3644                 {
3645                   if (TREE_CODE (t) == TYPE_DECL
3646                       || TREE_CODE (t) == TEMPLATE_DECL)
3647                     {
3648                       t = TREE_TYPE (t);
3649                       
3650                       if (TEMPLATE_TYPE_PARAMETER_PACK (t))
3651                         {
3652                           /* Turn this argument into a TYPE_ARGUMENT_PACK
3653                              with a single element, which expands T.  */
3654                           tree vec = make_tree_vec (1);
3655 #ifdef ENABLE_CHECKING
3656                           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3657                                 (vec, TREE_VEC_LENGTH (vec));
3658 #endif
3659                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3660                           
3661                           t = cxx_make_type (TYPE_ARGUMENT_PACK);
3662                           SET_ARGUMENT_PACK_ARGS (t, vec);
3663                         }
3664                     }
3665                   else
3666                     {
3667                       t = DECL_INITIAL (t);
3668                       
3669                       if (TEMPLATE_PARM_PARAMETER_PACK (t))
3670                         {
3671                           /* Turn this argument into a NONTYPE_ARGUMENT_PACK
3672                              with a single element, which expands T.  */
3673                           tree vec = make_tree_vec (1);
3674                           tree type = TREE_TYPE (TEMPLATE_PARM_DECL (t));
3675 #ifdef ENABLE_CHECKING
3676                           SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT
3677                                 (vec, TREE_VEC_LENGTH (vec));
3678 #endif
3679                           TREE_VEC_ELT (vec, 0) = make_pack_expansion (t);
3680                           
3681                           t  = make_node (NONTYPE_ARGUMENT_PACK);
3682                           SET_ARGUMENT_PACK_ARGS (t, vec);
3683                           TREE_TYPE (t) = type;
3684                         }
3685                     }
3686                   TREE_VEC_ELT (a, i) = t;
3687                 }
3688             }
3689         }
3690
3691 #ifdef ENABLE_CHECKING
3692       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (a, TREE_VEC_LENGTH (a));
3693 #endif
3694
3695       if (length > 1)
3696         TREE_VEC_ELT (args, --l) = a;
3697       else
3698         args = a;
3699     }
3700
3701   return args;
3702 }
3703
3704 /* Update the declared TYPE by doing any lookups which were thought to be
3705    dependent, but are not now that we know the SCOPE of the declarator.  */
3706
3707 tree
3708 maybe_update_decl_type (tree orig_type, tree scope)
3709 {
3710   tree type = orig_type;
3711
3712   if (type == NULL_TREE)
3713     return type;
3714
3715   if (TREE_CODE (orig_type) == TYPE_DECL)
3716     type = TREE_TYPE (type);
3717
3718   if (scope && TYPE_P (scope) && dependent_type_p (scope)
3719       && dependent_type_p (type)
3720       /* Don't bother building up the args in this case.  */
3721       && TREE_CODE (type) != TEMPLATE_TYPE_PARM)
3722     {
3723       /* tsubst in the args corresponding to the template parameters,
3724          including auto if present.  Most things will be unchanged, but
3725          make_typename_type and tsubst_qualified_id will resolve
3726          TYPENAME_TYPEs and SCOPE_REFs that were previously dependent.  */
3727       tree args = current_template_args ();
3728       tree auto_node = type_uses_auto (type);
3729       tree pushed;
3730       if (auto_node)
3731         {
3732           tree auto_vec = make_tree_vec (1);
3733           TREE_VEC_ELT (auto_vec, 0) = auto_node;
3734           args = add_to_template_args (args, auto_vec);
3735         }
3736       pushed = push_scope (scope);
3737       type = tsubst (type, args, tf_warning_or_error, NULL_TREE);
3738       if (pushed)
3739         pop_scope (scope);
3740     }
3741
3742   if (type == error_mark_node)
3743     return orig_type;
3744
3745   if (TREE_CODE (orig_type) == TYPE_DECL)
3746     {
3747       if (same_type_p (type, TREE_TYPE (orig_type)))
3748         type = orig_type;
3749       else
3750         type = TYPE_NAME (type);
3751     }
3752   return type;
3753 }
3754
3755 /* Return a TEMPLATE_DECL corresponding to DECL, using the indicated
3756    template PARMS.  If MEMBER_TEMPLATE_P is true, the new template is
3757    a member template.  Used by push_template_decl below.  */
3758
3759 static tree
3760 build_template_decl (tree decl, tree parms, bool member_template_p)
3761 {
3762   tree tmpl = build_lang_decl (TEMPLATE_DECL, DECL_NAME (decl), NULL_TREE);
3763   DECL_TEMPLATE_PARMS (tmpl) = parms;
3764   DECL_CONTEXT (tmpl) = DECL_CONTEXT (decl);
3765   DECL_MEMBER_TEMPLATE_P (tmpl) = member_template_p;
3766
3767   return tmpl;
3768 }
3769
3770 struct template_parm_data
3771 {
3772   /* The level of the template parameters we are currently
3773      processing.  */
3774   int level;
3775
3776   /* The index of the specialization argument we are currently
3777      processing.  */
3778   int current_arg;
3779
3780   /* An array whose size is the number of template parameters.  The
3781      elements are nonzero if the parameter has been used in any one
3782      of the arguments processed so far.  */
3783   int* parms;
3784
3785   /* An array whose size is the number of template arguments.  The
3786      elements are nonzero if the argument makes use of template
3787      parameters of this level.  */
3788   int* arg_uses_template_parms;
3789 };
3790
3791 /* Subroutine of push_template_decl used to see if each template
3792    parameter in a partial specialization is used in the explicit
3793    argument list.  If T is of the LEVEL given in DATA (which is
3794    treated as a template_parm_data*), then DATA->PARMS is marked
3795    appropriately.  */
3796
3797 static int
3798 mark_template_parm (tree t, void* data)
3799 {
3800   int level;
3801   int idx;
3802   struct template_parm_data* tpd = (struct template_parm_data*) data;
3803
3804   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
3805     {
3806       level = TEMPLATE_PARM_LEVEL (t);
3807       idx = TEMPLATE_PARM_IDX (t);
3808     }
3809   else
3810     {
3811       level = TEMPLATE_TYPE_LEVEL (t);
3812       idx = TEMPLATE_TYPE_IDX (t);
3813     }
3814
3815   if (level == tpd->level)
3816     {
3817       tpd->parms[idx] = 1;
3818       tpd->arg_uses_template_parms[tpd->current_arg] = 1;
3819     }
3820
3821   /* Return zero so that for_each_template_parm will continue the
3822      traversal of the tree; we want to mark *every* template parm.  */
3823   return 0;
3824 }
3825
3826 /* Process the partial specialization DECL.  */
3827
3828 static tree
3829 process_partial_specialization (tree decl)
3830 {
3831   tree type = TREE_TYPE (decl);
3832   tree maintmpl = CLASSTYPE_TI_TEMPLATE (type);
3833   tree specargs = CLASSTYPE_TI_ARGS (type);
3834   tree inner_args = INNERMOST_TEMPLATE_ARGS (specargs);
3835   tree main_inner_parms = DECL_INNERMOST_TEMPLATE_PARMS (maintmpl);
3836   tree inner_parms;
3837   int nargs = TREE_VEC_LENGTH (inner_args);
3838   int ntparms;
3839   int  i;
3840   int did_error_intro = 0;
3841   struct template_parm_data tpd;
3842   struct template_parm_data tpd2;
3843
3844   gcc_assert (current_template_parms);
3845
3846   inner_parms = INNERMOST_TEMPLATE_PARMS (current_template_parms);
3847   ntparms = TREE_VEC_LENGTH (inner_parms);
3848
3849   /* We check that each of the template parameters given in the
3850      partial specialization is used in the argument list to the
3851      specialization.  For example:
3852
3853        template <class T> struct S;
3854        template <class T> struct S<T*>;
3855
3856      The second declaration is OK because `T*' uses the template
3857      parameter T, whereas
3858
3859        template <class T> struct S<int>;
3860
3861      is no good.  Even trickier is:
3862
3863        template <class T>
3864        struct S1
3865        {
3866           template <class U>
3867           struct S2;
3868           template <class U>
3869           struct S2<T>;
3870        };
3871
3872      The S2<T> declaration is actually invalid; it is a
3873      full-specialization.  Of course,
3874
3875           template <class U>
3876           struct S2<T (*)(U)>;
3877
3878      or some such would have been OK.  */
3879   tpd.level = TMPL_PARMS_DEPTH (current_template_parms);
3880   tpd.parms = (int *) alloca (sizeof (int) * ntparms);
3881   memset (tpd.parms, 0, sizeof (int) * ntparms);
3882
3883   tpd.arg_uses_template_parms = (int *) alloca (sizeof (int) * nargs);
3884   memset (tpd.arg_uses_template_parms, 0, sizeof (int) * nargs);
3885   for (i = 0; i < nargs; ++i)
3886     {
3887       tpd.current_arg = i;
3888       for_each_template_parm (TREE_VEC_ELT (inner_args, i),
3889                               &mark_template_parm,
3890                               &tpd,
3891                               NULL,
3892                               /*include_nondeduced_p=*/false);
3893     }
3894   for (i = 0; i < ntparms; ++i)
3895     if (tpd.parms[i] == 0)
3896       {
3897         /* One of the template parms was not used in the
3898            specialization.  */
3899         if (!did_error_intro)
3900           {
3901             error ("template parameters not used in partial specialization:");
3902             did_error_intro = 1;
3903           }
3904
3905         error ("        %qD", TREE_VALUE (TREE_VEC_ELT (inner_parms, i)));
3906       }
3907
3908   /* [temp.class.spec]
3909
3910      The argument list of the specialization shall not be identical to
3911      the implicit argument list of the primary template.  */
3912   if (comp_template_args
3913       (inner_args,
3914        INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE
3915                                                    (maintmpl)))))
3916     error ("partial specialization %qT does not specialize any template arguments", type);
3917
3918   /* [temp.class.spec]
3919
3920      A partially specialized non-type argument expression shall not
3921      involve template parameters of the partial specialization except
3922      when the argument expression is a simple identifier.
3923
3924      The type of a template parameter corresponding to a specialized
3925      non-type argument shall not be dependent on a parameter of the
3926      specialization. 
3927
3928      Also, we verify that pack expansions only occur at the
3929      end of the argument list.  */
3930   gcc_assert (nargs == DECL_NTPARMS (maintmpl));
3931   tpd2.parms = 0;
3932   for (i = 0; i < nargs; ++i)
3933     {
3934       tree parm = TREE_VALUE (TREE_VEC_ELT (main_inner_parms, i));
3935       tree arg = TREE_VEC_ELT (inner_args, i);
3936       tree packed_args = NULL_TREE;
3937       int j, len = 1;
3938
3939       if (ARGUMENT_PACK_P (arg))
3940         {
3941           /* Extract the arguments from the argument pack. We'll be
3942              iterating over these in the following loop.  */
3943           packed_args = ARGUMENT_PACK_ARGS (arg);
3944           len = TREE_VEC_LENGTH (packed_args);
3945         }
3946
3947       for (j = 0; j < len; j++)
3948         {
3949           if (packed_args)
3950             /* Get the Jth argument in the parameter pack.  */
3951             arg = TREE_VEC_ELT (packed_args, j);
3952
3953           if (PACK_EXPANSION_P (arg))
3954             {
3955               /* Pack expansions must come at the end of the
3956                  argument list.  */
3957               if ((packed_args && j < len - 1)
3958                   || (!packed_args && i < nargs - 1))
3959                 {
3960                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3961                     error ("parameter pack argument %qE must be at the "
3962                            "end of the template argument list", arg);
3963                   else
3964                     error ("parameter pack argument %qT must be at the "
3965                            "end of the template argument list", arg);
3966                 }
3967             }
3968
3969           if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
3970             /* We only care about the pattern.  */
3971             arg = PACK_EXPANSION_PATTERN (arg);
3972
3973           if (/* These first two lines are the `non-type' bit.  */
3974               !TYPE_P (arg)
3975               && TREE_CODE (arg) != TEMPLATE_DECL
3976               /* This next line is the `argument expression is not just a
3977                  simple identifier' condition and also the `specialized
3978                  non-type argument' bit.  */
3979               && TREE_CODE (arg) != TEMPLATE_PARM_INDEX)
3980             {
3981               if ((!packed_args && tpd.arg_uses_template_parms[i])
3982                   || (packed_args && uses_template_parms (arg)))
3983                 error ("template argument %qE involves template parameter(s)",
3984                        arg);
3985               else 
3986                 {
3987                   /* Look at the corresponding template parameter,
3988                      marking which template parameters its type depends
3989                      upon.  */
3990                   tree type = TREE_TYPE (parm);
3991
3992                   if (!tpd2.parms)
3993                     {
3994                       /* We haven't yet initialized TPD2.  Do so now.  */
3995                       tpd2.arg_uses_template_parms 
3996                         = (int *) alloca (sizeof (int) * nargs);
3997                       /* The number of parameters here is the number in the
3998                          main template, which, as checked in the assertion
3999                          above, is NARGS.  */
4000                       tpd2.parms = (int *) alloca (sizeof (int) * nargs);
4001                       tpd2.level = 
4002                         TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (maintmpl));
4003                     }
4004
4005                   /* Mark the template parameters.  But this time, we're
4006                      looking for the template parameters of the main
4007                      template, not in the specialization.  */
4008                   tpd2.current_arg = i;
4009                   tpd2.arg_uses_template_parms[i] = 0;
4010                   memset (tpd2.parms, 0, sizeof (int) * nargs);
4011                   for_each_template_parm (type,
4012                                           &mark_template_parm,
4013                                           &tpd2,
4014                                           NULL,
4015                                           /*include_nondeduced_p=*/false);
4016
4017                   if (tpd2.arg_uses_template_parms [i])
4018                     {
4019                       /* The type depended on some template parameters.
4020                          If they are fully specialized in the
4021                          specialization, that's OK.  */
4022                       int j;
4023                       int count = 0;
4024                       for (j = 0; j < nargs; ++j)
4025                         if (tpd2.parms[j] != 0
4026                             && tpd.arg_uses_template_parms [j])
4027                           ++count;
4028                       if (count != 0)
4029                         error_n (input_location, count,
4030                                  "type %qT of template argument %qE depends "
4031                                  "on a template parameter",
4032                                  "type %qT of template argument %qE depends "
4033                                  "on template parameters",
4034                                  type,
4035                                  arg);
4036                     }
4037                 }
4038             }
4039         }
4040     }
4041
4042   /* We should only get here once.  */
4043   gcc_assert (!COMPLETE_TYPE_P (type));
4044
4045   DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)
4046     = tree_cons (specargs, inner_parms,
4047                  DECL_TEMPLATE_SPECIALIZATIONS (maintmpl));
4048   TREE_TYPE (DECL_TEMPLATE_SPECIALIZATIONS (maintmpl)) = type;
4049   return decl;
4050 }
4051
4052 /* Check that a template declaration's use of default arguments and
4053    parameter packs is not invalid.  Here, PARMS are the template
4054    parameters.  IS_PRIMARY is nonzero if DECL is the thing declared by
4055    a primary template.  IS_PARTIAL is nonzero if DECL is a partial
4056    specialization.
4057    
4058
4059    IS_FRIEND_DECL is nonzero if DECL is a friend function template
4060    declaration (but not a definition); 1 indicates a declaration, 2
4061    indicates a redeclaration. When IS_FRIEND_DECL=2, no errors are
4062    emitted for extraneous default arguments.
4063
4064    Returns TRUE if there were no errors found, FALSE otherwise. */
4065
4066 bool
4067 check_default_tmpl_args (tree decl, tree parms, int is_primary, 
4068                          int is_partial, int is_friend_decl)
4069 {
4070   const char *msg;
4071   int last_level_to_check;
4072   tree parm_level;
4073   bool no_errors = true;
4074
4075   /* [temp.param]
4076
4077      A default template-argument shall not be specified in a
4078      function template declaration or a function template definition, nor
4079      in the template-parameter-list of the definition of a member of a
4080      class template.  */
4081
4082   if (TREE_CODE (CP_DECL_CONTEXT (decl)) == FUNCTION_DECL)
4083     /* You can't have a function template declaration in a local
4084        scope, nor you can you define a member of a class template in a
4085        local scope.  */
4086     return true;
4087
4088   if (current_class_type
4089       && !TYPE_BEING_DEFINED (current_class_type)
4090       && DECL_LANG_SPECIFIC (decl)
4091       && DECL_DECLARES_FUNCTION_P (decl)
4092       /* If this is either a friend defined in the scope of the class
4093          or a member function.  */
4094       && (DECL_FUNCTION_MEMBER_P (decl)
4095           ? same_type_p (DECL_CONTEXT (decl), current_class_type)
4096           : DECL_FRIEND_CONTEXT (decl)
4097           ? same_type_p (DECL_FRIEND_CONTEXT (decl), current_class_type)
4098           : false)
4099       /* And, if it was a member function, it really was defined in
4100          the scope of the class.  */
4101       && (!DECL_FUNCTION_MEMBER_P (decl)
4102           || DECL_INITIALIZED_IN_CLASS_P (decl)))
4103     /* We already checked these parameters when the template was
4104        declared, so there's no need to do it again now.  This function
4105        was defined in class scope, but we're processing it's body now
4106        that the class is complete.  */
4107     return true;
4108
4109   /* Core issue 226 (C++0x only): the following only applies to class
4110      templates.  */
4111   if ((cxx_dialect == cxx98) || TREE_CODE (decl) != FUNCTION_DECL)
4112     {
4113       /* [temp.param]
4114
4115          If a template-parameter has a default template-argument, all
4116          subsequent template-parameters shall have a default
4117          template-argument supplied.  */
4118       for (parm_level = parms; parm_level; parm_level = TREE_CHAIN (parm_level))
4119         {
4120           tree inner_parms = TREE_VALUE (parm_level);
4121           int ntparms = TREE_VEC_LENGTH (inner_parms);
4122           int seen_def_arg_p = 0;
4123           int i;
4124
4125           for (i = 0; i < ntparms; ++i)
4126             {
4127               tree parm = TREE_VEC_ELT (inner_parms, i);
4128
4129               if (parm == error_mark_node)
4130                 continue;
4131
4132               if (TREE_PURPOSE (parm))
4133                 seen_def_arg_p = 1;
4134               else if (seen_def_arg_p
4135                        && !template_parameter_pack_p (TREE_VALUE (parm)))
4136                 {
4137                   error ("no default argument for %qD", TREE_VALUE (parm));
4138                   /* For better subsequent error-recovery, we indicate that
4139                      there should have been a default argument.  */
4140                   TREE_PURPOSE (parm) = error_mark_node;
4141                   no_errors = false;
4142                 }
4143               else if (is_primary
4144                        && !is_partial
4145                        && !is_friend_decl
4146                        /* Don't complain about an enclosing partial
4147                           specialization.  */
4148                        && parm_level == parms
4149                        && TREE_CODE (decl) == TYPE_DECL
4150                        && i < ntparms - 1
4151                        && template_parameter_pack_p (TREE_VALUE (parm)))
4152                 {
4153                   /* A primary class template can only have one
4154                      parameter pack, at the end of the template
4155                      parameter list.  */
4156
4157                   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL)
4158                     error ("parameter pack %qE must be at the end of the"
4159                            " template parameter list", TREE_VALUE (parm));
4160                   else
4161                     error ("parameter pack %qT must be at the end of the"
4162                            " template parameter list", 
4163                            TREE_TYPE (TREE_VALUE (parm)));
4164
4165                   TREE_VALUE (TREE_VEC_ELT (inner_parms, i)) 
4166                     = error_mark_node;
4167                   no_errors = false;
4168                 }
4169             }
4170         }
4171     }
4172
4173   if (((cxx_dialect == cxx98) && TREE_CODE (decl) != TYPE_DECL)
4174       || is_partial 
4175       || !is_primary
4176       || is_friend_decl)
4177     /* For an ordinary class template, default template arguments are
4178        allowed at the innermost level, e.g.:
4179          template <class T = int>
4180          struct S {};
4181        but, in a partial specialization, they're not allowed even
4182        there, as we have in [temp.class.spec]:
4183
4184          The template parameter list of a specialization shall not
4185          contain default template argument values.
4186
4187        So, for a partial specialization, or for a function template
4188        (in C++98/C++03), we look at all of them.  */
4189     ;
4190   else
4191     /* But, for a primary class template that is not a partial
4192        specialization we look at all template parameters except the
4193        innermost ones.  */
4194     parms = TREE_CHAIN (parms);
4195
4196   /* Figure out what error message to issue.  */
4197   if (is_friend_decl == 2)
4198     msg = G_("default template arguments may not be used in function template "
4199              "friend re-declaration");
4200   else if (is_friend_decl)
4201     msg = G_("default template arguments may not be used in function template "
4202              "friend declarations");
4203   else if (TREE_CODE (decl) == FUNCTION_DECL && (cxx_dialect == cxx98))
4204     msg = G_("default template arguments may not be used in function templates "
4205              "without -std=c++0x or -std=gnu++0x");
4206   else if (is_partial)
4207     msg = G_("default template arguments may not be used in "
4208              "partial specializations");
4209   else
4210     msg = G_("default argument for template parameter for class enclosing %qD");
4211
4212   if (current_class_type && TYPE_BEING_DEFINED (current_class_type))
4213     /* If we're inside a class definition, there's no need to
4214        examine the parameters to the class itself.  On the one
4215        hand, they will be checked when the class is defined, and,
4216        on the other, default arguments are valid in things like:
4217          template <class T = double>
4218          struct S { template <class U> void f(U); };
4219        Here the default argument for `S' has no bearing on the
4220        declaration of `f'.  */
4221     last_level_to_check = template_class_depth (current_class_type) + 1;
4222   else
4223     /* Check everything.  */
4224     last_level_to_check = 0;
4225
4226   for (parm_level = parms;
4227        parm_level && TMPL_PARMS_DEPTH (parm_level) >= last_level_to_check;
4228        parm_level = TREE_CHAIN (parm_level))
4229     {
4230       tree inner_parms = TREE_VALUE (parm_level);
4231       int i;
4232       int ntparms;
4233
4234       ntparms = TREE_VEC_LENGTH (inner_parms);
4235       for (i = 0; i < ntparms; ++i)
4236         {
4237           if (TREE_VEC_ELT (inner_parms, i) == error_mark_node)
4238             continue;
4239
4240           if (TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)))
4241             {
4242               if (msg)
4243                 {
4244                   no_errors = false;
4245                   if (is_friend_decl == 2)
4246                     return no_errors;
4247
4248                   error (msg, decl);
4249                   msg = 0;
4250                 }
4251
4252               /* Clear out the default argument so that we are not
4253                  confused later.  */
4254               TREE_PURPOSE (TREE_VEC_ELT (inner_parms, i)) = NULL_TREE;
4255             }
4256         }
4257
4258       /* At this point, if we're still interested in issuing messages,
4259          they must apply to classes surrounding the object declared.  */
4260       if (msg)
4261         msg = G_("default argument for template parameter for class "
4262                  "enclosing %qD");
4263     }
4264
4265   return no_errors;
4266 }
4267
4268 /* Worker for push_template_decl_real, called via
4269    for_each_template_parm.  DATA is really an int, indicating the
4270    level of the parameters we are interested in.  If T is a template
4271    parameter of that level, return nonzero.  */
4272
4273 static int
4274 template_parm_this_level_p (tree t, void* data)
4275 {
4276   int this_level = *(int *)data;
4277   int level;
4278
4279   if (TREE_CODE (t) == TEMPLATE_PARM_INDEX)
4280     level = TEMPLATE_PARM_LEVEL (t);
4281   else
4282     level = TEMPLATE_TYPE_LEVEL (t);
4283   return level == this_level;
4284 }
4285
4286 /* Creates a TEMPLATE_DECL for the indicated DECL using the template
4287    parameters given by current_template_args, or reuses a
4288    previously existing one, if appropriate.  Returns the DECL, or an
4289    equivalent one, if it is replaced via a call to duplicate_decls.
4290
4291    If IS_FRIEND is true, DECL is a friend declaration.  */
4292
4293 tree
4294 push_template_decl_real (tree decl, bool is_friend)
4295 {
4296   tree tmpl;
4297   tree args;
4298   tree info;
4299   tree ctx;
4300   int primary;
4301   int is_partial;
4302   int new_template_p = 0;
4303   /* True if the template is a member template, in the sense of
4304      [temp.mem].  */
4305   bool member_template_p = false;
4306
4307   if (decl == error_mark_node || !current_template_parms)
4308     return error_mark_node;
4309
4310   /* See if this is a partial specialization.  */
4311   is_partial = (DECL_IMPLICIT_TYPEDEF_P (decl)
4312                 && TREE_CODE (TREE_TYPE (decl)) != ENUMERAL_TYPE
4313                 && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)));
4314
4315   if (TREE_CODE (decl) == FUNCTION_DECL && DECL_FRIEND_P (decl))
4316     is_friend = true;
4317
4318   if (is_friend)
4319     /* For a friend, we want the context of the friend function, not
4320        the type of which it is a friend.  */
4321     ctx = DECL_CONTEXT (decl);
4322   else if (CP_DECL_CONTEXT (decl)
4323            && TREE_CODE (CP_DECL_CONTEXT (decl)) != NAMESPACE_DECL)
4324     /* In the case of a virtual function, we want the class in which
4325        it is defined.  */
4326     ctx = CP_DECL_CONTEXT (decl);
4327   else
4328     /* Otherwise, if we're currently defining some class, the DECL
4329        is assumed to be a member of the class.  */
4330     ctx = current_scope ();
4331
4332   if (ctx && TREE_CODE (ctx) == NAMESPACE_DECL)
4333     ctx = NULL_TREE;
4334
4335   if (!DECL_CONTEXT (decl))
4336     DECL_CONTEXT (decl) = FROB_CONTEXT (current_namespace);
4337
4338   /* See if this is a primary template.  */
4339   if (is_friend && ctx)
4340     /* A friend template that specifies a class context, i.e.
4341          template <typename T> friend void A<T>::f();
4342        is not primary.  */
4343     primary = 0;
4344   else
4345     primary = template_parm_scope_p ();
4346
4347   if (primary)
4348     {
4349       if (DECL_CLASS_SCOPE_P (decl))
4350         member_template_p = true;
4351       if (TREE_CODE (decl) == TYPE_DECL
4352           && ANON_AGGRNAME_P (DECL_NAME (decl)))
4353         {
4354           error ("template class without a name");
4355           return error_mark_node;
4356         }
4357       else if (TREE_CODE (decl) == FUNCTION_DECL)
4358         {
4359           if (DECL_DESTRUCTOR_P (decl))
4360             {
4361               /* [temp.mem]
4362
4363                  A destructor shall not be a member template.  */
4364               error ("destructor %qD declared as member template", decl);
4365               return error_mark_node;
4366             }
4367           if (NEW_DELETE_OPNAME_P (DECL_NAME (decl))
4368               && (!TYPE_ARG_TYPES (TREE_TYPE (decl))
4369                   || TYPE_ARG_TYPES (TREE_TYPE (decl)) == void_list_node
4370                   || !TREE_CHAIN (TYPE_ARG_TYPES (TREE_TYPE (decl)))
4371                   || (TREE_CHAIN (TYPE_ARG_TYPES ((TREE_TYPE (decl))))
4372                       == void_list_node)))
4373             {
4374               /* [basic.stc.dynamic.allocation]
4375
4376                  An allocation function can be a function
4377                  template. ... Template allocation functions shall
4378                  have two or more parameters.  */
4379               error ("invalid template declaration of %qD", decl);
4380               return error_mark_node;
4381             }
4382         }
4383       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4384                && CLASS_TYPE_P (TREE_TYPE (decl)))
4385         /* OK */;
4386       else
4387         {
4388           error ("template declaration of %q#D", decl);
4389           return error_mark_node;
4390         }
4391     }
4392
4393   /* Check to see that the rules regarding the use of default
4394      arguments are not being violated.  */
4395   check_default_tmpl_args (decl, current_template_parms,
4396                            primary, is_partial, /*is_friend_decl=*/0);
4397
4398   /* Ensure that there are no parameter packs in the type of this
4399      declaration that have not been expanded.  */
4400   if (TREE_CODE (decl) == FUNCTION_DECL)
4401     {
4402       /* Check each of the arguments individually to see if there are
4403          any bare parameter packs.  */
4404       tree type = TREE_TYPE (decl);
4405       tree arg = DECL_ARGUMENTS (decl);
4406       tree argtype = TYPE_ARG_TYPES (type);
4407
4408       while (arg && argtype)
4409         {
4410           if (!FUNCTION_PARAMETER_PACK_P (arg)
4411               && check_for_bare_parameter_packs (TREE_TYPE (arg)))
4412             {
4413             /* This is a PARM_DECL that contains unexpanded parameter
4414                packs. We have already complained about this in the
4415                check_for_bare_parameter_packs call, so just replace
4416                these types with ERROR_MARK_NODE.  */
4417               TREE_TYPE (arg) = error_mark_node;
4418               TREE_VALUE (argtype) = error_mark_node;
4419             }
4420
4421           arg = TREE_CHAIN (arg);
4422           argtype = TREE_CHAIN (argtype);
4423         }
4424
4425       /* Check for bare parameter packs in the return type and the
4426          exception specifiers.  */
4427       if (check_for_bare_parameter_packs (TREE_TYPE (type)))
4428         /* Errors were already issued, set return type to int
4429            as the frontend doesn't expect error_mark_node as
4430            the return type.  */
4431         TREE_TYPE (type) = integer_type_node;
4432       if (check_for_bare_parameter_packs (TYPE_RAISES_EXCEPTIONS (type)))
4433         TYPE_RAISES_EXCEPTIONS (type) = NULL_TREE;
4434     }
4435   else if (check_for_bare_parameter_packs (TREE_TYPE (decl)))
4436     {
4437       TREE_TYPE (decl) = error_mark_node;
4438       return error_mark_node;
4439     }
4440
4441   if (is_partial)
4442     return process_partial_specialization (decl);
4443
4444   args = current_template_args ();
4445
4446   if (!ctx
4447       || TREE_CODE (ctx) == FUNCTION_DECL
4448       || (CLASS_TYPE_P (ctx) && TYPE_BEING_DEFINED (ctx))
4449       || (is_friend && !DECL_TEMPLATE_INFO (decl)))
4450     {
4451       if (DECL_LANG_SPECIFIC (decl)
4452           && DECL_TEMPLATE_INFO (decl)
4453           && DECL_TI_TEMPLATE (decl))
4454         tmpl = DECL_TI_TEMPLATE (decl);
4455       /* If DECL is a TYPE_DECL for a class-template, then there won't
4456          be DECL_LANG_SPECIFIC.  The information equivalent to
4457          DECL_TEMPLATE_INFO is found in TYPE_TEMPLATE_INFO instead.  */
4458       else if (DECL_IMPLICIT_TYPEDEF_P (decl)
4459                && TYPE_TEMPLATE_INFO (TREE_TYPE (decl))
4460                && TYPE_TI_TEMPLATE (TREE_TYPE (decl)))
4461         {
4462           /* Since a template declaration already existed for this
4463              class-type, we must be redeclaring it here.  Make sure
4464              that the redeclaration is valid.  */
4465           redeclare_class_template (TREE_TYPE (decl),
4466                                     current_template_parms);
4467           /* We don't need to create a new TEMPLATE_DECL; just use the
4468              one we already had.  */
4469           tmpl = TYPE_TI_TEMPLATE (TREE_TYPE (decl));
4470         }
4471       else
4472         {
4473           tmpl = build_template_decl (decl, current_template_parms,
4474                                       member_template_p);
4475           new_template_p = 1;
4476
4477           if (DECL_LANG_SPECIFIC (decl)
4478               && DECL_TEMPLATE_SPECIALIZATION (decl))
4479             {
4480               /* A specialization of a member template of a template
4481                  class.  */
4482               SET_DECL_TEMPLATE_SPECIALIZATION (tmpl);
4483               DECL_TEMPLATE_INFO (tmpl) = DECL_TEMPLATE_INFO (decl);
4484               DECL_TEMPLATE_INFO (decl) = NULL_TREE;
4485             }
4486         }
4487     }
4488   else
4489     {
4490       tree a, t, current, parms;
4491       int i;
4492       tree tinfo = get_template_info (decl);
4493
4494       if (!tinfo)
4495         {
4496           error ("template definition of non-template %q#D", decl);
4497           return error_mark_node;
4498         }
4499
4500       tmpl = TI_TEMPLATE (tinfo);
4501
4502       if (DECL_FUNCTION_TEMPLATE_P (tmpl)
4503           && DECL_TEMPLATE_INFO (decl) && DECL_TI_ARGS (decl)
4504           && DECL_TEMPLATE_SPECIALIZATION (decl)
4505           && DECL_MEMBER_TEMPLATE_P (tmpl))
4506         {
4507           tree new_tmpl;
4508
4509           /* The declaration is a specialization of a member
4510              template, declared outside the class.  Therefore, the
4511              innermost template arguments will be NULL, so we
4512              replace them with the arguments determined by the
4513              earlier call to check_explicit_specialization.  */
4514           args = DECL_TI_ARGS (decl);
4515
4516           new_tmpl
4517             = build_template_decl (decl, current_template_parms,
4518                                    member_template_p);
4519           DECL_TEMPLATE_RESULT (new_tmpl) = decl;
4520           TREE_TYPE (new_tmpl) = TREE_TYPE (decl);
4521           DECL_TI_TEMPLATE (decl) = new_tmpl;
4522           SET_DECL_TEMPLATE_SPECIALIZATION (new_tmpl);
4523           DECL_TEMPLATE_INFO (new_tmpl)
4524             = build_template_info (tmpl, args);
4525
4526           register_specialization (new_tmpl,
4527                                    most_general_template (tmpl),
4528                                    args,
4529                                    is_friend, 0);
4530           return decl;
4531         }
4532
4533       /* Make sure the template headers we got make sense.  */
4534
4535       parms = DECL_TEMPLATE_PARMS (tmpl);
4536       i = TMPL_PARMS_DEPTH (parms);
4537       if (TMPL_ARGS_DEPTH (args) != i)
4538         {
4539           error ("expected %d levels of template parms for %q#D, got %d",
4540                  i, decl, TMPL_ARGS_DEPTH (args));
4541         }
4542       else
4543         for (current = decl; i > 0; --i, parms = TREE_CHAIN (parms))
4544           {
4545             a = TMPL_ARGS_LEVEL (args, i);
4546             t = INNERMOST_TEMPLATE_PARMS (parms);
4547
4548             if (TREE_VEC_LENGTH (t) != TREE_VEC_LENGTH (a))
4549               {
4550                 if (current == decl)
4551                   error ("got %d template parameters for %q#D",
4552                          TREE_VEC_LENGTH (a), decl);
4553                 else
4554                   error ("got %d template parameters for %q#T",
4555                          TREE_VEC_LENGTH (a), current);
4556                 error ("  but %d required", TREE_VEC_LENGTH (t));
4557                 return error_mark_node;
4558               }
4559
4560             if (current == decl)
4561               current = ctx;
4562             else if (current == NULL_TREE)
4563               /* Can happen in erroneous input.  */
4564               break;
4565             else
4566               current = (TYPE_P (current)
4567                          ? TYPE_CONTEXT (current)
4568                          : DECL_CONTEXT (current));
4569           }
4570
4571       /* Check that the parms are used in the appropriate qualifying scopes
4572          in the declarator.  */
4573       if (!comp_template_args
4574           (TI_ARGS (tinfo),
4575            TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (tmpl)))))
4576         {
4577           error ("\
4578 template arguments to %qD do not match original template %qD",
4579                  decl, DECL_TEMPLATE_RESULT (tmpl));
4580           if (!uses_template_parms (TI_ARGS (tinfo)))
4581             inform (input_location, "use template<> for an explicit specialization");
4582           /* Avoid crash in import_export_decl.  */
4583           DECL_INTERFACE_KNOWN (decl) = 1;
4584           return error_mark_node;
4585         }
4586     }
4587
4588   DECL_TEMPLATE_RESULT (tmpl) = decl;
4589   TREE_TYPE (tmpl) = TREE_TYPE (decl);
4590
4591   /* Push template declarations for global functions and types.  Note
4592      that we do not try to push a global template friend declared in a
4593      template class; such a thing may well depend on the template
4594      parameters of the class.  */
4595   if (new_template_p && !ctx
4596       && !(is_friend && template_class_depth (current_class_type) > 0))
4597     {
4598       tmpl = pushdecl_namespace_level (tmpl, is_friend);
4599       if (tmpl == error_mark_node)
4600         return error_mark_node;
4601
4602       /* Hide template friend classes that haven't been declared yet.  */
4603       if (is_friend && TREE_CODE (decl) == TYPE_DECL)
4604         {
4605           DECL_ANTICIPATED (tmpl) = 1;
4606           DECL_FRIEND_P (tmpl) = 1;
4607         }
4608     }
4609
4610   if (primary)
4611     {
4612       tree parms = DECL_TEMPLATE_PARMS (tmpl);
4613       int i;
4614
4615       DECL_PRIMARY_TEMPLATE (tmpl) = tmpl;
4616       if (DECL_CONV_FN_P (tmpl))
4617         {
4618           int depth = TMPL_PARMS_DEPTH (parms);
4619
4620           /* It is a conversion operator. See if the type converted to
4621              depends on innermost template operands.  */
4622
4623           if (uses_template_parms_level (TREE_TYPE (TREE_TYPE (tmpl)),
4624                                          depth))
4625             DECL_TEMPLATE_CONV_FN_P (tmpl) = 1;
4626         }
4627
4628       /* Give template template parms a DECL_CONTEXT of the template
4629          for which they are a parameter.  */
4630       parms = INNERMOST_TEMPLATE_PARMS (parms);
4631       for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
4632         {
4633           tree parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4634           if (TREE_CODE (parm) == TEMPLATE_DECL)
4635             DECL_CONTEXT (parm) = tmpl;
4636         }
4637     }
4638
4639   /* The DECL_TI_ARGS of DECL contains full set of arguments referring
4640      back to its most general template.  If TMPL is a specialization,
4641      ARGS may only have the innermost set of arguments.  Add the missing
4642      argument levels if necessary.  */
4643   if (DECL_TEMPLATE_INFO (tmpl))
4644     args = add_outermost_template_args (DECL_TI_ARGS (tmpl), args);
4645
4646   info = build_template_info (tmpl, args);
4647
4648   if (DECL_IMPLICIT_TYPEDEF_P (decl))
4649     SET_TYPE_TEMPLATE_INFO (TREE_TYPE (tmpl), info);
4650   else if (DECL_LANG_SPECIFIC (decl))
4651     DECL_TEMPLATE_INFO (decl) = info;
4652
4653   return DECL_TEMPLATE_RESULT (tmpl);
4654 }
4655
4656 tree
4657 push_template_decl (tree decl)
4658 {
4659   return push_template_decl_real (decl, false);
4660 }
4661
4662 /* Called when a class template TYPE is redeclared with the indicated
4663    template PARMS, e.g.:
4664
4665      template <class T> struct S;
4666      template <class T> struct S {};  */
4667
4668 bool
4669 redeclare_class_template (tree type, tree parms)
4670 {
4671   tree tmpl;
4672   tree tmpl_parms;
4673   int i;
4674
4675   if (!TYPE_TEMPLATE_INFO (type))
4676     {
4677       error ("%qT is not a template type", type);
4678       return false;
4679     }
4680
4681   tmpl = TYPE_TI_TEMPLATE (type);
4682   if (!PRIMARY_TEMPLATE_P (tmpl))
4683     /* The type is nested in some template class.  Nothing to worry
4684        about here; there are no new template parameters for the nested
4685        type.  */
4686     return true;
4687
4688   if (!parms)
4689     {
4690       error ("template specifiers not specified in declaration of %qD",
4691              tmpl);
4692       return false;
4693     }
4694
4695   parms = INNERMOST_TEMPLATE_PARMS (parms);
4696   tmpl_parms = DECL_INNERMOST_TEMPLATE_PARMS (tmpl);
4697
4698   if (TREE_VEC_LENGTH (parms) != TREE_VEC_LENGTH (tmpl_parms))
4699     {
4700       error_n (input_location, TREE_VEC_LENGTH (parms),
4701                "redeclared with %d template parameter",
4702                "redeclared with %d template parameters",
4703                TREE_VEC_LENGTH (parms));
4704       inform_n (input_location, TREE_VEC_LENGTH (tmpl_parms),
4705                 "previous declaration %q+D used %d template parameter",
4706                 "previous declaration %q+D used %d template parameters",
4707                 tmpl, TREE_VEC_LENGTH (tmpl_parms));
4708       return false;
4709     }
4710
4711   for (i = 0; i < TREE_VEC_LENGTH (tmpl_parms); ++i)
4712     {
4713       tree tmpl_parm;
4714       tree parm;
4715       tree tmpl_default;
4716       tree parm_default;
4717
4718       if (TREE_VEC_ELT (tmpl_parms, i) == error_mark_node
4719           || TREE_VEC_ELT (parms, i) == error_mark_node)
4720         continue;
4721
4722       tmpl_parm = TREE_VALUE (TREE_VEC_ELT (tmpl_parms, i));
4723       if (tmpl_parm == error_mark_node)
4724         return false;
4725
4726       parm = TREE_VALUE (TREE_VEC_ELT (parms, i));
4727       tmpl_default = TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i));
4728       parm_default = TREE_PURPOSE (TREE_VEC_ELT (parms, i));
4729
4730       /* TMPL_PARM and PARM can be either TYPE_DECL, PARM_DECL, or
4731          TEMPLATE_DECL.  */
4732       if (TREE_CODE (tmpl_parm) != TREE_CODE (parm)
4733           || (TREE_CODE (tmpl_parm) != TYPE_DECL
4734               && !same_type_p (TREE_TYPE (tmpl_parm), TREE_TYPE (parm)))
4735           || (TREE_CODE (tmpl_parm) != PARM_DECL
4736               && (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (tmpl_parm))
4737                   != TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm))))
4738           || (TREE_CODE (tmpl_parm) == PARM_DECL
4739               && (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (tmpl_parm))
4740                   != TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))))
4741         {
4742           error ("template parameter %q+#D", tmpl_parm);
4743           error ("redeclared here as %q#D", parm);
4744           return false;
4745         }
4746
4747       if (tmpl_default != NULL_TREE && parm_default != NULL_TREE)
4748         {
4749           /* We have in [temp.param]:
4750
4751              A template-parameter may not be given default arguments
4752              by two different declarations in the same scope.  */
4753           error_at (input_location, "redefinition of default argument for %q#D", parm);
4754           inform (DECL_SOURCE_LOCATION (tmpl_parm),
4755                   "original definition appeared here");
4756           return false;
4757         }
4758
4759       if (parm_default != NULL_TREE)
4760         /* Update the previous template parameters (which are the ones
4761            that will really count) with the new default value.  */
4762         TREE_PURPOSE (TREE_VEC_ELT (tmpl_parms, i)) = parm_default;
4763       else if (tmpl_default != NULL_TREE)
4764         /* Update the new parameters, too; they'll be used as the
4765            parameters for any members.  */
4766         TREE_PURPOSE (TREE_VEC_ELT (parms, i)) = tmpl_default;
4767     }
4768
4769     return true;
4770 }
4771
4772 /* Simplify EXPR if it is a non-dependent expression.  Returns the
4773    (possibly simplified) expression.  */
4774
4775 tree
4776 fold_non_dependent_expr (tree expr)
4777 {
4778   if (expr == NULL_TREE)
4779     return NULL_TREE;
4780
4781   /* If we're in a template, but EXPR isn't value dependent, simplify
4782      it.  We're supposed to treat:
4783
4784        template <typename T> void f(T[1 + 1]);
4785        template <typename T> void f(T[2]);
4786
4787      as two declarations of the same function, for example.  */
4788   if (processing_template_decl
4789       && !type_dependent_expression_p (expr)
4790       && !value_dependent_expression_p (expr))
4791     {
4792       HOST_WIDE_INT saved_processing_template_decl;
4793
4794       saved_processing_template_decl = processing_template_decl;
4795       processing_template_decl = 0;
4796       expr = tsubst_copy_and_build (expr,
4797                                     /*args=*/NULL_TREE,
4798                                     tf_error,
4799                                     /*in_decl=*/NULL_TREE,
4800                                     /*function_p=*/false,
4801                                     /*integral_constant_expression_p=*/true);
4802       processing_template_decl = saved_processing_template_decl;
4803     }
4804   return expr;
4805 }
4806
4807 /* EXPR is an expression which is used in a constant-expression context.
4808    For instance, it could be a VAR_DECL with a constant initializer.
4809    Extract the innermost constant expression.
4810
4811    This is basically a more powerful version of
4812    integral_constant_value, which can be used also in templates where
4813    initializers can maintain a syntactic rather than semantic form
4814    (even if they are non-dependent, for access-checking purposes).  */
4815
4816 static tree
4817 fold_decl_constant_value (tree expr)
4818 {
4819   tree const_expr = expr;
4820   do
4821     {
4822       expr = fold_non_dependent_expr (const_expr);
4823       const_expr = integral_constant_value (expr);
4824     }
4825   while (expr != const_expr);
4826
4827   return expr;
4828 }
4829
4830 /* Subroutine of convert_nontype_argument. Converts EXPR to TYPE, which
4831    must be a function or a pointer-to-function type, as specified
4832    in [temp.arg.nontype]: disambiguate EXPR if it is an overload set,
4833    and check that the resulting function has external linkage.  */
4834
4835 static tree
4836 convert_nontype_argument_function (tree type, tree expr)
4837 {
4838   tree fns = expr;
4839   tree fn, fn_no_ptr;
4840
4841   fn = instantiate_type (type, fns, tf_none);
4842   if (fn == error_mark_node)
4843     return error_mark_node;
4844
4845   fn_no_ptr = fn;
4846   if (TREE_CODE (fn_no_ptr) == ADDR_EXPR)
4847     fn_no_ptr = TREE_OPERAND (fn_no_ptr, 0);
4848   if (TREE_CODE (fn_no_ptr) == BASELINK)
4849     fn_no_ptr = BASELINK_FUNCTIONS (fn_no_ptr);
4850  
4851   /* [temp.arg.nontype]/1
4852
4853      A template-argument for a non-type, non-template template-parameter
4854      shall be one of:
4855      [...]
4856      -- the address of an object or function with external linkage.  */
4857   if (!DECL_EXTERNAL_LINKAGE_P (fn_no_ptr))
4858     {
4859       error ("%qE is not a valid template argument for type %qT "
4860              "because function %qD has not external linkage",
4861              expr, type, fn_no_ptr);
4862       return NULL_TREE;
4863     }
4864
4865   return fn;
4866 }
4867
4868 /* Subroutine of convert_nontype_argument.
4869    Check if EXPR of type TYPE is a valid pointer-to-member constant.
4870    Emit an error otherwise.  */
4871
4872 static bool
4873 check_valid_ptrmem_cst_expr (tree type, tree expr)
4874 {
4875   STRIP_NOPS (expr);
4876   if (expr && (null_ptr_cst_p (expr) || TREE_CODE (expr) == PTRMEM_CST))
4877     return true;
4878   error ("%qE is not a valid template argument for type %qT",
4879          expr, type);
4880   error ("it must be a pointer-to-member of the form `&X::Y'");
4881   return false;
4882 }
4883
4884 /* Attempt to convert the non-type template parameter EXPR to the
4885    indicated TYPE.  If the conversion is successful, return the
4886    converted value.  If the conversion is unsuccessful, return
4887    NULL_TREE if we issued an error message, or error_mark_node if we
4888    did not.  We issue error messages for out-and-out bad template
4889    parameters, but not simply because the conversion failed, since we
4890    might be just trying to do argument deduction.  Both TYPE and EXPR
4891    must be non-dependent.
4892
4893    The conversion follows the special rules described in
4894    [temp.arg.nontype], and it is much more strict than an implicit
4895    conversion.
4896
4897    This function is called twice for each template argument (see
4898    lookup_template_class for a more accurate description of this
4899    problem). This means that we need to handle expressions which
4900    are not valid in a C++ source, but can be created from the
4901    first call (for instance, casts to perform conversions). These
4902    hacks can go away after we fix the double coercion problem.  */
4903
4904 static tree
4905 convert_nontype_argument (tree type, tree expr)
4906 {
4907   tree expr_type;
4908
4909   /* Detect immediately string literals as invalid non-type argument.
4910      This special-case is not needed for correctness (we would easily
4911      catch this later), but only to provide better diagnostic for this
4912      common user mistake. As suggested by DR 100, we do not mention
4913      linkage issues in the diagnostic as this is not the point.  */
4914   if (TREE_CODE (expr) == STRING_CST)
4915     {
4916       error ("%qE is not a valid template argument for type %qT "
4917              "because string literals can never be used in this context",
4918              expr, type);
4919       return NULL_TREE;
4920     }
4921
4922   /* If we are in a template, EXPR may be non-dependent, but still
4923      have a syntactic, rather than semantic, form.  For example, EXPR
4924      might be a SCOPE_REF, rather than the VAR_DECL to which the
4925      SCOPE_REF refers.  Preserving the qualifying scope is necessary
4926      so that access checking can be performed when the template is
4927      instantiated -- but here we need the resolved form so that we can
4928      convert the argument.  */
4929   expr = fold_non_dependent_expr (expr);
4930   if (error_operand_p (expr))
4931     return error_mark_node;
4932   expr_type = TREE_TYPE (expr);
4933   expr = mark_rvalue_use (expr);
4934
4935   /* HACK: Due to double coercion, we can get a
4936      NOP_EXPR<REFERENCE_TYPE>(ADDR_EXPR<POINTER_TYPE> (arg)) here,
4937      which is the tree that we built on the first call (see
4938      below when coercing to reference to object or to reference to
4939      function). We just strip everything and get to the arg.
4940      See g++.old-deja/g++.oliva/template4.C and g++.dg/template/nontype9.C
4941      for examples.  */
4942   if (TREE_CODE (expr) == NOP_EXPR)
4943     {
4944       if (TYPE_REF_OBJ_P (type) || TYPE_REFFN_P (type))
4945         {
4946           /* ??? Maybe we could use convert_from_reference here, but we
4947              would need to relax its constraints because the NOP_EXPR
4948              could actually change the type to something more cv-qualified,
4949              and this is not folded by convert_from_reference.  */
4950           tree addr = TREE_OPERAND (expr, 0);
4951           gcc_assert (TREE_CODE (expr_type) == REFERENCE_TYPE);
4952           gcc_assert (TREE_CODE (addr) == ADDR_EXPR);
4953           gcc_assert (TREE_CODE (TREE_TYPE (addr)) == POINTER_TYPE);
4954           gcc_assert (same_type_ignoring_top_level_qualifiers_p
4955                       (TREE_TYPE (expr_type),
4956                        TREE_TYPE (TREE_TYPE (addr))));
4957
4958           expr = TREE_OPERAND (addr, 0);
4959           expr_type = TREE_TYPE (expr);
4960         }
4961
4962       /* We could also generate a NOP_EXPR(ADDR_EXPR()) when the
4963          parameter is a pointer to object, through decay and
4964          qualification conversion. Let's strip everything.  */
4965       else if (TYPE_PTROBV_P (type))
4966         {
4967           STRIP_NOPS (expr);
4968           gcc_assert (TREE_CODE (expr) == ADDR_EXPR);
4969           gcc_assert (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE);
4970           /* Skip the ADDR_EXPR only if it is part of the decay for
4971              an array. Otherwise, it is part of the original argument
4972              in the source code.  */
4973           if (TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0))) == ARRAY_TYPE)
4974             expr = TREE_OPERAND (expr, 0);
4975           expr_type = TREE_TYPE (expr);
4976         }
4977     }
4978
4979   /* [temp.arg.nontype]/5, bullet 1
4980
4981      For a non-type template-parameter of integral or enumeration type,
4982      integral promotions (_conv.prom_) and integral conversions
4983      (_conv.integral_) are applied.  */
4984   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
4985     {
4986       if (!INTEGRAL_OR_ENUMERATION_TYPE_P (expr_type))
4987         return error_mark_node;
4988
4989       expr = fold_decl_constant_value (expr);
4990       /* Notice that there are constant expressions like '4 % 0' which
4991          do not fold into integer constants.  */
4992       if (TREE_CODE (expr) != INTEGER_CST)
4993         {
4994           error ("%qE is not a valid template argument for type %qT "
4995                  "because it is a non-constant expression", expr, type);
4996           return NULL_TREE;
4997         }
4998
4999       /* At this point, an implicit conversion does what we want,
5000          because we already know that the expression is of integral
5001          type.  */
5002       expr = ocp_convert (type, expr, CONV_IMPLICIT, LOOKUP_PROTECT);
5003       if (expr == error_mark_node)
5004         return error_mark_node;
5005
5006       /* Conversion was allowed: fold it to a bare integer constant.  */
5007       expr = fold (expr);
5008     }
5009   /* [temp.arg.nontype]/5, bullet 2
5010
5011      For a non-type template-parameter of type pointer to object,
5012      qualification conversions (_conv.qual_) and the array-to-pointer
5013      conversion (_conv.array_) are applied.  */
5014   else if (TYPE_PTROBV_P (type))
5015     {
5016       /* [temp.arg.nontype]/1  (TC1 version, DR 49):
5017
5018          A template-argument for a non-type, non-template template-parameter
5019          shall be one of: [...]
5020
5021          -- the name of a non-type template-parameter;
5022          -- the address of an object or function with external linkage, [...]
5023             expressed as "& id-expression" where the & is optional if the name
5024             refers to a function or array, or if the corresponding
5025             template-parameter is a reference.
5026
5027         Here, we do not care about functions, as they are invalid anyway
5028         for a parameter of type pointer-to-object.  */
5029
5030       if (DECL_P (expr) && DECL_TEMPLATE_PARM_P (expr))
5031         /* Non-type template parameters are OK.  */
5032         ;
5033       else if (TREE_CODE (expr) != ADDR_EXPR
5034                && TREE_CODE (expr_type) != ARRAY_TYPE)
5035         {
5036           if (TREE_CODE (expr) == VAR_DECL)
5037             {
5038               error ("%qD is not a valid template argument "
5039                      "because %qD is a variable, not the address of "
5040                      "a variable",
5041                      expr, expr);
5042               return NULL_TREE;
5043             }
5044           /* Other values, like integer constants, might be valid
5045              non-type arguments of some other type.  */
5046           return error_mark_node;
5047         }
5048       else
5049         {
5050           tree decl;
5051
5052           decl = ((TREE_CODE (expr) == ADDR_EXPR)
5053                   ? TREE_OPERAND (expr, 0) : expr);
5054           if (TREE_CODE (decl) != VAR_DECL)
5055             {
5056               error ("%qE is not a valid template argument of type %qT "
5057                      "because %qE is not a variable",
5058                      expr, type, decl);
5059               return NULL_TREE;
5060             }
5061           else if (!DECL_EXTERNAL_LINKAGE_P (decl))
5062             {
5063               error ("%qE is not a valid template argument of type %qT "
5064                      "because %qD does not have external linkage",
5065                      expr, type, decl);
5066               return NULL_TREE;
5067             }
5068         }
5069
5070       expr = decay_conversion (expr);
5071       if (expr == error_mark_node)
5072         return error_mark_node;
5073
5074       expr = perform_qualification_conversions (type, expr);
5075       if (expr == error_mark_node)
5076         return error_mark_node;
5077     }
5078   /* [temp.arg.nontype]/5, bullet 3
5079
5080      For a non-type template-parameter of type reference to object, no
5081      conversions apply. The type referred to by the reference may be more
5082      cv-qualified than the (otherwise identical) type of the
5083      template-argument. The template-parameter is bound directly to the
5084      template-argument, which must be an lvalue.  */
5085   else if (TYPE_REF_OBJ_P (type))
5086     {
5087       if (!same_type_ignoring_top_level_qualifiers_p (TREE_TYPE (type),
5088                                                       expr_type))
5089         return error_mark_node;
5090
5091       if (!at_least_as_qualified_p (TREE_TYPE (type), expr_type))
5092         {
5093           error ("%qE is not a valid template argument for type %qT "
5094                  "because of conflicts in cv-qualification", expr, type);
5095           return NULL_TREE;
5096         }
5097
5098       if (!real_lvalue_p (expr))
5099         {
5100           error ("%qE is not a valid template argument for type %qT "
5101                  "because it is not an lvalue", expr, type);
5102           return NULL_TREE;
5103         }
5104
5105       /* [temp.arg.nontype]/1
5106
5107          A template-argument for a non-type, non-template template-parameter
5108          shall be one of: [...]
5109
5110          -- the address of an object or function with external linkage.  */
5111       if (TREE_CODE (expr) == INDIRECT_REF
5112           && TYPE_REF_OBJ_P (TREE_TYPE (TREE_OPERAND (expr, 0))))
5113         {
5114           expr = TREE_OPERAND (expr, 0);
5115           if (DECL_P (expr))
5116             {
5117               error ("%q#D is not a valid template argument for type %qT "
5118                      "because a reference variable does not have a constant "
5119                      "address", expr, type);
5120               return NULL_TREE;
5121             }
5122         }
5123
5124       if (!DECL_P (expr))
5125         {
5126           error ("%qE is not a valid template argument for type %qT "
5127                  "because it is not an object with external linkage",
5128                  expr, type);
5129           return NULL_TREE;
5130         }
5131
5132       if (!DECL_EXTERNAL_LINKAGE_P (expr))
5133         {
5134           error ("%qE is not a valid template argument for type %qT "
5135                  "because object %qD has not external linkage",
5136                  expr, type, expr);
5137           return NULL_TREE;
5138         }
5139
5140       expr = build_nop (type, build_address (expr));
5141     }
5142   /* [temp.arg.nontype]/5, bullet 4
5143
5144      For a non-type template-parameter of type pointer to function, only
5145      the function-to-pointer conversion (_conv.func_) is applied. If the
5146      template-argument represents a set of overloaded functions (or a
5147      pointer to such), the matching function is selected from the set
5148      (_over.over_).  */
5149   else if (TYPE_PTRFN_P (type))
5150     {
5151       /* If the argument is a template-id, we might not have enough
5152          context information to decay the pointer.  */
5153       if (!type_unknown_p (expr_type))
5154         {
5155           expr = decay_conversion (expr);
5156           if (expr == error_mark_node)
5157             return error_mark_node;
5158         }
5159
5160       expr = convert_nontype_argument_function (type, expr);
5161       if (!expr || expr == error_mark_node)
5162         return expr;
5163
5164       if (TREE_CODE (expr) != ADDR_EXPR)
5165         {
5166           error ("%qE is not a valid template argument for type %qT", expr, type);
5167           error ("it must be the address of a function with external linkage");
5168           return NULL_TREE;
5169         }
5170     }
5171   /* [temp.arg.nontype]/5, bullet 5
5172
5173      For a non-type template-parameter of type reference to function, no
5174      conversions apply. If the template-argument represents a set of
5175      overloaded functions, the matching function is selected from the set
5176      (_over.over_).  */
5177   else if (TYPE_REFFN_P (type))
5178     {
5179       if (TREE_CODE (expr) == ADDR_EXPR)
5180         {
5181           error ("%qE is not a valid template argument for type %qT "
5182                  "because it is a pointer", expr, type);
5183           inform (input_location, "try using %qE instead", TREE_OPERAND (expr, 0));
5184           return NULL_TREE;
5185         }
5186
5187       expr = convert_nontype_argument_function (TREE_TYPE (type), expr);
5188       if (!expr || expr == error_mark_node)
5189         return expr;
5190
5191       expr = build_nop (type, build_address (expr));
5192     }
5193   /* [temp.arg.nontype]/5, bullet 6
5194
5195      For a non-type template-parameter of type pointer to member function,
5196      no conversions apply. If the template-argument represents a set of
5197      overloaded member functions, the matching member function is selected
5198      from the set (_over.over_).  */
5199   else if (TYPE_PTRMEMFUNC_P (type))
5200     {
5201       expr = instantiate_type (type, expr, tf_none);
5202       if (expr == error_mark_node)
5203         return error_mark_node;
5204
5205       /* [temp.arg.nontype] bullet 1 says the pointer to member
5206          expression must be a pointer-to-member constant.  */
5207       if (!check_valid_ptrmem_cst_expr (type, expr))
5208         return error_mark_node;
5209
5210       /* There is no way to disable standard conversions in
5211          resolve_address_of_overloaded_function (called by
5212          instantiate_type). It is possible that the call succeeded by
5213          converting &B::I to &D::I (where B is a base of D), so we need
5214          to reject this conversion here.
5215
5216          Actually, even if there was a way to disable standard conversions,
5217          it would still be better to reject them here so that we can
5218          provide a superior diagnostic.  */
5219       if (!same_type_p (TREE_TYPE (expr), type))
5220         {
5221           error ("%qE is not a valid template argument for type %qT "
5222                  "because it is of type %qT", expr, type,
5223                  TREE_TYPE (expr));
5224           /* If we are just one standard conversion off, explain.  */
5225           if (can_convert (type, TREE_TYPE (expr)))
5226             inform (input_location,
5227                     "standard conversions are not allowed in this context");
5228           return NULL_TREE;
5229         }
5230     }
5231   /* [temp.arg.nontype]/5, bullet 7
5232
5233      For a non-type template-parameter of type pointer to data member,
5234      qualification conversions (_conv.qual_) are applied.  */
5235   else if (TYPE_PTRMEM_P (type))
5236     {
5237       /* [temp.arg.nontype] bullet 1 says the pointer to member
5238          expression must be a pointer-to-member constant.  */
5239       if (!check_valid_ptrmem_cst_expr (type, expr))
5240         return error_mark_node;
5241
5242       expr = perform_qualification_conversions (type, expr);
5243       if (expr == error_mark_node)
5244         return expr;
5245     }
5246   /* A template non-type parameter must be one of the above.  */
5247   else
5248     gcc_unreachable ();
5249
5250   /* Sanity check: did we actually convert the argument to the
5251      right type?  */
5252   gcc_assert (same_type_p (type, TREE_TYPE (expr)));
5253   return expr;
5254 }
5255
5256 /* Subroutine of coerce_template_template_parms, which returns 1 if
5257    PARM_PARM and ARG_PARM match using the rule for the template
5258    parameters of template template parameters. Both PARM and ARG are
5259    template parameters; the rest of the arguments are the same as for
5260    coerce_template_template_parms.
5261  */
5262 static int
5263 coerce_template_template_parm (tree parm,
5264                               tree arg,
5265                               tsubst_flags_t complain,
5266                               tree in_decl,
5267                               tree outer_args)
5268 {
5269   if (arg == NULL_TREE || arg == error_mark_node
5270       || parm == NULL_TREE || parm == error_mark_node)
5271     return 0;
5272   
5273   if (TREE_CODE (arg) != TREE_CODE (parm))
5274     return 0;
5275   
5276   switch (TREE_CODE (parm))
5277     {
5278     case TEMPLATE_DECL:
5279       /* We encounter instantiations of templates like
5280          template <template <template <class> class> class TT>
5281          class C;  */
5282       {
5283         tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5284         tree argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5285         
5286         if (!coerce_template_template_parms
5287             (parmparm, argparm, complain, in_decl, outer_args))
5288           return 0;
5289       }
5290       /* Fall through.  */
5291       
5292     case TYPE_DECL:
5293       if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (arg))
5294           && !TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5295         /* Argument is a parameter pack but parameter is not.  */
5296         return 0;
5297       break;
5298       
5299     case PARM_DECL:
5300       /* The tsubst call is used to handle cases such as
5301          
5302            template <int> class C {};
5303            template <class T, template <T> class TT> class D {};
5304            D<int, C> d;
5305
5306          i.e. the parameter list of TT depends on earlier parameters.  */
5307       if (!uses_template_parms (TREE_TYPE (arg))
5308           && !same_type_p
5309                 (tsubst (TREE_TYPE (parm), outer_args, complain, in_decl),
5310                  TREE_TYPE (arg)))
5311         return 0;
5312       
5313       if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (arg))
5314           && !TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5315         /* Argument is a parameter pack but parameter is not.  */
5316         return 0;
5317       
5318       break;
5319
5320     default:
5321       gcc_unreachable ();
5322     }
5323
5324   return 1;
5325 }
5326
5327
5328 /* Return 1 if PARM_PARMS and ARG_PARMS matches using rule for
5329    template template parameters.  Both PARM_PARMS and ARG_PARMS are
5330    vectors of TREE_LIST nodes containing TYPE_DECL, TEMPLATE_DECL
5331    or PARM_DECL.
5332
5333    Consider the example:
5334      template <class T> class A;
5335      template<template <class U> class TT> class B;
5336
5337    For B<A>, PARM_PARMS are the parameters to TT, while ARG_PARMS are
5338    the parameters to A, and OUTER_ARGS contains A.  */
5339
5340 static int
5341 coerce_template_template_parms (tree parm_parms,
5342                                 tree arg_parms,
5343                                 tsubst_flags_t complain,
5344                                 tree in_decl,
5345                                 tree outer_args)
5346 {
5347   int nparms, nargs, i;
5348   tree parm, arg;
5349   int variadic_p = 0;
5350
5351   gcc_assert (TREE_CODE (parm_parms) == TREE_VEC);
5352   gcc_assert (TREE_CODE (arg_parms) == TREE_VEC);
5353
5354   nparms = TREE_VEC_LENGTH (parm_parms);
5355   nargs = TREE_VEC_LENGTH (arg_parms);
5356
5357   /* Determine whether we have a parameter pack at the end of the
5358      template template parameter's template parameter list.  */
5359   if (TREE_VEC_ELT (parm_parms, nparms - 1) != error_mark_node)
5360     {
5361       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, nparms - 1));
5362       
5363       if (parm == error_mark_node)
5364         return 0;
5365
5366       switch (TREE_CODE (parm))
5367         {
5368         case TEMPLATE_DECL:
5369         case TYPE_DECL:
5370           if (TEMPLATE_TYPE_PARAMETER_PACK (TREE_TYPE (parm)))
5371             variadic_p = 1;
5372           break;
5373           
5374         case PARM_DECL:
5375           if (TEMPLATE_PARM_PARAMETER_PACK (DECL_INITIAL (parm)))
5376             variadic_p = 1;
5377           break;
5378           
5379         default:
5380           gcc_unreachable ();
5381         }
5382     }
5383  
5384   if (nargs != nparms
5385       && !(variadic_p && nargs >= nparms - 1))
5386     return 0;
5387
5388   /* Check all of the template parameters except the parameter pack at
5389      the end (if any).  */
5390   for (i = 0; i < nparms - variadic_p; ++i)
5391     {
5392       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node
5393           || TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5394         continue;
5395
5396       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5397       arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5398
5399       if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5400                                           outer_args))
5401         return 0;
5402
5403     }
5404
5405   if (variadic_p)
5406     {
5407       /* Check each of the template parameters in the template
5408          argument against the template parameter pack at the end of
5409          the template template parameter.  */
5410       if (TREE_VEC_ELT (parm_parms, i) == error_mark_node)
5411         return 0;
5412
5413       parm = TREE_VALUE (TREE_VEC_ELT (parm_parms, i));
5414
5415       for (; i < nargs; ++i)
5416         {
5417           if (TREE_VEC_ELT (arg_parms, i) == error_mark_node)
5418             continue;
5419  
5420           arg = TREE_VALUE (TREE_VEC_ELT (arg_parms, i));
5421  
5422           if (!coerce_template_template_parm (parm, arg, complain, in_decl,
5423                                               outer_args))
5424             return 0;
5425         }
5426     }
5427
5428   return 1;
5429 }
5430
5431 /* Verifies that the deduced template arguments (in TARGS) for the
5432    template template parameters (in TPARMS) represent valid bindings,
5433    by comparing the template parameter list of each template argument
5434    to the template parameter list of its corresponding template
5435    template parameter, in accordance with DR150. This
5436    routine can only be called after all template arguments have been
5437    deduced. It will return TRUE if all of the template template
5438    parameter bindings are okay, FALSE otherwise.  */
5439 bool 
5440 template_template_parm_bindings_ok_p (tree tparms, tree targs)
5441 {
5442   int i, ntparms = TREE_VEC_LENGTH (tparms);
5443   bool ret = true;
5444
5445   /* We're dealing with template parms in this process.  */
5446   ++processing_template_decl;
5447
5448   targs = INNERMOST_TEMPLATE_ARGS (targs);
5449
5450   for (i = 0; i < ntparms; ++i)
5451     {
5452       tree tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
5453       tree targ = TREE_VEC_ELT (targs, i);
5454
5455       if (TREE_CODE (tparm) == TEMPLATE_DECL && targ)
5456         {
5457           tree packed_args = NULL_TREE;
5458           int idx, len = 1;
5459
5460           if (ARGUMENT_PACK_P (targ))
5461             {
5462               /* Look inside the argument pack.  */
5463               packed_args = ARGUMENT_PACK_ARGS (targ);
5464               len = TREE_VEC_LENGTH (packed_args);
5465             }
5466
5467           for (idx = 0; idx < len; ++idx)
5468             {
5469               tree targ_parms = NULL_TREE;
5470
5471               if (packed_args)
5472                 /* Extract the next argument from the argument
5473                    pack.  */
5474                 targ = TREE_VEC_ELT (packed_args, idx);
5475
5476               if (PACK_EXPANSION_P (targ))
5477                 /* Look at the pattern of the pack expansion.  */
5478                 targ = PACK_EXPANSION_PATTERN (targ);
5479
5480               /* Extract the template parameters from the template
5481                  argument.  */
5482               if (TREE_CODE (targ) == TEMPLATE_DECL)
5483                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (targ);
5484               else if (TREE_CODE (targ) == TEMPLATE_TEMPLATE_PARM)
5485                 targ_parms = DECL_INNERMOST_TEMPLATE_PARMS (TYPE_NAME (targ));
5486
5487               /* Verify that we can coerce the template template
5488                  parameters from the template argument to the template
5489                  parameter.  This requires an exact match.  */
5490               if (targ_parms
5491                   && !coerce_template_template_parms
5492                        (DECL_INNERMOST_TEMPLATE_PARMS (tparm),
5493                         targ_parms,
5494                         tf_none,
5495                         tparm,
5496                         targs))
5497                 {
5498                   ret = false;
5499                   goto out;
5500                 }
5501             }
5502         }
5503     }
5504
5505  out:
5506
5507   --processing_template_decl;
5508   return ret;
5509 }
5510
5511 /* Convert the indicated template ARG as necessary to match the
5512    indicated template PARM.  Returns the converted ARG, or
5513    error_mark_node if the conversion was unsuccessful.  Error and
5514    warning messages are issued under control of COMPLAIN.  This
5515    conversion is for the Ith parameter in the parameter list.  ARGS is
5516    the full set of template arguments deduced so far.  */
5517
5518 static tree
5519 convert_template_argument (tree parm,
5520                            tree arg,
5521                            tree args,
5522                            tsubst_flags_t complain,
5523                            int i,
5524                            tree in_decl)
5525 {
5526   tree orig_arg;
5527   tree val;
5528   int is_type, requires_type, is_tmpl_type, requires_tmpl_type;
5529
5530   if (TREE_CODE (arg) == TREE_LIST
5531       && TREE_CODE (TREE_VALUE (arg)) == OFFSET_REF)
5532     {
5533       /* The template argument was the name of some
5534          member function.  That's usually
5535          invalid, but static members are OK.  In any
5536          case, grab the underlying fields/functions
5537          and issue an error later if required.  */
5538       orig_arg = TREE_VALUE (arg);
5539       TREE_TYPE (arg) = unknown_type_node;
5540     }
5541
5542   orig_arg = arg;
5543
5544   requires_tmpl_type = TREE_CODE (parm) == TEMPLATE_DECL;
5545   requires_type = (TREE_CODE (parm) == TYPE_DECL
5546                    || requires_tmpl_type);
5547
5548   /* When determining whether an argument pack expansion is a template,
5549      look at the pattern.  */
5550   if (TREE_CODE (arg) == TYPE_PACK_EXPANSION)
5551     arg = PACK_EXPANSION_PATTERN (arg);
5552
5553   /* Deal with an injected-class-name used as a template template arg.  */
5554   if (requires_tmpl_type && CLASS_TYPE_P (arg))
5555     {
5556       tree t = maybe_get_template_decl_from_type_decl (TYPE_NAME (arg));
5557       if (TREE_CODE (t) == TEMPLATE_DECL)
5558         {
5559           if (complain & tf_warning_or_error)
5560             pedwarn (input_location, OPT_pedantic, "injected-class-name %qD"
5561                      " used as template template argument", TYPE_NAME (arg));
5562           else if (flag_pedantic_errors)
5563             t = arg;
5564
5565           arg = t;
5566         }
5567     }
5568
5569   is_tmpl_type = 
5570     ((TREE_CODE (arg) == TEMPLATE_DECL
5571       && TREE_CODE (DECL_TEMPLATE_RESULT (arg)) == TYPE_DECL)
5572      || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5573      || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE);
5574
5575   if (is_tmpl_type
5576       && (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM
5577           || TREE_CODE (arg) == UNBOUND_CLASS_TEMPLATE))
5578     arg = TYPE_STUB_DECL (arg);
5579
5580   is_type = TYPE_P (arg) || is_tmpl_type;
5581
5582   if (requires_type && ! is_type && TREE_CODE (arg) == SCOPE_REF
5583       && TREE_CODE (TREE_OPERAND (arg, 0)) == TEMPLATE_TYPE_PARM)
5584     {
5585       permerror (input_location, "to refer to a type member of a template parameter, "
5586                  "use %<typename %E%>", orig_arg);
5587
5588       orig_arg = make_typename_type (TREE_OPERAND (arg, 0),
5589                                      TREE_OPERAND (arg, 1),
5590                                      typename_type,
5591                                      complain & tf_error);
5592       arg = orig_arg;
5593       is_type = 1;
5594     }
5595   if (is_type != requires_type)
5596     {
5597       if (in_decl)
5598         {
5599           if (complain & tf_error)
5600             {
5601               error ("type/value mismatch at argument %d in template "
5602                      "parameter list for %qD",
5603                      i + 1, in_decl);
5604               if (is_type)
5605                 error ("  expected a constant of type %qT, got %qT",
5606                        TREE_TYPE (parm),
5607                        (DECL_P (arg) ? DECL_NAME (arg) : orig_arg));
5608               else if (requires_tmpl_type)
5609                 error ("  expected a class template, got %qE", orig_arg);
5610               else
5611                 error ("  expected a type, got %qE", orig_arg);
5612             }
5613         }
5614       return error_mark_node;
5615     }
5616   if (is_tmpl_type ^ requires_tmpl_type)
5617     {
5618       if (in_decl && (complain & tf_error))
5619         {
5620           error ("type/value mismatch at argument %d in template "
5621                  "parameter list for %qD",
5622                  i + 1, in_decl);
5623           if (is_tmpl_type)
5624             error ("  expected a type, got %qT", DECL_NAME (arg));
5625           else
5626             error ("  expected a class template, got %qT", orig_arg);
5627         }
5628       return error_mark_node;
5629     }
5630
5631   if (is_type)
5632     {
5633       if (requires_tmpl_type)
5634         {
5635           if (TREE_CODE (TREE_TYPE (arg)) == UNBOUND_CLASS_TEMPLATE)
5636             /* The number of argument required is not known yet.
5637                Just accept it for now.  */
5638             val = TREE_TYPE (arg);
5639           else
5640             {
5641               tree parmparm = DECL_INNERMOST_TEMPLATE_PARMS (parm);
5642               tree argparm;
5643
5644               argparm = DECL_INNERMOST_TEMPLATE_PARMS (arg);
5645
5646               if (coerce_template_template_parms (parmparm, argparm,
5647                                                   complain, in_decl,
5648                                                   args))
5649                 {
5650                   val = arg;
5651
5652                   /* TEMPLATE_TEMPLATE_PARM node is preferred over
5653                      TEMPLATE_DECL.  */
5654                   if (val != error_mark_node)
5655                     {
5656                       if (DECL_TEMPLATE_TEMPLATE_PARM_P (val))
5657                         val = TREE_TYPE (val);
5658                       if (TREE_CODE (orig_arg) == TYPE_PACK_EXPANSION)
5659                         val = make_pack_expansion (val);
5660                     }
5661                 }
5662               else
5663                 {
5664                   if (in_decl && (complain & tf_error))
5665                     {
5666                       error ("type/value mismatch at argument %d in "
5667                              "template parameter list for %qD",
5668                              i + 1, in_decl);
5669                       error ("  expected a template of type %qD, got %qT",
5670                              parm, orig_arg);
5671                     }
5672
5673                   val = error_mark_node;
5674                 }
5675             }
5676         }
5677       else
5678         val = orig_arg;
5679       /* We only form one instance of each template specialization.
5680          Therefore, if we use a non-canonical variant (i.e., a
5681          typedef), any future messages referring to the type will use
5682          the typedef, which is confusing if those future uses do not
5683          themselves also use the typedef.  */
5684       if (TYPE_P (val))
5685         val = strip_typedefs (val);
5686     }
5687   else
5688     {
5689       tree t = tsubst (TREE_TYPE (parm), args, complain, in_decl);
5690
5691       if (invalid_nontype_parm_type_p (t, complain))
5692         return error_mark_node;
5693
5694       if (template_parameter_pack_p (parm) && ARGUMENT_PACK_P (orig_arg))
5695         {
5696           if (same_type_p (t, TREE_TYPE (orig_arg)))
5697             val = orig_arg;
5698           else
5699             {
5700               /* Not sure if this is reachable, but it doesn't hurt
5701                  to be robust.  */
5702               error ("type mismatch in nontype parameter pack");
5703               val = error_mark_node;
5704             }
5705         }
5706       else if (!uses_template_parms (orig_arg) && !uses_template_parms (t))
5707         /* We used to call digest_init here.  However, digest_init
5708            will report errors, which we don't want when complain
5709            is zero.  More importantly, digest_init will try too
5710            hard to convert things: for example, `0' should not be
5711            converted to pointer type at this point according to
5712            the standard.  Accepting this is not merely an
5713            extension, since deciding whether or not these
5714            conversions can occur is part of determining which
5715            function template to call, or whether a given explicit
5716            argument specification is valid.  */
5717         val = convert_nontype_argument (t, orig_arg);
5718       else
5719         val = orig_arg;
5720
5721       if (val == NULL_TREE)
5722         val = error_mark_node;
5723       else if (val == error_mark_node && (complain & tf_error))
5724         error ("could not convert template argument %qE to %qT",  orig_arg, t);
5725
5726       if (TREE_CODE (val) == SCOPE_REF)
5727         {
5728           /* Strip typedefs from the SCOPE_REF.  */
5729           tree type = strip_typedefs (TREE_TYPE (val));
5730           tree scope = strip_typedefs (TREE_OPERAND (val, 0));
5731           val = build_qualified_name (type, scope, TREE_OPERAND (val, 1),
5732                                       QUALIFIED_NAME_IS_TEMPLATE (val));
5733         }
5734     }
5735
5736   return val;
5737 }
5738
5739 /* Coerces the remaining template arguments in INNER_ARGS (from
5740    ARG_IDX to the end) into the parameter pack at PARM_IDX in PARMS.
5741    Returns the coerced argument pack. PARM_IDX is the position of this
5742    parameter in the template parameter list. ARGS is the original
5743    template argument list.  */
5744 static tree
5745 coerce_template_parameter_pack (tree parms,
5746                                 int parm_idx,
5747                                 tree args,
5748                                 tree inner_args,
5749                                 int arg_idx,
5750                                 tree new_args,
5751                                 int* lost,
5752                                 tree in_decl,
5753                                 tsubst_flags_t complain)
5754 {
5755   tree parm = TREE_VEC_ELT (parms, parm_idx);
5756   int nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5757   tree packed_args;
5758   tree argument_pack;
5759   tree packed_types = NULL_TREE;
5760
5761   if (arg_idx > nargs)
5762     arg_idx = nargs;
5763
5764   packed_args = make_tree_vec (nargs - arg_idx);
5765
5766   if (TREE_CODE (TREE_VALUE (parm)) == PARM_DECL
5767       && uses_parameter_packs (TREE_TYPE (TREE_VALUE (parm))))
5768     {
5769       /* When the template parameter is a non-type template
5770          parameter pack whose type uses parameter packs, we need
5771          to look at each of the template arguments
5772          separately. Build a vector of the types for these
5773          non-type template parameters in PACKED_TYPES.  */
5774       tree expansion 
5775         = make_pack_expansion (TREE_TYPE (TREE_VALUE (parm)));
5776       packed_types = tsubst_pack_expansion (expansion, args,
5777                                             complain, in_decl);
5778
5779       if (packed_types == error_mark_node)
5780         return error_mark_node;
5781
5782       /* Check that we have the right number of arguments.  */
5783       if (arg_idx < nargs
5784           && !PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx))
5785           && nargs - arg_idx != TREE_VEC_LENGTH (packed_types))
5786         {
5787           int needed_parms 
5788             = TREE_VEC_LENGTH (parms) - 1 + TREE_VEC_LENGTH (packed_types);
5789           error ("wrong number of template arguments (%d, should be %d)",
5790                  nargs, needed_parms);
5791           return error_mark_node;
5792         }
5793
5794       /* If we aren't able to check the actual arguments now
5795          (because they haven't been expanded yet), we can at least
5796          verify that all of the types used for the non-type
5797          template parameter pack are, in fact, valid for non-type
5798          template parameters.  */
5799       if (arg_idx < nargs 
5800           && PACK_EXPANSION_P (TREE_VEC_ELT (inner_args, arg_idx)))
5801         {
5802           int j, len = TREE_VEC_LENGTH (packed_types);
5803           for (j = 0; j < len; ++j)
5804             {
5805               tree t = TREE_VEC_ELT (packed_types, j);
5806               if (invalid_nontype_parm_type_p (t, complain))
5807                 return error_mark_node;
5808             }
5809         }
5810     }
5811
5812   /* Convert the remaining arguments, which will be a part of the
5813      parameter pack "parm".  */
5814   for (; arg_idx < nargs; ++arg_idx)
5815     {
5816       tree arg = TREE_VEC_ELT (inner_args, arg_idx);
5817       tree actual_parm = TREE_VALUE (parm);
5818
5819       if (packed_types && !PACK_EXPANSION_P (arg))
5820         {
5821           /* When we have a vector of types (corresponding to the
5822              non-type template parameter pack that uses parameter
5823              packs in its type, as mention above), and the
5824              argument is not an expansion (which expands to a
5825              currently unknown number of arguments), clone the
5826              parm and give it the next type in PACKED_TYPES.  */
5827           actual_parm = copy_node (actual_parm);
5828           TREE_TYPE (actual_parm) = 
5829             TREE_VEC_ELT (packed_types, arg_idx - parm_idx);
5830         }
5831
5832       if (arg != error_mark_node)
5833         arg = convert_template_argument (actual_parm, 
5834                                          arg, new_args, complain, parm_idx,
5835                                          in_decl);
5836       if (arg == error_mark_node)
5837         (*lost)++;
5838       TREE_VEC_ELT (packed_args, arg_idx - parm_idx) = arg; 
5839     }
5840
5841   if (TREE_CODE (TREE_VALUE (parm)) == TYPE_DECL
5842       || TREE_CODE (TREE_VALUE (parm)) == TEMPLATE_DECL)
5843     argument_pack = cxx_make_type (TYPE_ARGUMENT_PACK);
5844   else
5845     {
5846       argument_pack = make_node (NONTYPE_ARGUMENT_PACK);
5847       TREE_TYPE (argument_pack) 
5848         = tsubst (TREE_TYPE (TREE_VALUE (parm)), new_args, complain, in_decl);
5849       TREE_CONSTANT (argument_pack) = 1;
5850     }
5851
5852   SET_ARGUMENT_PACK_ARGS (argument_pack, packed_args);
5853 #ifdef ENABLE_CHECKING
5854   SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (packed_args,
5855                                        TREE_VEC_LENGTH (packed_args));
5856 #endif
5857   return argument_pack;
5858 }
5859
5860 /* Convert all template arguments to their appropriate types, and
5861    return a vector containing the innermost resulting template
5862    arguments.  If any error occurs, return error_mark_node. Error and
5863    warning messages are issued under control of COMPLAIN.
5864
5865    If REQUIRE_ALL_ARGS is false, argument deduction will be performed
5866    for arguments not specified in ARGS.  Otherwise, if
5867    USE_DEFAULT_ARGS is true, default arguments will be used to fill in
5868    unspecified arguments.  If REQUIRE_ALL_ARGS is true, but
5869    USE_DEFAULT_ARGS is false, then all arguments must be specified in
5870    ARGS.  */
5871
5872 static tree
5873 coerce_template_parms (tree parms,
5874                        tree args,
5875                        tree in_decl,
5876                        tsubst_flags_t complain,
5877                        bool require_all_args,
5878                        bool use_default_args)
5879 {
5880   int nparms, nargs, parm_idx, arg_idx, lost = 0;
5881   tree inner_args;
5882   tree new_args;
5883   tree new_inner_args;
5884   int saved_unevaluated_operand;
5885   int saved_inhibit_evaluation_warnings;
5886
5887   /* When used as a boolean value, indicates whether this is a
5888      variadic template parameter list. Since it's an int, we can also
5889      subtract it from nparms to get the number of non-variadic
5890      parameters.  */
5891   int variadic_p = 0;
5892
5893   nparms = TREE_VEC_LENGTH (parms);
5894
5895   /* Determine if there are any parameter packs.  */
5896   for (parm_idx = 0; parm_idx < nparms; ++parm_idx)
5897     {
5898       tree tparm = TREE_VALUE (TREE_VEC_ELT (parms, parm_idx));
5899       if (template_parameter_pack_p (tparm))
5900         ++variadic_p;
5901     }
5902
5903   inner_args = INNERMOST_TEMPLATE_ARGS (args);
5904   /* If there are 0 or 1 parameter packs, we need to expand any argument
5905      packs so that we can deduce a parameter pack from some non-packed args
5906      followed by an argument pack, as in variadic85.C.  If there are more
5907      than that, we need to leave argument packs intact so the arguments are
5908      assigned to the right parameter packs.  This should only happen when
5909      dealing with a nested class inside a partial specialization of a class
5910      template, as in variadic92.C.  */
5911   if (variadic_p <= 1)
5912     inner_args = expand_template_argument_pack (inner_args);
5913
5914   nargs = inner_args ? NUM_TMPL_ARGS (inner_args) : 0;
5915   if ((nargs > nparms && !variadic_p)
5916       || (nargs < nparms - variadic_p
5917           && require_all_args
5918           && (!use_default_args
5919               || (TREE_VEC_ELT (parms, nargs) != error_mark_node
5920                   && !TREE_PURPOSE (TREE_VEC_ELT (parms, nargs))))))
5921     {
5922       if (complain & tf_error)
5923         {
5924           const char *or_more = "";
5925           if (variadic_p)
5926             {
5927               or_more = " or more";
5928               --nparms;
5929             }
5930
5931           error ("wrong number of template arguments (%d, should be %d%s)",
5932                  nargs, nparms, or_more);
5933
5934           if (in_decl)
5935             error ("provided for %q+D", in_decl);
5936         }
5937
5938       return error_mark_node;
5939     }
5940
5941   /* We need to evaluate the template arguments, even though this
5942      template-id may be nested within a "sizeof".  */
5943   saved_unevaluated_operand = cp_unevaluated_operand;
5944   cp_unevaluated_operand = 0;
5945   saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
5946   c_inhibit_evaluation_warnings = 0;
5947   new_inner_args = make_tree_vec (nparms);
5948   new_args = add_outermost_template_args (args, new_inner_args);
5949   for (parm_idx = 0, arg_idx = 0; parm_idx < nparms; parm_idx++, arg_idx++)
5950     {
5951       tree arg;
5952       tree parm;
5953
5954       /* Get the Ith template parameter.  */
5955       parm = TREE_VEC_ELT (parms, parm_idx);
5956  
5957       if (parm == error_mark_node)
5958       {
5959         TREE_VEC_ELT (new_inner_args, arg_idx) = error_mark_node;
5960         continue;
5961       }
5962
5963       /* Calculate the next argument.  */
5964       if (arg_idx < nargs)
5965         arg = TREE_VEC_ELT (inner_args, arg_idx);
5966       else
5967         arg = NULL_TREE;
5968
5969       if (template_parameter_pack_p (TREE_VALUE (parm))
5970           && !(arg && ARGUMENT_PACK_P (arg)))
5971         {
5972           /* All remaining arguments will be placed in the
5973              template parameter pack PARM.  */
5974           arg = coerce_template_parameter_pack (parms, parm_idx, args, 
5975                                                 inner_args, arg_idx,
5976                                                 new_args, &lost,
5977                                                 in_decl, complain);
5978
5979           /* Store this argument.  */
5980           if (arg == error_mark_node)
5981             lost++;
5982           TREE_VEC_ELT (new_inner_args, parm_idx) = arg;
5983
5984           /* We are done with all of the arguments.  */
5985           arg_idx = nargs;
5986           
5987           continue;
5988         }
5989       else if (arg)
5990         {
5991           if (PACK_EXPANSION_P (arg))
5992             {
5993               if (complain & tf_error)
5994                 {
5995                   /* FIXME this restriction was removed by N2555; see
5996                      bug 35722.  */
5997                   /* If ARG is a pack expansion, but PARM is not a
5998                      template parameter pack (if it were, we would have
5999                      handled it above), we're trying to expand into a
6000                      fixed-length argument list.  */
6001                   if (TREE_CODE (arg) == EXPR_PACK_EXPANSION)
6002                     sorry ("cannot expand %<%E%> into a fixed-length "
6003                            "argument list", arg);
6004                   else
6005                     sorry ("cannot expand %<%T%> into a fixed-length "
6006                            "argument list", arg);
6007                 }
6008               return error_mark_node;
6009             }
6010         }
6011       else if (require_all_args)
6012         {
6013           /* There must be a default arg in this case.  */
6014           arg = tsubst_template_arg (TREE_PURPOSE (parm), new_args,
6015                                      complain, in_decl);
6016           /* The position of the first default template argument,
6017              is also the number of non-defaulted arguments in NEW_INNER_ARGS.
6018              Record that.  */
6019           if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6020             SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args, arg_idx);
6021         }
6022       else
6023         break;
6024
6025       if (arg == error_mark_node)
6026         {
6027           if (complain & tf_error)
6028             error ("template argument %d is invalid", arg_idx + 1);
6029         }
6030       else if (!arg)
6031         /* This only occurs if there was an error in the template
6032            parameter list itself (which we would already have
6033            reported) that we are trying to recover from, e.g., a class
6034            template with a parameter list such as
6035            template<typename..., typename>.  */
6036         return error_mark_node;
6037       else
6038         arg = convert_template_argument (TREE_VALUE (parm),
6039                                          arg, new_args, complain, 
6040                                          parm_idx, in_decl);
6041
6042       if (arg == error_mark_node)
6043         lost++;
6044       TREE_VEC_ELT (new_inner_args, arg_idx) = arg;
6045     }
6046   cp_unevaluated_operand = saved_unevaluated_operand;
6047   c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
6048
6049   if (lost)
6050     return error_mark_node;
6051
6052 #ifdef ENABLE_CHECKING
6053   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args))
6054     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (new_inner_args,
6055                                          TREE_VEC_LENGTH (new_inner_args));
6056 #endif
6057
6058   return new_inner_args;
6059 }
6060
6061 /* Returns 1 if template args OT and NT are equivalent.  */
6062
6063 static int
6064 template_args_equal (tree ot, tree nt)
6065 {
6066   if (nt == ot)
6067     return 1;
6068
6069   if (TREE_CODE (nt) == TREE_VEC)
6070     /* For member templates */
6071     return TREE_CODE (ot) == TREE_VEC && comp_template_args (ot, nt);
6072   else if (PACK_EXPANSION_P (ot))
6073     return PACK_EXPANSION_P (nt) 
6074       && template_args_equal (PACK_EXPANSION_PATTERN (ot),
6075                               PACK_EXPANSION_PATTERN (nt));
6076   else if (ARGUMENT_PACK_P (ot))
6077     {
6078       int i, len;
6079       tree opack, npack;
6080
6081       if (!ARGUMENT_PACK_P (nt))
6082         return 0;
6083
6084       opack = ARGUMENT_PACK_ARGS (ot);
6085       npack = ARGUMENT_PACK_ARGS (nt);
6086       len = TREE_VEC_LENGTH (opack);
6087       if (TREE_VEC_LENGTH (npack) != len)
6088         return 0;
6089       for (i = 0; i < len; ++i)
6090         if (!template_args_equal (TREE_VEC_ELT (opack, i),
6091                                   TREE_VEC_ELT (npack, i)))
6092           return 0;
6093       return 1;
6094     }
6095   else if (ot && TREE_CODE (ot) == ARGUMENT_PACK_SELECT)
6096     {
6097       /* We get here probably because we are in the middle of substituting
6098          into the pattern of a pack expansion. In that case the
6099          ARGUMENT_PACK_SELECT temporarily replaces the pack argument we are
6100          interested in. So we want to use the initial pack argument for
6101          the comparison.  */
6102       ot = ARGUMENT_PACK_SELECT_FROM_PACK (ot);
6103       if (nt && TREE_CODE (nt) == ARGUMENT_PACK_SELECT)
6104         nt = ARGUMENT_PACK_SELECT_FROM_PACK (nt);
6105       return template_args_equal (ot, nt);
6106     }
6107   else if (TYPE_P (nt))
6108     return TYPE_P (ot) && same_type_p (ot, nt);
6109   else if (TREE_CODE (ot) == TREE_VEC || TYPE_P (ot))
6110     return 0;
6111   else
6112     return cp_tree_equal (ot, nt);
6113 }
6114
6115 /* Returns 1 iff the OLDARGS and NEWARGS are in fact identical sets
6116    of template arguments.  Returns 0 otherwise.  */
6117
6118 int
6119 comp_template_args (tree oldargs, tree newargs)
6120 {
6121   int i;
6122
6123   if (TREE_VEC_LENGTH (oldargs) != TREE_VEC_LENGTH (newargs))
6124     return 0;
6125
6126   for (i = 0; i < TREE_VEC_LENGTH (oldargs); ++i)
6127     {
6128       tree nt = TREE_VEC_ELT (newargs, i);
6129       tree ot = TREE_VEC_ELT (oldargs, i);
6130
6131       if (! template_args_equal (ot, nt))
6132         return 0;
6133     }
6134   return 1;
6135 }
6136
6137 static void
6138 add_pending_template (tree d)
6139 {
6140   tree ti = (TYPE_P (d)
6141              ? CLASSTYPE_TEMPLATE_INFO (d)
6142              : DECL_TEMPLATE_INFO (d));
6143   struct pending_template *pt;
6144   int level;
6145
6146   if (TI_PENDING_TEMPLATE_FLAG (ti))
6147     return;
6148
6149   /* We are called both from instantiate_decl, where we've already had a
6150      tinst_level pushed, and instantiate_template, where we haven't.
6151      Compensate.  */
6152   level = !current_tinst_level || current_tinst_level->decl != d;
6153
6154   if (level)
6155     push_tinst_level (d);
6156
6157   pt = GGC_NEW (struct pending_template);
6158   pt->next = NULL;
6159   pt->tinst = current_tinst_level;
6160   if (last_pending_template)
6161     last_pending_template->next = pt;
6162   else
6163     pending_templates = pt;
6164
6165   last_pending_template = pt;
6166
6167   TI_PENDING_TEMPLATE_FLAG (ti) = 1;
6168
6169   if (level)
6170     pop_tinst_level ();
6171 }
6172
6173
6174 /* Return a TEMPLATE_ID_EXPR corresponding to the indicated FNS and
6175    ARGLIST.  Valid choices for FNS are given in the cp-tree.def
6176    documentation for TEMPLATE_ID_EXPR.  */
6177
6178 tree
6179 lookup_template_function (tree fns, tree arglist)
6180 {
6181   tree type;
6182
6183   if (fns == error_mark_node || arglist == error_mark_node)
6184     return error_mark_node;
6185
6186   gcc_assert (!arglist || TREE_CODE (arglist) == TREE_VEC);
6187   gcc_assert (fns && (is_overloaded_fn (fns)
6188                       || TREE_CODE (fns) == IDENTIFIER_NODE));
6189
6190   if (BASELINK_P (fns))
6191     {
6192       BASELINK_FUNCTIONS (fns) = build2 (TEMPLATE_ID_EXPR,
6193                                          unknown_type_node,
6194                                          BASELINK_FUNCTIONS (fns),
6195                                          arglist);
6196       return fns;
6197     }
6198
6199   type = TREE_TYPE (fns);
6200   if (TREE_CODE (fns) == OVERLOAD || !type)
6201     type = unknown_type_node;
6202
6203   return build2 (TEMPLATE_ID_EXPR, type, fns, arglist);
6204 }
6205
6206 /* Within the scope of a template class S<T>, the name S gets bound
6207    (in build_self_reference) to a TYPE_DECL for the class, not a
6208    TEMPLATE_DECL.  If DECL is a TYPE_DECL for current_class_type,
6209    or one of its enclosing classes, and that type is a template,
6210    return the associated TEMPLATE_DECL.  Otherwise, the original
6211    DECL is returned.
6212
6213    Also handle the case when DECL is a TREE_LIST of ambiguous
6214    injected-class-names from different bases.  */
6215
6216 tree
6217 maybe_get_template_decl_from_type_decl (tree decl)
6218 {
6219   if (decl == NULL_TREE)
6220     return decl;
6221
6222   /* DR 176: A lookup that finds an injected-class-name (10.2
6223      [class.member.lookup]) can result in an ambiguity in certain cases
6224      (for example, if it is found in more than one base class). If all of
6225      the injected-class-names that are found refer to specializations of
6226      the same class template, and if the name is followed by a
6227      template-argument-list, the reference refers to the class template
6228      itself and not a specialization thereof, and is not ambiguous.  */
6229   if (TREE_CODE (decl) == TREE_LIST)
6230     {
6231       tree t, tmpl = NULL_TREE;
6232       for (t = decl; t; t = TREE_CHAIN (t))
6233         {
6234           tree elt = maybe_get_template_decl_from_type_decl (TREE_VALUE (t));
6235           if (!tmpl)
6236             tmpl = elt;
6237           else if (tmpl != elt)
6238             break;
6239         }
6240       if (tmpl && t == NULL_TREE)
6241         return tmpl;
6242       else
6243         return decl;
6244     }
6245
6246   return (decl != NULL_TREE
6247           && DECL_SELF_REFERENCE_P (decl)
6248           && CLASSTYPE_TEMPLATE_INFO (TREE_TYPE (decl)))
6249     ? CLASSTYPE_TI_TEMPLATE (TREE_TYPE (decl)) : decl;
6250 }
6251
6252 /* Given an IDENTIFIER_NODE (type TEMPLATE_DECL) and a chain of
6253    parameters, find the desired type.
6254
6255    D1 is the PTYPENAME terminal, and ARGLIST is the list of arguments.
6256
6257    IN_DECL, if non-NULL, is the template declaration we are trying to
6258    instantiate.
6259
6260    If ENTERING_SCOPE is nonzero, we are about to enter the scope of
6261    the class we are looking up.
6262
6263    Issue error and warning messages under control of COMPLAIN.
6264
6265    If the template class is really a local class in a template
6266    function, then the FUNCTION_CONTEXT is the function in which it is
6267    being instantiated.
6268
6269    ??? Note that this function is currently called *twice* for each
6270    template-id: the first time from the parser, while creating the
6271    incomplete type (finish_template_type), and the second type during the
6272    real instantiation (instantiate_template_class). This is surely something
6273    that we want to avoid. It also causes some problems with argument
6274    coercion (see convert_nontype_argument for more information on this).  */
6275
6276 tree
6277 lookup_template_class (tree d1,
6278                        tree arglist,
6279                        tree in_decl,
6280                        tree context,
6281                        int entering_scope,
6282                        tsubst_flags_t complain)
6283 {
6284   tree templ = NULL_TREE, parmlist;
6285   tree t;
6286   spec_entry **slot;
6287   spec_entry *entry;
6288   spec_entry elt;
6289   hashval_t hash;
6290
6291   timevar_push (TV_NAME_LOOKUP);
6292
6293   if (TREE_CODE (d1) == IDENTIFIER_NODE)
6294     {
6295       tree value = innermost_non_namespace_value (d1);
6296       if (value && DECL_TEMPLATE_TEMPLATE_PARM_P (value))
6297         templ = value;
6298       else
6299         {
6300           if (context)
6301             push_decl_namespace (context);
6302           templ = lookup_name (d1);
6303           templ = maybe_get_template_decl_from_type_decl (templ);
6304           if (context)
6305             pop_decl_namespace ();
6306         }
6307       if (templ)
6308         context = DECL_CONTEXT (templ);
6309     }
6310   else if (TREE_CODE (d1) == TYPE_DECL && MAYBE_CLASS_TYPE_P (TREE_TYPE (d1)))
6311     {
6312       tree type = TREE_TYPE (d1);
6313
6314       /* If we are declaring a constructor, say A<T>::A<T>, we will get
6315          an implicit typename for the second A.  Deal with it.  */
6316       if (TREE_CODE (type) == TYPENAME_TYPE && TREE_TYPE (type))
6317         type = TREE_TYPE (type);
6318
6319       if (CLASSTYPE_TEMPLATE_INFO (type))
6320         {
6321           templ = CLASSTYPE_TI_TEMPLATE (type);
6322           d1 = DECL_NAME (templ);
6323         }
6324     }
6325   else if (TREE_CODE (d1) == ENUMERAL_TYPE
6326            || (TYPE_P (d1) && MAYBE_CLASS_TYPE_P (d1)))
6327     {
6328       templ = TYPE_TI_TEMPLATE (d1);
6329       d1 = DECL_NAME (templ);
6330     }
6331   else if (TREE_CODE (d1) == TEMPLATE_DECL
6332            && DECL_TEMPLATE_RESULT (d1)
6333            && TREE_CODE (DECL_TEMPLATE_RESULT (d1)) == TYPE_DECL)
6334     {
6335       templ = d1;
6336       d1 = DECL_NAME (templ);
6337       context = DECL_CONTEXT (templ);
6338     }
6339
6340   /* Issue an error message if we didn't find a template.  */
6341   if (! templ)
6342     {
6343       if (complain & tf_error)
6344         error ("%qT is not a template", d1);
6345       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6346     }
6347
6348   if (TREE_CODE (templ) != TEMPLATE_DECL
6349          /* Make sure it's a user visible template, if it was named by
6350             the user.  */
6351       || ((complain & tf_user) && !DECL_TEMPLATE_PARM_P (templ)
6352           && !PRIMARY_TEMPLATE_P (templ)))
6353     {
6354       if (complain & tf_error)
6355         {
6356           error ("non-template type %qT used as a template", d1);
6357           if (in_decl)
6358             error ("for template declaration %q+D", in_decl);
6359         }
6360       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6361     }
6362
6363   complain &= ~tf_user;
6364
6365   if (DECL_TEMPLATE_TEMPLATE_PARM_P (templ))
6366     {
6367       /* Create a new TEMPLATE_DECL and TEMPLATE_TEMPLATE_PARM node to store
6368          template arguments */
6369
6370       tree parm;
6371       tree arglist2;
6372       tree outer;
6373
6374       parmlist = DECL_INNERMOST_TEMPLATE_PARMS (templ);
6375
6376       /* Consider an example where a template template parameter declared as
6377
6378            template <class T, class U = std::allocator<T> > class TT
6379
6380          The template parameter level of T and U are one level larger than
6381          of TT.  To proper process the default argument of U, say when an
6382          instantiation `TT<int>' is seen, we need to build the full
6383          arguments containing {int} as the innermost level.  Outer levels,
6384          available when not appearing as default template argument, can be
6385          obtained from the arguments of the enclosing template.
6386
6387          Suppose that TT is later substituted with std::vector.  The above
6388          instantiation is `TT<int, std::allocator<T> >' with TT at
6389          level 1, and T at level 2, while the template arguments at level 1
6390          becomes {std::vector} and the inner level 2 is {int}.  */
6391
6392       outer = DECL_CONTEXT (templ);
6393       if (outer)
6394         outer = TI_ARGS (get_template_info (DECL_TEMPLATE_RESULT (outer)));
6395       else if (current_template_parms)
6396         /* This is an argument of the current template, so we haven't set
6397            DECL_CONTEXT yet.  */
6398         outer = current_template_args ();
6399
6400       if (outer)
6401         arglist = add_to_template_args (outer, arglist);
6402
6403       arglist2 = coerce_template_parms (parmlist, arglist, templ,
6404                                         complain,
6405                                         /*require_all_args=*/true,
6406                                         /*use_default_args=*/true);
6407       if (arglist2 == error_mark_node
6408           || (!uses_template_parms (arglist2)
6409               && check_instantiated_args (templ, arglist2, complain)))
6410         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6411
6412       parm = bind_template_template_parm (TREE_TYPE (templ), arglist2);
6413       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, parm);
6414     }
6415   else
6416     {
6417       tree template_type = TREE_TYPE (templ);
6418       tree gen_tmpl;
6419       tree type_decl;
6420       tree found = NULL_TREE;
6421       int arg_depth;
6422       int parm_depth;
6423       int is_dependent_type;
6424       int use_partial_inst_tmpl = false;
6425
6426       gen_tmpl = most_general_template (templ);
6427       parmlist = DECL_TEMPLATE_PARMS (gen_tmpl);
6428       parm_depth = TMPL_PARMS_DEPTH (parmlist);
6429       arg_depth = TMPL_ARGS_DEPTH (arglist);
6430
6431       if (arg_depth == 1 && parm_depth > 1)
6432         {
6433           /* We've been given an incomplete set of template arguments.
6434              For example, given:
6435
6436                template <class T> struct S1 {
6437                  template <class U> struct S2 {};
6438                  template <class U> struct S2<U*> {};
6439                 };
6440
6441              we will be called with an ARGLIST of `U*', but the
6442              TEMPLATE will be `template <class T> template
6443              <class U> struct S1<T>::S2'.  We must fill in the missing
6444              arguments.  */
6445           arglist
6446             = add_outermost_template_args (TYPE_TI_ARGS (TREE_TYPE (templ)),
6447                                            arglist);
6448           arg_depth = TMPL_ARGS_DEPTH (arglist);
6449         }
6450
6451       /* Now we should have enough arguments.  */
6452       gcc_assert (parm_depth == arg_depth);
6453
6454       /* From here on, we're only interested in the most general
6455          template.  */
6456
6457       /* Calculate the BOUND_ARGS.  These will be the args that are
6458          actually tsubst'd into the definition to create the
6459          instantiation.  */
6460       if (parm_depth > 1)
6461         {
6462           /* We have multiple levels of arguments to coerce, at once.  */
6463           int i;
6464           int saved_depth = TMPL_ARGS_DEPTH (arglist);
6465
6466           tree bound_args = make_tree_vec (parm_depth);
6467
6468           for (i = saved_depth,
6469                  t = DECL_TEMPLATE_PARMS (gen_tmpl);
6470                i > 0 && t != NULL_TREE;
6471                --i, t = TREE_CHAIN (t))
6472             {
6473               tree a = coerce_template_parms (TREE_VALUE (t),
6474                                               arglist, gen_tmpl,
6475                                               complain,
6476                                               /*require_all_args=*/true,
6477                                               /*use_default_args=*/true);
6478
6479               /* Don't process further if one of the levels fails.  */
6480               if (a == error_mark_node)
6481                 {
6482                   /* Restore the ARGLIST to its full size.  */
6483                   TREE_VEC_LENGTH (arglist) = saved_depth;
6484                   POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6485                 }
6486
6487               SET_TMPL_ARGS_LEVEL (bound_args, i, a);
6488
6489               /* We temporarily reduce the length of the ARGLIST so
6490                  that coerce_template_parms will see only the arguments
6491                  corresponding to the template parameters it is
6492                  examining.  */
6493               TREE_VEC_LENGTH (arglist)--;
6494             }
6495
6496           /* Restore the ARGLIST to its full size.  */
6497           TREE_VEC_LENGTH (arglist) = saved_depth;
6498
6499           arglist = bound_args;
6500         }
6501       else
6502         arglist
6503           = coerce_template_parms (INNERMOST_TEMPLATE_PARMS (parmlist),
6504                                    INNERMOST_TEMPLATE_ARGS (arglist),
6505                                    gen_tmpl,
6506                                    complain,
6507                                    /*require_all_args=*/true,
6508                                    /*use_default_args=*/true);
6509
6510       if (arglist == error_mark_node)
6511         /* We were unable to bind the arguments.  */
6512         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6513
6514       /* In the scope of a template class, explicit references to the
6515          template class refer to the type of the template, not any
6516          instantiation of it.  For example, in:
6517
6518            template <class T> class C { void f(C<T>); }
6519
6520          the `C<T>' is just the same as `C'.  Outside of the
6521          class, however, such a reference is an instantiation.  */
6522       if ((entering_scope
6523            || !PRIMARY_TEMPLATE_P (gen_tmpl)
6524            || currently_open_class (template_type))
6525           /* comp_template_args is expensive, check it last.  */
6526           && comp_template_args (TYPE_TI_ARGS (template_type),
6527                                  arglist))
6528         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, template_type);
6529
6530       /* If we already have this specialization, return it.  */
6531       elt.tmpl = gen_tmpl;
6532       elt.args = arglist;
6533       hash = hash_specialization (&elt);
6534       entry = (spec_entry *) htab_find_with_hash (type_specializations,
6535                                                   &elt, hash);
6536
6537       if (entry)
6538         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, entry->spec);
6539
6540       is_dependent_type = uses_template_parms (arglist);
6541
6542       /* If the deduced arguments are invalid, then the binding
6543          failed.  */
6544       if (!is_dependent_type
6545           && check_instantiated_args (gen_tmpl,
6546                                       INNERMOST_TEMPLATE_ARGS (arglist),
6547                                       complain))
6548         POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, error_mark_node);
6549
6550       if (!is_dependent_type
6551           && !PRIMARY_TEMPLATE_P (gen_tmpl)
6552           && !LAMBDA_TYPE_P (TREE_TYPE (gen_tmpl))
6553           && TREE_CODE (CP_DECL_CONTEXT (gen_tmpl)) == NAMESPACE_DECL)
6554         {
6555           found = xref_tag_from_type (TREE_TYPE (gen_tmpl),
6556                                       DECL_NAME (gen_tmpl),
6557                                       /*tag_scope=*/ts_global);
6558           POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, found);
6559         }
6560
6561       context = tsubst (DECL_CONTEXT (gen_tmpl), arglist,
6562                         complain, in_decl);
6563       if (!context)
6564         context = global_namespace;
6565
6566       /* Create the type.  */
6567       if (TREE_CODE (template_type) == ENUMERAL_TYPE)
6568         {
6569           if (!is_dependent_type)
6570             {
6571               set_current_access_from_decl (TYPE_NAME (template_type));
6572               t = start_enum (TYPE_IDENTIFIER (template_type),
6573                               tsubst (ENUM_UNDERLYING_TYPE (template_type),
6574                                       arglist, complain, in_decl),
6575                               SCOPED_ENUM_P (template_type));
6576             }
6577           else
6578             {
6579               /* We don't want to call start_enum for this type, since
6580                  the values for the enumeration constants may involve
6581                  template parameters.  And, no one should be interested
6582                  in the enumeration constants for such a type.  */
6583               t = cxx_make_type (ENUMERAL_TYPE);
6584               SET_SCOPED_ENUM_P (t, SCOPED_ENUM_P (template_type));
6585             }
6586         }
6587       else
6588         {
6589           t = make_class_type (TREE_CODE (template_type));
6590           CLASSTYPE_DECLARED_CLASS (t)
6591             = CLASSTYPE_DECLARED_CLASS (template_type);
6592           SET_CLASSTYPE_IMPLICIT_INSTANTIATION (t);
6593           TYPE_FOR_JAVA (t) = TYPE_FOR_JAVA (template_type);
6594
6595           /* A local class.  Make sure the decl gets registered properly.  */
6596           if (context == current_function_decl)
6597             pushtag (DECL_NAME (gen_tmpl), t, /*tag_scope=*/ts_current);
6598
6599           if (comp_template_args (CLASSTYPE_TI_ARGS (template_type), arglist))
6600             /* This instantiation is another name for the primary
6601                template type. Set the TYPE_CANONICAL field
6602                appropriately. */
6603             TYPE_CANONICAL (t) = template_type;
6604           else if (any_template_arguments_need_structural_equality_p (arglist))
6605             /* Some of the template arguments require structural
6606                equality testing, so this template class requires
6607                structural equality testing. */
6608             SET_TYPE_STRUCTURAL_EQUALITY (t);
6609         }
6610
6611       /* If we called start_enum or pushtag above, this information
6612          will already be set up.  */
6613       if (!TYPE_NAME (t))
6614         {
6615           TYPE_CONTEXT (t) = FROB_CONTEXT (context);
6616
6617           type_decl = create_implicit_typedef (DECL_NAME (gen_tmpl), t);
6618           DECL_CONTEXT (type_decl) = TYPE_CONTEXT (t);
6619           DECL_SOURCE_LOCATION (type_decl)
6620             = DECL_SOURCE_LOCATION (TYPE_STUB_DECL (template_type));
6621         }
6622       else
6623         type_decl = TYPE_NAME (t);
6624
6625       TREE_PRIVATE (type_decl)
6626         = TREE_PRIVATE (TYPE_STUB_DECL (template_type));
6627       TREE_PROTECTED (type_decl)
6628         = TREE_PROTECTED (TYPE_STUB_DECL (template_type));
6629       if (CLASSTYPE_VISIBILITY_SPECIFIED (template_type))
6630         {
6631           DECL_VISIBILITY_SPECIFIED (type_decl) = 1;
6632           DECL_VISIBILITY (type_decl) = CLASSTYPE_VISIBILITY (template_type);
6633         }
6634
6635       /* Let's consider the explicit specialization of a member
6636          of a class template specialization that is implicitely instantiated,
6637          e.g.:
6638              template<class T>
6639              struct S
6640              {
6641                template<class U> struct M {}; //#0
6642              };
6643
6644              template<>
6645              template<>
6646              struct S<int>::M<char> //#1
6647              {
6648                int i;
6649              };
6650         [temp.expl.spec]/4 says this is valid.
6651
6652         In this case, when we write:
6653         S<int>::M<char> m;
6654
6655         M is instantiated from the CLASSTYPE_TI_TEMPLATE of #1, not from
6656         the one of #0.
6657
6658         When we encounter #1, we want to store the partial instantiation
6659         of M (template<class T> S<int>::M<T>) in it's CLASSTYPE_TI_TEMPLATE.
6660
6661         For all cases other than this "explicit specialization of member of a
6662         class template", we just want to store the most general template into
6663         the CLASSTYPE_TI_TEMPLATE of M.
6664
6665         This case of "explicit specialization of member of a class template"
6666         only happens when:
6667         1/ the enclosing class is an instantiation of, and therefore not
6668         the same as, the context of the most general template, and
6669         2/ we aren't looking at the partial instantiation itself, i.e.
6670         the innermost arguments are not the same as the innermost parms of
6671         the most general template.
6672
6673         So it's only when 1/ and 2/ happens that we want to use the partial
6674         instantiation of the member template in lieu of its most general
6675         template.  */
6676
6677       if (PRIMARY_TEMPLATE_P (gen_tmpl)
6678           && TMPL_ARGS_HAVE_MULTIPLE_LEVELS (arglist)
6679           /* the enclosing class must be an instantiation...  */
6680           && CLASS_TYPE_P (context)
6681           && !same_type_p (context, DECL_CONTEXT (gen_tmpl)))
6682         {
6683           tree partial_inst_args;
6684           TREE_VEC_LENGTH (arglist)--;
6685           ++processing_template_decl;
6686           partial_inst_args =
6687             tsubst (INNERMOST_TEMPLATE_ARGS
6688                         (CLASSTYPE_TI_ARGS (TREE_TYPE (gen_tmpl))),
6689                     arglist, complain, NULL_TREE);
6690           --processing_template_decl;
6691           TREE_VEC_LENGTH (arglist)++;
6692           use_partial_inst_tmpl =
6693             /*...and we must not be looking at the partial instantiation
6694              itself. */
6695             !comp_template_args (INNERMOST_TEMPLATE_ARGS (arglist),
6696                                  partial_inst_args);
6697         }
6698
6699       if (!use_partial_inst_tmpl)
6700         /* This case is easy; there are no member templates involved.  */
6701         found = gen_tmpl;
6702       else
6703         {
6704           /* This is a full instantiation of a member template.  Find
6705              the partial instantiation of which this is an instance.  */
6706
6707           /* Temporarily reduce by one the number of levels in the ARGLIST
6708              so as to avoid comparing the last set of arguments.  */
6709           TREE_VEC_LENGTH (arglist)--;
6710           found = tsubst (gen_tmpl, arglist, complain, NULL_TREE);
6711           TREE_VEC_LENGTH (arglist)++;
6712           found = CLASSTYPE_TI_TEMPLATE (found);
6713         }
6714
6715       SET_TYPE_TEMPLATE_INFO (t, build_template_info (found, arglist));
6716
6717       elt.spec = t;
6718       slot = (spec_entry **) htab_find_slot_with_hash (type_specializations,
6719                                                        &elt, hash, INSERT);
6720       *slot = GGC_NEW (spec_entry);
6721       **slot = elt;
6722
6723       /* Note this use of the partial instantiation so we can check it
6724          later in maybe_process_partial_specialization.  */
6725       DECL_TEMPLATE_INSTANTIATIONS (templ)
6726         = tree_cons (arglist, t,
6727                      DECL_TEMPLATE_INSTANTIATIONS (templ));
6728
6729       if (TREE_CODE (t) == ENUMERAL_TYPE && !is_dependent_type)
6730         /* Now that the type has been registered on the instantiations
6731            list, we set up the enumerators.  Because the enumeration
6732            constants may involve the enumeration type itself, we make
6733            sure to register the type first, and then create the
6734            constants.  That way, doing tsubst_expr for the enumeration
6735            constants won't result in recursive calls here; we'll find
6736            the instantiation and exit above.  */
6737         tsubst_enum (template_type, t, arglist);
6738
6739       if (is_dependent_type)
6740         /* If the type makes use of template parameters, the
6741            code that generates debugging information will crash.  */
6742         DECL_IGNORED_P (TYPE_STUB_DECL (t)) = 1;
6743
6744       /* Possibly limit visibility based on template args.  */
6745       TREE_PUBLIC (type_decl) = 1;
6746       determine_visibility (type_decl);
6747
6748       POP_TIMEVAR_AND_RETURN (TV_NAME_LOOKUP, t);
6749     }
6750   timevar_pop (TV_NAME_LOOKUP);
6751 }
6752 \f
6753 struct pair_fn_data
6754 {
6755   tree_fn_t fn;
6756   void *data;
6757   /* True when we should also visit template parameters that occur in
6758      non-deduced contexts.  */
6759   bool include_nondeduced_p;
6760   struct pointer_set_t *visited;
6761 };
6762
6763 /* Called from for_each_template_parm via walk_tree.  */
6764
6765 static tree
6766 for_each_template_parm_r (tree *tp, int *walk_subtrees, void *d)
6767 {
6768   tree t = *tp;
6769   struct pair_fn_data *pfd = (struct pair_fn_data *) d;
6770   tree_fn_t fn = pfd->fn;
6771   void *data = pfd->data;
6772
6773   if (TYPE_P (t)
6774       && (pfd->include_nondeduced_p || TREE_CODE (t) != TYPENAME_TYPE)
6775       && for_each_template_parm (TYPE_CONTEXT (t), fn, data, pfd->visited,
6776                                  pfd->include_nondeduced_p))
6777     return error_mark_node;
6778
6779   switch (TREE_CODE (t))
6780     {
6781     case RECORD_TYPE:
6782       if (TYPE_PTRMEMFUNC_P (t))
6783         break;
6784       /* Fall through.  */
6785
6786     case UNION_TYPE:
6787     case ENUMERAL_TYPE:
6788       if (!TYPE_TEMPLATE_INFO (t))
6789         *walk_subtrees = 0;
6790       else if (for_each_template_parm (TI_ARGS (TYPE_TEMPLATE_INFO (t)),
6791                                        fn, data, pfd->visited, 
6792                                        pfd->include_nondeduced_p))
6793         return error_mark_node;
6794       break;
6795
6796     case INTEGER_TYPE:
6797       if (for_each_template_parm (TYPE_MIN_VALUE (t),
6798                                   fn, data, pfd->visited, 
6799                                   pfd->include_nondeduced_p)
6800           || for_each_template_parm (TYPE_MAX_VALUE (t),
6801                                      fn, data, pfd->visited,
6802                                      pfd->include_nondeduced_p))
6803         return error_mark_node;
6804       break;
6805
6806     case METHOD_TYPE:
6807       /* Since we're not going to walk subtrees, we have to do this
6808          explicitly here.  */
6809       if (for_each_template_parm (TYPE_METHOD_BASETYPE (t), fn, data,
6810                                   pfd->visited, pfd->include_nondeduced_p))
6811         return error_mark_node;
6812       /* Fall through.  */
6813
6814     case FUNCTION_TYPE:
6815       /* Check the return type.  */
6816       if (for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6817                                   pfd->include_nondeduced_p))
6818         return error_mark_node;
6819
6820       /* Check the parameter types.  Since default arguments are not
6821          instantiated until they are needed, the TYPE_ARG_TYPES may
6822          contain expressions that involve template parameters.  But,
6823          no-one should be looking at them yet.  And, once they're
6824          instantiated, they don't contain template parameters, so
6825          there's no point in looking at them then, either.  */
6826       {
6827         tree parm;
6828
6829         for (parm = TYPE_ARG_TYPES (t); parm; parm = TREE_CHAIN (parm))
6830           if (for_each_template_parm (TREE_VALUE (parm), fn, data,
6831                                       pfd->visited, pfd->include_nondeduced_p))
6832             return error_mark_node;
6833
6834         /* Since we've already handled the TYPE_ARG_TYPES, we don't
6835            want walk_tree walking into them itself.  */
6836         *walk_subtrees = 0;
6837       }
6838       break;
6839
6840     case TYPEOF_TYPE:
6841       if (pfd->include_nondeduced_p
6842           && for_each_template_parm (TYPE_FIELDS (t), fn, data,
6843                                      pfd->visited, 
6844                                      pfd->include_nondeduced_p))
6845         return error_mark_node;
6846       break;
6847
6848     case FUNCTION_DECL:
6849     case VAR_DECL:
6850       if (DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t)
6851           && for_each_template_parm (DECL_TI_ARGS (t), fn, data,
6852                                      pfd->visited, pfd->include_nondeduced_p))
6853         return error_mark_node;
6854       /* Fall through.  */
6855
6856     case PARM_DECL:
6857     case CONST_DECL:
6858       if (TREE_CODE (t) == CONST_DECL && DECL_TEMPLATE_PARM_P (t)
6859           && for_each_template_parm (DECL_INITIAL (t), fn, data,
6860                                      pfd->visited, pfd->include_nondeduced_p))
6861         return error_mark_node;
6862       if (DECL_CONTEXT (t)
6863           && pfd->include_nondeduced_p
6864           && for_each_template_parm (DECL_CONTEXT (t), fn, data,
6865                                      pfd->visited, pfd->include_nondeduced_p))
6866         return error_mark_node;
6867       break;
6868
6869     case BOUND_TEMPLATE_TEMPLATE_PARM:
6870       /* Record template parameters such as `T' inside `TT<T>'.  */
6871       if (for_each_template_parm (TYPE_TI_ARGS (t), fn, data, pfd->visited,
6872                                   pfd->include_nondeduced_p))
6873         return error_mark_node;
6874       /* Fall through.  */
6875
6876     case TEMPLATE_TEMPLATE_PARM:
6877     case TEMPLATE_TYPE_PARM:
6878     case TEMPLATE_PARM_INDEX:
6879       if (fn && (*fn)(t, data))
6880         return error_mark_node;
6881       else if (!fn)
6882         return error_mark_node;
6883       break;
6884
6885     case TEMPLATE_DECL:
6886       /* A template template parameter is encountered.  */
6887       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t)
6888           && for_each_template_parm (TREE_TYPE (t), fn, data, pfd->visited,
6889                                      pfd->include_nondeduced_p))
6890         return error_mark_node;
6891
6892       /* Already substituted template template parameter */
6893       *walk_subtrees = 0;
6894       break;
6895
6896     case TYPENAME_TYPE:
6897       if (!fn
6898           || for_each_template_parm (TYPENAME_TYPE_FULLNAME (t), fn,
6899                                      data, pfd->visited, 
6900                                      pfd->include_nondeduced_p))
6901         return error_mark_node;
6902       break;
6903
6904     case CONSTRUCTOR:
6905       if (TREE_TYPE (t) && TYPE_PTRMEMFUNC_P (TREE_TYPE (t))
6906           && pfd->include_nondeduced_p
6907           && for_each_template_parm (TYPE_PTRMEMFUNC_FN_TYPE
6908                                      (TREE_TYPE (t)), fn, data,
6909                                      pfd->visited, pfd->include_nondeduced_p))
6910         return error_mark_node;
6911       break;
6912
6913     case INDIRECT_REF:
6914     case COMPONENT_REF:
6915       /* If there's no type, then this thing must be some expression
6916          involving template parameters.  */
6917       if (!fn && !TREE_TYPE (t))
6918         return error_mark_node;
6919       break;
6920
6921     case MODOP_EXPR:
6922     case CAST_EXPR:
6923     case REINTERPRET_CAST_EXPR:
6924     case CONST_CAST_EXPR:
6925     case STATIC_CAST_EXPR:
6926     case DYNAMIC_CAST_EXPR:
6927     case ARROW_EXPR:
6928     case DOTSTAR_EXPR:
6929     case TYPEID_EXPR:
6930     case PSEUDO_DTOR_EXPR:
6931       if (!fn)
6932         return error_mark_node;
6933       break;
6934
6935     default:
6936       break;
6937     }
6938
6939   /* We didn't find any template parameters we liked.  */
6940   return NULL_TREE;
6941 }
6942
6943 /* For each TEMPLATE_TYPE_PARM, TEMPLATE_TEMPLATE_PARM,
6944    BOUND_TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX in T,
6945    call FN with the parameter and the DATA.
6946    If FN returns nonzero, the iteration is terminated, and
6947    for_each_template_parm returns 1.  Otherwise, the iteration
6948    continues.  If FN never returns a nonzero value, the value
6949    returned by for_each_template_parm is 0.  If FN is NULL, it is
6950    considered to be the function which always returns 1.
6951
6952    If INCLUDE_NONDEDUCED_P, then this routine will also visit template
6953    parameters that occur in non-deduced contexts.  When false, only
6954    visits those template parameters that can be deduced.  */
6955
6956 static int
6957 for_each_template_parm (tree t, tree_fn_t fn, void* data,
6958                         struct pointer_set_t *visited,
6959                         bool include_nondeduced_p)
6960 {
6961   struct pair_fn_data pfd;
6962   int result;
6963
6964   /* Set up.  */
6965   pfd.fn = fn;
6966   pfd.data = data;
6967   pfd.include_nondeduced_p = include_nondeduced_p;
6968
6969   /* Walk the tree.  (Conceptually, we would like to walk without
6970      duplicates, but for_each_template_parm_r recursively calls
6971      for_each_template_parm, so we would need to reorganize a fair
6972      bit to use walk_tree_without_duplicates, so we keep our own
6973      visited list.)  */
6974   if (visited)
6975     pfd.visited = visited;
6976   else
6977     pfd.visited = pointer_set_create ();
6978   result = cp_walk_tree (&t,
6979                          for_each_template_parm_r,
6980                          &pfd,
6981                          pfd.visited) != NULL_TREE;
6982
6983   /* Clean up.  */
6984   if (!visited)
6985     {
6986       pointer_set_destroy (pfd.visited);
6987       pfd.visited = 0;
6988     }
6989
6990   return result;
6991 }
6992
6993 /* Returns true if T depends on any template parameter.  */
6994
6995 int
6996 uses_template_parms (tree t)
6997 {
6998   bool dependent_p;
6999   int saved_processing_template_decl;
7000
7001   saved_processing_template_decl = processing_template_decl;
7002   if (!saved_processing_template_decl)
7003     processing_template_decl = 1;
7004   if (TYPE_P (t))
7005     dependent_p = dependent_type_p (t);
7006   else if (TREE_CODE (t) == TREE_VEC)
7007     dependent_p = any_dependent_template_arguments_p (t);
7008   else if (TREE_CODE (t) == TREE_LIST)
7009     dependent_p = (uses_template_parms (TREE_VALUE (t))
7010                    || uses_template_parms (TREE_CHAIN (t)));
7011   else if (TREE_CODE (t) == TYPE_DECL)
7012     dependent_p = dependent_type_p (TREE_TYPE (t));
7013   else if (DECL_P (t)
7014            || EXPR_P (t)
7015            || TREE_CODE (t) == TEMPLATE_PARM_INDEX
7016            || TREE_CODE (t) == OVERLOAD
7017            || TREE_CODE (t) == BASELINK
7018            || TREE_CODE (t) == IDENTIFIER_NODE
7019            || TREE_CODE (t) == TRAIT_EXPR
7020            || TREE_CODE (t) == CONSTRUCTOR
7021            || CONSTANT_CLASS_P (t))
7022     dependent_p = (type_dependent_expression_p (t)
7023                    || value_dependent_expression_p (t));
7024   else
7025     {
7026       gcc_assert (t == error_mark_node);
7027       dependent_p = false;
7028     }
7029
7030   processing_template_decl = saved_processing_template_decl;
7031
7032   return dependent_p;
7033 }
7034
7035 /* Returns true if T depends on any template parameter with level LEVEL.  */
7036
7037 int
7038 uses_template_parms_level (tree t, int level)
7039 {
7040   return for_each_template_parm (t, template_parm_this_level_p, &level, NULL,
7041                                  /*include_nondeduced_p=*/true);
7042 }
7043
7044 static int tinst_depth;
7045 extern int max_tinst_depth;
7046 #ifdef GATHER_STATISTICS
7047 int depth_reached;
7048 #endif
7049 static int tinst_level_tick;
7050 static int last_template_error_tick;
7051
7052 /* We're starting to instantiate D; record the template instantiation context
7053    for diagnostics and to restore it later.  */
7054
7055 int
7056 push_tinst_level (tree d)
7057 {
7058   struct tinst_level *new_level;
7059
7060   if (tinst_depth >= max_tinst_depth)
7061     {
7062       /* If the instantiation in question still has unbound template parms,
7063          we don't really care if we can't instantiate it, so just return.
7064          This happens with base instantiation for implicit `typename'.  */
7065       if (uses_template_parms (d))
7066         return 0;
7067
7068       last_template_error_tick = tinst_level_tick;
7069       error ("template instantiation depth exceeds maximum of %d (use "
7070              "-ftemplate-depth= to increase the maximum) instantiating %qD",
7071              max_tinst_depth, d);
7072
7073       print_instantiation_context ();
7074
7075       return 0;
7076     }
7077
7078   new_level = GGC_NEW (struct tinst_level);
7079   new_level->decl = d;
7080   new_level->locus = input_location;
7081   new_level->in_system_header_p = in_system_header;
7082   new_level->next = current_tinst_level;
7083   current_tinst_level = new_level;
7084
7085   ++tinst_depth;
7086 #ifdef GATHER_STATISTICS
7087   if (tinst_depth > depth_reached)
7088     depth_reached = tinst_depth;
7089 #endif
7090
7091   ++tinst_level_tick;
7092   return 1;
7093 }
7094
7095 /* We're done instantiating this template; return to the instantiation
7096    context.  */
7097
7098 void
7099 pop_tinst_level (void)
7100 {
7101   /* Restore the filename and line number stashed away when we started
7102      this instantiation.  */
7103   input_location = current_tinst_level->locus;
7104   current_tinst_level = current_tinst_level->next;
7105   --tinst_depth;
7106   ++tinst_level_tick;
7107 }
7108
7109 /* We're instantiating a deferred template; restore the template
7110    instantiation context in which the instantiation was requested, which
7111    is one step out from LEVEL.  Return the corresponding DECL or TYPE.  */
7112
7113 static tree
7114 reopen_tinst_level (struct tinst_level *level)
7115 {
7116   struct tinst_level *t;
7117
7118   tinst_depth = 0;
7119   for (t = level; t; t = t->next)
7120     ++tinst_depth;
7121
7122   current_tinst_level = level;
7123   pop_tinst_level ();
7124   return level->decl;
7125 }
7126
7127 /* Returns the TINST_LEVEL which gives the original instantiation
7128    context.  */
7129
7130 struct tinst_level *
7131 outermost_tinst_level (void)
7132 {
7133   struct tinst_level *level = current_tinst_level;
7134   if (level)
7135     while (level->next)
7136       level = level->next;
7137   return level;
7138 }
7139
7140 /* Returns TRUE if PARM is a parameter of the template TEMPL.  */
7141
7142 bool
7143 parameter_of_template_p (tree parm, tree templ)
7144 {
7145   tree parms;
7146   int i;
7147
7148   if (!parm || !templ)
7149     return false;
7150
7151   gcc_assert (DECL_TEMPLATE_PARM_P (parm));
7152   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7153
7154   parms = DECL_TEMPLATE_PARMS (templ);
7155   parms = INNERMOST_TEMPLATE_PARMS (parms);
7156
7157   for (i = 0; i < TREE_VEC_LENGTH (parms); ++i)
7158     if (parm == TREE_VALUE (TREE_VEC_ELT (parms, i)))
7159       return true;
7160
7161   return false;
7162 }
7163
7164 /* DECL is a friend FUNCTION_DECL or TEMPLATE_DECL.  ARGS is the
7165    vector of template arguments, as for tsubst.
7166
7167    Returns an appropriate tsubst'd friend declaration.  */
7168
7169 static tree
7170 tsubst_friend_function (tree decl, tree args)
7171 {
7172   tree new_friend;
7173
7174   if (TREE_CODE (decl) == FUNCTION_DECL
7175       && DECL_TEMPLATE_INSTANTIATION (decl)
7176       && TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
7177     /* This was a friend declared with an explicit template
7178        argument list, e.g.:
7179
7180        friend void f<>(T);
7181
7182        to indicate that f was a template instantiation, not a new
7183        function declaration.  Now, we have to figure out what
7184        instantiation of what template.  */
7185     {
7186       tree template_id, arglist, fns;
7187       tree new_args;
7188       tree tmpl;
7189       tree ns = decl_namespace_context (TYPE_MAIN_DECL (current_class_type));
7190
7191       /* Friend functions are looked up in the containing namespace scope.
7192          We must enter that scope, to avoid finding member functions of the
7193          current class with same name.  */
7194       push_nested_namespace (ns);
7195       fns = tsubst_expr (DECL_TI_TEMPLATE (decl), args,
7196                          tf_warning_or_error, NULL_TREE,
7197                          /*integral_constant_expression_p=*/false);
7198       pop_nested_namespace (ns);
7199       arglist = tsubst (DECL_TI_ARGS (decl), args,
7200                         tf_warning_or_error, NULL_TREE);
7201       template_id = lookup_template_function (fns, arglist);
7202
7203       new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7204       tmpl = determine_specialization (template_id, new_friend,
7205                                        &new_args,
7206                                        /*need_member_template=*/0,
7207                                        TREE_VEC_LENGTH (args),
7208                                        tsk_none);
7209       return instantiate_template (tmpl, new_args, tf_error);
7210     }
7211
7212   new_friend = tsubst (decl, args, tf_warning_or_error, NULL_TREE);
7213
7214   /* The NEW_FRIEND will look like an instantiation, to the
7215      compiler, but is not an instantiation from the point of view of
7216      the language.  For example, we might have had:
7217
7218      template <class T> struct S {
7219        template <class U> friend void f(T, U);
7220      };
7221
7222      Then, in S<int>, template <class U> void f(int, U) is not an
7223      instantiation of anything.  */
7224   if (new_friend == error_mark_node)
7225     return error_mark_node;
7226
7227   DECL_USE_TEMPLATE (new_friend) = 0;
7228   if (TREE_CODE (decl) == TEMPLATE_DECL)
7229     {
7230       DECL_USE_TEMPLATE (DECL_TEMPLATE_RESULT (new_friend)) = 0;
7231       DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (new_friend))
7232         = DECL_SAVED_TREE (DECL_TEMPLATE_RESULT (decl));
7233     }
7234
7235   /* The mangled name for the NEW_FRIEND is incorrect.  The function
7236      is not a template instantiation and should not be mangled like
7237      one.  Therefore, we forget the mangling here; we'll recompute it
7238      later if we need it.  */
7239   if (TREE_CODE (new_friend) != TEMPLATE_DECL)
7240     {
7241       SET_DECL_RTL (new_friend, NULL_RTX);
7242       SET_DECL_ASSEMBLER_NAME (new_friend, NULL_TREE);
7243     }
7244
7245   if (DECL_NAMESPACE_SCOPE_P (new_friend))
7246     {
7247       tree old_decl;
7248       tree new_friend_template_info;
7249       tree new_friend_result_template_info;
7250       tree ns;
7251       int  new_friend_is_defn;
7252
7253       /* We must save some information from NEW_FRIEND before calling
7254          duplicate decls since that function will free NEW_FRIEND if
7255          possible.  */
7256       new_friend_template_info = DECL_TEMPLATE_INFO (new_friend);
7257       new_friend_is_defn =
7258             (DECL_INITIAL (DECL_TEMPLATE_RESULT
7259                            (template_for_substitution (new_friend)))
7260              != NULL_TREE);
7261       if (TREE_CODE (new_friend) == TEMPLATE_DECL)
7262         {
7263           /* This declaration is a `primary' template.  */
7264           DECL_PRIMARY_TEMPLATE (new_friend) = new_friend;
7265
7266           new_friend_result_template_info
7267             = DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (new_friend));
7268         }
7269       else
7270         new_friend_result_template_info = NULL_TREE;
7271
7272       /* Make the init_value nonzero so pushdecl knows this is a defn.  */
7273       if (new_friend_is_defn)
7274         DECL_INITIAL (new_friend) = error_mark_node;
7275
7276       /* Inside pushdecl_namespace_level, we will push into the
7277          current namespace. However, the friend function should go
7278          into the namespace of the template.  */
7279       ns = decl_namespace_context (new_friend);
7280       push_nested_namespace (ns);
7281       old_decl = pushdecl_namespace_level (new_friend, /*is_friend=*/true);
7282       pop_nested_namespace (ns);
7283
7284       if (old_decl == error_mark_node)
7285         return error_mark_node;
7286
7287       if (old_decl != new_friend)
7288         {
7289           /* This new friend declaration matched an existing
7290              declaration.  For example, given:
7291
7292                template <class T> void f(T);
7293                template <class U> class C {
7294                  template <class T> friend void f(T) {}
7295                };
7296
7297              the friend declaration actually provides the definition
7298              of `f', once C has been instantiated for some type.  So,
7299              old_decl will be the out-of-class template declaration,
7300              while new_friend is the in-class definition.
7301
7302              But, if `f' was called before this point, the
7303              instantiation of `f' will have DECL_TI_ARGS corresponding
7304              to `T' but not to `U', references to which might appear
7305              in the definition of `f'.  Previously, the most general
7306              template for an instantiation of `f' was the out-of-class
7307              version; now it is the in-class version.  Therefore, we
7308              run through all specialization of `f', adding to their
7309              DECL_TI_ARGS appropriately.  In particular, they need a
7310              new set of outer arguments, corresponding to the
7311              arguments for this class instantiation.
7312
7313              The same situation can arise with something like this:
7314
7315                friend void f(int);
7316                template <class T> class C {
7317                  friend void f(T) {}
7318                };
7319
7320              when `C<int>' is instantiated.  Now, `f(int)' is defined
7321              in the class.  */
7322
7323           if (!new_friend_is_defn)
7324             /* On the other hand, if the in-class declaration does
7325                *not* provide a definition, then we don't want to alter
7326                existing definitions.  We can just leave everything
7327                alone.  */
7328             ;
7329           else
7330             {
7331               tree new_template = TI_TEMPLATE (new_friend_template_info);
7332               tree new_args = TI_ARGS (new_friend_template_info);
7333
7334               /* Overwrite whatever template info was there before, if
7335                  any, with the new template information pertaining to
7336                  the declaration.  */
7337               DECL_TEMPLATE_INFO (old_decl) = new_friend_template_info;
7338
7339               if (TREE_CODE (old_decl) != TEMPLATE_DECL)
7340                 {
7341                   /* We should have called reregister_specialization in
7342                      duplicate_decls.  */
7343                   gcc_assert (retrieve_specialization (new_template,
7344                                                        new_args, 0)
7345                               == old_decl);
7346
7347                   /* Instantiate it if the global has already been used.  */
7348                   if (DECL_ODR_USED (old_decl))
7349                     instantiate_decl (old_decl, /*defer_ok=*/true,
7350                                       /*expl_inst_class_mem_p=*/false);
7351                 }
7352               else
7353                 {
7354                   tree t;
7355
7356                   /* Indicate that the old function template is a partial
7357                      instantiation.  */
7358                   DECL_TEMPLATE_INFO (DECL_TEMPLATE_RESULT (old_decl))
7359                     = new_friend_result_template_info;
7360
7361                   gcc_assert (new_template
7362                               == most_general_template (new_template));
7363                   gcc_assert (new_template != old_decl);
7364
7365                   /* Reassign any specializations already in the hash table
7366                      to the new more general template, and add the
7367                      additional template args.  */
7368                   for (t = DECL_TEMPLATE_INSTANTIATIONS (old_decl);
7369                        t != NULL_TREE;
7370                        t = TREE_CHAIN (t))
7371                     {
7372                       tree spec = TREE_VALUE (t);
7373                       spec_entry elt;
7374
7375                       elt.tmpl = old_decl;
7376                       elt.args = DECL_TI_ARGS (spec);
7377                       elt.spec = NULL_TREE;
7378
7379                       htab_remove_elt (decl_specializations, &elt);
7380
7381                       DECL_TI_ARGS (spec)
7382                         = add_outermost_template_args (new_args,
7383                                                        DECL_TI_ARGS (spec));
7384
7385                       register_specialization
7386                         (spec, new_template, DECL_TI_ARGS (spec), true, 0);
7387
7388                     }
7389                   DECL_TEMPLATE_INSTANTIATIONS (old_decl) = NULL_TREE;
7390                 }
7391             }
7392
7393           /* The information from NEW_FRIEND has been merged into OLD_DECL
7394              by duplicate_decls.  */
7395           new_friend = old_decl;
7396         }
7397     }
7398   else
7399     {
7400       tree context = DECL_CONTEXT (new_friend);
7401       bool dependent_p;
7402
7403       /* In the code
7404            template <class T> class C {
7405              template <class U> friend void C1<U>::f (); // case 1
7406              friend void C2<T>::f ();                    // case 2
7407            };
7408          we only need to make sure CONTEXT is a complete type for
7409          case 2.  To distinguish between the two cases, we note that
7410          CONTEXT of case 1 remains dependent type after tsubst while
7411          this isn't true for case 2.  */
7412       ++processing_template_decl;
7413       dependent_p = dependent_type_p (context);
7414       --processing_template_decl;
7415
7416       if (!dependent_p
7417           && !complete_type_or_else (context, NULL_TREE))
7418         return error_mark_node;
7419
7420       if (COMPLETE_TYPE_P (context))
7421         {
7422           /* Check to see that the declaration is really present, and,
7423              possibly obtain an improved declaration.  */
7424           tree fn = check_classfn (context,
7425                                    new_friend, NULL_TREE);
7426
7427           if (fn)
7428             new_friend = fn;
7429         }
7430     }
7431
7432   return new_friend;
7433 }
7434
7435 /* FRIEND_TMPL is a friend TEMPLATE_DECL.  ARGS is the vector of
7436    template arguments, as for tsubst.
7437
7438    Returns an appropriate tsubst'd friend type or error_mark_node on
7439    failure.  */
7440
7441 static tree
7442 tsubst_friend_class (tree friend_tmpl, tree args)
7443 {
7444   tree friend_type;
7445   tree tmpl;
7446   tree context;
7447
7448   context = DECL_CONTEXT (friend_tmpl);
7449
7450   if (context)
7451     {
7452       if (TREE_CODE (context) == NAMESPACE_DECL)
7453         push_nested_namespace (context);
7454       else
7455         push_nested_class (tsubst (context, args, tf_none, NULL_TREE));
7456     }
7457
7458   /* Look for a class template declaration.  We look for hidden names
7459      because two friend declarations of the same template are the
7460      same.  For example, in:
7461
7462        struct A { 
7463          template <typename> friend class F;
7464        };
7465        template <typename> struct B { 
7466          template <typename> friend class F;
7467        };
7468
7469      both F templates are the same.  */
7470   tmpl = lookup_name_real (DECL_NAME (friend_tmpl), 0, 0,
7471                            /*block_p=*/true, 0, 
7472                            LOOKUP_COMPLAIN | LOOKUP_HIDDEN);
7473
7474   /* But, if we don't find one, it might be because we're in a
7475      situation like this:
7476
7477        template <class T>
7478        struct S {
7479          template <class U>
7480          friend struct S;
7481        };
7482
7483      Here, in the scope of (say) S<int>, `S' is bound to a TYPE_DECL
7484      for `S<int>', not the TEMPLATE_DECL.  */
7485   if (!tmpl || !DECL_CLASS_TEMPLATE_P (tmpl))
7486     {
7487       tmpl = lookup_name_prefer_type (DECL_NAME (friend_tmpl), 1);
7488       tmpl = maybe_get_template_decl_from_type_decl (tmpl);
7489     }
7490
7491   if (tmpl && DECL_CLASS_TEMPLATE_P (tmpl))
7492     {
7493       /* The friend template has already been declared.  Just
7494          check to see that the declarations match, and install any new
7495          default parameters.  We must tsubst the default parameters,
7496          of course.  We only need the innermost template parameters
7497          because that is all that redeclare_class_template will look
7498          at.  */
7499       if (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (friend_tmpl))
7500           > TMPL_ARGS_DEPTH (args))
7501         {
7502           tree parms;
7503           location_t saved_input_location;
7504           parms = tsubst_template_parms (DECL_TEMPLATE_PARMS (friend_tmpl),
7505                                          args, tf_warning_or_error);
7506
7507           saved_input_location = input_location;
7508           input_location = DECL_SOURCE_LOCATION (friend_tmpl);
7509           redeclare_class_template (TREE_TYPE (tmpl), parms);
7510           input_location = saved_input_location;
7511           
7512         }
7513
7514       friend_type = TREE_TYPE (tmpl);
7515     }
7516   else
7517     {
7518       /* The friend template has not already been declared.  In this
7519          case, the instantiation of the template class will cause the
7520          injection of this template into the global scope.  */
7521       tmpl = tsubst (friend_tmpl, args, tf_warning_or_error, NULL_TREE);
7522       if (tmpl == error_mark_node)
7523         return error_mark_node;
7524
7525       /* The new TMPL is not an instantiation of anything, so we
7526          forget its origins.  We don't reset CLASSTYPE_TI_TEMPLATE for
7527          the new type because that is supposed to be the corresponding
7528          template decl, i.e., TMPL.  */
7529       DECL_USE_TEMPLATE (tmpl) = 0;
7530       DECL_TEMPLATE_INFO (tmpl) = NULL_TREE;
7531       CLASSTYPE_USE_TEMPLATE (TREE_TYPE (tmpl)) = 0;
7532       CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl))
7533         = INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (TREE_TYPE (tmpl)));
7534
7535       /* Inject this template into the global scope.  */
7536       friend_type = TREE_TYPE (pushdecl_top_level_maybe_friend (tmpl, true));
7537     }
7538
7539   if (context)
7540     {
7541       if (TREE_CODE (context) == NAMESPACE_DECL)
7542         pop_nested_namespace (context);
7543       else
7544         pop_nested_class ();
7545     }
7546
7547   return friend_type;
7548 }
7549
7550 /* Returns zero if TYPE cannot be completed later due to circularity.
7551    Otherwise returns one.  */
7552
7553 static int
7554 can_complete_type_without_circularity (tree type)
7555 {
7556   if (type == NULL_TREE || type == error_mark_node)
7557     return 0;
7558   else if (COMPLETE_TYPE_P (type))
7559     return 1;
7560   else if (TREE_CODE (type) == ARRAY_TYPE && TYPE_DOMAIN (type))
7561     return can_complete_type_without_circularity (TREE_TYPE (type));
7562   else if (CLASS_TYPE_P (type)
7563            && TYPE_BEING_DEFINED (TYPE_MAIN_VARIANT (type)))
7564     return 0;
7565   else
7566     return 1;
7567 }
7568
7569 /* Apply any attributes which had to be deferred until instantiation
7570    time.  DECL_P, ATTRIBUTES and ATTR_FLAGS are as cplus_decl_attributes;
7571    ARGS, COMPLAIN, IN_DECL are as tsubst.  */
7572
7573 static void
7574 apply_late_template_attributes (tree *decl_p, tree attributes, int attr_flags,
7575                                 tree args, tsubst_flags_t complain, tree in_decl)
7576 {
7577   tree last_dep = NULL_TREE;
7578   tree t;
7579   tree *p;
7580
7581   for (t = attributes; t; t = TREE_CHAIN (t))
7582     if (ATTR_IS_DEPENDENT (t))
7583       {
7584         last_dep = t;
7585         attributes = copy_list (attributes);
7586         break;
7587       }
7588
7589   if (DECL_P (*decl_p))
7590     {
7591       if (TREE_TYPE (*decl_p) == error_mark_node)
7592         return;
7593       p = &DECL_ATTRIBUTES (*decl_p);
7594     }
7595   else
7596     p = &TYPE_ATTRIBUTES (*decl_p);
7597
7598   if (last_dep)
7599     {
7600       tree late_attrs = NULL_TREE;
7601       tree *q = &late_attrs;
7602
7603       for (*p = attributes; *p; )
7604         {
7605           t = *p;
7606           if (ATTR_IS_DEPENDENT (t))
7607             {
7608               *p = TREE_CHAIN (t);
7609               TREE_CHAIN (t) = NULL_TREE;
7610               /* If the first attribute argument is an identifier, don't
7611                  pass it through tsubst.  Attributes like mode, format,
7612                  cleanup and several target specific attributes expect it
7613                  unmodified.  */
7614               if (TREE_VALUE (t)
7615                   && TREE_CODE (TREE_VALUE (t)) == TREE_LIST
7616                   && TREE_VALUE (TREE_VALUE (t))
7617                   && (TREE_CODE (TREE_VALUE (TREE_VALUE (t)))
7618                       == IDENTIFIER_NODE))
7619                 {
7620                   tree chain
7621                     = tsubst_expr (TREE_CHAIN (TREE_VALUE (t)), args, complain,
7622                                    in_decl,
7623                                    /*integral_constant_expression_p=*/false);
7624                   if (chain != TREE_CHAIN (TREE_VALUE (t)))
7625                     TREE_VALUE (t)
7626                       = tree_cons (NULL_TREE, TREE_VALUE (TREE_VALUE (t)),
7627                                    chain);
7628                 }
7629               else
7630                 TREE_VALUE (t)
7631                   = tsubst_expr (TREE_VALUE (t), args, complain, in_decl,
7632                                  /*integral_constant_expression_p=*/false);
7633               *q = t;
7634               q = &TREE_CHAIN (t);
7635             }
7636           else
7637             p = &TREE_CHAIN (t);
7638         }
7639
7640       cplus_decl_attributes (decl_p, late_attrs, attr_flags);
7641     }
7642 }
7643
7644 /* Perform (or defer) access check for typedefs that were referenced
7645    from within the template TMPL code.
7646    This is a subroutine of instantiate_template and instantiate_class_template.
7647    TMPL is the template to consider and TARGS is the list of arguments of
7648    that template.  */
7649
7650 static void
7651 perform_typedefs_access_check (tree tmpl, tree targs)
7652 {
7653   location_t saved_location;
7654   int i;
7655   qualified_typedef_usage_t *iter;
7656
7657   if (!tmpl
7658       || (!CLASS_TYPE_P (tmpl)
7659           && TREE_CODE (tmpl) != FUNCTION_DECL))
7660     return;
7661
7662   saved_location = input_location;
7663   for (i = 0;
7664        VEC_iterate (qualified_typedef_usage_t,
7665                     get_types_needing_access_check (tmpl),
7666                     i, iter);
7667         ++i)
7668     {
7669       tree type_decl = iter->typedef_decl;
7670       tree type_scope = iter->context;
7671
7672       if (!type_decl || !type_scope || !CLASS_TYPE_P (type_scope))
7673         continue;
7674
7675       if (uses_template_parms (type_decl))
7676         type_decl = tsubst (type_decl, targs, tf_error, NULL_TREE);
7677       if (uses_template_parms (type_scope))
7678         type_scope = tsubst (type_scope, targs, tf_error, NULL_TREE);
7679
7680       /* Make access check error messages point to the location
7681          of the use of the typedef.  */
7682       input_location = iter->locus;
7683       perform_or_defer_access_check (TYPE_BINFO (type_scope),
7684                                      type_decl, type_decl);
7685     }
7686     input_location = saved_location;
7687 }
7688
7689 tree
7690 instantiate_class_template (tree type)
7691 {
7692   tree templ, args, pattern, t, member;
7693   tree typedecl;
7694   tree pbinfo;
7695   tree base_list;
7696   unsigned int saved_maximum_field_alignment;
7697
7698   if (type == error_mark_node)
7699     return error_mark_node;
7700
7701   if (TYPE_BEING_DEFINED (type)
7702       || COMPLETE_TYPE_P (type)
7703       || uses_template_parms (type))
7704     return type;
7705
7706   /* Figure out which template is being instantiated.  */
7707   templ = most_general_template (CLASSTYPE_TI_TEMPLATE (type));
7708   gcc_assert (TREE_CODE (templ) == TEMPLATE_DECL);
7709
7710   /* Determine what specialization of the original template to
7711      instantiate.  */
7712   t = most_specialized_class (type, templ);
7713   if (t == error_mark_node)
7714     {
7715       TYPE_BEING_DEFINED (type) = 1;
7716       return error_mark_node;
7717     }
7718   else if (t)
7719     {
7720       /* This TYPE is actually an instantiation of a partial
7721          specialization.  We replace the innermost set of ARGS with
7722          the arguments appropriate for substitution.  For example,
7723          given:
7724
7725            template <class T> struct S {};
7726            template <class T> struct S<T*> {};
7727
7728          and supposing that we are instantiating S<int*>, ARGS will
7729          presently be {int*} -- but we need {int}.  */
7730       pattern = TREE_TYPE (t);
7731       args = TREE_PURPOSE (t);
7732     }
7733   else
7734     {
7735       pattern = TREE_TYPE (templ);
7736       args = CLASSTYPE_TI_ARGS (type);
7737     }
7738
7739   /* If the template we're instantiating is incomplete, then clearly
7740      there's nothing we can do.  */
7741   if (!COMPLETE_TYPE_P (pattern))
7742     return type;
7743
7744   /* If we've recursively instantiated too many templates, stop.  */
7745   if (! push_tinst_level (type))
7746     return type;
7747
7748   /* Now we're really doing the instantiation.  Mark the type as in
7749      the process of being defined.  */
7750   TYPE_BEING_DEFINED (type) = 1;
7751
7752   /* We may be in the middle of deferred access check.  Disable
7753      it now.  */
7754   push_deferring_access_checks (dk_no_deferred);
7755
7756   push_to_top_level ();
7757   /* Use #pragma pack from the template context.  */
7758   saved_maximum_field_alignment = maximum_field_alignment;
7759   maximum_field_alignment = TYPE_PRECISION (pattern);
7760
7761   SET_CLASSTYPE_INTERFACE_UNKNOWN (type);
7762
7763   /* Set the input location to the most specialized template definition.
7764      This is needed if tsubsting causes an error.  */
7765   typedecl = TYPE_MAIN_DECL (pattern);
7766   input_location = DECL_SOURCE_LOCATION (typedecl);
7767
7768   TYPE_HAS_USER_CONSTRUCTOR (type) = TYPE_HAS_USER_CONSTRUCTOR (pattern);
7769   TYPE_HAS_NEW_OPERATOR (type) = TYPE_HAS_NEW_OPERATOR (pattern);
7770   TYPE_HAS_ARRAY_NEW_OPERATOR (type) = TYPE_HAS_ARRAY_NEW_OPERATOR (pattern);
7771   TYPE_GETS_DELETE (type) = TYPE_GETS_DELETE (pattern);
7772   TYPE_HAS_ASSIGN_REF (type) = TYPE_HAS_ASSIGN_REF (pattern);
7773   TYPE_HAS_CONST_ASSIGN_REF (type) = TYPE_HAS_CONST_ASSIGN_REF (pattern);
7774   TYPE_HAS_INIT_REF (type) = TYPE_HAS_INIT_REF (pattern);
7775   TYPE_HAS_CONST_INIT_REF (type) = TYPE_HAS_CONST_INIT_REF (pattern);
7776   TYPE_HAS_DEFAULT_CONSTRUCTOR (type) = TYPE_HAS_DEFAULT_CONSTRUCTOR (pattern);
7777   TYPE_HAS_CONVERSION (type) = TYPE_HAS_CONVERSION (pattern);
7778   TYPE_PACKED (type) = TYPE_PACKED (pattern);
7779   TYPE_ALIGN (type) = TYPE_ALIGN (pattern);
7780   TYPE_USER_ALIGN (type) = TYPE_USER_ALIGN (pattern);
7781   TYPE_FOR_JAVA (type) = TYPE_FOR_JAVA (pattern); /* For libjava's JArray<T> */
7782   if (ANON_AGGR_TYPE_P (pattern))
7783     SET_ANON_AGGR_TYPE_P (type);
7784   if (CLASSTYPE_VISIBILITY_SPECIFIED (pattern))
7785     {
7786       CLASSTYPE_VISIBILITY_SPECIFIED (type) = 1;
7787       CLASSTYPE_VISIBILITY (type) = CLASSTYPE_VISIBILITY (pattern);
7788     }
7789
7790   pbinfo = TYPE_BINFO (pattern);
7791
7792   /* We should never instantiate a nested class before its enclosing
7793      class; we need to look up the nested class by name before we can
7794      instantiate it, and that lookup should instantiate the enclosing
7795      class.  */
7796   gcc_assert (!DECL_CLASS_SCOPE_P (TYPE_MAIN_DECL (pattern))
7797               || COMPLETE_TYPE_P (TYPE_CONTEXT (type))
7798               || TYPE_BEING_DEFINED (TYPE_CONTEXT (type)));
7799
7800   base_list = NULL_TREE;
7801   if (BINFO_N_BASE_BINFOS (pbinfo))
7802     {
7803       tree pbase_binfo;
7804       tree context = TYPE_CONTEXT (type);
7805       tree pushed_scope;
7806       int i;
7807
7808       /* We must enter the scope containing the type, as that is where
7809          the accessibility of types named in dependent bases are
7810          looked up from.  */
7811       pushed_scope = push_scope (context ? context : global_namespace);
7812
7813       /* Substitute into each of the bases to determine the actual
7814          basetypes.  */
7815       for (i = 0; BINFO_BASE_ITERATE (pbinfo, i, pbase_binfo); i++)
7816         {
7817           tree base;
7818           tree access = BINFO_BASE_ACCESS (pbinfo, i);
7819           tree expanded_bases = NULL_TREE;
7820           int idx, len = 1;
7821
7822           if (PACK_EXPANSION_P (BINFO_TYPE (pbase_binfo)))
7823             {
7824               expanded_bases = 
7825                 tsubst_pack_expansion (BINFO_TYPE (pbase_binfo),
7826                                        args, tf_error, NULL_TREE);
7827               if (expanded_bases == error_mark_node)
7828                 continue;
7829
7830               len = TREE_VEC_LENGTH (expanded_bases);
7831             }
7832
7833           for (idx = 0; idx < len; idx++)
7834             {
7835               if (expanded_bases)
7836                 /* Extract the already-expanded base class.  */
7837                 base = TREE_VEC_ELT (expanded_bases, idx);
7838               else
7839                 /* Substitute to figure out the base class.  */
7840                 base = tsubst (BINFO_TYPE (pbase_binfo), args, tf_error, 
7841                                NULL_TREE);
7842
7843               if (base == error_mark_node)
7844                 continue;
7845
7846               base_list = tree_cons (access, base, base_list);
7847               if (BINFO_VIRTUAL_P (pbase_binfo))
7848                 TREE_TYPE (base_list) = integer_type_node;
7849             }
7850         }
7851
7852       /* The list is now in reverse order; correct that.  */
7853       base_list = nreverse (base_list);
7854
7855       if (pushed_scope)
7856         pop_scope (pushed_scope);
7857     }
7858   /* Now call xref_basetypes to set up all the base-class
7859      information.  */
7860   xref_basetypes (type, base_list);
7861
7862   apply_late_template_attributes (&type, TYPE_ATTRIBUTES (pattern),
7863                                   (int) ATTR_FLAG_TYPE_IN_PLACE,
7864                                   args, tf_error, NULL_TREE);
7865
7866   /* Now that our base classes are set up, enter the scope of the
7867      class, so that name lookups into base classes, etc. will work
7868      correctly.  This is precisely analogous to what we do in
7869      begin_class_definition when defining an ordinary non-template
7870      class, except we also need to push the enclosing classes.  */
7871   push_nested_class (type);
7872
7873   /* Now members are processed in the order of declaration.  */
7874   for (member = CLASSTYPE_DECL_LIST (pattern);
7875        member; member = TREE_CHAIN (member))
7876     {
7877       tree t = TREE_VALUE (member);
7878
7879       if (TREE_PURPOSE (member))
7880         {
7881           if (TYPE_P (t))
7882             {
7883               /* Build new CLASSTYPE_NESTED_UTDS.  */
7884
7885               tree newtag;
7886               bool class_template_p;
7887
7888               class_template_p = (TREE_CODE (t) != ENUMERAL_TYPE
7889                                   && TYPE_LANG_SPECIFIC (t)
7890                                   && CLASSTYPE_IS_TEMPLATE (t));
7891               /* If the member is a class template, then -- even after
7892                  substitution -- there may be dependent types in the
7893                  template argument list for the class.  We increment
7894                  PROCESSING_TEMPLATE_DECL so that dependent_type_p, as
7895                  that function will assume that no types are dependent
7896                  when outside of a template.  */
7897               if (class_template_p)
7898                 ++processing_template_decl;
7899               newtag = tsubst (t, args, tf_error, NULL_TREE);
7900               if (class_template_p)
7901                 --processing_template_decl;
7902               if (newtag == error_mark_node)
7903                 continue;
7904
7905               if (TREE_CODE (newtag) != ENUMERAL_TYPE)
7906                 {
7907                   tree name = TYPE_IDENTIFIER (t);
7908
7909                   if (class_template_p)
7910                     /* Unfortunately, lookup_template_class sets
7911                        CLASSTYPE_IMPLICIT_INSTANTIATION for a partial
7912                        instantiation (i.e., for the type of a member
7913                        template class nested within a template class.)
7914                        This behavior is required for
7915                        maybe_process_partial_specialization to work
7916                        correctly, but is not accurate in this case;
7917                        the TAG is not an instantiation of anything.
7918                        (The corresponding TEMPLATE_DECL is an
7919                        instantiation, but the TYPE is not.) */
7920                     CLASSTYPE_USE_TEMPLATE (newtag) = 0;
7921
7922                   /* Now, we call pushtag to put this NEWTAG into the scope of
7923                      TYPE.  We first set up the IDENTIFIER_TYPE_VALUE to avoid
7924                      pushtag calling push_template_decl.  We don't have to do
7925                      this for enums because it will already have been done in
7926                      tsubst_enum.  */
7927                   if (name)
7928                     SET_IDENTIFIER_TYPE_VALUE (name, newtag);
7929                   pushtag (name, newtag, /*tag_scope=*/ts_current);
7930                 }
7931             }
7932           else if (TREE_CODE (t) == FUNCTION_DECL
7933                    || DECL_FUNCTION_TEMPLATE_P (t))
7934             {
7935               /* Build new TYPE_METHODS.  */
7936               tree r;
7937
7938               if (TREE_CODE (t) == TEMPLATE_DECL)
7939                 ++processing_template_decl;
7940               r = tsubst (t, args, tf_error, NULL_TREE);
7941               if (TREE_CODE (t) == TEMPLATE_DECL)
7942                 --processing_template_decl;
7943               set_current_access_from_decl (r);
7944               finish_member_declaration (r);
7945             }
7946           else
7947             {
7948               /* Build new TYPE_FIELDS.  */
7949               if (TREE_CODE (t) == STATIC_ASSERT)
7950                 {
7951                   tree condition = 
7952                     tsubst_expr (STATIC_ASSERT_CONDITION (t), args, 
7953                                  tf_warning_or_error, NULL_TREE,
7954                                  /*integral_constant_expression_p=*/true);
7955                   finish_static_assert (condition,
7956                                         STATIC_ASSERT_MESSAGE (t), 
7957                                         STATIC_ASSERT_SOURCE_LOCATION (t),
7958                                         /*member_p=*/true);
7959                 }
7960               else if (TREE_CODE (t) != CONST_DECL)
7961                 {
7962                   tree r;
7963
7964                   /* The file and line for this declaration, to
7965                      assist in error message reporting.  Since we
7966                      called push_tinst_level above, we don't need to
7967                      restore these.  */
7968                   input_location = DECL_SOURCE_LOCATION (t);
7969
7970                   if (TREE_CODE (t) == TEMPLATE_DECL)
7971                     ++processing_template_decl;
7972                   r = tsubst (t, args, tf_warning_or_error, NULL_TREE);
7973                   if (TREE_CODE (t) == TEMPLATE_DECL)
7974                     --processing_template_decl;
7975                   if (TREE_CODE (r) == VAR_DECL)
7976                     {
7977                       /* In [temp.inst]:
7978
7979                            [t]he initialization (and any associated
7980                            side-effects) of a static data member does
7981                            not occur unless the static data member is
7982                            itself used in a way that requires the
7983                            definition of the static data member to
7984                            exist.
7985
7986                          Therefore, we do not substitute into the
7987                          initialized for the static data member here.  */
7988                       finish_static_data_member_decl
7989                         (r,
7990                          /*init=*/NULL_TREE,
7991                          /*init_const_expr_p=*/false,
7992                          /*asmspec_tree=*/NULL_TREE,
7993                          /*flags=*/0);
7994                       if (DECL_INITIALIZED_IN_CLASS_P (r))
7995                         check_static_variable_definition (r, TREE_TYPE (r));
7996                     }
7997                   else if (TREE_CODE (r) == FIELD_DECL)
7998                     {
7999                       /* Determine whether R has a valid type and can be
8000                          completed later.  If R is invalid, then it is
8001                          replaced by error_mark_node so that it will not be
8002                          added to TYPE_FIELDS.  */
8003                       tree rtype = TREE_TYPE (r);
8004                       if (can_complete_type_without_circularity (rtype))
8005                         complete_type (rtype);
8006
8007                       if (!COMPLETE_TYPE_P (rtype))
8008                         {
8009                           cxx_incomplete_type_error (r, rtype);
8010                           r = error_mark_node;
8011                         }
8012                     }
8013
8014                   /* If it is a TYPE_DECL for a class-scoped ENUMERAL_TYPE,
8015                      such a thing will already have been added to the field
8016                      list by tsubst_enum in finish_member_declaration in the
8017                      CLASSTYPE_NESTED_UTDS case above.  */
8018                   if (!(TREE_CODE (r) == TYPE_DECL
8019                         && TREE_CODE (TREE_TYPE (r)) == ENUMERAL_TYPE
8020                         && DECL_ARTIFICIAL (r)))
8021                     {
8022                       set_current_access_from_decl (r);
8023                       finish_member_declaration (r);
8024                     }
8025                 }
8026             }
8027         }
8028       else
8029         {
8030           if (TYPE_P (t) || DECL_CLASS_TEMPLATE_P (t))
8031             {
8032               /* Build new CLASSTYPE_FRIEND_CLASSES.  */
8033
8034               tree friend_type = t;
8035               bool adjust_processing_template_decl = false;
8036
8037               if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8038                 {
8039                   /* template <class T> friend class C;  */
8040                   friend_type = tsubst_friend_class (friend_type, args);
8041                   adjust_processing_template_decl = true;
8042                 }
8043               else if (TREE_CODE (friend_type) == UNBOUND_CLASS_TEMPLATE)
8044                 {
8045                   /* template <class T> friend class C::D;  */
8046                   friend_type = tsubst (friend_type, args,
8047                                         tf_warning_or_error, NULL_TREE);
8048                   if (TREE_CODE (friend_type) == TEMPLATE_DECL)
8049                     friend_type = TREE_TYPE (friend_type);
8050                   adjust_processing_template_decl = true;
8051                 }
8052               else if (TREE_CODE (friend_type) == TYPENAME_TYPE)
8053                 {
8054                   /* This could be either
8055
8056                        friend class T::C;
8057
8058                      when dependent_type_p is false or
8059
8060                        template <class U> friend class T::C;
8061
8062                      otherwise.  */
8063                   friend_type = tsubst (friend_type, args,
8064                                         tf_warning_or_error, NULL_TREE);
8065                   /* Bump processing_template_decl for correct
8066                      dependent_type_p calculation.  */
8067                   ++processing_template_decl;
8068                   if (dependent_type_p (friend_type))
8069                     adjust_processing_template_decl = true;
8070                   --processing_template_decl;
8071                 }
8072               else if (!CLASSTYPE_USE_TEMPLATE (friend_type)
8073                        && hidden_name_p (TYPE_NAME (friend_type)))
8074                 {
8075                   /* friend class C;
8076
8077                      where C hasn't been declared yet.  Let's lookup name
8078                      from namespace scope directly, bypassing any name that
8079                      come from dependent base class.  */
8080                   tree ns = decl_namespace_context (TYPE_MAIN_DECL (friend_type));
8081
8082                   /* The call to xref_tag_from_type does injection for friend
8083                      classes.  */
8084                   push_nested_namespace (ns);
8085                   friend_type =
8086                     xref_tag_from_type (friend_type, NULL_TREE,
8087                                         /*tag_scope=*/ts_current);
8088                   pop_nested_namespace (ns);
8089                 }
8090               else if (uses_template_parms (friend_type))
8091                 /* friend class C<T>;  */
8092                 friend_type = tsubst (friend_type, args,
8093                                       tf_warning_or_error, NULL_TREE);
8094               /* Otherwise it's
8095
8096                    friend class C;
8097
8098                  where C is already declared or
8099
8100                    friend class C<int>;
8101
8102                  We don't have to do anything in these cases.  */
8103
8104               if (adjust_processing_template_decl)
8105                 /* Trick make_friend_class into realizing that the friend
8106                    we're adding is a template, not an ordinary class.  It's
8107                    important that we use make_friend_class since it will
8108                    perform some error-checking and output cross-reference
8109                    information.  */
8110                 ++processing_template_decl;
8111
8112               if (friend_type != error_mark_node)
8113                 make_friend_class (type, friend_type, /*complain=*/false);
8114
8115               if (adjust_processing_template_decl)
8116                 --processing_template_decl;
8117             }
8118           else
8119             {
8120               /* Build new DECL_FRIENDLIST.  */
8121               tree r;
8122
8123               /* The file and line for this declaration, to
8124                  assist in error message reporting.  Since we
8125                  called push_tinst_level above, we don't need to
8126                  restore these.  */
8127               input_location = DECL_SOURCE_LOCATION (t);
8128
8129               if (TREE_CODE (t) == TEMPLATE_DECL)
8130                 {
8131                   ++processing_template_decl;
8132                   push_deferring_access_checks (dk_no_check);
8133                 }
8134
8135               r = tsubst_friend_function (t, args);
8136               add_friend (type, r, /*complain=*/false);
8137               if (TREE_CODE (t) == TEMPLATE_DECL)
8138                 {
8139                   pop_deferring_access_checks ();
8140                   --processing_template_decl;
8141                 }
8142             }
8143         }
8144     }
8145
8146   /* Set the file and line number information to whatever is given for
8147      the class itself.  This puts error messages involving generated
8148      implicit functions at a predictable point, and the same point
8149      that would be used for non-template classes.  */
8150   input_location = DECL_SOURCE_LOCATION (typedecl);
8151
8152   unreverse_member_declarations (type);
8153   finish_struct_1 (type);
8154   TYPE_BEING_DEFINED (type) = 0;
8155
8156   /* Now that the class is complete, instantiate default arguments for
8157      any member functions.  We don't do this earlier because the
8158      default arguments may reference members of the class.  */
8159   if (!PRIMARY_TEMPLATE_P (templ))
8160     for (t = TYPE_METHODS (type); t; t = TREE_CHAIN (t))
8161       if (TREE_CODE (t) == FUNCTION_DECL
8162           /* Implicitly generated member functions will not have template
8163              information; they are not instantiations, but instead are
8164              created "fresh" for each instantiation.  */
8165           && DECL_TEMPLATE_INFO (t))
8166         tsubst_default_arguments (t);
8167
8168   /* Some typedefs referenced from within the template code need to be access
8169      checked at template instantiation time, i.e now. These types were
8170      added to the template at parsing time. Let's get those and perform
8171      the access checks then.  */
8172   perform_typedefs_access_check (pattern, args);
8173   perform_deferred_access_checks ();
8174   pop_nested_class ();
8175   maximum_field_alignment = saved_maximum_field_alignment;
8176   pop_from_top_level ();
8177   pop_deferring_access_checks ();
8178   pop_tinst_level ();
8179
8180   /* The vtable for a template class can be emitted in any translation
8181      unit in which the class is instantiated.  When there is no key
8182      method, however, finish_struct_1 will already have added TYPE to
8183      the keyed_classes list.  */
8184   if (TYPE_CONTAINS_VPTR_P (type) && CLASSTYPE_KEY_METHOD (type))
8185     keyed_classes = tree_cons (NULL_TREE, type, keyed_classes);
8186
8187   return type;
8188 }
8189
8190 static tree
8191 tsubst_template_arg (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8192 {
8193   tree r;
8194
8195   if (!t)
8196     r = t;
8197   else if (TYPE_P (t))
8198     r = tsubst (t, args, complain, in_decl);
8199   else
8200     {
8201       r = tsubst_expr (t, args, complain, in_decl,
8202                        /*integral_constant_expression_p=*/true);
8203       r = fold_non_dependent_expr (r);
8204     }
8205   return r;
8206 }
8207
8208 /* Give a chain SPEC_PARM of PARM_DECLs, pack them into a
8209    NONTYPE_ARGUMENT_PACK.  */
8210
8211 static tree
8212 make_fnparm_pack (tree spec_parm)
8213 {
8214   /* Collect all of the extra "packed" parameters into an
8215      argument pack.  */
8216   tree parmvec;
8217   tree parmtypevec;
8218   tree argpack = make_node (NONTYPE_ARGUMENT_PACK);
8219   tree argtypepack = cxx_make_type (TYPE_ARGUMENT_PACK);
8220   int i, len = list_length (spec_parm);
8221
8222   /* Fill in PARMVEC and PARMTYPEVEC with all of the parameters.  */
8223   parmvec = make_tree_vec (len);
8224   parmtypevec = make_tree_vec (len);
8225   for (i = 0; i < len; i++, spec_parm = TREE_CHAIN (spec_parm))
8226     {
8227       TREE_VEC_ELT (parmvec, i) = spec_parm;
8228       TREE_VEC_ELT (parmtypevec, i) = TREE_TYPE (spec_parm);
8229     }
8230
8231   /* Build the argument packs.  */
8232   SET_ARGUMENT_PACK_ARGS (argpack, parmvec);
8233   SET_ARGUMENT_PACK_ARGS (argtypepack, parmtypevec);
8234   TREE_TYPE (argpack) = argtypepack;
8235
8236   return argpack;
8237 }        
8238
8239 /* Substitute ARGS into T, which is an pack expansion
8240    (i.e. TYPE_PACK_EXPANSION or EXPR_PACK_EXPANSION). Returns a
8241    TREE_VEC with the substituted arguments, a PACK_EXPANSION_* node
8242    (if only a partial substitution could be performed) or
8243    ERROR_MARK_NODE if there was an error.  */
8244 tree
8245 tsubst_pack_expansion (tree t, tree args, tsubst_flags_t complain,
8246                        tree in_decl)
8247 {
8248   tree pattern;
8249   tree pack, packs = NULL_TREE, unsubstituted_packs = NULL_TREE;
8250   int i, len = -1;
8251   tree result;
8252   int incomplete = 0;
8253   bool very_local_specializations = false;
8254
8255   gcc_assert (PACK_EXPANSION_P (t));
8256   pattern = PACK_EXPANSION_PATTERN (t);
8257
8258   /* Determine the argument packs that will instantiate the parameter
8259      packs used in the expansion expression. While we're at it,
8260      compute the number of arguments to be expanded and make sure it
8261      is consistent.  */
8262   for (pack = PACK_EXPANSION_PARAMETER_PACKS (t); pack; 
8263        pack = TREE_CHAIN (pack))
8264     {
8265       tree parm_pack = TREE_VALUE (pack);
8266       tree arg_pack = NULL_TREE;
8267       tree orig_arg = NULL_TREE;
8268
8269       if (TREE_CODE (parm_pack) == PARM_DECL)
8270         {
8271           arg_pack = retrieve_local_specialization (parm_pack);
8272           if (arg_pack == NULL_TREE)
8273             {
8274               /* This can happen for a parameter name used later in a function
8275                  declaration (such as in a late-specified return type).  Just
8276                  make a dummy decl, since it's only used for its type.  */
8277               gcc_assert (cp_unevaluated_operand != 0);
8278               arg_pack = tsubst_decl (parm_pack, args, complain);
8279               arg_pack = make_fnparm_pack (arg_pack);
8280             }
8281         }
8282       else
8283         {
8284           int level, idx, levels;
8285           template_parm_level_and_index (parm_pack, &level, &idx);
8286
8287           levels = TMPL_ARGS_DEPTH (args);
8288           if (level <= levels)
8289             arg_pack = TMPL_ARG (args, level, idx);
8290         }
8291
8292       orig_arg = arg_pack;
8293       if (arg_pack && TREE_CODE (arg_pack) == ARGUMENT_PACK_SELECT)
8294         arg_pack = ARGUMENT_PACK_SELECT_FROM_PACK (arg_pack);
8295       
8296       if (arg_pack && !ARGUMENT_PACK_P (arg_pack))
8297         /* This can only happen if we forget to expand an argument
8298            pack somewhere else. Just return an error, silently.  */
8299         {
8300           result = make_tree_vec (1);
8301           TREE_VEC_ELT (result, 0) = error_mark_node;
8302           return result;
8303         }
8304
8305       if (arg_pack
8306           && TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack)) == 1
8307           && PACK_EXPANSION_P (TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0)))
8308         {
8309           tree expansion = TREE_VEC_ELT (ARGUMENT_PACK_ARGS (arg_pack), 0);
8310           tree pattern = PACK_EXPANSION_PATTERN (expansion);
8311           if ((TYPE_P (pattern) && same_type_p (pattern, parm_pack))
8312               || (!TYPE_P (pattern) && cp_tree_equal (parm_pack, pattern)))
8313             /* The argument pack that the parameter maps to is just an
8314                expansion of the parameter itself, such as one would
8315                find in the implicit typedef of a class inside the
8316                class itself.  Consider this parameter "unsubstituted",
8317                so that we will maintain the outer pack expansion.  */
8318             arg_pack = NULL_TREE;
8319         }
8320           
8321       if (arg_pack)
8322         {
8323           int my_len = 
8324             TREE_VEC_LENGTH (ARGUMENT_PACK_ARGS (arg_pack));
8325
8326           /* It's all-or-nothing with incomplete argument packs.  */
8327           if (incomplete && !ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8328             return error_mark_node;
8329           
8330           if (ARGUMENT_PACK_INCOMPLETE_P (arg_pack))
8331             incomplete = 1;
8332
8333           if (len < 0)
8334             len = my_len;
8335           else if (len != my_len)
8336             {
8337               if (incomplete)
8338                 /* We got explicit args for some packs but not others;
8339                    do nothing now and try again after deduction.  */
8340                 return t;
8341               if (TREE_CODE (t) == TYPE_PACK_EXPANSION)
8342                 error ("mismatched argument pack lengths while expanding "
8343                        "%<%T%>",
8344                        pattern);
8345               else
8346                 error ("mismatched argument pack lengths while expanding "
8347                        "%<%E%>",
8348                        pattern);
8349               return error_mark_node;
8350             }
8351
8352           /* Keep track of the parameter packs and their corresponding
8353              argument packs.  */
8354           packs = tree_cons (parm_pack, arg_pack, packs);
8355           TREE_TYPE (packs) = orig_arg;
8356         }
8357       else
8358         /* We can't substitute for this parameter pack.  */
8359         unsubstituted_packs = tree_cons (TREE_PURPOSE (pack),
8360                                          TREE_VALUE (pack),
8361                                          unsubstituted_packs);
8362     }
8363
8364   /* We cannot expand this expansion expression, because we don't have
8365      all of the argument packs we need. Substitute into the pattern
8366      and return a PACK_EXPANSION_*. The caller will need to deal with
8367      that.  */
8368   if (unsubstituted_packs)
8369     {
8370       tree new_pat;
8371       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8372         new_pat = tsubst_expr (pattern, args, complain, in_decl,
8373                                /*integral_constant_expression_p=*/false);
8374       else
8375         new_pat = tsubst (pattern, args, complain, in_decl);
8376       return make_pack_expansion (new_pat);
8377     }
8378
8379   /* We could not find any argument packs that work.  */
8380   if (len < 0)
8381     return error_mark_node;
8382
8383   if (!local_specializations)
8384     {
8385       /* We're in a late-specified return type, so we don't have a local
8386          specializations table.  Create one for doing this expansion.  */
8387       very_local_specializations = true;
8388       local_specializations = htab_create (37,
8389                                            hash_local_specialization,
8390                                            eq_local_specializations,
8391                                            NULL);
8392     }
8393
8394   /* For each argument in each argument pack, substitute into the
8395      pattern.  */
8396   result = make_tree_vec (len + incomplete);
8397   for (i = 0; i < len + incomplete; ++i)
8398     {
8399       /* For parameter pack, change the substitution of the parameter
8400          pack to the ith argument in its argument pack, then expand
8401          the pattern.  */
8402       for (pack = packs; pack; pack = TREE_CHAIN (pack))
8403         {
8404           tree parm = TREE_PURPOSE (pack);
8405
8406           if (TREE_CODE (parm) == PARM_DECL)
8407             {
8408               /* Select the Ith argument from the pack.  */
8409               tree arg = make_node (ARGUMENT_PACK_SELECT);
8410               ARGUMENT_PACK_SELECT_FROM_PACK (arg) = TREE_VALUE (pack);
8411               ARGUMENT_PACK_SELECT_INDEX (arg) = i;
8412               mark_used (parm);
8413               register_local_specialization (arg, parm);
8414             }
8415           else
8416             {
8417               tree value = parm;
8418               int idx, level;
8419               template_parm_level_and_index (parm, &level, &idx);
8420               
8421               if (i < len) 
8422                 {
8423                   /* Select the Ith argument from the pack. */
8424                   value = make_node (ARGUMENT_PACK_SELECT);
8425                   ARGUMENT_PACK_SELECT_FROM_PACK (value) = TREE_VALUE (pack);
8426                   ARGUMENT_PACK_SELECT_INDEX (value) = i;
8427                 }
8428
8429               /* Update the corresponding argument.  */
8430               TMPL_ARG (args, level, idx) = value;
8431             }
8432         }
8433
8434       /* Substitute into the PATTERN with the altered arguments.  */
8435       if (TREE_CODE (t) == EXPR_PACK_EXPANSION)
8436         TREE_VEC_ELT (result, i) = 
8437           tsubst_expr (pattern, args, complain, in_decl,
8438                        /*integral_constant_expression_p=*/false);
8439       else
8440         TREE_VEC_ELT (result, i) = tsubst (pattern, args, complain, in_decl);
8441
8442       if (i == len)
8443         /* When we have incomplete argument packs, the last "expanded"
8444            result is itself a pack expansion, which allows us
8445            to deduce more arguments.  */
8446         TREE_VEC_ELT (result, i) = 
8447           make_pack_expansion (TREE_VEC_ELT (result, i));
8448
8449       if (TREE_VEC_ELT (result, i) == error_mark_node)
8450         {
8451           result = error_mark_node;
8452           break;
8453         }
8454     }
8455
8456   /* Update ARGS to restore the substitution from parameter packs to
8457      their argument packs.  */
8458   for (pack = packs; pack; pack = TREE_CHAIN (pack))
8459     {
8460       tree parm = TREE_PURPOSE (pack);
8461
8462       if (TREE_CODE (parm) == PARM_DECL)
8463         register_local_specialization (TREE_TYPE (pack), parm);
8464       else
8465         {
8466           int idx, level;
8467           template_parm_level_and_index (parm, &level, &idx);
8468           
8469           /* Update the corresponding argument.  */
8470           if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
8471             TREE_VEC_ELT (TREE_VEC_ELT (args, level -1 ), idx) =
8472               TREE_TYPE (pack);
8473           else
8474             TREE_VEC_ELT (args, idx) = TREE_TYPE (pack);
8475         }
8476     }
8477
8478   if (very_local_specializations)
8479     {
8480       htab_delete (local_specializations);
8481       local_specializations = NULL;
8482     }
8483   
8484   return result;
8485 }
8486
8487 /* Given PARM_DECL PARM, find the corresponding PARM_DECL in the template
8488    TMPL.  We do this using DECL_PARM_INDEX, which should work even with
8489    parameter packs; all parms generated from a function parameter pack will
8490    have the same DECL_PARM_INDEX.  */
8491
8492 tree
8493 get_pattern_parm (tree parm, tree tmpl)
8494 {
8495   tree pattern = DECL_TEMPLATE_RESULT (tmpl);
8496   tree patparm;
8497
8498   if (DECL_ARTIFICIAL (parm))
8499     {
8500       for (patparm = DECL_ARGUMENTS (pattern);
8501            patparm; patparm = TREE_CHAIN (patparm))
8502         if (DECL_ARTIFICIAL (patparm)
8503             && DECL_NAME (parm) == DECL_NAME (patparm))
8504           break;
8505     }
8506   else
8507     {
8508       patparm = FUNCTION_FIRST_USER_PARM (DECL_TEMPLATE_RESULT (tmpl));
8509       patparm = chain_index (DECL_PARM_INDEX (parm)-1, patparm);
8510       gcc_assert (DECL_PARM_INDEX (patparm)
8511                   == DECL_PARM_INDEX (parm));
8512     }
8513
8514   return patparm;
8515 }
8516
8517 /* Substitute ARGS into the vector or list of template arguments T.  */
8518
8519 static tree
8520 tsubst_template_args (tree t, tree args, tsubst_flags_t complain, tree in_decl)
8521 {
8522   tree orig_t = t;
8523   int len = TREE_VEC_LENGTH (t);
8524   int need_new = 0, i, expanded_len_adjust = 0, out;
8525   tree *elts = (tree *) alloca (len * sizeof (tree));
8526
8527   for (i = 0; i < len; i++)
8528     {
8529       tree orig_arg = TREE_VEC_ELT (t, i);
8530       tree new_arg;
8531
8532       if (TREE_CODE (orig_arg) == TREE_VEC)
8533         new_arg = tsubst_template_args (orig_arg, args, complain, in_decl);
8534       else if (PACK_EXPANSION_P (orig_arg))
8535         {
8536           /* Substitute into an expansion expression.  */
8537           new_arg = tsubst_pack_expansion (orig_arg, args, complain, in_decl);
8538
8539           if (TREE_CODE (new_arg) == TREE_VEC)
8540             /* Add to the expanded length adjustment the number of
8541                expanded arguments. We subtract one from this
8542                measurement, because the argument pack expression
8543                itself is already counted as 1 in
8544                LEN. EXPANDED_LEN_ADJUST can actually be negative, if
8545                the argument pack is empty.  */
8546             expanded_len_adjust += TREE_VEC_LENGTH (new_arg) - 1;
8547         }
8548       else if (ARGUMENT_PACK_P (orig_arg))
8549         {
8550           /* Substitute into each of the arguments.  */
8551           new_arg = TYPE_P (orig_arg)
8552             ? cxx_make_type (TREE_CODE (orig_arg))
8553             : make_node (TREE_CODE (orig_arg));
8554           
8555           SET_ARGUMENT_PACK_ARGS (
8556             new_arg,
8557             tsubst_template_args (ARGUMENT_PACK_ARGS (orig_arg),
8558                                   args, complain, in_decl));
8559
8560           if (ARGUMENT_PACK_ARGS (new_arg) == error_mark_node)
8561             new_arg = error_mark_node;
8562
8563           if (TREE_CODE (new_arg) == NONTYPE_ARGUMENT_PACK) {
8564             TREE_TYPE (new_arg) = tsubst (TREE_TYPE (orig_arg), args,
8565                                           complain, in_decl);
8566             TREE_CONSTANT (new_arg) = TREE_CONSTANT (orig_arg);
8567
8568             if (TREE_TYPE (new_arg) == error_mark_node)
8569               new_arg = error_mark_node;
8570           }
8571         }
8572       else
8573         new_arg = tsubst_template_arg (orig_arg, args, complain, in_decl);
8574
8575       if (new_arg == error_mark_node)
8576         return error_mark_node;
8577
8578       elts[i] = new_arg;
8579       if (new_arg != orig_arg)
8580         need_new = 1;
8581     }
8582
8583   if (!need_new)
8584     return t;
8585
8586   /* Make space for the expanded arguments coming from template
8587      argument packs.  */
8588   t = make_tree_vec (len + expanded_len_adjust);
8589   /* ORIG_T can contain TREE_VECs. That happens if ORIG_T contains the
8590      arguments for a member template.
8591      In that case each TREE_VEC in ORIG_T represents a level of template
8592      arguments, and ORIG_T won't carry any non defaulted argument count.
8593      It will rather be the nested TREE_VECs that will carry one.
8594      In other words, ORIG_T carries a non defaulted argument count only
8595      if it doesn't contain any nested TREE_VEC.  */
8596   if (NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t))
8597     {
8598       int count = GET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (orig_t);
8599       count += expanded_len_adjust;
8600       SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (t, count);
8601     }
8602   for (i = 0, out = 0; i < len; i++)
8603     {
8604       if ((PACK_EXPANSION_P (TREE_VEC_ELT (orig_t, i))
8605            || ARGUMENT_PACK_P (TREE_VEC_ELT (orig_t, i)))
8606           && TREE_CODE (elts[i]) == TREE_VEC)
8607         {
8608           int idx;
8609
8610           /* Now expand the template argument pack "in place".  */
8611           for (idx = 0; idx < TREE_VEC_LENGTH (elts[i]); idx++, out++)
8612             TREE_VEC_ELT (t, out) = TREE_VEC_ELT (elts[i], idx);
8613         }
8614       else
8615         {
8616           TREE_VEC_ELT (t, out) = elts[i];
8617           out++;
8618         }
8619     }
8620
8621   return t;
8622 }
8623
8624 /* Return the result of substituting ARGS into the template parameters
8625    given by PARMS.  If there are m levels of ARGS and m + n levels of
8626    PARMS, then the result will contain n levels of PARMS.  For
8627    example, if PARMS is `template <class T> template <class U>
8628    template <T*, U, class V>' and ARGS is {{int}, {double}} then the
8629    result will be `template <int*, double, class V>'.  */
8630
8631 static tree
8632 tsubst_template_parms (tree parms, tree args, tsubst_flags_t complain)
8633 {
8634   tree r = NULL_TREE;
8635   tree* new_parms;
8636
8637   /* When substituting into a template, we must set
8638      PROCESSING_TEMPLATE_DECL as the template parameters may be
8639      dependent if they are based on one-another, and the dependency
8640      predicates are short-circuit outside of templates.  */
8641   ++processing_template_decl;
8642
8643   for (new_parms = &r;
8644        TMPL_PARMS_DEPTH (parms) > TMPL_ARGS_DEPTH (args);
8645        new_parms = &(TREE_CHAIN (*new_parms)),
8646          parms = TREE_CHAIN (parms))
8647     {
8648       tree new_vec =
8649         make_tree_vec (TREE_VEC_LENGTH (TREE_VALUE (parms)));
8650       int i;
8651
8652       for (i = 0; i < TREE_VEC_LENGTH (new_vec); ++i)
8653         {
8654           tree tuple;
8655           tree default_value;
8656           tree parm_decl;
8657
8658           if (parms == error_mark_node)
8659             continue;
8660
8661           tuple = TREE_VEC_ELT (TREE_VALUE (parms), i);
8662
8663           if (tuple == error_mark_node)
8664             continue;
8665
8666           default_value = TREE_PURPOSE (tuple);
8667           parm_decl = TREE_VALUE (tuple);
8668
8669           parm_decl = tsubst (parm_decl, args, complain, NULL_TREE);
8670           if (TREE_CODE (parm_decl) == PARM_DECL
8671               && invalid_nontype_parm_type_p (TREE_TYPE (parm_decl), complain))
8672             parm_decl = error_mark_node;
8673           default_value = tsubst_template_arg (default_value, args,
8674                                                complain, NULL_TREE);
8675
8676           tuple = build_tree_list (default_value, parm_decl);
8677           TREE_VEC_ELT (new_vec, i) = tuple;
8678         }
8679
8680       *new_parms =
8681         tree_cons (size_int (TMPL_PARMS_DEPTH (parms)
8682                              - TMPL_ARGS_DEPTH (args)),
8683                    new_vec, NULL_TREE);
8684     }
8685
8686   --processing_template_decl;
8687
8688   return r;
8689 }
8690
8691 /* Substitute the ARGS into the indicated aggregate (or enumeration)
8692    type T.  If T is not an aggregate or enumeration type, it is
8693    handled as if by tsubst.  IN_DECL is as for tsubst.  If
8694    ENTERING_SCOPE is nonzero, T is the context for a template which
8695    we are presently tsubst'ing.  Return the substituted value.  */
8696
8697 static tree
8698 tsubst_aggr_type (tree t,
8699                   tree args,
8700                   tsubst_flags_t complain,
8701                   tree in_decl,
8702                   int entering_scope)
8703 {
8704   if (t == NULL_TREE)
8705     return NULL_TREE;
8706
8707   switch (TREE_CODE (t))
8708     {
8709     case RECORD_TYPE:
8710       if (TYPE_PTRMEMFUNC_P (t))
8711         return tsubst (TYPE_PTRMEMFUNC_FN_TYPE (t), args, complain, in_decl);
8712
8713       /* Else fall through.  */
8714     case ENUMERAL_TYPE:
8715     case UNION_TYPE:
8716       if (TYPE_TEMPLATE_INFO (t) && uses_template_parms (t))
8717         {
8718           tree argvec;
8719           tree context;
8720           tree r;
8721           int saved_unevaluated_operand;
8722           int saved_inhibit_evaluation_warnings;
8723
8724           /* In "sizeof(X<I>)" we need to evaluate "I".  */
8725           saved_unevaluated_operand = cp_unevaluated_operand;
8726           cp_unevaluated_operand = 0;
8727           saved_inhibit_evaluation_warnings = c_inhibit_evaluation_warnings;
8728           c_inhibit_evaluation_warnings = 0;
8729
8730           /* First, determine the context for the type we are looking
8731              up.  */
8732           context = TYPE_CONTEXT (t);
8733           if (context)
8734             {
8735               context = tsubst_aggr_type (context, args, complain,
8736                                           in_decl, /*entering_scope=*/1);
8737               /* If context is a nested class inside a class template,
8738                  it may still need to be instantiated (c++/33959).  */
8739               if (TYPE_P (context))
8740                 context = complete_type (context);
8741             }
8742
8743           /* Then, figure out what arguments are appropriate for the
8744              type we are trying to find.  For example, given:
8745
8746                template <class T> struct S;
8747                template <class T, class U> void f(T, U) { S<U> su; }
8748
8749              and supposing that we are instantiating f<int, double>,
8750              then our ARGS will be {int, double}, but, when looking up
8751              S we only want {double}.  */
8752           argvec = tsubst_template_args (TYPE_TI_ARGS (t), args,
8753                                          complain, in_decl);
8754           if (argvec == error_mark_node)
8755             r = error_mark_node;
8756           else
8757             {
8758               r = lookup_template_class (t, argvec, in_decl, context,
8759                                          entering_scope, complain);
8760               r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
8761             }
8762
8763           cp_unevaluated_operand = saved_unevaluated_operand;
8764           c_inhibit_evaluation_warnings = saved_inhibit_evaluation_warnings;
8765
8766           return r;
8767         }
8768       else
8769         /* This is not a template type, so there's nothing to do.  */
8770         return t;
8771
8772     default:
8773       return tsubst (t, args, complain, in_decl);
8774     }
8775 }
8776
8777 /* Substitute into the default argument ARG (a default argument for
8778    FN), which has the indicated TYPE.  */
8779
8780 tree
8781 tsubst_default_argument (tree fn, tree type, tree arg)
8782 {
8783   tree saved_class_ptr = NULL_TREE;
8784   tree saved_class_ref = NULL_TREE;
8785
8786   /* This default argument came from a template.  Instantiate the
8787      default argument here, not in tsubst.  In the case of
8788      something like:
8789
8790        template <class T>
8791        struct S {
8792          static T t();
8793          void f(T = t());
8794        };
8795
8796      we must be careful to do name lookup in the scope of S<T>,
8797      rather than in the current class.  */
8798   push_access_scope (fn);
8799   /* The "this" pointer is not valid in a default argument.  */
8800   if (cfun)
8801     {
8802       saved_class_ptr = current_class_ptr;
8803       cp_function_chain->x_current_class_ptr = NULL_TREE;
8804       saved_class_ref = current_class_ref;
8805       cp_function_chain->x_current_class_ref = NULL_TREE;
8806     }
8807
8808   push_deferring_access_checks(dk_no_deferred);
8809   /* The default argument expression may cause implicitly defined
8810      member functions to be synthesized, which will result in garbage
8811      collection.  We must treat this situation as if we were within
8812      the body of function so as to avoid collecting live data on the
8813      stack.  */
8814   ++function_depth;
8815   arg = tsubst_expr (arg, DECL_TI_ARGS (fn),
8816                      tf_warning_or_error, NULL_TREE,
8817                      /*integral_constant_expression_p=*/false);
8818   --function_depth;
8819   pop_deferring_access_checks();
8820
8821   /* Restore the "this" pointer.  */
8822   if (cfun)
8823     {
8824       cp_function_chain->x_current_class_ptr = saved_class_ptr;
8825       cp_function_chain->x_current_class_ref = saved_class_ref;
8826     }
8827
8828   /* Make sure the default argument is reasonable.  */
8829   arg = check_default_argument (type, arg);
8830
8831   pop_access_scope (fn);
8832
8833   return arg;
8834 }
8835
8836 /* Substitute into all the default arguments for FN.  */
8837
8838 static void
8839 tsubst_default_arguments (tree fn)
8840 {
8841   tree arg;
8842   tree tmpl_args;
8843
8844   tmpl_args = DECL_TI_ARGS (fn);
8845
8846   /* If this function is not yet instantiated, we certainly don't need
8847      its default arguments.  */
8848   if (uses_template_parms (tmpl_args))
8849     return;
8850
8851   for (arg = TYPE_ARG_TYPES (TREE_TYPE (fn));
8852        arg;
8853        arg = TREE_CHAIN (arg))
8854     if (TREE_PURPOSE (arg))
8855       TREE_PURPOSE (arg) = tsubst_default_argument (fn,
8856                                                     TREE_VALUE (arg),
8857                                                     TREE_PURPOSE (arg));
8858 }
8859
8860 /* Substitute the ARGS into the T, which is a _DECL.  Return the
8861    result of the substitution.  Issue error and warning messages under
8862    control of COMPLAIN.  */
8863
8864 static tree
8865 tsubst_decl (tree t, tree args, tsubst_flags_t complain)
8866 {
8867 #define RETURN(EXP) do { r = (EXP); goto out; } while(0)
8868   location_t saved_loc;
8869   tree r = NULL_TREE;
8870   tree in_decl = t;
8871   hashval_t hash = 0;
8872
8873   /* Set the filename and linenumber to improve error-reporting.  */
8874   saved_loc = input_location;
8875   input_location = DECL_SOURCE_LOCATION (t);
8876
8877   switch (TREE_CODE (t))
8878     {
8879     case TEMPLATE_DECL:
8880       {
8881         /* We can get here when processing a member function template,
8882            member class template, or template template parameter.  */
8883         tree decl = DECL_TEMPLATE_RESULT (t);
8884         tree spec;
8885         tree tmpl_args;
8886         tree full_args;
8887
8888         if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
8889           {
8890             /* Template template parameter is treated here.  */
8891             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8892             if (new_type == error_mark_node)
8893               RETURN (error_mark_node);
8894
8895             r = copy_decl (t);
8896             TREE_CHAIN (r) = NULL_TREE;
8897             TREE_TYPE (r) = new_type;
8898             DECL_TEMPLATE_RESULT (r)
8899               = build_decl (DECL_SOURCE_LOCATION (decl),
8900                             TYPE_DECL, DECL_NAME (decl), new_type);
8901             DECL_TEMPLATE_PARMS (r)
8902               = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8903                                        complain);
8904             TYPE_NAME (new_type) = r;
8905             break;
8906           }
8907
8908         /* We might already have an instance of this template.
8909            The ARGS are for the surrounding class type, so the
8910            full args contain the tsubst'd args for the context,
8911            plus the innermost args from the template decl.  */
8912         tmpl_args = DECL_CLASS_TEMPLATE_P (t)
8913           ? CLASSTYPE_TI_ARGS (TREE_TYPE (t))
8914           : DECL_TI_ARGS (DECL_TEMPLATE_RESULT (t));
8915         /* Because this is a template, the arguments will still be
8916            dependent, even after substitution.  If
8917            PROCESSING_TEMPLATE_DECL is not set, the dependency
8918            predicates will short-circuit.  */
8919         ++processing_template_decl;
8920         full_args = tsubst_template_args (tmpl_args, args,
8921                                           complain, in_decl);
8922         --processing_template_decl;
8923         if (full_args == error_mark_node)
8924           RETURN (error_mark_node);
8925
8926         /* If this is a default template template argument,
8927            tsubst might not have changed anything.  */
8928         if (full_args == tmpl_args)
8929           RETURN (t);
8930
8931         hash = hash_tmpl_and_args (t, full_args);
8932         spec = retrieve_specialization (t, full_args, hash);
8933         if (spec != NULL_TREE)
8934           {
8935             r = spec;
8936             break;
8937           }
8938
8939         /* Make a new template decl.  It will be similar to the
8940            original, but will record the current template arguments.
8941            We also create a new function declaration, which is just
8942            like the old one, but points to this new template, rather
8943            than the old one.  */
8944         r = copy_decl (t);
8945         gcc_assert (DECL_LANG_SPECIFIC (r) != 0);
8946         TREE_CHAIN (r) = NULL_TREE;
8947
8948         DECL_TEMPLATE_INFO (r) = build_template_info (t, args);
8949
8950         if (TREE_CODE (decl) == TYPE_DECL)
8951           {
8952             tree new_type;
8953             ++processing_template_decl;
8954             new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
8955             --processing_template_decl;
8956             if (new_type == error_mark_node)
8957               RETURN (error_mark_node);
8958
8959             TREE_TYPE (r) = new_type;
8960             CLASSTYPE_TI_TEMPLATE (new_type) = r;
8961             DECL_TEMPLATE_RESULT (r) = TYPE_MAIN_DECL (new_type);
8962             DECL_TI_ARGS (r) = CLASSTYPE_TI_ARGS (new_type);
8963             DECL_CONTEXT (r) = TYPE_CONTEXT (new_type);
8964           }
8965         else
8966           {
8967             tree new_decl;
8968             ++processing_template_decl;
8969             new_decl = tsubst (decl, args, complain, in_decl);
8970             --processing_template_decl;
8971             if (new_decl == error_mark_node)
8972               RETURN (error_mark_node);
8973
8974             DECL_TEMPLATE_RESULT (r) = new_decl;
8975             DECL_TI_TEMPLATE (new_decl) = r;
8976             TREE_TYPE (r) = TREE_TYPE (new_decl);
8977             DECL_TI_ARGS (r) = DECL_TI_ARGS (new_decl);
8978             DECL_CONTEXT (r) = DECL_CONTEXT (new_decl);
8979           }
8980
8981         SET_DECL_IMPLICIT_INSTANTIATION (r);
8982         DECL_TEMPLATE_INSTANTIATIONS (r) = NULL_TREE;
8983         DECL_TEMPLATE_SPECIALIZATIONS (r) = NULL_TREE;
8984
8985         /* The template parameters for this new template are all the
8986            template parameters for the old template, except the
8987            outermost level of parameters.  */
8988         DECL_TEMPLATE_PARMS (r)
8989           = tsubst_template_parms (DECL_TEMPLATE_PARMS (t), args,
8990                                    complain);
8991
8992         if (PRIMARY_TEMPLATE_P (t))
8993           DECL_PRIMARY_TEMPLATE (r) = r;
8994
8995         if (TREE_CODE (decl) != TYPE_DECL)
8996           /* Record this non-type partial instantiation.  */
8997           register_specialization (r, t,
8998                                    DECL_TI_ARGS (DECL_TEMPLATE_RESULT (r)),
8999                                    false, hash);
9000       }
9001       break;
9002
9003     case FUNCTION_DECL:
9004       {
9005         tree ctx;
9006         tree argvec = NULL_TREE;
9007         tree *friends;
9008         tree gen_tmpl;
9009         tree type;
9010         int member;
9011         int args_depth;
9012         int parms_depth;
9013
9014         /* Nobody should be tsubst'ing into non-template functions.  */
9015         gcc_assert (DECL_TEMPLATE_INFO (t) != NULL_TREE);
9016
9017         if (TREE_CODE (DECL_TI_TEMPLATE (t)) == TEMPLATE_DECL)
9018           {
9019             tree spec;
9020             bool dependent_p;
9021
9022             /* If T is not dependent, just return it.  We have to
9023                increment PROCESSING_TEMPLATE_DECL because
9024                value_dependent_expression_p assumes that nothing is
9025                dependent when PROCESSING_TEMPLATE_DECL is zero.  */
9026             ++processing_template_decl;
9027             dependent_p = value_dependent_expression_p (t);
9028             --processing_template_decl;
9029             if (!dependent_p)
9030               RETURN (t);
9031
9032             /* Calculate the most general template of which R is a
9033                specialization, and the complete set of arguments used to
9034                specialize R.  */
9035             gen_tmpl = most_general_template (DECL_TI_TEMPLATE (t));
9036             argvec = tsubst_template_args (DECL_TI_ARGS
9037                                           (DECL_TEMPLATE_RESULT
9038                                                  (DECL_TI_TEMPLATE (t))),
9039                                            args, complain, in_decl);
9040
9041             /* Check to see if we already have this specialization.  */
9042             hash = hash_tmpl_and_args (gen_tmpl, argvec);
9043             spec = retrieve_specialization (gen_tmpl, argvec, hash);
9044
9045             if (spec)
9046               {
9047                 r = spec;
9048                 break;
9049               }
9050
9051             /* We can see more levels of arguments than parameters if
9052                there was a specialization of a member template, like
9053                this:
9054
9055                  template <class T> struct S { template <class U> void f(); }
9056                  template <> template <class U> void S<int>::f(U);
9057
9058                Here, we'll be substituting into the specialization,
9059                because that's where we can find the code we actually
9060                want to generate, but we'll have enough arguments for
9061                the most general template.
9062
9063                We also deal with the peculiar case:
9064
9065                  template <class T> struct S {
9066                    template <class U> friend void f();
9067                  };
9068                  template <class U> void f() {}
9069                  template S<int>;
9070                  template void f<double>();
9071
9072                Here, the ARGS for the instantiation of will be {int,
9073                double}.  But, we only need as many ARGS as there are
9074                levels of template parameters in CODE_PATTERN.  We are
9075                careful not to get fooled into reducing the ARGS in
9076                situations like:
9077
9078                  template <class T> struct S { template <class U> void f(U); }
9079                  template <class T> template <> void S<T>::f(int) {}
9080
9081                which we can spot because the pattern will be a
9082                specialization in this case.  */
9083             args_depth = TMPL_ARGS_DEPTH (args);
9084             parms_depth =
9085               TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (DECL_TI_TEMPLATE (t)));
9086             if (args_depth > parms_depth
9087                 && !DECL_TEMPLATE_SPECIALIZATION (t))
9088               args = get_innermost_template_args (args, parms_depth);
9089           }
9090         else
9091           {
9092             /* This special case arises when we have something like this:
9093
9094                  template <class T> struct S {
9095                    friend void f<int>(int, double);
9096                  };
9097
9098                Here, the DECL_TI_TEMPLATE for the friend declaration
9099                will be an IDENTIFIER_NODE.  We are being called from
9100                tsubst_friend_function, and we want only to create a
9101                new decl (R) with appropriate types so that we can call
9102                determine_specialization.  */
9103             gen_tmpl = NULL_TREE;
9104           }
9105
9106         if (DECL_CLASS_SCOPE_P (t))
9107           {
9108             if (DECL_NAME (t) == constructor_name (DECL_CONTEXT (t)))
9109               member = 2;
9110             else
9111               member = 1;
9112             ctx = tsubst_aggr_type (DECL_CONTEXT (t), args,
9113                                     complain, t, /*entering_scope=*/1);
9114           }
9115         else
9116           {
9117             member = 0;
9118             ctx = DECL_CONTEXT (t);
9119           }
9120         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9121         if (type == error_mark_node)
9122           RETURN (error_mark_node);
9123
9124         /* We do NOT check for matching decls pushed separately at this
9125            point, as they may not represent instantiations of this
9126            template, and in any case are considered separate under the
9127            discrete model.  */
9128         r = copy_decl (t);
9129         DECL_USE_TEMPLATE (r) = 0;
9130         TREE_TYPE (r) = type;
9131         /* Clear out the mangled name and RTL for the instantiation.  */
9132         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9133         SET_DECL_RTL (r, NULL_RTX);
9134         /* Leave DECL_INITIAL set on deleted instantiations.  */
9135         if (!DECL_DELETED_FN (r))
9136           DECL_INITIAL (r) = NULL_TREE;
9137         DECL_CONTEXT (r) = ctx;
9138
9139         if (member && DECL_CONV_FN_P (r))
9140           /* Type-conversion operator.  Reconstruct the name, in
9141              case it's the name of one of the template's parameters.  */
9142           DECL_NAME (r) = mangle_conv_op_name_for_type (TREE_TYPE (type));
9143
9144         DECL_ARGUMENTS (r) = tsubst (DECL_ARGUMENTS (t), args,
9145                                      complain, t);
9146         DECL_RESULT (r) = NULL_TREE;
9147
9148         TREE_STATIC (r) = 0;
9149         TREE_PUBLIC (r) = TREE_PUBLIC (t);
9150         DECL_EXTERNAL (r) = 1;
9151         /* If this is an instantiation of a function with internal
9152            linkage, we already know what object file linkage will be
9153            assigned to the instantiation.  */
9154         DECL_INTERFACE_KNOWN (r) = !TREE_PUBLIC (r);
9155         DECL_DEFER_OUTPUT (r) = 0;
9156         TREE_CHAIN (r) = NULL_TREE;
9157         DECL_PENDING_INLINE_INFO (r) = 0;
9158         DECL_PENDING_INLINE_P (r) = 0;
9159         DECL_SAVED_TREE (r) = NULL_TREE;
9160         DECL_STRUCT_FUNCTION (r) = NULL;
9161         TREE_USED (r) = 0;
9162         /* We'll re-clone as appropriate in instantiate_template.  */
9163         DECL_CLONED_FUNCTION (r) = NULL_TREE;
9164
9165         /* If we aren't complaining now, return on error before we register
9166            the specialization so that we'll complain eventually.  */
9167         if ((complain & tf_error) == 0
9168             && IDENTIFIER_OPNAME_P (DECL_NAME (r))
9169             && !grok_op_properties (r, /*complain=*/false))
9170           RETURN (error_mark_node);
9171
9172         /* Set up the DECL_TEMPLATE_INFO for R.  There's no need to do
9173            this in the special friend case mentioned above where
9174            GEN_TMPL is NULL.  */
9175         if (gen_tmpl)
9176           {
9177             DECL_TEMPLATE_INFO (r)
9178               = build_template_info (gen_tmpl, argvec);
9179             SET_DECL_IMPLICIT_INSTANTIATION (r);
9180             register_specialization (r, gen_tmpl, argvec, false, hash);
9181
9182             /* We're not supposed to instantiate default arguments
9183                until they are called, for a template.  But, for a
9184                declaration like:
9185
9186                  template <class T> void f ()
9187                  { extern void g(int i = T()); }
9188
9189                we should do the substitution when the template is
9190                instantiated.  We handle the member function case in
9191                instantiate_class_template since the default arguments
9192                might refer to other members of the class.  */
9193             if (!member
9194                 && !PRIMARY_TEMPLATE_P (gen_tmpl)
9195                 && !uses_template_parms (argvec))
9196               tsubst_default_arguments (r);
9197           }
9198         else
9199           DECL_TEMPLATE_INFO (r) = NULL_TREE;
9200
9201         /* Copy the list of befriending classes.  */
9202         for (friends = &DECL_BEFRIENDING_CLASSES (r);
9203              *friends;
9204              friends = &TREE_CHAIN (*friends))
9205           {
9206             *friends = copy_node (*friends);
9207             TREE_VALUE (*friends) = tsubst (TREE_VALUE (*friends),
9208                                             args, complain,
9209                                             in_decl);
9210           }
9211
9212         if (DECL_CONSTRUCTOR_P (r) || DECL_DESTRUCTOR_P (r))
9213           {
9214             maybe_retrofit_in_chrg (r);
9215             if (DECL_CONSTRUCTOR_P (r))
9216               grok_ctor_properties (ctx, r);
9217             /* If this is an instantiation of a member template, clone it.
9218                If it isn't, that'll be handled by
9219                clone_constructors_and_destructors.  */
9220             if (PRIMARY_TEMPLATE_P (gen_tmpl))
9221               clone_function_decl (r, /*update_method_vec_p=*/0);
9222           }
9223         else if ((complain & tf_error) != 0
9224                  && IDENTIFIER_OPNAME_P (DECL_NAME (r))
9225                  && !grok_op_properties (r, /*complain=*/true))
9226           RETURN (error_mark_node);
9227
9228         if (DECL_FRIEND_P (t) && DECL_FRIEND_CONTEXT (t))
9229           SET_DECL_FRIEND_CONTEXT (r,
9230                                    tsubst (DECL_FRIEND_CONTEXT (t),
9231                                             args, complain, in_decl));
9232
9233         /* Possibly limit visibility based on template args.  */
9234         DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
9235         if (DECL_VISIBILITY_SPECIFIED (t))
9236           {
9237             DECL_VISIBILITY_SPECIFIED (r) = 0;
9238             DECL_ATTRIBUTES (r)
9239               = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
9240           }
9241         determine_visibility (r);
9242         if (DECL_DEFAULTED_OUTSIDE_CLASS_P (r)
9243             && !processing_template_decl)
9244           defaulted_late_check (r);
9245
9246         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9247                                         args, complain, in_decl);
9248       }
9249       break;
9250
9251     case PARM_DECL:
9252       {
9253         tree type = NULL_TREE;
9254         int i, len = 1;
9255         tree expanded_types = NULL_TREE;
9256         tree prev_r = NULL_TREE;
9257         tree first_r = NULL_TREE;
9258
9259         if (FUNCTION_PARAMETER_PACK_P (t))
9260           {
9261             /* If there is a local specialization that isn't a
9262                parameter pack, it means that we're doing a "simple"
9263                substitution from inside tsubst_pack_expansion. Just
9264                return the local specialization (which will be a single
9265                parm).  */
9266             tree spec = retrieve_local_specialization (t);
9267             if (spec 
9268                 && TREE_CODE (spec) == PARM_DECL
9269                 && TREE_CODE (TREE_TYPE (spec)) != TYPE_PACK_EXPANSION)
9270               RETURN (spec);
9271
9272             /* Expand the TYPE_PACK_EXPANSION that provides the types for
9273                the parameters in this function parameter pack.  */
9274             expanded_types = tsubst_pack_expansion (TREE_TYPE (t), args,
9275                                                     complain, in_decl);
9276             if (TREE_CODE (expanded_types) == TREE_VEC)
9277               {
9278                 len = TREE_VEC_LENGTH (expanded_types);
9279
9280                 /* Zero-length parameter packs are boring. Just substitute
9281                    into the chain.  */
9282                 if (len == 0)
9283                   RETURN (tsubst (TREE_CHAIN (t), args, complain,
9284                                   TREE_CHAIN (t)));
9285               }
9286             else
9287               {
9288                 /* All we did was update the type. Make a note of that.  */
9289                 type = expanded_types;
9290                 expanded_types = NULL_TREE;
9291               }
9292           }
9293
9294         /* Loop through all of the parameter's we'll build. When T is
9295            a function parameter pack, LEN is the number of expanded
9296            types in EXPANDED_TYPES; otherwise, LEN is 1.  */
9297         r = NULL_TREE;
9298         for (i = 0; i < len; ++i)
9299           {
9300             prev_r = r;
9301             r = copy_node (t);
9302             if (DECL_TEMPLATE_PARM_P (t))
9303               SET_DECL_TEMPLATE_PARM_P (r);
9304
9305             /* An argument of a function parameter pack is not a parameter
9306                pack.  */
9307             FUNCTION_PARAMETER_PACK_P (r) = false;
9308
9309             if (expanded_types)
9310               /* We're on the Ith parameter of the function parameter
9311                  pack.  */
9312               {
9313                 /* Get the Ith type.  */
9314                 type = TREE_VEC_ELT (expanded_types, i);
9315
9316                 if (DECL_NAME (r))
9317                   /* Rename the parameter to include the index.  */
9318                   DECL_NAME (r) =
9319                     make_ith_pack_parameter_name (DECL_NAME (r), i);
9320               }
9321             else if (!type)
9322               /* We're dealing with a normal parameter.  */
9323               type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9324
9325             type = type_decays_to (type);
9326             TREE_TYPE (r) = type;
9327             cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9328
9329             if (DECL_INITIAL (r))
9330               {
9331                 if (TREE_CODE (DECL_INITIAL (r)) != TEMPLATE_PARM_INDEX)
9332                   DECL_INITIAL (r) = TREE_TYPE (r);
9333                 else
9334                   DECL_INITIAL (r) = tsubst (DECL_INITIAL (r), args,
9335                                              complain, in_decl);
9336               }
9337
9338             DECL_CONTEXT (r) = NULL_TREE;
9339
9340             if (!DECL_TEMPLATE_PARM_P (r))
9341               DECL_ARG_TYPE (r) = type_passed_as (type);
9342
9343             apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9344                                             args, complain, in_decl);
9345
9346             /* Keep track of the first new parameter we
9347                generate. That's what will be returned to the
9348                caller.  */
9349             if (!first_r)
9350               first_r = r;
9351
9352             /* Build a proper chain of parameters when substituting
9353                into a function parameter pack.  */
9354             if (prev_r)
9355               TREE_CHAIN (prev_r) = r;
9356           }
9357
9358         if (TREE_CHAIN (t))
9359           TREE_CHAIN (r) = tsubst (TREE_CHAIN (t), args,
9360                                    complain, TREE_CHAIN (t));
9361
9362         /* FIRST_R contains the start of the chain we've built.  */
9363         r = first_r;
9364       }
9365       break;
9366
9367     case FIELD_DECL:
9368       {
9369         tree type;
9370
9371         r = copy_decl (t);
9372         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9373         if (type == error_mark_node)
9374           RETURN (error_mark_node);
9375         TREE_TYPE (r) = type;
9376         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9377
9378         /* DECL_INITIAL gives the number of bits in a bit-field.  */
9379         DECL_INITIAL (r)
9380           = tsubst_expr (DECL_INITIAL (t), args,
9381                          complain, in_decl,
9382                          /*integral_constant_expression_p=*/true);
9383         /* We don't have to set DECL_CONTEXT here; it is set by
9384            finish_member_declaration.  */
9385         TREE_CHAIN (r) = NULL_TREE;
9386         if (VOID_TYPE_P (type))
9387           error ("instantiation of %q+D as type %qT", r, type);
9388
9389         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r), 0,
9390                                         args, complain, in_decl);
9391       }
9392       break;
9393
9394     case USING_DECL:
9395       /* We reach here only for member using decls.  */
9396       if (DECL_DEPENDENT_P (t))
9397         {
9398           r = do_class_using_decl
9399             (tsubst_copy (USING_DECL_SCOPE (t), args, complain, in_decl),
9400              tsubst_copy (DECL_NAME (t), args, complain, in_decl));
9401           if (!r)
9402             r = error_mark_node;
9403           else
9404             {
9405               TREE_PROTECTED (r) = TREE_PROTECTED (t);
9406               TREE_PRIVATE (r) = TREE_PRIVATE (t);
9407             }
9408         }
9409       else
9410         {
9411           r = copy_node (t);
9412           TREE_CHAIN (r) = NULL_TREE;
9413         }
9414       break;
9415
9416     case TYPE_DECL:
9417     case VAR_DECL:
9418       {
9419         tree argvec = NULL_TREE;
9420         tree gen_tmpl = NULL_TREE;
9421         tree spec;
9422         tree tmpl = NULL_TREE;
9423         tree ctx;
9424         tree type = NULL_TREE;
9425         bool local_p;
9426
9427         if (TREE_CODE (t) == TYPE_DECL
9428             && t == TYPE_MAIN_DECL (TREE_TYPE (t)))
9429           {
9430             /* If this is the canonical decl, we don't have to
9431                mess with instantiations, and often we can't (for
9432                typename, template type parms and such).  Note that
9433                TYPE_NAME is not correct for the above test if
9434                we've copied the type for a typedef.  */
9435             type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9436             if (type == error_mark_node)
9437               RETURN (error_mark_node);
9438             r = TYPE_NAME (type);
9439             break;
9440           }
9441
9442         /* Check to see if we already have the specialization we
9443            need.  */
9444         spec = NULL_TREE;
9445         if (DECL_CLASS_SCOPE_P (t) || DECL_NAMESPACE_SCOPE_P (t))
9446           {
9447             /* T is a static data member or namespace-scope entity.
9448                We have to substitute into namespace-scope variables
9449                (even though such entities are never templates) because
9450                of cases like:
9451                
9452                  template <class T> void f() { extern T t; }
9453
9454                where the entity referenced is not known until
9455                instantiation time.  */
9456             local_p = false;
9457             ctx = DECL_CONTEXT (t);
9458             if (DECL_CLASS_SCOPE_P (t))
9459               {
9460                 ctx = tsubst_aggr_type (ctx, args,
9461                                         complain,
9462                                         in_decl, /*entering_scope=*/1);
9463                 /* If CTX is unchanged, then T is in fact the
9464                    specialization we want.  That situation occurs when
9465                    referencing a static data member within in its own
9466                    class.  We can use pointer equality, rather than
9467                    same_type_p, because DECL_CONTEXT is always
9468                    canonical.  */
9469                 if (ctx == DECL_CONTEXT (t))
9470                   spec = t;
9471               }
9472
9473             if (!spec)
9474               {
9475                 tmpl = DECL_TI_TEMPLATE (t);
9476                 gen_tmpl = most_general_template (tmpl);
9477                 argvec = tsubst (DECL_TI_ARGS (t), args, complain, in_decl);
9478                 hash = hash_tmpl_and_args (gen_tmpl, argvec);
9479                 spec = retrieve_specialization (gen_tmpl, argvec, hash);
9480               }
9481           }
9482         else
9483           {
9484             /* A local variable.  */
9485             local_p = true;
9486             /* Subsequent calls to pushdecl will fill this in.  */
9487             ctx = NULL_TREE;
9488             spec = retrieve_local_specialization (t);
9489           }
9490         /* If we already have the specialization we need, there is
9491            nothing more to do.  */ 
9492         if (spec)
9493           {
9494             r = spec;
9495             break;
9496           }
9497
9498         /* Create a new node for the specialization we need.  */
9499         r = copy_decl (t);
9500         if (type == NULL_TREE)
9501           {
9502             if (is_typedef_decl (t))
9503               type = DECL_ORIGINAL_TYPE (t);
9504             else
9505               type = TREE_TYPE (t);
9506             if (TREE_CODE (t) == VAR_DECL && VAR_HAD_UNKNOWN_BOUND (t))
9507               type = strip_array_domain (type);
9508             type = tsubst (type, args, complain, in_decl);
9509           }
9510         if (TREE_CODE (r) == VAR_DECL)
9511           {
9512             /* Even if the original location is out of scope, the
9513                newly substituted one is not.  */
9514             DECL_DEAD_FOR_LOCAL (r) = 0;
9515             DECL_INITIALIZED_P (r) = 0;
9516             DECL_TEMPLATE_INSTANTIATED (r) = 0;
9517             if (type == error_mark_node)
9518               RETURN (error_mark_node);
9519             if (TREE_CODE (type) == FUNCTION_TYPE)
9520               {
9521                 /* It may seem that this case cannot occur, since:
9522
9523                      typedef void f();
9524                      void g() { f x; }
9525
9526                    declares a function, not a variable.  However:
9527       
9528                      typedef void f();
9529                      template <typename T> void g() { T t; }
9530                      template void g<f>();
9531
9532                    is an attempt to declare a variable with function
9533                    type.  */
9534                 error ("variable %qD has function type",
9535                        /* R is not yet sufficiently initialized, so we
9536                           just use its name.  */
9537                        DECL_NAME (r));
9538                 RETURN (error_mark_node);
9539               }
9540             type = complete_type (type);
9541             DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (r)
9542               = DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (t);
9543             type = check_var_type (DECL_NAME (r), type);
9544
9545             if (DECL_HAS_VALUE_EXPR_P (t))
9546               {
9547                 tree ve = DECL_VALUE_EXPR (t);
9548                 ve = tsubst_expr (ve, args, complain, in_decl,
9549                                   /*constant_expression_p=*/false);
9550                 SET_DECL_VALUE_EXPR (r, ve);
9551               }
9552           }
9553         else if (DECL_SELF_REFERENCE_P (t))
9554           SET_DECL_SELF_REFERENCE_P (r);
9555         TREE_TYPE (r) = type;
9556         cp_apply_type_quals_to_decl (cp_type_quals (type), r);
9557         DECL_CONTEXT (r) = ctx;
9558         /* Clear out the mangled name and RTL for the instantiation.  */
9559         SET_DECL_ASSEMBLER_NAME (r, NULL_TREE);
9560         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9561           SET_DECL_RTL (r, NULL_RTX);
9562         /* The initializer must not be expanded until it is required;
9563            see [temp.inst].  */
9564         DECL_INITIAL (r) = NULL_TREE;
9565         if (CODE_CONTAINS_STRUCT (TREE_CODE (t), TS_DECL_WRTL))
9566           SET_DECL_RTL (r, NULL_RTX);
9567         DECL_SIZE (r) = DECL_SIZE_UNIT (r) = 0;
9568         if (TREE_CODE (r) == VAR_DECL)
9569           {
9570             /* Possibly limit visibility based on template args.  */
9571             DECL_VISIBILITY (r) = VISIBILITY_DEFAULT;
9572             if (DECL_VISIBILITY_SPECIFIED (t))
9573               {
9574                 DECL_VISIBILITY_SPECIFIED (r) = 0;
9575                 DECL_ATTRIBUTES (r)
9576                   = remove_attribute ("visibility", DECL_ATTRIBUTES (r));
9577               }
9578             determine_visibility (r);
9579           }
9580
9581         if (!local_p)
9582           {
9583             /* A static data member declaration is always marked
9584                external when it is declared in-class, even if an
9585                initializer is present.  We mimic the non-template
9586                processing here.  */
9587             DECL_EXTERNAL (r) = 1;
9588
9589             register_specialization (r, gen_tmpl, argvec, false, hash);
9590             DECL_TEMPLATE_INFO (r) = build_template_info (tmpl, argvec);
9591             SET_DECL_IMPLICIT_INSTANTIATION (r);
9592           }
9593         else if (cp_unevaluated_operand)
9594           {
9595             /* We're substituting this var in a decltype outside of its
9596                scope, such as for a lambda return type.  Don't add it to
9597                local_specializations, do perform auto deduction.  */
9598             tree auto_node = type_uses_auto (type);
9599             tree init
9600               = tsubst_expr (DECL_INITIAL (t), args, complain, in_decl,
9601                              /*constant_expression_p=*/false);
9602
9603             if (auto_node && init && describable_type (init))
9604               {
9605                 type = do_auto_deduction (type, init, auto_node);
9606                 TREE_TYPE (r) = type;
9607               }
9608           }
9609         else
9610           register_local_specialization (r, t);
9611
9612         TREE_CHAIN (r) = NULL_TREE;
9613
9614         apply_late_template_attributes (&r, DECL_ATTRIBUTES (r),
9615                                         /*flags=*/0,
9616                                         args, complain, in_decl);
9617
9618         /* Preserve a typedef that names a type.  */
9619         if (is_typedef_decl (r))
9620           {
9621             DECL_ORIGINAL_TYPE (r) = NULL_TREE;
9622             set_underlying_type (r);
9623           }
9624
9625         layout_decl (r, 0);
9626       }
9627       break;
9628
9629     default:
9630       gcc_unreachable ();
9631     }
9632 #undef RETURN
9633
9634  out:
9635   /* Restore the file and line information.  */
9636   input_location = saved_loc;
9637
9638   return r;
9639 }
9640
9641 /* Substitute into the ARG_TYPES of a function type.  */
9642
9643 static tree
9644 tsubst_arg_types (tree arg_types,
9645                   tree args,
9646                   tsubst_flags_t complain,
9647                   tree in_decl)
9648 {
9649   tree remaining_arg_types;
9650   tree type = NULL_TREE;
9651   int i = 1;
9652   tree expanded_args = NULL_TREE;
9653   tree default_arg;
9654
9655   if (!arg_types || arg_types == void_list_node)
9656     return arg_types;
9657
9658   remaining_arg_types = tsubst_arg_types (TREE_CHAIN (arg_types),
9659                                           args, complain, in_decl);
9660   if (remaining_arg_types == error_mark_node)
9661     return error_mark_node;
9662
9663   if (PACK_EXPANSION_P (TREE_VALUE (arg_types)))
9664     {
9665       /* For a pack expansion, perform substitution on the
9666          entire expression. Later on, we'll handle the arguments
9667          one-by-one.  */
9668       expanded_args = tsubst_pack_expansion (TREE_VALUE (arg_types),
9669                                             args, complain, in_decl);
9670
9671       if (TREE_CODE (expanded_args) == TREE_VEC)
9672         /* So that we'll spin through the parameters, one by one.  */
9673         i = TREE_VEC_LENGTH (expanded_args);
9674       else
9675         {
9676           /* We only partially substituted into the parameter
9677              pack. Our type is TYPE_PACK_EXPANSION.  */
9678           type = expanded_args;
9679           expanded_args = NULL_TREE;
9680         }
9681     }
9682
9683   while (i > 0) {
9684     --i;
9685     
9686     if (expanded_args)
9687       type = TREE_VEC_ELT (expanded_args, i);
9688     else if (!type)
9689       type = tsubst (TREE_VALUE (arg_types), args, complain, in_decl);
9690
9691     if (type == error_mark_node)
9692       return error_mark_node;
9693     if (VOID_TYPE_P (type))
9694       {
9695         if (complain & tf_error)
9696           {
9697             error ("invalid parameter type %qT", type);
9698             if (in_decl)
9699               error ("in declaration %q+D", in_decl);
9700           }
9701         return error_mark_node;
9702     }
9703     
9704     /* Do array-to-pointer, function-to-pointer conversion, and ignore
9705        top-level qualifiers as required.  */
9706     type = TYPE_MAIN_VARIANT (type_decays_to (type));
9707
9708     /* We do not substitute into default arguments here.  The standard
9709        mandates that they be instantiated only when needed, which is
9710        done in build_over_call.  */
9711     default_arg = TREE_PURPOSE (arg_types);
9712
9713     if (default_arg && TREE_CODE (default_arg) == DEFAULT_ARG)
9714       {
9715         /* We've instantiated a template before its default arguments
9716            have been parsed.  This can happen for a nested template
9717            class, and is not an error unless we require the default
9718            argument in a call of this function.  */
9719         remaining_arg_types = 
9720           tree_cons (default_arg, type, remaining_arg_types);
9721         VEC_safe_push (tree, gc, DEFARG_INSTANTIATIONS (default_arg), 
9722                        remaining_arg_types);
9723       }
9724     else
9725       remaining_arg_types = 
9726         hash_tree_cons (default_arg, type, remaining_arg_types);
9727   }
9728         
9729   return remaining_arg_types;
9730 }
9731
9732 /* Substitute into a FUNCTION_TYPE or METHOD_TYPE.  This routine does
9733    *not* handle the exception-specification for FNTYPE, because the
9734    initial substitution of explicitly provided template parameters
9735    during argument deduction forbids substitution into the
9736    exception-specification:
9737
9738      [temp.deduct]
9739
9740      All references in the function type of the function template to  the
9741      corresponding template parameters are replaced by the specified tem-
9742      plate argument values.  If a substitution in a template parameter or
9743      in  the function type of the function template results in an invalid
9744      type, type deduction fails.  [Note: The equivalent  substitution  in
9745      exception specifications is done only when the function is instanti-
9746      ated, at which point a program is  ill-formed  if  the  substitution
9747      results in an invalid type.]  */
9748
9749 static tree
9750 tsubst_function_type (tree t,
9751                       tree args,
9752                       tsubst_flags_t complain,
9753                       tree in_decl)
9754 {
9755   tree return_type;
9756   tree arg_types;
9757   tree fntype;
9758
9759   /* The TYPE_CONTEXT is not used for function/method types.  */
9760   gcc_assert (TYPE_CONTEXT (t) == NULL_TREE);
9761
9762   /* Substitute the return type.  */
9763   return_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
9764   if (return_type == error_mark_node)
9765     return error_mark_node;
9766   /* The standard does not presently indicate that creation of a
9767      function type with an invalid return type is a deduction failure.
9768      However, that is clearly analogous to creating an array of "void"
9769      or a reference to a reference.  This is core issue #486.  */
9770   if (TREE_CODE (return_type) == ARRAY_TYPE
9771       || TREE_CODE (return_type) == FUNCTION_TYPE)
9772     {
9773       if (complain & tf_error)
9774         {
9775           if (TREE_CODE (return_type) == ARRAY_TYPE)
9776             error ("function returning an array");
9777           else
9778             error ("function returning a function");
9779         }
9780       return error_mark_node;
9781     }
9782
9783   /* Substitute the argument types.  */
9784   arg_types = tsubst_arg_types (TYPE_ARG_TYPES (t), args,
9785                                 complain, in_decl);
9786   if (arg_types == error_mark_node)
9787     return error_mark_node;
9788
9789   /* Construct a new type node and return it.  */
9790   if (TREE_CODE (t) == FUNCTION_TYPE)
9791     fntype = build_function_type (return_type, arg_types);
9792   else
9793     {
9794       tree r = TREE_TYPE (TREE_VALUE (arg_types));
9795       if (! MAYBE_CLASS_TYPE_P (r))
9796         {
9797           /* [temp.deduct]
9798
9799              Type deduction may fail for any of the following
9800              reasons:
9801
9802              -- Attempting to create "pointer to member of T" when T
9803              is not a class type.  */
9804           if (complain & tf_error)
9805             error ("creating pointer to member function of non-class type %qT",
9806                       r);
9807           return error_mark_node;
9808         }
9809
9810       fntype = build_method_type_directly (r, return_type,
9811                                            TREE_CHAIN (arg_types));
9812     }
9813   fntype = cp_build_qualified_type_real (fntype, TYPE_QUALS (t), complain);
9814   fntype = cp_build_type_attribute_variant (fntype, TYPE_ATTRIBUTES (t));
9815
9816   return fntype;
9817 }
9818
9819 /* FNTYPE is a FUNCTION_TYPE or METHOD_TYPE.  Substitute the template
9820    ARGS into that specification, and return the substituted
9821    specification.  If there is no specification, return NULL_TREE.  */
9822
9823 static tree
9824 tsubst_exception_specification (tree fntype,
9825                                 tree args,
9826                                 tsubst_flags_t complain,
9827                                 tree in_decl)
9828 {
9829   tree specs;
9830   tree new_specs;
9831
9832   specs = TYPE_RAISES_EXCEPTIONS (fntype);
9833   new_specs = NULL_TREE;
9834   if (specs)
9835     {
9836       if (! TREE_VALUE (specs))
9837         new_specs = specs;
9838       else
9839         while (specs)
9840           {
9841             tree spec;
9842             int i, len = 1;
9843             tree expanded_specs = NULL_TREE;
9844
9845             if (PACK_EXPANSION_P (TREE_VALUE (specs)))
9846               {
9847                 /* Expand the pack expansion type.  */
9848                 expanded_specs = tsubst_pack_expansion (TREE_VALUE (specs),
9849                                                        args, complain,
9850                                                        in_decl);
9851
9852                 if (expanded_specs == error_mark_node)
9853                   return error_mark_node;
9854                 else if (TREE_CODE (expanded_specs) == TREE_VEC)
9855                   len = TREE_VEC_LENGTH (expanded_specs);
9856                 else
9857                   {
9858                     /* We're substituting into a member template, so
9859                        we got a TYPE_PACK_EXPANSION back.  Add that
9860                        expansion and move on.  */
9861                     gcc_assert (TREE_CODE (expanded_specs) 
9862                                 == TYPE_PACK_EXPANSION);
9863                     new_specs = add_exception_specifier (new_specs,
9864                                                          expanded_specs,
9865                                                          complain);
9866                     specs = TREE_CHAIN (specs);
9867                     continue;
9868                   }
9869               }
9870
9871             for (i = 0; i < len; ++i)
9872               {
9873                 if (expanded_specs)
9874                   spec = TREE_VEC_ELT (expanded_specs, i);
9875                 else
9876                   spec = tsubst (TREE_VALUE (specs), args, complain, in_decl);
9877                 if (spec == error_mark_node)
9878                   return spec;
9879                 new_specs = add_exception_specifier (new_specs, spec, 
9880                                                      complain);
9881               }
9882
9883             specs = TREE_CHAIN (specs);
9884           }
9885     }
9886   return new_specs;
9887 }
9888
9889 /* Take the tree structure T and replace template parameters used
9890    therein with the argument vector ARGS.  IN_DECL is an associated
9891    decl for diagnostics.  If an error occurs, returns ERROR_MARK_NODE.
9892    Issue error and warning messages under control of COMPLAIN.  Note
9893    that we must be relatively non-tolerant of extensions here, in
9894    order to preserve conformance; if we allow substitutions that
9895    should not be allowed, we may allow argument deductions that should
9896    not succeed, and therefore report ambiguous overload situations
9897    where there are none.  In theory, we could allow the substitution,
9898    but indicate that it should have failed, and allow our caller to
9899    make sure that the right thing happens, but we don't try to do this
9900    yet.
9901
9902    This function is used for dealing with types, decls and the like;
9903    for expressions, use tsubst_expr or tsubst_copy.  */
9904
9905 tree
9906 tsubst (tree t, tree args, tsubst_flags_t complain, tree in_decl)
9907 {
9908   tree type, r;
9909
9910   if (t == NULL_TREE || t == error_mark_node
9911       || t == integer_type_node
9912       || t == void_type_node
9913       || t == char_type_node
9914       || t == unknown_type_node
9915       || TREE_CODE (t) == NAMESPACE_DECL)
9916     return t;
9917
9918   if (DECL_P (t))
9919     return tsubst_decl (t, args, complain);
9920
9921   if (args == NULL_TREE)
9922     return t;
9923
9924   if (TREE_CODE (t) == IDENTIFIER_NODE)
9925     type = IDENTIFIER_TYPE_VALUE (t);
9926   else
9927     type = TREE_TYPE (t);
9928
9929   gcc_assert (type != unknown_type_node);
9930
9931   /* Reuse typedefs.  We need to do this to handle dependent attributes,
9932      such as attribute aligned.  */
9933   if (TYPE_P (t)
9934       && TYPE_NAME (t)
9935       && TYPE_NAME (t) != TYPE_MAIN_DECL (t))
9936     {
9937       tree decl = TYPE_NAME (t);
9938       
9939       if (DECL_CLASS_SCOPE_P (decl)
9940           && CLASSTYPE_TEMPLATE_INFO (DECL_CONTEXT (decl))
9941           && uses_template_parms (DECL_CONTEXT (decl)))
9942         {
9943           tree tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
9944           tree gen_args = tsubst (DECL_TI_ARGS (decl), args, complain, in_decl);
9945           r = retrieve_specialization (tmpl, gen_args, 0);
9946         }
9947       else if (DECL_FUNCTION_SCOPE_P (decl)
9948                && DECL_TEMPLATE_INFO (DECL_CONTEXT (decl))
9949                && uses_template_parms (DECL_TI_ARGS (DECL_CONTEXT (decl))))
9950         r = retrieve_local_specialization (decl);
9951       else
9952         /* The typedef is from a non-template context.  */
9953         return t;
9954
9955       if (r)
9956         {
9957           r = TREE_TYPE (r);
9958           r = cp_build_qualified_type_real
9959             (r, cp_type_quals (t) | cp_type_quals (r),
9960              complain | tf_ignore_bad_quals);
9961           return r;
9962         }
9963       /* Else we must be instantiating the typedef, so fall through.  */
9964     }
9965
9966   if (type
9967       && TREE_CODE (t) != TYPENAME_TYPE
9968       && TREE_CODE (t) != TEMPLATE_TYPE_PARM
9969       && TREE_CODE (t) != IDENTIFIER_NODE
9970       && TREE_CODE (t) != FUNCTION_TYPE
9971       && TREE_CODE (t) != METHOD_TYPE)
9972     type = tsubst (type, args, complain, in_decl);
9973   if (type == error_mark_node)
9974     return error_mark_node;
9975
9976   switch (TREE_CODE (t))
9977     {
9978     case RECORD_TYPE:
9979     case UNION_TYPE:
9980     case ENUMERAL_TYPE:
9981       return tsubst_aggr_type (t, args, complain, in_decl,
9982                                /*entering_scope=*/0);
9983
9984     case ERROR_MARK:
9985     case IDENTIFIER_NODE:
9986     case VOID_TYPE:
9987     case REAL_TYPE:
9988     case COMPLEX_TYPE:
9989     case VECTOR_TYPE:
9990     case BOOLEAN_TYPE:
9991     case INTEGER_CST:
9992     case REAL_CST:
9993     case STRING_CST:
9994       return t;
9995
9996     case INTEGER_TYPE:
9997       if (t == integer_type_node)
9998         return t;
9999
10000       if (TREE_CODE (TYPE_MIN_VALUE (t)) == INTEGER_CST
10001           && TREE_CODE (TYPE_MAX_VALUE (t)) == INTEGER_CST)
10002         return t;
10003
10004       {
10005         tree max, omax = TREE_OPERAND (TYPE_MAX_VALUE (t), 0);
10006
10007         max = tsubst_expr (omax, args, complain, in_decl,
10008                            /*integral_constant_expression_p=*/false);
10009
10010         /* Fix up type of the magic NOP_EXPR with TREE_SIDE_EFFECTS if
10011            needed.  */
10012         if (TREE_CODE (max) == NOP_EXPR
10013             && TREE_SIDE_EFFECTS (omax)
10014             && !TREE_TYPE (max))
10015           TREE_TYPE (max) = TREE_TYPE (TREE_OPERAND (max, 0));
10016
10017         max = fold_decl_constant_value (max);
10018
10019         /* If we're in a partial instantiation, preserve the magic NOP_EXPR
10020            with TREE_SIDE_EFFECTS that indicates this is not an integral
10021            constant expression.  */
10022         if (processing_template_decl
10023             && TREE_SIDE_EFFECTS (omax) && TREE_CODE (omax) == NOP_EXPR)
10024           {
10025             gcc_assert (TREE_CODE (max) == NOP_EXPR);
10026             TREE_SIDE_EFFECTS (max) = 1;
10027           }
10028
10029         if (TREE_CODE (max) != INTEGER_CST
10030             && !at_function_scope_p ()
10031             && !TREE_SIDE_EFFECTS (max)
10032             && !value_dependent_expression_p (max))
10033           {
10034             if (complain & tf_error)
10035               error ("array bound is not an integer constant");
10036             return error_mark_node;
10037           }
10038
10039         /* [temp.deduct]
10040
10041            Type deduction may fail for any of the following
10042            reasons:
10043
10044              Attempting to create an array with a size that is
10045              zero or negative.  */
10046         if (integer_zerop (max) && !(complain & tf_error))
10047           /* We must fail if performing argument deduction (as
10048              indicated by the state of complain), so that
10049              another substitution can be found.  */
10050           return error_mark_node;
10051         else if (TREE_CODE (max) == INTEGER_CST
10052                  && INT_CST_LT (max, integer_zero_node))
10053           {
10054             if (complain & tf_error)
10055               error ("creating array with negative size (%qE)", max);
10056
10057             return error_mark_node;
10058           }
10059
10060         return compute_array_index_type (NULL_TREE, max);
10061       }
10062
10063     case TEMPLATE_TYPE_PARM:
10064     case TEMPLATE_TEMPLATE_PARM:
10065     case BOUND_TEMPLATE_TEMPLATE_PARM:
10066     case TEMPLATE_PARM_INDEX:
10067       {
10068         int idx;
10069         int level;
10070         int levels;
10071         tree arg = NULL_TREE;
10072
10073         r = NULL_TREE;
10074
10075         gcc_assert (TREE_VEC_LENGTH (args) > 0);
10076         template_parm_level_and_index (t, &level, &idx); 
10077
10078         levels = TMPL_ARGS_DEPTH (args);
10079         if (level <= levels)
10080           {
10081             arg = TMPL_ARG (args, level, idx);
10082
10083             if (arg && TREE_CODE (arg) == ARGUMENT_PACK_SELECT)
10084               /* See through ARGUMENT_PACK_SELECT arguments. */
10085               arg = ARGUMENT_PACK_SELECT_ARG (arg);
10086           }
10087
10088         if (arg == error_mark_node)
10089           return error_mark_node;
10090         else if (arg != NULL_TREE)
10091           {
10092             if (ARGUMENT_PACK_P (arg))
10093               /* If ARG is an argument pack, we don't actually want to
10094                  perform a substitution here, because substitutions
10095                  for argument packs are only done
10096                  element-by-element. We can get to this point when
10097                  substituting the type of a non-type template
10098                  parameter pack, when that type actually contains
10099                  template parameter packs from an outer template, e.g.,
10100
10101                  template<typename... Types> struct A {
10102                    template<Types... Values> struct B { };
10103                  };  */
10104               return t;
10105
10106             if (TREE_CODE (t) == TEMPLATE_TYPE_PARM)
10107               {
10108                 int quals;
10109                 gcc_assert (TYPE_P (arg));
10110
10111                 /* cv-quals from the template are discarded when
10112                    substituting in a function or reference type.  */
10113                 if (TREE_CODE (arg) == FUNCTION_TYPE
10114                     || TREE_CODE (arg) == METHOD_TYPE
10115                     || TREE_CODE (arg) == REFERENCE_TYPE)
10116                   quals = cp_type_quals (arg);
10117                 else
10118                   quals = cp_type_quals (arg) | cp_type_quals (t);
10119                   
10120                 return cp_build_qualified_type_real
10121                   (arg, quals, complain | tf_ignore_bad_quals);
10122               }
10123             else if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
10124               {
10125                 /* We are processing a type constructed from a
10126                    template template parameter.  */
10127                 tree argvec = tsubst (TYPE_TI_ARGS (t),
10128                                       args, complain, in_decl);
10129                 if (argvec == error_mark_node)
10130                   return error_mark_node;
10131
10132                 /* We can get a TEMPLATE_TEMPLATE_PARM here when we
10133                    are resolving nested-types in the signature of a
10134                    member function templates.  Otherwise ARG is a
10135                    TEMPLATE_DECL and is the real template to be
10136                    instantiated.  */
10137                 if (TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
10138                   arg = TYPE_NAME (arg);
10139
10140                 r = lookup_template_class (arg,
10141                                            argvec, in_decl,
10142                                            DECL_CONTEXT (arg),
10143                                             /*entering_scope=*/0,
10144                                            complain);
10145                 return cp_build_qualified_type_real
10146                   (r, TYPE_QUALS (t), complain);
10147               }
10148             else
10149               /* TEMPLATE_TEMPLATE_PARM or TEMPLATE_PARM_INDEX.  */
10150               return arg;
10151           }
10152
10153         if (level == 1)
10154           /* This can happen during the attempted tsubst'ing in
10155              unify.  This means that we don't yet have any information
10156              about the template parameter in question.  */
10157           return t;
10158
10159         /* If we get here, we must have been looking at a parm for a
10160            more deeply nested template.  Make a new version of this
10161            template parameter, but with a lower level.  */
10162         switch (TREE_CODE (t))
10163           {
10164           case TEMPLATE_TYPE_PARM:
10165           case TEMPLATE_TEMPLATE_PARM:
10166           case BOUND_TEMPLATE_TEMPLATE_PARM:
10167             if (cp_type_quals (t))
10168               {
10169                 r = tsubst (TYPE_MAIN_VARIANT (t), args, complain, in_decl);
10170                 r = cp_build_qualified_type_real
10171                   (r, cp_type_quals (t),
10172                    complain | (TREE_CODE (t) == TEMPLATE_TYPE_PARM
10173                                ? tf_ignore_bad_quals : 0));
10174               }
10175             else
10176               {
10177                 r = copy_type (t);
10178                 TEMPLATE_TYPE_PARM_INDEX (r)
10179                   = reduce_template_parm_level (TEMPLATE_TYPE_PARM_INDEX (t),
10180                                                 r, levels, args, complain);
10181                 TYPE_STUB_DECL (r) = TYPE_NAME (r) = TEMPLATE_TYPE_DECL (r);
10182                 TYPE_MAIN_VARIANT (r) = r;
10183                 TYPE_POINTER_TO (r) = NULL_TREE;
10184                 TYPE_REFERENCE_TO (r) = NULL_TREE;
10185
10186                 if (TREE_CODE (r) == TEMPLATE_TEMPLATE_PARM)
10187                   /* We have reduced the level of the template
10188                      template parameter, but not the levels of its
10189                      template parameters, so canonical_type_parameter
10190                      will not be able to find the canonical template
10191                      template parameter for this level. Thus, we
10192                      require structural equality checking to compare
10193                      TEMPLATE_TEMPLATE_PARMs. */
10194                   SET_TYPE_STRUCTURAL_EQUALITY (r);
10195                 else if (TYPE_STRUCTURAL_EQUALITY_P (t))
10196                   SET_TYPE_STRUCTURAL_EQUALITY (r);
10197                 else
10198                   TYPE_CANONICAL (r) = canonical_type_parameter (r);
10199
10200                 if (TREE_CODE (t) == BOUND_TEMPLATE_TEMPLATE_PARM)
10201                   {
10202                     tree argvec = tsubst (TYPE_TI_ARGS (t), args,
10203                                           complain, in_decl);
10204                     if (argvec == error_mark_node)
10205                       return error_mark_node;
10206
10207                     TEMPLATE_TEMPLATE_PARM_TEMPLATE_INFO (r)
10208                       = build_template_info (TYPE_TI_TEMPLATE (t), argvec);
10209                   }
10210               }
10211             break;
10212
10213           case TEMPLATE_PARM_INDEX:
10214             r = reduce_template_parm_level (t, type, levels, args, complain);
10215             break;
10216
10217           default:
10218             gcc_unreachable ();
10219           }
10220
10221         return r;
10222       }
10223
10224     case TREE_LIST:
10225       {
10226         tree purpose, value, chain;
10227
10228         if (t == void_list_node)
10229           return t;
10230
10231         purpose = TREE_PURPOSE (t);
10232         if (purpose)
10233           {
10234             purpose = tsubst (purpose, args, complain, in_decl);
10235             if (purpose == error_mark_node)
10236               return error_mark_node;
10237           }
10238         value = TREE_VALUE (t);
10239         if (value)
10240           {
10241             value = tsubst (value, args, complain, in_decl);
10242             if (value == error_mark_node)
10243               return error_mark_node;
10244           }
10245         chain = TREE_CHAIN (t);
10246         if (chain && chain != void_type_node)
10247           {
10248             chain = tsubst (chain, args, complain, in_decl);
10249             if (chain == error_mark_node)
10250               return error_mark_node;
10251           }
10252         if (purpose == TREE_PURPOSE (t)
10253             && value == TREE_VALUE (t)
10254             && chain == TREE_CHAIN (t))
10255           return t;
10256         return hash_tree_cons (purpose, value, chain);
10257       }
10258
10259     case TREE_BINFO:
10260       /* We should never be tsubsting a binfo.  */
10261       gcc_unreachable ();
10262
10263     case TREE_VEC:
10264       /* A vector of template arguments.  */
10265       gcc_assert (!type);
10266       return tsubst_template_args (t, args, complain, in_decl);
10267
10268     case POINTER_TYPE:
10269     case REFERENCE_TYPE:
10270       {
10271         enum tree_code code;
10272
10273         if (type == TREE_TYPE (t) && TREE_CODE (type) != METHOD_TYPE)
10274           return t;
10275
10276         code = TREE_CODE (t);
10277
10278
10279         /* [temp.deduct]
10280
10281            Type deduction may fail for any of the following
10282            reasons:
10283
10284            -- Attempting to create a pointer to reference type.
10285            -- Attempting to create a reference to a reference type or
10286               a reference to void.
10287
10288           Core issue 106 says that creating a reference to a reference
10289           during instantiation is no longer a cause for failure. We
10290           only enforce this check in strict C++98 mode.  */
10291         if ((TREE_CODE (type) == REFERENCE_TYPE
10292              && (((cxx_dialect == cxx98) && flag_iso) || code != REFERENCE_TYPE))
10293             || (code == REFERENCE_TYPE && TREE_CODE (type) == VOID_TYPE))
10294           {
10295             static location_t last_loc;
10296
10297             /* We keep track of the last time we issued this error
10298                message to avoid spewing a ton of messages during a
10299                single bad template instantiation.  */
10300             if (complain & tf_error
10301                 && last_loc != input_location)
10302               {
10303                 if (TREE_CODE (type) == VOID_TYPE)
10304                   error ("forming reference to void");
10305                else if (code == POINTER_TYPE)
10306                  error ("forming pointer to reference type %qT", type);
10307                else
10308                   error ("forming reference to reference type %qT", type);
10309                 last_loc = input_location;
10310               }
10311
10312             return error_mark_node;
10313           }
10314         else if (code == POINTER_TYPE)
10315           {
10316             r = build_pointer_type (type);
10317             if (TREE_CODE (type) == METHOD_TYPE)
10318               r = build_ptrmemfunc_type (r);
10319           }
10320         else if (TREE_CODE (type) == REFERENCE_TYPE)
10321           /* In C++0x, during template argument substitution, when there is an
10322              attempt to create a reference to a reference type, reference
10323              collapsing is applied as described in [14.3.1/4 temp.arg.type]:
10324
10325              "If a template-argument for a template-parameter T names a type
10326              that is a reference to a type A, an attempt to create the type
10327              'lvalue reference to cv T' creates the type 'lvalue reference to
10328              A,' while an attempt to create the type type rvalue reference to
10329              cv T' creates the type T"
10330           */
10331           r = cp_build_reference_type
10332               (TREE_TYPE (type),
10333                TYPE_REF_IS_RVALUE (t) && TYPE_REF_IS_RVALUE (type));
10334         else
10335           r = cp_build_reference_type (type, TYPE_REF_IS_RVALUE (t));
10336         r = cp_build_qualified_type_real (r, TYPE_QUALS (t), complain);
10337
10338         if (r != error_mark_node)
10339           /* Will this ever be needed for TYPE_..._TO values?  */
10340           layout_type (r);
10341
10342         return r;
10343       }
10344     case OFFSET_TYPE:
10345       {
10346         r = tsubst (TYPE_OFFSET_BASETYPE (t), args, complain, in_decl);
10347         if (r == error_mark_node || !MAYBE_CLASS_TYPE_P (r))
10348           {
10349             /* [temp.deduct]
10350
10351                Type deduction may fail for any of the following
10352                reasons:
10353
10354                -- Attempting to create "pointer to member of T" when T
10355                   is not a class type.  */
10356             if (complain & tf_error)
10357               error ("creating pointer to member of non-class type %qT", r);
10358             return error_mark_node;
10359           }
10360         if (TREE_CODE (type) == REFERENCE_TYPE)
10361           {
10362             if (complain & tf_error)
10363               error ("creating pointer to member reference type %qT", type);
10364             return error_mark_node;
10365           }
10366         if (TREE_CODE (type) == VOID_TYPE)
10367           {
10368             if (complain & tf_error)
10369               error ("creating pointer to member of type void");
10370             return error_mark_node;
10371           }
10372         gcc_assert (TREE_CODE (type) != METHOD_TYPE);
10373         if (TREE_CODE (type) == FUNCTION_TYPE)
10374           {
10375             /* The type of the implicit object parameter gets its
10376                cv-qualifiers from the FUNCTION_TYPE. */
10377             tree memptr;
10378             tree method_type = build_memfn_type (type, r, cp_type_quals (type));
10379             memptr = build_ptrmemfunc_type (build_pointer_type (method_type));
10380             return cp_build_qualified_type_real (memptr, cp_type_quals (t),
10381                                                  complain);
10382           }
10383         else
10384           return cp_build_qualified_type_real (build_ptrmem_type (r, type),
10385                                                TYPE_QUALS (t),
10386                                                complain);
10387       }
10388     case FUNCTION_TYPE:
10389     case METHOD_TYPE:
10390       {
10391         tree fntype;
10392         tree specs;
10393         fntype = tsubst_function_type (t, args, complain, in_decl);
10394         if (fntype == error_mark_node)
10395           return error_mark_node;
10396
10397         /* Substitute the exception specification.  */
10398         specs = tsubst_exception_specification (t, args, complain,
10399                                                 in_decl);
10400         if (specs == error_mark_node)
10401           return error_mark_node;
10402         if (specs)
10403           fntype = build_exception_variant (fntype, specs);
10404         return fntype;
10405       }
10406     case ARRAY_TYPE:
10407       {
10408         tree domain = tsubst (TYPE_DOMAIN (t), args, complain, in_decl);
10409         if (domain == error_mark_node)
10410           return error_mark_node;
10411
10412         /* As an optimization, we avoid regenerating the array type if
10413            it will obviously be the same as T.  */
10414         if (type == TREE_TYPE (t) && domain == TYPE_DOMAIN (t))
10415           return t;
10416
10417         /* These checks should match the ones in grokdeclarator.
10418
10419            [temp.deduct]
10420
10421            The deduction may fail for any of the following reasons:
10422
10423            -- Attempting to create an array with an element type that
10424               is void, a function type, or a reference type, or [DR337]
10425               an abstract class type.  */
10426         if (TREE_CODE (type) == VOID_TYPE
10427             || TREE_CODE (type) == FUNCTION_TYPE
10428             || TREE_CODE (type) == REFERENCE_TYPE)
10429           {
10430             if (complain & tf_error)
10431               error ("creating array of %qT", type);
10432             return error_mark_node;
10433           }
10434         if (CLASS_TYPE_P (type) && CLASSTYPE_PURE_VIRTUALS (type))
10435           {
10436             if (complain & tf_error)
10437               error ("creating array of %qT, which is an abstract class type",
10438                      type);
10439             return error_mark_node;
10440           }
10441
10442         r = build_cplus_array_type (type, domain);
10443
10444         if (TYPE_USER_ALIGN (t))
10445           {
10446             TYPE_ALIGN (r) = TYPE_ALIGN (t);
10447             TYPE_USER_ALIGN (r) = 1;
10448           }
10449
10450         return r;
10451       }
10452
10453     case PLUS_EXPR:
10454     case MINUS_EXPR:
10455       {
10456         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10457         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
10458
10459         if (e1 == error_mark_node || e2 == error_mark_node)
10460           return error_mark_node;
10461
10462         return fold_build2_loc (input_location,
10463                             TREE_CODE (t), TREE_TYPE (t), e1, e2);
10464       }
10465
10466     case NEGATE_EXPR:
10467     case NOP_EXPR:
10468       {
10469         tree e = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10470         if (e == error_mark_node)
10471           return error_mark_node;
10472
10473         return fold_build1_loc (input_location, TREE_CODE (t), TREE_TYPE (t), e);
10474       }
10475
10476     case TYPENAME_TYPE:
10477       {
10478         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10479                                      in_decl, /*entering_scope=*/1);
10480         tree f = tsubst_copy (TYPENAME_TYPE_FULLNAME (t), args,
10481                               complain, in_decl);
10482
10483         if (ctx == error_mark_node || f == error_mark_node)
10484           return error_mark_node;
10485
10486         if (!MAYBE_CLASS_TYPE_P (ctx))
10487           {
10488             if (complain & tf_error)
10489               error ("%qT is not a class, struct, or union type", ctx);
10490             return error_mark_node;
10491           }
10492         else if (!uses_template_parms (ctx) && !TYPE_BEING_DEFINED (ctx))
10493           {
10494             /* Normally, make_typename_type does not require that the CTX
10495                have complete type in order to allow things like:
10496
10497                  template <class T> struct S { typename S<T>::X Y; };
10498
10499                But, such constructs have already been resolved by this
10500                point, so here CTX really should have complete type, unless
10501                it's a partial instantiation.  */
10502             if (!(complain & tf_no_class_instantiations))
10503               ctx = complete_type (ctx);
10504             if (!COMPLETE_TYPE_P (ctx))
10505               {
10506                 if (complain & tf_error)
10507                   cxx_incomplete_type_error (NULL_TREE, ctx);
10508                 return error_mark_node;
10509               }
10510           }
10511
10512         f = make_typename_type (ctx, f, typename_type,
10513                                 (complain & tf_error) | tf_keep_type_decl);
10514         if (f == error_mark_node)
10515           return f;
10516         if (TREE_CODE (f) == TYPE_DECL)
10517           {
10518             complain |= tf_ignore_bad_quals;
10519             f = TREE_TYPE (f);
10520           }
10521
10522         if (TREE_CODE (f) != TYPENAME_TYPE)
10523           {
10524             if (TYPENAME_IS_ENUM_P (t) && TREE_CODE (f) != ENUMERAL_TYPE)
10525               error ("%qT resolves to %qT, which is not an enumeration type",
10526                      t, f);
10527             else if (TYPENAME_IS_CLASS_P (t) && !CLASS_TYPE_P (f))
10528               error ("%qT resolves to %qT, which is is not a class type",
10529                      t, f);
10530           }
10531
10532         return cp_build_qualified_type_real
10533           (f, cp_type_quals (f) | cp_type_quals (t), complain);
10534       }
10535
10536     case UNBOUND_CLASS_TEMPLATE:
10537       {
10538         tree ctx = tsubst_aggr_type (TYPE_CONTEXT (t), args, complain,
10539                                      in_decl, /*entering_scope=*/1);
10540         tree name = TYPE_IDENTIFIER (t);
10541         tree parm_list = DECL_TEMPLATE_PARMS (TYPE_NAME (t));
10542
10543         if (ctx == error_mark_node || name == error_mark_node)
10544           return error_mark_node;
10545
10546         if (parm_list)
10547           parm_list = tsubst_template_parms (parm_list, args, complain);
10548         return make_unbound_class_template (ctx, name, parm_list, complain);
10549       }
10550
10551     case INDIRECT_REF:
10552     case ADDR_EXPR:
10553     case CALL_EXPR:
10554       gcc_unreachable ();
10555
10556     case ARRAY_REF:
10557       {
10558         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10559         tree e2 = tsubst_expr (TREE_OPERAND (t, 1), args, complain, in_decl,
10560                                /*integral_constant_expression_p=*/false);
10561         if (e1 == error_mark_node || e2 == error_mark_node)
10562           return error_mark_node;
10563
10564         return build_nt (ARRAY_REF, e1, e2, NULL_TREE, NULL_TREE);
10565       }
10566
10567     case SCOPE_REF:
10568       {
10569         tree e1 = tsubst (TREE_OPERAND (t, 0), args, complain, in_decl);
10570         tree e2 = tsubst (TREE_OPERAND (t, 1), args, complain, in_decl);
10571         if (e1 == error_mark_node || e2 == error_mark_node)
10572           return error_mark_node;
10573
10574         return build_qualified_name (/*type=*/NULL_TREE,
10575                                      e1, e2, QUALIFIED_NAME_IS_TEMPLATE (t));
10576       }
10577
10578     case TYPEOF_TYPE:
10579       {
10580         tree type;
10581
10582         ++cp_unevaluated_operand;
10583         ++c_inhibit_evaluation_warnings;
10584
10585         type = tsubst_expr (TYPEOF_TYPE_EXPR (t), args,
10586                             complain, in_decl,
10587                             /*integral_constant_expression_p=*/false);
10588
10589         --cp_unevaluated_operand;
10590         --c_inhibit_evaluation_warnings;
10591
10592         type = finish_typeof (type);
10593         return cp_build_qualified_type_real (type,
10594                                              cp_type_quals (t)
10595                                              | cp_type_quals (type),
10596                                              complain);
10597       }
10598
10599     case DECLTYPE_TYPE:
10600       {
10601         tree type;
10602
10603         ++cp_unevaluated_operand;
10604         ++c_inhibit_evaluation_warnings;
10605
10606         type = tsubst_expr (DECLTYPE_TYPE_EXPR (t), args,
10607                             complain, in_decl,
10608                             /*integral_constant_expression_p=*/false);
10609
10610         --cp_unevaluated_operand;
10611         --c_inhibit_evaluation_warnings;
10612
10613         if (DECLTYPE_FOR_LAMBDA_CAPTURE (t))
10614           type = lambda_capture_field_type (type);
10615         else if (DECLTYPE_FOR_LAMBDA_RETURN (t))
10616           type = lambda_return_type (type);
10617         else
10618           type = finish_decltype_type
10619             (type, DECLTYPE_TYPE_ID_EXPR_OR_MEMBER_ACCESS_P (t));
10620         return cp_build_qualified_type_real (type,
10621                                              cp_type_quals (t)
10622                                              | cp_type_quals (type),
10623                                              complain);
10624       }
10625
10626     case TYPE_ARGUMENT_PACK:
10627     case NONTYPE_ARGUMENT_PACK:
10628       {
10629         tree r = TYPE_P (t)
10630           ? cxx_make_type (TREE_CODE (t))
10631           : make_node (TREE_CODE (t));
10632         tree packed_out = 
10633           tsubst_template_args (ARGUMENT_PACK_ARGS (t), 
10634                                 args,
10635                                 complain,
10636                                 in_decl);
10637         SET_ARGUMENT_PACK_ARGS (r, packed_out);
10638
10639         /* For template nontype argument packs, also substitute into
10640            the type.  */
10641         if (TREE_CODE (t) == NONTYPE_ARGUMENT_PACK)
10642           TREE_TYPE (r) = tsubst (TREE_TYPE (t), args, complain, in_decl);
10643
10644         return r;
10645       }
10646       break;
10647
10648     default:
10649       sorry ("use of %qs in template",
10650              tree_code_name [(int) TREE_CODE (t)]);
10651       return error_mark_node;
10652     }
10653 }
10654
10655 /* Like tsubst_expr for a BASELINK.  OBJECT_TYPE, if non-NULL, is the
10656    type of the expression on the left-hand side of the "." or "->"
10657    operator.  */
10658
10659 static tree
10660 tsubst_baselink (tree baselink, tree object_type,
10661                  tree args, tsubst_flags_t complain, tree in_decl)
10662 {
10663     tree name;
10664     tree qualifying_scope;
10665     tree fns;
10666     tree optype;
10667     tree template_args = 0;
10668     bool template_id_p = false;
10669
10670     /* A baselink indicates a function from a base class.  Both the
10671        BASELINK_ACCESS_BINFO and the base class referenced may
10672        indicate bases of the template class, rather than the
10673        instantiated class.  In addition, lookups that were not
10674        ambiguous before may be ambiguous now.  Therefore, we perform
10675        the lookup again.  */
10676     qualifying_scope = BINFO_TYPE (BASELINK_ACCESS_BINFO (baselink));
10677     qualifying_scope = tsubst (qualifying_scope, args,
10678                                complain, in_decl);
10679     fns = BASELINK_FUNCTIONS (baselink);
10680     optype = tsubst (BASELINK_OPTYPE (baselink), args, complain, in_decl);
10681     if (TREE_CODE (fns) == TEMPLATE_ID_EXPR)
10682       {
10683         template_id_p = true;
10684         template_args = TREE_OPERAND (fns, 1);
10685         fns = TREE_OPERAND (fns, 0);
10686         if (template_args)
10687           template_args = tsubst_template_args (template_args, args,
10688                                                 complain, in_decl);
10689       }
10690     name = DECL_NAME (get_first_fn (fns));
10691     if (IDENTIFIER_TYPENAME_P (name))
10692       name = mangle_conv_op_name_for_type (optype);
10693     baselink = lookup_fnfields (qualifying_scope, name, /*protect=*/1);
10694
10695     /* If lookup found a single function, mark it as used at this
10696        point.  (If it lookup found multiple functions the one selected
10697        later by overload resolution will be marked as used at that
10698        point.)  */
10699     if (BASELINK_P (baselink))
10700       fns = BASELINK_FUNCTIONS (baselink);
10701     if (!template_id_p && !really_overloaded_fn (fns))
10702       mark_used (OVL_CURRENT (fns));
10703
10704     /* Add back the template arguments, if present.  */
10705     if (BASELINK_P (baselink) && template_id_p)
10706       BASELINK_FUNCTIONS (baselink)
10707         = build_nt (TEMPLATE_ID_EXPR,
10708                     BASELINK_FUNCTIONS (baselink),
10709                     template_args);
10710     /* Update the conversion operator type.  */
10711     BASELINK_OPTYPE (baselink) = optype;
10712
10713     if (!object_type)
10714       object_type = current_class_type;
10715     return adjust_result_of_qualified_name_lookup (baselink,
10716                                                    qualifying_scope,
10717                                                    object_type);
10718 }
10719
10720 /* Like tsubst_expr for a SCOPE_REF, given by QUALIFIED_ID.  DONE is
10721    true if the qualified-id will be a postfix-expression in-and-of
10722    itself; false if more of the postfix-expression follows the
10723    QUALIFIED_ID.  ADDRESS_P is true if the qualified-id is the operand
10724    of "&".  */
10725
10726 static tree
10727 tsubst_qualified_id (tree qualified_id, tree args,
10728                      tsubst_flags_t complain, tree in_decl,
10729                      bool done, bool address_p)
10730 {
10731   tree expr;
10732   tree scope;
10733   tree name;
10734   bool is_template;
10735   tree template_args;
10736
10737   gcc_assert (TREE_CODE (qualified_id) == SCOPE_REF);
10738
10739   /* Figure out what name to look up.  */
10740   name = TREE_OPERAND (qualified_id, 1);
10741   if (TREE_CODE (name) == TEMPLATE_ID_EXPR)
10742     {
10743       is_template = true;
10744       template_args = TREE_OPERAND (name, 1);
10745       if (template_args)
10746         template_args = tsubst_template_args (template_args, args,
10747                                               complain, in_decl);
10748       name = TREE_OPERAND (name, 0);
10749     }
10750   else
10751     {
10752       is_template = false;
10753       template_args = NULL_TREE;
10754     }
10755
10756   /* Substitute into the qualifying scope.  When there are no ARGS, we
10757      are just trying to simplify a non-dependent expression.  In that
10758      case the qualifying scope may be dependent, and, in any case,
10759      substituting will not help.  */
10760   scope = TREE_OPERAND (qualified_id, 0);
10761   if (args)
10762     {
10763       scope = tsubst (scope, args, complain, in_decl);
10764       expr = tsubst_copy (name, args, complain, in_decl);
10765     }
10766   else
10767     expr = name;
10768
10769   if (dependent_scope_p (scope))
10770     return build_qualified_name (NULL_TREE, scope, expr,
10771                                  QUALIFIED_NAME_IS_TEMPLATE (qualified_id));
10772
10773   if (!BASELINK_P (name) && !DECL_P (expr))
10774     {
10775       if (TREE_CODE (expr) == BIT_NOT_EXPR)
10776         {
10777           /* A BIT_NOT_EXPR is used to represent a destructor.  */
10778           if (!check_dtor_name (scope, TREE_OPERAND (expr, 0)))
10779             {
10780               error ("qualifying type %qT does not match destructor name ~%qT",
10781                      scope, TREE_OPERAND (expr, 0));
10782               expr = error_mark_node;
10783             }
10784           else
10785             expr = lookup_qualified_name (scope, complete_dtor_identifier,
10786                                           /*is_type_p=*/0, false);
10787         }
10788       else
10789         expr = lookup_qualified_name (scope, expr, /*is_type_p=*/0, false);
10790       if (TREE_CODE (TREE_CODE (expr) == TEMPLATE_DECL
10791                      ? DECL_TEMPLATE_RESULT (expr) : expr) == TYPE_DECL)
10792         {
10793           if (complain & tf_error)
10794             {
10795               error ("dependent-name %qE is parsed as a non-type, but "
10796                      "instantiation yields a type", qualified_id);
10797               inform (input_location, "say %<typename %E%> if a type is meant", qualified_id);
10798             }
10799           return error_mark_node;
10800         }
10801     }
10802
10803   if (DECL_P (expr))
10804     {
10805       check_accessibility_of_qualified_id (expr, /*object_type=*/NULL_TREE,
10806                                            scope);
10807       /* Remember that there was a reference to this entity.  */
10808       mark_used (expr);
10809     }
10810
10811   if (expr == error_mark_node || TREE_CODE (expr) == TREE_LIST)
10812     {
10813       if (complain & tf_error)
10814         qualified_name_lookup_error (scope,
10815                                      TREE_OPERAND (qualified_id, 1),
10816                                      expr, input_location);
10817       return error_mark_node;
10818     }
10819
10820   if (is_template)
10821     expr = lookup_template_function (expr, template_args);
10822
10823   if (expr == error_mark_node && complain & tf_error)
10824     qualified_name_lookup_error (scope, TREE_OPERAND (qualified_id, 1),
10825                                  expr, input_location);
10826   else if (TYPE_P (scope))
10827     {
10828       expr = (adjust_result_of_qualified_name_lookup
10829               (expr, scope, current_class_type));
10830       expr = (finish_qualified_id_expr
10831               (scope, expr, done, address_p,
10832                QUALIFIED_NAME_IS_TEMPLATE (qualified_id),
10833                /*template_arg_p=*/false));
10834     }
10835
10836   /* Expressions do not generally have reference type.  */
10837   if (TREE_CODE (expr) != SCOPE_REF
10838       /* However, if we're about to form a pointer-to-member, we just
10839          want the referenced member referenced.  */
10840       && TREE_CODE (expr) != OFFSET_REF)
10841     expr = convert_from_reference (expr);
10842
10843   return expr;
10844 }
10845
10846 /* Like tsubst, but deals with expressions.  This function just replaces
10847    template parms; to finish processing the resultant expression, use
10848    tsubst_expr.  */
10849
10850 static tree
10851 tsubst_copy (tree t, tree args, tsubst_flags_t complain, tree in_decl)
10852 {
10853   enum tree_code code;
10854   tree r;
10855
10856   if (t == NULL_TREE || t == error_mark_node || args == NULL_TREE)
10857     return t;
10858
10859   code = TREE_CODE (t);
10860
10861   switch (code)
10862     {
10863     case PARM_DECL:
10864       r = retrieve_local_specialization (t);
10865
10866       if (r == NULL)
10867         {
10868           tree c;
10869           /* This can happen for a parameter name used later in a function
10870              declaration (such as in a late-specified return type).  Just
10871              make a dummy decl, since it's only used for its type.  */
10872           gcc_assert (cp_unevaluated_operand != 0);
10873           /* We copy T because want to tsubst the PARM_DECL only,
10874              not the following PARM_DECLs that are chained to T.  */
10875           c = copy_node (t);
10876           r = tsubst_decl (c, args, complain);
10877           /* Give it the template pattern as its context; its true context
10878              hasn't been instantiated yet and this is good enough for
10879              mangling.  */
10880           DECL_CONTEXT (r) = DECL_CONTEXT (t);
10881         }
10882       
10883       if (TREE_CODE (r) == ARGUMENT_PACK_SELECT)
10884         r = ARGUMENT_PACK_SELECT_ARG (r);
10885       mark_used (r);
10886       return r;
10887
10888     case CONST_DECL:
10889       {
10890         tree enum_type;
10891         tree v;
10892
10893         if (DECL_TEMPLATE_PARM_P (t))
10894           return tsubst_copy (DECL_INITIAL (t), args, complain, in_decl);
10895         /* There is no need to substitute into namespace-scope
10896            enumerators.  */
10897         if (DECL_NAMESPACE_SCOPE_P (t))
10898           return t;
10899         /* If ARGS is NULL, then T is known to be non-dependent.  */
10900         if (args == NULL_TREE)
10901           return integral_constant_value (t);
10902
10903         /* Unfortunately, we cannot just call lookup_name here.
10904            Consider:
10905
10906              template <int I> int f() {
10907              enum E { a = I };
10908              struct S { void g() { E e = a; } };
10909              };
10910
10911            When we instantiate f<7>::S::g(), say, lookup_name is not
10912            clever enough to find f<7>::a.  */
10913         enum_type
10914           = tsubst_aggr_type (TREE_TYPE (t), args, complain, in_decl,
10915                               /*entering_scope=*/0);
10916
10917         for (v = TYPE_VALUES (enum_type);
10918              v != NULL_TREE;
10919              v = TREE_CHAIN (v))
10920           if (TREE_PURPOSE (v) == DECL_NAME (t))
10921             return TREE_VALUE (v);
10922
10923           /* We didn't find the name.  That should never happen; if
10924              name-lookup found it during preliminary parsing, we
10925              should find it again here during instantiation.  */
10926         gcc_unreachable ();
10927       }
10928       return t;
10929
10930     case FIELD_DECL:
10931       if (DECL_CONTEXT (t))
10932         {
10933           tree ctx;
10934
10935           ctx = tsubst_aggr_type (DECL_CONTEXT (t), args, complain, in_decl,
10936                                   /*entering_scope=*/1);
10937           if (ctx != DECL_CONTEXT (t))
10938             {
10939               tree r = lookup_field (ctx, DECL_NAME (t), 0, false);
10940               if (!r)
10941                 {
10942                   if (complain & tf_error)
10943                     error ("using invalid field %qD", t);
10944                   return error_mark_node;
10945                 }
10946               return r;
10947             }
10948         }
10949
10950       return t;
10951
10952     case VAR_DECL:
10953     case FUNCTION_DECL:
10954       if ((DECL_LANG_SPECIFIC (t) && DECL_TEMPLATE_INFO (t))
10955           || local_variable_p (t))
10956         t = tsubst (t, args, complain, in_decl);
10957       mark_used (t);
10958       return t;
10959
10960     case BASELINK:
10961       return tsubst_baselink (t, current_class_type, args, complain, in_decl);
10962
10963     case TEMPLATE_DECL:
10964       if (DECL_TEMPLATE_TEMPLATE_PARM_P (t))
10965         return tsubst (TREE_TYPE (DECL_TEMPLATE_RESULT (t)),
10966                        args, complain, in_decl);
10967       else if (DECL_FUNCTION_TEMPLATE_P (t) && DECL_MEMBER_TEMPLATE_P (t))
10968         return tsubst (t, args, complain, in_decl);
10969       else if (DECL_CLASS_SCOPE_P (t)
10970                && uses_template_parms (DECL_CONTEXT (t)))
10971         {
10972           /* Template template argument like the following example need
10973              special treatment:
10974
10975                template <template <class> class TT> struct C {};
10976                template <class T> struct D {
10977                  template <class U> struct E {};
10978                  C<E> c;                                // #1
10979                };
10980                D<int> d;                                // #2
10981
10982              We are processing the template argument `E' in #1 for
10983              the template instantiation #2.  Originally, `E' is a
10984              TEMPLATE_DECL with `D<T>' as its DECL_CONTEXT.  Now we
10985              have to substitute this with one having context `D<int>'.  */
10986
10987           tree context = tsubst (DECL_CONTEXT (t), args, complain, in_decl);
10988           return lookup_field (context, DECL_NAME(t), 0, false);
10989         }
10990       else
10991         /* Ordinary template template argument.  */
10992         return t;
10993
10994     case CAST_EXPR:
10995     case REINTERPRET_CAST_EXPR:
10996     case CONST_CAST_EXPR:
10997     case STATIC_CAST_EXPR:
10998     case DYNAMIC_CAST_EXPR:
10999     case NOP_EXPR:
11000       return build1
11001         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11002          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11003
11004     case SIZEOF_EXPR:
11005       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
11006         {
11007           /* We only want to compute the number of arguments.  */
11008           tree expanded = tsubst_pack_expansion (TREE_OPERAND (t, 0), args,
11009                                                 complain, in_decl);
11010           int len = 0;
11011
11012           if (TREE_CODE (expanded) == TREE_VEC)
11013             len = TREE_VEC_LENGTH (expanded);
11014
11015           if (expanded == error_mark_node)
11016             return error_mark_node;
11017           else if (PACK_EXPANSION_P (expanded)
11018                    || (TREE_CODE (expanded) == TREE_VEC
11019                        && len > 0
11020                        && PACK_EXPANSION_P (TREE_VEC_ELT (expanded, len-1))))
11021             {
11022               if (TREE_CODE (expanded) == TREE_VEC)
11023                 expanded = TREE_VEC_ELT (expanded, len - 1);
11024
11025               if (TYPE_P (expanded))
11026                 return cxx_sizeof_or_alignof_type (expanded, SIZEOF_EXPR, 
11027                                                    complain & tf_error);
11028               else
11029                 return cxx_sizeof_or_alignof_expr (expanded, SIZEOF_EXPR,
11030                                                    complain & tf_error);
11031             }
11032           else
11033             return build_int_cst (size_type_node, len);
11034         }
11035       /* Fall through */
11036
11037     case INDIRECT_REF:
11038     case NEGATE_EXPR:
11039     case TRUTH_NOT_EXPR:
11040     case BIT_NOT_EXPR:
11041     case ADDR_EXPR:
11042     case UNARY_PLUS_EXPR:      /* Unary + */
11043     case ALIGNOF_EXPR:
11044     case ARROW_EXPR:
11045     case THROW_EXPR:
11046     case TYPEID_EXPR:
11047     case REALPART_EXPR:
11048     case IMAGPART_EXPR:
11049       return build1
11050         (code, tsubst (TREE_TYPE (t), args, complain, in_decl),
11051          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl));
11052
11053     case COMPONENT_REF:
11054       {
11055         tree object;
11056         tree name;
11057
11058         object = tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl);
11059         name = TREE_OPERAND (t, 1);
11060         if (TREE_CODE (name) == BIT_NOT_EXPR)
11061           {
11062             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11063                                 complain, in_decl);
11064             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11065           }
11066         else if (TREE_CODE (name) == SCOPE_REF
11067                  && TREE_CODE (TREE_OPERAND (name, 1)) == BIT_NOT_EXPR)
11068           {
11069             tree base = tsubst_copy (TREE_OPERAND (name, 0), args,
11070                                      complain, in_decl);
11071             name = TREE_OPERAND (name, 1);
11072             name = tsubst_copy (TREE_OPERAND (name, 0), args,
11073                                 complain, in_decl);
11074             name = build1 (BIT_NOT_EXPR, NULL_TREE, name);
11075             name = build_qualified_name (/*type=*/NULL_TREE,
11076                                          base, name,
11077                                          /*template_p=*/false);
11078           }
11079         else if (TREE_CODE (name) == BASELINK)
11080           name = tsubst_baselink (name,
11081                                   non_reference (TREE_TYPE (object)),
11082                                   args, complain,
11083                                   in_decl);
11084         else
11085           name = tsubst_copy (name, args, complain, in_decl);
11086         return build_nt (COMPONENT_REF, object, name, NULL_TREE);
11087       }
11088
11089     case PLUS_EXPR:
11090     case MINUS_EXPR:
11091     case MULT_EXPR:
11092     case TRUNC_DIV_EXPR:
11093     case CEIL_DIV_EXPR:
11094     case FLOOR_DIV_EXPR:
11095     case ROUND_DIV_EXPR:
11096     case EXACT_DIV_EXPR:
11097     case BIT_AND_EXPR:
11098     case BIT_IOR_EXPR:
11099     case BIT_XOR_EXPR:
11100     case TRUNC_MOD_EXPR:
11101     case FLOOR_MOD_EXPR:
11102     case TRUTH_ANDIF_EXPR:
11103     case TRUTH_ORIF_EXPR:
11104     case TRUTH_AND_EXPR:
11105     case TRUTH_OR_EXPR:
11106     case RSHIFT_EXPR:
11107     case LSHIFT_EXPR:
11108     case RROTATE_EXPR:
11109     case LROTATE_EXPR:
11110     case EQ_EXPR:
11111     case NE_EXPR:
11112     case MAX_EXPR:
11113     case MIN_EXPR:
11114     case LE_EXPR:
11115     case GE_EXPR:
11116     case LT_EXPR:
11117     case GT_EXPR:
11118     case COMPOUND_EXPR:
11119     case DOTSTAR_EXPR:
11120     case MEMBER_REF:
11121     case PREDECREMENT_EXPR:
11122     case PREINCREMENT_EXPR:
11123     case POSTDECREMENT_EXPR:
11124     case POSTINCREMENT_EXPR:
11125       return build_nt
11126         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11127          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11128
11129     case SCOPE_REF:
11130       return build_qualified_name (/*type=*/NULL_TREE,
11131                                    tsubst_copy (TREE_OPERAND (t, 0),
11132                                                 args, complain, in_decl),
11133                                    tsubst_copy (TREE_OPERAND (t, 1),
11134                                                 args, complain, in_decl),
11135                                    QUALIFIED_NAME_IS_TEMPLATE (t));
11136
11137     case ARRAY_REF:
11138       return build_nt
11139         (ARRAY_REF,
11140          tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11141          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11142          NULL_TREE, NULL_TREE);
11143
11144     case CALL_EXPR:
11145       {
11146         int n = VL_EXP_OPERAND_LENGTH (t);
11147         tree result = build_vl_exp (CALL_EXPR, n);
11148         int i;
11149         for (i = 0; i < n; i++)
11150           TREE_OPERAND (t, i) = tsubst_copy (TREE_OPERAND (t, i), args,
11151                                              complain, in_decl);
11152         return result;
11153       }
11154
11155     case COND_EXPR:
11156     case MODOP_EXPR:
11157     case PSEUDO_DTOR_EXPR:
11158       {
11159         r = build_nt
11160           (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11161            tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11162            tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
11163         TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
11164         return r;
11165       }
11166
11167     case NEW_EXPR:
11168       {
11169         r = build_nt
11170         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11171          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl),
11172          tsubst_copy (TREE_OPERAND (t, 2), args, complain, in_decl));
11173         NEW_EXPR_USE_GLOBAL (r) = NEW_EXPR_USE_GLOBAL (t);
11174         return r;
11175       }
11176
11177     case DELETE_EXPR:
11178       {
11179         r = build_nt
11180         (code, tsubst_copy (TREE_OPERAND (t, 0), args, complain, in_decl),
11181          tsubst_copy (TREE_OPERAND (t, 1), args, complain, in_decl));
11182         DELETE_EXPR_USE_GLOBAL (r) = DELETE_EXPR_USE_GLOBAL (t);
11183         DELETE_EXPR_USE_VEC (r) = DELETE_EXPR_USE_VEC (t);
11184         return r;
11185       }
11186
11187     case TEMPLATE_ID_EXPR:
11188       {
11189         /* Substituted template arguments */
11190         tree fn = TREE_OPERAND (t, 0);
11191         tree targs = TREE_OPERAND (t, 1);
11192
11193         fn = tsubst_copy (fn, args, complain, in_decl);
11194         if (targs)
11195           targs = tsubst_template_args (targs, args, complain, in_decl);
11196
11197         return lookup_template_function (fn, targs);
11198       }
11199
11200     case TREE_LIST:
11201       {
11202         tree purpose, value, chain;
11203
11204         if (t == void_list_node)
11205           return t;
11206
11207         purpose = TREE_PURPOSE (t);
11208         if (purpose)
11209           purpose = tsubst_copy (purpose, args, complain, in_decl);
11210         value = TREE_VALUE (t);
11211         if (value)
11212           value = tsubst_copy (value, args, complain, in_decl);
11213         chain = TREE_CHAIN (t);
11214         if (chain && chain != void_type_node)
11215           chain = tsubst_copy (chain, args, complain, in_decl);
11216         if (purpose == TREE_PURPOSE (t)
11217             && value == TREE_VALUE (t)
11218             && chain == TREE_CHAIN (t))
11219           return t;
11220         return tree_cons (purpose, value, chain);
11221       }
11222
11223     case RECORD_TYPE:
11224     case UNION_TYPE:
11225     case ENUMERAL_TYPE:
11226     case INTEGER_TYPE:
11227     case TEMPLATE_TYPE_PARM:
11228     case TEMPLATE_TEMPLATE_PARM:
11229     case BOUND_TEMPLATE_TEMPLATE_PARM:
11230     case TEMPLATE_PARM_INDEX:
11231     case POINTER_TYPE:
11232     case REFERENCE_TYPE:
11233     case OFFSET_TYPE:
11234     case FUNCTION_TYPE:
11235     case METHOD_TYPE:
11236     case ARRAY_TYPE:
11237     case TYPENAME_TYPE:
11238     case UNBOUND_CLASS_TEMPLATE:
11239     case TYPEOF_TYPE:
11240     case DECLTYPE_TYPE:
11241     case TYPE_DECL:
11242       return tsubst (t, args, complain, in_decl);
11243
11244     case IDENTIFIER_NODE:
11245       if (IDENTIFIER_TYPENAME_P (t))
11246         {
11247           tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
11248           return mangle_conv_op_name_for_type (new_type);
11249         }
11250       else
11251         return t;
11252
11253     case CONSTRUCTOR:
11254       /* This is handled by tsubst_copy_and_build.  */
11255       gcc_unreachable ();
11256
11257     case VA_ARG_EXPR:
11258       return build_x_va_arg (tsubst_copy (TREE_OPERAND (t, 0), args, complain,
11259                                           in_decl),
11260                              tsubst (TREE_TYPE (t), args, complain, in_decl));
11261
11262     case CLEANUP_POINT_EXPR:
11263       /* We shouldn't have built any of these during initial template
11264          generation.  Instead, they should be built during instantiation
11265          in response to the saved STMT_IS_FULL_EXPR_P setting.  */
11266       gcc_unreachable ();
11267
11268     case OFFSET_REF:
11269       mark_used (TREE_OPERAND (t, 1));
11270       return t;
11271
11272     case EXPR_PACK_EXPANSION:
11273       error ("invalid use of pack expansion expression");
11274       return error_mark_node;
11275
11276     case NONTYPE_ARGUMENT_PACK:
11277       error ("use %<...%> to expand argument pack");
11278       return error_mark_node;
11279
11280     default:
11281       return t;
11282     }
11283 }
11284
11285 /* Like tsubst_copy, but specifically for OpenMP clauses.  */
11286
11287 static tree
11288 tsubst_omp_clauses (tree clauses, tree args, tsubst_flags_t complain,
11289                     tree in_decl)
11290 {
11291   tree new_clauses = NULL, nc, oc;
11292
11293   for (oc = clauses; oc ; oc = OMP_CLAUSE_CHAIN (oc))
11294     {
11295       nc = copy_node (oc);
11296       OMP_CLAUSE_CHAIN (nc) = new_clauses;
11297       new_clauses = nc;
11298
11299       switch (OMP_CLAUSE_CODE (nc))
11300         {
11301         case OMP_CLAUSE_LASTPRIVATE:
11302           if (OMP_CLAUSE_LASTPRIVATE_STMT (oc))
11303             {
11304               OMP_CLAUSE_LASTPRIVATE_STMT (nc) = push_stmt_list ();
11305               tsubst_expr (OMP_CLAUSE_LASTPRIVATE_STMT (oc), args, complain,
11306                            in_decl, /*integral_constant_expression_p=*/false);
11307               OMP_CLAUSE_LASTPRIVATE_STMT (nc)
11308                 = pop_stmt_list (OMP_CLAUSE_LASTPRIVATE_STMT (nc));
11309             }
11310           /* FALLTHRU */
11311         case OMP_CLAUSE_PRIVATE:
11312         case OMP_CLAUSE_SHARED:
11313         case OMP_CLAUSE_FIRSTPRIVATE:
11314         case OMP_CLAUSE_REDUCTION:
11315         case OMP_CLAUSE_COPYIN:
11316         case OMP_CLAUSE_COPYPRIVATE:
11317         case OMP_CLAUSE_IF:
11318         case OMP_CLAUSE_NUM_THREADS:
11319         case OMP_CLAUSE_SCHEDULE:
11320         case OMP_CLAUSE_COLLAPSE:
11321           OMP_CLAUSE_OPERAND (nc, 0)
11322             = tsubst_expr (OMP_CLAUSE_OPERAND (oc, 0), args, complain, 
11323                            in_decl, /*integral_constant_expression_p=*/false);
11324           break;
11325         case OMP_CLAUSE_NOWAIT:
11326         case OMP_CLAUSE_ORDERED:
11327         case OMP_CLAUSE_DEFAULT:
11328         case OMP_CLAUSE_UNTIED:
11329           break;
11330         default:
11331           gcc_unreachable ();
11332         }
11333     }
11334
11335   return finish_omp_clauses (nreverse (new_clauses));
11336 }
11337
11338 /* Like tsubst_copy_and_build, but unshare TREE_LIST nodes.  */
11339
11340 static tree
11341 tsubst_copy_asm_operands (tree t, tree args, tsubst_flags_t complain,
11342                           tree in_decl)
11343 {
11344 #define RECUR(t) tsubst_copy_asm_operands (t, args, complain, in_decl)
11345
11346   tree purpose, value, chain;
11347
11348   if (t == NULL)
11349     return t;
11350
11351   if (TREE_CODE (t) != TREE_LIST)
11352     return tsubst_copy_and_build (t, args, complain, in_decl,
11353                                   /*function_p=*/false,
11354                                   /*integral_constant_expression_p=*/false);
11355
11356   if (t == void_list_node)
11357     return t;
11358
11359   purpose = TREE_PURPOSE (t);
11360   if (purpose)
11361     purpose = RECUR (purpose);
11362   value = TREE_VALUE (t);
11363   if (value && TREE_CODE (value) != LABEL_DECL)
11364     value = RECUR (value);
11365   chain = TREE_CHAIN (t);
11366   if (chain && chain != void_type_node)
11367     chain = RECUR (chain);
11368   return tree_cons (purpose, value, chain);
11369 #undef RECUR
11370 }
11371
11372 /* Substitute one OMP_FOR iterator.  */
11373
11374 static void
11375 tsubst_omp_for_iterator (tree t, int i, tree declv, tree initv,
11376                          tree condv, tree incrv, tree *clauses,
11377                          tree args, tsubst_flags_t complain, tree in_decl,
11378                          bool integral_constant_expression_p)
11379 {
11380 #define RECUR(NODE)                             \
11381   tsubst_expr ((NODE), args, complain, in_decl, \
11382                integral_constant_expression_p)
11383   tree decl, init, cond, incr, auto_node;
11384
11385   init = TREE_VEC_ELT (OMP_FOR_INIT (t), i);
11386   gcc_assert (TREE_CODE (init) == MODIFY_EXPR);
11387   decl = RECUR (TREE_OPERAND (init, 0));
11388   init = TREE_OPERAND (init, 1);
11389   auto_node = type_uses_auto (TREE_TYPE (decl));
11390   if (auto_node && init)
11391     {
11392       tree init_expr = init;
11393       if (TREE_CODE (init_expr) == DECL_EXPR)
11394         init_expr = DECL_INITIAL (DECL_EXPR_DECL (init_expr));
11395       init_expr = RECUR (init_expr);
11396       TREE_TYPE (decl)
11397         = do_auto_deduction (TREE_TYPE (decl), init_expr, auto_node);
11398     }
11399   gcc_assert (!type_dependent_expression_p (decl));
11400
11401   if (!CLASS_TYPE_P (TREE_TYPE (decl)))
11402     {
11403       cond = RECUR (TREE_VEC_ELT (OMP_FOR_COND (t), i));
11404       incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11405       if (TREE_CODE (incr) == MODIFY_EXPR)
11406         incr = build_x_modify_expr (RECUR (TREE_OPERAND (incr, 0)), NOP_EXPR,
11407                                     RECUR (TREE_OPERAND (incr, 1)),
11408                                     complain);
11409       else
11410         incr = RECUR (incr);
11411       TREE_VEC_ELT (declv, i) = decl;
11412       TREE_VEC_ELT (initv, i) = init;
11413       TREE_VEC_ELT (condv, i) = cond;
11414       TREE_VEC_ELT (incrv, i) = incr;
11415       return;
11416     }
11417
11418   if (init && TREE_CODE (init) != DECL_EXPR)
11419     {
11420       tree c;
11421       for (c = *clauses; c ; c = OMP_CLAUSE_CHAIN (c))
11422         {
11423           if ((OMP_CLAUSE_CODE (c) == OMP_CLAUSE_PRIVATE
11424                || OMP_CLAUSE_CODE (c) == OMP_CLAUSE_LASTPRIVATE)
11425               && OMP_CLAUSE_DECL (c) == decl)
11426             break;
11427           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_FIRSTPRIVATE
11428                    && OMP_CLAUSE_DECL (c) == decl)
11429             error ("iteration variable %qD should not be firstprivate", decl);
11430           else if (OMP_CLAUSE_CODE (c) == OMP_CLAUSE_REDUCTION
11431                    && OMP_CLAUSE_DECL (c) == decl)
11432             error ("iteration variable %qD should not be reduction", decl);
11433         }
11434       if (c == NULL)
11435         {
11436           c = build_omp_clause (input_location, OMP_CLAUSE_PRIVATE);
11437           OMP_CLAUSE_DECL (c) = decl;
11438           c = finish_omp_clauses (c);
11439           if (c)
11440             {
11441               OMP_CLAUSE_CHAIN (c) = *clauses;
11442               *clauses = c;
11443             }
11444         }
11445     }
11446   cond = TREE_VEC_ELT (OMP_FOR_COND (t), i);
11447   if (COMPARISON_CLASS_P (cond))
11448     cond = build2 (TREE_CODE (cond), boolean_type_node,
11449                    RECUR (TREE_OPERAND (cond, 0)),
11450                    RECUR (TREE_OPERAND (cond, 1)));
11451   else
11452     cond = RECUR (cond);
11453   incr = TREE_VEC_ELT (OMP_FOR_INCR (t), i);
11454   switch (TREE_CODE (incr))
11455     {
11456     case PREINCREMENT_EXPR:
11457     case PREDECREMENT_EXPR:
11458     case POSTINCREMENT_EXPR:
11459     case POSTDECREMENT_EXPR:
11460       incr = build2 (TREE_CODE (incr), TREE_TYPE (decl),
11461                      RECUR (TREE_OPERAND (incr, 0)), NULL_TREE);
11462       break;
11463     case MODIFY_EXPR:
11464       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11465           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11466         {
11467           tree rhs = TREE_OPERAND (incr, 1);
11468           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11469                          RECUR (TREE_OPERAND (incr, 0)),
11470                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11471                                  RECUR (TREE_OPERAND (rhs, 0)),
11472                                  RECUR (TREE_OPERAND (rhs, 1))));
11473         }
11474       else
11475         incr = RECUR (incr);
11476       break;
11477     case MODOP_EXPR:
11478       if (TREE_CODE (TREE_OPERAND (incr, 1)) == PLUS_EXPR
11479           || TREE_CODE (TREE_OPERAND (incr, 1)) == MINUS_EXPR)
11480         {
11481           tree lhs = RECUR (TREE_OPERAND (incr, 0));
11482           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl), lhs,
11483                          build2 (TREE_CODE (TREE_OPERAND (incr, 1)),
11484                                  TREE_TYPE (decl), lhs,
11485                                  RECUR (TREE_OPERAND (incr, 2))));
11486         }
11487       else if (TREE_CODE (TREE_OPERAND (incr, 1)) == NOP_EXPR
11488                && (TREE_CODE (TREE_OPERAND (incr, 2)) == PLUS_EXPR
11489                    || (TREE_CODE (TREE_OPERAND (incr, 2)) == MINUS_EXPR)))
11490         {
11491           tree rhs = TREE_OPERAND (incr, 2);
11492           incr = build2 (MODIFY_EXPR, TREE_TYPE (decl),
11493                          RECUR (TREE_OPERAND (incr, 0)),
11494                          build2 (TREE_CODE (rhs), TREE_TYPE (decl),
11495                                  RECUR (TREE_OPERAND (rhs, 0)),
11496                                  RECUR (TREE_OPERAND (rhs, 1))));
11497         }
11498       else
11499         incr = RECUR (incr);
11500       break;
11501     default:
11502       incr = RECUR (incr);
11503       break;
11504     }
11505
11506   TREE_VEC_ELT (declv, i) = decl;
11507   TREE_VEC_ELT (initv, i) = init;
11508   TREE_VEC_ELT (condv, i) = cond;
11509   TREE_VEC_ELT (incrv, i) = incr;
11510 #undef RECUR
11511 }
11512
11513 /* Like tsubst_copy for expressions, etc. but also does semantic
11514    processing.  */
11515
11516 static tree
11517 tsubst_expr (tree t, tree args, tsubst_flags_t complain, tree in_decl,
11518              bool integral_constant_expression_p)
11519 {
11520 #define RECUR(NODE)                             \
11521   tsubst_expr ((NODE), args, complain, in_decl, \
11522                integral_constant_expression_p)
11523
11524   tree stmt, tmp;
11525
11526   if (t == NULL_TREE || t == error_mark_node)
11527     return t;
11528
11529   if (EXPR_HAS_LOCATION (t))
11530     input_location = EXPR_LOCATION (t);
11531   if (STATEMENT_CODE_P (TREE_CODE (t)))
11532     current_stmt_tree ()->stmts_are_full_exprs_p = STMT_IS_FULL_EXPR_P (t);
11533
11534   switch (TREE_CODE (t))
11535     {
11536     case STATEMENT_LIST:
11537       {
11538         tree_stmt_iterator i;
11539         for (i = tsi_start (t); !tsi_end_p (i); tsi_next (&i))
11540           RECUR (tsi_stmt (i));
11541         break;
11542       }
11543
11544     case CTOR_INITIALIZER:
11545       finish_mem_initializers (tsubst_initializer_list
11546                                (TREE_OPERAND (t, 0), args));
11547       break;
11548
11549     case RETURN_EXPR:
11550       finish_return_stmt (RECUR (TREE_OPERAND (t, 0)));
11551       break;
11552
11553     case EXPR_STMT:
11554       tmp = RECUR (EXPR_STMT_EXPR (t));
11555       if (EXPR_STMT_STMT_EXPR_RESULT (t))
11556         finish_stmt_expr_expr (tmp, cur_stmt_expr);
11557       else
11558         finish_expr_stmt (tmp);
11559       break;
11560
11561     case USING_STMT:
11562       do_using_directive (RECUR (USING_STMT_NAMESPACE (t)));
11563       break;
11564
11565     case DECL_EXPR:
11566       {
11567         tree decl;
11568         tree init;
11569
11570         decl = DECL_EXPR_DECL (t);
11571         if (TREE_CODE (decl) == LABEL_DECL)
11572           finish_label_decl (DECL_NAME (decl));
11573         else if (TREE_CODE (decl) == USING_DECL)
11574           {
11575             tree scope = USING_DECL_SCOPE (decl);
11576             tree name = DECL_NAME (decl);
11577             tree decl;
11578
11579             scope = RECUR (scope);
11580             decl = lookup_qualified_name (scope, name,
11581                                           /*is_type_p=*/false,
11582                                           /*complain=*/false);
11583             if (decl == error_mark_node || TREE_CODE (decl) == TREE_LIST)
11584               qualified_name_lookup_error (scope, name, decl, input_location);
11585             else
11586               do_local_using_decl (decl, scope, name);
11587           }
11588         else
11589           {
11590             init = DECL_INITIAL (decl);
11591             decl = tsubst (decl, args, complain, in_decl);
11592             if (decl != error_mark_node)
11593               {
11594                 /* By marking the declaration as instantiated, we avoid
11595                    trying to instantiate it.  Since instantiate_decl can't
11596                    handle local variables, and since we've already done
11597                    all that needs to be done, that's the right thing to
11598                    do.  */
11599                 if (TREE_CODE (decl) == VAR_DECL)
11600                   DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11601                 if (TREE_CODE (decl) == VAR_DECL
11602                     && ANON_AGGR_TYPE_P (TREE_TYPE (decl)))
11603                   /* Anonymous aggregates are a special case.  */
11604                   finish_anon_union (decl);
11605                 else
11606                   {
11607                     maybe_push_decl (decl);
11608                     if (TREE_CODE (decl) == VAR_DECL
11609                         && DECL_PRETTY_FUNCTION_P (decl))
11610                       {
11611                         /* For __PRETTY_FUNCTION__ we have to adjust the
11612                            initializer.  */
11613                         const char *const name
11614                           = cxx_printable_name (current_function_decl, 2);
11615                         init = cp_fname_init (name, &TREE_TYPE (decl));
11616                       }
11617                     else
11618                       {
11619                         tree t = RECUR (init);
11620
11621                         if (init && !t)
11622                           /* If we had an initializer but it
11623                              instantiated to nothing,
11624                              value-initialize the object.  This will
11625                              only occur when the initializer was a
11626                              pack expansion where the parameter packs
11627                              used in that expansion were of length
11628                              zero.  */
11629                           init = build_value_init (TREE_TYPE (decl));
11630                         else
11631                           init = t;
11632                       }
11633
11634                     cp_finish_decl (decl, init, false, NULL_TREE, 0);
11635                   }
11636               }
11637           }
11638
11639         /* A DECL_EXPR can also be used as an expression, in the condition
11640            clause of an if/for/while construct.  */
11641         return decl;
11642       }
11643
11644     case FOR_STMT:
11645       stmt = begin_for_stmt ();
11646                           RECUR (FOR_INIT_STMT (t));
11647       finish_for_init_stmt (stmt);
11648       tmp = RECUR (FOR_COND (t));
11649       finish_for_cond (tmp, stmt);
11650       tmp = RECUR (FOR_EXPR (t));
11651       finish_for_expr (tmp, stmt);
11652       RECUR (FOR_BODY (t));
11653       finish_for_stmt (stmt);
11654       break;
11655
11656     case WHILE_STMT:
11657       stmt = begin_while_stmt ();
11658       tmp = RECUR (WHILE_COND (t));
11659       finish_while_stmt_cond (tmp, stmt);
11660       RECUR (WHILE_BODY (t));
11661       finish_while_stmt (stmt);
11662       break;
11663
11664     case DO_STMT:
11665       stmt = begin_do_stmt ();
11666       RECUR (DO_BODY (t));
11667       finish_do_body (stmt);
11668       tmp = RECUR (DO_COND (t));
11669       finish_do_stmt (tmp, stmt);
11670       break;
11671
11672     case IF_STMT:
11673       stmt = begin_if_stmt ();
11674       tmp = RECUR (IF_COND (t));
11675       finish_if_stmt_cond (tmp, stmt);
11676       RECUR (THEN_CLAUSE (t));
11677       finish_then_clause (stmt);
11678
11679       if (ELSE_CLAUSE (t))
11680         {
11681           begin_else_clause (stmt);
11682           RECUR (ELSE_CLAUSE (t));
11683           finish_else_clause (stmt);
11684         }
11685
11686       finish_if_stmt (stmt);
11687       break;
11688
11689     case BIND_EXPR:
11690       if (BIND_EXPR_BODY_BLOCK (t))
11691         stmt = begin_function_body ();
11692       else
11693         stmt = begin_compound_stmt (BIND_EXPR_TRY_BLOCK (t)
11694                                     ? BCS_TRY_BLOCK : 0);
11695
11696       RECUR (BIND_EXPR_BODY (t));
11697
11698       if (BIND_EXPR_BODY_BLOCK (t))
11699         finish_function_body (stmt);
11700       else
11701         finish_compound_stmt (stmt);
11702       break;
11703
11704     case BREAK_STMT:
11705       finish_break_stmt ();
11706       break;
11707
11708     case CONTINUE_STMT:
11709       finish_continue_stmt ();
11710       break;
11711
11712     case SWITCH_STMT:
11713       stmt = begin_switch_stmt ();
11714       tmp = RECUR (SWITCH_STMT_COND (t));
11715       finish_switch_cond (tmp, stmt);
11716       RECUR (SWITCH_STMT_BODY (t));
11717       finish_switch_stmt (stmt);
11718       break;
11719
11720     case CASE_LABEL_EXPR:
11721       finish_case_label (EXPR_LOCATION (t),
11722                          RECUR (CASE_LOW (t)),
11723                          RECUR (CASE_HIGH (t)));
11724       break;
11725
11726     case LABEL_EXPR:
11727       {
11728         tree decl = LABEL_EXPR_LABEL (t);
11729         tree label;
11730
11731         label = finish_label_stmt (DECL_NAME (decl));
11732         if (DECL_ATTRIBUTES (decl) != NULL_TREE)
11733           cplus_decl_attributes (&label, DECL_ATTRIBUTES (decl), 0);
11734       }
11735       break;
11736
11737     case GOTO_EXPR:
11738       tmp = GOTO_DESTINATION (t);
11739       if (TREE_CODE (tmp) != LABEL_DECL)
11740         /* Computed goto's must be tsubst'd into.  On the other hand,
11741            non-computed gotos must not be; the identifier in question
11742            will have no binding.  */
11743         tmp = RECUR (tmp);
11744       else
11745         tmp = DECL_NAME (tmp);
11746       finish_goto_stmt (tmp);
11747       break;
11748
11749     case ASM_EXPR:
11750       tmp = finish_asm_stmt
11751         (ASM_VOLATILE_P (t),
11752          RECUR (ASM_STRING (t)),
11753          tsubst_copy_asm_operands (ASM_OUTPUTS (t), args, complain, in_decl),
11754          tsubst_copy_asm_operands (ASM_INPUTS (t), args, complain, in_decl),
11755          tsubst_copy_asm_operands (ASM_CLOBBERS (t), args, complain, in_decl),
11756          tsubst_copy_asm_operands (ASM_LABELS (t), args, complain, in_decl));
11757       {
11758         tree asm_expr = tmp;
11759         if (TREE_CODE (asm_expr) == CLEANUP_POINT_EXPR)
11760           asm_expr = TREE_OPERAND (asm_expr, 0);
11761         ASM_INPUT_P (asm_expr) = ASM_INPUT_P (t);
11762       }
11763       break;
11764
11765     case TRY_BLOCK:
11766       if (CLEANUP_P (t))
11767         {
11768           stmt = begin_try_block ();
11769           RECUR (TRY_STMTS (t));
11770           finish_cleanup_try_block (stmt);
11771           finish_cleanup (RECUR (TRY_HANDLERS (t)), stmt);
11772         }
11773       else
11774         {
11775           tree compound_stmt = NULL_TREE;
11776
11777           if (FN_TRY_BLOCK_P (t))
11778             stmt = begin_function_try_block (&compound_stmt);
11779           else
11780             stmt = begin_try_block ();
11781
11782           RECUR (TRY_STMTS (t));
11783
11784           if (FN_TRY_BLOCK_P (t))
11785             finish_function_try_block (stmt);
11786           else
11787             finish_try_block (stmt);
11788
11789           RECUR (TRY_HANDLERS (t));
11790           if (FN_TRY_BLOCK_P (t))
11791             finish_function_handler_sequence (stmt, compound_stmt);
11792           else
11793             finish_handler_sequence (stmt);
11794         }
11795       break;
11796
11797     case HANDLER:
11798       {
11799         tree decl = HANDLER_PARMS (t);
11800
11801         if (decl)
11802           {
11803             decl = tsubst (decl, args, complain, in_decl);
11804             /* Prevent instantiate_decl from trying to instantiate
11805                this variable.  We've already done all that needs to be
11806                done.  */
11807             if (decl != error_mark_node)
11808               DECL_TEMPLATE_INSTANTIATED (decl) = 1;
11809           }
11810         stmt = begin_handler ();
11811         finish_handler_parms (decl, stmt);
11812         RECUR (HANDLER_BODY (t));
11813         finish_handler (stmt);
11814       }
11815       break;
11816
11817     case TAG_DEFN:
11818       tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
11819       break;
11820
11821     case STATIC_ASSERT:
11822       {
11823         tree condition = 
11824           tsubst_expr (STATIC_ASSERT_CONDITION (t), 
11825                        args,
11826                        complain, in_decl,
11827                        /*integral_constant_expression_p=*/true);
11828         finish_static_assert (condition,
11829                               STATIC_ASSERT_MESSAGE (t),
11830                               STATIC_ASSERT_SOURCE_LOCATION (t),
11831                               /*member_p=*/false);
11832       }
11833       break;
11834
11835     case OMP_PARALLEL:
11836       tmp = tsubst_omp_clauses (OMP_PARALLEL_CLAUSES (t),
11837                                 args, complain, in_decl);
11838       stmt = begin_omp_parallel ();
11839       RECUR (OMP_PARALLEL_BODY (t));
11840       OMP_PARALLEL_COMBINED (finish_omp_parallel (tmp, stmt))
11841         = OMP_PARALLEL_COMBINED (t);
11842       break;
11843
11844     case OMP_TASK:
11845       tmp = tsubst_omp_clauses (OMP_TASK_CLAUSES (t),
11846                                 args, complain, in_decl);
11847       stmt = begin_omp_task ();
11848       RECUR (OMP_TASK_BODY (t));
11849       finish_omp_task (tmp, stmt);
11850       break;
11851
11852     case OMP_FOR:
11853       {
11854         tree clauses, body, pre_body;
11855         tree declv, initv, condv, incrv;
11856         int i;
11857
11858         clauses = tsubst_omp_clauses (OMP_FOR_CLAUSES (t),
11859                                       args, complain, in_decl);
11860         declv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11861         initv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11862         condv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11863         incrv = make_tree_vec (TREE_VEC_LENGTH (OMP_FOR_INIT (t)));
11864
11865         for (i = 0; i < TREE_VEC_LENGTH (OMP_FOR_INIT (t)); i++)
11866           tsubst_omp_for_iterator (t, i, declv, initv, condv, incrv,
11867                                    &clauses, args, complain, in_decl,
11868                                    integral_constant_expression_p);
11869
11870         stmt = begin_omp_structured_block ();
11871
11872         for (i = 0; i < TREE_VEC_LENGTH (initv); i++)
11873           if (TREE_VEC_ELT (initv, i) == NULL
11874               || TREE_CODE (TREE_VEC_ELT (initv, i)) != DECL_EXPR)
11875             TREE_VEC_ELT (initv, i) = RECUR (TREE_VEC_ELT (initv, i));
11876           else if (CLASS_TYPE_P (TREE_TYPE (TREE_VEC_ELT (initv, i))))
11877             {
11878               tree init = RECUR (TREE_VEC_ELT (initv, i));
11879               gcc_assert (init == TREE_VEC_ELT (declv, i));
11880               TREE_VEC_ELT (initv, i) = NULL_TREE;
11881             }
11882           else
11883             {
11884               tree decl_expr = TREE_VEC_ELT (initv, i);
11885               tree init = DECL_INITIAL (DECL_EXPR_DECL (decl_expr));
11886               gcc_assert (init != NULL);
11887               TREE_VEC_ELT (initv, i) = RECUR (init);
11888               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = NULL;
11889               RECUR (decl_expr);
11890               DECL_INITIAL (DECL_EXPR_DECL (decl_expr)) = init;
11891             }
11892
11893         pre_body = push_stmt_list ();
11894         RECUR (OMP_FOR_PRE_BODY (t));
11895         pre_body = pop_stmt_list (pre_body);
11896
11897         body = push_stmt_list ();
11898         RECUR (OMP_FOR_BODY (t));
11899         body = pop_stmt_list (body);
11900
11901         t = finish_omp_for (EXPR_LOCATION (t), declv, initv, condv, incrv,
11902                             body, pre_body, clauses);
11903
11904         add_stmt (finish_omp_structured_block (stmt));
11905       }
11906       break;
11907
11908     case OMP_SECTIONS:
11909     case OMP_SINGLE:
11910       tmp = tsubst_omp_clauses (OMP_CLAUSES (t), args, complain, in_decl);
11911       stmt = push_stmt_list ();
11912       RECUR (OMP_BODY (t));
11913       stmt = pop_stmt_list (stmt);
11914
11915       t = copy_node (t);
11916       OMP_BODY (t) = stmt;
11917       OMP_CLAUSES (t) = tmp;
11918       add_stmt (t);
11919       break;
11920
11921     case OMP_SECTION:
11922     case OMP_CRITICAL:
11923     case OMP_MASTER:
11924     case OMP_ORDERED:
11925       stmt = push_stmt_list ();
11926       RECUR (OMP_BODY (t));
11927       stmt = pop_stmt_list (stmt);
11928
11929       t = copy_node (t);
11930       OMP_BODY (t) = stmt;
11931       add_stmt (t);
11932       break;
11933
11934     case OMP_ATOMIC:
11935       gcc_assert (OMP_ATOMIC_DEPENDENT_P (t));
11936       {
11937         tree op1 = TREE_OPERAND (t, 1);
11938         tree lhs = RECUR (TREE_OPERAND (op1, 0));
11939         tree rhs = RECUR (TREE_OPERAND (op1, 1));
11940         finish_omp_atomic (TREE_CODE (op1), lhs, rhs);
11941       }
11942       break;
11943
11944     case EXPR_PACK_EXPANSION:
11945       error ("invalid use of pack expansion expression");
11946       return error_mark_node;
11947
11948     case NONTYPE_ARGUMENT_PACK:
11949       error ("use %<...%> to expand argument pack");
11950       return error_mark_node;
11951
11952     default:
11953       gcc_assert (!STATEMENT_CODE_P (TREE_CODE (t)));
11954
11955       return tsubst_copy_and_build (t, args, complain, in_decl,
11956                                     /*function_p=*/false,
11957                                     integral_constant_expression_p);
11958     }
11959
11960   return NULL_TREE;
11961 #undef RECUR
11962 }
11963
11964 /* T is a postfix-expression that is not being used in a function
11965    call.  Return the substituted version of T.  */
11966
11967 static tree
11968 tsubst_non_call_postfix_expression (tree t, tree args,
11969                                     tsubst_flags_t complain,
11970                                     tree in_decl)
11971 {
11972   if (TREE_CODE (t) == SCOPE_REF)
11973     t = tsubst_qualified_id (t, args, complain, in_decl,
11974                              /*done=*/false, /*address_p=*/false);
11975   else
11976     t = tsubst_copy_and_build (t, args, complain, in_decl,
11977                                /*function_p=*/false,
11978                                /*integral_constant_expression_p=*/false);
11979
11980   return t;
11981 }
11982
11983 /* Like tsubst but deals with expressions and performs semantic
11984    analysis.  FUNCTION_P is true if T is the "F" in "F (ARGS)".  */
11985
11986 tree
11987 tsubst_copy_and_build (tree t,
11988                        tree args,
11989                        tsubst_flags_t complain,
11990                        tree in_decl,
11991                        bool function_p,
11992                        bool integral_constant_expression_p)
11993 {
11994 #define RECUR(NODE)                                             \
11995   tsubst_copy_and_build (NODE, args, complain, in_decl,         \
11996                          /*function_p=*/false,                  \
11997                          integral_constant_expression_p)
11998
11999   tree op1;
12000
12001   if (t == NULL_TREE || t == error_mark_node)
12002     return t;
12003
12004   switch (TREE_CODE (t))
12005     {
12006     case USING_DECL:
12007       t = DECL_NAME (t);
12008       /* Fall through.  */
12009     case IDENTIFIER_NODE:
12010       {
12011         tree decl;
12012         cp_id_kind idk;
12013         bool non_integral_constant_expression_p;
12014         const char *error_msg;
12015
12016         if (IDENTIFIER_TYPENAME_P (t))
12017           {
12018             tree new_type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12019             t = mangle_conv_op_name_for_type (new_type);
12020           }
12021
12022         /* Look up the name.  */
12023         decl = lookup_name (t);
12024
12025         /* By convention, expressions use ERROR_MARK_NODE to indicate
12026            failure, not NULL_TREE.  */
12027         if (decl == NULL_TREE)
12028           decl = error_mark_node;
12029
12030         decl = finish_id_expression (t, decl, NULL_TREE,
12031                                      &idk,
12032                                      integral_constant_expression_p,
12033                                      /*allow_non_integral_constant_expression_p=*/false,
12034                                      &non_integral_constant_expression_p,
12035                                      /*template_p=*/false,
12036                                      /*done=*/true,
12037                                      /*address_p=*/false,
12038                                      /*template_arg_p=*/false,
12039                                      &error_msg,
12040                                      input_location);
12041         if (error_msg)
12042           error (error_msg);
12043         if (!function_p && TREE_CODE (decl) == IDENTIFIER_NODE)
12044           decl = unqualified_name_lookup_error (decl);
12045         return decl;
12046       }
12047
12048     case TEMPLATE_ID_EXPR:
12049       {
12050         tree object;
12051         tree templ = RECUR (TREE_OPERAND (t, 0));
12052         tree targs = TREE_OPERAND (t, 1);
12053
12054         if (targs)
12055           targs = tsubst_template_args (targs, args, complain, in_decl);
12056
12057         if (TREE_CODE (templ) == COMPONENT_REF)
12058           {
12059             object = TREE_OPERAND (templ, 0);
12060             templ = TREE_OPERAND (templ, 1);
12061           }
12062         else
12063           object = NULL_TREE;
12064         templ = lookup_template_function (templ, targs);
12065
12066         if (object)
12067           return build3 (COMPONENT_REF, TREE_TYPE (templ),
12068                          object, templ, NULL_TREE);
12069         else
12070           return baselink_for_fns (templ);
12071       }
12072
12073     case INDIRECT_REF:
12074       {
12075         tree r = RECUR (TREE_OPERAND (t, 0));
12076
12077         if (REFERENCE_REF_P (t))
12078           {
12079             /* A type conversion to reference type will be enclosed in
12080                such an indirect ref, but the substitution of the cast
12081                will have also added such an indirect ref.  */
12082             if (TREE_CODE (TREE_TYPE (r)) == REFERENCE_TYPE)
12083               r = convert_from_reference (r);
12084           }
12085         else
12086           r = build_x_indirect_ref (r, RO_UNARY_STAR, complain);
12087         return r;
12088       }
12089
12090     case NOP_EXPR:
12091       return build_nop
12092         (tsubst (TREE_TYPE (t), args, complain, in_decl),
12093          RECUR (TREE_OPERAND (t, 0)));
12094
12095     case CAST_EXPR:
12096     case REINTERPRET_CAST_EXPR:
12097     case CONST_CAST_EXPR:
12098     case DYNAMIC_CAST_EXPR:
12099     case STATIC_CAST_EXPR:
12100       {
12101         tree type;
12102         tree op;
12103
12104         type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12105         if (integral_constant_expression_p
12106             && !cast_valid_in_integral_constant_expression_p (type))
12107           {
12108             if (complain & tf_error)
12109               error ("a cast to a type other than an integral or "
12110                      "enumeration type cannot appear in a constant-expression");
12111             return error_mark_node; 
12112           }
12113
12114         op = RECUR (TREE_OPERAND (t, 0));
12115
12116         switch (TREE_CODE (t))
12117           {
12118           case CAST_EXPR:
12119             return build_functional_cast (type, op, complain);
12120           case REINTERPRET_CAST_EXPR:
12121             return build_reinterpret_cast (type, op, complain);
12122           case CONST_CAST_EXPR:
12123             return build_const_cast (type, op, complain);
12124           case DYNAMIC_CAST_EXPR:
12125             return build_dynamic_cast (type, op, complain);
12126           case STATIC_CAST_EXPR:
12127             return build_static_cast (type, op, complain);
12128           default:
12129             gcc_unreachable ();
12130           }
12131       }
12132
12133     case POSTDECREMENT_EXPR:
12134     case POSTINCREMENT_EXPR:
12135       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12136                                                 args, complain, in_decl);
12137       return build_x_unary_op (TREE_CODE (t), op1, complain);
12138
12139     case PREDECREMENT_EXPR:
12140     case PREINCREMENT_EXPR:
12141     case NEGATE_EXPR:
12142     case BIT_NOT_EXPR:
12143     case ABS_EXPR:
12144     case TRUTH_NOT_EXPR:
12145     case UNARY_PLUS_EXPR:  /* Unary + */
12146     case REALPART_EXPR:
12147     case IMAGPART_EXPR:
12148       return build_x_unary_op (TREE_CODE (t), RECUR (TREE_OPERAND (t, 0)),
12149                                complain);
12150
12151     case ADDR_EXPR:
12152       op1 = TREE_OPERAND (t, 0);
12153       if (TREE_CODE (op1) == SCOPE_REF)
12154         op1 = tsubst_qualified_id (op1, args, complain, in_decl,
12155                                    /*done=*/true, /*address_p=*/true);
12156       else
12157         op1 = tsubst_non_call_postfix_expression (op1, args, complain,
12158                                                   in_decl);
12159       if (TREE_CODE (op1) == LABEL_DECL)
12160         return finish_label_address_expr (DECL_NAME (op1),
12161                                           EXPR_LOCATION (op1));
12162       return build_x_unary_op (ADDR_EXPR, op1, complain);
12163
12164     case PLUS_EXPR:
12165     case MINUS_EXPR:
12166     case MULT_EXPR:
12167     case TRUNC_DIV_EXPR:
12168     case CEIL_DIV_EXPR:
12169     case FLOOR_DIV_EXPR:
12170     case ROUND_DIV_EXPR:
12171     case EXACT_DIV_EXPR:
12172     case BIT_AND_EXPR:
12173     case BIT_IOR_EXPR:
12174     case BIT_XOR_EXPR:
12175     case TRUNC_MOD_EXPR:
12176     case FLOOR_MOD_EXPR:
12177     case TRUTH_ANDIF_EXPR:
12178     case TRUTH_ORIF_EXPR:
12179     case TRUTH_AND_EXPR:
12180     case TRUTH_OR_EXPR:
12181     case RSHIFT_EXPR:
12182     case LSHIFT_EXPR:
12183     case RROTATE_EXPR:
12184     case LROTATE_EXPR:
12185     case EQ_EXPR:
12186     case NE_EXPR:
12187     case MAX_EXPR:
12188     case MIN_EXPR:
12189     case LE_EXPR:
12190     case GE_EXPR:
12191     case LT_EXPR:
12192     case GT_EXPR:
12193     case MEMBER_REF:
12194     case DOTSTAR_EXPR:
12195       return build_x_binary_op
12196         (TREE_CODE (t),
12197          RECUR (TREE_OPERAND (t, 0)),
12198          (TREE_NO_WARNING (TREE_OPERAND (t, 0))
12199           ? ERROR_MARK
12200           : TREE_CODE (TREE_OPERAND (t, 0))),
12201          RECUR (TREE_OPERAND (t, 1)),
12202          (TREE_NO_WARNING (TREE_OPERAND (t, 1))
12203           ? ERROR_MARK
12204           : TREE_CODE (TREE_OPERAND (t, 1))),
12205          /*overloaded_p=*/NULL,
12206          complain);
12207
12208     case SCOPE_REF:
12209       return tsubst_qualified_id (t, args, complain, in_decl, /*done=*/true,
12210                                   /*address_p=*/false);
12211     case ARRAY_REF:
12212       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12213                                                 args, complain, in_decl);
12214       return build_x_array_ref (op1, RECUR (TREE_OPERAND (t, 1)), complain);
12215
12216     case SIZEOF_EXPR:
12217       if (PACK_EXPANSION_P (TREE_OPERAND (t, 0)))
12218         return tsubst_copy (t, args, complain, in_decl);
12219       /* Fall through */
12220       
12221     case ALIGNOF_EXPR:
12222       op1 = TREE_OPERAND (t, 0);
12223       if (!args)
12224         {
12225           /* When there are no ARGS, we are trying to evaluate a
12226              non-dependent expression from the parser.  Trying to do
12227              the substitutions may not work.  */
12228           if (!TYPE_P (op1))
12229             op1 = TREE_TYPE (op1);
12230         }
12231       else
12232         {
12233           ++cp_unevaluated_operand;
12234           ++c_inhibit_evaluation_warnings;
12235           op1 = tsubst_copy_and_build (op1, args, complain, in_decl,
12236                                        /*function_p=*/false,
12237                                        /*integral_constant_expression_p=*/false);
12238           --cp_unevaluated_operand;
12239           --c_inhibit_evaluation_warnings;
12240         }
12241       if (TYPE_P (op1))
12242         return cxx_sizeof_or_alignof_type (op1, TREE_CODE (t), 
12243                                            complain & tf_error);
12244       else
12245         return cxx_sizeof_or_alignof_expr (op1, TREE_CODE (t), 
12246                                            complain & tf_error);
12247
12248     case MODOP_EXPR:
12249       {
12250         tree r = build_x_modify_expr
12251           (RECUR (TREE_OPERAND (t, 0)),
12252            TREE_CODE (TREE_OPERAND (t, 1)),
12253            RECUR (TREE_OPERAND (t, 2)),
12254            complain);
12255         /* TREE_NO_WARNING must be set if either the expression was
12256            parenthesized or it uses an operator such as >>= rather
12257            than plain assignment.  In the former case, it was already
12258            set and must be copied.  In the latter case,
12259            build_x_modify_expr sets it and it must not be reset
12260            here.  */
12261         if (TREE_NO_WARNING (t))
12262           TREE_NO_WARNING (r) = TREE_NO_WARNING (t);
12263         return r;
12264       }
12265
12266     case ARROW_EXPR:
12267       op1 = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12268                                                 args, complain, in_decl);
12269       /* Remember that there was a reference to this entity.  */
12270       if (DECL_P (op1))
12271         mark_used (op1);
12272       return build_x_arrow (op1);
12273
12274     case NEW_EXPR:
12275       {
12276         tree placement = RECUR (TREE_OPERAND (t, 0));
12277         tree init = RECUR (TREE_OPERAND (t, 3));
12278         VEC(tree,gc) *placement_vec;
12279         VEC(tree,gc) *init_vec;
12280         tree ret;
12281
12282         if (placement == NULL_TREE)
12283           placement_vec = NULL;
12284         else
12285           {
12286             placement_vec = make_tree_vector ();
12287             for (; placement != NULL_TREE; placement = TREE_CHAIN (placement))
12288               VEC_safe_push (tree, gc, placement_vec, TREE_VALUE (placement));
12289           }
12290
12291         /* If there was an initializer in the original tree, but it
12292            instantiated to an empty list, then we should pass a
12293            non-NULL empty vector to tell build_new that it was an
12294            empty initializer() rather than no initializer.  This can
12295            only happen when the initializer is a pack expansion whose
12296            parameter packs are of length zero.  */
12297         if (init == NULL_TREE && TREE_OPERAND (t, 3) == NULL_TREE)
12298           init_vec = NULL;
12299         else
12300           {
12301             init_vec = make_tree_vector ();
12302             if (init == void_zero_node)
12303               gcc_assert (init_vec != NULL);
12304             else
12305               {
12306                 for (; init != NULL_TREE; init = TREE_CHAIN (init))
12307                   VEC_safe_push (tree, gc, init_vec, TREE_VALUE (init));
12308               }
12309           }
12310
12311         ret = build_new (&placement_vec,
12312                          RECUR (TREE_OPERAND (t, 1)),
12313                          RECUR (TREE_OPERAND (t, 2)),
12314                          &init_vec,
12315                          NEW_EXPR_USE_GLOBAL (t),
12316                          complain);
12317
12318         if (placement_vec != NULL)
12319           release_tree_vector (placement_vec);
12320         if (init_vec != NULL)
12321           release_tree_vector (init_vec);
12322
12323         return ret;
12324       }
12325
12326     case DELETE_EXPR:
12327      return delete_sanity
12328        (RECUR (TREE_OPERAND (t, 0)),
12329         RECUR (TREE_OPERAND (t, 1)),
12330         DELETE_EXPR_USE_VEC (t),
12331         DELETE_EXPR_USE_GLOBAL (t));
12332
12333     case COMPOUND_EXPR:
12334       return build_x_compound_expr (RECUR (TREE_OPERAND (t, 0)),
12335                                     RECUR (TREE_OPERAND (t, 1)),
12336                                     complain);
12337
12338     case CALL_EXPR:
12339       {
12340         tree function;
12341         VEC(tree,gc) *call_args;
12342         unsigned int nargs, i;
12343         bool qualified_p;
12344         bool koenig_p;
12345         tree ret;
12346
12347         function = CALL_EXPR_FN (t);
12348         /* When we parsed the expression,  we determined whether or
12349            not Koenig lookup should be performed.  */
12350         koenig_p = KOENIG_LOOKUP_P (t);
12351         if (TREE_CODE (function) == SCOPE_REF)
12352           {
12353             qualified_p = true;
12354             function = tsubst_qualified_id (function, args, complain, in_decl,
12355                                             /*done=*/false,
12356                                             /*address_p=*/false);
12357           }
12358         else
12359           {
12360             if (TREE_CODE (function) == COMPONENT_REF)
12361               {
12362                 tree op = TREE_OPERAND (function, 1);
12363
12364                 qualified_p = (TREE_CODE (op) == SCOPE_REF
12365                                || (BASELINK_P (op)
12366                                    && BASELINK_QUALIFIED_P (op)));
12367               }
12368             else
12369               qualified_p = false;
12370
12371             function = tsubst_copy_and_build (function, args, complain,
12372                                               in_decl,
12373                                               !qualified_p,
12374                                               integral_constant_expression_p);
12375
12376             if (BASELINK_P (function))
12377               qualified_p = true;
12378           }
12379
12380         nargs = call_expr_nargs (t);
12381         call_args = make_tree_vector ();
12382         for (i = 0; i < nargs; ++i)
12383           {
12384             tree arg = CALL_EXPR_ARG (t, i);
12385
12386             if (!PACK_EXPANSION_P (arg))
12387               VEC_safe_push (tree, gc, call_args,
12388                              RECUR (CALL_EXPR_ARG (t, i)));
12389             else
12390               {
12391                 /* Expand the pack expansion and push each entry onto
12392                    CALL_ARGS.  */
12393                 arg = tsubst_pack_expansion (arg, args, complain, in_decl);
12394                 if (TREE_CODE (arg) == TREE_VEC)
12395                   {
12396                     unsigned int len, j;
12397
12398                     len = TREE_VEC_LENGTH (arg);
12399                     for (j = 0; j < len; ++j)
12400                       {
12401                         tree value = TREE_VEC_ELT (arg, j);
12402                         if (value != NULL_TREE)
12403                           value = convert_from_reference (value);
12404                         VEC_safe_push (tree, gc, call_args, value);
12405                       }
12406                   }
12407                 else
12408                   {
12409                     /* A partial substitution.  Add one entry.  */
12410                     VEC_safe_push (tree, gc, call_args, arg);
12411                   }
12412               }
12413           }
12414
12415         /* We do not perform argument-dependent lookup if normal
12416            lookup finds a non-function, in accordance with the
12417            expected resolution of DR 218.  */
12418         if (koenig_p
12419             && ((is_overloaded_fn (function)
12420                  /* If lookup found a member function, the Koenig lookup is
12421                     not appropriate, even if an unqualified-name was used
12422                     to denote the function.  */
12423                  && !DECL_FUNCTION_MEMBER_P (get_first_fn (function)))
12424                 || TREE_CODE (function) == IDENTIFIER_NODE)
12425             /* Only do this when substitution turns a dependent call
12426                into a non-dependent call.  */
12427             && type_dependent_expression_p_push (t)
12428             && !any_type_dependent_arguments_p (call_args))
12429           function = perform_koenig_lookup (function, call_args);
12430
12431         if (TREE_CODE (function) == IDENTIFIER_NODE)
12432           {
12433             unqualified_name_lookup_error (function);
12434             release_tree_vector (call_args);
12435             return error_mark_node;
12436           }
12437
12438         /* Remember that there was a reference to this entity.  */
12439         if (DECL_P (function))
12440           mark_used (function);
12441
12442         if (TREE_CODE (function) == OFFSET_REF)
12443           ret = build_offset_ref_call_from_tree (function, &call_args);
12444         else if (TREE_CODE (function) == COMPONENT_REF)
12445           {
12446             if (!BASELINK_P (TREE_OPERAND (function, 1)))
12447               ret = finish_call_expr (function, &call_args,
12448                                        /*disallow_virtual=*/false,
12449                                        /*koenig_p=*/false,
12450                                        complain);
12451             else
12452               ret = (build_new_method_call
12453                       (TREE_OPERAND (function, 0),
12454                        TREE_OPERAND (function, 1),
12455                        &call_args, NULL_TREE,
12456                        qualified_p ? LOOKUP_NONVIRTUAL : LOOKUP_NORMAL,
12457                        /*fn_p=*/NULL,
12458                        complain));
12459           }
12460         else
12461           ret = finish_call_expr (function, &call_args,
12462                                   /*disallow_virtual=*/qualified_p,
12463                                   koenig_p,
12464                                   complain);
12465
12466         release_tree_vector (call_args);
12467
12468         return ret;
12469       }
12470
12471     case COND_EXPR:
12472       return build_x_conditional_expr
12473         (RECUR (TREE_OPERAND (t, 0)),
12474          RECUR (TREE_OPERAND (t, 1)),
12475          RECUR (TREE_OPERAND (t, 2)),
12476          complain);
12477
12478     case PSEUDO_DTOR_EXPR:
12479       return finish_pseudo_destructor_expr
12480         (RECUR (TREE_OPERAND (t, 0)),
12481          RECUR (TREE_OPERAND (t, 1)),
12482          RECUR (TREE_OPERAND (t, 2)));
12483
12484     case TREE_LIST:
12485       {
12486         tree purpose, value, chain;
12487
12488         if (t == void_list_node)
12489           return t;
12490
12491         if ((TREE_PURPOSE (t) && PACK_EXPANSION_P (TREE_PURPOSE (t)))
12492             || (TREE_VALUE (t) && PACK_EXPANSION_P (TREE_VALUE (t))))
12493           {
12494             /* We have pack expansions, so expand those and
12495                create a new list out of it.  */
12496             tree purposevec = NULL_TREE;
12497             tree valuevec = NULL_TREE;
12498             tree chain;
12499             int i, len = -1;
12500
12501             /* Expand the argument expressions.  */
12502             if (TREE_PURPOSE (t))
12503               purposevec = tsubst_pack_expansion (TREE_PURPOSE (t), args,
12504                                                  complain, in_decl);
12505             if (TREE_VALUE (t))
12506               valuevec = tsubst_pack_expansion (TREE_VALUE (t), args,
12507                                                complain, in_decl);
12508
12509             /* Build the rest of the list.  */
12510             chain = TREE_CHAIN (t);
12511             if (chain && chain != void_type_node)
12512               chain = RECUR (chain);
12513
12514             /* Determine the number of arguments.  */
12515             if (purposevec && TREE_CODE (purposevec) == TREE_VEC)
12516               {
12517                 len = TREE_VEC_LENGTH (purposevec);
12518                 gcc_assert (!valuevec || len == TREE_VEC_LENGTH (valuevec));
12519               }
12520             else if (TREE_CODE (valuevec) == TREE_VEC)
12521               len = TREE_VEC_LENGTH (valuevec);
12522             else
12523               {
12524                 /* Since we only performed a partial substitution into
12525                    the argument pack, we only return a single list
12526                    node.  */
12527                 if (purposevec == TREE_PURPOSE (t)
12528                     && valuevec == TREE_VALUE (t)
12529                     && chain == TREE_CHAIN (t))
12530                   return t;
12531
12532                 return tree_cons (purposevec, valuevec, chain);
12533               }
12534             
12535             /* Convert the argument vectors into a TREE_LIST */
12536             i = len;
12537             while (i > 0)
12538               {
12539                 /* Grab the Ith values.  */
12540                 i--;
12541                 purpose = purposevec ? TREE_VEC_ELT (purposevec, i) 
12542                                      : NULL_TREE;
12543                 value 
12544                   = valuevec ? convert_from_reference (TREE_VEC_ELT (valuevec, i)) 
12545                              : NULL_TREE;
12546
12547                 /* Build the list (backwards).  */
12548                 chain = tree_cons (purpose, value, chain);
12549               }
12550
12551             return chain;
12552           }
12553
12554         purpose = TREE_PURPOSE (t);
12555         if (purpose)
12556           purpose = RECUR (purpose);
12557         value = TREE_VALUE (t);
12558         if (value)
12559           value = RECUR (value);
12560         chain = TREE_CHAIN (t);
12561         if (chain && chain != void_type_node)
12562           chain = RECUR (chain);
12563         if (purpose == TREE_PURPOSE (t)
12564             && value == TREE_VALUE (t)
12565             && chain == TREE_CHAIN (t))
12566           return t;
12567         return tree_cons (purpose, value, chain);
12568       }
12569
12570     case COMPONENT_REF:
12571       {
12572         tree object;
12573         tree object_type;
12574         tree member;
12575
12576         object = tsubst_non_call_postfix_expression (TREE_OPERAND (t, 0),
12577                                                      args, complain, in_decl);
12578         /* Remember that there was a reference to this entity.  */
12579         if (DECL_P (object))
12580           mark_used (object);
12581         object_type = TREE_TYPE (object);
12582
12583         member = TREE_OPERAND (t, 1);
12584         if (BASELINK_P (member))
12585           member = tsubst_baselink (member,
12586                                     non_reference (TREE_TYPE (object)),
12587                                     args, complain, in_decl);
12588         else
12589           member = tsubst_copy (member, args, complain, in_decl);
12590         if (member == error_mark_node)
12591           return error_mark_node;
12592
12593         if (object_type && !CLASS_TYPE_P (object_type))
12594           {
12595             if (SCALAR_TYPE_P (object_type))
12596               {
12597                 tree s = NULL_TREE;
12598                 tree dtor = member;
12599
12600                 if (TREE_CODE (dtor) == SCOPE_REF)
12601                   {
12602                     s = TREE_OPERAND (dtor, 0);
12603                     dtor = TREE_OPERAND (dtor, 1);
12604                   }
12605                 if (TREE_CODE (dtor) == BIT_NOT_EXPR)
12606                   {
12607                     dtor = TREE_OPERAND (dtor, 0);
12608                     if (TYPE_P (dtor))
12609                       return finish_pseudo_destructor_expr (object, s, dtor);
12610                   }
12611               }
12612           }
12613         else if (TREE_CODE (member) == SCOPE_REF
12614                  && TREE_CODE (TREE_OPERAND (member, 1)) == TEMPLATE_ID_EXPR)
12615           {
12616             tree tmpl;
12617             tree args;
12618
12619             /* Lookup the template functions now that we know what the
12620                scope is.  */
12621             tmpl = TREE_OPERAND (TREE_OPERAND (member, 1), 0);
12622             args = TREE_OPERAND (TREE_OPERAND (member, 1), 1);
12623             member = lookup_qualified_name (TREE_OPERAND (member, 0), tmpl,
12624                                             /*is_type_p=*/false,
12625                                             /*complain=*/false);
12626             if (BASELINK_P (member))
12627               {
12628                 BASELINK_FUNCTIONS (member)
12629                   = build_nt (TEMPLATE_ID_EXPR, BASELINK_FUNCTIONS (member),
12630                               args);
12631                 member = (adjust_result_of_qualified_name_lookup
12632                           (member, BINFO_TYPE (BASELINK_BINFO (member)),
12633                            object_type));
12634               }
12635             else
12636               {
12637                 qualified_name_lookup_error (object_type, tmpl, member,
12638                                              input_location);
12639                 return error_mark_node;
12640               }
12641           }
12642         else if (TREE_CODE (member) == SCOPE_REF
12643                  && !CLASS_TYPE_P (TREE_OPERAND (member, 0))
12644                  && TREE_CODE (TREE_OPERAND (member, 0)) != NAMESPACE_DECL)
12645           {
12646             if (complain & tf_error)
12647               {
12648                 if (TYPE_P (TREE_OPERAND (member, 0)))
12649                   error ("%qT is not a class or namespace",
12650                          TREE_OPERAND (member, 0));
12651                 else
12652                   error ("%qD is not a class or namespace",
12653                          TREE_OPERAND (member, 0));
12654               }
12655             return error_mark_node;
12656           }
12657         else if (TREE_CODE (member) == FIELD_DECL)
12658           return finish_non_static_data_member (member, object, NULL_TREE);
12659
12660         return finish_class_member_access_expr (object, member,
12661                                                 /*template_p=*/false,
12662                                                 complain);
12663       }
12664
12665     case THROW_EXPR:
12666       return build_throw
12667         (RECUR (TREE_OPERAND (t, 0)));
12668
12669     case CONSTRUCTOR:
12670       {
12671         VEC(constructor_elt,gc) *n;
12672         constructor_elt *ce;
12673         unsigned HOST_WIDE_INT idx;
12674         tree type = tsubst (TREE_TYPE (t), args, complain, in_decl);
12675         bool process_index_p;
12676         int newlen;
12677         bool need_copy_p = false;
12678         tree r;
12679
12680         if (type == error_mark_node)
12681           return error_mark_node;
12682
12683         /* digest_init will do the wrong thing if we let it.  */
12684         if (type && TYPE_PTRMEMFUNC_P (type))
12685           return t;
12686
12687         /* We do not want to process the index of aggregate
12688            initializers as they are identifier nodes which will be
12689            looked up by digest_init.  */
12690         process_index_p = !(type && MAYBE_CLASS_TYPE_P (type));
12691
12692         n = VEC_copy (constructor_elt, gc, CONSTRUCTOR_ELTS (t));
12693         newlen = VEC_length (constructor_elt, n);
12694         for (idx = 0; VEC_iterate (constructor_elt, n, idx, ce); idx++)
12695           {
12696             if (ce->index && process_index_p)
12697               ce->index = RECUR (ce->index);
12698
12699             if (PACK_EXPANSION_P (ce->value))
12700               {
12701                 /* Substitute into the pack expansion.  */
12702                 ce->value = tsubst_pack_expansion (ce->value, args, complain,
12703                                                   in_decl);
12704
12705                 if (ce->value == error_mark_node)
12706                   ;
12707                 else if (TREE_VEC_LENGTH (ce->value) == 1)
12708                   /* Just move the argument into place.  */
12709                   ce->value = TREE_VEC_ELT (ce->value, 0);
12710                 else
12711                   {
12712                     /* Update the length of the final CONSTRUCTOR
12713                        arguments vector, and note that we will need to
12714                        copy.*/
12715                     newlen = newlen + TREE_VEC_LENGTH (ce->value) - 1;
12716                     need_copy_p = true;
12717                   }
12718               }
12719             else
12720               ce->value = RECUR (ce->value);
12721           }
12722
12723         if (need_copy_p)
12724           {
12725             VEC(constructor_elt,gc) *old_n = n;
12726
12727             n = VEC_alloc (constructor_elt, gc, newlen);
12728             for (idx = 0; VEC_iterate (constructor_elt, old_n, idx, ce); 
12729                  idx++)
12730               {
12731                 if (TREE_CODE (ce->value) == TREE_VEC)
12732                   {
12733                     int i, len = TREE_VEC_LENGTH (ce->value);
12734                     for (i = 0; i < len; ++i)
12735                       CONSTRUCTOR_APPEND_ELT (n, 0,
12736                                               TREE_VEC_ELT (ce->value, i));
12737                   }
12738                 else
12739                   CONSTRUCTOR_APPEND_ELT (n, 0, ce->value);
12740               }
12741           }
12742
12743         r = build_constructor (init_list_type_node, n);
12744         CONSTRUCTOR_IS_DIRECT_INIT (r) = CONSTRUCTOR_IS_DIRECT_INIT (t);
12745
12746         if (TREE_HAS_CONSTRUCTOR (t))
12747           return finish_compound_literal (type, r);
12748
12749         return r;
12750       }
12751
12752     case TYPEID_EXPR:
12753       {
12754         tree operand_0 = RECUR (TREE_OPERAND (t, 0));
12755         if (TYPE_P (operand_0))
12756           return get_typeid (operand_0);
12757         return build_typeid (operand_0);
12758       }
12759
12760     case VAR_DECL:
12761       if (!args)
12762         return t;
12763       /* Fall through */
12764
12765     case PARM_DECL:
12766       {
12767         tree r = tsubst_copy (t, args, complain, in_decl);
12768
12769         if (TREE_CODE (TREE_TYPE (t)) != REFERENCE_TYPE)
12770           /* If the original type was a reference, we'll be wrapped in
12771              the appropriate INDIRECT_REF.  */
12772           r = convert_from_reference (r);
12773         return r;
12774       }
12775
12776     case VA_ARG_EXPR:
12777       return build_x_va_arg (RECUR (TREE_OPERAND (t, 0)),
12778                              tsubst_copy (TREE_TYPE (t), args, complain,
12779                                           in_decl));
12780
12781     case OFFSETOF_EXPR:
12782       return finish_offsetof (RECUR (TREE_OPERAND (t, 0)));
12783
12784     case TRAIT_EXPR:
12785       {
12786         tree type1 = tsubst_copy (TRAIT_EXPR_TYPE1 (t), args,
12787                                   complain, in_decl);
12788
12789         tree type2 = TRAIT_EXPR_TYPE2 (t);
12790         if (type2)
12791           type2 = tsubst_copy (type2, args, complain, in_decl);
12792         
12793         return finish_trait_expr (TRAIT_EXPR_KIND (t), type1, type2);
12794       }
12795
12796     case STMT_EXPR:
12797       {
12798         tree old_stmt_expr = cur_stmt_expr;
12799         tree stmt_expr = begin_stmt_expr ();
12800
12801         cur_stmt_expr = stmt_expr;
12802         tsubst_expr (STMT_EXPR_STMT (t), args, complain, in_decl,
12803                      integral_constant_expression_p);
12804         stmt_expr = finish_stmt_expr (stmt_expr, false);
12805         cur_stmt_expr = old_stmt_expr;
12806
12807         /* If the resulting list of expression statement is empty,
12808            fold it further into void_zero_node.  */
12809         if (empty_expr_stmt_p (stmt_expr))
12810           stmt_expr = void_zero_node;
12811
12812         return stmt_expr;
12813       }
12814
12815     case CONST_DECL:
12816       t = tsubst_copy (t, args, complain, in_decl);
12817       /* As in finish_id_expression, we resolve enumeration constants
12818          to their underlying values.  */
12819       if (TREE_CODE (t) == CONST_DECL)
12820         {
12821           used_types_insert (TREE_TYPE (t));
12822           return DECL_INITIAL (t);
12823         }
12824       return t;
12825
12826     case LAMBDA_EXPR:
12827       {
12828         tree r = build_lambda_expr ();
12829
12830         tree type = tsubst (TREE_TYPE (t), args, complain, NULL_TREE);
12831         TREE_TYPE (r) = type;
12832         CLASSTYPE_LAMBDA_EXPR (type) = r;
12833
12834         LAMBDA_EXPR_LOCATION (r)
12835           = LAMBDA_EXPR_LOCATION (t);
12836         LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (r)
12837           = LAMBDA_EXPR_DEFAULT_CAPTURE_MODE (t);
12838         LAMBDA_EXPR_MUTABLE_P (r) = LAMBDA_EXPR_MUTABLE_P (t);
12839         LAMBDA_EXPR_DISCRIMINATOR (r)
12840           = (LAMBDA_EXPR_DISCRIMINATOR (t));
12841         LAMBDA_EXPR_CAPTURE_LIST (r)
12842           = RECUR (LAMBDA_EXPR_CAPTURE_LIST (t));
12843         LAMBDA_EXPR_THIS_CAPTURE (r)
12844           = RECUR (LAMBDA_EXPR_THIS_CAPTURE (t));
12845         LAMBDA_EXPR_EXTRA_SCOPE (r)
12846           = RECUR (LAMBDA_EXPR_EXTRA_SCOPE (t));
12847
12848         /* Do this again now that LAMBDA_EXPR_EXTRA_SCOPE is set.  */
12849         determine_visibility (TYPE_NAME (type));
12850         /* Now that we know visibility, instantiate the type so we have a
12851            declaration of the op() for later calls to lambda_function.  */
12852         complete_type (type);
12853
12854         type = tsubst (LAMBDA_EXPR_RETURN_TYPE (t), args, complain, in_decl);
12855         if (type)
12856           apply_lambda_return_type (r, type);
12857
12858         return build_lambda_object (r);
12859       }
12860
12861     default:
12862       /* Handle Objective-C++ constructs, if appropriate.  */
12863       {
12864         tree subst
12865           = objcp_tsubst_copy_and_build (t, args, complain,
12866                                          in_decl, /*function_p=*/false);
12867         if (subst)
12868           return subst;
12869       }
12870       return tsubst_copy (t, args, complain, in_decl);
12871     }
12872
12873 #undef RECUR
12874 }
12875
12876 /* Verify that the instantiated ARGS are valid. For type arguments,
12877    make sure that the type's linkage is ok. For non-type arguments,
12878    make sure they are constants if they are integral or enumerations.
12879    Emit an error under control of COMPLAIN, and return TRUE on error.  */
12880
12881 static bool
12882 check_instantiated_arg (tree tmpl, tree t, tsubst_flags_t complain)
12883 {
12884   if (ARGUMENT_PACK_P (t))
12885     {
12886       tree vec = ARGUMENT_PACK_ARGS (t);
12887       int len = TREE_VEC_LENGTH (vec);
12888       bool result = false;
12889       int i;
12890
12891       for (i = 0; i < len; ++i)
12892         if (check_instantiated_arg (tmpl, TREE_VEC_ELT (vec, i), complain))
12893           result = true;
12894       return result;
12895     }
12896   else if (TYPE_P (t))
12897     {
12898       /* [basic.link]: A name with no linkage (notably, the name
12899          of a class or enumeration declared in a local scope)
12900          shall not be used to declare an entity with linkage.
12901          This implies that names with no linkage cannot be used as
12902          template arguments
12903
12904          DR 757 relaxes this restriction for C++0x.  */
12905       tree nt = (cxx_dialect > cxx98 ? NULL_TREE
12906                  : no_linkage_check (t, /*relaxed_p=*/false));
12907
12908       if (nt)
12909         {
12910           /* DR 488 makes use of a type with no linkage cause
12911              type deduction to fail.  */
12912           if (complain & tf_error)
12913             {
12914               if (TYPE_ANONYMOUS_P (nt))
12915                 error ("%qT is/uses anonymous type", t);
12916               else
12917                 error ("template argument for %qD uses local type %qT",
12918                        tmpl, t);
12919             }
12920           return true;
12921         }
12922       /* In order to avoid all sorts of complications, we do not
12923          allow variably-modified types as template arguments.  */
12924       else if (variably_modified_type_p (t, NULL_TREE))
12925         {
12926           if (complain & tf_error)
12927             error ("%qT is a variably modified type", t);
12928           return true;
12929         }
12930     }
12931   /* A non-type argument of integral or enumerated type must be a
12932      constant.  */
12933   else if (TREE_TYPE (t)
12934            && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (t))
12935            && !TREE_CONSTANT (t))
12936     {
12937       if (complain & tf_error)
12938         error ("integral expression %qE is not constant", t);
12939       return true;
12940     }
12941   return false;
12942 }
12943
12944 static bool
12945 check_instantiated_args (tree tmpl, tree args, tsubst_flags_t complain)
12946 {
12947   int ix, len = DECL_NTPARMS (tmpl);
12948   bool result = false;
12949
12950   for (ix = 0; ix != len; ix++)
12951     {
12952       if (check_instantiated_arg (tmpl, TREE_VEC_ELT (args, ix), complain))
12953         result = true;
12954     }
12955   if (result && (complain & tf_error))
12956     error ("  trying to instantiate %qD", tmpl);
12957   return result;
12958 }
12959
12960 /* Instantiate the indicated variable or function template TMPL with
12961    the template arguments in TARG_PTR.  */
12962
12963 tree
12964 instantiate_template (tree tmpl, tree orig_args, tsubst_flags_t complain)
12965 {
12966   tree targ_ptr = orig_args;
12967   tree fndecl;
12968   tree gen_tmpl;
12969   tree spec;
12970   HOST_WIDE_INT saved_processing_template_decl;
12971
12972   if (tmpl == error_mark_node)
12973     return error_mark_node;
12974
12975   gcc_assert (TREE_CODE (tmpl) == TEMPLATE_DECL);
12976
12977   /* If this function is a clone, handle it specially.  */
12978   if (DECL_CLONED_FUNCTION_P (tmpl))
12979     {
12980       tree spec;
12981       tree clone;
12982
12983       /* Use DECL_ABSTRACT_ORIGIN because only FUNCTION_DECLs have
12984          DECL_CLONED_FUNCTION.  */
12985       spec = instantiate_template (DECL_ABSTRACT_ORIGIN (tmpl),
12986                                    targ_ptr, complain);
12987       if (spec == error_mark_node)
12988         return error_mark_node;
12989
12990       /* Look for the clone.  */
12991       FOR_EACH_CLONE (clone, spec)
12992         if (DECL_NAME (clone) == DECL_NAME (tmpl))
12993           return clone;
12994       /* We should always have found the clone by now.  */
12995       gcc_unreachable ();
12996       return NULL_TREE;
12997     }
12998
12999   /* Check to see if we already have this specialization.  */
13000   gen_tmpl = most_general_template (tmpl);
13001   if (tmpl != gen_tmpl)
13002     /* The TMPL is a partial instantiation.  To get a full set of
13003        arguments we must add the arguments used to perform the
13004        partial instantiation.  */
13005     targ_ptr = add_outermost_template_args (DECL_TI_ARGS (tmpl),
13006                                             targ_ptr);
13007
13008   /* It would be nice to avoid hashing here and then again in tsubst_decl,
13009      but it doesn't seem to be on the hot path.  */
13010   spec = retrieve_specialization (gen_tmpl, targ_ptr, 0);
13011
13012   gcc_assert (tmpl == gen_tmpl
13013               || ((fndecl = retrieve_specialization (tmpl, orig_args, 0))
13014                   == spec)
13015               || fndecl == NULL_TREE);
13016
13017   if (spec != NULL_TREE)
13018     return spec;
13019
13020   if (check_instantiated_args (gen_tmpl, INNERMOST_TEMPLATE_ARGS (targ_ptr),
13021                                complain))
13022     return error_mark_node;
13023
13024   /* We are building a FUNCTION_DECL, during which the access of its
13025      parameters and return types have to be checked.  However this
13026      FUNCTION_DECL which is the desired context for access checking
13027      is not built yet.  We solve this chicken-and-egg problem by
13028      deferring all checks until we have the FUNCTION_DECL.  */
13029   push_deferring_access_checks (dk_deferred);
13030
13031   /* Although PROCESSING_TEMPLATE_DECL may be true at this point
13032      (because, for example, we have encountered a non-dependent
13033      function call in the body of a template function and must now
13034      determine which of several overloaded functions will be called),
13035      within the instantiation itself we are not processing a
13036      template.  */  
13037   saved_processing_template_decl = processing_template_decl;
13038   processing_template_decl = 0;
13039   /* Substitute template parameters to obtain the specialization.  */
13040   fndecl = tsubst (DECL_TEMPLATE_RESULT (gen_tmpl),
13041                    targ_ptr, complain, gen_tmpl);
13042   processing_template_decl = saved_processing_template_decl;
13043   if (fndecl == error_mark_node)
13044     return error_mark_node;
13045
13046   /* Now we know the specialization, compute access previously
13047      deferred.  */
13048   push_access_scope (fndecl);
13049
13050   /* Some typedefs referenced from within the template code need to be access
13051      checked at template instantiation time, i.e now. These types were
13052      added to the template at parsing time. Let's get those and perfom
13053      the acces checks then.  */
13054   perform_typedefs_access_check (DECL_TEMPLATE_RESULT (tmpl), targ_ptr);
13055   perform_deferred_access_checks ();
13056   pop_access_scope (fndecl);
13057   pop_deferring_access_checks ();
13058
13059   /* The DECL_TI_TEMPLATE should always be the immediate parent
13060      template, not the most general template.  */
13061   DECL_TI_TEMPLATE (fndecl) = tmpl;
13062
13063   /* If we've just instantiated the main entry point for a function,
13064      instantiate all the alternate entry points as well.  We do this
13065      by cloning the instantiation of the main entry point, not by
13066      instantiating the template clones.  */
13067   if (TREE_CHAIN (gen_tmpl) && DECL_CLONED_FUNCTION_P (TREE_CHAIN (gen_tmpl)))
13068     clone_function_decl (fndecl, /*update_method_vec_p=*/0);
13069
13070   return fndecl;
13071 }
13072
13073 /* The FN is a TEMPLATE_DECL for a function.  ARGS is an array with
13074    NARGS elements of the arguments that are being used when calling
13075    it.  TARGS is a vector into which the deduced template arguments
13076    are placed.
13077
13078    Return zero for success, 2 for an incomplete match that doesn't resolve
13079    all the types, and 1 for complete failure.  An error message will be
13080    printed only for an incomplete match.
13081
13082    If FN is a conversion operator, or we are trying to produce a specific
13083    specialization, RETURN_TYPE is the return type desired.
13084
13085    The EXPLICIT_TARGS are explicit template arguments provided via a
13086    template-id.
13087
13088    The parameter STRICT is one of:
13089
13090    DEDUCE_CALL:
13091      We are deducing arguments for a function call, as in
13092      [temp.deduct.call].
13093
13094    DEDUCE_CONV:
13095      We are deducing arguments for a conversion function, as in
13096      [temp.deduct.conv].
13097
13098    DEDUCE_EXACT:
13099      We are deducing arguments when doing an explicit instantiation
13100      as in [temp.explicit], when determining an explicit specialization
13101      as in [temp.expl.spec], or when taking the address of a function
13102      template, as in [temp.deduct.funcaddr].  */
13103
13104 int
13105 fn_type_unification (tree fn,
13106                      tree explicit_targs,
13107                      tree targs,
13108                      const tree *args,
13109                      unsigned int nargs,
13110                      tree return_type,
13111                      unification_kind_t strict,
13112                      int flags)
13113 {
13114   tree parms;
13115   tree fntype;
13116   int result;
13117   bool incomplete_argument_packs_p = false;
13118
13119   gcc_assert (TREE_CODE (fn) == TEMPLATE_DECL);
13120
13121   fntype = TREE_TYPE (fn);
13122   if (explicit_targs)
13123     {
13124       /* [temp.deduct]
13125
13126          The specified template arguments must match the template
13127          parameters in kind (i.e., type, nontype, template), and there
13128          must not be more arguments than there are parameters;
13129          otherwise type deduction fails.
13130
13131          Nontype arguments must match the types of the corresponding
13132          nontype template parameters, or must be convertible to the
13133          types of the corresponding nontype parameters as specified in
13134          _temp.arg.nontype_, otherwise type deduction fails.
13135
13136          All references in the function type of the function template
13137          to the corresponding template parameters are replaced by the
13138          specified template argument values.  If a substitution in a
13139          template parameter or in the function type of the function
13140          template results in an invalid type, type deduction fails.  */
13141       tree tparms = DECL_INNERMOST_TEMPLATE_PARMS (fn);
13142       int i, len = TREE_VEC_LENGTH (tparms);
13143       tree converted_args;
13144       bool incomplete = false;
13145
13146       if (explicit_targs == error_mark_node)
13147         return 1;
13148
13149       converted_args
13150         = (coerce_template_parms (tparms, explicit_targs, NULL_TREE, tf_none,
13151                                   /*require_all_args=*/false,
13152                                   /*use_default_args=*/false));
13153       if (converted_args == error_mark_node)
13154         return 1;
13155
13156       /* Substitute the explicit args into the function type.  This is
13157          necessary so that, for instance, explicitly declared function
13158          arguments can match null pointed constants.  If we were given
13159          an incomplete set of explicit args, we must not do semantic
13160          processing during substitution as we could create partial
13161          instantiations.  */
13162       for (i = 0; i < len; i++)
13163         {
13164           tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13165           bool parameter_pack = false;
13166
13167           /* Dig out the actual parm.  */
13168           if (TREE_CODE (parm) == TYPE_DECL
13169               || TREE_CODE (parm) == TEMPLATE_DECL)
13170             {
13171               parm = TREE_TYPE (parm);
13172               parameter_pack = TEMPLATE_TYPE_PARAMETER_PACK (parm);
13173             }
13174           else if (TREE_CODE (parm) == PARM_DECL)
13175             {
13176               parm = DECL_INITIAL (parm);
13177               parameter_pack = TEMPLATE_PARM_PARAMETER_PACK (parm);
13178             }
13179
13180           if (parameter_pack)
13181             {
13182               int level, idx;
13183               tree targ;
13184               template_parm_level_and_index (parm, &level, &idx);
13185
13186               /* Mark the argument pack as "incomplete". We could
13187                  still deduce more arguments during unification.  */
13188               targ = TMPL_ARG (converted_args, level, idx);
13189               if (targ)
13190                 {
13191                   ARGUMENT_PACK_INCOMPLETE_P(targ) = 1;
13192                   ARGUMENT_PACK_EXPLICIT_ARGS (targ) 
13193                     = ARGUMENT_PACK_ARGS (targ);
13194                 }
13195
13196               /* We have some incomplete argument packs.  */
13197               incomplete_argument_packs_p = true;
13198             }
13199         }
13200
13201       if (incomplete_argument_packs_p)
13202         /* Any substitution is guaranteed to be incomplete if there
13203            are incomplete argument packs, because we can still deduce
13204            more arguments.  */
13205         incomplete = 1;
13206       else
13207         incomplete = NUM_TMPL_ARGS (explicit_targs) != NUM_TMPL_ARGS (targs);
13208
13209       processing_template_decl += incomplete;
13210       fntype = tsubst (fntype, converted_args, tf_none, NULL_TREE);
13211       processing_template_decl -= incomplete;
13212
13213       if (fntype == error_mark_node)
13214         return 1;
13215
13216       /* Place the explicitly specified arguments in TARGS.  */
13217       for (i = NUM_TMPL_ARGS (converted_args); i--;)
13218         TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (converted_args, i);
13219     }
13220
13221   /* Never do unification on the 'this' parameter.  */
13222   parms = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (fntype));
13223
13224   if (return_type)
13225     {
13226       tree *new_args;
13227
13228       parms = tree_cons (NULL_TREE, TREE_TYPE (fntype), parms);
13229       new_args = XALLOCAVEC (tree, nargs + 1);
13230       new_args[0] = return_type;
13231       memcpy (new_args + 1, args, nargs * sizeof (tree));
13232       args = new_args;
13233       ++nargs;
13234     }
13235
13236   /* We allow incomplete unification without an error message here
13237      because the standard doesn't seem to explicitly prohibit it.  Our
13238      callers must be ready to deal with unification failures in any
13239      event.  */
13240   result = type_unification_real (DECL_INNERMOST_TEMPLATE_PARMS (fn),
13241                                   targs, parms, args, nargs, /*subr=*/0,
13242                                   strict, flags);
13243
13244   if (result == 0 && incomplete_argument_packs_p)
13245     {
13246       int i, len = NUM_TMPL_ARGS (targs);
13247
13248       /* Clear the "incomplete" flags on all argument packs.  */
13249       for (i = 0; i < len; i++)
13250         {
13251           tree arg = TREE_VEC_ELT (targs, i);
13252           if (ARGUMENT_PACK_P (arg))
13253             {
13254               ARGUMENT_PACK_INCOMPLETE_P (arg) = 0;
13255               ARGUMENT_PACK_EXPLICIT_ARGS (arg) = NULL_TREE;
13256             }
13257         }
13258     }
13259
13260   /* Now that we have bindings for all of the template arguments,
13261      ensure that the arguments deduced for the template template
13262      parameters have compatible template parameter lists.  We cannot
13263      check this property before we have deduced all template
13264      arguments, because the template parameter types of a template
13265      template parameter might depend on prior template parameters
13266      deduced after the template template parameter.  The following
13267      ill-formed example illustrates this issue:
13268
13269        template<typename T, template<T> class C> void f(C<5>, T);
13270
13271        template<int N> struct X {};
13272
13273        void g() {
13274          f(X<5>(), 5l); // error: template argument deduction fails
13275        }
13276
13277      The template parameter list of 'C' depends on the template type
13278      parameter 'T', but 'C' is deduced to 'X' before 'T' is deduced to
13279      'long'.  Thus, we can't check that 'C' cannot bind to 'X' at the
13280      time that we deduce 'C'.  */
13281   if (result == 0
13282       && !template_template_parm_bindings_ok_p 
13283            (DECL_INNERMOST_TEMPLATE_PARMS (fn), targs))
13284     return 1;
13285
13286   if (result == 0)
13287     /* All is well so far.  Now, check:
13288
13289        [temp.deduct]
13290
13291        When all template arguments have been deduced, all uses of
13292        template parameters in nondeduced contexts are replaced with
13293        the corresponding deduced argument values.  If the
13294        substitution results in an invalid type, as described above,
13295        type deduction fails.  */
13296     {
13297       tree substed = tsubst (TREE_TYPE (fn), targs, tf_none, NULL_TREE);
13298       if (substed == error_mark_node)
13299         return 1;
13300
13301       /* If we're looking for an exact match, check that what we got
13302          is indeed an exact match.  It might not be if some template
13303          parameters are used in non-deduced contexts.  */
13304       if (strict == DEDUCE_EXACT)
13305         {
13306           unsigned int i;
13307
13308           tree sarg
13309             = skip_artificial_parms_for (fn, TYPE_ARG_TYPES (substed));
13310           if (return_type)
13311             sarg = tree_cons (NULL_TREE, TREE_TYPE (substed), sarg);
13312           for (i = 0; i < nargs && sarg; ++i, sarg = TREE_CHAIN (sarg))
13313             if (!same_type_p (args[i], TREE_VALUE (sarg)))
13314               return 1;
13315         }
13316     }
13317
13318   return result;
13319 }
13320
13321 /* Adjust types before performing type deduction, as described in
13322    [temp.deduct.call] and [temp.deduct.conv].  The rules in these two
13323    sections are symmetric.  PARM is the type of a function parameter
13324    or the return type of the conversion function.  ARG is the type of
13325    the argument passed to the call, or the type of the value
13326    initialized with the result of the conversion function.
13327    ARG_EXPR is the original argument expression, which may be null.  */
13328
13329 static int
13330 maybe_adjust_types_for_deduction (unification_kind_t strict,
13331                                   tree* parm,
13332                                   tree* arg,
13333                                   tree arg_expr)
13334 {
13335   int result = 0;
13336
13337   switch (strict)
13338     {
13339     case DEDUCE_CALL:
13340       break;
13341
13342     case DEDUCE_CONV:
13343       {
13344         /* Swap PARM and ARG throughout the remainder of this
13345            function; the handling is precisely symmetric since PARM
13346            will initialize ARG rather than vice versa.  */
13347         tree* temp = parm;
13348         parm = arg;
13349         arg = temp;
13350         break;
13351       }
13352
13353     case DEDUCE_EXACT:
13354       /* Core issue #873: Do the DR606 thing (see below) for these cases,
13355          too, but here handle it by stripping the reference from PARM
13356          rather than by adding it to ARG.  */
13357       if (TREE_CODE (*parm) == REFERENCE_TYPE
13358           && TYPE_REF_IS_RVALUE (*parm)
13359           && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13360           && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13361           && TREE_CODE (*arg) == REFERENCE_TYPE
13362           && !TYPE_REF_IS_RVALUE (*arg))
13363         *parm = TREE_TYPE (*parm);
13364       /* Nothing else to do in this case.  */
13365       return 0;
13366
13367     default:
13368       gcc_unreachable ();
13369     }
13370
13371   if (TREE_CODE (*parm) != REFERENCE_TYPE)
13372     {
13373       /* [temp.deduct.call]
13374
13375          If P is not a reference type:
13376
13377          --If A is an array type, the pointer type produced by the
13378          array-to-pointer standard conversion (_conv.array_) is
13379          used in place of A for type deduction; otherwise,
13380
13381          --If A is a function type, the pointer type produced by
13382          the function-to-pointer standard conversion
13383          (_conv.func_) is used in place of A for type deduction;
13384          otherwise,
13385
13386          --If A is a cv-qualified type, the top level
13387          cv-qualifiers of A's type are ignored for type
13388          deduction.  */
13389       if (TREE_CODE (*arg) == ARRAY_TYPE)
13390         *arg = build_pointer_type (TREE_TYPE (*arg));
13391       else if (TREE_CODE (*arg) == FUNCTION_TYPE)
13392         *arg = build_pointer_type (*arg);
13393       else
13394         *arg = TYPE_MAIN_VARIANT (*arg);
13395     }
13396
13397   /* From C++0x [14.8.2.1/3 temp.deduct.call] (after DR606), "If P is
13398      of the form T&&, where T is a template parameter, and the argument
13399      is an lvalue, T is deduced as A& */
13400   if (TREE_CODE (*parm) == REFERENCE_TYPE
13401       && TYPE_REF_IS_RVALUE (*parm)
13402       && TREE_CODE (TREE_TYPE (*parm)) == TEMPLATE_TYPE_PARM
13403       && cp_type_quals (TREE_TYPE (*parm)) == TYPE_UNQUALIFIED
13404       && arg_expr && real_lvalue_p (arg_expr))
13405     *arg = build_reference_type (*arg);
13406
13407   /* [temp.deduct.call]
13408
13409      If P is a cv-qualified type, the top level cv-qualifiers
13410      of P's type are ignored for type deduction.  If P is a
13411      reference type, the type referred to by P is used for
13412      type deduction.  */
13413   *parm = TYPE_MAIN_VARIANT (*parm);
13414   if (TREE_CODE (*parm) == REFERENCE_TYPE)
13415     {
13416       *parm = TREE_TYPE (*parm);
13417       result |= UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
13418     }
13419
13420   /* DR 322. For conversion deduction, remove a reference type on parm
13421      too (which has been swapped into ARG).  */
13422   if (strict == DEDUCE_CONV && TREE_CODE (*arg) == REFERENCE_TYPE)
13423     *arg = TREE_TYPE (*arg);
13424
13425   return result;
13426 }
13427
13428 /* Most parms like fn_type_unification.
13429
13430    If SUBR is 1, we're being called recursively (to unify the
13431    arguments of a function or method parameter of a function
13432    template). */
13433
13434 static int
13435 type_unification_real (tree tparms,
13436                        tree targs,
13437                        tree xparms,
13438                        const tree *xargs,
13439                        unsigned int xnargs,
13440                        int subr,
13441                        unification_kind_t strict,
13442                        int flags)
13443 {
13444   tree parm, arg, arg_expr;
13445   int i;
13446   int ntparms = TREE_VEC_LENGTH (tparms);
13447   int sub_strict;
13448   int saw_undeduced = 0;
13449   tree parms;
13450   const tree *args;
13451   unsigned int nargs;
13452   unsigned int ia;
13453
13454   gcc_assert (TREE_CODE (tparms) == TREE_VEC);
13455   gcc_assert (xparms == NULL_TREE || TREE_CODE (xparms) == TREE_LIST);
13456   gcc_assert (ntparms > 0);
13457
13458   /* Reset the number of non-defaulted template arguments contained
13459      in in TARGS.  */
13460   NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs) = NULL_TREE;
13461
13462   switch (strict)
13463     {
13464     case DEDUCE_CALL:
13465       sub_strict = (UNIFY_ALLOW_OUTER_LEVEL | UNIFY_ALLOW_MORE_CV_QUAL
13466                     | UNIFY_ALLOW_DERIVED);
13467       break;
13468
13469     case DEDUCE_CONV:
13470       sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
13471       break;
13472
13473     case DEDUCE_EXACT:
13474       sub_strict = UNIFY_ALLOW_NONE;
13475       break;
13476
13477     default:
13478       gcc_unreachable ();
13479     }
13480
13481  again:
13482   parms = xparms;
13483   args = xargs;
13484   nargs = xnargs;
13485
13486   ia = 0;
13487   while (parms && parms != void_list_node
13488          && ia < nargs)
13489     {
13490       if (TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13491         break;
13492
13493       parm = TREE_VALUE (parms);
13494       parms = TREE_CHAIN (parms);
13495       arg = args[ia];
13496       ++ia;
13497       arg_expr = NULL;
13498
13499       if (arg == error_mark_node)
13500         return 1;
13501       if (arg == unknown_type_node)
13502         /* We can't deduce anything from this, but we might get all the
13503            template args from other function args.  */
13504         continue;
13505
13506       /* Conversions will be performed on a function argument that
13507          corresponds with a function parameter that contains only
13508          non-deducible template parameters and explicitly specified
13509          template parameters.  */
13510       if (!uses_template_parms (parm))
13511         {
13512           tree type;
13513
13514           if (!TYPE_P (arg))
13515             type = TREE_TYPE (arg);
13516           else
13517             type = arg;
13518
13519           if (same_type_p (parm, type))
13520             continue;
13521           if (strict != DEDUCE_EXACT
13522               && can_convert_arg (parm, type, TYPE_P (arg) ? NULL_TREE : arg,
13523                                   flags))
13524             continue;
13525
13526           return 1;
13527         }
13528
13529       if (!TYPE_P (arg))
13530         {
13531           gcc_assert (TREE_TYPE (arg) != NULL_TREE);
13532           if (type_unknown_p (arg))
13533             {
13534               /* [temp.deduct.type] 
13535
13536                  A template-argument can be deduced from a pointer to
13537                  function or pointer to member function argument if
13538                  the set of overloaded functions does not contain
13539                  function templates and at most one of a set of
13540                  overloaded functions provides a unique match.  */
13541               if (resolve_overloaded_unification
13542                   (tparms, targs, parm, arg, strict, sub_strict))
13543                 continue;
13544
13545               return 1;
13546             }
13547           arg_expr = arg;
13548           arg = unlowered_expr_type (arg);
13549           if (arg == error_mark_node)
13550             return 1;
13551         }
13552
13553       {
13554         int arg_strict = sub_strict;
13555
13556         if (!subr)
13557           arg_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg,
13558                                                           arg_expr);
13559
13560         if (arg == init_list_type_node && arg_expr)
13561           arg = arg_expr;
13562         if (unify (tparms, targs, parm, arg, arg_strict))
13563           return 1;
13564       }
13565     }
13566
13567
13568   if (parms 
13569       && parms != void_list_node
13570       && TREE_CODE (TREE_VALUE (parms)) == TYPE_PACK_EXPANSION)
13571     {
13572       /* Unify the remaining arguments with the pack expansion type.  */
13573       tree argvec;
13574       tree parmvec = make_tree_vec (1);
13575
13576       /* Allocate a TREE_VEC and copy in all of the arguments */ 
13577       argvec = make_tree_vec (nargs - ia);
13578       for (i = 0; ia < nargs; ++ia, ++i)
13579         TREE_VEC_ELT (argvec, i) = args[ia];
13580
13581       /* Copy the parameter into parmvec.  */
13582       TREE_VEC_ELT (parmvec, 0) = TREE_VALUE (parms);
13583       if (unify_pack_expansion (tparms, targs, parmvec, argvec, strict,
13584                                 /*call_args_p=*/true, /*subr=*/subr))
13585         return 1;
13586
13587       /* Advance to the end of the list of parameters.  */
13588       parms = TREE_CHAIN (parms);
13589     }
13590
13591   /* Fail if we've reached the end of the parm list, and more args
13592      are present, and the parm list isn't variadic.  */
13593   if (ia < nargs && parms == void_list_node)
13594     return 1;
13595   /* Fail if parms are left and they don't have default values.  */
13596   if (parms && parms != void_list_node
13597       && TREE_PURPOSE (parms) == NULL_TREE)
13598     return 1;
13599
13600   if (!subr)
13601     for (i = 0; i < ntparms; i++)
13602       if (!TREE_VEC_ELT (targs, i))
13603         {
13604           tree tparm;
13605
13606           if (TREE_VEC_ELT (tparms, i) == error_mark_node)
13607             continue;
13608
13609           tparm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13610
13611           /* If this is an undeduced nontype parameter that depends on
13612              a type parameter, try another pass; its type may have been
13613              deduced from a later argument than the one from which
13614              this parameter can be deduced.  */
13615           if (TREE_CODE (tparm) == PARM_DECL
13616               && uses_template_parms (TREE_TYPE (tparm))
13617               && !saw_undeduced++)
13618             goto again;
13619
13620           /* Core issue #226 (C++0x) [temp.deduct]:
13621
13622                If a template argument has not been deduced, its
13623                default template argument, if any, is used. 
13624
13625              When we are in C++98 mode, TREE_PURPOSE will either
13626              be NULL_TREE or ERROR_MARK_NODE, so we do not need
13627              to explicitly check cxx_dialect here.  */
13628           if (TREE_PURPOSE (TREE_VEC_ELT (tparms, i)))
13629             {
13630               tree parm = TREE_VALUE (TREE_VEC_ELT (tparms, i));
13631               tree arg = TREE_PURPOSE (TREE_VEC_ELT (tparms, i));
13632               arg = tsubst_template_arg (arg, targs, tf_none, NULL_TREE);
13633               arg = convert_template_argument (parm, arg, targs, tf_none,
13634                                                i, NULL_TREE);
13635               if (arg == error_mark_node)
13636                 return 1;
13637               else
13638                 {
13639                   TREE_VEC_ELT (targs, i) = arg;
13640                   /* The position of the first default template argument,
13641                      is also the number of non-defaulted arguments in TARGS.
13642                      Record that.  */
13643                   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
13644                     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, i);
13645                   continue;
13646                 }
13647             }
13648
13649           /* If the type parameter is a parameter pack, then it will
13650              be deduced to an empty parameter pack.  */
13651           if (template_parameter_pack_p (tparm))
13652             {
13653               tree arg;
13654
13655               if (TREE_CODE (tparm) == TEMPLATE_PARM_INDEX)
13656                 {
13657                   arg = make_node (NONTYPE_ARGUMENT_PACK);
13658                   TREE_TYPE (arg)  = TREE_TYPE (TEMPLATE_PARM_DECL (tparm));
13659                   TREE_CONSTANT (arg) = 1;
13660                 }
13661               else
13662                 arg = cxx_make_type (TYPE_ARGUMENT_PACK);
13663
13664               SET_ARGUMENT_PACK_ARGS (arg, make_tree_vec (0));
13665
13666               TREE_VEC_ELT (targs, i) = arg;
13667               continue;
13668             }
13669
13670           return 2;
13671         }
13672 #ifdef ENABLE_CHECKING
13673   if (!NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs))
13674     SET_NON_DEFAULT_TEMPLATE_ARGS_COUNT (targs, TREE_VEC_LENGTH (targs));
13675 #endif
13676
13677   return 0;
13678 }
13679
13680 /* Subroutine of type_unification_real.  Args are like the variables
13681    at the call site.  ARG is an overloaded function (or template-id);
13682    we try deducing template args from each of the overloads, and if
13683    only one succeeds, we go with that.  Modifies TARGS and returns
13684    true on success.  */
13685
13686 static bool
13687 resolve_overloaded_unification (tree tparms,
13688                                 tree targs,
13689                                 tree parm,
13690                                 tree arg,
13691                                 unification_kind_t strict,
13692                                 int sub_strict)
13693 {
13694   tree tempargs = copy_node (targs);
13695   int good = 0;
13696   tree goodfn = NULL_TREE;
13697   bool addr_p;
13698
13699   if (TREE_CODE (arg) == ADDR_EXPR)
13700     {
13701       arg = TREE_OPERAND (arg, 0);
13702       addr_p = true;
13703     }
13704   else
13705     addr_p = false;
13706
13707   if (TREE_CODE (arg) == COMPONENT_REF)
13708     /* Handle `&x' where `x' is some static or non-static member
13709        function name.  */
13710     arg = TREE_OPERAND (arg, 1);
13711
13712   if (TREE_CODE (arg) == OFFSET_REF)
13713     arg = TREE_OPERAND (arg, 1);
13714
13715   /* Strip baselink information.  */
13716   if (BASELINK_P (arg))
13717     arg = BASELINK_FUNCTIONS (arg);
13718
13719   if (TREE_CODE (arg) == TEMPLATE_ID_EXPR)
13720     {
13721       /* If we got some explicit template args, we need to plug them into
13722          the affected templates before we try to unify, in case the
13723          explicit args will completely resolve the templates in question.  */
13724
13725       tree expl_subargs = TREE_OPERAND (arg, 1);
13726       arg = TREE_OPERAND (arg, 0);
13727
13728       for (; arg; arg = OVL_NEXT (arg))
13729         {
13730           tree fn = OVL_CURRENT (arg);
13731           tree subargs, elem;
13732
13733           if (TREE_CODE (fn) != TEMPLATE_DECL)
13734             continue;
13735
13736           ++processing_template_decl;
13737           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13738                                   expl_subargs, /*check_ret=*/false);
13739           if (subargs)
13740             {
13741               elem = tsubst (TREE_TYPE (fn), subargs, tf_none, NULL_TREE);
13742               if (try_one_overload (tparms, targs, tempargs, parm,
13743                                     elem, strict, sub_strict, addr_p)
13744                   && (!goodfn || !decls_match (goodfn, elem)))
13745                 {
13746                   goodfn = elem;
13747                   ++good;
13748                 }
13749             }
13750           --processing_template_decl;
13751         }
13752     }
13753   else if (TREE_CODE (arg) != OVERLOAD
13754            && TREE_CODE (arg) != FUNCTION_DECL)
13755     /* If ARG is, for example, "(0, &f)" then its type will be unknown
13756        -- but the deduction does not succeed because the expression is
13757        not just the function on its own.  */
13758     return false;
13759   else
13760     for (; arg; arg = OVL_NEXT (arg))
13761       if (try_one_overload (tparms, targs, tempargs, parm,
13762                             TREE_TYPE (OVL_CURRENT (arg)),
13763                             strict, sub_strict, addr_p)
13764           && (!goodfn || !decls_match (goodfn, OVL_CURRENT (arg))))
13765         {
13766           goodfn = OVL_CURRENT (arg);
13767           ++good;
13768         }
13769
13770   /* [temp.deduct.type] A template-argument can be deduced from a pointer
13771      to function or pointer to member function argument if the set of
13772      overloaded functions does not contain function templates and at most
13773      one of a set of overloaded functions provides a unique match.
13774
13775      So if we found multiple possibilities, we return success but don't
13776      deduce anything.  */
13777
13778   if (good == 1)
13779     {
13780       int i = TREE_VEC_LENGTH (targs);
13781       for (; i--; )
13782         if (TREE_VEC_ELT (tempargs, i))
13783           TREE_VEC_ELT (targs, i) = TREE_VEC_ELT (tempargs, i);
13784     }
13785   if (good)
13786     return true;
13787
13788   return false;
13789 }
13790
13791 /* Core DR 115: In contexts where deduction is done and fails, or in
13792    contexts where deduction is not done, if a template argument list is
13793    specified and it, along with any default template arguments, identifies
13794    a single function template specialization, then the template-id is an
13795    lvalue for the function template specialization.  */
13796
13797 tree
13798 resolve_nondeduced_context (tree orig_expr)
13799 {
13800   tree expr, offset, baselink;
13801   bool addr;
13802
13803   if (!type_unknown_p (orig_expr))
13804     return orig_expr;
13805
13806   expr = orig_expr;
13807   addr = false;
13808   offset = NULL_TREE;
13809   baselink = NULL_TREE;
13810
13811   if (TREE_CODE (expr) == ADDR_EXPR)
13812     {
13813       expr = TREE_OPERAND (expr, 0);
13814       addr = true;
13815     }
13816   if (TREE_CODE (expr) == OFFSET_REF)
13817     {
13818       offset = expr;
13819       expr = TREE_OPERAND (expr, 1);
13820     }
13821   if (TREE_CODE (expr) == BASELINK)
13822     {
13823       baselink = expr;
13824       expr = BASELINK_FUNCTIONS (expr);
13825     }
13826
13827   if (TREE_CODE (expr) == TEMPLATE_ID_EXPR)
13828     {
13829       int good = 0;
13830       tree goodfn = NULL_TREE;
13831
13832       /* If we got some explicit template args, we need to plug them into
13833          the affected templates before we try to unify, in case the
13834          explicit args will completely resolve the templates in question.  */
13835
13836       tree expl_subargs = TREE_OPERAND (expr, 1);
13837       tree arg = TREE_OPERAND (expr, 0);
13838       tree badfn = NULL_TREE;
13839       tree badargs = NULL_TREE;
13840
13841       for (; arg; arg = OVL_NEXT (arg))
13842         {
13843           tree fn = OVL_CURRENT (arg);
13844           tree subargs, elem;
13845
13846           if (TREE_CODE (fn) != TEMPLATE_DECL)
13847             continue;
13848
13849           ++processing_template_decl;
13850           subargs = get_bindings (fn, DECL_TEMPLATE_RESULT (fn),
13851                                   expl_subargs, /*check_ret=*/false);
13852           if (subargs && !any_dependent_template_arguments_p (subargs))
13853             {
13854               elem = instantiate_template (fn, subargs, tf_none);
13855               if (elem == error_mark_node)
13856                 {
13857                   badfn = fn;
13858                   badargs = subargs;
13859                 }
13860               else if (elem && (!goodfn || !decls_match (goodfn, elem)))
13861                 {
13862                   goodfn = elem;
13863                   ++good;
13864                 }
13865             }
13866           --processing_template_decl;
13867         }
13868       if (good == 1)
13869         {
13870           expr = goodfn;
13871           if (baselink)
13872             expr = build_baselink (BASELINK_BINFO (baselink),
13873                                    BASELINK_ACCESS_BINFO (baselink),
13874                                    expr, BASELINK_OPTYPE (baselink));
13875           if (offset)
13876             expr = build2 (OFFSET_REF, TREE_TYPE (expr),
13877                            TREE_OPERAND (offset, 0), expr);
13878           if (addr)
13879             expr = build_address (expr);
13880           return expr;
13881         }
13882       else if (good == 0 && badargs)
13883         /* There were no good options and at least one bad one, so let the
13884            user know what the problem is.  */
13885         instantiate_template (badfn, badargs, tf_warning_or_error);
13886     }
13887   return orig_expr;
13888 }
13889
13890 /* Subroutine of resolve_overloaded_unification; does deduction for a single
13891    overload.  Fills TARGS with any deduced arguments, or error_mark_node if
13892    different overloads deduce different arguments for a given parm.
13893    ADDR_P is true if the expression for which deduction is being
13894    performed was of the form "& fn" rather than simply "fn".
13895
13896    Returns 1 on success.  */
13897
13898 static int
13899 try_one_overload (tree tparms,
13900                   tree orig_targs,
13901                   tree targs,
13902                   tree parm,
13903                   tree arg,
13904                   unification_kind_t strict,
13905                   int sub_strict,
13906                   bool addr_p)
13907 {
13908   int nargs;
13909   tree tempargs;
13910   int i;
13911
13912   /* [temp.deduct.type] A template-argument can be deduced from a pointer
13913      to function or pointer to member function argument if the set of
13914      overloaded functions does not contain function templates and at most
13915      one of a set of overloaded functions provides a unique match.
13916
13917      So if this is a template, just return success.  */
13918
13919   if (uses_template_parms (arg))
13920     return 1;
13921
13922   if (TREE_CODE (arg) == METHOD_TYPE)
13923     arg = build_ptrmemfunc_type (build_pointer_type (arg));
13924   else if (addr_p)
13925     arg = build_pointer_type (arg);
13926
13927   sub_strict |= maybe_adjust_types_for_deduction (strict, &parm, &arg, NULL);
13928
13929   /* We don't copy orig_targs for this because if we have already deduced
13930      some template args from previous args, unify would complain when we
13931      try to deduce a template parameter for the same argument, even though
13932      there isn't really a conflict.  */
13933   nargs = TREE_VEC_LENGTH (targs);
13934   tempargs = make_tree_vec (nargs);
13935
13936   if (unify (tparms, tempargs, parm, arg, sub_strict) != 0)
13937     return 0;
13938
13939   /* First make sure we didn't deduce anything that conflicts with
13940      explicitly specified args.  */
13941   for (i = nargs; i--; )
13942     {
13943       tree elt = TREE_VEC_ELT (tempargs, i);
13944       tree oldelt = TREE_VEC_ELT (orig_targs, i);
13945
13946       if (!elt)
13947         /*NOP*/;
13948       else if (uses_template_parms (elt))
13949         /* Since we're unifying against ourselves, we will fill in
13950            template args used in the function parm list with our own
13951            template parms.  Discard them.  */
13952         TREE_VEC_ELT (tempargs, i) = NULL_TREE;
13953       else if (oldelt && !template_args_equal (oldelt, elt))
13954         return 0;
13955     }
13956
13957   for (i = nargs; i--; )
13958     {
13959       tree elt = TREE_VEC_ELT (tempargs, i);
13960
13961       if (elt)
13962         TREE_VEC_ELT (targs, i) = elt;
13963     }
13964
13965   return 1;
13966 }
13967
13968 /* PARM is a template class (perhaps with unbound template
13969    parameters).  ARG is a fully instantiated type.  If ARG can be
13970    bound to PARM, return ARG, otherwise return NULL_TREE.  TPARMS and
13971    TARGS are as for unify.  */
13972
13973 static tree
13974 try_class_unification (tree tparms, tree targs, tree parm, tree arg)
13975 {
13976   tree copy_of_targs;
13977
13978   if (!CLASSTYPE_TEMPLATE_INFO (arg)
13979       || (most_general_template (CLASSTYPE_TI_TEMPLATE (arg))
13980           != most_general_template (CLASSTYPE_TI_TEMPLATE (parm))))
13981     return NULL_TREE;
13982
13983   /* We need to make a new template argument vector for the call to
13984      unify.  If we used TARGS, we'd clutter it up with the result of
13985      the attempted unification, even if this class didn't work out.
13986      We also don't want to commit ourselves to all the unifications
13987      we've already done, since unification is supposed to be done on
13988      an argument-by-argument basis.  In other words, consider the
13989      following pathological case:
13990
13991        template <int I, int J, int K>
13992        struct S {};
13993
13994        template <int I, int J>
13995        struct S<I, J, 2> : public S<I, I, I>, S<J, J, J> {};
13996
13997        template <int I, int J, int K>
13998        void f(S<I, J, K>, S<I, I, I>);
13999
14000        void g() {
14001          S<0, 0, 0> s0;
14002          S<0, 1, 2> s2;
14003
14004          f(s0, s2);
14005        }
14006
14007      Now, by the time we consider the unification involving `s2', we
14008      already know that we must have `f<0, 0, 0>'.  But, even though
14009      `S<0, 1, 2>' is derived from `S<0, 0, 0>', the code is invalid
14010      because there are two ways to unify base classes of S<0, 1, 2>
14011      with S<I, I, I>.  If we kept the already deduced knowledge, we
14012      would reject the possibility I=1.  */
14013   copy_of_targs = make_tree_vec (TREE_VEC_LENGTH (targs));
14014
14015   /* If unification failed, we're done.  */
14016   if (unify (tparms, copy_of_targs, CLASSTYPE_TI_ARGS (parm),
14017              CLASSTYPE_TI_ARGS (arg), UNIFY_ALLOW_NONE))
14018     return NULL_TREE;
14019
14020   return arg;
14021 }
14022
14023 /* Given a template type PARM and a class type ARG, find the unique
14024    base type in ARG that is an instance of PARM.  We do not examine
14025    ARG itself; only its base-classes.  If there is not exactly one
14026    appropriate base class, return NULL_TREE.  PARM may be the type of
14027    a partial specialization, as well as a plain template type.  Used
14028    by unify.  */
14029
14030 static tree
14031 get_template_base (tree tparms, tree targs, tree parm, tree arg)
14032 {
14033   tree rval = NULL_TREE;
14034   tree binfo;
14035
14036   gcc_assert (RECORD_OR_UNION_CODE_P (TREE_CODE (arg)));
14037
14038   binfo = TYPE_BINFO (complete_type (arg));
14039   if (!binfo)
14040     /* The type could not be completed.  */
14041     return NULL_TREE;
14042
14043   /* Walk in inheritance graph order.  The search order is not
14044      important, and this avoids multiple walks of virtual bases.  */
14045   for (binfo = TREE_CHAIN (binfo); binfo; binfo = TREE_CHAIN (binfo))
14046     {
14047       tree r = try_class_unification (tparms, targs, parm, BINFO_TYPE (binfo));
14048
14049       if (r)
14050         {
14051           /* If there is more than one satisfactory baseclass, then:
14052
14053                [temp.deduct.call]
14054
14055               If they yield more than one possible deduced A, the type
14056               deduction fails.
14057
14058              applies.  */
14059           if (rval && !same_type_p (r, rval))
14060             return NULL_TREE;
14061
14062           rval = r;
14063         }
14064     }
14065
14066   return rval;
14067 }
14068
14069 /* Returns the level of DECL, which declares a template parameter.  */
14070
14071 static int
14072 template_decl_level (tree decl)
14073 {
14074   switch (TREE_CODE (decl))
14075     {
14076     case TYPE_DECL:
14077     case TEMPLATE_DECL:
14078       return TEMPLATE_TYPE_LEVEL (TREE_TYPE (decl));
14079
14080     case PARM_DECL:
14081       return TEMPLATE_PARM_LEVEL (DECL_INITIAL (decl));
14082
14083     default:
14084       gcc_unreachable ();
14085     }
14086   return 0;
14087 }
14088
14089 /* Decide whether ARG can be unified with PARM, considering only the
14090    cv-qualifiers of each type, given STRICT as documented for unify.
14091    Returns nonzero iff the unification is OK on that basis.  */
14092
14093 static int
14094 check_cv_quals_for_unify (int strict, tree arg, tree parm)
14095 {
14096   int arg_quals = cp_type_quals (arg);
14097   int parm_quals = cp_type_quals (parm);
14098
14099   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14100       && !(strict & UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
14101     {
14102       /*  Although a CVR qualifier is ignored when being applied to a
14103           substituted template parameter ([8.3.2]/1 for example), that
14104           does not apply during deduction [14.8.2.4]/1, (even though
14105           that is not explicitly mentioned, [14.8.2.4]/9 indicates
14106           this).  Except when we're allowing additional CV qualifiers
14107           at the outer level [14.8.2.1]/3,1st bullet.  */
14108       if ((TREE_CODE (arg) == REFERENCE_TYPE
14109            || TREE_CODE (arg) == FUNCTION_TYPE
14110            || TREE_CODE (arg) == METHOD_TYPE)
14111           && (parm_quals & (TYPE_QUAL_CONST | TYPE_QUAL_VOLATILE)))
14112         return 0;
14113
14114       if ((!POINTER_TYPE_P (arg) && TREE_CODE (arg) != TEMPLATE_TYPE_PARM)
14115           && (parm_quals & TYPE_QUAL_RESTRICT))
14116         return 0;
14117     }
14118
14119   if (!(strict & (UNIFY_ALLOW_MORE_CV_QUAL | UNIFY_ALLOW_OUTER_MORE_CV_QUAL))
14120       && (arg_quals & parm_quals) != parm_quals)
14121     return 0;
14122
14123   if (!(strict & (UNIFY_ALLOW_LESS_CV_QUAL | UNIFY_ALLOW_OUTER_LESS_CV_QUAL))
14124       && (parm_quals & arg_quals) != arg_quals)
14125     return 0;
14126
14127   return 1;
14128 }
14129
14130 /* Determines the LEVEL and INDEX for the template parameter PARM.  */
14131 void 
14132 template_parm_level_and_index (tree parm, int* level, int* index)
14133 {
14134   if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14135       || TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14136       || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14137     {
14138       *index = TEMPLATE_TYPE_IDX (parm);
14139       *level = TEMPLATE_TYPE_LEVEL (parm);
14140     }
14141   else
14142     {
14143       *index = TEMPLATE_PARM_IDX (parm);
14144       *level = TEMPLATE_PARM_LEVEL (parm);
14145     }
14146 }
14147
14148 /* Unifies the remaining arguments in PACKED_ARGS with the pack
14149    expansion at the end of PACKED_PARMS. Returns 0 if the type
14150    deduction succeeds, 1 otherwise. STRICT is the same as in
14151    unify. CALL_ARGS_P is true iff PACKED_ARGS is actually a function
14152    call argument list. We'll need to adjust the arguments to make them
14153    types. SUBR tells us if this is from a recursive call to
14154    type_unification_real.  */
14155 int
14156 unify_pack_expansion (tree tparms, tree targs, tree packed_parms, 
14157                       tree packed_args, int strict, bool call_args_p,
14158                       bool subr)
14159 {
14160   tree parm 
14161     = TREE_VEC_ELT (packed_parms, TREE_VEC_LENGTH (packed_parms) - 1);
14162   tree pattern = PACK_EXPANSION_PATTERN (parm);
14163   tree pack, packs = NULL_TREE;
14164   int i, start = TREE_VEC_LENGTH (packed_parms) - 1;
14165   int len = TREE_VEC_LENGTH (packed_args);
14166
14167   /* Determine the parameter packs we will be deducing from the
14168      pattern, and record their current deductions.  */
14169   for (pack = PACK_EXPANSION_PARAMETER_PACKS (parm); 
14170        pack; pack = TREE_CHAIN (pack))
14171     {
14172       tree parm_pack = TREE_VALUE (pack);
14173       int idx, level;
14174
14175       /* Determine the index and level of this parameter pack.  */
14176       template_parm_level_and_index (parm_pack, &level, &idx);
14177
14178       /* Keep track of the parameter packs and their corresponding
14179          argument packs.  */
14180       packs = tree_cons (parm_pack, TMPL_ARG (targs, level, idx), packs);
14181       TREE_TYPE (packs) = make_tree_vec (len - start);
14182     }
14183   
14184   /* Loop through all of the arguments that have not yet been
14185      unified and unify each with the pattern.  */
14186   for (i = start; i < len; i++)
14187     {
14188       tree parm = pattern;
14189
14190       /* For each parameter pack, clear out the deduced value so that
14191          we can deduce it again.  */
14192       for (pack = packs; pack; pack = TREE_CHAIN (pack))
14193         {
14194           int idx, level;
14195           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14196
14197           TMPL_ARG (targs, level, idx) = NULL_TREE;
14198         }
14199
14200       /* Unify the pattern with the current argument.  */
14201       {
14202         tree arg = TREE_VEC_ELT (packed_args, i);
14203         tree arg_expr = NULL_TREE;
14204         int arg_strict = strict;
14205         bool skip_arg_p = false;
14206
14207         if (call_args_p)
14208           {
14209             int sub_strict;
14210
14211             /* This mirrors what we do in type_unification_real.  */
14212             switch (strict)
14213               {
14214               case DEDUCE_CALL:
14215                 sub_strict = (UNIFY_ALLOW_OUTER_LEVEL 
14216                               | UNIFY_ALLOW_MORE_CV_QUAL
14217                               | UNIFY_ALLOW_DERIVED);
14218                 break;
14219                 
14220               case DEDUCE_CONV:
14221                 sub_strict = UNIFY_ALLOW_LESS_CV_QUAL;
14222                 break;
14223                 
14224               case DEDUCE_EXACT:
14225                 sub_strict = UNIFY_ALLOW_NONE;
14226                 break;
14227                 
14228               default:
14229                 gcc_unreachable ();
14230               }
14231
14232             if (!TYPE_P (arg))
14233               {
14234                 gcc_assert (TREE_TYPE (arg) != NULL_TREE);
14235                 if (type_unknown_p (arg))
14236                   {
14237                     /* [temp.deduct.type] A template-argument can be
14238                        deduced from a pointer to function or pointer
14239                        to member function argument if the set of
14240                        overloaded functions does not contain function
14241                        templates and at most one of a set of
14242                        overloaded functions provides a unique
14243                        match.  */
14244
14245                     if (resolve_overloaded_unification
14246                         (tparms, targs, parm, arg,
14247                          (unification_kind_t) strict,
14248                          sub_strict)
14249                         != 0)
14250                       return 1;
14251                     skip_arg_p = true;
14252                   }
14253
14254                 if (!skip_arg_p)
14255                   {
14256                     arg_expr = arg;
14257                     arg = unlowered_expr_type (arg);
14258                     if (arg == error_mark_node)
14259                       return 1;
14260                   }
14261               }
14262       
14263             arg_strict = sub_strict;
14264
14265             if (!subr)
14266               arg_strict |= 
14267                 maybe_adjust_types_for_deduction ((unification_kind_t) strict,
14268                                                   &parm, &arg, arg_expr);
14269           }
14270
14271         if (!skip_arg_p)
14272           {
14273             /* For deduction from an init-list we need the actual list.  */
14274             if (arg_expr && BRACE_ENCLOSED_INITIALIZER_P (arg_expr))
14275               arg = arg_expr;
14276             if (unify (tparms, targs, parm, arg, arg_strict))
14277               return 1;
14278           }
14279       }
14280
14281       /* For each parameter pack, collect the deduced value.  */
14282       for (pack = packs; pack; pack = TREE_CHAIN (pack))
14283         {
14284           int idx, level;
14285           template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14286
14287           TREE_VEC_ELT (TREE_TYPE (pack), i - start) = 
14288             TMPL_ARG (targs, level, idx);
14289         }
14290     }
14291
14292   /* Verify that the results of unification with the parameter packs
14293      produce results consistent with what we've seen before, and make
14294      the deduced argument packs available.  */
14295   for (pack = packs; pack; pack = TREE_CHAIN (pack))
14296     {
14297       tree old_pack = TREE_VALUE (pack);
14298       tree new_args = TREE_TYPE (pack);
14299       int i, len = TREE_VEC_LENGTH (new_args);
14300       int idx, level;
14301       bool nondeduced_p = false;
14302
14303       /* By default keep the original deduced argument pack.
14304          If necessary, more specific code is going to update the
14305          resulting deduced argument later down in this function.  */
14306       template_parm_level_and_index (TREE_PURPOSE (pack), &level, &idx);
14307       TMPL_ARG (targs, level, idx) = old_pack;
14308
14309       /* If NEW_ARGS contains any NULL_TREE entries, we didn't
14310          actually deduce anything.  */
14311       for (i = 0; i < len && !nondeduced_p; ++i)
14312         if (TREE_VEC_ELT (new_args, i) == NULL_TREE)
14313           nondeduced_p = true;
14314       if (nondeduced_p)
14315         continue;
14316
14317       if (old_pack && ARGUMENT_PACK_INCOMPLETE_P (old_pack))
14318         {
14319           /* Prepend the explicit arguments onto NEW_ARGS.  */
14320           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14321           tree old_args = new_args;
14322           int i, explicit_len = TREE_VEC_LENGTH (explicit_args);
14323           int len = explicit_len + TREE_VEC_LENGTH (old_args);
14324
14325           /* Copy the explicit arguments.  */
14326           new_args = make_tree_vec (len);
14327           for (i = 0; i < explicit_len; i++)
14328             TREE_VEC_ELT (new_args, i) = TREE_VEC_ELT (explicit_args, i);
14329
14330           /* Copy the deduced arguments.  */
14331           for (; i < len; i++)
14332             TREE_VEC_ELT (new_args, i) =
14333               TREE_VEC_ELT (old_args, i - explicit_len);
14334         }
14335
14336       if (!old_pack)
14337         {
14338           tree result;
14339           /* Build the deduced *_ARGUMENT_PACK.  */
14340           if (TREE_CODE (TREE_PURPOSE (pack)) == TEMPLATE_PARM_INDEX)
14341             {
14342               result = make_node (NONTYPE_ARGUMENT_PACK);
14343               TREE_TYPE (result) = 
14344                 TREE_TYPE (TEMPLATE_PARM_DECL (TREE_PURPOSE (pack)));
14345               TREE_CONSTANT (result) = 1;
14346             }
14347           else
14348             result = cxx_make_type (TYPE_ARGUMENT_PACK);
14349
14350           SET_ARGUMENT_PACK_ARGS (result, new_args);
14351
14352           /* Note the deduced argument packs for this parameter
14353              pack.  */
14354           TMPL_ARG (targs, level, idx) = result;
14355         }
14356       else if (ARGUMENT_PACK_INCOMPLETE_P (old_pack)
14357                && (ARGUMENT_PACK_ARGS (old_pack) 
14358                    == ARGUMENT_PACK_EXPLICIT_ARGS (old_pack)))
14359         {
14360           /* We only had the explicitly-provided arguments before, but
14361              now we have a complete set of arguments.  */
14362           tree explicit_args = ARGUMENT_PACK_EXPLICIT_ARGS (old_pack);
14363
14364           SET_ARGUMENT_PACK_ARGS (old_pack, new_args);
14365           ARGUMENT_PACK_INCOMPLETE_P (old_pack) = 1;
14366           ARGUMENT_PACK_EXPLICIT_ARGS (old_pack) = explicit_args;
14367         }
14368       else if (!comp_template_args (ARGUMENT_PACK_ARGS (old_pack),
14369                                     new_args))
14370         /* Inconsistent unification of this parameter pack.  */
14371         return 1;
14372     }
14373
14374   return 0;
14375 }
14376
14377 /* Deduce the value of template parameters.  TPARMS is the (innermost)
14378    set of template parameters to a template.  TARGS is the bindings
14379    for those template parameters, as determined thus far; TARGS may
14380    include template arguments for outer levels of template parameters
14381    as well.  PARM is a parameter to a template function, or a
14382    subcomponent of that parameter; ARG is the corresponding argument.
14383    This function attempts to match PARM with ARG in a manner
14384    consistent with the existing assignments in TARGS.  If more values
14385    are deduced, then TARGS is updated.
14386
14387    Returns 0 if the type deduction succeeds, 1 otherwise.  The
14388    parameter STRICT is a bitwise or of the following flags:
14389
14390      UNIFY_ALLOW_NONE:
14391        Require an exact match between PARM and ARG.
14392      UNIFY_ALLOW_MORE_CV_QUAL:
14393        Allow the deduced ARG to be more cv-qualified (by qualification
14394        conversion) than ARG.
14395      UNIFY_ALLOW_LESS_CV_QUAL:
14396        Allow the deduced ARG to be less cv-qualified than ARG.
14397      UNIFY_ALLOW_DERIVED:
14398        Allow the deduced ARG to be a template base class of ARG,
14399        or a pointer to a template base class of the type pointed to by
14400        ARG.
14401      UNIFY_ALLOW_INTEGER:
14402        Allow any integral type to be deduced.  See the TEMPLATE_PARM_INDEX
14403        case for more information.
14404      UNIFY_ALLOW_OUTER_LEVEL:
14405        This is the outermost level of a deduction. Used to determine validity
14406        of qualification conversions. A valid qualification conversion must
14407        have const qualified pointers leading up to the inner type which
14408        requires additional CV quals, except at the outer level, where const
14409        is not required [conv.qual]. It would be normal to set this flag in
14410        addition to setting UNIFY_ALLOW_MORE_CV_QUAL.
14411      UNIFY_ALLOW_OUTER_MORE_CV_QUAL:
14412        This is the outermost level of a deduction, and PARM can be more CV
14413        qualified at this point.
14414      UNIFY_ALLOW_OUTER_LESS_CV_QUAL:
14415        This is the outermost level of a deduction, and PARM can be less CV
14416        qualified at this point.  */
14417
14418 static int
14419 unify (tree tparms, tree targs, tree parm, tree arg, int strict)
14420 {
14421   int idx;
14422   tree targ;
14423   tree tparm;
14424   int strict_in = strict;
14425
14426   /* I don't think this will do the right thing with respect to types.
14427      But the only case I've seen it in so far has been array bounds, where
14428      signedness is the only information lost, and I think that will be
14429      okay.  */
14430   while (TREE_CODE (parm) == NOP_EXPR)
14431     parm = TREE_OPERAND (parm, 0);
14432
14433   if (arg == error_mark_node)
14434     return 1;
14435   if (arg == unknown_type_node
14436       || arg == init_list_type_node)
14437     /* We can't deduce anything from this, but we might get all the
14438        template args from other function args.  */
14439     return 0;
14440
14441   /* If PARM uses template parameters, then we can't bail out here,
14442      even if ARG == PARM, since we won't record unifications for the
14443      template parameters.  We might need them if we're trying to
14444      figure out which of two things is more specialized.  */
14445   if (arg == parm && !uses_template_parms (parm))
14446     return 0;
14447
14448   /* Handle init lists early, so the rest of the function can assume
14449      we're dealing with a type. */
14450   if (BRACE_ENCLOSED_INITIALIZER_P (arg))
14451     {
14452       tree elt, elttype;
14453       unsigned i;
14454       tree orig_parm = parm;
14455
14456       /* Replace T with std::initializer_list<T> for deduction.  */
14457       if (TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14458           && flag_deduce_init_list)
14459         parm = listify (parm);
14460
14461       if (!is_std_init_list (parm))
14462         /* We can only deduce from an initializer list argument if the
14463            parameter is std::initializer_list; otherwise this is a
14464            non-deduced context. */
14465         return 0;
14466
14467       elttype = TREE_VEC_ELT (CLASSTYPE_TI_ARGS (parm), 0);
14468
14469       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (arg), i, elt)
14470         {
14471           int elt_strict = strict;
14472
14473           if (elt == error_mark_node)
14474             return 1;
14475
14476           if (!BRACE_ENCLOSED_INITIALIZER_P (elt))
14477             {
14478               tree type = TREE_TYPE (elt);
14479               /* It should only be possible to get here for a call.  */
14480               gcc_assert (elt_strict & UNIFY_ALLOW_OUTER_LEVEL);
14481               elt_strict |= maybe_adjust_types_for_deduction
14482                 (DEDUCE_CALL, &elttype, &type, elt);
14483               elt = type;
14484             }
14485
14486           if (unify (tparms, targs, elttype, elt, elt_strict))
14487             return 1;
14488         }
14489
14490       /* If the std::initializer_list<T> deduction worked, replace the
14491          deduced A with std::initializer_list<A>.  */
14492       if (orig_parm != parm)
14493         {
14494           idx = TEMPLATE_TYPE_IDX (orig_parm);
14495           targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14496           targ = listify (targ);
14497           TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = targ;
14498         }
14499       return 0;
14500     }
14501
14502   /* Immediately reject some pairs that won't unify because of
14503      cv-qualification mismatches.  */
14504   if (TREE_CODE (arg) == TREE_CODE (parm)
14505       && TYPE_P (arg)
14506       /* It is the elements of the array which hold the cv quals of an array
14507          type, and the elements might be template type parms. We'll check
14508          when we recurse.  */
14509       && TREE_CODE (arg) != ARRAY_TYPE
14510       /* We check the cv-qualifiers when unifying with template type
14511          parameters below.  We want to allow ARG `const T' to unify with
14512          PARM `T' for example, when computing which of two templates
14513          is more specialized, for example.  */
14514       && TREE_CODE (arg) != TEMPLATE_TYPE_PARM
14515       && !check_cv_quals_for_unify (strict_in, arg, parm))
14516     return 1;
14517
14518   if (!(strict & UNIFY_ALLOW_OUTER_LEVEL)
14519       && TYPE_P (parm) && !CP_TYPE_CONST_P (parm))
14520     strict &= ~UNIFY_ALLOW_MORE_CV_QUAL;
14521   strict &= ~UNIFY_ALLOW_OUTER_LEVEL;
14522   strict &= ~UNIFY_ALLOW_DERIVED;
14523   strict &= ~UNIFY_ALLOW_OUTER_MORE_CV_QUAL;
14524   strict &= ~UNIFY_ALLOW_OUTER_LESS_CV_QUAL;
14525
14526   switch (TREE_CODE (parm))
14527     {
14528     case TYPENAME_TYPE:
14529     case SCOPE_REF:
14530     case UNBOUND_CLASS_TEMPLATE:
14531       /* In a type which contains a nested-name-specifier, template
14532          argument values cannot be deduced for template parameters used
14533          within the nested-name-specifier.  */
14534       return 0;
14535
14536     case TEMPLATE_TYPE_PARM:
14537     case TEMPLATE_TEMPLATE_PARM:
14538     case BOUND_TEMPLATE_TEMPLATE_PARM:
14539       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14540       if (tparm == error_mark_node)
14541         return 1;
14542
14543       if (TEMPLATE_TYPE_LEVEL (parm)
14544           != template_decl_level (tparm))
14545         /* The PARM is not one we're trying to unify.  Just check
14546            to see if it matches ARG.  */
14547         return (TREE_CODE (arg) == TREE_CODE (parm)
14548                 && same_type_p (parm, arg)) ? 0 : 1;
14549       idx = TEMPLATE_TYPE_IDX (parm);
14550       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14551       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, idx));
14552
14553       /* Check for mixed types and values.  */
14554       if ((TREE_CODE (parm) == TEMPLATE_TYPE_PARM
14555            && TREE_CODE (tparm) != TYPE_DECL)
14556           || (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14557               && TREE_CODE (tparm) != TEMPLATE_DECL))
14558         return 1;
14559
14560       if (TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14561         {
14562           /* ARG must be constructed from a template class or a template
14563              template parameter.  */
14564           if (TREE_CODE (arg) != BOUND_TEMPLATE_TEMPLATE_PARM
14565               && !CLASSTYPE_SPECIALIZATION_OF_PRIMARY_TEMPLATE_P (arg))
14566             return 1;
14567
14568           {
14569             tree parmvec = TYPE_TI_ARGS (parm);
14570             tree argvec = INNERMOST_TEMPLATE_ARGS (TYPE_TI_ARGS (arg));
14571             tree parm_parms 
14572               = DECL_INNERMOST_TEMPLATE_PARMS
14573                   (TEMPLATE_TEMPLATE_PARM_TEMPLATE_DECL (parm));
14574             int i, len;
14575             int parm_variadic_p = 0;
14576
14577             /* The resolution to DR150 makes clear that default
14578                arguments for an N-argument may not be used to bind T
14579                to a template template parameter with fewer than N
14580                parameters.  It is not safe to permit the binding of
14581                default arguments as an extension, as that may change
14582                the meaning of a conforming program.  Consider:
14583
14584                   struct Dense { static const unsigned int dim = 1; };
14585
14586                   template <template <typename> class View,
14587                             typename Block>
14588                   void operator+(float, View<Block> const&);
14589
14590                   template <typename Block,
14591                             unsigned int Dim = Block::dim>
14592                   struct Lvalue_proxy { operator float() const; };
14593
14594                   void
14595                   test_1d (void) {
14596                     Lvalue_proxy<Dense> p;
14597                     float b;
14598                     b + p;
14599                   }
14600
14601               Here, if Lvalue_proxy is permitted to bind to View, then
14602               the global operator+ will be used; if they are not, the
14603               Lvalue_proxy will be converted to float.  */
14604             if (coerce_template_parms (parm_parms,
14605                                        argvec,
14606                                        TYPE_TI_TEMPLATE (parm),
14607                                        tf_none,
14608                                        /*require_all_args=*/true,
14609                                        /*use_default_args=*/false)
14610                 == error_mark_node)
14611               return 1;
14612
14613             /* Deduce arguments T, i from TT<T> or TT<i>.
14614                We check each element of PARMVEC and ARGVEC individually
14615                rather than the whole TREE_VEC since they can have
14616                different number of elements.  */
14617
14618             parmvec = expand_template_argument_pack (parmvec);
14619             argvec = expand_template_argument_pack (argvec);
14620
14621             len = TREE_VEC_LENGTH (parmvec);
14622
14623             /* Check if the parameters end in a pack, making them
14624                variadic.  */
14625             if (len > 0
14626                 && PACK_EXPANSION_P (TREE_VEC_ELT (parmvec, len - 1)))
14627               parm_variadic_p = 1;
14628             
14629             if (TREE_VEC_LENGTH (argvec) < len - parm_variadic_p)
14630               return 1;
14631
14632              for (i = 0; i < len - parm_variadic_p; ++i)
14633               {
14634                 if (unify (tparms, targs,
14635                            TREE_VEC_ELT (parmvec, i),
14636                            TREE_VEC_ELT (argvec, i),
14637                            UNIFY_ALLOW_NONE))
14638                   return 1;
14639               }
14640
14641             if (parm_variadic_p
14642                 && unify_pack_expansion (tparms, targs,
14643                                          parmvec, argvec,
14644                                          UNIFY_ALLOW_NONE,
14645                                          /*call_args_p=*/false,
14646                                          /*subr=*/false))
14647               return 1;
14648           }
14649           arg = TYPE_TI_TEMPLATE (arg);
14650
14651           /* Fall through to deduce template name.  */
14652         }
14653
14654       if (TREE_CODE (parm) == TEMPLATE_TEMPLATE_PARM
14655           || TREE_CODE (parm) == BOUND_TEMPLATE_TEMPLATE_PARM)
14656         {
14657           /* Deduce template name TT from TT, TT<>, TT<T> and TT<i>.  */
14658
14659           /* Simple cases: Value already set, does match or doesn't.  */
14660           if (targ != NULL_TREE && template_args_equal (targ, arg))
14661             return 0;
14662           else if (targ)
14663             return 1;
14664         }
14665       else
14666         {
14667           /* If PARM is `const T' and ARG is only `int', we don't have
14668              a match unless we are allowing additional qualification.
14669              If ARG is `const int' and PARM is just `T' that's OK;
14670              that binds `const int' to `T'.  */
14671           if (!check_cv_quals_for_unify (strict_in | UNIFY_ALLOW_LESS_CV_QUAL,
14672                                          arg, parm))
14673             return 1;
14674
14675           /* Consider the case where ARG is `const volatile int' and
14676              PARM is `const T'.  Then, T should be `volatile int'.  */
14677           arg = cp_build_qualified_type_real
14678             (arg, cp_type_quals (arg) & ~cp_type_quals (parm), tf_none);
14679           if (arg == error_mark_node)
14680             return 1;
14681
14682           /* Simple cases: Value already set, does match or doesn't.  */
14683           if (targ != NULL_TREE && same_type_p (targ, arg))
14684             return 0;
14685           else if (targ)
14686             return 1;
14687
14688           /* Make sure that ARG is not a variable-sized array.  (Note
14689              that were talking about variable-sized arrays (like
14690              `int[n]'), rather than arrays of unknown size (like
14691              `int[]').)  We'll get very confused by such a type since
14692              the bound of the array will not be computable in an
14693              instantiation.  Besides, such types are not allowed in
14694              ISO C++, so we can do as we please here.  */
14695           if (variably_modified_type_p (arg, NULL_TREE))
14696             return 1;
14697
14698           /* Strip typedefs as in convert_template_argument.  */
14699           arg = strip_typedefs (arg);
14700         }
14701
14702       /* If ARG is a parameter pack or an expansion, we cannot unify
14703          against it unless PARM is also a parameter pack.  */
14704       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
14705           && !template_parameter_pack_p (parm))
14706         return 1;
14707
14708       /* If the argument deduction results is a METHOD_TYPE,
14709          then there is a problem.
14710          METHOD_TYPE doesn't map to any real C++ type the result of
14711          the deduction can not be of that type.  */
14712       if (TREE_CODE (arg) == METHOD_TYPE)
14713         return 1;
14714
14715       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
14716       return 0;
14717
14718     case TEMPLATE_PARM_INDEX:
14719       tparm = TREE_VALUE (TREE_VEC_ELT (tparms, 0));
14720       if (tparm == error_mark_node)
14721         return 1;
14722
14723       if (TEMPLATE_PARM_LEVEL (parm)
14724           != template_decl_level (tparm))
14725         /* The PARM is not one we're trying to unify.  Just check
14726            to see if it matches ARG.  */
14727         return !(TREE_CODE (arg) == TREE_CODE (parm)
14728                  && cp_tree_equal (parm, arg));
14729
14730       idx = TEMPLATE_PARM_IDX (parm);
14731       targ = TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx);
14732
14733       if (targ)
14734         return !cp_tree_equal (targ, arg);
14735
14736       /* [temp.deduct.type] If, in the declaration of a function template
14737          with a non-type template-parameter, the non-type
14738          template-parameter is used in an expression in the function
14739          parameter-list and, if the corresponding template-argument is
14740          deduced, the template-argument type shall match the type of the
14741          template-parameter exactly, except that a template-argument
14742          deduced from an array bound may be of any integral type.
14743          The non-type parameter might use already deduced type parameters.  */
14744       tparm = tsubst (TREE_TYPE (parm), targs, 0, NULL_TREE);
14745       if (!TREE_TYPE (arg))
14746         /* Template-parameter dependent expression.  Just accept it for now.
14747            It will later be processed in convert_template_argument.  */
14748         ;
14749       else if (same_type_p (TREE_TYPE (arg), tparm))
14750         /* OK */;
14751       else if ((strict & UNIFY_ALLOW_INTEGER)
14752                && (TREE_CODE (tparm) == INTEGER_TYPE
14753                    || TREE_CODE (tparm) == BOOLEAN_TYPE))
14754         /* Convert the ARG to the type of PARM; the deduced non-type
14755            template argument must exactly match the types of the
14756            corresponding parameter.  */
14757         arg = fold (build_nop (tparm, arg));
14758       else if (uses_template_parms (tparm))
14759         /* We haven't deduced the type of this parameter yet.  Try again
14760            later.  */
14761         return 0;
14762       else
14763         return 1;
14764
14765       /* If ARG is a parameter pack or an expansion, we cannot unify
14766          against it unless PARM is also a parameter pack.  */
14767       if ((template_parameter_pack_p (arg) || PACK_EXPANSION_P (arg))
14768           && !TEMPLATE_PARM_PARAMETER_PACK (parm))
14769         return 1;
14770
14771       TREE_VEC_ELT (INNERMOST_TEMPLATE_ARGS (targs), idx) = arg;
14772       return 0;
14773
14774     case PTRMEM_CST:
14775      {
14776         /* A pointer-to-member constant can be unified only with
14777          another constant.  */
14778       if (TREE_CODE (arg) != PTRMEM_CST)
14779         return 1;
14780
14781       /* Just unify the class member. It would be useless (and possibly
14782          wrong, depending on the strict flags) to unify also
14783          PTRMEM_CST_CLASS, because we want to be sure that both parm and
14784          arg refer to the same variable, even if through different
14785          classes. For instance:
14786
14787          struct A { int x; };
14788          struct B : A { };
14789
14790          Unification of &A::x and &B::x must succeed.  */
14791       return unify (tparms, targs, PTRMEM_CST_MEMBER (parm),
14792                     PTRMEM_CST_MEMBER (arg), strict);
14793      }
14794
14795     case POINTER_TYPE:
14796       {
14797         if (TREE_CODE (arg) != POINTER_TYPE)
14798           return 1;
14799
14800         /* [temp.deduct.call]
14801
14802            A can be another pointer or pointer to member type that can
14803            be converted to the deduced A via a qualification
14804            conversion (_conv.qual_).
14805
14806            We pass down STRICT here rather than UNIFY_ALLOW_NONE.
14807            This will allow for additional cv-qualification of the
14808            pointed-to types if appropriate.  */
14809
14810         if (TREE_CODE (TREE_TYPE (arg)) == RECORD_TYPE)
14811           /* The derived-to-base conversion only persists through one
14812              level of pointers.  */
14813           strict |= (strict_in & UNIFY_ALLOW_DERIVED);
14814
14815         return unify (tparms, targs, TREE_TYPE (parm),
14816                       TREE_TYPE (arg), strict);
14817       }
14818
14819     case REFERENCE_TYPE:
14820       if (TREE_CODE (arg) != REFERENCE_TYPE)
14821         return 1;
14822       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14823                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
14824
14825     case ARRAY_TYPE:
14826       if (TREE_CODE (arg) != ARRAY_TYPE)
14827         return 1;
14828       if ((TYPE_DOMAIN (parm) == NULL_TREE)
14829           != (TYPE_DOMAIN (arg) == NULL_TREE))
14830         return 1;
14831       if (TYPE_DOMAIN (parm) != NULL_TREE)
14832         {
14833           tree parm_max;
14834           tree arg_max;
14835           bool parm_cst;
14836           bool arg_cst;
14837
14838           /* Our representation of array types uses "N - 1" as the
14839              TYPE_MAX_VALUE for an array with "N" elements, if "N" is
14840              not an integer constant.  We cannot unify arbitrarily
14841              complex expressions, so we eliminate the MINUS_EXPRs
14842              here.  */
14843           parm_max = TYPE_MAX_VALUE (TYPE_DOMAIN (parm));
14844           parm_cst = TREE_CODE (parm_max) == INTEGER_CST;
14845           if (!parm_cst)
14846             {
14847               gcc_assert (TREE_CODE (parm_max) == MINUS_EXPR);
14848               parm_max = TREE_OPERAND (parm_max, 0);
14849             }
14850           arg_max = TYPE_MAX_VALUE (TYPE_DOMAIN (arg));
14851           arg_cst = TREE_CODE (arg_max) == INTEGER_CST;
14852           if (!arg_cst)
14853             {
14854               /* The ARG_MAX may not be a simple MINUS_EXPR, if we are
14855                  trying to unify the type of a variable with the type
14856                  of a template parameter.  For example:
14857
14858                    template <unsigned int N>
14859                    void f (char (&) [N]);
14860                    int g(); 
14861                    void h(int i) {
14862                      char a[g(i)];
14863                      f(a); 
14864                    }
14865
14866                 Here, the type of the ARG will be "int [g(i)]", and
14867                 may be a SAVE_EXPR, etc.  */
14868               if (TREE_CODE (arg_max) != MINUS_EXPR)
14869                 return 1;
14870               arg_max = TREE_OPERAND (arg_max, 0);
14871             }
14872
14873           /* If only one of the bounds used a MINUS_EXPR, compensate
14874              by adding one to the other bound.  */
14875           if (parm_cst && !arg_cst)
14876             parm_max = fold_build2_loc (input_location, PLUS_EXPR,
14877                                     integer_type_node,
14878                                     parm_max,
14879                                     integer_one_node);
14880           else if (arg_cst && !parm_cst)
14881             arg_max = fold_build2_loc (input_location, PLUS_EXPR,
14882                                    integer_type_node,
14883                                    arg_max,
14884                                    integer_one_node);
14885
14886           if (unify (tparms, targs, parm_max, arg_max, UNIFY_ALLOW_INTEGER))
14887             return 1;
14888         }
14889       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
14890                     strict & UNIFY_ALLOW_MORE_CV_QUAL);
14891
14892     case REAL_TYPE:
14893     case COMPLEX_TYPE:
14894     case VECTOR_TYPE:
14895     case INTEGER_TYPE:
14896     case BOOLEAN_TYPE:
14897     case ENUMERAL_TYPE:
14898     case VOID_TYPE:
14899       if (TREE_CODE (arg) != TREE_CODE (parm))
14900         return 1;
14901
14902       /* We have already checked cv-qualification at the top of the
14903          function.  */
14904       if (!same_type_ignoring_top_level_qualifiers_p (arg, parm))
14905         return 1;
14906
14907       /* As far as unification is concerned, this wins.  Later checks
14908          will invalidate it if necessary.  */
14909       return 0;
14910
14911       /* Types INTEGER_CST and MINUS_EXPR can come from array bounds.  */
14912       /* Type INTEGER_CST can come from ordinary constant template args.  */
14913     case INTEGER_CST:
14914       while (TREE_CODE (arg) == NOP_EXPR)
14915         arg = TREE_OPERAND (arg, 0);
14916
14917       if (TREE_CODE (arg) != INTEGER_CST)
14918         return 1;
14919       return !tree_int_cst_equal (parm, arg);
14920
14921     case TREE_VEC:
14922       {
14923         int i;
14924         if (TREE_CODE (arg) != TREE_VEC)
14925           return 1;
14926         if (TREE_VEC_LENGTH (parm) != TREE_VEC_LENGTH (arg))
14927           return 1;
14928         for (i = 0; i < TREE_VEC_LENGTH (parm); ++i)
14929           if (unify (tparms, targs,
14930                      TREE_VEC_ELT (parm, i), TREE_VEC_ELT (arg, i),
14931                      UNIFY_ALLOW_NONE))
14932             return 1;
14933         return 0;
14934       }
14935
14936     case RECORD_TYPE:
14937     case UNION_TYPE:
14938       if (TREE_CODE (arg) != TREE_CODE (parm))
14939         return 1;
14940
14941       if (TYPE_PTRMEMFUNC_P (parm))
14942         {
14943           if (!TYPE_PTRMEMFUNC_P (arg))
14944             return 1;
14945
14946           return unify (tparms, targs,
14947                         TYPE_PTRMEMFUNC_FN_TYPE (parm),
14948                         TYPE_PTRMEMFUNC_FN_TYPE (arg),
14949                         strict);
14950         }
14951
14952       if (CLASSTYPE_TEMPLATE_INFO (parm))
14953         {
14954           tree t = NULL_TREE;
14955
14956           if (strict_in & UNIFY_ALLOW_DERIVED)
14957             {
14958               /* First, we try to unify the PARM and ARG directly.  */
14959               t = try_class_unification (tparms, targs,
14960                                          parm, arg);
14961
14962               if (!t)
14963                 {
14964                   /* Fallback to the special case allowed in
14965                      [temp.deduct.call]:
14966
14967                        If P is a class, and P has the form
14968                        template-id, then A can be a derived class of
14969                        the deduced A.  Likewise, if P is a pointer to
14970                        a class of the form template-id, A can be a
14971                        pointer to a derived class pointed to by the
14972                        deduced A.  */
14973                   t = get_template_base (tparms, targs, parm, arg);
14974
14975                   if (!t)
14976                     return 1;
14977                 }
14978             }
14979           else if (CLASSTYPE_TEMPLATE_INFO (arg)
14980                    && (CLASSTYPE_TI_TEMPLATE (parm)
14981                        == CLASSTYPE_TI_TEMPLATE (arg)))
14982             /* Perhaps PARM is something like S<U> and ARG is S<int>.
14983                Then, we should unify `int' and `U'.  */
14984             t = arg;
14985           else
14986             /* There's no chance of unification succeeding.  */
14987             return 1;
14988
14989           return unify (tparms, targs, CLASSTYPE_TI_ARGS (parm),
14990                         CLASSTYPE_TI_ARGS (t), UNIFY_ALLOW_NONE);
14991         }
14992       else if (!same_type_ignoring_top_level_qualifiers_p (parm, arg))
14993         return 1;
14994       return 0;
14995
14996     case METHOD_TYPE:
14997     case FUNCTION_TYPE:
14998       {
14999         unsigned int nargs;
15000         tree *args;
15001         tree a;
15002         unsigned int i;
15003
15004         if (TREE_CODE (arg) != TREE_CODE (parm))
15005           return 1;
15006
15007         /* CV qualifications for methods can never be deduced, they must
15008            match exactly.  We need to check them explicitly here,
15009            because type_unification_real treats them as any other
15010            cv-qualified parameter.  */
15011         if (TREE_CODE (parm) == METHOD_TYPE
15012             && (!check_cv_quals_for_unify
15013                 (UNIFY_ALLOW_NONE,
15014                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (arg))),
15015                  TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (parm))))))
15016           return 1;
15017
15018         if (unify (tparms, targs, TREE_TYPE (parm),
15019                    TREE_TYPE (arg), UNIFY_ALLOW_NONE))
15020           return 1;
15021
15022         nargs = list_length (TYPE_ARG_TYPES (arg));
15023         args = XALLOCAVEC (tree, nargs);
15024         for (a = TYPE_ARG_TYPES (arg), i = 0;
15025              a != NULL_TREE && a != void_list_node;
15026              a = TREE_CHAIN (a), ++i)
15027           args[i] = TREE_VALUE (a);
15028         nargs = i;
15029
15030         return type_unification_real (tparms, targs, TYPE_ARG_TYPES (parm),
15031                                       args, nargs, 1, DEDUCE_EXACT,
15032                                       LOOKUP_NORMAL);
15033       }
15034
15035     case OFFSET_TYPE:
15036       /* Unify a pointer to member with a pointer to member function, which
15037          deduces the type of the member as a function type. */
15038       if (TYPE_PTRMEMFUNC_P (arg))
15039         {
15040           tree method_type;
15041           tree fntype;
15042           cp_cv_quals cv_quals;
15043
15044           /* Check top-level cv qualifiers */
15045           if (!check_cv_quals_for_unify (UNIFY_ALLOW_NONE, arg, parm))
15046             return 1;
15047
15048           if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
15049                      TYPE_PTRMEMFUNC_OBJECT_TYPE (arg), UNIFY_ALLOW_NONE))
15050             return 1;
15051
15052           /* Determine the type of the function we are unifying against. */
15053           method_type = TREE_TYPE (TYPE_PTRMEMFUNC_FN_TYPE (arg));
15054           fntype =
15055             build_function_type (TREE_TYPE (method_type),
15056                                  TREE_CHAIN (TYPE_ARG_TYPES (method_type)));
15057
15058           /* Extract the cv-qualifiers of the member function from the
15059              implicit object parameter and place them on the function
15060              type to be restored later. */
15061           cv_quals =
15062             cp_type_quals(TREE_TYPE (TREE_VALUE (TYPE_ARG_TYPES (method_type))));
15063           fntype = build_qualified_type (fntype, cv_quals);
15064           return unify (tparms, targs, TREE_TYPE (parm), fntype, strict);
15065         }
15066
15067       if (TREE_CODE (arg) != OFFSET_TYPE)
15068         return 1;
15069       if (unify (tparms, targs, TYPE_OFFSET_BASETYPE (parm),
15070                  TYPE_OFFSET_BASETYPE (arg), UNIFY_ALLOW_NONE))
15071         return 1;
15072       return unify (tparms, targs, TREE_TYPE (parm), TREE_TYPE (arg),
15073                     strict);
15074
15075     case CONST_DECL:
15076       if (DECL_TEMPLATE_PARM_P (parm))
15077         return unify (tparms, targs, DECL_INITIAL (parm), arg, strict);
15078       if (arg != integral_constant_value (parm))
15079         return 1;
15080       return 0;
15081
15082     case FIELD_DECL:
15083     case TEMPLATE_DECL:
15084       /* Matched cases are handled by the ARG == PARM test above.  */
15085       return 1;
15086
15087     case VAR_DECL:
15088       /* A non-type template parameter that is a variable should be a
15089          an integral constant, in which case, it whould have been
15090          folded into its (constant) value. So we should not be getting
15091          a variable here.  */
15092       gcc_unreachable ();
15093
15094     case TYPE_ARGUMENT_PACK:
15095     case NONTYPE_ARGUMENT_PACK:
15096       {
15097         tree packed_parms = ARGUMENT_PACK_ARGS (parm);
15098         tree packed_args = ARGUMENT_PACK_ARGS (arg);
15099         int i, len = TREE_VEC_LENGTH (packed_parms);
15100         int argslen = TREE_VEC_LENGTH (packed_args);
15101         int parm_variadic_p = 0;
15102
15103         for (i = 0; i < len; ++i)
15104           {
15105             if (PACK_EXPANSION_P (TREE_VEC_ELT (packed_parms, i)))
15106               {
15107                 if (i == len - 1)
15108                   /* We can unify against something with a trailing
15109                      parameter pack.  */
15110                   parm_variadic_p = 1;
15111                 else
15112                   /* Since there is something following the pack
15113                      expansion, we cannot unify this template argument
15114                      list.  */
15115                   return 0;
15116               }
15117           }
15118           
15119
15120         /* If we don't have enough arguments to satisfy the parameters
15121            (not counting the pack expression at the end), or we have
15122            too many arguments for a parameter list that doesn't end in
15123            a pack expression, we can't unify.  */
15124         if (argslen < (len - parm_variadic_p)
15125             || (argslen > len && !parm_variadic_p))
15126           return 1;
15127
15128         /* Unify all of the parameters that precede the (optional)
15129            pack expression.  */
15130         for (i = 0; i < len - parm_variadic_p; ++i)
15131           {
15132             if (unify (tparms, targs, TREE_VEC_ELT (packed_parms, i),
15133                        TREE_VEC_ELT (packed_args, i), strict))
15134               return 1;
15135           }
15136
15137         if (parm_variadic_p)
15138           return unify_pack_expansion (tparms, targs, 
15139                                        packed_parms, packed_args,
15140                                        strict, /*call_args_p=*/false,
15141                                        /*subr=*/false);
15142         return 0;
15143       }
15144
15145       break;
15146
15147     case TYPEOF_TYPE:
15148     case DECLTYPE_TYPE:
15149       /* Cannot deduce anything from TYPEOF_TYPE or DECLTYPE_TYPE
15150          nodes.  */
15151       return 0;
15152
15153     case ERROR_MARK:
15154       /* Unification fails if we hit an error node.  */
15155       return 1;
15156
15157     default:
15158       gcc_assert (EXPR_P (parm));
15159
15160       /* We must be looking at an expression.  This can happen with
15161          something like:
15162
15163            template <int I>
15164            void foo(S<I>, S<I + 2>);
15165
15166          This is a "nondeduced context":
15167
15168            [deduct.type]
15169
15170            The nondeduced contexts are:
15171
15172            --A type that is a template-id in which one or more of
15173              the template-arguments is an expression that references
15174              a template-parameter.
15175
15176          In these cases, we assume deduction succeeded, but don't
15177          actually infer any unifications.  */
15178
15179       if (!uses_template_parms (parm)
15180           && !template_args_equal (parm, arg))
15181         return 1;
15182       else
15183         return 0;
15184     }
15185 }
15186 \f
15187 /* Note that DECL can be defined in this translation unit, if
15188    required.  */
15189
15190 static void
15191 mark_definable (tree decl)
15192 {
15193   tree clone;
15194   DECL_NOT_REALLY_EXTERN (decl) = 1;
15195   FOR_EACH_CLONE (clone, decl)
15196     DECL_NOT_REALLY_EXTERN (clone) = 1;
15197 }
15198
15199 /* Called if RESULT is explicitly instantiated, or is a member of an
15200    explicitly instantiated class.  */
15201
15202 void
15203 mark_decl_instantiated (tree result, int extern_p)
15204 {
15205   SET_DECL_EXPLICIT_INSTANTIATION (result);
15206
15207   /* If this entity has already been written out, it's too late to
15208      make any modifications.  */
15209   if (TREE_ASM_WRITTEN (result))
15210     return;
15211
15212   if (TREE_CODE (result) != FUNCTION_DECL)
15213     /* The TREE_PUBLIC flag for function declarations will have been
15214        set correctly by tsubst.  */
15215     TREE_PUBLIC (result) = 1;
15216
15217   /* This might have been set by an earlier implicit instantiation.  */
15218   DECL_COMDAT (result) = 0;
15219
15220   if (extern_p)
15221     DECL_NOT_REALLY_EXTERN (result) = 0;
15222   else
15223     {
15224       mark_definable (result);
15225       /* Always make artificials weak.  */
15226       if (DECL_ARTIFICIAL (result) && flag_weak)
15227         comdat_linkage (result);
15228       /* For WIN32 we also want to put explicit instantiations in
15229          linkonce sections.  */
15230       else if (TREE_PUBLIC (result))
15231         maybe_make_one_only (result);
15232     }
15233
15234   /* If EXTERN_P, then this function will not be emitted -- unless
15235      followed by an explicit instantiation, at which point its linkage
15236      will be adjusted.  If !EXTERN_P, then this function will be
15237      emitted here.  In neither circumstance do we want
15238      import_export_decl to adjust the linkage.  */
15239   DECL_INTERFACE_KNOWN (result) = 1;
15240 }
15241
15242 /* Subroutine of more_specialized_fn: check whether TARGS is missing any
15243    important template arguments.  If any are missing, we check whether
15244    they're important by using error_mark_node for substituting into any
15245    args that were used for partial ordering (the ones between ARGS and END)
15246    and seeing if it bubbles up.  */
15247
15248 static bool
15249 check_undeduced_parms (tree targs, tree args, tree end)
15250 {
15251   bool found = false;
15252   int i;
15253   for (i = TREE_VEC_LENGTH (targs) - 1; i >= 0; --i)
15254     if (TREE_VEC_ELT (targs, i) == NULL_TREE)
15255       {
15256         found = true;
15257         TREE_VEC_ELT (targs, i) = error_mark_node;
15258       }
15259   if (found)
15260     {
15261       for (; args != end; args = TREE_CHAIN (args))
15262         {
15263           tree substed = tsubst (TREE_VALUE (args), targs, tf_none, NULL_TREE);
15264           if (substed == error_mark_node)
15265             return true;
15266         }
15267     }
15268   return false;
15269 }
15270
15271 /* Given two function templates PAT1 and PAT2, return:
15272
15273    1 if PAT1 is more specialized than PAT2 as described in [temp.func.order].
15274    -1 if PAT2 is more specialized than PAT1.
15275    0 if neither is more specialized.
15276
15277    LEN indicates the number of parameters we should consider
15278    (defaulted parameters should not be considered).
15279
15280    The 1998 std underspecified function template partial ordering, and
15281    DR214 addresses the issue.  We take pairs of arguments, one from
15282    each of the templates, and deduce them against each other.  One of
15283    the templates will be more specialized if all the *other*
15284    template's arguments deduce against its arguments and at least one
15285    of its arguments *does* *not* deduce against the other template's
15286    corresponding argument.  Deduction is done as for class templates.
15287    The arguments used in deduction have reference and top level cv
15288    qualifiers removed.  Iff both arguments were originally reference
15289    types *and* deduction succeeds in both directions, the template
15290    with the more cv-qualified argument wins for that pairing (if
15291    neither is more cv-qualified, they both are equal).  Unlike regular
15292    deduction, after all the arguments have been deduced in this way,
15293    we do *not* verify the deduced template argument values can be
15294    substituted into non-deduced contexts.
15295
15296    The logic can be a bit confusing here, because we look at deduce1 and
15297    targs1 to see if pat2 is at least as specialized, and vice versa; if we
15298    can find template arguments for pat1 to make arg1 look like arg2, that
15299    means that arg2 is at least as specialized as arg1.  */
15300
15301 int
15302 more_specialized_fn (tree pat1, tree pat2, int len)
15303 {
15304   tree decl1 = DECL_TEMPLATE_RESULT (pat1);
15305   tree decl2 = DECL_TEMPLATE_RESULT (pat2);
15306   tree targs1 = make_tree_vec (DECL_NTPARMS (pat1));
15307   tree targs2 = make_tree_vec (DECL_NTPARMS (pat2));
15308   tree tparms1 = DECL_INNERMOST_TEMPLATE_PARMS (pat1);
15309   tree tparms2 = DECL_INNERMOST_TEMPLATE_PARMS (pat2);
15310   tree args1 = TYPE_ARG_TYPES (TREE_TYPE (decl1));
15311   tree args2 = TYPE_ARG_TYPES (TREE_TYPE (decl2));
15312   tree origs1, origs2;
15313   bool lose1 = false;
15314   bool lose2 = false;
15315
15316   /* Remove the this parameter from non-static member functions.  If
15317      one is a non-static member function and the other is not a static
15318      member function, remove the first parameter from that function
15319      also.  This situation occurs for operator functions where we
15320      locate both a member function (with this pointer) and non-member
15321      operator (with explicit first operand).  */
15322   if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl1))
15323     {
15324       len--; /* LEN is the number of significant arguments for DECL1 */
15325       args1 = TREE_CHAIN (args1);
15326       if (!DECL_STATIC_FUNCTION_P (decl2))
15327         args2 = TREE_CHAIN (args2);
15328     }
15329   else if (DECL_NONSTATIC_MEMBER_FUNCTION_P (decl2))
15330     {
15331       args2 = TREE_CHAIN (args2);
15332       if (!DECL_STATIC_FUNCTION_P (decl1))
15333         {
15334           len--;
15335           args1 = TREE_CHAIN (args1);
15336         }
15337     }
15338
15339   /* If only one is a conversion operator, they are unordered.  */
15340   if (DECL_CONV_FN_P (decl1) != DECL_CONV_FN_P (decl2))
15341     return 0;
15342
15343   /* Consider the return type for a conversion function */
15344   if (DECL_CONV_FN_P (decl1))
15345     {
15346       args1 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl1)), args1);
15347       args2 = tree_cons (NULL_TREE, TREE_TYPE (TREE_TYPE (decl2)), args2);
15348       len++;
15349     }
15350
15351   processing_template_decl++;
15352
15353   origs1 = args1;
15354   origs2 = args2;
15355
15356   while (len--
15357          /* Stop when an ellipsis is seen.  */
15358          && args1 != NULL_TREE && args2 != NULL_TREE)
15359     {
15360       tree arg1 = TREE_VALUE (args1);
15361       tree arg2 = TREE_VALUE (args2);
15362       int deduce1, deduce2;
15363       int quals1 = -1;
15364       int quals2 = -1;
15365
15366       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15367           && TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15368         {
15369           /* When both arguments are pack expansions, we need only
15370              unify the patterns themselves.  */
15371           arg1 = PACK_EXPANSION_PATTERN (arg1);
15372           arg2 = PACK_EXPANSION_PATTERN (arg2);
15373
15374           /* This is the last comparison we need to do.  */
15375           len = 0;
15376         }
15377
15378       if (TREE_CODE (arg1) == REFERENCE_TYPE)
15379         {
15380           arg1 = TREE_TYPE (arg1);
15381           quals1 = cp_type_quals (arg1);
15382         }
15383
15384       if (TREE_CODE (arg2) == REFERENCE_TYPE)
15385         {
15386           arg2 = TREE_TYPE (arg2);
15387           quals2 = cp_type_quals (arg2);
15388         }
15389
15390       if ((quals1 < 0) != (quals2 < 0))
15391         {
15392           /* Only of the args is a reference, see if we should apply
15393              array/function pointer decay to it.  This is not part of
15394              DR214, but is, IMHO, consistent with the deduction rules
15395              for the function call itself, and with our earlier
15396              implementation of the underspecified partial ordering
15397              rules.  (nathan).  */
15398           if (quals1 >= 0)
15399             {
15400               switch (TREE_CODE (arg1))
15401                 {
15402                 case ARRAY_TYPE:
15403                   arg1 = TREE_TYPE (arg1);
15404                   /* FALLTHROUGH. */
15405                 case FUNCTION_TYPE:
15406                   arg1 = build_pointer_type (arg1);
15407                   break;
15408
15409                 default:
15410                   break;
15411                 }
15412             }
15413           else
15414             {
15415               switch (TREE_CODE (arg2))
15416                 {
15417                 case ARRAY_TYPE:
15418                   arg2 = TREE_TYPE (arg2);
15419                   /* FALLTHROUGH. */
15420                 case FUNCTION_TYPE:
15421                   arg2 = build_pointer_type (arg2);
15422                   break;
15423
15424                 default:
15425                   break;
15426                 }
15427             }
15428         }
15429
15430       arg1 = TYPE_MAIN_VARIANT (arg1);
15431       arg2 = TYPE_MAIN_VARIANT (arg2);
15432
15433       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION)
15434         {
15435           int i, len2 = list_length (args2);
15436           tree parmvec = make_tree_vec (1);
15437           tree argvec = make_tree_vec (len2);
15438           tree ta = args2;
15439
15440           /* Setup the parameter vector, which contains only ARG1.  */
15441           TREE_VEC_ELT (parmvec, 0) = arg1;
15442
15443           /* Setup the argument vector, which contains the remaining
15444              arguments.  */
15445           for (i = 0; i < len2; i++, ta = TREE_CHAIN (ta))
15446             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15447
15448           deduce1 = !unify_pack_expansion (tparms1, targs1, parmvec, 
15449                                            argvec, UNIFY_ALLOW_NONE, 
15450                                            /*call_args_p=*/false, 
15451                                            /*subr=*/0);
15452
15453           /* We cannot deduce in the other direction, because ARG1 is
15454              a pack expansion but ARG2 is not.  */
15455           deduce2 = 0;
15456         }
15457       else if (TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15458         {
15459           int i, len1 = list_length (args1);
15460           tree parmvec = make_tree_vec (1);
15461           tree argvec = make_tree_vec (len1);
15462           tree ta = args1;
15463
15464           /* Setup the parameter vector, which contains only ARG1.  */
15465           TREE_VEC_ELT (parmvec, 0) = arg2;
15466
15467           /* Setup the argument vector, which contains the remaining
15468              arguments.  */
15469           for (i = 0; i < len1; i++, ta = TREE_CHAIN (ta))
15470             TREE_VEC_ELT (argvec, i) = TREE_VALUE (ta);
15471
15472           deduce2 = !unify_pack_expansion (tparms2, targs2, parmvec, 
15473                                            argvec, UNIFY_ALLOW_NONE, 
15474                                            /*call_args_p=*/false, 
15475                                            /*subr=*/0);
15476
15477           /* We cannot deduce in the other direction, because ARG2 is
15478              a pack expansion but ARG1 is not.*/
15479           deduce1 = 0;
15480         }
15481
15482       else
15483         {
15484           /* The normal case, where neither argument is a pack
15485              expansion.  */
15486           deduce1 = !unify (tparms1, targs1, arg1, arg2, UNIFY_ALLOW_NONE);
15487           deduce2 = !unify (tparms2, targs2, arg2, arg1, UNIFY_ALLOW_NONE);
15488         }
15489
15490       /* If we couldn't deduce arguments for tparms1 to make arg1 match
15491          arg2, then arg2 is not as specialized as arg1.  */
15492       if (!deduce1)
15493         lose2 = true;
15494       if (!deduce2)
15495         lose1 = true;
15496
15497       /* "If, for a given type, deduction succeeds in both directions
15498          (i.e., the types are identical after the transformations above)
15499          and if the type from the argument template is more cv-qualified
15500          than the type from the parameter template (as described above)
15501          that type is considered to be more specialized than the other. If
15502          neither type is more cv-qualified than the other then neither type
15503          is more specialized than the other."  */
15504
15505       if (deduce1 && deduce2
15506           && quals1 != quals2 && quals1 >= 0 && quals2 >= 0)
15507         {
15508           if ((quals1 & quals2) == quals2)
15509             lose2 = true;
15510           if ((quals1 & quals2) == quals1)
15511             lose1 = true;
15512         }
15513
15514       if (lose1 && lose2)
15515         /* We've failed to deduce something in either direction.
15516            These must be unordered.  */
15517         break;
15518
15519       if (TREE_CODE (arg1) == TYPE_PACK_EXPANSION
15520           || TREE_CODE (arg2) == TYPE_PACK_EXPANSION)
15521         /* We have already processed all of the arguments in our
15522            handing of the pack expansion type.  */
15523         len = 0;
15524
15525       args1 = TREE_CHAIN (args1);
15526       args2 = TREE_CHAIN (args2);
15527     }
15528
15529   /* "In most cases, all template parameters must have values in order for
15530      deduction to succeed, but for partial ordering purposes a template
15531      parameter may remain without a value provided it is not used in the
15532      types being used for partial ordering."
15533
15534      Thus, if we are missing any of the targs1 we need to substitute into
15535      origs1, then pat2 is not as specialized as pat1.  This can happen when
15536      there is a nondeduced context.  */
15537   if (!lose2 && check_undeduced_parms (targs1, origs1, args1))
15538     lose2 = true;
15539   if (!lose1 && check_undeduced_parms (targs2, origs2, args2))
15540     lose1 = true;
15541
15542   processing_template_decl--;
15543
15544   /* All things being equal, if the next argument is a pack expansion
15545      for one function but not for the other, prefer the
15546      non-variadic function.  FIXME this is bogus; see c++/41958.  */
15547   if (lose1 == lose2
15548       && args1 && TREE_VALUE (args1)
15549       && args2 && TREE_VALUE (args2))
15550     {
15551       lose1 = TREE_CODE (TREE_VALUE (args1)) == TYPE_PACK_EXPANSION;
15552       lose2 = TREE_CODE (TREE_VALUE (args2)) == TYPE_PACK_EXPANSION;
15553     }
15554
15555   if (lose1 == lose2)
15556     return 0;
15557   else if (!lose1)
15558     return 1;
15559   else
15560     return -1;
15561 }
15562
15563 /* Determine which of two partial specializations is more specialized.
15564
15565    PAT1 is a TREE_LIST whose TREE_TYPE is the _TYPE node corresponding
15566    to the first partial specialization.  The TREE_VALUE is the
15567    innermost set of template parameters for the partial
15568    specialization.  PAT2 is similar, but for the second template.
15569
15570    Return 1 if the first partial specialization is more specialized;
15571    -1 if the second is more specialized; 0 if neither is more
15572    specialized.
15573
15574    See [temp.class.order] for information about determining which of
15575    two templates is more specialized.  */
15576
15577 static int
15578 more_specialized_class (tree pat1, tree pat2)
15579 {
15580   tree targs;
15581   tree tmpl1, tmpl2;
15582   int winner = 0;
15583   bool any_deductions = false;
15584
15585   tmpl1 = TREE_TYPE (pat1);
15586   tmpl2 = TREE_TYPE (pat2);
15587
15588   /* Just like what happens for functions, if we are ordering between
15589      different class template specializations, we may encounter dependent
15590      types in the arguments, and we need our dependency check functions
15591      to behave correctly.  */
15592   ++processing_template_decl;
15593   targs = get_class_bindings (TREE_VALUE (pat1),
15594                               CLASSTYPE_TI_ARGS (tmpl1),
15595                               CLASSTYPE_TI_ARGS (tmpl2));
15596   if (targs)
15597     {
15598       --winner;
15599       any_deductions = true;
15600     }
15601
15602   targs = get_class_bindings (TREE_VALUE (pat2),
15603                               CLASSTYPE_TI_ARGS (tmpl2),
15604                               CLASSTYPE_TI_ARGS (tmpl1));
15605   if (targs)
15606     {
15607       ++winner;
15608       any_deductions = true;
15609     }
15610   --processing_template_decl;
15611
15612   /* In the case of a tie where at least one of the class templates
15613      has a parameter pack at the end, the template with the most
15614      non-packed parameters wins.  */
15615   if (winner == 0
15616       && any_deductions
15617       && (template_args_variadic_p (TREE_PURPOSE (pat1))
15618           || template_args_variadic_p (TREE_PURPOSE (pat2))))
15619     {
15620       tree args1 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat1));
15621       tree args2 = INNERMOST_TEMPLATE_ARGS (TREE_PURPOSE (pat2));
15622       int len1 = TREE_VEC_LENGTH (args1);
15623       int len2 = TREE_VEC_LENGTH (args2);
15624
15625       /* We don't count the pack expansion at the end.  */
15626       if (template_args_variadic_p (TREE_PURPOSE (pat1)))
15627         --len1;
15628       if (template_args_variadic_p (TREE_PURPOSE (pat2)))
15629         --len2;
15630
15631       if (len1 > len2)
15632         return 1;
15633       else if (len1 < len2)
15634         return -1;
15635     }
15636
15637   return winner;
15638 }
15639
15640 /* Return the template arguments that will produce the function signature
15641    DECL from the function template FN, with the explicit template
15642    arguments EXPLICIT_ARGS.  If CHECK_RETTYPE is true, the return type must
15643    also match.  Return NULL_TREE if no satisfactory arguments could be
15644    found.  */
15645
15646 static tree
15647 get_bindings (tree fn, tree decl, tree explicit_args, bool check_rettype)
15648 {
15649   int ntparms = DECL_NTPARMS (fn);
15650   tree targs = make_tree_vec (ntparms);
15651   tree decl_type;
15652   tree decl_arg_types;
15653   tree *args;
15654   unsigned int nargs, ix;
15655   tree arg;
15656
15657   /* Substitute the explicit template arguments into the type of DECL.
15658      The call to fn_type_unification will handle substitution into the
15659      FN.  */
15660   decl_type = TREE_TYPE (decl);
15661   if (explicit_args && uses_template_parms (decl_type))
15662     {
15663       tree tmpl;
15664       tree converted_args;
15665
15666       if (DECL_TEMPLATE_INFO (decl))
15667         tmpl = DECL_TI_TEMPLATE (decl);
15668       else
15669         /* We can get here for some invalid specializations.  */
15670         return NULL_TREE;
15671
15672       converted_args
15673         = coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
15674                                  explicit_args, NULL_TREE,
15675                                  tf_none,
15676                                  /*require_all_args=*/false,
15677                                  /*use_default_args=*/false);
15678       if (converted_args == error_mark_node)
15679         return NULL_TREE;
15680
15681       decl_type = tsubst (decl_type, converted_args, tf_none, NULL_TREE);
15682       if (decl_type == error_mark_node)
15683         return NULL_TREE;
15684     }
15685
15686   /* Never do unification on the 'this' parameter.  */
15687   decl_arg_types = skip_artificial_parms_for (decl, 
15688                                               TYPE_ARG_TYPES (decl_type));
15689
15690   nargs = list_length (decl_arg_types);
15691   args = XALLOCAVEC (tree, nargs);
15692   for (arg = decl_arg_types, ix = 0;
15693        arg != NULL_TREE && arg != void_list_node;
15694        arg = TREE_CHAIN (arg), ++ix)
15695     args[ix] = TREE_VALUE (arg);
15696
15697   if (fn_type_unification (fn, explicit_args, targs,
15698                            args, ix,
15699                            (check_rettype || DECL_CONV_FN_P (fn)
15700                             ? TREE_TYPE (decl_type) : NULL_TREE),
15701                            DEDUCE_EXACT, LOOKUP_NORMAL))
15702     return NULL_TREE;
15703
15704   return targs;
15705 }
15706
15707 /* Return the innermost template arguments that, when applied to a
15708    template specialization whose innermost template parameters are
15709    TPARMS, and whose specialization arguments are SPEC_ARGS, yield the
15710    ARGS.
15711
15712    For example, suppose we have:
15713
15714      template <class T, class U> struct S {};
15715      template <class T> struct S<T*, int> {};
15716
15717    Then, suppose we want to get `S<double*, int>'.  The TPARMS will be
15718    {T}, the SPEC_ARGS will be {T*, int} and the ARGS will be {double*,
15719    int}.  The resulting vector will be {double}, indicating that `T'
15720    is bound to `double'.  */
15721
15722 static tree
15723 get_class_bindings (tree tparms, tree spec_args, tree args)
15724 {
15725   int i, ntparms = TREE_VEC_LENGTH (tparms);
15726   tree deduced_args;
15727   tree innermost_deduced_args;
15728
15729   innermost_deduced_args = make_tree_vec (ntparms);
15730   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
15731     {
15732       deduced_args = copy_node (args);
15733       SET_TMPL_ARGS_LEVEL (deduced_args,
15734                            TMPL_ARGS_DEPTH (deduced_args),
15735                            innermost_deduced_args);
15736     }
15737   else
15738     deduced_args = innermost_deduced_args;
15739
15740   if (unify (tparms, deduced_args,
15741              INNERMOST_TEMPLATE_ARGS (spec_args),
15742              INNERMOST_TEMPLATE_ARGS (args),
15743              UNIFY_ALLOW_NONE))
15744     return NULL_TREE;
15745
15746   for (i =  0; i < ntparms; ++i)
15747     if (! TREE_VEC_ELT (innermost_deduced_args, i))
15748       return NULL_TREE;
15749
15750   /* Verify that nondeduced template arguments agree with the type
15751      obtained from argument deduction.
15752
15753      For example:
15754
15755        struct A { typedef int X; };
15756        template <class T, class U> struct C {};
15757        template <class T> struct C<T, typename T::X> {};
15758
15759      Then with the instantiation `C<A, int>', we can deduce that
15760      `T' is `A' but unify () does not check whether `typename T::X'
15761      is `int'.  */
15762   spec_args = tsubst (spec_args, deduced_args, tf_none, NULL_TREE);
15763   if (spec_args == error_mark_node
15764       /* We only need to check the innermost arguments; the other
15765          arguments will always agree.  */
15766       || !comp_template_args (INNERMOST_TEMPLATE_ARGS (spec_args),
15767                               INNERMOST_TEMPLATE_ARGS (args)))
15768     return NULL_TREE;
15769
15770   /* Now that we have bindings for all of the template arguments,
15771      ensure that the arguments deduced for the template template
15772      parameters have compatible template parameter lists.  See the use
15773      of template_template_parm_bindings_ok_p in fn_type_unification
15774      for more information.  */
15775   if (!template_template_parm_bindings_ok_p (tparms, deduced_args))
15776     return NULL_TREE;
15777
15778   return deduced_args;
15779 }
15780
15781 /* TEMPLATES is a TREE_LIST.  Each TREE_VALUE is a TEMPLATE_DECL.
15782    Return the TREE_LIST node with the most specialized template, if
15783    any.  If there is no most specialized template, the error_mark_node
15784    is returned.
15785
15786    Note that this function does not look at, or modify, the
15787    TREE_PURPOSE or TREE_TYPE of any of the nodes.  Since the node
15788    returned is one of the elements of INSTANTIATIONS, callers may
15789    store information in the TREE_PURPOSE or TREE_TYPE of the nodes,
15790    and retrieve it from the value returned.  */
15791
15792 tree
15793 most_specialized_instantiation (tree templates)
15794 {
15795   tree fn, champ;
15796
15797   ++processing_template_decl;
15798
15799   champ = templates;
15800   for (fn = TREE_CHAIN (templates); fn; fn = TREE_CHAIN (fn))
15801     {
15802       int fate = 0;
15803
15804       if (get_bindings (TREE_VALUE (champ),
15805                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
15806                         NULL_TREE, /*check_ret=*/false))
15807         fate--;
15808
15809       if (get_bindings (TREE_VALUE (fn),
15810                         DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
15811                         NULL_TREE, /*check_ret=*/false))
15812         fate++;
15813
15814       if (fate == -1)
15815         champ = fn;
15816       else if (!fate)
15817         {
15818           /* Equally specialized, move to next function.  If there
15819              is no next function, nothing's most specialized.  */
15820           fn = TREE_CHAIN (fn);
15821           champ = fn;
15822           if (!fn)
15823             break;
15824         }
15825     }
15826
15827   if (champ)
15828     /* Now verify that champ is better than everything earlier in the
15829        instantiation list.  */
15830     for (fn = templates; fn != champ; fn = TREE_CHAIN (fn))
15831       if (get_bindings (TREE_VALUE (champ),
15832                         DECL_TEMPLATE_RESULT (TREE_VALUE (fn)),
15833                         NULL_TREE, /*check_ret=*/false)
15834           || !get_bindings (TREE_VALUE (fn),
15835                             DECL_TEMPLATE_RESULT (TREE_VALUE (champ)),
15836                             NULL_TREE, /*check_ret=*/false))
15837         {
15838           champ = NULL_TREE;
15839           break;
15840         }
15841
15842   processing_template_decl--;
15843
15844   if (!champ)
15845     return error_mark_node;
15846
15847   return champ;
15848 }
15849
15850 /* If DECL is a specialization of some template, return the most
15851    general such template.  Otherwise, returns NULL_TREE.
15852
15853    For example, given:
15854
15855      template <class T> struct S { template <class U> void f(U); };
15856
15857    if TMPL is `template <class U> void S<int>::f(U)' this will return
15858    the full template.  This function will not trace past partial
15859    specializations, however.  For example, given in addition:
15860
15861      template <class T> struct S<T*> { template <class U> void f(U); };
15862
15863    if TMPL is `template <class U> void S<int*>::f(U)' this will return
15864    `template <class T> template <class U> S<T*>::f(U)'.  */
15865
15866 tree
15867 most_general_template (tree decl)
15868 {
15869   /* If DECL is a FUNCTION_DECL, find the TEMPLATE_DECL of which it is
15870      an immediate specialization.  */
15871   if (TREE_CODE (decl) == FUNCTION_DECL)
15872     {
15873       if (DECL_TEMPLATE_INFO (decl)) {
15874         decl = DECL_TI_TEMPLATE (decl);
15875
15876         /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE for a
15877            template friend.  */
15878         if (TREE_CODE (decl) != TEMPLATE_DECL)
15879           return NULL_TREE;
15880       } else
15881         return NULL_TREE;
15882     }
15883
15884   /* Look for more and more general templates.  */
15885   while (DECL_TEMPLATE_INFO (decl))
15886     {
15887       /* The DECL_TI_TEMPLATE can be an IDENTIFIER_NODE in some cases.
15888          (See cp-tree.h for details.)  */
15889       if (TREE_CODE (DECL_TI_TEMPLATE (decl)) != TEMPLATE_DECL)
15890         break;
15891
15892       if (CLASS_TYPE_P (TREE_TYPE (decl))
15893           && CLASSTYPE_TEMPLATE_SPECIALIZATION (TREE_TYPE (decl)))
15894         break;
15895
15896       /* Stop if we run into an explicitly specialized class template.  */
15897       if (!DECL_NAMESPACE_SCOPE_P (decl)
15898           && DECL_CONTEXT (decl)
15899           && CLASSTYPE_TEMPLATE_SPECIALIZATION (DECL_CONTEXT (decl)))
15900         break;
15901
15902       decl = DECL_TI_TEMPLATE (decl);
15903     }
15904
15905   return decl;
15906 }
15907
15908 /* Return the most specialized of the class template partial
15909    specializations of TMPL which can produce TYPE, a specialization of
15910    TMPL.  The value returned is actually a TREE_LIST; the TREE_TYPE is
15911    a _TYPE node corresponding to the partial specialization, while the
15912    TREE_PURPOSE is the set of template arguments that must be
15913    substituted into the TREE_TYPE in order to generate TYPE.
15914
15915    If the choice of partial specialization is ambiguous, a diagnostic
15916    is issued, and the error_mark_node is returned.  If there are no
15917    partial specializations of TMPL matching TYPE, then NULL_TREE is
15918    returned.  */
15919
15920 static tree
15921 most_specialized_class (tree type, tree tmpl)
15922 {
15923   tree list = NULL_TREE;
15924   tree t;
15925   tree champ;
15926   int fate;
15927   bool ambiguous_p;
15928   tree args;
15929   tree outer_args = NULL_TREE;
15930
15931   tmpl = most_general_template (tmpl);
15932   args = CLASSTYPE_TI_ARGS (type);
15933
15934   /* For determining which partial specialization to use, only the
15935      innermost args are interesting.  */
15936   if (TMPL_ARGS_HAVE_MULTIPLE_LEVELS (args))
15937     {
15938       outer_args = strip_innermost_template_args (args, 1);
15939       args = INNERMOST_TEMPLATE_ARGS (args);
15940     }
15941
15942   for (t = DECL_TEMPLATE_SPECIALIZATIONS (tmpl); t; t = TREE_CHAIN (t))
15943     {
15944       tree partial_spec_args;
15945       tree spec_args;
15946       tree parms = TREE_VALUE (t);
15947
15948       partial_spec_args = CLASSTYPE_TI_ARGS (TREE_TYPE (t));
15949
15950       ++processing_template_decl;
15951
15952       if (outer_args)
15953         {
15954           int i;
15955
15956           /* Discard the outer levels of args, and then substitute in the
15957              template args from the enclosing class.  */
15958           partial_spec_args = INNERMOST_TEMPLATE_ARGS (partial_spec_args);
15959           partial_spec_args = tsubst_template_args
15960             (partial_spec_args, outer_args, tf_none, NULL_TREE);
15961
15962           /* PARMS already refers to just the innermost parms, but the
15963              template parms in partial_spec_args had their levels lowered
15964              by tsubst, so we need to do the same for the parm list.  We
15965              can't just tsubst the TREE_VEC itself, as tsubst wants to
15966              treat a TREE_VEC as an argument vector.  */
15967           parms = copy_node (parms);
15968           for (i = TREE_VEC_LENGTH (parms) - 1; i >= 0; --i)
15969             TREE_VEC_ELT (parms, i) =
15970               tsubst (TREE_VEC_ELT (parms, i), outer_args, tf_none, NULL_TREE);
15971
15972         }
15973
15974       partial_spec_args =
15975           coerce_template_parms (DECL_INNERMOST_TEMPLATE_PARMS (tmpl),
15976                                  add_to_template_args (outer_args,
15977                                                        partial_spec_args),
15978                                  tmpl, tf_none,
15979                                  /*require_all_args=*/true,
15980                                  /*use_default_args=*/true);
15981
15982       --processing_template_decl;
15983
15984       if (partial_spec_args == error_mark_node)
15985         return error_mark_node;
15986
15987       spec_args = get_class_bindings (parms,
15988                                       partial_spec_args,
15989                                       args);
15990       if (spec_args)
15991         {
15992           if (outer_args)
15993             spec_args = add_to_template_args (outer_args, spec_args);
15994           list = tree_cons (spec_args, TREE_VALUE (t), list);
15995           TREE_TYPE (list) = TREE_TYPE (t);
15996         }
15997     }
15998
15999   if (! list)
16000     return NULL_TREE;
16001
16002   ambiguous_p = false;
16003   t = list;
16004   champ = t;
16005   t = TREE_CHAIN (t);
16006   for (; t; t = TREE_CHAIN (t))
16007     {
16008       fate = more_specialized_class (champ, t);
16009       if (fate == 1)
16010         ;
16011       else
16012         {
16013           if (fate == 0)
16014             {
16015               t = TREE_CHAIN (t);
16016               if (! t)
16017                 {
16018                   ambiguous_p = true;
16019                   break;
16020                 }
16021             }
16022           champ = t;
16023         }
16024     }
16025
16026   if (!ambiguous_p)
16027     for (t = list; t && t != champ; t = TREE_CHAIN (t))
16028       {
16029         fate = more_specialized_class (champ, t);
16030         if (fate != 1)
16031           {
16032             ambiguous_p = true;
16033             break;
16034           }
16035       }
16036
16037   if (ambiguous_p)
16038     {
16039       const char *str;
16040       char *spaces = NULL;
16041       error ("ambiguous class template instantiation for %q#T", type);
16042       str = TREE_CHAIN (list) ? _("candidates are:") : _("candidate is:");
16043       for (t = list; t; t = TREE_CHAIN (t))
16044         {
16045           error ("%s %+#T", spaces ? spaces : str, TREE_TYPE (t));
16046           spaces = spaces ? spaces : get_spaces (str);
16047         }
16048       free (spaces);
16049       return error_mark_node;
16050     }
16051
16052   return champ;
16053 }
16054
16055 /* Explicitly instantiate DECL.  */
16056
16057 void
16058 do_decl_instantiation (tree decl, tree storage)
16059 {
16060   tree result = NULL_TREE;
16061   int extern_p = 0;
16062
16063   if (!decl || decl == error_mark_node)
16064     /* An error occurred, for which grokdeclarator has already issued
16065        an appropriate message.  */
16066     return;
16067   else if (! DECL_LANG_SPECIFIC (decl))
16068     {
16069       error ("explicit instantiation of non-template %q#D", decl);
16070       return;
16071     }
16072   else if (TREE_CODE (decl) == VAR_DECL)
16073     {
16074       /* There is an asymmetry here in the way VAR_DECLs and
16075          FUNCTION_DECLs are handled by grokdeclarator.  In the case of
16076          the latter, the DECL we get back will be marked as a
16077          template instantiation, and the appropriate
16078          DECL_TEMPLATE_INFO will be set up.  This does not happen for
16079          VAR_DECLs so we do the lookup here.  Probably, grokdeclarator
16080          should handle VAR_DECLs as it currently handles
16081          FUNCTION_DECLs.  */
16082       if (!DECL_CLASS_SCOPE_P (decl))
16083         {
16084           error ("%qD is not a static data member of a class template", decl);
16085           return;
16086         }
16087       result = lookup_field (DECL_CONTEXT (decl), DECL_NAME (decl), 0, false);
16088       if (!result || TREE_CODE (result) != VAR_DECL)
16089         {
16090           error ("no matching template for %qD found", decl);
16091           return;
16092         }
16093       if (!same_type_p (TREE_TYPE (result), TREE_TYPE (decl)))
16094         {
16095           error ("type %qT for explicit instantiation %qD does not match "
16096                  "declared type %qT", TREE_TYPE (result), decl,
16097                  TREE_TYPE (decl));
16098           return;
16099         }
16100     }
16101   else if (TREE_CODE (decl) != FUNCTION_DECL)
16102     {
16103       error ("explicit instantiation of %q#D", decl);
16104       return;
16105     }
16106   else
16107     result = decl;
16108
16109   /* Check for various error cases.  Note that if the explicit
16110      instantiation is valid the RESULT will currently be marked as an
16111      *implicit* instantiation; DECL_EXPLICIT_INSTANTIATION is not set
16112      until we get here.  */
16113
16114   if (DECL_TEMPLATE_SPECIALIZATION (result))
16115     {
16116       /* DR 259 [temp.spec].
16117
16118          Both an explicit instantiation and a declaration of an explicit
16119          specialization shall not appear in a program unless the explicit
16120          instantiation follows a declaration of the explicit specialization.
16121
16122          For a given set of template parameters, if an explicit
16123          instantiation of a template appears after a declaration of an
16124          explicit specialization for that template, the explicit
16125          instantiation has no effect.  */
16126       return;
16127     }
16128   else if (DECL_EXPLICIT_INSTANTIATION (result))
16129     {
16130       /* [temp.spec]
16131
16132          No program shall explicitly instantiate any template more
16133          than once.
16134
16135          We check DECL_NOT_REALLY_EXTERN so as not to complain when
16136          the first instantiation was `extern' and the second is not,
16137          and EXTERN_P for the opposite case.  */
16138       if (DECL_NOT_REALLY_EXTERN (result) && !extern_p)
16139         permerror (input_location, "duplicate explicit instantiation of %q#D", result);
16140       /* If an "extern" explicit instantiation follows an ordinary
16141          explicit instantiation, the template is instantiated.  */
16142       if (extern_p)
16143         return;
16144     }
16145   else if (!DECL_IMPLICIT_INSTANTIATION (result))
16146     {
16147       error ("no matching template for %qD found", result);
16148       return;
16149     }
16150   else if (!DECL_TEMPLATE_INFO (result))
16151     {
16152       permerror (input_location, "explicit instantiation of non-template %q#D", result);
16153       return;
16154     }
16155
16156   if (storage == NULL_TREE)
16157     ;
16158   else if (storage == ridpointers[(int) RID_EXTERN])
16159     {
16160       if (!in_system_header && (cxx_dialect == cxx98))
16161         pedwarn (input_location, OPT_pedantic, 
16162                  "ISO C++ 1998 forbids the use of %<extern%> on explicit "
16163                  "instantiations");
16164       extern_p = 1;
16165     }
16166   else
16167     error ("storage class %qD applied to template instantiation", storage);
16168
16169   check_explicit_instantiation_namespace (result);
16170   mark_decl_instantiated (result, extern_p);
16171   if (! extern_p)
16172     instantiate_decl (result, /*defer_ok=*/1,
16173                       /*expl_inst_class_mem_p=*/false);
16174 }
16175
16176 static void
16177 mark_class_instantiated (tree t, int extern_p)
16178 {
16179   SET_CLASSTYPE_EXPLICIT_INSTANTIATION (t);
16180   SET_CLASSTYPE_INTERFACE_KNOWN (t);
16181   CLASSTYPE_INTERFACE_ONLY (t) = extern_p;
16182   TYPE_DECL_SUPPRESS_DEBUG (TYPE_NAME (t)) = extern_p;
16183   if (! extern_p)
16184     {
16185       CLASSTYPE_DEBUG_REQUESTED (t) = 1;
16186       rest_of_type_compilation (t, 1);
16187     }
16188 }
16189
16190 /* Called from do_type_instantiation through binding_table_foreach to
16191    do recursive instantiation for the type bound in ENTRY.  */
16192 static void
16193 bt_instantiate_type_proc (binding_entry entry, void *data)
16194 {
16195   tree storage = *(tree *) data;
16196
16197   if (MAYBE_CLASS_TYPE_P (entry->type)
16198       && !uses_template_parms (CLASSTYPE_TI_ARGS (entry->type)))
16199     do_type_instantiation (TYPE_MAIN_DECL (entry->type), storage, 0);
16200 }
16201
16202 /* Called from do_type_instantiation to instantiate a member
16203    (a member function or a static member variable) of an
16204    explicitly instantiated class template.  */
16205 static void
16206 instantiate_class_member (tree decl, int extern_p)
16207 {
16208   mark_decl_instantiated (decl, extern_p);
16209   if (! extern_p)
16210     instantiate_decl (decl, /*defer_ok=*/1,
16211                       /*expl_inst_class_mem_p=*/true);
16212 }
16213
16214 /* Perform an explicit instantiation of template class T.  STORAGE, if
16215    non-null, is the RID for extern, inline or static.  COMPLAIN is
16216    nonzero if this is called from the parser, zero if called recursively,
16217    since the standard is unclear (as detailed below).  */
16218
16219 void
16220 do_type_instantiation (tree t, tree storage, tsubst_flags_t complain)
16221 {
16222   int extern_p = 0;
16223   int nomem_p = 0;
16224   int static_p = 0;
16225   int previous_instantiation_extern_p = 0;
16226
16227   if (TREE_CODE (t) == TYPE_DECL)
16228     t = TREE_TYPE (t);
16229
16230   if (! CLASS_TYPE_P (t) || ! CLASSTYPE_TEMPLATE_INFO (t))
16231     {
16232       error ("explicit instantiation of non-template type %qT", t);
16233       return;
16234     }
16235
16236   complete_type (t);
16237
16238   if (!COMPLETE_TYPE_P (t))
16239     {
16240       if (complain & tf_error)
16241         error ("explicit instantiation of %q#T before definition of template",
16242                t);
16243       return;
16244     }
16245
16246   if (storage != NULL_TREE)
16247     {
16248       if (!in_system_header)
16249         {
16250           if (storage == ridpointers[(int) RID_EXTERN])
16251             {
16252               if (cxx_dialect == cxx98)
16253                 pedwarn (input_location, OPT_pedantic, 
16254                          "ISO C++ 1998 forbids the use of %<extern%> on "
16255                          "explicit instantiations");
16256             }
16257           else
16258             pedwarn (input_location, OPT_pedantic, 
16259                      "ISO C++ forbids the use of %qE"
16260                      " on explicit instantiations", storage);
16261         }
16262
16263       if (storage == ridpointers[(int) RID_INLINE])
16264         nomem_p = 1;
16265       else if (storage == ridpointers[(int) RID_EXTERN])
16266         extern_p = 1;
16267       else if (storage == ridpointers[(int) RID_STATIC])
16268         static_p = 1;
16269       else
16270         {
16271           error ("storage class %qD applied to template instantiation",
16272                  storage);
16273           extern_p = 0;
16274         }
16275     }
16276
16277   if (CLASSTYPE_TEMPLATE_SPECIALIZATION (t))
16278     {
16279       /* DR 259 [temp.spec].
16280
16281          Both an explicit instantiation and a declaration of an explicit
16282          specialization shall not appear in a program unless the explicit
16283          instantiation follows a declaration of the explicit specialization.
16284
16285          For a given set of template parameters, if an explicit
16286          instantiation of a template appears after a declaration of an
16287          explicit specialization for that template, the explicit
16288          instantiation has no effect.  */
16289       return;
16290     }
16291   else if (CLASSTYPE_EXPLICIT_INSTANTIATION (t))
16292     {
16293       /* [temp.spec]
16294
16295          No program shall explicitly instantiate any template more
16296          than once.
16297
16298          If PREVIOUS_INSTANTIATION_EXTERN_P, then the first explicit
16299          instantiation was `extern'.  If EXTERN_P then the second is.
16300          These cases are OK.  */
16301       previous_instantiation_extern_p = CLASSTYPE_INTERFACE_ONLY (t);
16302
16303       if (!previous_instantiation_extern_p && !extern_p
16304           && (complain & tf_error))
16305         permerror (input_location, "duplicate explicit instantiation of %q#T", t);
16306
16307       /* If we've already instantiated the template, just return now.  */
16308       if (!CLASSTYPE_INTERFACE_ONLY (t))
16309         return;
16310     }
16311
16312   check_explicit_instantiation_namespace (TYPE_NAME (t));
16313   mark_class_instantiated (t, extern_p);
16314
16315   if (nomem_p)
16316     return;
16317
16318   {
16319     tree tmp;
16320
16321     /* In contrast to implicit instantiation, where only the
16322        declarations, and not the definitions, of members are
16323        instantiated, we have here:
16324
16325          [temp.explicit]
16326
16327          The explicit instantiation of a class template specialization
16328          implies the instantiation of all of its members not
16329          previously explicitly specialized in the translation unit
16330          containing the explicit instantiation.
16331
16332        Of course, we can't instantiate member template classes, since
16333        we don't have any arguments for them.  Note that the standard
16334        is unclear on whether the instantiation of the members are
16335        *explicit* instantiations or not.  However, the most natural
16336        interpretation is that it should be an explicit instantiation.  */
16337
16338     if (! static_p)
16339       for (tmp = TYPE_METHODS (t); tmp; tmp = TREE_CHAIN (tmp))
16340         if (TREE_CODE (tmp) == FUNCTION_DECL
16341             && DECL_TEMPLATE_INSTANTIATION (tmp))
16342           instantiate_class_member (tmp, extern_p);
16343
16344     for (tmp = TYPE_FIELDS (t); tmp; tmp = TREE_CHAIN (tmp))
16345       if (TREE_CODE (tmp) == VAR_DECL && DECL_TEMPLATE_INSTANTIATION (tmp))
16346         instantiate_class_member (tmp, extern_p);
16347
16348     if (CLASSTYPE_NESTED_UTDS (t))
16349       binding_table_foreach (CLASSTYPE_NESTED_UTDS (t),
16350                              bt_instantiate_type_proc, &storage);
16351   }
16352 }
16353
16354 /* Given a function DECL, which is a specialization of TMPL, modify
16355    DECL to be a re-instantiation of TMPL with the same template
16356    arguments.  TMPL should be the template into which tsubst'ing
16357    should occur for DECL, not the most general template.
16358
16359    One reason for doing this is a scenario like this:
16360
16361      template <class T>
16362      void f(const T&, int i);
16363
16364      void g() { f(3, 7); }
16365
16366      template <class T>
16367      void f(const T& t, const int i) { }
16368
16369    Note that when the template is first instantiated, with
16370    instantiate_template, the resulting DECL will have no name for the
16371    first parameter, and the wrong type for the second.  So, when we go
16372    to instantiate the DECL, we regenerate it.  */
16373
16374 static void
16375 regenerate_decl_from_template (tree decl, tree tmpl)
16376 {
16377   /* The arguments used to instantiate DECL, from the most general
16378      template.  */
16379   tree args;
16380   tree code_pattern;
16381
16382   args = DECL_TI_ARGS (decl);
16383   code_pattern = DECL_TEMPLATE_RESULT (tmpl);
16384
16385   /* Make sure that we can see identifiers, and compute access
16386      correctly.  */
16387   push_access_scope (decl);
16388
16389   if (TREE_CODE (decl) == FUNCTION_DECL)
16390     {
16391       tree decl_parm;
16392       tree pattern_parm;
16393       tree specs;
16394       int args_depth;
16395       int parms_depth;
16396
16397       args_depth = TMPL_ARGS_DEPTH (args);
16398       parms_depth = TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (tmpl));
16399       if (args_depth > parms_depth)
16400         args = get_innermost_template_args (args, parms_depth);
16401
16402       specs = tsubst_exception_specification (TREE_TYPE (code_pattern),
16403                                               args, tf_error, NULL_TREE);
16404       if (specs)
16405         TREE_TYPE (decl) = build_exception_variant (TREE_TYPE (decl),
16406                                                     specs);
16407
16408       /* Merge parameter declarations.  */
16409       decl_parm = skip_artificial_parms_for (decl,
16410                                              DECL_ARGUMENTS (decl));
16411       pattern_parm
16412         = skip_artificial_parms_for (code_pattern,
16413                                      DECL_ARGUMENTS (code_pattern));
16414       while (decl_parm && !FUNCTION_PARAMETER_PACK_P (pattern_parm))
16415         {
16416           tree parm_type;
16417           tree attributes;
16418           
16419           if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16420             DECL_NAME (decl_parm) = DECL_NAME (pattern_parm);
16421           parm_type = tsubst (TREE_TYPE (pattern_parm), args, tf_error,
16422                               NULL_TREE);
16423           parm_type = type_decays_to (parm_type);
16424           if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16425             TREE_TYPE (decl_parm) = parm_type;
16426           attributes = DECL_ATTRIBUTES (pattern_parm);
16427           if (DECL_ATTRIBUTES (decl_parm) != attributes)
16428             {
16429               DECL_ATTRIBUTES (decl_parm) = attributes;
16430               cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16431             }
16432           decl_parm = TREE_CHAIN (decl_parm);
16433           pattern_parm = TREE_CHAIN (pattern_parm);
16434         }
16435       /* Merge any parameters that match with the function parameter
16436          pack.  */
16437       if (pattern_parm && FUNCTION_PARAMETER_PACK_P (pattern_parm))
16438         {
16439           int i, len;
16440           tree expanded_types;
16441           /* Expand the TYPE_PACK_EXPANSION that provides the types for
16442              the parameters in this function parameter pack.  */
16443           expanded_types = tsubst_pack_expansion (TREE_TYPE (pattern_parm), 
16444                                                  args, tf_error, NULL_TREE);
16445           len = TREE_VEC_LENGTH (expanded_types);
16446           for (i = 0; i < len; i++)
16447             {
16448               tree parm_type;
16449               tree attributes;
16450           
16451               if (DECL_NAME (decl_parm) != DECL_NAME (pattern_parm))
16452                 /* Rename the parameter to include the index.  */
16453                 DECL_NAME (decl_parm) = 
16454                   make_ith_pack_parameter_name (DECL_NAME (pattern_parm), i);
16455               parm_type = TREE_VEC_ELT (expanded_types, i);
16456               parm_type = type_decays_to (parm_type);
16457               if (!same_type_p (TREE_TYPE (decl_parm), parm_type))
16458                 TREE_TYPE (decl_parm) = parm_type;
16459               attributes = DECL_ATTRIBUTES (pattern_parm);
16460               if (DECL_ATTRIBUTES (decl_parm) != attributes)
16461                 {
16462                   DECL_ATTRIBUTES (decl_parm) = attributes;
16463                   cplus_decl_attributes (&decl_parm, attributes, /*flags=*/0);
16464                 }
16465               decl_parm = TREE_CHAIN (decl_parm);
16466             }
16467         }
16468       /* Merge additional specifiers from the CODE_PATTERN.  */
16469       if (DECL_DECLARED_INLINE_P (code_pattern)
16470           && !DECL_DECLARED_INLINE_P (decl))
16471         DECL_DECLARED_INLINE_P (decl) = 1;
16472     }
16473   else if (TREE_CODE (decl) == VAR_DECL)
16474     {
16475       DECL_INITIAL (decl) =
16476         tsubst_expr (DECL_INITIAL (code_pattern), args,
16477                      tf_error, DECL_TI_TEMPLATE (decl),
16478                      /*integral_constant_expression_p=*/false);
16479       if (VAR_HAD_UNKNOWN_BOUND (decl))
16480         TREE_TYPE (decl) = tsubst (TREE_TYPE (code_pattern), args,
16481                                    tf_error, DECL_TI_TEMPLATE (decl));
16482     }
16483   else
16484     gcc_unreachable ();
16485
16486   pop_access_scope (decl);
16487 }
16488
16489 /* Return the TEMPLATE_DECL into which DECL_TI_ARGS(DECL) should be
16490    substituted to get DECL.  */
16491
16492 tree
16493 template_for_substitution (tree decl)
16494 {
16495   tree tmpl = DECL_TI_TEMPLATE (decl);
16496
16497   /* Set TMPL to the template whose DECL_TEMPLATE_RESULT is the pattern
16498      for the instantiation.  This is not always the most general
16499      template.  Consider, for example:
16500
16501         template <class T>
16502         struct S { template <class U> void f();
16503                    template <> void f<int>(); };
16504
16505      and an instantiation of S<double>::f<int>.  We want TD to be the
16506      specialization S<T>::f<int>, not the more general S<T>::f<U>.  */
16507   while (/* An instantiation cannot have a definition, so we need a
16508             more general template.  */
16509          DECL_TEMPLATE_INSTANTIATION (tmpl)
16510            /* We must also deal with friend templates.  Given:
16511
16512                 template <class T> struct S {
16513                   template <class U> friend void f() {};
16514                 };
16515
16516               S<int>::f<U> say, is not an instantiation of S<T>::f<U>,
16517               so far as the language is concerned, but that's still
16518               where we get the pattern for the instantiation from.  On
16519               other hand, if the definition comes outside the class, say:
16520
16521                 template <class T> struct S {
16522                   template <class U> friend void f();
16523                 };
16524                 template <class U> friend void f() {}
16525
16526               we don't need to look any further.  That's what the check for
16527               DECL_INITIAL is for.  */
16528           || (TREE_CODE (decl) == FUNCTION_DECL
16529               && DECL_FRIEND_PSEUDO_TEMPLATE_INSTANTIATION (tmpl)
16530               && !DECL_INITIAL (DECL_TEMPLATE_RESULT (tmpl))))
16531     {
16532       /* The present template, TD, should not be a definition.  If it
16533          were a definition, we should be using it!  Note that we
16534          cannot restructure the loop to just keep going until we find
16535          a template with a definition, since that might go too far if
16536          a specialization was declared, but not defined.  */
16537       gcc_assert (TREE_CODE (decl) != VAR_DECL
16538                   || DECL_IN_AGGR_P (DECL_TEMPLATE_RESULT (tmpl)));
16539
16540       /* Fetch the more general template.  */
16541       tmpl = DECL_TI_TEMPLATE (tmpl);
16542     }
16543
16544   return tmpl;
16545 }
16546
16547 /* Returns true if we need to instantiate this template instance even if we
16548    know we aren't going to emit it..  */
16549
16550 bool
16551 always_instantiate_p (tree decl)
16552 {
16553   /* We always instantiate inline functions so that we can inline them.  An
16554      explicit instantiation declaration prohibits implicit instantiation of
16555      non-inline functions.  With high levels of optimization, we would
16556      normally inline non-inline functions -- but we're not allowed to do
16557      that for "extern template" functions.  Therefore, we check
16558      DECL_DECLARED_INLINE_P, rather than possibly_inlined_p.  */
16559   return ((TREE_CODE (decl) == FUNCTION_DECL
16560            && DECL_DECLARED_INLINE_P (decl))
16561           /* And we need to instantiate static data members so that
16562              their initializers are available in integral constant
16563              expressions.  */
16564           || (TREE_CODE (decl) == VAR_DECL
16565               && DECL_INITIALIZED_BY_CONSTANT_EXPRESSION_P (decl)));
16566 }
16567
16568 /* Produce the definition of D, a _DECL generated from a template.  If
16569    DEFER_OK is nonzero, then we don't have to actually do the
16570    instantiation now; we just have to do it sometime.  Normally it is
16571    an error if this is an explicit instantiation but D is undefined.
16572    EXPL_INST_CLASS_MEM_P is true iff D is a member of an
16573    explicitly instantiated class template.  */
16574
16575 tree
16576 instantiate_decl (tree d, int defer_ok,
16577                   bool expl_inst_class_mem_p)
16578 {
16579   tree tmpl = DECL_TI_TEMPLATE (d);
16580   tree gen_args;
16581   tree args;
16582   tree td;
16583   tree code_pattern;
16584   tree spec;
16585   tree gen_tmpl;
16586   bool pattern_defined;
16587   int need_push;
16588   location_t saved_loc = input_location;
16589   bool external_p;
16590
16591   /* This function should only be used to instantiate templates for
16592      functions and static member variables.  */
16593   gcc_assert (TREE_CODE (d) == FUNCTION_DECL
16594               || TREE_CODE (d) == VAR_DECL);
16595
16596   /* Variables are never deferred; if instantiation is required, they
16597      are instantiated right away.  That allows for better code in the
16598      case that an expression refers to the value of the variable --
16599      if the variable has a constant value the referring expression can
16600      take advantage of that fact.  */
16601   if (TREE_CODE (d) == VAR_DECL)
16602     defer_ok = 0;
16603
16604   /* Don't instantiate cloned functions.  Instead, instantiate the
16605      functions they cloned.  */
16606   if (TREE_CODE (d) == FUNCTION_DECL && DECL_CLONED_FUNCTION_P (d))
16607     d = DECL_CLONED_FUNCTION (d);
16608
16609   if (DECL_TEMPLATE_INSTANTIATED (d)
16610       || DECL_TEMPLATE_SPECIALIZATION (d))
16611     /* D has already been instantiated or explicitly specialized, so
16612        there's nothing for us to do here.
16613
16614        It might seem reasonable to check whether or not D is an explicit
16615        instantiation, and, if so, stop here.  But when an explicit
16616        instantiation is deferred until the end of the compilation,
16617        DECL_EXPLICIT_INSTANTIATION is set, even though we still need to do
16618        the instantiation.  */
16619     return d;
16620
16621   /* Check to see whether we know that this template will be
16622      instantiated in some other file, as with "extern template"
16623      extension.  */
16624   external_p = (DECL_INTERFACE_KNOWN (d) && DECL_REALLY_EXTERN (d));
16625
16626   /* In general, we do not instantiate such templates.  */
16627   if (external_p && !always_instantiate_p (d))
16628     return d;
16629
16630   gen_tmpl = most_general_template (tmpl);
16631   gen_args = DECL_TI_ARGS (d);
16632
16633   if (tmpl != gen_tmpl)
16634     /* We should already have the extra args.  */
16635     gcc_assert (TMPL_PARMS_DEPTH (DECL_TEMPLATE_PARMS (gen_tmpl))
16636                 == TMPL_ARGS_DEPTH (gen_args));
16637   /* And what's in the hash table should match D.  */
16638   gcc_assert ((spec = retrieve_specialization (gen_tmpl, gen_args, 0)) == d
16639               || spec == NULL_TREE);
16640
16641   /* This needs to happen before any tsubsting.  */
16642   if (! push_tinst_level (d))
16643     return d;
16644
16645   timevar_push (TV_PARSE);
16646
16647   /* Set TD to the template whose DECL_TEMPLATE_RESULT is the pattern
16648      for the instantiation.  */
16649   td = template_for_substitution (d);
16650   code_pattern = DECL_TEMPLATE_RESULT (td);
16651
16652   /* We should never be trying to instantiate a member of a class
16653      template or partial specialization.  */
16654   gcc_assert (d != code_pattern);
16655
16656   if ((DECL_NAMESPACE_SCOPE_P (d) && !DECL_INITIALIZED_IN_CLASS_P (d))
16657       || DECL_TEMPLATE_SPECIALIZATION (td))
16658     /* In the case of a friend template whose definition is provided
16659        outside the class, we may have too many arguments.  Drop the
16660        ones we don't need.  The same is true for specializations.  */
16661     args = get_innermost_template_args
16662       (gen_args, TMPL_PARMS_DEPTH  (DECL_TEMPLATE_PARMS (td)));
16663   else
16664     args = gen_args;
16665
16666   if (TREE_CODE (d) == FUNCTION_DECL)
16667     pattern_defined = (DECL_SAVED_TREE (code_pattern) != NULL_TREE);
16668   else
16669     pattern_defined = ! DECL_IN_AGGR_P (code_pattern);
16670
16671   /* We may be in the middle of deferred access check.  Disable it now.  */
16672   push_deferring_access_checks (dk_no_deferred);
16673
16674   /* Unless an explicit instantiation directive has already determined
16675      the linkage of D, remember that a definition is available for
16676      this entity.  */
16677   if (pattern_defined
16678       && !DECL_INTERFACE_KNOWN (d)
16679       && !DECL_NOT_REALLY_EXTERN (d))
16680     mark_definable (d);
16681
16682   input_location = DECL_SOURCE_LOCATION (d);
16683
16684   /* If D is a member of an explicitly instantiated class template,
16685      and no definition is available, treat it like an implicit
16686      instantiation.  */
16687   if (!pattern_defined && expl_inst_class_mem_p
16688       && DECL_EXPLICIT_INSTANTIATION (d))
16689     {
16690       DECL_NOT_REALLY_EXTERN (d) = 0;
16691       DECL_INTERFACE_KNOWN (d) = 0;
16692       SET_DECL_IMPLICIT_INSTANTIATION (d);
16693     }
16694
16695   /* Recheck the substitutions to obtain any warning messages
16696      about ignoring cv qualifiers.  Don't do this for artificial decls,
16697      as it breaks the context-sensitive substitution for lambda op(). */
16698   if (!defer_ok && !DECL_ARTIFICIAL (d))
16699     {
16700       tree gen = DECL_TEMPLATE_RESULT (gen_tmpl);
16701       tree type = TREE_TYPE (gen);
16702
16703       /* Make sure that we can see identifiers, and compute access
16704          correctly.  D is already the target FUNCTION_DECL with the
16705          right context.  */
16706       push_access_scope (d);
16707
16708       if (TREE_CODE (gen) == FUNCTION_DECL)
16709         {
16710           tsubst (DECL_ARGUMENTS (gen), gen_args, tf_warning_or_error, d);
16711           tsubst_exception_specification (type, gen_args, tf_warning_or_error,
16712                                           d);
16713           /* Don't simply tsubst the function type, as that will give
16714              duplicate warnings about poor parameter qualifications.
16715              The function arguments are the same as the decl_arguments
16716              without the top level cv qualifiers.  */
16717           type = TREE_TYPE (type);
16718         }
16719       tsubst (type, gen_args, tf_warning_or_error, d);
16720
16721       pop_access_scope (d);
16722     }
16723
16724   /* Defer all other templates, unless we have been explicitly
16725      forbidden from doing so.  */
16726   if (/* If there is no definition, we cannot instantiate the
16727          template.  */
16728       ! pattern_defined
16729       /* If it's OK to postpone instantiation, do so.  */
16730       || defer_ok
16731       /* If this is a static data member that will be defined
16732          elsewhere, we don't want to instantiate the entire data
16733          member, but we do want to instantiate the initializer so that
16734          we can substitute that elsewhere.  */
16735       || (external_p && TREE_CODE (d) == VAR_DECL))
16736     {
16737       /* The definition of the static data member is now required so
16738          we must substitute the initializer.  */
16739       if (TREE_CODE (d) == VAR_DECL
16740           && !DECL_INITIAL (d)
16741           && DECL_INITIAL (code_pattern))
16742         {
16743           tree ns;
16744           tree init;
16745
16746           ns = decl_namespace_context (d);
16747           push_nested_namespace (ns);
16748           push_nested_class (DECL_CONTEXT (d));
16749           init = tsubst_expr (DECL_INITIAL (code_pattern),
16750                               args,
16751                               tf_warning_or_error, NULL_TREE,
16752                               /*integral_constant_expression_p=*/false);
16753           cp_finish_decl (d, init, /*init_const_expr_p=*/false,
16754                           /*asmspec_tree=*/NULL_TREE,
16755                           LOOKUP_ONLYCONVERTING);
16756           pop_nested_class ();
16757           pop_nested_namespace (ns);
16758         }
16759
16760       /* We restore the source position here because it's used by
16761          add_pending_template.  */
16762       input_location = saved_loc;
16763
16764       if (at_eof && !pattern_defined
16765           && DECL_EXPLICIT_INSTANTIATION (d)
16766           && DECL_NOT_REALLY_EXTERN (d))
16767         /* [temp.explicit]
16768
16769            The definition of a non-exported function template, a
16770            non-exported member function template, or a non-exported
16771            member function or static data member of a class template
16772            shall be present in every translation unit in which it is
16773            explicitly instantiated.  */
16774         permerror (input_location,  "explicit instantiation of %qD "
16775                    "but no definition available", d);
16776
16777       /* ??? Historically, we have instantiated inline functions, even
16778          when marked as "extern template".  */
16779       if (!(external_p && TREE_CODE (d) == VAR_DECL))
16780         add_pending_template (d);
16781       goto out;
16782     }
16783   /* Tell the repository that D is available in this translation unit
16784      -- and see if it is supposed to be instantiated here.  */
16785   if (TREE_PUBLIC (d) && !DECL_REALLY_EXTERN (d) && !repo_emit_p (d))
16786     {
16787       /* In a PCH file, despite the fact that the repository hasn't
16788          requested instantiation in the PCH it is still possible that
16789          an instantiation will be required in a file that includes the
16790          PCH.  */
16791       if (pch_file)
16792         add_pending_template (d);
16793       /* Instantiate inline functions so that the inliner can do its
16794          job, even though we'll not be emitting a copy of this
16795          function.  */
16796       if (!(TREE_CODE (d) == FUNCTION_DECL && possibly_inlined_p (d)))
16797         goto out;
16798     }
16799
16800   need_push = !cfun || !global_bindings_p ();
16801   if (need_push)
16802     push_to_top_level ();
16803
16804   /* Mark D as instantiated so that recursive calls to
16805      instantiate_decl do not try to instantiate it again.  */
16806   DECL_TEMPLATE_INSTANTIATED (d) = 1;
16807
16808   /* Regenerate the declaration in case the template has been modified
16809      by a subsequent redeclaration.  */
16810   regenerate_decl_from_template (d, td);
16811
16812   /* We already set the file and line above.  Reset them now in case
16813      they changed as a result of calling regenerate_decl_from_template.  */
16814   input_location = DECL_SOURCE_LOCATION (d);
16815
16816   if (TREE_CODE (d) == VAR_DECL)
16817     {
16818       tree init;
16819
16820       /* Clear out DECL_RTL; whatever was there before may not be right
16821          since we've reset the type of the declaration.  */
16822       SET_DECL_RTL (d, NULL_RTX);
16823       DECL_IN_AGGR_P (d) = 0;
16824
16825       /* The initializer is placed in DECL_INITIAL by
16826          regenerate_decl_from_template.  Pull it out so that
16827          cp_finish_decl can process it.  */
16828       init = DECL_INITIAL (d);
16829       DECL_INITIAL (d) = NULL_TREE;
16830       DECL_INITIALIZED_P (d) = 0;
16831
16832       /* Clear DECL_EXTERNAL so that cp_finish_decl will process the
16833          initializer.  That function will defer actual emission until
16834          we have a chance to determine linkage.  */
16835       DECL_EXTERNAL (d) = 0;
16836
16837       /* Enter the scope of D so that access-checking works correctly.  */
16838       push_nested_class (DECL_CONTEXT (d));
16839       cp_finish_decl (d, init, false, NULL_TREE, 0);
16840       pop_nested_class ();
16841     }
16842   else if (TREE_CODE (d) == FUNCTION_DECL)
16843     {
16844       htab_t saved_local_specializations;
16845       tree subst_decl;
16846       tree tmpl_parm;
16847       tree spec_parm;
16848
16849       /* Save away the current list, in case we are instantiating one
16850          template from within the body of another.  */
16851       saved_local_specializations = local_specializations;
16852
16853       /* Set up the list of local specializations.  */
16854       local_specializations = htab_create (37,
16855                                            hash_local_specialization,
16856                                            eq_local_specializations,
16857                                            NULL);
16858
16859       /* Set up context.  */
16860       start_preparsed_function (d, NULL_TREE, SF_PRE_PARSED);
16861
16862       /* Create substitution entries for the parameters.  */
16863       subst_decl = DECL_TEMPLATE_RESULT (template_for_substitution (d));
16864       tmpl_parm = DECL_ARGUMENTS (subst_decl);
16865       spec_parm = DECL_ARGUMENTS (d);
16866       if (DECL_NONSTATIC_MEMBER_FUNCTION_P (d))
16867         {
16868           register_local_specialization (spec_parm, tmpl_parm);
16869           spec_parm = skip_artificial_parms_for (d, spec_parm);
16870           tmpl_parm = skip_artificial_parms_for (subst_decl, tmpl_parm);
16871         }
16872       while (tmpl_parm && !FUNCTION_PARAMETER_PACK_P (tmpl_parm))
16873         {
16874           register_local_specialization (spec_parm, tmpl_parm);
16875           tmpl_parm = TREE_CHAIN (tmpl_parm);
16876           spec_parm = TREE_CHAIN (spec_parm);
16877         }
16878       if (tmpl_parm && FUNCTION_PARAMETER_PACK_P (tmpl_parm))
16879         {
16880           /* Register the (value) argument pack as a specialization of
16881              TMPL_PARM, then move on.  */
16882           tree argpack = make_fnparm_pack (spec_parm);
16883           register_local_specialization (argpack, tmpl_parm);
16884           tmpl_parm = TREE_CHAIN (tmpl_parm);
16885           spec_parm = NULL_TREE;
16886         }
16887       gcc_assert (!spec_parm);
16888
16889       /* Substitute into the body of the function.  */
16890       tsubst_expr (DECL_SAVED_TREE (code_pattern), args,
16891                    tf_warning_or_error, tmpl,
16892                    /*integral_constant_expression_p=*/false);
16893
16894       /* Set the current input_location to the end of the function
16895          so that finish_function knows where we are.  */
16896       input_location = DECL_STRUCT_FUNCTION (code_pattern)->function_end_locus;
16897
16898       /* We don't need the local specializations any more.  */
16899       htab_delete (local_specializations);
16900       local_specializations = saved_local_specializations;
16901
16902       /* Finish the function.  */
16903       d = finish_function (0);
16904       expand_or_defer_fn (d);
16905     }
16906
16907   /* We're not deferring instantiation any more.  */
16908   TI_PENDING_TEMPLATE_FLAG (DECL_TEMPLATE_INFO (d)) = 0;
16909
16910   if (need_push)
16911     pop_from_top_level ();
16912
16913 out:
16914   input_location = saved_loc;
16915   pop_deferring_access_checks ();
16916   pop_tinst_level ();
16917
16918   timevar_pop (TV_PARSE);
16919
16920   return d;
16921 }
16922
16923 /* Run through the list of templates that we wish we could
16924    instantiate, and instantiate any we can.  RETRIES is the
16925    number of times we retry pending template instantiation.  */
16926
16927 void
16928 instantiate_pending_templates (int retries)
16929 {
16930   int reconsider;
16931   location_t saved_loc = input_location;
16932
16933   /* Instantiating templates may trigger vtable generation.  This in turn
16934      may require further template instantiations.  We place a limit here
16935      to avoid infinite loop.  */
16936   if (pending_templates && retries >= max_tinst_depth)
16937     {
16938       tree decl = pending_templates->tinst->decl;
16939
16940       error ("template instantiation depth exceeds maximum of %d"
16941              " instantiating %q+D, possibly from virtual table generation"
16942              " (use -ftemplate-depth= to increase the maximum)",
16943              max_tinst_depth, decl);
16944       if (TREE_CODE (decl) == FUNCTION_DECL)
16945         /* Pretend that we defined it.  */
16946         DECL_INITIAL (decl) = error_mark_node;
16947       return;
16948     }
16949
16950   do
16951     {
16952       struct pending_template **t = &pending_templates;
16953       struct pending_template *last = NULL;
16954       reconsider = 0;
16955       while (*t)
16956         {
16957           tree instantiation = reopen_tinst_level ((*t)->tinst);
16958           bool complete = false;
16959
16960           if (TYPE_P (instantiation))
16961             {
16962               tree fn;
16963
16964               if (!COMPLETE_TYPE_P (instantiation))
16965                 {
16966                   instantiate_class_template (instantiation);
16967                   if (CLASSTYPE_TEMPLATE_INSTANTIATION (instantiation))
16968                     for (fn = TYPE_METHODS (instantiation);
16969                          fn;
16970                          fn = TREE_CHAIN (fn))
16971                       if (! DECL_ARTIFICIAL (fn))
16972                         instantiate_decl (fn,
16973                                           /*defer_ok=*/0,
16974                                           /*expl_inst_class_mem_p=*/false);
16975                   if (COMPLETE_TYPE_P (instantiation))
16976                     reconsider = 1;
16977                 }
16978
16979               complete = COMPLETE_TYPE_P (instantiation);
16980             }
16981           else
16982             {
16983               if (!DECL_TEMPLATE_SPECIALIZATION (instantiation)
16984                   && !DECL_TEMPLATE_INSTANTIATED (instantiation))
16985                 {
16986                   instantiation
16987                     = instantiate_decl (instantiation,
16988                                         /*defer_ok=*/0,
16989                                         /*expl_inst_class_mem_p=*/false);
16990                   if (DECL_TEMPLATE_INSTANTIATED (instantiation))
16991                     reconsider = 1;
16992                 }
16993
16994               complete = (DECL_TEMPLATE_SPECIALIZATION (instantiation)
16995                           || DECL_TEMPLATE_INSTANTIATED (instantiation));
16996             }
16997
16998           if (complete)
16999             /* If INSTANTIATION has been instantiated, then we don't
17000                need to consider it again in the future.  */
17001             *t = (*t)->next;
17002           else
17003             {
17004               last = *t;
17005               t = &(*t)->next;
17006             }
17007           tinst_depth = 0;
17008           current_tinst_level = NULL;
17009         }
17010       last_pending_template = last;
17011     }
17012   while (reconsider);
17013
17014   input_location = saved_loc;
17015 }
17016
17017 /* Substitute ARGVEC into T, which is a list of initializers for
17018    either base class or a non-static data member.  The TREE_PURPOSEs
17019    are DECLs, and the TREE_VALUEs are the initializer values.  Used by
17020    instantiate_decl.  */
17021
17022 static tree
17023 tsubst_initializer_list (tree t, tree argvec)
17024 {
17025   tree inits = NULL_TREE;
17026
17027   for (; t; t = TREE_CHAIN (t))
17028     {
17029       tree decl;
17030       tree init;
17031       tree expanded_bases = NULL_TREE;
17032       tree expanded_arguments = NULL_TREE;
17033       int i, len = 1;
17034
17035       if (TREE_CODE (TREE_PURPOSE (t)) == TYPE_PACK_EXPANSION)
17036         {
17037           tree expr;
17038           tree arg;
17039
17040           /* Expand the base class expansion type into separate base
17041              classes.  */
17042           expanded_bases = tsubst_pack_expansion (TREE_PURPOSE (t), argvec,
17043                                                  tf_warning_or_error,
17044                                                  NULL_TREE);
17045           if (expanded_bases == error_mark_node)
17046             continue;
17047           
17048           /* We'll be building separate TREE_LISTs of arguments for
17049              each base.  */
17050           len = TREE_VEC_LENGTH (expanded_bases);
17051           expanded_arguments = make_tree_vec (len);
17052           for (i = 0; i < len; i++)
17053             TREE_VEC_ELT (expanded_arguments, i) = NULL_TREE;
17054
17055           /* Build a dummy EXPR_PACK_EXPANSION that will be used to
17056              expand each argument in the TREE_VALUE of t.  */
17057           expr = make_node (EXPR_PACK_EXPANSION);
17058           PACK_EXPANSION_PARAMETER_PACKS (expr) =
17059             PACK_EXPANSION_PARAMETER_PACKS (TREE_PURPOSE (t));
17060
17061           if (TREE_VALUE (t) == void_type_node)
17062             /* VOID_TYPE_NODE is used to indicate
17063                value-initialization.  */
17064             {
17065               for (i = 0; i < len; i++)
17066                 TREE_VEC_ELT (expanded_arguments, i) = void_type_node;
17067             }
17068           else
17069             {
17070               /* Substitute parameter packs into each argument in the
17071                  TREE_LIST.  */
17072               in_base_initializer = 1;
17073               for (arg = TREE_VALUE (t); arg; arg = TREE_CHAIN (arg))
17074                 {
17075                   tree expanded_exprs;
17076
17077                   /* Expand the argument.  */
17078                   SET_PACK_EXPANSION_PATTERN (expr, TREE_VALUE (arg));
17079                   expanded_exprs 
17080                     = tsubst_pack_expansion (expr, argvec,
17081                                              tf_warning_or_error,
17082                                              NULL_TREE);
17083                   if (expanded_exprs == error_mark_node)
17084                     continue;
17085
17086                   /* Prepend each of the expanded expressions to the
17087                      corresponding TREE_LIST in EXPANDED_ARGUMENTS.  */
17088                   for (i = 0; i < len; i++)
17089                     {
17090                       TREE_VEC_ELT (expanded_arguments, i) = 
17091                         tree_cons (NULL_TREE, 
17092                                    TREE_VEC_ELT (expanded_exprs, i),
17093                                    TREE_VEC_ELT (expanded_arguments, i));
17094                     }
17095                 }
17096               in_base_initializer = 0;
17097
17098               /* Reverse all of the TREE_LISTs in EXPANDED_ARGUMENTS,
17099                  since we built them backwards.  */
17100               for (i = 0; i < len; i++)
17101                 {
17102                   TREE_VEC_ELT (expanded_arguments, i) = 
17103                     nreverse (TREE_VEC_ELT (expanded_arguments, i));
17104                 }
17105             }
17106         }
17107
17108       for (i = 0; i < len; ++i)
17109         {
17110           if (expanded_bases)
17111             {
17112               decl = TREE_VEC_ELT (expanded_bases, i);
17113               decl = expand_member_init (decl);
17114               init = TREE_VEC_ELT (expanded_arguments, i);
17115             }
17116           else
17117             {
17118               decl = tsubst_copy (TREE_PURPOSE (t), argvec, 
17119                                   tf_warning_or_error, NULL_TREE);
17120
17121               decl = expand_member_init (decl);
17122               if (decl && !DECL_P (decl))
17123                 in_base_initializer = 1;
17124
17125               init = tsubst_expr (TREE_VALUE (t), argvec, 
17126                                   tf_warning_or_error, NULL_TREE,
17127                                   /*integral_constant_expression_p=*/false);
17128               in_base_initializer = 0;
17129             }
17130
17131           if (decl)
17132             {
17133               init = build_tree_list (decl, init);
17134               TREE_CHAIN (init) = inits;
17135               inits = init;
17136             }
17137         }
17138     }
17139   return inits;
17140 }
17141
17142 /* Set CURRENT_ACCESS_SPECIFIER based on the protection of DECL.  */
17143
17144 static void
17145 set_current_access_from_decl (tree decl)
17146 {
17147   if (TREE_PRIVATE (decl))
17148     current_access_specifier = access_private_node;
17149   else if (TREE_PROTECTED (decl))
17150     current_access_specifier = access_protected_node;
17151   else
17152     current_access_specifier = access_public_node;
17153 }
17154
17155 /* Instantiate an enumerated type.  TAG is the template type, NEWTAG
17156    is the instantiation (which should have been created with
17157    start_enum) and ARGS are the template arguments to use.  */
17158
17159 static void
17160 tsubst_enum (tree tag, tree newtag, tree args)
17161 {
17162   tree e;
17163
17164   for (e = TYPE_VALUES (tag); e; e = TREE_CHAIN (e))
17165     {
17166       tree value;
17167       tree decl;
17168
17169       decl = TREE_VALUE (e);
17170       /* Note that in a template enum, the TREE_VALUE is the
17171          CONST_DECL, not the corresponding INTEGER_CST.  */
17172       value = tsubst_expr (DECL_INITIAL (decl),
17173                            args, tf_warning_or_error, NULL_TREE,
17174                            /*integral_constant_expression_p=*/true);
17175
17176       /* Give this enumeration constant the correct access.  */
17177       set_current_access_from_decl (decl);
17178
17179       /* Actually build the enumerator itself.  */
17180       build_enumerator (DECL_NAME (decl), value, newtag);
17181     }
17182
17183   finish_enum (newtag);
17184   DECL_SOURCE_LOCATION (TYPE_NAME (newtag))
17185     = DECL_SOURCE_LOCATION (TYPE_NAME (tag));
17186 }
17187
17188 /* DECL is a FUNCTION_DECL that is a template specialization.  Return
17189    its type -- but without substituting the innermost set of template
17190    arguments.  So, innermost set of template parameters will appear in
17191    the type.  */
17192
17193 tree
17194 get_mostly_instantiated_function_type (tree decl)
17195 {
17196   tree fn_type;
17197   tree tmpl;
17198   tree targs;
17199   tree tparms;
17200   int parm_depth;
17201
17202   tmpl = most_general_template (DECL_TI_TEMPLATE (decl));
17203   targs = DECL_TI_ARGS (decl);
17204   tparms = DECL_TEMPLATE_PARMS (tmpl);
17205   parm_depth = TMPL_PARMS_DEPTH (tparms);
17206
17207   /* There should be as many levels of arguments as there are levels
17208      of parameters.  */
17209   gcc_assert (parm_depth == TMPL_ARGS_DEPTH (targs));
17210
17211   fn_type = TREE_TYPE (tmpl);
17212
17213   if (parm_depth == 1)
17214     /* No substitution is necessary.  */
17215     ;
17216   else
17217     {
17218       int i, save_access_control;
17219       tree partial_args;
17220
17221       /* Replace the innermost level of the TARGS with NULL_TREEs to
17222          let tsubst know not to substitute for those parameters.  */
17223       partial_args = make_tree_vec (TREE_VEC_LENGTH (targs));
17224       for (i = 1; i < TMPL_ARGS_DEPTH (targs); ++i)
17225         SET_TMPL_ARGS_LEVEL (partial_args, i,
17226                              TMPL_ARGS_LEVEL (targs, i));
17227       SET_TMPL_ARGS_LEVEL (partial_args,
17228                            TMPL_ARGS_DEPTH (targs),
17229                            make_tree_vec (DECL_NTPARMS (tmpl)));
17230
17231       /* Disable access control as this function is used only during
17232          name-mangling.  */
17233       save_access_control = flag_access_control;
17234       flag_access_control = 0;
17235
17236       ++processing_template_decl;
17237       /* Now, do the (partial) substitution to figure out the
17238          appropriate function type.  */
17239       fn_type = tsubst (fn_type, partial_args, tf_error, NULL_TREE);
17240       --processing_template_decl;
17241
17242       /* Substitute into the template parameters to obtain the real
17243          innermost set of parameters.  This step is important if the
17244          innermost set of template parameters contains value
17245          parameters whose types depend on outer template parameters.  */
17246       TREE_VEC_LENGTH (partial_args)--;
17247       tparms = tsubst_template_parms (tparms, partial_args, tf_error);
17248
17249       flag_access_control = save_access_control;
17250     }
17251
17252   return fn_type;
17253 }
17254
17255 /* Return truthvalue if we're processing a template different from
17256    the last one involved in diagnostics.  */
17257 int
17258 problematic_instantiation_changed (void)
17259 {
17260   return last_template_error_tick != tinst_level_tick;
17261 }
17262
17263 /* Remember current template involved in diagnostics.  */
17264 void
17265 record_last_problematic_instantiation (void)
17266 {
17267   last_template_error_tick = tinst_level_tick;
17268 }
17269
17270 struct tinst_level *
17271 current_instantiation (void)
17272 {
17273   return current_tinst_level;
17274 }
17275
17276 /* [temp.param] Check that template non-type parm TYPE is of an allowable
17277    type. Return zero for ok, nonzero for disallowed. Issue error and
17278    warning messages under control of COMPLAIN.  */
17279
17280 static int
17281 invalid_nontype_parm_type_p (tree type, tsubst_flags_t complain)
17282 {
17283   if (INTEGRAL_OR_ENUMERATION_TYPE_P (type))
17284     return 0;
17285   else if (POINTER_TYPE_P (type))
17286     return 0;
17287   else if (TYPE_PTR_TO_MEMBER_P (type))
17288     return 0;
17289   else if (TREE_CODE (type) == TEMPLATE_TYPE_PARM)
17290     return 0;
17291   else if (TREE_CODE (type) == TYPENAME_TYPE)
17292     return 0;
17293
17294   if (complain & tf_error)
17295     error ("%q#T is not a valid type for a template constant parameter", type);
17296   return 1;
17297 }
17298
17299 /* Returns TRUE if TYPE is dependent, in the sense of [temp.dep.type].
17300    Assumes that TYPE really is a type, and not the ERROR_MARK_NODE.*/
17301
17302 static bool
17303 dependent_type_p_r (tree type)
17304 {
17305   tree scope;
17306
17307   /* [temp.dep.type]
17308
17309      A type is dependent if it is:
17310
17311      -- a template parameter. Template template parameters are types
17312         for us (since TYPE_P holds true for them) so we handle
17313         them here.  */
17314   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
17315       || TREE_CODE (type) == TEMPLATE_TEMPLATE_PARM)
17316     return true;
17317   /* -- a qualified-id with a nested-name-specifier which contains a
17318         class-name that names a dependent type or whose unqualified-id
17319         names a dependent type.  */
17320   if (TREE_CODE (type) == TYPENAME_TYPE)
17321     return true;
17322   /* -- a cv-qualified type where the cv-unqualified type is
17323         dependent.  */
17324   type = TYPE_MAIN_VARIANT (type);
17325   /* -- a compound type constructed from any dependent type.  */
17326   if (TYPE_PTR_TO_MEMBER_P (type))
17327     return (dependent_type_p (TYPE_PTRMEM_CLASS_TYPE (type))
17328             || dependent_type_p (TYPE_PTRMEM_POINTED_TO_TYPE
17329                                            (type)));
17330   else if (TREE_CODE (type) == POINTER_TYPE
17331            || TREE_CODE (type) == REFERENCE_TYPE)
17332     return dependent_type_p (TREE_TYPE (type));
17333   else if (TREE_CODE (type) == FUNCTION_TYPE
17334            || TREE_CODE (type) == METHOD_TYPE)
17335     {
17336       tree arg_type;
17337
17338       if (dependent_type_p (TREE_TYPE (type)))
17339         return true;
17340       for (arg_type = TYPE_ARG_TYPES (type);
17341            arg_type;
17342            arg_type = TREE_CHAIN (arg_type))
17343         if (dependent_type_p (TREE_VALUE (arg_type)))
17344           return true;
17345       return false;
17346     }
17347   /* -- an array type constructed from any dependent type or whose
17348         size is specified by a constant expression that is
17349         value-dependent.  */
17350   if (TREE_CODE (type) == ARRAY_TYPE)
17351     {
17352       if (TYPE_DOMAIN (type)
17353           && dependent_type_p (TYPE_DOMAIN (type)))
17354         return true;
17355       return dependent_type_p (TREE_TYPE (type));
17356     }
17357   else if (TREE_CODE (type) == INTEGER_TYPE
17358            && !TREE_CONSTANT (TYPE_MAX_VALUE (type)))
17359     {
17360       /* If this is the TYPE_DOMAIN of an array type, consider it
17361          dependent.  We already checked for value-dependence in
17362          compute_array_index_type.  */
17363       return type_dependent_expression_p (TYPE_MAX_VALUE (type));
17364     }
17365
17366   /* -- a template-id in which either the template name is a template
17367      parameter ...  */
17368   if (TREE_CODE (type) == BOUND_TEMPLATE_TEMPLATE_PARM)
17369     return true;
17370   /* ... or any of the template arguments is a dependent type or
17371         an expression that is type-dependent or value-dependent.  */
17372   else if (CLASS_TYPE_P (type) && CLASSTYPE_TEMPLATE_INFO (type)
17373            && (any_dependent_template_arguments_p
17374                (INNERMOST_TEMPLATE_ARGS (CLASSTYPE_TI_ARGS (type)))))
17375     return true;
17376
17377   /* All TYPEOF_TYPEs and DECLTYPE_TYPEs are dependent; if the
17378      argument of the `typeof' expression is not type-dependent, then
17379      it should already been have resolved.  */
17380   if (TREE_CODE (type) == TYPEOF_TYPE
17381       || TREE_CODE (type) == DECLTYPE_TYPE)
17382     return true;
17383
17384   /* A template argument pack is dependent if any of its packed
17385      arguments are.  */
17386   if (TREE_CODE (type) == TYPE_ARGUMENT_PACK)
17387     {
17388       tree args = ARGUMENT_PACK_ARGS (type);
17389       int i, len = TREE_VEC_LENGTH (args);
17390       for (i = 0; i < len; ++i)
17391         if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
17392           return true;
17393     }
17394
17395   /* All TYPE_PACK_EXPANSIONs are dependent, because parameter packs must
17396      be template parameters.  */
17397   if (TREE_CODE (type) == TYPE_PACK_EXPANSION)
17398     return true;
17399
17400   /* The standard does not specifically mention types that are local
17401      to template functions or local classes, but they should be
17402      considered dependent too.  For example:
17403
17404        template <int I> void f() {
17405          enum E { a = I };
17406          S<sizeof (E)> s;
17407        }
17408
17409      The size of `E' cannot be known until the value of `I' has been
17410      determined.  Therefore, `E' must be considered dependent.  */
17411   scope = TYPE_CONTEXT (type);
17412   if (scope && TYPE_P (scope))
17413     return dependent_type_p (scope);
17414   else if (scope && TREE_CODE (scope) == FUNCTION_DECL)
17415     return type_dependent_expression_p (scope);
17416
17417   /* Other types are non-dependent.  */
17418   return false;
17419 }
17420
17421 /* Returns TRUE if TYPE is dependent, in the sense of
17422    [temp.dep.type].  */
17423
17424 bool
17425 dependent_type_p (tree type)
17426 {
17427   /* If there are no template parameters in scope, then there can't be
17428      any dependent types.  */
17429   if (!processing_template_decl)
17430     {
17431       /* If we are not processing a template, then nobody should be
17432          providing us with a dependent type.  */
17433       gcc_assert (type);
17434       gcc_assert (TREE_CODE (type) != TEMPLATE_TYPE_PARM || is_auto (type));
17435       return false;
17436     }
17437
17438   /* If the type is NULL, we have not computed a type for the entity
17439      in question; in that case, the type is dependent.  */
17440   if (!type)
17441     return true;
17442
17443   /* Erroneous types can be considered non-dependent.  */
17444   if (type == error_mark_node)
17445     return false;
17446
17447   /* If we have not already computed the appropriate value for TYPE,
17448      do so now.  */
17449   if (!TYPE_DEPENDENT_P_VALID (type))
17450     {
17451       TYPE_DEPENDENT_P (type) = dependent_type_p_r (type);
17452       TYPE_DEPENDENT_P_VALID (type) = 1;
17453     }
17454
17455   return TYPE_DEPENDENT_P (type);
17456 }
17457
17458 /* Returns TRUE if SCOPE is a dependent scope, in which we can't do any
17459    lookup.  In other words, a dependent type that is not the current
17460    instantiation.  */
17461
17462 bool
17463 dependent_scope_p (tree scope)
17464 {
17465   return (scope && TYPE_P (scope) && dependent_type_p (scope)
17466           && !currently_open_class (scope));
17467 }
17468
17469 /* Returns TRUE if EXPRESSION is dependent, according to CRITERION.  */
17470
17471 static bool
17472 dependent_scope_ref_p (tree expression, bool criterion (tree))
17473 {
17474   tree scope;
17475   tree name;
17476
17477   gcc_assert (TREE_CODE (expression) == SCOPE_REF);
17478
17479   if (!TYPE_P (TREE_OPERAND (expression, 0)))
17480     return true;
17481
17482   scope = TREE_OPERAND (expression, 0);
17483   name = TREE_OPERAND (expression, 1);
17484
17485   /* [temp.dep.expr]
17486
17487      An id-expression is type-dependent if it contains a
17488      nested-name-specifier that contains a class-name that names a
17489      dependent type.  */
17490   /* The suggested resolution to Core Issue 224 implies that if the
17491      qualifying type is the current class, then we must peek
17492      inside it.  */
17493   if (DECL_P (name)
17494       && currently_open_class (scope)
17495       && !criterion (name))
17496     return false;
17497   if (dependent_type_p (scope))
17498     return true;
17499
17500   return false;
17501 }
17502
17503 /* Returns TRUE if the EXPRESSION is value-dependent, in the sense of
17504    [temp.dep.constexpr].  EXPRESSION is already known to be a constant
17505    expression.  */
17506
17507 bool
17508 value_dependent_expression_p (tree expression)
17509 {
17510   if (!processing_template_decl)
17511     return false;
17512
17513   /* A name declared with a dependent type.  */
17514   if (DECL_P (expression) && type_dependent_expression_p (expression))
17515     return true;
17516
17517   switch (TREE_CODE (expression))
17518     {
17519     case IDENTIFIER_NODE:
17520       /* A name that has not been looked up -- must be dependent.  */
17521       return true;
17522
17523     case TEMPLATE_PARM_INDEX:
17524       /* A non-type template parm.  */
17525       return true;
17526
17527     case CONST_DECL:
17528       /* A non-type template parm.  */
17529       if (DECL_TEMPLATE_PARM_P (expression))
17530         return true;
17531       return value_dependent_expression_p (DECL_INITIAL (expression));
17532
17533     case VAR_DECL:
17534        /* A constant with integral or enumeration type and is initialized
17535           with an expression that is value-dependent.  */
17536       if (DECL_INITIAL (expression)
17537           && INTEGRAL_OR_ENUMERATION_TYPE_P (TREE_TYPE (expression))
17538           && value_dependent_expression_p (DECL_INITIAL (expression)))
17539         return true;
17540       return false;
17541
17542     case DYNAMIC_CAST_EXPR:
17543     case STATIC_CAST_EXPR:
17544     case CONST_CAST_EXPR:
17545     case REINTERPRET_CAST_EXPR:
17546     case CAST_EXPR:
17547       /* These expressions are value-dependent if the type to which
17548          the cast occurs is dependent or the expression being casted
17549          is value-dependent.  */
17550       {
17551         tree type = TREE_TYPE (expression);
17552
17553         if (dependent_type_p (type))
17554           return true;
17555
17556         /* A functional cast has a list of operands.  */
17557         expression = TREE_OPERAND (expression, 0);
17558         if (!expression)
17559           {
17560             /* If there are no operands, it must be an expression such
17561                as "int()". This should not happen for aggregate types
17562                because it would form non-constant expressions.  */
17563             gcc_assert (INTEGRAL_OR_ENUMERATION_TYPE_P (type));
17564
17565             return false;
17566           }
17567
17568         if (TREE_CODE (expression) == TREE_LIST)
17569           return any_value_dependent_elements_p (expression);
17570
17571         return value_dependent_expression_p (expression);
17572       }
17573
17574     case SIZEOF_EXPR:
17575     case ALIGNOF_EXPR:
17576       /* A `sizeof' expression is value-dependent if the operand is
17577          type-dependent or is a pack expansion.  */
17578       expression = TREE_OPERAND (expression, 0);
17579       if (PACK_EXPANSION_P (expression))
17580         return true;
17581       else if (TYPE_P (expression))
17582         return dependent_type_p (expression);
17583       return type_dependent_expression_p (expression);
17584
17585     case SCOPE_REF:
17586       return dependent_scope_ref_p (expression, value_dependent_expression_p);
17587
17588     case COMPONENT_REF:
17589       return (value_dependent_expression_p (TREE_OPERAND (expression, 0))
17590               || value_dependent_expression_p (TREE_OPERAND (expression, 1)));
17591
17592     case CALL_EXPR:
17593       /* A CALL_EXPR may appear in a constant expression if it is a
17594          call to a builtin function, e.g., __builtin_constant_p.  All
17595          such calls are value-dependent.  */
17596       return true;
17597
17598     case NONTYPE_ARGUMENT_PACK:
17599       /* A NONTYPE_ARGUMENT_PACK is value-dependent if any packed argument
17600          is value-dependent.  */
17601       {
17602         tree values = ARGUMENT_PACK_ARGS (expression);
17603         int i, len = TREE_VEC_LENGTH (values);
17604         
17605         for (i = 0; i < len; ++i)
17606           if (value_dependent_expression_p (TREE_VEC_ELT (values, i)))
17607             return true;
17608         
17609         return false;
17610       }
17611
17612     case TRAIT_EXPR:
17613       {
17614         tree type2 = TRAIT_EXPR_TYPE2 (expression);
17615         return (dependent_type_p (TRAIT_EXPR_TYPE1 (expression))
17616                 || (type2 ? dependent_type_p (type2) : false));
17617       }
17618
17619     case MODOP_EXPR:
17620       return ((value_dependent_expression_p (TREE_OPERAND (expression, 0)))
17621               || (value_dependent_expression_p (TREE_OPERAND (expression, 2))));
17622
17623     default:
17624       /* A constant expression is value-dependent if any subexpression is
17625          value-dependent.  */
17626       switch (TREE_CODE_CLASS (TREE_CODE (expression)))
17627         {
17628         case tcc_reference:
17629         case tcc_unary:
17630           return (value_dependent_expression_p
17631                   (TREE_OPERAND (expression, 0)));
17632
17633         case tcc_comparison:
17634         case tcc_binary:
17635           return ((value_dependent_expression_p
17636                    (TREE_OPERAND (expression, 0)))
17637                   || (value_dependent_expression_p
17638                       (TREE_OPERAND (expression, 1))));
17639
17640         case tcc_expression:
17641         case tcc_vl_exp:
17642           {
17643             int i;
17644             for (i = 0; i < TREE_OPERAND_LENGTH (expression); ++i)
17645               /* In some cases, some of the operands may be missing.
17646                  (For example, in the case of PREDECREMENT_EXPR, the
17647                  amount to increment by may be missing.)  That doesn't
17648                  make the expression dependent.  */
17649               if (TREE_OPERAND (expression, i)
17650                   && (value_dependent_expression_p
17651                       (TREE_OPERAND (expression, i))))
17652                 return true;
17653             return false;
17654           }
17655
17656         default:
17657           break;
17658         }
17659     }
17660
17661   /* The expression is not value-dependent.  */
17662   return false;
17663 }
17664
17665 /* Returns TRUE if the EXPRESSION is type-dependent, in the sense of
17666    [temp.dep.expr].  */
17667
17668 bool
17669 type_dependent_expression_p (tree expression)
17670 {
17671   if (!processing_template_decl)
17672     return false;
17673
17674   if (expression == error_mark_node)
17675     return false;
17676
17677   /* An unresolved name is always dependent.  */
17678   if (TREE_CODE (expression) == IDENTIFIER_NODE
17679       || TREE_CODE (expression) == USING_DECL)
17680     return true;
17681
17682   /* Some expression forms are never type-dependent.  */
17683   if (TREE_CODE (expression) == PSEUDO_DTOR_EXPR
17684       || TREE_CODE (expression) == SIZEOF_EXPR
17685       || TREE_CODE (expression) == ALIGNOF_EXPR
17686       || TREE_CODE (expression) == TRAIT_EXPR
17687       || TREE_CODE (expression) == TYPEID_EXPR
17688       || TREE_CODE (expression) == DELETE_EXPR
17689       || TREE_CODE (expression) == VEC_DELETE_EXPR
17690       || TREE_CODE (expression) == THROW_EXPR)
17691     return false;
17692
17693   /* The types of these expressions depends only on the type to which
17694      the cast occurs.  */
17695   if (TREE_CODE (expression) == DYNAMIC_CAST_EXPR
17696       || TREE_CODE (expression) == STATIC_CAST_EXPR
17697       || TREE_CODE (expression) == CONST_CAST_EXPR
17698       || TREE_CODE (expression) == REINTERPRET_CAST_EXPR
17699       || TREE_CODE (expression) == CAST_EXPR)
17700     return dependent_type_p (TREE_TYPE (expression));
17701
17702   /* The types of these expressions depends only on the type created
17703      by the expression.  */
17704   if (TREE_CODE (expression) == NEW_EXPR
17705       || TREE_CODE (expression) == VEC_NEW_EXPR)
17706     {
17707       /* For NEW_EXPR tree nodes created inside a template, either
17708          the object type itself or a TREE_LIST may appear as the
17709          operand 1.  */
17710       tree type = TREE_OPERAND (expression, 1);
17711       if (TREE_CODE (type) == TREE_LIST)
17712         /* This is an array type.  We need to check array dimensions
17713            as well.  */
17714         return dependent_type_p (TREE_VALUE (TREE_PURPOSE (type)))
17715                || value_dependent_expression_p
17716                     (TREE_OPERAND (TREE_VALUE (type), 1));
17717       else
17718         return dependent_type_p (type);
17719     }
17720
17721   if (TREE_CODE (expression) == SCOPE_REF
17722       && dependent_scope_ref_p (expression,
17723                                 type_dependent_expression_p))
17724     return true;
17725
17726   if (TREE_CODE (expression) == FUNCTION_DECL
17727       && DECL_LANG_SPECIFIC (expression)
17728       && DECL_TEMPLATE_INFO (expression)
17729       && (any_dependent_template_arguments_p
17730           (INNERMOST_TEMPLATE_ARGS (DECL_TI_ARGS (expression)))))
17731     return true;
17732
17733   if (TREE_CODE (expression) == TEMPLATE_DECL
17734       && !DECL_TEMPLATE_TEMPLATE_PARM_P (expression))
17735     return false;
17736
17737   if (TREE_CODE (expression) == STMT_EXPR)
17738     expression = stmt_expr_value_expr (expression);
17739
17740   if (BRACE_ENCLOSED_INITIALIZER_P (expression))
17741     {
17742       tree elt;
17743       unsigned i;
17744
17745       FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (expression), i, elt)
17746         {
17747           if (type_dependent_expression_p (elt))
17748             return true;
17749         }
17750       return false;
17751     }
17752
17753   /* A static data member of the current instantiation with incomplete
17754      array type is type-dependent, as the definition and specializations
17755      can have different bounds.  */
17756   if (TREE_CODE (expression) == VAR_DECL
17757       && DECL_CLASS_SCOPE_P (expression)
17758       && dependent_type_p (DECL_CONTEXT (expression))
17759       && VAR_HAD_UNKNOWN_BOUND (expression))
17760     return true;
17761
17762   if (TREE_TYPE (expression) == unknown_type_node)
17763     {
17764       if (TREE_CODE (expression) == ADDR_EXPR)
17765         return type_dependent_expression_p (TREE_OPERAND (expression, 0));
17766       if (TREE_CODE (expression) == COMPONENT_REF
17767           || TREE_CODE (expression) == OFFSET_REF)
17768         {
17769           if (type_dependent_expression_p (TREE_OPERAND (expression, 0)))
17770             return true;
17771           expression = TREE_OPERAND (expression, 1);
17772           if (TREE_CODE (expression) == IDENTIFIER_NODE)
17773             return false;
17774         }
17775       /* SCOPE_REF with non-null TREE_TYPE is always non-dependent.  */
17776       if (TREE_CODE (expression) == SCOPE_REF)
17777         return false;
17778
17779       if (TREE_CODE (expression) == BASELINK)
17780         expression = BASELINK_FUNCTIONS (expression);
17781
17782       if (TREE_CODE (expression) == TEMPLATE_ID_EXPR)
17783         {
17784           if (any_dependent_template_arguments_p
17785               (TREE_OPERAND (expression, 1)))
17786             return true;
17787           expression = TREE_OPERAND (expression, 0);
17788         }
17789       gcc_assert (TREE_CODE (expression) == OVERLOAD
17790                   || TREE_CODE (expression) == FUNCTION_DECL);
17791
17792       while (expression)
17793         {
17794           if (type_dependent_expression_p (OVL_CURRENT (expression)))
17795             return true;
17796           expression = OVL_NEXT (expression);
17797         }
17798       return false;
17799     }
17800
17801   gcc_assert (TREE_CODE (expression) != TYPE_DECL);
17802
17803   return (dependent_type_p (TREE_TYPE (expression)));
17804 }
17805
17806 /* Like type_dependent_expression_p, but it also works while not processing
17807    a template definition, i.e. during substitution or mangling.  */
17808
17809 bool
17810 type_dependent_expression_p_push (tree expr)
17811 {
17812   bool b;
17813   ++processing_template_decl;
17814   b = type_dependent_expression_p (expr);
17815   --processing_template_decl;
17816   return b;
17817 }
17818
17819 /* Returns TRUE if ARGS contains a type-dependent expression.  */
17820
17821 bool
17822 any_type_dependent_arguments_p (const VEC(tree,gc) *args)
17823 {
17824   unsigned int i;
17825   tree arg;
17826
17827   for (i = 0; VEC_iterate (tree, args, i, arg); ++i)
17828     {
17829       if (type_dependent_expression_p (arg))
17830         return true;
17831     }
17832   return false;
17833 }
17834
17835 /* Returns TRUE if LIST (a TREE_LIST whose TREE_VALUEs are
17836    expressions) contains any value-dependent expressions.  */
17837
17838 bool
17839 any_value_dependent_elements_p (const_tree list)
17840 {
17841   for (; list; list = TREE_CHAIN (list))
17842     if (value_dependent_expression_p (TREE_VALUE (list)))
17843       return true;
17844
17845   return false;
17846 }
17847
17848 /* Returns TRUE if the ARG (a template argument) is dependent.  */
17849
17850 bool
17851 dependent_template_arg_p (tree arg)
17852 {
17853   if (!processing_template_decl)
17854     return false;
17855
17856   if (TREE_CODE (arg) == TEMPLATE_DECL
17857       || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
17858     return dependent_template_p (arg);
17859   else if (ARGUMENT_PACK_P (arg))
17860     {
17861       tree args = ARGUMENT_PACK_ARGS (arg);
17862       int i, len = TREE_VEC_LENGTH (args);
17863       for (i = 0; i < len; ++i)
17864         {
17865           if (dependent_template_arg_p (TREE_VEC_ELT (args, i)))
17866             return true;
17867         }
17868
17869       return false;
17870     }
17871   else if (TYPE_P (arg))
17872     return dependent_type_p (arg);
17873   else
17874     return (type_dependent_expression_p (arg)
17875             || value_dependent_expression_p (arg));
17876 }
17877
17878 /* Returns true if ARGS (a collection of template arguments) contains
17879    any types that require structural equality testing.  */
17880
17881 bool
17882 any_template_arguments_need_structural_equality_p (tree args)
17883 {
17884   int i;
17885   int j;
17886
17887   if (!args)
17888     return false;
17889   if (args == error_mark_node)
17890     return true;
17891
17892   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
17893     {
17894       tree level = TMPL_ARGS_LEVEL (args, i + 1);
17895       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
17896         {
17897           tree arg = TREE_VEC_ELT (level, j);
17898           tree packed_args = NULL_TREE;
17899           int k, len = 1;
17900
17901           if (ARGUMENT_PACK_P (arg))
17902             {
17903               /* Look inside the argument pack.  */
17904               packed_args = ARGUMENT_PACK_ARGS (arg);
17905               len = TREE_VEC_LENGTH (packed_args);
17906             }
17907
17908           for (k = 0; k < len; ++k)
17909             {
17910               if (packed_args)
17911                 arg = TREE_VEC_ELT (packed_args, k);
17912
17913               if (error_operand_p (arg))
17914                 return true;
17915               else if (TREE_CODE (arg) == TEMPLATE_DECL
17916                        || TREE_CODE (arg) == TEMPLATE_TEMPLATE_PARM)
17917                 continue;
17918               else if (TYPE_P (arg) && TYPE_STRUCTURAL_EQUALITY_P (arg))
17919                 return true;
17920               else if (!TYPE_P (arg) && TREE_TYPE (arg)
17921                        && TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (arg)))
17922                 return true;
17923             }
17924         }
17925     }
17926
17927   return false;
17928 }
17929
17930 /* Returns true if ARGS (a collection of template arguments) contains
17931    any dependent arguments.  */
17932
17933 bool
17934 any_dependent_template_arguments_p (const_tree args)
17935 {
17936   int i;
17937   int j;
17938
17939   if (!args)
17940     return false;
17941   if (args == error_mark_node)
17942     return true;
17943
17944   for (i = 0; i < TMPL_ARGS_DEPTH (args); ++i)
17945     {
17946       const_tree level = TMPL_ARGS_LEVEL (args, i + 1);
17947       for (j = 0; j < TREE_VEC_LENGTH (level); ++j)
17948         if (dependent_template_arg_p (TREE_VEC_ELT (level, j)))
17949           return true;
17950     }
17951
17952   return false;
17953 }
17954
17955 /* Returns TRUE if the template TMPL is dependent.  */
17956
17957 bool
17958 dependent_template_p (tree tmpl)
17959 {
17960   if (TREE_CODE (tmpl) == OVERLOAD)
17961     {
17962       while (tmpl)
17963         {
17964           if (dependent_template_p (OVL_FUNCTION (tmpl)))
17965             return true;
17966           tmpl = OVL_CHAIN (tmpl);
17967         }
17968       return false;
17969     }
17970
17971   /* Template template parameters are dependent.  */
17972   if (DECL_TEMPLATE_TEMPLATE_PARM_P (tmpl)
17973       || TREE_CODE (tmpl) == TEMPLATE_TEMPLATE_PARM)
17974     return true;
17975   /* So are names that have not been looked up.  */
17976   if (TREE_CODE (tmpl) == SCOPE_REF
17977       || TREE_CODE (tmpl) == IDENTIFIER_NODE)
17978     return true;
17979   /* So are member templates of dependent classes.  */
17980   if (TYPE_P (CP_DECL_CONTEXT (tmpl)))
17981     return dependent_type_p (DECL_CONTEXT (tmpl));
17982   return false;
17983 }
17984
17985 /* Returns TRUE if the specialization TMPL<ARGS> is dependent.  */
17986
17987 bool
17988 dependent_template_id_p (tree tmpl, tree args)
17989 {
17990   return (dependent_template_p (tmpl)
17991           || any_dependent_template_arguments_p (args));
17992 }
17993
17994 /* Returns TRUE if OMP_FOR with DECLV, INITV, CONDV and INCRV vectors
17995    is dependent.  */
17996
17997 bool
17998 dependent_omp_for_p (tree declv, tree initv, tree condv, tree incrv)
17999 {
18000   int i;
18001
18002   if (!processing_template_decl)
18003     return false;
18004
18005   for (i = 0; i < TREE_VEC_LENGTH (declv); i++)
18006     {
18007       tree decl = TREE_VEC_ELT (declv, i);
18008       tree init = TREE_VEC_ELT (initv, i);
18009       tree cond = TREE_VEC_ELT (condv, i);
18010       tree incr = TREE_VEC_ELT (incrv, i);
18011
18012       if (type_dependent_expression_p (decl))
18013         return true;
18014
18015       if (init && type_dependent_expression_p (init))
18016         return true;
18017
18018       if (type_dependent_expression_p (cond))
18019         return true;
18020
18021       if (COMPARISON_CLASS_P (cond)
18022           && (type_dependent_expression_p (TREE_OPERAND (cond, 0))
18023               || type_dependent_expression_p (TREE_OPERAND (cond, 1))))
18024         return true;
18025
18026       if (TREE_CODE (incr) == MODOP_EXPR)
18027         {
18028           if (type_dependent_expression_p (TREE_OPERAND (incr, 0))
18029               || type_dependent_expression_p (TREE_OPERAND (incr, 2)))
18030             return true;
18031         }
18032       else if (type_dependent_expression_p (incr))
18033         return true;
18034       else if (TREE_CODE (incr) == MODIFY_EXPR)
18035         {
18036           if (type_dependent_expression_p (TREE_OPERAND (incr, 0)))
18037             return true;
18038           else if (BINARY_CLASS_P (TREE_OPERAND (incr, 1)))
18039             {
18040               tree t = TREE_OPERAND (incr, 1);
18041               if (type_dependent_expression_p (TREE_OPERAND (t, 0))
18042                   || type_dependent_expression_p (TREE_OPERAND (t, 1)))
18043                 return true;
18044             }
18045         }
18046     }
18047
18048   return false;
18049 }
18050
18051 /* TYPE is a TYPENAME_TYPE.  Returns the ordinary TYPE to which the
18052    TYPENAME_TYPE corresponds.  Returns the original TYPENAME_TYPE if
18053    no such TYPE can be found.  Note that this function peers inside
18054    uninstantiated templates and therefore should be used only in
18055    extremely limited situations.  ONLY_CURRENT_P restricts this
18056    peering to the currently open classes hierarchy (which is required
18057    when comparing types).  */
18058
18059 tree
18060 resolve_typename_type (tree type, bool only_current_p)
18061 {
18062   tree scope;
18063   tree name;
18064   tree decl;
18065   int quals;
18066   tree pushed_scope;
18067   tree result;
18068
18069   gcc_assert (TREE_CODE (type) == TYPENAME_TYPE);
18070
18071   scope = TYPE_CONTEXT (type);
18072   /* Usually the non-qualified identifier of a TYPENAME_TYPE is
18073      TYPE_IDENTIFIER (type). But when 'type' is a typedef variant of
18074      a TYPENAME_TYPE node, then TYPE_NAME (type) is set to the TYPE_DECL representing
18075      the typedef. In that case TYPE_IDENTIFIER (type) is not the non-qualified
18076      identifier  of the TYPENAME_TYPE anymore.
18077      So by getting the TYPE_IDENTIFIER of the _main declaration_ of the
18078      TYPENAME_TYPE instead, we avoid messing up with a possible
18079      typedef variant case.  */
18080   name = TYPE_IDENTIFIER (TYPE_MAIN_VARIANT (type));
18081
18082   /* If the SCOPE is itself a TYPENAME_TYPE, then we need to resolve
18083      it first before we can figure out what NAME refers to.  */
18084   if (TREE_CODE (scope) == TYPENAME_TYPE)
18085     scope = resolve_typename_type (scope, only_current_p);
18086   /* If we don't know what SCOPE refers to, then we cannot resolve the
18087      TYPENAME_TYPE.  */
18088   if (TREE_CODE (scope) == TYPENAME_TYPE)
18089     return type;
18090   /* If the SCOPE is a template type parameter, we have no way of
18091      resolving the name.  */
18092   if (TREE_CODE (scope) == TEMPLATE_TYPE_PARM)
18093     return type;
18094   /* If the SCOPE is not the current instantiation, there's no reason
18095      to look inside it.  */
18096   if (only_current_p && !currently_open_class (scope))
18097     return type;
18098   /* If this is a typedef, we don't want to look inside (c++/11987).  */
18099   if (typedef_variant_p (type))
18100     return type;
18101   /* If SCOPE isn't the template itself, it will not have a valid
18102      TYPE_FIELDS list.  */
18103   if (same_type_p (scope, CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope)))
18104     /* scope is either the template itself or a compatible instantiation
18105        like X<T>, so look up the name in the original template.  */
18106     scope = CLASSTYPE_PRIMARY_TEMPLATE_TYPE (scope);
18107   else
18108     /* scope is a partial instantiation, so we can't do the lookup or we
18109        will lose the template arguments.  */
18110     return type;
18111   /* Enter the SCOPE so that name lookup will be resolved as if we
18112      were in the class definition.  In particular, SCOPE will no
18113      longer be considered a dependent type.  */
18114   pushed_scope = push_scope (scope);
18115   /* Look up the declaration.  */
18116   decl = lookup_member (scope, name, /*protect=*/0, /*want_type=*/true);
18117
18118   result = NULL_TREE;
18119   
18120   /* For a TYPENAME_TYPE like "typename X::template Y<T>", we want to
18121      find a TEMPLATE_DECL.  Otherwise, we want to find a TYPE_DECL.  */
18122   if (!decl)
18123     /*nop*/;
18124   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == IDENTIFIER_NODE
18125            && TREE_CODE (decl) == TYPE_DECL)
18126     {
18127       result = TREE_TYPE (decl);
18128       if (result == error_mark_node)
18129         result = NULL_TREE;
18130     }
18131   else if (TREE_CODE (TYPENAME_TYPE_FULLNAME (type)) == TEMPLATE_ID_EXPR
18132            && DECL_CLASS_TEMPLATE_P (decl))
18133     {
18134       tree tmpl;
18135       tree args;
18136       /* Obtain the template and the arguments.  */
18137       tmpl = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 0);
18138       args = TREE_OPERAND (TYPENAME_TYPE_FULLNAME (type), 1);
18139       /* Instantiate the template.  */
18140       result = lookup_template_class (tmpl, args, NULL_TREE, NULL_TREE,
18141                                       /*entering_scope=*/0,
18142                                       tf_error | tf_user);
18143       if (result == error_mark_node)
18144         result = NULL_TREE;
18145     }
18146   
18147   /* Leave the SCOPE.  */
18148   if (pushed_scope)
18149     pop_scope (pushed_scope);
18150
18151   /* If we failed to resolve it, return the original typename.  */
18152   if (!result)
18153     return type;
18154   
18155   /* If lookup found a typename type, resolve that too.  */
18156   if (TREE_CODE (result) == TYPENAME_TYPE && !TYPENAME_IS_RESOLVING_P (result))
18157     {
18158       /* Ill-formed programs can cause infinite recursion here, so we
18159          must catch that.  */
18160       TYPENAME_IS_RESOLVING_P (type) = 1;
18161       result = resolve_typename_type (result, only_current_p);
18162       TYPENAME_IS_RESOLVING_P (type) = 0;
18163     }
18164   
18165   /* Qualify the resulting type.  */
18166   quals = cp_type_quals (type);
18167   if (quals)
18168     result = cp_build_qualified_type (result, cp_type_quals (result) | quals);
18169
18170   return result;
18171 }
18172
18173 /* EXPR is an expression which is not type-dependent.  Return a proxy
18174    for EXPR that can be used to compute the types of larger
18175    expressions containing EXPR.  */
18176
18177 tree
18178 build_non_dependent_expr (tree expr)
18179 {
18180   tree inner_expr;
18181
18182   /* Preserve null pointer constants so that the type of things like
18183      "p == 0" where "p" is a pointer can be determined.  */
18184   if (null_ptr_cst_p (expr))
18185     return expr;
18186   /* Preserve OVERLOADs; the functions must be available to resolve
18187      types.  */
18188   inner_expr = expr;
18189   if (TREE_CODE (inner_expr) == STMT_EXPR)
18190     inner_expr = stmt_expr_value_expr (inner_expr);
18191   if (TREE_CODE (inner_expr) == ADDR_EXPR)
18192     inner_expr = TREE_OPERAND (inner_expr, 0);
18193   if (TREE_CODE (inner_expr) == COMPONENT_REF)
18194     inner_expr = TREE_OPERAND (inner_expr, 1);
18195   if (is_overloaded_fn (inner_expr)
18196       || TREE_CODE (inner_expr) == OFFSET_REF)
18197     return expr;
18198   /* There is no need to return a proxy for a variable.  */
18199   if (TREE_CODE (expr) == VAR_DECL)
18200     return expr;
18201   /* Preserve string constants; conversions from string constants to
18202      "char *" are allowed, even though normally a "const char *"
18203      cannot be used to initialize a "char *".  */
18204   if (TREE_CODE (expr) == STRING_CST)
18205     return expr;
18206   /* Preserve arithmetic constants, as an optimization -- there is no
18207      reason to create a new node.  */
18208   if (TREE_CODE (expr) == INTEGER_CST || TREE_CODE (expr) == REAL_CST)
18209     return expr;
18210   /* Preserve THROW_EXPRs -- all throw-expressions have type "void".
18211      There is at least one place where we want to know that a
18212      particular expression is a throw-expression: when checking a ?:
18213      expression, there are special rules if the second or third
18214      argument is a throw-expression.  */
18215   if (TREE_CODE (expr) == THROW_EXPR)
18216     return expr;
18217
18218   if (TREE_CODE (expr) == COND_EXPR)
18219     return build3 (COND_EXPR,
18220                    TREE_TYPE (expr),
18221                    TREE_OPERAND (expr, 0),
18222                    (TREE_OPERAND (expr, 1)
18223                     ? build_non_dependent_expr (TREE_OPERAND (expr, 1))
18224                     : build_non_dependent_expr (TREE_OPERAND (expr, 0))),
18225                    build_non_dependent_expr (TREE_OPERAND (expr, 2)));
18226   if (TREE_CODE (expr) == COMPOUND_EXPR
18227       && !COMPOUND_EXPR_OVERLOADED (expr))
18228     return build2 (COMPOUND_EXPR,
18229                    TREE_TYPE (expr),
18230                    TREE_OPERAND (expr, 0),
18231                    build_non_dependent_expr (TREE_OPERAND (expr, 1)));
18232
18233   /* If the type is unknown, it can't really be non-dependent */
18234   gcc_assert (TREE_TYPE (expr) != unknown_type_node);
18235
18236   /* Otherwise, build a NON_DEPENDENT_EXPR.
18237
18238      REFERENCE_TYPEs are not stripped for expressions in templates
18239      because doing so would play havoc with mangling.  Consider, for
18240      example:
18241
18242        template <typename T> void f<T& g>() { g(); }
18243
18244      In the body of "f", the expression for "g" will have
18245      REFERENCE_TYPE, even though the standard says that it should
18246      not.  The reason is that we must preserve the syntactic form of
18247      the expression so that mangling (say) "f<g>" inside the body of
18248      "f" works out correctly.  Therefore, the REFERENCE_TYPE is
18249      stripped here.  */
18250   return build1 (NON_DEPENDENT_EXPR, non_reference (TREE_TYPE (expr)), expr);
18251 }
18252
18253 /* ARGS is a vector of expressions as arguments to a function call.
18254    Replace the arguments with equivalent non-dependent expressions.
18255    This modifies ARGS in place.  */
18256
18257 void
18258 make_args_non_dependent (VEC(tree,gc) *args)
18259 {
18260   unsigned int ix;
18261   tree arg;
18262
18263   for (ix = 0; VEC_iterate (tree, args, ix, arg); ++ix)
18264     {
18265       tree newarg = build_non_dependent_expr (arg);
18266       if (newarg != arg)
18267         VEC_replace (tree, args, ix, newarg);
18268     }
18269 }
18270
18271 /* Returns a type which represents 'auto'.  We use a TEMPLATE_TYPE_PARM
18272    with a level one deeper than the actual template parms.  */
18273
18274 tree
18275 make_auto (void)
18276 {
18277   tree au = cxx_make_type (TEMPLATE_TYPE_PARM);
18278   TYPE_NAME (au) = build_decl (BUILTINS_LOCATION,
18279                                TYPE_DECL, get_identifier ("auto"), au);
18280   TYPE_STUB_DECL (au) = TYPE_NAME (au);
18281   TEMPLATE_TYPE_PARM_INDEX (au) = build_template_parm_index
18282     (0, processing_template_decl + 1, processing_template_decl + 1,
18283      TYPE_NAME (au), NULL_TREE);
18284   TYPE_CANONICAL (au) = canonical_type_parameter (au);
18285   DECL_ARTIFICIAL (TYPE_NAME (au)) = 1;
18286   SET_DECL_TEMPLATE_PARM_P (TYPE_NAME (au));
18287
18288   return au;
18289 }
18290
18291 /* Given type ARG, return std::initializer_list<ARG>.  */
18292
18293 static tree
18294 listify (tree arg)
18295 {
18296   tree std_init_list = namespace_binding
18297     (get_identifier ("initializer_list"), std_node);
18298   tree argvec;
18299   if (!std_init_list || !DECL_CLASS_TEMPLATE_P (std_init_list))
18300     {    
18301       error ("deducing from brace-enclosed initializer list requires "
18302              "#include <initializer_list>");
18303       return error_mark_node;
18304     }
18305   argvec = make_tree_vec (1);
18306   TREE_VEC_ELT (argvec, 0) = arg;
18307   return lookup_template_class (std_init_list, argvec, NULL_TREE,
18308                                 NULL_TREE, 0, tf_warning_or_error);
18309 }
18310
18311 /* Replace auto in TYPE with std::initializer_list<auto>.  */
18312
18313 static tree
18314 listify_autos (tree type, tree auto_node)
18315 {
18316   tree init_auto = listify (auto_node);
18317   tree argvec = make_tree_vec (1);
18318   TREE_VEC_ELT (argvec, 0) = init_auto;
18319   if (processing_template_decl)
18320     argvec = add_to_template_args (current_template_args (), argvec);
18321   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
18322 }
18323
18324 /* walk_tree helper for do_auto_deduction.  */
18325
18326 static tree
18327 contains_auto_r (tree *tp, int *walk_subtrees ATTRIBUTE_UNUSED,
18328                  void *type)
18329 {
18330   /* Is this a variable with the type we're looking for?  */
18331   if (DECL_P (*tp)
18332       && TREE_TYPE (*tp) == type)
18333     return *tp;
18334   else
18335     return NULL_TREE;
18336 }
18337
18338 /* Replace occurrences of 'auto' in TYPE with the appropriate type deduced
18339    from INIT.  AUTO_NODE is the TEMPLATE_TYPE_PARM used for 'auto' in TYPE.  */
18340
18341 tree
18342 do_auto_deduction (tree type, tree init, tree auto_node)
18343 {
18344   tree parms, tparms, targs;
18345   tree args[1];
18346   tree decl;
18347   int val;
18348
18349   /* The name of the object being declared shall not appear in the
18350      initializer expression.  */
18351   decl = cp_walk_tree_without_duplicates (&init, contains_auto_r, type);
18352   if (decl)
18353     {
18354       error ("variable %q#D with %<auto%> type used in its own "
18355              "initializer", decl);
18356       return error_mark_node;
18357     }
18358
18359   /* [dcl.spec.auto]: Obtain P from T by replacing the occurrences of auto
18360      with either a new invented type template parameter U or, if the
18361      initializer is a braced-init-list (8.5.4), with
18362      std::initializer_list<U>.  */
18363   if (BRACE_ENCLOSED_INITIALIZER_P (init))
18364     type = listify_autos (type, auto_node);
18365
18366   parms = build_tree_list (NULL_TREE, type);
18367   args[0] = init;
18368   tparms = make_tree_vec (1);
18369   targs = make_tree_vec (1);
18370   TREE_VEC_ELT (tparms, 0)
18371     = build_tree_list (NULL_TREE, TYPE_NAME (auto_node));
18372   val = type_unification_real (tparms, targs, parms, args, 1, 0,
18373                                DEDUCE_CALL, LOOKUP_NORMAL);
18374   if (val > 0)
18375     {
18376       error ("unable to deduce %qT from %qE", type, init);
18377       return error_mark_node;
18378     }
18379
18380   /* If the list of declarators contains more than one declarator, the type
18381      of each declared variable is determined as described above. If the
18382      type deduced for the template parameter U is not the same in each
18383      deduction, the program is ill-formed.  */
18384   if (TREE_TYPE (auto_node)
18385       && !same_type_p (TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0)))
18386     {
18387       error ("inconsistent deduction for %qT: %qT and then %qT",
18388              auto_node, TREE_TYPE (auto_node), TREE_VEC_ELT (targs, 0));
18389       return error_mark_node;
18390     }
18391   TREE_TYPE (auto_node) = TREE_VEC_ELT (targs, 0);
18392
18393   if (processing_template_decl)
18394     targs = add_to_template_args (current_template_args (), targs);
18395   return tsubst (type, targs, tf_warning_or_error, NULL_TREE);
18396 }
18397
18398 /* Substitutes LATE_RETURN_TYPE for 'auto' in TYPE and returns the
18399    result.  */
18400
18401 tree
18402 splice_late_return_type (tree type, tree late_return_type)
18403 {
18404   tree argvec;
18405
18406   if (late_return_type == NULL_TREE)
18407     return type;
18408   argvec = make_tree_vec (1);
18409   TREE_VEC_ELT (argvec, 0) = late_return_type;
18410   if (processing_template_decl)
18411     argvec = add_to_template_args (current_template_args (), argvec);
18412   return tsubst (type, argvec, tf_warning_or_error, NULL_TREE);
18413 }
18414
18415 /* Returns true iff TYPE is a TEMPLATE_TYPE_PARM representing 'auto'.  */
18416
18417 bool
18418 is_auto (const_tree type)
18419 {
18420   if (TREE_CODE (type) == TEMPLATE_TYPE_PARM
18421       && TYPE_IDENTIFIER (type) == get_identifier ("auto"))
18422     return true;
18423   else
18424     return false;
18425 }
18426
18427 /* Returns true iff TYPE contains a use of 'auto'.  Since auto can only
18428    appear as a type-specifier for the declaration in question, we don't
18429    have to look through the whole type.  */
18430
18431 tree
18432 type_uses_auto (tree type)
18433 {
18434   enum tree_code code;
18435   if (is_auto (type))
18436     return type;
18437
18438   code = TREE_CODE (type);
18439
18440   if (code == POINTER_TYPE || code == REFERENCE_TYPE
18441       || code == OFFSET_TYPE || code == FUNCTION_TYPE
18442       || code == METHOD_TYPE || code == ARRAY_TYPE)
18443     return type_uses_auto (TREE_TYPE (type));
18444
18445   if (TYPE_PTRMEMFUNC_P (type))
18446     return type_uses_auto (TREE_TYPE (TREE_TYPE
18447                                    (TYPE_PTRMEMFUNC_FN_TYPE (type))));
18448
18449   return NULL_TREE;
18450 }
18451
18452 /* For a given template T, return the vector of typedefs referenced
18453    in T for which access check is needed at T instantiation time.
18454    T is either  a FUNCTION_DECL or a RECORD_TYPE.
18455    Those typedefs were added to T by the function
18456    append_type_to_template_for_access_check.  */
18457
18458 VEC(qualified_typedef_usage_t,gc)*
18459 get_types_needing_access_check (tree t)
18460 {
18461   tree ti;
18462   VEC(qualified_typedef_usage_t,gc) *result = NULL;
18463
18464   if (!t || t == error_mark_node)
18465     return NULL;
18466
18467   if (!(ti = get_template_info (t)))
18468     return NULL;
18469
18470   if (CLASS_TYPE_P (t)
18471       || TREE_CODE (t) == FUNCTION_DECL)
18472     {
18473       if (!TI_TEMPLATE (ti))
18474         return NULL;
18475
18476       result = TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti);
18477     }
18478
18479   return result;
18480 }
18481
18482 /* Append the typedef TYPE_DECL used in template T to a list of typedefs
18483    tied to T. That list of typedefs will be access checked at
18484    T instantiation time.
18485    T is either a FUNCTION_DECL or a RECORD_TYPE.
18486    TYPE_DECL is a TYPE_DECL node representing a typedef.
18487    SCOPE is the scope through which TYPE_DECL is accessed.
18488    LOCATION is the location of the usage point of TYPE_DECL.
18489
18490    This function is a subroutine of
18491    append_type_to_template_for_access_check.  */
18492
18493 static void
18494 append_type_to_template_for_access_check_1 (tree t,
18495                                             tree type_decl,
18496                                             tree scope,
18497                                             location_t location)
18498 {
18499   qualified_typedef_usage_t typedef_usage;
18500   tree ti;
18501
18502   if (!t || t == error_mark_node)
18503     return;
18504
18505   gcc_assert ((TREE_CODE (t) == FUNCTION_DECL
18506                || CLASS_TYPE_P (t))
18507               && type_decl
18508               && TREE_CODE (type_decl) == TYPE_DECL
18509               && scope);
18510
18511   if (!(ti = get_template_info (t)))
18512     return;
18513
18514   gcc_assert (TI_TEMPLATE (ti));
18515
18516   typedef_usage.typedef_decl = type_decl;
18517   typedef_usage.context = scope;
18518   typedef_usage.locus = location;
18519
18520   VEC_safe_push (qualified_typedef_usage_t, gc,
18521                  TI_TYPEDEFS_NEEDING_ACCESS_CHECKING (ti),
18522                  &typedef_usage);
18523 }
18524
18525 /* Append TYPE_DECL to the template TEMPL.
18526    TEMPL is either a class type, a FUNCTION_DECL or a a TEMPLATE_DECL.
18527    At TEMPL instanciation time, TYPE_DECL will be checked to see
18528    if it can be accessed through SCOPE.
18529    LOCATION is the location of the usage point of TYPE_DECL.
18530
18531    e.g. consider the following code snippet:
18532
18533      class C
18534      {
18535        typedef int myint;
18536      };
18537
18538      template<class U> struct S
18539      {
18540        C::myint mi; // <-- usage point of the typedef C::myint
18541      };
18542
18543      S<char> s;
18544
18545    At S<char> instantiation time, we need to check the access of C::myint
18546    In other words, we need to check the access of the myint typedef through
18547    the C scope. For that purpose, this function will add the myint typedef
18548    and the scope C through which its being accessed to a list of typedefs
18549    tied to the template S. That list will be walked at template instantiation
18550    time and access check performed on each typedefs it contains.
18551    Note that this particular code snippet should yield an error because
18552    myint is private to C.  */
18553
18554 void
18555 append_type_to_template_for_access_check (tree templ,
18556                                           tree type_decl,
18557                                           tree scope,
18558                                           location_t location)
18559 {
18560   qualified_typedef_usage_t *iter;
18561   int i;
18562
18563   gcc_assert (type_decl && (TREE_CODE (type_decl) == TYPE_DECL));
18564
18565   /* Make sure we don't append the type to the template twice.  */
18566   for (i = 0;
18567        VEC_iterate (qualified_typedef_usage_t,
18568                     get_types_needing_access_check (templ),
18569                     i, iter);
18570        ++i)
18571     if (iter->typedef_decl == type_decl && scope == iter->context)
18572       return;
18573
18574   append_type_to_template_for_access_check_1 (templ, type_decl,
18575                                               scope, location);
18576 }
18577
18578 /* Set up the hash tables for template instantiations.  */
18579
18580 void
18581 init_template_processing (void)
18582 {
18583   decl_specializations = htab_create_ggc (37,
18584                                           hash_specialization,
18585                                           eq_specializations,
18586                                           ggc_free);
18587   type_specializations = htab_create_ggc (37,
18588                                           hash_specialization,
18589                                           eq_specializations,
18590                                           ggc_free);
18591 }
18592
18593 /* Print stats about the template hash tables for -fstats.  */
18594
18595 void
18596 print_template_statistics (void)
18597 {
18598   fprintf (stderr, "decl_specializations: size %ld, %ld elements, "
18599            "%f collisions\n", (long) htab_size (decl_specializations),
18600            (long) htab_elements (decl_specializations),
18601            htab_collisions (decl_specializations));
18602   fprintf (stderr, "type_specializations: size %ld, %ld elements, "
18603            "%f collisions\n", (long) htab_size (type_specializations),
18604            (long) htab_elements (type_specializations),
18605            htab_collisions (type_specializations));
18606 }
18607
18608 #include "gt-cp-pt.h"